Files
dpl/scripts/theme-fuc/dom.test.mjs
T

235 lines
21 KiB
JavaScript

// 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('<!doctype html><html><head></head><body></body></html>',{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.prepareNativeTemplates('header','index','home','login','register','plans','profile','article','orders','purchase','checkout');
test('touch login waits for a tap while desktop keeps keyboard autofocus',()=>{
const original=window.matchMedia;
try {
window.matchMedia=()=>({matches:true});
const touch=new DOMParser().parseFromString(native.nativeLogin('富蕴'),'text/html');
assert.equal(touch.querySelector('[autofocus]'),null);
window.matchMedia=()=>({matches:false});
const desktop=new DOMParser().parseFromString(native.nativeLogin('富蕴'),'text/html');
assert.equal(desktop.querySelector('[autofocus]').name,'email');
}finally{window.matchMedia=original;}
});
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.match(detail.querySelector('[data-order-settlement]').textContent,/套餐价格:.*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/);
});
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.doesNotMatch(view.body.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('discounted checkout formats fixed and percentage coupons without changing the native amount due',()=>{
const context={user:{vip:{levels:[{name:'小福',discount:8}]}},sub:{},asModal:true,data:{trade_no:'synthetic-discount',status:0,period:'month_price',total_amount:404,balance_amount:500,discount_amount:296,coupon_id:1,plan:{name:'Synthetic'}},discountBreakdown:{original_amount:1200,member_amount:96,coupon_amount:200,member_percent:8,coupon_code:'FUCUI2',coupon_type:1},methods:[{id:17,name:"微信",payment:"Epay"},{id:21,name:"支付宝",payment:"Epay"}],config:{}};
const view=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html');
const text=view.querySelector('[data-order-settlement]').textContent;
assert.match(text,/套餐价格:.*12\.00/);
assert.match(text,/小福:-8%优惠码:-¥2\.00优惠合计:-¥2\.96/);
assert.equal(view.querySelector('[data-order-settlement] > [data-settlement-divider]').textContent,'优惠合计:-¥2.96');
assert.match(text,/钱包抵扣:.*5\.00/);assert.match(text,/还需支付:.*4\.04/);
assert.equal(view.querySelector('#fuc-checkout-modal details'),null);
const pay=view.querySelector('[data-form=checkout] button[type=submit]');
assert.equal(pay.textContent,'在线支付');
assert.equal(pay.disabled,false);
assert.equal(view.querySelectorAll('input[name=method]').length,2);
const checkout=coupon_type=>native.nativeSecondary('checkout',{...context,discountBreakdown:{...context.discountBreakdown,coupon_type}});
assert.match(new DOMParser().parseFromString(checkout(2),'text/html').querySelector('[data-order-settlement]').textContent,/优惠码:-16\.67%/);
assert.match(new DOMParser().parseFromString(checkout(null),'text/html').querySelector('[data-order-settlement]').textContent,/优惠码:-¥2\.00/);
});
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.match(view.querySelector('[data-order-settlement]').textContent,/套餐价格:.*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 without the removed upgrade hint',()=>{
const user={email:'[email protected]',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.equal(card.querySelector('[data-vip-progress]'),null);
const off=document.createElement('div');off.innerHTML=native.nativeDashboard({email:'[email protected]'},{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('<form action="https://pay.example.test/checkout" method="post" onsubmit="bad()"><input name="signature" value="signed"><input name="bad" type="file"><script>bad()</script></form>');
assert.equal(form.method,'post');assert.equal(form.target,'_self');assert.equal(form.querySelector('[name=signature]').value,'signed');
assert.equal(form.querySelector('script,[onsubmit],input[type=file]'),null);
assert.throws(()=>paymentForm('<form action="javascript:bad()"></form>'));
assert.throws(()=>paymentForm('<form action="https://u:[email protected]/"></form>'));
});
test('checkout submits a rebuilt provider form directly without running response HTML',async t=>{
const container=document.createElement('div');
const sent=[];
t.mock.method(window.HTMLFormElement.prototype,'submit',function(){
assert.ok(this.isConnected);
sent.push([this.action,this.method,this.target,this.querySelector('[name=signature]').value]);
});
assert.equal(await showPayment({type:1,data:'<form action="https://pay.example.test/checkout" method="post"><input name="signature" value="signed"><script>bad()</script></form>'},container),false);
assert.deepEqual(sent,[['https://pay.example.test/checkout','post','_self','signed']]);
assert.equal(container.childElementCount,0);
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<img src="https://img.example.test/a.png" onerror="bad()"><script>bad()</script>'},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]'));
assert.equal(view.querySelector('#checkin,.fa-calendar-check'),null);assert.doesNotMatch(view.body.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('the dashboard enables each Nyanpasu download against the configured Resource origin',()=>{
const render=origin=>new DOMParser().parseFromString(native.nativeDashboard({},{},[],'QA',richText,null,origin),'text/html');
const links=view=>[...view.querySelectorAll('[data-nyanpasu-package]')];
assert.ok(links(render('')).every(link=>link.href.startsWith('https://github.com/libnyanpasu/clash-nyanpasu/releases/download/')));
const connected=links(render('http://resource.loc:8612'));
assert.deepEqual(connected.map(link=>link.getAttribute('href')),[
'http://resource.loc:8612/downloads/software/clash-nyanpasu/clash-nyanpasu-windows-x64.exe',
'http://resource.loc:8612/downloads/software/clash-nyanpasu/clash-nyanpasu-macos-arm64.dmg',
'http://resource.loc:8612/downloads/software/clash-nyanpasu/clash-nyanpasu-macos-x64.dmg',
]);
assert.ok(connected.every(link=>!link.hasAttribute('data-action')));
});
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.match(view.querySelector('[data-confirm-plan-specs]').textContent,/套餐流量:100 GB/);
assert.match(view.querySelector('[data-confirm-plan-specs]').textContent,/优惠码:QA/);
assert.equal(view.querySelector('#order_modal [name=coupon_code]').value,'QA');
assert.match(view.querySelector('#shop_time').textContent,/12 个月/);
assert.equal(view.querySelector('#order_modal #autorenew'),null);
assert.doesNotMatch(view.querySelector('#order_modal').textContent,/自动续订|从本地钱包扣费/);
assert.doesNotMatch(view.querySelector('.selling-slide').textContent,/—GB|满—元/);
assert.match(group.querySelector('.pricing-content').textContent,/跟随系统设置/);
});
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();}
});