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,108 @@
/* ---------- daily tick ---------- */
function dayTick(){
if(!S||S.lost)return;
S.day++;
const d=S.day;
dkTick(d);ixPriceWar(d);inboxDay(d);pniDay(d);
if(!S.phpDone&&d>45&&Math.random()<1/400)elephant();
if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved);
{const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('<b>You are no longer Tier 1.</b><br>Because {why}. Your Tier 1 badge stays; win the status back to show it again.',{why:t1Why()}),'bad');S.t1Now=t1;}
if(S.grace&&S.grace.until===d){toast(tr('<b>The courtesy route has ended.</b><br>New networks you have not connected to are now only reachable through your own peering and transit.'),'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}]);}
{const a=S.ev.ddos;if(a&&a.until>d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,sfOf(R,a.city));}
if(scnRule('ddos')&&!(S.scn.done||S.scn.failed)&&d>=(+S.scn.nextDdos||3)&&!(S.ev.ddos&&S.ev.ddos.until>d)){ddosAttack();S.scn.nextDdos=d+3+Math.floor(Math.random()*5);}
if(R&&R.demand>0)S.stats.clean=R.served/R.demand>=0.995?(S.stats.clean||0)+1:0;
if(S.scn&&S.scn.id==='redsea')S.stats.asiaRun=asiaG()>=RS_G?(S.stats.asiaRun||0)+1:0;
if(S.ev.php===d)toast(tr('<b>The internet is back.</b><br>Half of it, anyway. Everything was patched in a hurry and nobody learned anything.'),'good');
for(const k in S.peers){const [id,c]=k.split('@'),sn=snub(id,c);if(!sn)continue;delete S.peers[k];S.stats.depeered=(S.stats.depeered||0)+1;
{const v={net:esc(NET[id].name),ix:esc(ixName(c)),city:esc(CITY[ixCity(c)].name),why:esc(sn.why)};toast(ixNamesCity(c)?tr('<b>{net} de-peered you at {ix}.</b><br>{why} Traffic falls back to your next best path.',v):tr('<b>{net} de-peered you at {ix} in {city}.</b><br>{why} Traffic falls back to your next best path.',v),'bad');}}
if(S.cnLic&&S.cnLic.state==='pending'&&d>=S.cnLic.ready){S.cnLic.state='ok';toast(tr('<b>License granted!</b><br>Your joint venture can now build POPs in mainland China.'),'goal');sfx('coin');}
// resolve incidents
for(const i of S.inc.slice())if(i.until<=d){const o=incOpen(i),l=o&&o.a==='link'&&S.links.find(x=>x.id===o.v),where=l?CITY[l.a].name+'–'+CITY[l.b].name:o&&o.a==='city'?CITY[o.v].name:'';clearInc(i);
toast(where?tr('<b>Resolved: {what}</b><br>{where} is back to normal.',{what:incTitle(i.type),where:esc(where)}):tr('<b>Resolved: {what}</b>',{what:incTitle(i.type)}),'good',[],o);}
// eyeball growth / churn uses last computed service
for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c),P=eyeP(c);
if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);}
else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));}
compute();
for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();}
S.cash+=(R.revMo-R.costMo)/30;
S.stats.peak=Math.max(S.stats.peak,R.served);
S.hist=S.hist||[];S.hist.push({d,dem:+R.demand.toFixed(2),srv:+R.served.toFixed(2),c:+(R.egT.c||0).toFixed(2),p:+(R.egT.p||0).toFixed(2),ix:+(R.egT.ix||0).toFixed(2),t:+(R.egT.t||0).toFixed(2),l2:+(R.egT.l2||0).toFixed(2),rev:Math.round(R.revMo),cost:Math.round(R.costMo),cash:Math.round(S.cash),inc:S.inc.length});if(S.hist.length>180)S.hist.shift();
{const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('<b>Customer level {lv}: {name}</b><br>New customers unlocked: {unlock}',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`<br><i>${esc(LEVELS[lv-1].q)}</i>`,'goal');}S.lvl=top;sfx('coin');}}
for(const l of S.links){if(l.kind!=='df')continue;
if(l.ready===d){toast(`<b>${l.own?tr('Your fiber is finished: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('Dark fiber handed over: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name})}</b><br>${(l.ch||[]).length?tr('Channels are lighting up now.'):tr('It is dark. Add optics to light it up.')}`,'goal',[{l:tr('Open'),act:'selLink',args:{id:l.id}}]);sfx('coin');}
if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+extra);toast(tr('<b>Construction delay: +{n} days</b><br>{why} ({a}–{b})',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('Archaeologists found a Roman bathhouse on your route.'),tr('A protected hamster species lives along the right-of-way.'),tr('The railway changed its mind about the easement.'),tr('The drilling crew hit a granite boulder the size of a bus.'),tr('A town council wants a public hearing. About the color of the manhole covers.'),tr('Somebody else’s gas main was exactly where the map said it was not.'),tr('The permit office lost your permit. And then the replacement.')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}}
// DDoS protection SLA: if a protected customer's own city is hit and still goes down, you pay out (once per attack).
if(S.ev.ddos&&S.ev.ddos.until>d){const a=S.ev.ddos;
for(const b of S.biz)if(b.type==='scrub'&&b.city===a.city&&b.slaFor!==a.start&&sfOf(R,b.city)<0.85){
b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1;
toast(tr('<b>SLA breach: {name}.</b><br>The attack on {city} got through and your protected customer went down. You owe {pen} in SLA credits.',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}}
// businesses mood
for(const b of S.biz.slice()){if(eventTick(b,d))continue;b.pm=b.mood;const sf=bizSf(b),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b);
if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2);
else if(S.day-(b.since||0)<15){}
else{b.mood-=(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));
if(b.mood<=0){S.biz=S.biz.filter(x=>x!==b);toast(tr('<b>{name} cancelled.</b><br>Too many outages and too little bandwidth in {city}.',{name:esc(b.name),city:CITY[b.city].name}),'bad');sfx('err');}
else if(b.mood<30&&!b.warned){b.warned=b.warn60=true;const why=bizWhy(b)[0],paused=pref('pauseFurious')&&autoPause();
toast(tr('<b>{name} is furious.</b><br>Fix service in {city} or they leave.',{name:esc(b.name),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:'')+(paused?`<br><b>${tr('Game paused.')}</b>`:''),'bad',[{l:tr('Show me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');}
else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('<b>{name} is getting unhappy.</b><br>Happiness {p}% in {city}.',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:''),'',[{l:tr('Show me'),act:'custGo',args:{id:b.id}}]);}}
if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}
// own IX members join
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<myFab(c).max){
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
if(cands.length){cands.sort((a,b)=>(a.pol==='open'?0:1)-(b.pol==='open'?0:1)||b.share-a.share);const n=Math.random()<.6?cands[0]:pick(cands);m.members.push(n.id);toast(tr('<b>{net} joined {ix}!</b><br>Another member paying {fee}/mo for a port.',{net:esc(n.name),ix:esc(m.name),fee:fmt$(MYIX_FEE)}),'good');sfx('coin');}
m.next=d+8+Math.floor(Math.random()*10);}}
loanTick(d);
if(S.mode==='sandbox'&&S.cash<1e8)S.cash=1e9;
// offers
S.offers=S.offers.filter(o=>o.exp>d);
if(S.offers.length<5&&Math.random()<0.05+0.01*(S.lvl||1))spawnOffer();
// failures & events
let dirty=false;
if(d>=S.nextFail){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1));}
if(d>=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+45+Math.floor(Math.random()*45);}
if(dirty)compute();
// payday floaters
if(d%30===0){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-(CITY[c].arpu||1));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}
checkGoals();
scnTick(d);
confTick(d);
// money trouble
if(S.cash<0){S.neg++;if(S.neg===1)toast(tr('<b>You are in the red.</b><br>Cancel something expensive, wait for revenue, or check the bank for a loan. At −$100k the bank takes your routers.'),'bad');}
else S.neg=0;
if(S.cash<-100000){S.lost=true;track('bankrupt');showLose();return;}
if(d%360===0&&[1,2,4].includes(d/360))track('game_year_'+(d/360+1),true);
if(d%10===0)save();
}
function spawnOffer(){
const mine=Object.keys(S.pops),lv=S.lvl||1;
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub');
if(lv>=2)types.push('isp','stream','edu','host','hft','bulk','event','event');if(mine.length>=3&&lv>=2)types.push('sdwan','sdwan');
if(S.links.some(l=>l.kind==='df'&&l.ready<=S.day))types.push('wwave','wwave');if(S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('dfpair');if(lv>=3)types.push('gpu','gpu','onramp','onramp');if(lv>=4)types.push('ai','ai','hyper','hyper');
if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if(lv>=4&&S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('pairs');
if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars');
const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor');
const fabC=mine.filter(c=>FABS.some(f=>f.cities.includes(c)));if(lv>=2&&fabC.length){types.push('fabip','fabip');if(mine.length>=2)types.push('fabl2');}
const t=pick(types),T=BIZ_T[t];
if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;}
if(T.nni){const city=pick(fabC),prov=pick(FABS.filter(f=>f.cities.includes(city))).id,bw=pick(T.opts),others=mine.filter(c=>c!==city),city2=T.l2&&others.length?pick(others):null;if(T.l2&&!city2)return;
const base=pick(BIZ_N.filter(n=>!S.usedNames.includes(n)).concat(BIZ_N)).replace(/ (Inc\.|Co\.|Ltd)$/,'');const name=tr('{name} via {fab}',{name:base,fab:FAB[prov].name});S.usedNames.push(base);
const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate;
S.offers.push({id:uid(),city,city2,prov,name,type:t,bw,rate,reqs:['nni'],exp:S.day+40});return;}
let city=(Math.random()<0.65&&mine.length)?pick(mine):pick(ALLC.concat(cnOk()?['pek','sha']:[])),city2=null;
if(T.l2){city=pick(mine);const pool=(Math.random()<(T.lv>=3?0.8:0.6)?mine:ALLC).filter(c=>c!==city);city2=pick(pool.length?pool:ALLC.filter(c=>c!==city));}
let bw=T.lv>=2?pick(T.opts):pick(T.opts.slice(0,mine.length>=4?4:3));
const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));
let name=list.length?pick(list):(T.names?pick(T.names):'Startup #'+Math.floor(Math.random()*999));
S.usedNames.push(name);
if(t==='provedor')city=pick(br);
if(t==='hft'){const fin=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'],mf=mine.filter(c=>fin.includes(c));city=mf.length?pick(mf):pick(mine);city2=pick(fin.filter(c=>c!==city));}
let rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate;
if(CITY[city].au&&!T.l2&&!T.fiber&&!T.event){rate=Math.round(rate*AU_ARPU);bw=Math.min(bw,pick(T.opts.slice(0,2)));}
if(T.div&&!reqCan('diverse',{city,city2}))return;
const reqs=T.div?['diverse']:T.lat?['lat']:[];if((t==='hyper'||t==='ai'||t==='gpu')&&Math.random()<0.4)reqs.push('metro');const pool=Object.keys(REQS).filter(k=>!reqs.includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,{city,city2}));
if(Math.random()<(T.lv>=3?0.65:0.3))reqs.push(pick(pool));
if(T.lv>=3&&Math.random()<0.35){const more=pool.filter(k=>!reqs.includes(k));if(more.length)reqs.push(pick(more));}
const r2=Math.round(rate*(1+reqs.reduce((a,k)=>a+REQS[k].bonus,0)));
S.offers.push({id:uid(),city,city2,name,type:t,bw,rate:r2,reqs,latMax:T.lat?+(kmBetween(city,city2)/200*1.35).toFixed(1):null,exp:S.day+40});
}

View file

@ -0,0 +1,89 @@
/* Badges: achievements with rarities. Earned per game, and also remembered across games on this
device in a hall of fame, so there is always something grand to work towards. */
const RARITY={c:{n:tr('Common'),col:'#16A866'},r:{n:tr('Rare'),col:'#3A7BEA'},e:{n:tr('Epic'),col:'#9D4EDD'},l:{n:tr('Legendary'),col:'#FF8A3D'}};
const st=()=>S.stats||{};
const BADGES=[
{id:'hello',i:'👋',t:tr('Hello, Neighbour'),d:tr('Bring up your first peering session.'),r:'c',ok:()=>R.sessions>=1},
{id:'backhoe',i:'🚜',t:tr('Met the Backhoe'),d:tr('Have a fiber cut.'),r:'c',ok:()=>(st().by||{}).cut>=1},
{id:'debt',i:'🏦',t:tr('In Debt We Trust'),d:tr('Take out a loan.'),r:'c',ok:()=>(st().loans||0)>=1||(S.loans||[]).length>0},
{id:'twins',i:'👯',t:tr('Twins'),d:tr('Run two routers in one POP.'),r:'c',ok:()=>Object.values(S.pops).some(p=>(p.routers||1)>=2)},
{id:'shark',i:'🦈',t:tr('Shark Week'),d:tr('Get a subsea cable bitten by a shark.'),r:'r',ok:()=>(st().sharks||0)>=1},
{id:'ixc',i:'🔀',t:tr('IX Collector'),d:tr('Have ports on 10 internet exchanges.'),r:'r',ok:()=>Object.keys(S.ixp).length>=10},
{id:'haggle',i:'🤝',t:tr('Never Paid List Price'),d:tr('Haggle a DE-KICKS quote down.'),r:'r',ok:()=>!!st().haggleWin},
{id:'unsub',i:'📭',t:tr('Unsubscribed'),d:tr('Opt out of 3 auto-enrolled add-ons.'),r:'r',ok:()=>(st().optouts||0)>=3},
{id:'read',i:'💔',t:tr('Left on Read'),d:tr('Get de-peered by a big network.'),r:'r',ok:()=>(st().depeered||0)>=1},
{id:'couch',i:'🛋️',t:tr('Peering From the Couch'),d:tr('Peer at an IX remotely.'),r:'r',ok:()=>Object.keys(S.ixp).some(c=>isRemote(c)&&ixSessions(c).size>0)},
{id:'sender',i:'🇰🇷',t:tr('Sender Pays'),d:tr('Paid PNIs with all three Korean incumbents.'),r:'e',ok:()=>['ktt','skb','lgu'].every(n=>S.pni.some(p=>p.net===n&&pniOn(p)))},
{id:'oink',i:'🐖',t:tr('Pig Whisperer'),d:tr('Run a slow-booting PacketOinker chassis.'),r:'r',ok:()=>Object.keys(S.pops).some(c=>/Oinker/.test(RG[S.pops[c].rgen||0].chip)&&slowBoot(c))},
{id:'gap',i:'🌴',t:tr('Mind the Gap'),d:tr('Link Panama City and Bogotá.'),r:'r',ok:()=>S.links.some(l=>[l.a,l.b].includes('pan')&&[l.a,l.b].includes('bog'))},
{id:'andes',i:'🏔️',t:tr('Over the Mountains'),d:tr('Build fiber across the Andes.'),r:'r',ok:()=>S.links.some(l=>!l.sub&&andesPair(l.a,l.b))},
{id:'duo',i:'🏜️',t:tr('Duopoly Customer'),d:tr('Buy a wave inside the UAE.'),r:'r',ok:()=>S.links.some(l=>uaePair(l.a,l.b))},
{id:'shed',i:'🔌',t:tr('Stage Six'),d:tr('Ride out load shedding on your own generator.'),r:'r',ok:()=>(st().shed||0)>=1},
{id:'metro3',i:'🏢',t:tr('Two Buildings, Three Cities'),d:tr('Have a second site in 3 metros.'),r:'r',ok:()=>Object.values(S.pops).filter(p=>p.site2).length>=3},
{id:'penguin',i:'🐧',t:tr('Lonely Penguin'),d:tr('Light a wave on the Humboldt cable to Sydney.'),r:'e',ok:()=>S.links.some(l=>l.cable==='humb')},
{id:'horn',i:'⛵',t:tr('The Long Way Round'),d:tr('Run a link round Cape Horn.'),r:'e',ok:()=>S.links.some(l=>l.cable==='sam1'&&[l.a,l.b].includes('bue')&&[l.a,l.b].includes('scl'))},
{id:'six',i:'🌍',t:tr('Six Continents'),d:tr('POPs in every region on the map.'),r:'e',ok:()=>regionsCount()>=6},
{id:'giants',i:'🏭',t:tr('Friend of Giants'),d:tr('Hold deals at 3 different AI campuses at once.'),r:'e',ok:()=>new Set(S.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega).flatMap(b=>bCities(b))).size>=3},
{id:'landlord',i:'🧵',t:tr('Trench Landlord'),d:tr('Lease hundreds of fiber pairs to a hyperscaler.'),r:'e',ok:()=>S.biz.some(b=>b.type==='pairs')},
{id:'t1',i:'👑',t:tr('Tier 1'),d:tr('Go transit-free.'),r:'e',ok:()=>!!S.won},
{id:'bait',i:'🎣',t:tr('Shark Bait'),d:tr('Get bitten by sharks 3 times in one game.'),r:'l',ok:()=>(st().sharks||0)>=3},
{id:'nines',i:'💎',t:tr('Five Nines'),d:tr('Serve 99.5% of demand every single day for a whole year.'),r:'l',ok:()=>(st().clean||0)>=365},
{id:'fifty',i:'🗺️',t:tr('Everywhere at Once'),d:tr('Have POPs in 50 cities.'),r:'l',ok:()=>Object.keys(S.pops).length>=50},
{id:'unicorn',i:'🦄',t:tr('Unicorn'),d:tr('Hold a billion dollars in cash.'),r:'l',ok:()=>S.cash>=1e9},
{id:'clean',i:'🧼',t:tr('Debt-Free Tier 1'),d:tr('Win without ever taking a loan.'),r:'l',ok:()=>!!S.won&&!(st().loans||0)&&!(S.loans||[]).length},
{id:'speed',i:'⚡',t:tr('Speedrun'),d:tr('Reach Tier 1 within three years.'),r:'l',ok:()=>!!S.won&&S.day<=1095},
{id:'te',i:'🧭',t:tr('Traffic Whisperer'),d:tr('Have Auto-TE move 100 Gbps onto alternate paths at once.'),r:'r',ok:()=>(st().teMax||0)>=100},
{id:'street',i:'🚧',t:tr('Same Street'),d:tr('Lose a metro ring to one backhoe.'),r:'r',ok:()=>(st().by||{}).ring>=1},
{id:'anchor',i:'⚓',t:tr('Anchors Aweigh'),d:tr('Have a cable cut by a dragged anchor.'),r:'r',ok:()=>!!(st().f||{}).anchor},
{id:'retained',i:'🎁',t:tr('Customer Success Story'),d:tr('Take a DE-KICKS retention offer.'),r:'r',ok:()=>!!st().retained},
{id:'brrr',i:'🇧🇷',t:tr('Samba Peering'),d:tr('Ports on IX.brrr in São Paulo, Rio and Fortaleza.'),r:'e',ok:()=>['sao','rio','for'].every(c=>S.ixp[c]!==undefined)},
{id:'bingo',i:'🎰',t:tr('DE-KICKS Bingo'),d:tr('Ports at all six DE-KICKS exchanges. They thank you for your continued partnership.'),r:'e',ok:()=>DK_CITIES.filter(c=>CITY[c]&&CITY[c].ix).every(c=>S.ixp[c]!==undefined)},
{id:'fire',i:'🌋',t:tr('Ring of Fire'),d:tr('POPs all the way round the Pacific: Los Angeles, Tokyo, Taipei, Manila, Jakarta, Sydney, Auckland and Santiago.'),r:'e',ok:()=>['lax','tok','tpe','mnl','jkt','syd','akl','scl'].every(c=>S.pops[c])},
{id:'curtain',i:'🎭',t:tr('Iron Curtain Call'),d:tr('POPs in Warsaw, Prague, Vienna, Budapest, Bucharest, Sofia, Belgrade and Tallinn.'),r:'e',ok:()=>['waw','prg','vie','bud','buh','sof','beg','tll'].every(c=>S.pops[c])},
{id:'islands',i:'🏝️',t:tr('Island Hopper'),d:tr('POPs in Reykjavik, Dublin, London, Colombo, Taipei, Manila, Tokyo and Auckland.'),r:'e',ok:()=>['rek','dub','lon','cbo','tpe','mnl','tok','akl'].every(c=>S.pops[c])},
{id:'wall',i:'🧱',t:tr('Through the Wall'),d:tr('Run a licensed POP in mainland China.'),r:'e',ok:()=>cnOk()&&Object.keys(S.pops).some(cnCity)},
{id:'beaver',i:'🦫',t:tr('Dam It'),d:tr('Have your fiber chewed through by a beaver.'),r:'e',ok:()=>!!(st().f||{}).beaver},
{id:'croc',i:'🐊',t:tr('Darwin Award'),d:tr('Have your fiber bitten by a crocodile.'),r:'l',ok:()=>!!(st().f||{}).croc},
{id:'unbreak',i:'🛡️',t:tr('Unbreakable'),d:tr('Survive 100 incidents without customer impact.'),r:'l',ok:()=>(st().survived||0)>=100},
{id:'lv13',i:'🌐',t:tr('Is This the Internet?'),d:tr('Reach customer level 13.'),r:'l',ok:()=>(S.lvl||1)>=13},
{id:'gigawatt',i:'⚛️',t:tr('Gigawatt Landlord'),d:tr('Hold an AI WAN, a training run, an ingest and a fiber-pairs deal at the same time.'),r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))},
{id:'blitz',i:'🚀',t:tr('Blitz'),d:tr('Reach Tier 1 within two years.'),r:'l',ok:()=>!!S.won&&S.day<=730},
{id:'peta',i:'🌌',t:tr('Hundred Terabits'),d:tr('Serve 100 Tbps.'),r:'l',ok:()=>R.served>=100000},
{id:'petabit',i:'🪐',t:tr('A Petabit a Second'),d:tr('Serve 1 Pbps: a thousand terabits of happy traffic.'),r:'l',ok:()=>R.served>=1e6},
{id:'llama',i:'🦙',t:tr('Llama Drama'),d:tr('Lose fiber to a llama herd.'),r:'l',secret:true,ok:()=>!!(st().f||{}).llama},
{id:'hallway',i:'🎤',t:tr('Hallway Track'),d:tr('Attend a conference.'),r:'r',ok:()=>(st().confs||0)>=1},
{id:'beer',i:'🍺',t:tr('Peering Over Beer'),d:tr('Set up a PNI while the conference glow lasts.'),r:'e',ok:()=>!!st().beerPni},
{id:'circuit',i:'✈️',t:tr('Conference Circuit'),d:tr('Attend six conferences in one game.'),r:'l',ok:()=>(st().confs||0)>=6},
{id:'kiddie',i:'💻',t:tr('Script Kiddie'),d:tr('Deploy a RouteScript that cuts your transit bill by 10% without losing traffic.'),r:'r',ok:()=>!!st().kiddie},
{id:'fat',i:'🫠',t:tr('Fat Finger'),d:tr('Deploy a RouteScript that takes down a third of your traffic.'),r:'r',ok:()=>!!st().fat},
{id:'scen1',i:'🎯',t:tr('Scenario Solver'),d:tr('Complete any scenario.'),r:'r',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')},
{id:'weekly',i:'📅',t:tr('Weekly Regular'),d:tr('Finish a weekly challenge.'),r:'r',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id==='weekly')},
{id:'scen3',i:'🏅',t:tr('Scenario Specialist'),d:tr('Complete three different scenarios.'),r:'e',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')&&Object.keys(scnHof()).filter(k=>k!=='weekly').length>=3},
{id:'scenall',i:'🏆',t:tr('Scenario Grandmaster'),d:tr('Complete every scenario.'),r:'l',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')&&SCN.every(x=>scnHof()[x.id])},
{id:'elephant',i:'🐘',t:tr('I Survived the Elephant'),d:tr('Live through the day half the internet went down.'),r:'l',secret:true,ok:()=>!!S.phpDone&&!(S.ev.php>S.day)},
{id:'vigil',i:'⚖️',t:tr('Vigilante'),d:tr('Fire the HackBack 3000™ and flatten an innocent.'),r:'e',secret:true,ok:()=>(st().vigilante||0)>=1},
{id:'nullroute',i:'💥',t:tr('Collateral Damage'),d:tr('Blackhole one of your own cities to stop a DDoS.'),r:'r',ok:()=>(st().rtbh||0)>=1},
{id:'toaster',i:'🍞',t:tr('Toaster Wrangler'),d:tr('Weather a DDoS with your defences ready.'),r:'c',ok:()=>(st().ddosHeld||0)>=1},
{id:'cleanpipe',i:'🚿',t:tr('Clean Pipes'),d:tr('Turn on a transit clean-pipe add-on.'),r:'r',ok:()=>S.transit.some(t=>t.clean)},
{id:'lamb',i:'🐐',t:tr('Sacrificial Lamb'),d:tr('Run a sacrificial PNI choke point.'),r:'r',ok:()=>S.pni.some(p=>p.sacrif)},
{id:'flood',i:'🌊',t:tr('Held the Flood'),d:tr('Weather a multi-terabit DDoS.'),r:'e',ok:()=>(st().ddosMonster||0)>=1},
{id:'skynot',i:'🤖',t:tr('Skynot Smiles'),d:tr('Land a HackBack 3000™ that actually works.'),r:'e',secret:true,ok:()=>(st().hackWin||0)>=1},
{id:'zero',i:'🕳️',t:tr('Zero Peers Given'),d:tr('Reach Tier 2 with every single session over the route server.'),r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length},
];
function hof(){try{return JSON.parse(localStorage.getItem('sot-badges')||'{}')||{};}catch(e){return {};}}
function checkBadges(){S.ach=S.ach||{};if(S.mode==='sandbox')return;let h=null;
for(const b of BADGES){if(S.ach[b.id]!==undefined)continue;let ok=false;try{ok=b.ok();}catch(e){}
if(!ok)continue;S.ach[b.id]=S.day;const R0=RARITY[b.r];
if(!h)h=hof();if(!h[b.id])h[b.id]={d:new Date().toISOString().slice(0,10),n:S.name};
toast(`<b>${b.i} ${tr('Badge unlocked: {name}',{name:esc(b.t)})}</b><br><span style="color:${R0.col};font-weight:900">${R0.n}</span> · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id);}
if(h)try{localStorage.setItem('sot-badges',JSON.stringify(h));}catch(e){}}
function badgeGrid(){const h=hof(),got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined).length;
return `<h3 style="font-size:15px;margin:14px 0 6px">${tr('Badges')} <span class="meta">${tr('{got}/{total} this game · {ever} ever',{got,total:BADGES.length,ever:Object.keys(h).filter(k=>BADGES.some(b=>b.id===k)).length})}</span></h3><div class="badges">${BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!h[b.id],R0=RARITY[b.r],hide=b.secret&&!on&&!ever;
return `<div class="bdg ${on?'on':ever?'ever':''}" style="--rc:${R0.col}" title="${esc(hide?tr('A secret badge'):b.t+': '+b.d)}"><span class="bi">${hide?'❔':b.i}</span><span class="bt">${esc(hide?'???':b.t)}</span><span class="br">${R0.n}${ever&&!on?' · '+tr('earned before'):''}</span>${hide?'':`<span class="bd">${esc(b.d)}</span>`}</div>`;}).join('')}</div>`;}
function checkGoals(){checkBadges();
for(const g of GOALS){if(S.done[g.id]!==undefined)continue;let ok=false;try{ok=g.ok();}catch(e){}
if(ok){S.done[g.id]=S.day;if(g.r&&S.mode!=='sandbox'){S.cash+=g.r;}
toast(`<b>${tr('Goal complete: {name}',{name:esc(g.t)})}</b>${g.r?`<br>${tr('Reward: +{amt}',{amt:fmt$(g.r)})}`:''}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');
track('goal_'+g.id);if(g.win&&!S.won){S.won=true;track('win_tier1');checkBadges();showWin();}}}
}