Split the game page into partials under src/, assembled into one index.html at build

site/index.html (900 KB of HTML, CSS and JS in one file) becomes src/: a shell
(src/index.html), styles/ and game/, concatenated in path order by
scripts/lib/page.js. The assembled page is byte-identical to the old file, so
load time and in-game performance are unchanged.

- scripts/build.js replaces build.sh (same env vars, same output)
- npm run dev: a zero-dependency dev server that assembles on every request
- tests assemble the page in memory; npm test runs every tests/*.test.js
- perf-bench takes --base-ref to build a git ref's page
- scripts/legacy/split-index-html.js is the splitter, kept for older branches
This commit is contained in:
Frederic Jung 2026-10-27 10:05:56 +01:00
parent 295e68cc46
commit 67a40942b4
No known key found for this signature in database
113 changed files with 5584 additions and 5195 deletions

View file

@ -0,0 +1,139 @@
const portMo=v=>v?tr('{price}/mo',{price:fmt$(v)}):tr('free');
function ixSection(c){const ids=ixIdsIn(c);if(ids.length<2)return ixBlock(c,false);
let h=`<section><h3>${tr('Internet Exchanges')}</h3><p class="lead">${tr('{n} exchanges compete in {city}. Members overlap, but not completely, and the challengers undercut the incumbent. Small networks often sit on just one of them.',{n:ids.length,city:esc(CITY[c].name)})}</p></section>`;
for(const x of ids)h+=ixBlock(x,true);return h;}
function ixBlock(c,multi){const city=ixCity(c),C=CITY[city],ix=ixName(c),X=XIXM[c];let h='';
h+=`<section><h3>${multi?esc(ix)+(X?' <span class="tag st">'+tr('challenger')+'</span>':' <span class="tag st">'+tr('incumbent')+'</span>'):tr('Internet Exchange')}</h3>`;
if(!ix&&C.cn){h+=`<p class="lead">${tr('Running an exchange in mainland China takes a different license entirely. Peer with Chinese networks over PNIs, or meet them in Hong Kong.')}</p>`;}
else if(!ix){h+=`<p class="lead">${tr("There's no IX in {city} yet. Found one: networks join over time, pay you for ports, and peer with you for free.",{city:C.name})}</p>${S.pops[city]?btn(tr('Found your own IX <small>{cost} + {mo}/mo</small>',{cost:fmt$(MYIX_COST),mo:fmt$(MYIX_MO)}),'foundIx',{city:c},'pink',S.cash<MYIX_COST):'<p class="note">'+tr('Build a POP here first.')+'</p>'}`;}
else if(S.ixp[c]===undefined){h+=`<p class="lead">${tr('{ix} is a shared switch. One port lets you peer with every member for free. Members: {list}.',{ix:esc(ix),list:(()=>{const m=ixMembers(c),big=m.filter(id=>!NET[id].tail),t=m.length-big.length;return (big.map(id=>esc(NET[id].name)).join(', ')||tr('nobody yet'))+(t?trn(', plus {n} small network',', plus {n} small networks',t):'');})()})}</p>${S.pops[city]?'':REMOTE_WARN}${X?`<p class="note">${esc(X.blurb)} ${X.freeTo!==undefined?tr('Ports up to {port} are free.',{port:PORT[X.freeTo].n}):tr('Ports at {p}% of the usual price.',{p:Math.round(ixMul(c)*100)})}</p>`:''}${CITY[city].ixCheap?`<p class="note">${tr('<b>Run by a nonprofit.</b> Public prices at a fraction of what other exchanges charge, and almost everyone is here.')}</p>`:''}${isDk(c)?`<p class="note">${tr('<b>Run by DE-KICKS Group.</b> No public price list. Ask sales for a personalised quote and bring your haggling face.')}</p>`:''}<div class="btns">${PORT.map((P2,i)=>btn(isDk(c)?tr('{port} port <small>Price on request ☎</small>',{port:P2.n}):tr('{port} port <small>{price}</small>',{port:P2.n,price:portMo(ixPortMo(c,i))}),'buyIx',{city:c,tier:i},'',(!isDk(c)&&S.cash<ixPortMo(c,i))||(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1))).join('')}</div>`;}
else{const mine=!!S.myIx[c],u=R.useIx[c]||0,cap=ixCap(c),set=ixSessions(c),xdown=S.ev.ixdown&&S.ev.ixdown[c]>S.day;
h+=`<div class="kv"><span>${mine?tr('Your own fabric · {name}',{name:myFab(c).n}):lagName(S.ixp[c],(S.ixn||{})[c])}${xdown?' · <b style="color:var(--bad)">FABRIC DOWN</b>':''}</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('ix',c,S.ixPref&&S.ixPref[c])}${S.pops[city]?siteCtl('ix',c,city,(S.ixSite||{})[c]):''}`;
if(isDk(c)&&S.dk){const ad=S.dk.add[c]||[],rt=S.dk.ret[c];h+=`<p class="note">${rt&&rt>S.day?tr('DE-KICKS personalised pricing: {p}% of what a normal IX would charge (promo, {n} days left).',{p:Math.round(dkMult(c)*100),n:rt-S.day}):tr('DE-KICKS personalised pricing: {p}% of what a normal IX would charge.',{p:Math.round(dkMult(c)*100)})}</p>`;
for(const x of ad)h+=`<div class="row"><div class="grow"><div class="nm">${esc(x.n)} <span class="tag paid">${tr('auto-enrolled')}</span></div><div class="meta">${esc(x.blurb)} · ${tr('{price}/mo',{price:fmt$(x.mo)})}</div></div>${btn(UI.confirm==='dk'+c+x.n?tr('Lose exclusive benefits?'):tr('Opt out'),'dkOptOut',{city:c,n:x.n},'ghost sm')}</div>`;}
if(isRemote(c))h+=`<p class="note">${trn('Remote port via a reseller: 1.5× price, 80% usable, and {n} member here refuse remote peers.','Remote port via a reseller: 1.5× price, 80% usable, and {n} members here refuse remote peers.',ixMembers(c).filter(noRemote).length)}</p>`;
if(mine){const f=S.myIx[c].fab|0,N=MYIX_FAB[f+1];h+=`<div class="kv"><span>${tr('Members paying you')}</span><b>${tr('{n} of up to {max} · {price}/mo',{n:S.myIx[c].members.length,max:myFab(c).max,price:fmt$(S.myIx[c].members.length*MYIX_FEE)})}</b></div>${N?`<div class="btns">${btn(N.lvl>lvl()?tr('{name} fabric <small>level {lv}</small>',{name:N.n,lv:N.lvl}):tr('Upgrade fabric to {name} <small>{cost} + {mo}/mo</small>',{name:N.n,cost:fmt$(N.cost),mo:fmt$(N.mo)}),'myIxUp',{city:c},'pink sm',N.lvl>lvl()||S.cash<N.cost)}</div><p class="note">${tr('A bigger fabric carries more traffic and has room for more members. Your router here still has to keep up.')}</p>`:'<p class="note">'+tr('Biggest fabric money can buy.')+'</p>'}`;}
else h+=`<div class="btns">${PORT.map((P2,i)=>i>S.ixp[c]&&portShown(i)?btn(tr('Upgrade {port} <small>{price}</small>',{port:P2.n,price:portMo(ixPortMo(c,i)*((S.ixn||{})[c]||1))}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)):'').join('')}${S.pops[city]&&((S.ixn||{})[c]||1)<LAG_MAX?btn(tr('+ LAG member <small>{price}</small>',{price:portMo(ixPortMo(c,S.ixp[c]))}),'lagIx',{city:c,d:1},'sm',S.cash<ixPortMo(c,S.ixp[c])):''}${((S.ixn||{})[c]||1)>1?btn(tr('− member'),'lagIx',{city:c,d:-1},'ghost sm'):''}${btn(S.rs[c]?tr('Leave route server'):tr('Join route server'),'rs',{city:c},S.rs[c]?'ghost sm':'pink sm')}${btn(UI.confirm==='ix'+c?tr('Really leave?'):tr('Leave IX'),'cancelIx',{city:c},'ghost sm')}</div>`;
h+=`<div style="margin-top:8px">`;
{const elig=mine?[]:ixMembers(c).filter(id=>!set.has(id)&&peerOk(id,'ix',c).ok);if(elig.length>1)h+=`<div class="btns">${btn(tr('Request all {n} willing peers',{n:elig.length}),'peerAll',{city:c},'pink sm')}</div>`;}
for(const id of ixMembers(c).sort((a,b)=>NSH[b]-NSH[a])){const n=NET[id],on=set.has(id),viaRs=on&&!S.peers[id+'@'+c]&&!mine,chk=peerOk(id,'ix',c);
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)}</div><div class="meta"><span class="tag ${n.type}">${TYPE_L[n.type]}</span> <span class="tag ${n.pol}">${n.pol}</span> · ${(NSH[id]*100).toFixed(NSH[id]<0.01?1:0)}%${n.tail?' <span class="tag st">'+tr('tiny')+'</span>':''}</div>${!on&&!chk.ok?`<div class="why">${esc(chk.why)}</div>`:''}</div>
${on?(viaRs||mine?`<span class="tag st on">${mine?tr('Member'):tr('via RS')}</span>`:btn(tr('Peered ✓'),'unpeer',{city:c,net:id},'green sm',false,tr('Click to tear down'))):btn(tr('Request'),'peer',{city:c,net:id},'sm',!chk.ok)}</div>`;}
h+=`</div>`;}
h+=`</section>`;return h;
}
function vxcPanel(l){
const load=R.load[l.id]||0,cap=VXC[l.vt].g,u=load/cap,down=linkDown(l),f=FAB[l.prov];
let h=`<div class="ph"><div><div class="eyebrow">${tr('Virtual circuit · {name} · {km} km',{name:esc(f.name),km:l.km.toLocaleString()})}</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('Close')}">×</button></div><div class="scroll">`;
if(down)h+=`<section><h3 style="color:var(--bad)">${tr('Fabric outage')}</h3><p class="lead">${tr('{name} is down. Nothing you can do but wait, or have another path.',{name:esc(f.name)})}</p></section>`;
h+=`<section><h3>${tr('Capacity')}</h3><div class="kv"><span>${tr('{name} circuit',{name:VXC[l.vt].n})}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>${tr('Monthly')}</span><b>${tr('{price}/mo',{price:fmt$(l.mo)})}</b></div>${!S.pops[l.b]?`<p class="note">${tr('Remote peering leg into {ix}.',{ix:esc(CITY[l.b].ix)})}</p>`:''}
<div class="btns">${VXC.map((V,t)=>t>l.vt?btn(`${V.n} <small>${tr('{price}/mo',{price:fmt$(vxcMo(l.km,l.sub,t))})}</small>`,'upVxc',{id:l.id,t},'sm'):'').join('')}</div></section>
${trafficSection(l)}${metricSection(l)}
<section>${btn(UI.confirm===l.id?tr('Really cancel?'):tr('Cancel circuit'),'cancelVxc',{id:l.id},'ghost sm')}</section></div>`;
return h;
}
function prefCtl(kind,id,cur){cur=cur||'normal';return `<div class="btns"><span class="meta" style="align-self:center">${tr('Egress:')}</span>${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}</div>`;}
function trafficSection(l){
const rec=R.ef[edgeKey(l)],n=pairLinks(l.a,l.b).length;
let h=`<section><h3>${tr("What's on this link")}</h3>`;
if(!rec){return h+`<p class="empty">${tr('No traffic right now.')}</p></section>`;}
const tot=Object.values(rec.net).reduce((a,b)=>a+b,0)||1;
const nets=Object.entries(rec.net).sort((a,b)=>b[1]-a[1]);
const col=id=>id==='junk'?'#FF4D5E':id==='l2vpn'?'#7B61FF':NET[id].col,nm=id=>id==='junk'?tr('DDoS junk'):id==='l2vpn'?tr('L2VPN customers'):NET[id].name;
h+=`${n>1?`<p class="note" style="margin-top:0">${tr('Totals for all {n} links between these cities.',{n})}</p>`:''}<div class="stack">${nets.map(([id,v])=>`<i style="width:${v/tot*100}%;background:${col(id)}" title="${esc(nm(id))}"></i>`).join('')}</div>`;
h+=`<h4 class="sub4">${tr('Content from')}</h4>`+nets.slice(0,6).map(([id,v])=>`<div class="kv"><span><span class="dot" style="background:${col(id)}"></span>${esc(nm(id))}</span><b>${fmtG(v)} · ${pct(v/tot)}</b></div>`).join('');
const egs=Object.entries(rec.eg).sort((a,b)=>b[1]-a[1]);
h+=`<h4 class="sub4">${tr('Enters your network at')}</h4>`+egs.slice(0,6).map(([k,v])=>{const d=R.egDesc[k];return `<div class="row"><div class="grow"><div class="nm">${esc(d.lab)}</div><div class="meta">${CITY[d.city].name} · ${fmtG(v)} · ${pct(v/tot)}</div></div>${btn(tr('Open'),'goEgress',{city:d.city,k:d.k},'ghost sm')}</div>`;}).join('');
const dst=Object.entries(rec.dst).sort((a,b)=>b[1]-a[1]);
h+=`<h4 class="sub4">${tr('Going to customers in')}</h4>`+dst.slice(0,6).map(([c,v])=>`<div class="kv"><span>${CITY[c].name}</span><b>${fmtG(v)} · ${pct(v/tot)}</b></div>`).join('');
const u=tot/pairLinks(l.a,l.b).filter(x=>!linkDown(x)).reduce((a,x)=>a+capOf(x),0);
if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`<p class="why">${tr("Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.",{egress:esc(d.lab),city:CITY[d.city].name})}</p>`;}
return h+`</section>`;
}
function metricSection(l){const cur=l.metric||'normal';
return `<section><h3>${tr('Routing metric')}</h3><p class="lead">${tr('Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.')}</p><div class="btns">${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}</div></section>`;}
function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2;
let h=`<section><h3>${tr('Behind the Great Firewall')}</h3><p class="lead">${tr('Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}</p>`;
if(st==='none')h+=`<p class="lead">${tr('Foreign networks need a local joint venture and an operating license to build infrastructure here.')}</p>${btn(tr('Apply for a license <small>{price} + {mo}/mo · ~45 days</small>',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO)}),'applyCn',{},'pink',S.cash<CN_LIC)}`;
else if(st==='pending')h+=`<p class="note">${tr('License paperwork in progress: {n} days left.',{n:Math.max(0,S.cnLic.ready-S.day)})}</p>`;
else h+=`<p class="note">${tr('Your joint venture holds an operating license.')}</p>`;
if(R.gfwCross>0.5)h+=`<div class="kv"><span>${tr('Your traffic crossing the border')}</span><b>${fmtG(R.gfwCross)}</b></div><div class="kv"><span>${tr('Lost on the way')}</span><b style="color:var(--bad)">${fmtG(R.gfwLost)}</b></div>`;
return h+`</section>`;}
function subUpgradePanel(l){return `<h4 class="sub4">${tr('Submarine transmission')}</h4><p class="note">${tr('Better terminals and optical tuning extend long-haul reach. Repeaters are already included; these upgrades do not change latency.')}</p>`+Object.entries(SUB_UPGRADES).map(([k,U])=>{
const at=l['sub'+k],done=subUpgradeReady(l,k),cost=subUpgradeCost(l,k),preview={...l,['sub'+k]:S.day};
const status=done?tr('Installed'):at!==undefined?tr('Ready in {n} days',{n:Math.max(0,at-S.day)}):tr('{price} · {n} days',{price:fmt$(cost),n:U.days});
return `<div class="row"><div class="grow"><div class="nm">${tr(U.n)}</div><div class="meta">${status}</div><div class="meta">${tr('Up to {g} per channel',{g:fmtG(submarineRate(preview))})}</div></div>${at===undefined?btn(tr('Install'),'subUpgrade',{id:l.id,k},'sm',lvl()<4||S.cash<cost):''}</div>`;}).join('');}
function dfPanel(l){
const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys];
let h=`<div class="ph"><div><div class="eyebrow">${tr('Dark fiber · {kind} · {km} km',{kind:l.own?tr('your own build'):tr('leased IRU'),km:l.km.toLocaleString()})}</div><h2>${A} ⇄ ${B}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('Close')}">×</button></div><div class="scroll">`;
if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1);
h+=`<section><h3>${l.own?tr('Under construction'):tr('Being spliced')}</h3><div class="kv"><span>${l.own?tr('Permits, trenching, splicing'):tr('IRU handover')}</span><b>${tr('{n} days left',{n:l.ready-S.day})}</b></div><div class="bar me"><i style="width:${done*100}%"></i></div>${l.own?`<div class="btns">${btn(tr('Hire extra crews <small>{price} · −30 days</small>',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',l.ready<=S.day+1||S.cash<crewCost(l))}${btn(tr('Finish in 1 day <small>{price}</small>',{price:fmt$(crewSteps(l)*crewCost(l))}),'crews',{id:l.id,all:1},'sm',!crewSteps(l)||S.cash<crewSteps(l)*crewCost(l))}</div>`:''}<p class="note">${tr("You can pre-install optics now so it lights up the day it's ready.")}</p></section>`;}
else if(inc&&linkDown(l))h+=`<section><h3 style="color:var(--bad)">${tr('Dark!')}</h3><p class="lead">${esc(inc.msg)}</p>${inc.cost?btn(`${esc(inc.fix||tr('Rush repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>${tr('Capacity')}</h3><div class="kv"><span>${tr('{n} of {max} channels lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('{n} sold as alien waves',{n:soldSlots(l)})}`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
${l.own&&l.sub?`<div class="kv"><span>${tr('Cable design')}</span><b>${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}</b></div>`:''}
<div class="kv"><span>${tr('Latency')}</span><b>${tr('{ms} ms one-way',{ms:linkLat(l).toFixed(1)})}</b></div><div class="kv"><span>${l.own?tr('Right-of-way upkeep'):tr('IRU lease')}</span><b>${tr('{price}/mo',{price:fmt$(l.mo)})}</b></div><div class="kv"><span>${tr('{n} amp huts',{n:amps})}</span><b>${tr('{price}/mo',{price:fmt$(amps*AMP_MO)})}</b></div>${!bld&&!(l.ch||[]).length?`<p class="why">${tr('This fiber is dark. Add optics below to carry traffic.')}</p>`:''}</section>`;
if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l);
h+=`<section><h3>${tr('Selling spare capacity')}</h3><p class="lead">${tr('Other carriers rent what you do not use: alien waves on free channels of your line system, or on your own build a spare fiber pair in the trench.')}</p>
<div class="kv"><span>${tr('Free channels')}</span><b>${fc} / ${chMax(l)}</b></div>${sold.map(b=>`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(b.what||BIZ_T[b.type].l)} · ${tr('{price}/mo',{price:fmt$(b.rate)})}</div></div></div>`).join('')}
${off?`<div class="row"><div class="grow"><div class="nm">${esc(off.name)}</div><div class="meta">${esc(off.what)} · ${tr('{price}/mo',{price:fmt$(off.rate)})} · ${tr('{n}d left',{n:off.exp-S.day})}${off.broker?' · '+tr('via a capacity broker'):''}</div></div>${btn(tr('Accept'),'accept',{id:off.id},'pink sm')}</div>`:fc>=1||pairFree(l)?`<div class="btns">${btn(tr('List it with a capacity broker <small>they keep 10%</small>'),'advertise',{id:l.id},'sm')}</div>`:`<p class="note">${tr('Nothing spare to sell on this fiber right now.')}</p>`}</section>`;}
h+=`<section><h3>${tr('Optics')}</h3><p class="lead">${tr('Each channel is a pair of optics, one per end. ZR+ optics plug straight into your routers. Transponders sit on a shelf.')}</p>`;
if(l.own&&l.sub)h+=subUpgradePanel(l);
for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k);
const md=optMode(k,l),cc=chCost(l,k),sp=spareN(k);
h+=`<div class="row"><div class="grow"><div class="nm">${O.n} <span class="meta">${optModes(k,l).map(([g,r])=>tr('{g} to {km} km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}</span></div><div class="meta">${esc(O.blurb)}${n?` · <b>${tr('{n} lit',{n})}</b>`:''}${sp?` · ${trn('{n} spare on the shelf','{n} spares on the shelf',sp)}`:''}</div>${md&&!md.full?`<div class="meta">⚠️ ${tr('Runs at <b>{g}</b> per channel on this route (long-haul mode).',{g:fmtG(md.g)})} ${!l.sub&&regenNeed(k,l)>(l.regen|0)?trn('{n} regen site would bring it back to {g}.','{n} regen sites would bring it back to {g}.',regenNeed(k,l),{g:fmtG(O.g)}):''}</div>`:''}${why?`<div class="why">${esc(why)}</div>`:''}</div>${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+ <small>${cc?tr('spare + {price}',{price:fmt$(cc)}):tr('spare')}</small>`:`+ <small>${fmt$(cc)}</small>`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash<cc)}</div>`;}
{const st=Object.keys(OPT).filter(k=>spareN(k)>0);h+=`<p class="note">${tr('Unplugged optics go on the spares shelf and are used first next time.')}</p>`;
{const used=[...new Set(l.ch||[])].filter(k=>OPT[k]&&OPT[k].lvl<=lvl());if(used.length)h+=`<div class="btns">${used.map(k=>btn(tr('Stock a spare {optic} <small>{price}</small>',{optic:OPT[k].n,price:fmt$(optCost(k))}),'buySpare',{o:k},'ghost sm',S.cash<optCost(k)||spareN(k)>=64)).join('')}</div><p class="meta">${tr('Spares bought now are already paid for when the next shortage hits.')}</p>`;}if(st.length)h+=`<h4 class="sub4">${tr('Spares shelf')}</h4>`+st.map(k=>`<div class="row"><div class="grow"><div class="nm">${spareN(k)} × ${OPT[k].n}</div></div>${btn(tr('Sell one <small>{price}</small>',{price:fmt$(spareValue(k))}),'sellSpare',{o:k},'ghost sm')}</div>`).join('');}
const rg=l.regen|0,rgAdd=REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH);
h+=`</section><section><h3>${tr('Line system')}</h3><div class="kv"><span>${esc(sysD.n)}</span><b>${tr('{n} amplifiers',{n:amps})}</b></div>
<div class="kv"><span>${tr('Regen sites')}</span><b>${rg?tr('{n} · optical spans of {km} km',{n:rg,km:spanKm(l).toLocaleString()}):tr('none')}</b></div><p class="note">${tr('A regen site turns the light back into bits halfway and sends it on fresh, so optics only have to reach the next site. Each needs a regen card for every lit channel. {price}/mo per site for the hut.',{price:fmt$(REGEN_MO)})}</p>${l.sub&&l.own?`<p class="note">${tr('No regen sites in the middle of the ocean: long cables run their optics in long-haul mode.')}</p>`:`<div class="btns">${rg<REGEN_MAX?btn(tr('+ Regen site <small>{price}</small>',{price:fmt$(rgAdd)}),'regen',{id:l.id,d:1},'sm',S.cash<rgAdd):''}${rg?btn(tr('− Regen site'),'regen',{id:l.id,d:-1},'ghost sm'):''}</div>`}<p class="note">${esc(sysD.blurb)}</p><div class="btns">${(()=>{const t=sysNext(l);if(!t)return '';const T=DF_SYS[t],c=sysUpCost(l);return T.lvl>lvl()?btn(tr('{sys} <small>level {n}</small>',{sys:T.n,n:T.lvl}),'upSys',{id:l.id},'sm',true):btn(tr('Upgrade to {sys} <small>{price}</small>',{sys:T.n,price:fmt$(c)}),'upSys',{id:l.id},'sm',S.cash<c);})()}${pairBtn(l)}${btn(l.spares?tr('Spares kit on ✓'):tr('Keep a spares kit <small>{price}/mo</small>',{price:fmt$(Math.round(150+(l.ch||[]).length*80))}),'spares',{id:l.id},l.spares?'green sm':'sm')}</div><p class="note">${tr('Spare optics and amplifier cards on the shelf turn multi-day hardware failures into one-day swaps.')}</p></section>`;
{const sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc');h+=`<section><h3>${tr('Redundancy')}</h3><p class="lead">${sib.length?tr('Other links between these cities:'):tr('This is the only link between these cities. Add a parallel one, or a path through another city.')}</p>${sib.map(x=>`<div class="row"><div class="grow"><div class="nm">${esc(capName(x))} ${linkDown(x)?'<span class="tag restrictive">'+tr('CUT')+'</span>':''}</div><div class="meta">${(x.trench||x.id)===(l.trench||l.id)?tr('same trench'):tr('diverse route')}</div></div>${btn(tr('Open'),'selLink',{id:x.id},'ghost sm')}</div>`).join('')}<div class="btns">${btn(tr('Add parallel link'),'addParallel',{id:l.id},'pink sm')}</div></section>`;}
h+=`${trafficSection(l)}${metricSection(l)}<section>${btn(UI.confirm===l.id?tr('Really give it up?'):(l.own?tr('Abandon the fiber'):tr('Cancel the IRU')),'rmLink',{id:l.id},'ghost sm')}${cabBack(l)>0?`<p class="note">${tr('Giving it up now returns {price}.',{price:fmt$(cabBack(l))})}</p>`:''}</section></div>`;
return h;
}
function offersHere(c){
const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return '';
return `<section><h3>${tr('Offers here')}</h3>${os.map(o=>`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}</div>${R.reach<0.99&&!BIZ_T[o.type].l2?`<div class="why">${tr('They need the full internet. Your reach is {pct}.',{pct:pct(R.reach)})}</div>`:''}${o.type==='scrub'&&!hasScrub()?`<div class="why">${tr('Needs your own scrubbing center (Infra tab).')}</div>`:''}${reqList(o)}${bHas(o)?'':`<div class="why">${tr('Needs a POP in {cities} too.',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div>${bHas(o)?btn(tr('Accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('No'),'decline',{id:o.id},'ghost sm')}</div>`).join('')}</section>`;
}
function linkPanel(id){
const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';}
if(l.kind==='vxc')return vxcPanel(l);
if(l.kind==='df')return dfPanel(l);
const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk);
let h=`<div class="ph"><div><div class="eyebrow">${l.cable?esc(CAB[l.cable].name):l.sub?tr('Subsea cable'):tr('Terrestrial fiber')} · ${l.km.toLocaleString()} km</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('Close')}">×</button></div><div class="scroll">`;
if(cut)h+=`<section><h3 style="color:var(--bad)">${tr('Cut!')}</h3><p class="lead">${inc?esc(inc.msg):''} ${tr('Back in {n} days.',{n:l.cut-S.day})}</p>${inc&&inc.cost?btn(`${esc(inc.fix||tr('Rush repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>${tr('Capacity')}</h3><div class="kv"><span>${tr('{name} wave',{name:LT[l.tier].n})}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>${tr('Latency')}</span><b>${tr('{ms} ms one-way',{ms:linkLat(l).toFixed(1)})}</b></div>${l.cable?`<div class="kv"><span>${tr('Cable system')}</span><b>${esc(CAB[l.cable].name)}</b></div>`:''}
<div class="kv"><span>${tr('Wave lease')}</span><b>${tr('{price}/mo',{price:fmt$(l.mo)})}</b></div>${u>=0.9?`<p class="why">${tr('Congested. Upgrade it or add a parallel path.')}</p>`:''}
<div class="btns">${LT.map((T,i)=>{const d=Math.round(waveMo(l.km,l.sub,i)*(l.mult||1)),sw=subWaveWhy(i,l.km,l.sub),ok=waveOk(l.a,l.b,i);return i>l.tier&&waveShown(i)?btn(`${T.n} <small>${sw?tr('too far for this cable'):ok?tr('{price}/mo',{price:fmt$(d)}):tr('needs {what}',{what:esc(waveNeed(i))})}</small>`,'upLink',{id:l.id,tier:i},'sm',S.cash<d||!ok||!!sw):'';}).join('')}${l.sub&&subMaxTier(l.km)<LT.length-1?`<p class="note">${tr('{km} km of cable carries at most {g} per carrier.',{km:Math.round(l.km).toLocaleString(),g:fmtCap(subCarrier(l.km))})}${l.tier>subMaxTier(l.km)?' '+tr('Your wave was sold before the cable owner re-engineered it, so it keeps running.'):''}</p>`:''}</div></section>
<section><h3>${tr('Redundancy')}</h3><p class="lead">${mates.length?trn('Shares a trench with {n} other link. One cut takes them all down.','Shares a trench with {n} other links. One cut takes them all down.',mates.length):sib.length?tr('Runs on its own route. A cut here leaves the other links up.'):tr('This is the only link between these cities. Add a parallel one, or a path through another city.')}</p>
${sib.map(x=>`<div class="row"><div class="grow"><div class="nm">${tr('{name} parallel link',{name:capName(x)})} ${x.cut>S.day?'<span class="tag restrictive">'+tr('CUT')+'</span>':''}</div><div class="meta">${(x.trench||x.id)===trk?tr('same trench'):tr('diverse route')}</div></div>${btn(tr('Open'),'selLink',{id:x.id},'ghost sm')}</div>`).join('')}
<div class="btns">${btn(tr('Add parallel link'),'addParallel',{id:l.id},'pink sm')}</div></section>
${trafficSection(l)}${metricSection(l)}
<section>${btn(UI.confirm===l.id?tr('Really decommission?'):tr('Decommission link'),'rmLink',{id:l.id},'ghost sm')}</section></div>`;
return h;
}
const EGC={c:[tr('Caches'),'#16A866'],p:[tr('PNIs'),'#7B61FF'],ix:[tr('IX peering'),'#FFD23F'],t:[tr('Transit'),'#FF8A3D'],l2:[tr('L2 circuits'),'#2F8CFF']};
function svgChart(rows,stackKeys,lines,fmtY){
const W=600,H=180,L=50,B=20,T=8,Rr=8;if(rows.length<2)return `<p class="empty">${tr('Collecting data. Check back in a few days.')}</p>`;
let ymax=1;for(const r of rows){let s=0;for(const k of stackKeys)s+=r[k]||0;ymax=Math.max(ymax,s);for(const ln of lines)ymax=Math.max(ymax,r[ln.k]||0);}ymax*=1.1;
const x=i=>L+(W-L-Rr)*i/(rows.length-1),y=v=>T+(H-T-B)*(1-v/ymax);let g='';
for(let j=0;j<=3;j++){const v=ymax*j/3,yy=y(v);g+=`<line x1="${L}" x2="${W-Rr}" y1="${yy}" y2="${yy}" stroke="#D5DEEC" stroke-width="1"/><text x="${L-6}" y="${yy+3}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${fmtY(v)}</text>`;}
const base=rows.map(()=>0);
for(const k of stackKeys){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`;for(let i=1;i<rows.length;i++)d+=`L${x(i)},${y(top[i])}`;for(let i=rows.length-1;i>=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=`<path d="${d}Z" fill="${EGC[k][1]}" fill-opacity=".85" stroke="#1E2640" stroke-width=".8"/>`;top.forEach((v,i)=>base[i]=v);}
for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=`<path d="${d}" fill="none" stroke="${ln.col}" stroke-width="2.5" ${ln.dash?'stroke-dasharray="5 4"':''} stroke-linejoin="round"/>`;const last=rows[rows.length-1][ln.k]||0;g+=`<circle cx="${x(rows.length-1)}" cy="${y(last)}" r="3.5" fill="${ln.col}" stroke="#1E2640" stroke-width="1.5"/>`;}
g+=`<text x="${L}" y="${H-5}" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[0].d)}</text><text x="${W-Rr}" y="${H-5}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[rows.length-1].d)}</text>`;
return `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img">${g}</svg>`;}
// For a network you currently reach over transit: the cheapest way to move it to peering.
// Exchange members as sets, rebuilt once per routing pass: hints are asked for many networks at a time.
let IXMR=null,IXMC={};const ixHas=(x,id)=>{if(IXMR!==R){IXMR=R;IXMC={};}return (IXMC[x]||(IXMC[x]=new Set(ixMembers(x)))).has(id);};
function offTransitHint(id,city){const n=NET[id];if(n.type==='t1')return tr('Tier 1: only a PNI, and only once you are big enough for the Tier 1 club');
const ixc=Object.keys(S.pops).flatMap(ixIdsIn).filter(x=>ixHas(x,id)),here=city&&ixIdsIn(city).find(x=>ixHas(x,id))||null,pick1=here||ixc.find(x=>S.ixp[x]!==undefined)||ixc[0];
if(n.pol==='open'){if(pick1)return here||ixNamesCity(pick1)?tr('Open peer: join the route server at {ix}',{ix:ixName(pick1)}):tr('Open peer: join the route server at {ix} ({city})',{ix:ixName(pick1),city:CITY[ixCity(pick1)].name});const x=nearestSpot(id);return x?tr('Open peer, but not on any IX where you have a POP. Nearest: {city}',{city:CITY[x.c].name}):tr('Open peer, but not on any IX where you have a POP');}
if(n.pol==='paid')return paidFree(n)?tr('Peers with you for free over a PNI. You got too big to charge.'):n.freeLv?tr('Paid peering only: a PNI costs {price}/mo. Free from customer level {n}.',{price:fmt$(n.paidFee),n:n.freeLv}):tr('Paid peering only: a PNI costs {price}/mo',{price:fmt$(n.paidFee)});
const pniC=Object.keys(S.pops).filter(c=>n.pops.includes(c));const ixOk=pick1?peerOk(id,'ix',pick1):null,pOk=pniC.length?peerOk(id,'pni',pniC.includes(city)?city:pniC[0]):null;
if(pOk&&pOk.ok)return tr('Ready for a PNI in {city}',{city:CITY[pniC.includes(city)?city:pniC[0]].name});
if(ixOk&&ixOk.ok)return tr('Will peer at {ix}: request a session',{ix:ixName(pick1)});
if(ixOk)return `${ixName(pick1)}: ${ixOk.why}`;
if(pniC.length)return tr('PNI in {city}: {why}',{city:CITY[pniC[0]].name,why:pOk.why});{const x=nearestSpot(id);return x?tr('Not in your cities yet. Nearest: {city}',{city:CITY[x.c].name}):tr('Not present in any of your cities yet');}}
function transitTop(ids,k=5){const m={};for(const id of ids)for(const [n,v] of Object.entries(R.tNet[id]||{}))m[n]=(m[n]||0)+v;return Object.entries(m).filter(([,v])=>v>0.01).sort((a,b)=>b[1]-a[1]).slice(0,k);}