export const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); export const money = n => new Intl.NumberFormat('zh-CN', {style:'currency',currency:'CNY'}).format(Number(n || 0) / 100); export const bytes = n => { n = Number(n || 0); if (!Number.isFinite(n) || n <= 0) return '0 B'; const i = Math.min(4, Math.floor(Math.log(n)/Math.log(1024))); return `${(n / 1024 ** i).toFixed(i ? 2 : 0)} ${['B','KB','MB','GB','TB'][i]}`; }; export const date = n => n ? new Date(Number(n)*1000).toLocaleDateString('zh-CN') : '长期有效'; export const list = value => Array.isArray(value) ? value : Array.isArray(value?.data) ? value.data : []; export const groupedList = value => Array.isArray(value) ? value : Object.values(value || {}).flatMap(list); export const periods = {month_price:'月付',quarter_price:'季付',half_year_price:'半年付',year_price:'年付',two_year_price:'两年付',three_year_price:'三年付',onetime_price:'一次性',reset_price:'流量重置'}; export const orderStates = ['待支付','开通中','已取消','已完成','已折抵']; // Display XB's package amount before wallet/old-plan deductions; never a quote. export function orderAmount(order) { return Math.max(0,Number(order.total_amount||0)+Number(order.balance_amount||0)+Number(order.surplus_amount||0)-Number(order.surplus_credit||0)); } export function trafficSummary(sub,logs=null,now=new Date()) { const positive=value=>Number.isFinite(Number(value))?Math.max(0,Number(value)):0; const total=positive(sub.transfer_enable),used=positive(sub.u)+positive(sub.d); const start=new Date(now);start.setHours(0,0,0,0);const end=new Date(start);end.setDate(end.getDate()+1); // StatUserJob has already applied server_rate to u/d; never charge it twice. const today=logs===null?null:logs.reduce((sum,row)=>Number(row.record_at)*1000>=start.getTime()&&Number(row.record_at)*1000total?value/total*100:0; return {remaining:Math.max(0,total-used),today,history:today===null?used:Math.max(0,used-countedToday),series:[pct(Math.max(0,total-used)),pct(Math.max(0,countedUsed-Math.min(countedUsed,countedToday))),pct(Math.min(countedUsed,countedToday))]}; } export function soldOut(plan) { const stock = plan.capacity_remaining ?? plan.capacity_limit; return stock === 0 || stock === '0' || (typeof stock === 'string' && !/^\d+$/.test(stock)); } export function canPurchase(plan,user,period) { if(!plan||!Object.hasOwn(periods,period)||plan[period]==null)return false; const owner=user.plan_id!=null&&String(user.plan_id)===String(plan.id); if(period==='reset_price')return owner; if(owner)return plan.renew!==false&&plan.renew!==0; return plan.show!==false&&plan.show!==0&&plan.sell!==false&&plan.sell!==0&&!soldOut(plan); } export function safeUrl(value, extra = []) { if(typeof value!=='string'||!value.trim())return ''; try { const url = new URL(value, globalThis.location?.origin || 'http://localhost'); return ['http:','https:',...extra].includes(url.protocol) && !url.username && !url.password ? url.href : ''; } catch { return ''; } } export function createApi({fetcher = fetch, getToken = () => '', onUnauthorized = () => {}} = {}) { return async (path, data, method = data === undefined ? 'GET' : 'POST') => { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 20000); const requestToken=getToken(); try { const response = await fetcher(`/api/v1/${path}`, { method, credentials:'same-origin', signal:controller.signal, headers:{Accept:'application/json',...(data !== undefined ? {'Content-Type':'application/json'} : {}),...(requestToken ? {Authorization:requestToken} : {})}, ...(data !== undefined ? {body:JSON.stringify(data)} : {}), }); let payload; try { payload = await response.json(); } catch { throw new Error('接口未返回有效数据,请检查网站配置'); } if ((response.status === 401 || (response.status === 403 && /未登录|登陆已过期|登录已过期|unauthenticated/i.test(payload.message || ''))) && requestToken===getToken()) onUnauthorized(); if (!response.ok || payload.status === 'fail' || payload.status === false) throw new Error(payload.message || `请求失败(${response.status})`); return Object.hasOwn(payload, 'type') ? payload : Object.hasOwn(payload, 'data') ? payload.data : payload; } catch (error) { if (error.name === 'AbortError') throw new Error('请求超时,请稍后重试'); throw error; } finally { clearTimeout(timer); } }; } export function paymentResult(result) { if (result?.type === -1 && result.data === true) return {kind:'complete'}; if (result?.type === -1) throw new Error(typeof result.data==='string'?result.data:'支付未完成,请重试'); if (result?.type === 0 && typeof result.data === 'string' && result.data.trim()) return {kind:'qr',value:result.data}; if (result?.type === 1 && typeof result.data === 'string') { const value=result.data.trim(); if (/^https?:\/\//i.test(value) && safeUrl(value)) return {kind:'url',value:safeUrl(value)}; if (/