// Static DOM contract tests, not a substitute for browser or provider acceptance. import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import {JSDOM} from '../../codex/output/fuc-theme/test-tools/node_modules/jsdom/lib/api.js'; const dom=new JSDOM('
',{url:'http://xb.loc/'}); for(const key of ['window','document','DOMParser','localStorage'])globalThis[key]=dom.window[key]; globalThis.fetch=async url=>({ok:true,text:()=>fs.readFile(new URL(url),'utf8'),json:async()=>JSON.parse(await fs.readFile(new URL(url),'utf8'))}); const {paymentForm,showPayment}=await import('../../theme/Fuc/assets/payments.mjs'); const {richText}=await import('../../theme/Fuc/assets/content.mjs'); const {copyText}=await import('../../theme/Fuc/assets/clipboard.mjs'); const native=await import('../../theme/Fuc/assets/native.mjs');await native.nativeReady; test('user navigation keeps active shared CSS and its dark/bridge overrides attached',async()=>{ const append=document.head.append.bind(document.head),insert=document.head.insertBefore.bind(document.head),moved=[]; document.head.append=node=>{if(node.isConnected&&node.tagName==='LINK')moved.push(node);append(node);if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());}; document.head.insertBefore=(node,before)=>{if(node.isConnected&&node.tagName==='LINK')moved.push(node);const result=insert(node,before);if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());return result;}; globalThis.innerWidth=1280; try { await native.prepareNativeMode('user','plans');native.nativeMode('user','plans'); const common=[...document.querySelectorAll('[data-fuc-native]')].filter(n=>!n.href.includes('/page/shop.css')); const dark=document.getElementById('native-dark'),bridge=document.getElementById('native-bridge');moved.length=0; await native.prepareNativeMode('user','wallet');native.nativeMode('user','wallet'); assert.ok(common.length>5);assert.ok(common.every(n=>n.isConnected&&n.media==='all')); assert.equal(document.getElementById('native-dark'),dark);assert.equal(document.getElementById('native-bridge'),bridge); assert.deepEqual(moved,[],'reparenting loaded LINKs can unload CSS and flash an unstyled page'); const before=[...document.querySelectorAll('[data-fuc-native]')]; const changing=native.prepareNativeMode('auth','login');assert.ok(before.every(n=>n.isConnected&&n.media==='all')); await changing;native.nativeMode('auth','login'); assert.ok(before.every(n=>!n.isConnected)); const styles=JSON.parse(await fs.readFile(new URL('../../theme/Fuc/assets/native/styles.json',import.meta.url),'utf8')); assert.deepEqual([...document.querySelectorAll('[data-fuc-native]')].map(n=>n.href.split('/native/')[1].split('?')[0]),styles.login.map(p=>p.split('?')[0])); assert.equal([...document.querySelectorAll('link[rel=stylesheet]')].at(-1),bridge,'overrides keep their position after the native CSS'); }finally{document.head.append=append;document.head.insertBefore=insert;} }); test('wallet-funded checkout and history show package value instead of zero online remainder',()=>{ const order={trade_no:'synthetic-wallet-order',status:3,total_amount:0,balance_amount:10000,surplus_amount:0,surplus_credit:0,period:'month_price',plan:{name:'Synthetic plan'},created_at:1}; const context={user:{},sub:{},data:order,methods:[],config:{}}; const detail=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html'); assert.equal(detail.querySelector('#invoice_content_table tbody td:last-child').textContent.trim(),'100.00'); assert.match(detail.querySelector('[data-order-settlement]').textContent,/钱包抵扣:.*100\.00/); const history=new DOMParser().parseFromString(native.nativeSecondary('orders',{...context,data:[order]}),'text/html'); assert.match(history.querySelector('tbody tr').textContent,/100\.00/); const myplan=new DOMParser().parseFromString(native.nativeSecondary('myplan',{...context,data:[order]}),'text/html'); assert.match(myplan.querySelector('tbody tr').textContent,/100\.00/); }); test('purchase preview keeps list price but leaves final VIP/coupon/balance settlement to native order',()=>{ const html=native.nativeSecondary('purchase',{user:{vip:{enabled:true,name:'小福',discount_percent:8}},sub:{},data:{id:167,name:'Synthetic',month_price:10000},period:'month_price',config:{}}); const view=new DOMParser().parseFromString(html,'text/html'); assert.equal(view.querySelector('#product-buy-total').textContent,'下单后确认'); assert.match(view.body.textContent,/100\.00/);assert.match(view.querySelector('[data-vip-price]').textContent,/9\.2 折/); assert.match(view.querySelector('[data-order-price-notice]').textContent,/取消未支付订单可退回已抵扣余额/); }); test('zero online remainder needs no channel and cancelled wallet deduction is labelled returned',()=>{ const context={user:{},sub:{},data:{trade_no:'synthetic',status:0,total_amount:0,balance_amount:9200,plan:{name:'Synthetic'},period:'month_price'},methods:[],config:{}}; let view=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html'); assert.equal(view.querySelector('select[name=method]'),null); assert.equal(view.querySelector('[data-form=checkout] button[type=submit]').textContent,'确认开通'); assert.equal(view.querySelector('[data-form=checkout] button[type=submit]').disabled,false); view=new DOMParser().parseFromString(native.nativeSecondary('checkout',{...context,data:{...context.data,status:2}}),'text/html'); assert.match(view.querySelector('[data-order-settlement]').textContent,/原钱包抵扣(已退回)/); }); test('package amount uses only consumed old-plan credit and displays channel fees separately',()=>{ const context={user:{},sub:{},data:{trade_no:'synthetic',status:3,total_amount:2500,balance_amount:1000,surplus_amount:3000,surplus_credit:1500,handling_amount:125,plan:{name:'Synthetic'},period:'month_price'},methods:[],config:{}}; const view=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html'); assert.equal(view.querySelector('#invoice_content_table tbody td:last-child').textContent.trim(),'50.00'); const settlement=view.querySelector('[data-order-settlement]').textContent; assert.match(settlement,/旧套餐折抵:.*15\.00/);assert.match(settlement,/渠道手续费:.*1\.25/);assert.match(settlement,/折抵返余:.*15\.00/); }); test('VIP uses the original dashboard card and displays cumulative, level and next discount',()=>{ const user={email:'vip@example.test',vip:{enabled:true,name:'小福',cumulative_cents:10000,discount_percent:8,next_level:{name:'中福'},remaining_cents:10000}}; const host=document.createElement('div');host.innerHTML=native.nativeDashboard(user,{plan_id:1,plan:{name:'套餐'},transfer_enable:100,u:0,d:0,expired_at:2000000000},[],'福云',v=>v); const card=host.querySelector('.card-stats .col');assert.equal(card.querySelector('span.h3').textContent,'小福');assert.match(card.textContent,/累计支付:¥ 100.00/);assert.match(card.querySelector('[data-vip-progress]').textContent,/9.2 折.*距中福还差 ¥100.00/); const off=document.createElement('div');off.innerHTML=native.nativeDashboard({email:'off@example.test'},{plan:{name:'套餐'}},[],'福云',v=>v);assert.equal(off.querySelector('[data-vip-progress]'),null); }); test('payment HTML rebuild excludes scripts, handlers and unsafe actions',()=>{ const form=paymentForm(''); assert.equal(form.method,'post');assert.equal(form.target,'_blank');assert.equal(form.querySelector('[name=signature]').value,'signed'); assert.equal(form.querySelector('script,[onsubmit],input[type=file]'),null); assert.throws(()=>paymentForm('')); assert.throws(()=>paymentForm('')); }); test('payment redirect is explicit and never reports completed before settlement',async()=>{ const container=document.createElement('div'); assert.equal(await showPayment({type:1,data:'https://pay.example.test/'},container),false); assert.equal(container.querySelector('a').rel,'noopener noreferrer'); assert.equal(await showPayment({type:-1,data:true},container),true); }); test('copy succeeds with original HTTP fallback, cleans selection field and prefers modern clipboard',async()=>{ let copied='';document.execCommand=action=>{assert.equal(action,'copy');copied=document.activeElement.value;return true;}; await copyText('synthetic local link',{clipboard:undefined,document}); assert.equal(copied,'synthetic local link');assert.equal(document.querySelector('textarea'),null); await copyText('modern local link',{clipboard:{writeText:async value=>copied=value},document}); assert.equal(copied,'modern local link');delete document.execCommand; }); test('knowledge Markdown renders tables and safe links after native template binding',()=>{ const html=native.nativeSecondary('article',{user:{},sub:{},data:{title:'Guide',body:'## Guide\n\n[Documentation](https://docs.example.test/)\n\n| A | B |\n| - | - |\n| 1 | 2 |\n\n
'},richText,config:{}});
const view=new DOMParser().parseFromString(html,'text/html');
assert.equal(view.querySelector('[data-fuc-richtext] a').href,'https://docs.example.test/');
assert.ok(view.querySelector('[data-fuc-richtext] table'));
assert.equal(view.querySelector('script,[onerror]'),null);
assert.equal(view.querySelector('[data-fuc-richtext] img').src,'https://img.example.test/a.png');
});
test('home shows only actual plans, with real available period and zero price',()=>{
const html=native.nativeHome([{name:'Annual',year_price:12000,transfer_enable:10},{name:'Free',month_price:0,transfer_enable:1}],'QA');
const view=new DOMParser().parseFromString(html,'text/html');
assert.equal(view.querySelectorAll('#pricing .pricing').length,2);
assert.match(view.querySelectorAll('.pricing-price')[0].textContent,/120.00.*年付/s);
assert.match(view.querySelectorAll('.pricing-price')[1].textContent,/0.00.*月付/s);
assert.equal(new DOMParser().parseFromString(native.nativeHome([],'QA'),'text/html').querySelectorAll('#pricing .pricing').length,0);
const loggedIn=new DOMParser().parseFromString(native.nativeHome([],'QA',true),'text/html');assert.equal(loggedIn.querySelector('.nav-btn').getAttribute('href'),'#/dashboard');assert.match(loggedIn.querySelector('.nav-btn').textContent,/用户中心/);
});
test('community link comes from XB config and never inherits the FUC channel',()=>{
const parse=config=>new DOMParser().parseFromString(native.nativeHeader({},'QA','dashboard',config),'text/html');
const link=doc=>[...doc.querySelectorAll('a')].find(n=>n.textContent.includes('加入 Telegram'));
assert.equal(link(parse({})).hasAttribute('href'),false);
const configured=link(parse({telegram_discuss_link:'https://t.me/example_test_channel'}));
assert.equal(configured.href,'https://t.me/example_test_channel');assert.equal(configured.hasAttribute('data-action'),false);
assert.equal(link(parse({telegram_discuss_link:'javascript:alert(1)'})).hasAttribute('href'),false);
});
test('panel settings retain saved palette, mode and collapsed menu after template serialization',()=>{
localStorage.setItem('fuc_themeLight','cyan');localStorage.setItem('fuc_themeMod','dark');localStorage.setItem('fuc_menuToggle','close');
try{const view=new DOMParser().parseFromString(native.nativeHeader({},'QA','plans'),'text/html');
assert.equal(view.querySelector('#themeLight').value,'cyan');assert.deepEqual([...view.querySelector('#themeLight').options].map(o=>[o.value,o.textContent.trim()]),[['cyan','绿色'],['purple','紫色']]);assert.equal(view.querySelector('#themeDark').value,'purple');assert.equal(view.querySelector('.season-palette-options'),null);assert.equal(view.querySelector('#themeMod').value,'dark');assert.equal(view.querySelector('#menuToggle').value,'close');
assert.ok(view.querySelector('.dropdown-user .dropdown-menu [data-target="#panel-option-modal"]'),'mobile users can open panel settings from their account menu');
}finally{localStorage.clear();}
});
test('native header restores the original light/dark menu scheme without conflicting classes',()=>{
try{for(const mode of ['light','dark']){
document.documentElement.dataset.color=mode;const view=new DOMParser().parseFromString(native.nativeHeader({},'QA','plans'),'text/html'),menu=view.querySelector('.main-menu');
assert.equal(menu.classList.contains('menu-light'),mode==='light');assert.equal(menu.classList.contains('menu-dark'),mode==='dark');
}}finally{delete document.documentElement.dataset.color;}
});
test('auth removes unsupported 2FA and optional verification without weakening required fields',()=>{
const login=new DOMParser().parseFromString(native.nativeAuth('login','QA',{}),'text/html');
assert.equal(login.querySelector('[id="2fa-form"]'),null);assert.equal(login.querySelector('[name=password]').required,true);
for(const required of [0,1]){const view=new DOMParser().parseFromString(native.nativeAuth('register','QA',{is_email_verify:required}),'text/html');assert.equal(!!view.querySelector('[name=email_code]'),!!required);}
});
test('dashboard retains source empty-subscription state and profile does not invent FUC user level',()=>{
const view=new DOMParser().parseFromString(native.nativeDashboard({},{},[],'QA',richText,[]),'text/html');
assert.equal(view.querySelector('#donut-chart').hidden,true);assert.match(view.body.textContent,/无可用流量/);
assert.ok(view.querySelector('[data-action=subscription-unavailable]'));
const checkin=view.querySelector('button[title="本站未开放签到"]');assert.equal(checkin.disabled,true);assert.doesNotMatch(checkin.textContent,/已签到/);
const profile=new DOMParser().parseFromString(native.nativeSecondary('profile',{sub:{plan:{name:'Long plan is not an account level'}},richText}),'text/html');
assert.equal(profile.querySelector('.card-profile-stats .heading').textContent,'—');
});
test('shop mirrors source plan-group tabs with period cards and original purchase modals',()=>{
const plans=[{id:1,name:'轻量套餐',month_price:1200,year_price:12000,reset_price:500,transfer_enable:100},{id:2,name:'标准套餐',month_price:0,transfer_enable:10}];
const html=native.nativeSecondary('plans',{user:{plan_id:2},sub:{},data:plans,period:'plan-1',richText,config:{}});
const view=new DOMParser().parseFromString(html,'text/html');
assert.deepEqual([...view.querySelectorAll('.shop_tab span')].map(n=>n.textContent),['轻量套餐','标准套餐']);
const group=view.getElementById('top-home-plan-1');assert.equal(group.classList.contains('show'),true);
assert.deepEqual([...group.querySelectorAll('[data-action=buy]')].map(n=>[n.dataset.id,n.dataset.period]),[['1','month_price'],['1','year_price']]);
assert.equal(view.querySelector('#coupon_modal [name=coupon_code]').required,false);
assert.equal(view.querySelector('#order_modal form').dataset.form,'purchase');
assert.equal(view.querySelector('#pay-confirm').closest('[data-action]'),null,'submit must not inherit an unrelated banner action');
native.fillPurchaseModal(view,plans[0],'year_price','QA');
assert.equal(view.querySelector('#order_modal [name=coupon_code]').value,'QA');
assert.match(view.querySelector('#shop_time').textContent,/365/);
assert.equal(view.querySelector('#autorenew').disabled,true);
assert.doesNotMatch(view.querySelector('.selling-slide').textContent,/—GB|满—元/);
assert.match(group.querySelector('.pricing-content').textContent,/跟随系统设置/);
});
test('current-plan renewal uses the authorized XB plan and preserves all configured periods',()=>{
const renewPlan={id:7,name:'Existing',sell:false,show:false,renew:true,capacity_limit:'Sold out',month_price:1200,year_price:12000,reset_price:100};
const view=new DOMParser().parseFromString(native.nativeSecondary('myplan',{user:{plan_id:7},sub:{plan:renewPlan},data:[],renewPlan,richText}),'text/html');
assert.deepEqual([...view.querySelectorAll('.card-header .dropdown-item')].map(n=>n.getAttribute('href')),['#/purchase/7?period=month_price','#/purchase/7?period=year_price','#/purchase/7?period=reset_price']);
assert.equal(view.querySelector('.card-header h4').textContent,'Existing');
});
test('captcha contracts cover Turnstile, v2, v3, expiration and disposal with SDK doubles',async()=>{
const {createCaptcha}=await import('../../theme/Fuc/assets/captcha.mjs');
const original=document.head.append.bind(document.head);document.head.append=node=>{original(node);queueMicrotask(()=>node.onload?.());};
try{
for(const [type,key,field] of [['turnstile','turnstile_site_key','turnstile_token'],['recaptcha','recaptcha_site_key','recaptcha_data'],['recaptcha-v3','recaptcha_v3_site_key','recaptcha_v3_token']]){
let callbacks;const sdk={ready:fn=>fn(),render:(el,options)=>{callbacks=options;return 0;},execute:async()=> 'synthetic-token',reset:()=>{},remove:()=>{}};
window.turnstile=sdk;window.grecaptcha=sdk;
const container=document.createElement('div');document.body.append(container);
const captcha=createCaptcha({is_captcha:1,captcha_type:type,[key]:'test-key'},container);
if(type!=='recaptcha-v3'){await assert.rejects(captcha.payload(),/请先完成/);callbacks.callback('synthetic-token');}
assert.deepEqual(await captcha.payload(),{[field]:'synthetic-token'});
if(callbacks){callbacks['expired-callback']();await assert.rejects(captcha.payload(),/请先完成/);}
captcha.dispose();await assert.rejects(captcha.payload(),/页面已切换/);container.remove();
}
}finally{document.head.append=original;}
});
test('Stripe hosted card tokenization passes only SDK token and destroys card',async()=>{
const {mountCard}=await import('../../theme/Fuc/assets/payments.mjs');let destroyed=false;
const original=document.head.append.bind(document.head);document.head.append=node=>{original(node);queueMicrotask(()=>node.onload?.());};
window.Stripe=()=>({elements:()=>({create:()=>({mount:()=>{},destroy:()=>destroyed=true})}),createToken:async()=>({token:{id:'tok_test_only'}})});
const container=document.createElement('div');document.body.append(container);
try{const card=await mountCard(async()=> 'pk_test_fixture',1,container);assert.equal(await card.token(),'tok_test_only');card.dispose();assert.equal(destroyed,true);}finally{document.head.append=original;container.remove();}
});