Merge upstream main and reconcile community exchanges

This commit is contained in:
Nick Bouwhuis 2026-10-24 15:15:22 +02:00
commit e0e1500b8e
24 changed files with 2265 additions and 346 deletions

View file

@ -6,17 +6,21 @@ name: Release to GitHub Pages
# tagged v<version>.
on:
release:
types: [published]
# "released" also fires when a pre-release is promoted to a full release.
types: [released]
workflow_dispatch:
inputs:
tag:
description: Existing release tag to redeploy (e.g. v1.0.0)
required: true
allow_older:
description: Allow deploying a version older than what is live (rollback)
type: boolean
default: false
# Least privilege: only the deploy job can write to Pages.
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
@ -29,6 +33,8 @@ jobs:
runs-on: ubuntu-latest
env:
TAG: ${{ github.event.release.tag_name || inputs.tag }}
ALLOW_OLDER: ${{ inputs.allow_older || false }}
GH_TOKEN: ${{ github.token }}
steps:
- uses: actions/checkout@v7
with:
@ -45,10 +51,21 @@ jobs:
echo "::error::Release tag $TAG does not match package.json version ($want)"
exit 1
fi
- name: Never deploy pre-releases or roll the live site back by accident
run: |
set -euo pipefail
if [ "$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isPrerelease -q .isPrerelease)" = "true" ]; then
echo "::error::$TAG is a pre-release; pre-releases never deploy"; exit 1
fi
live=$(curl -sSf https://seriesoftub.es/version.json 2>/dev/null | jq -r .version || echo "0.0.0")
new="${TAG#v}"
if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then
echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1
fi
- run: npm ci
- run: npm test
- name: Build site
run: VERSION="${TAG#v}" npm run build
run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build
- uses: actions/upload-pages-artifact@v5
with:
path: ./_site
@ -56,6 +73,9 @@ jobs:
deploy:
needs: build
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

View file

@ -6,6 +6,215 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- Barcelona joins the map with Catnip-IX, local transit and peering.
- Community exchanges now include FRIES-IX, Paella-NIX, KleyWrecks,
LO-NAPS, JINXED-IX and IX Strayla, plus BB-Kicks in Tokyo and
DE-KICKS New York. FRIES-IX ports and LAG members up to 400G are free.
## [1.10.0] — 2026-10-24
- Router ports are finite. Every transit, IX, PNI and cache port, every wave
and every fibre channel takes a router port; 10G ports ride a breakout,
four to a port. The Infra tab shows how many are left, and plugging in more
than you have is refused.
- More routers: up to six per POP, and six new models to swap in from the
Infra tab: Mikrowtik CCR-ish, Sonic the Whitebox 32 (cheap, crashes more),
Arrrhipster 7280R-ish and 7800R-ish (lots of ports, deep buffers, boots in
minutes), Disco 8K-ish (licence keys for everything) and Knockia 7750-ish.
A swap that would not fit what is already plugged in is refused.
- New cities: Milan, Rome, Palermo, Lisbon and Athens in Europe; Atlanta,
Denver, Phoenix, Boston, Houston and Salt Lake City in the US. New cables
land with them (Lisbon to Brazil, Africa and the US Southeast; Genoa to
Sicily and Athens; Palermo to Marseille and Alexandria; Athens to Istanbul;
Boston to Dublin), along with local networks to peer with.
- Rival exchanges: 25 big metros now have a second (sometimes third) IX.
Challengers are cheaper and share many members with the incumbent, but not
all of them. Each IX is its own port, LAG and route server.
- The long tail: 60 small, odd networks with a sliver of traffic each, spread
over random exchanges. "Request all willing peers" signs them up in one go,
and they fold into one row in the network lists.
- Europe's peering market is competitive: IX ports there cost 20% less, and
price wars between rival exchanges cut your port bill further. DE-KICKS
responds with a webinar.
- Voda-Phony has ended settlement-free peering. It now peers only over a paid
PNI, through its interconnection partner.
- New US eyeballs Spectre-um Cable and Very-Zone (paid peering only).
- Pausing now freezes the map too: packet dots, waves and clouds stop
moving until you press play again (#11).
- Ports in both buildings: with a second site, any transit port, PNI or IX
port can now be set to "Both". That splits it into a LAG with members in
each building (adding a member if needed), so a dark building only takes
out half the port instead of all of it (#8).
- The top bar no longer wraps onto a second row and covers the side panels
on laptop-sized screens.
- Routers make sense now: the Chonk 800 takes 800G waves and ports (a new
800G wave sits between 400G and 1.6T), and only the Absolute Unit has 1.6T
ports and takes 6.4T waves, handed off as 4×1.6T. Existing waves keep
their size.
- London–Amsterdam is everywhere: three more cheap North Sea cables, and dark
fiber you can lease on them (and on the Channel), since you can't dig under
the sea.
- Your own IX can grow (#10): upgrade its fabric from 400G to 1.6T, 6.4T and
25.6T. Bigger fabrics carry more and have room for more members.
- Wave prices follow real markets: Europe is cheap, North America average,
Asia and South America pricier, and anything into Africa several times the
price. Every route has its own going rate, and new leases get about 8%
cheaper each year. The link planner tells you how a route compares.
- Cairo–Dubai over the Red Sea, plus I-ME-WE-Us to Fujairah and Mumbai.
- The Gulf: Jeddah, Riyadh and Doha. Saudi POPs need a local telecom licence,
gigaprojects want enormous demo networks, and now and then the neighbours
fall out and every link between Qatar and Saudi Arabia or the UAE goes dark
for months. Qatar is on the map as a peninsula now, too.
- Tablets in landscape: slimmer side panels, bigger touch targets, and the
left panel tucks away while a city is open (tap "Goals & NOC" to bring it
back).
## [1.9.0] — 2026-10-23
- RouteScript: program your Auto-TE controller from the NOC tab with a tiny
rule language: `spill at 80%`, `prefer pni for goggle`, `avoid transit for
netchill`, `cap transit cogentle at 20 gbps`, `drain paris`, `avoid link
fra-ams` and `blackhole ddos`. Check runs a dry run against live traffic
and shows what would change; Deploy makes it real. Typos get a "did you
mean". Two new badges: Script Kiddie and Fat Finger.
- Zoom in twice as far as before, handy for crowded spots like the UAE,
Singapore or Central Europe.
- Half speed: a new ½× button, or press 0.
- NOC dashboard: a legend explains the colours in "How it arrives", the
network table sorts by any column (traffic, transit cost, loss, name), and a
new "Who your transit carries" list shows the networks you pay transit to
reach, with the cheapest way to move each one to peering (#7).
- The Transit tab shows the top destinations on each transit port, with the
same hint, so you can see who to peer with in that city (#7).
- A full code review, and about 40 fixes from it:
- Saves and imported files are checked and repaired before use, so a
damaged or hand-edited save can no longer break the game or inject
anything into the page.
- Loophole fixes: flipping crypto loans for profit, free repairs of
geopolitical cable cuts, re-rolling DE-KICKS quotes, walking out of a
failing event, and selling the same trench twice.
- The Red Sea scenario really cuts the Red Sea now, the weekly challenge
gives everyone the same world, and its "pricey" and "poor" twists work.
- China Telecomet and China Unicorn no longer act like Tier 1s.
- Metro ring cuts now alert you, overlapping site outages no longer cancel
each other, and alien waves work on unlit fiber.
- Routing is several times faster on big networks.
- The map fills wide screens at any zoom, pinch zoom goes as far as the
mouse wheel, and touch scrolling and cancelled touches behave.
- Starting a scenario from a running game asks first, and Space no longer
pauses when you meant to press a button.
- Settings for animations and sound, in the menu and on the help screen.
Animations can follow your device's reduce-motion setting (the default),
or be forced on or off. Off freezes the map: no moving packets, pulses or
floating text.
## [1.8.0] — 2026-10-23
- Traceroute and looking glass: tap 🔍 Traceroute on any of your cities, or
open it from the NOC tab. See the exact path to any network or POP, hop by
hop, with latency, the exit it leaves through and the AS path, plus why
that exit won.
- Share card: an image of your network with a mini map, your stats and your
rarest badges, ready to post. Find it in the menu, after winning and after
a scenario.
- Scenarios: six hand-built challenges with a goal and a deadline (Only
Spätzle-IX, Red Sea Crisis, The Cogentle Spat, Carnaval, Mind the Gap and
Anchors Away), plus a weekly challenge where everyone gets the same world,
the same start city and the same two twists for a week.
- Sandbox mode: a billion dollars, every unlock and nothing ever breaks.
No badges, though.
- Conference season: NANOG-ish, RIPE-ish, DENOG-ish, APRICOT-ish and more
come round every year. Register in the Deals tab and selective networks in
that region need half the usual traffic to peer with you for 45 days.
- A guided first game for new players, step by step, with a skip button.
- Kyiv, with Varenyky-IX and KyivStar-ish. Blackouts are frequent, so bring
a generator. Nobody sells capacity between Kyiv and Moscow.
- 7 more badges for scenarios, the weekly challenge and conferences.
## [1.7.0] — 2026-10-23
- Auto-TE: from customer level 3 you can install a traffic-engineering
controller in the NOC tab. When the shortest path is full, the overflow
spills onto up to two alternate paths with free capacity instead of being
dropped. Without it, traffic still reroutes around failures, but a full
link stays full, just like a real IGP.
- 16 more badges, mostly rare, epic and legendary: Traffic Whisperer, Same
Street, Anchors Aweigh, Samba Peering, DE-KICKS Bingo, Ring of Fire, Iron
Curtain Call, Island Hopper, Through the Wall, Darwin Award, Unbreakable,
Gigawatt Landlord, Blitz, Hundred Terabits and a few more, one of them
secret. That makes 46.
## [1.6.0] — 2026-10-23
- South America is on the map properly: Fortaleza, Rio de Janeiro, Buenos
Aires, Santiago, Lima, Bogotá and Panama City, with new cables including a
ring round Cape Horn, a direct São Paulo–New York cable and the first
cable from Chile to Sydney. Nothing crosses the Darién Gap by land, transit
is pricier because so much traffic hairpins through Miami, and fiber over
the Andes costs double and breaks often. IX.brrr is run by a nonprofit
with cheap public prices, and small Brazilian provedores now buy transit
from you.
- More India: Delhi, Chennai, Bengaluru and Hyderabad, with east-coast cables
to Singapore and a lot of road widening.
- Taiwan: Taipei, with cables to Tokyo, Hong Kong, Los Angeles, Seattle and
Shanghai, and ships that keep dragging their anchors over them.
- The UAE: Abu Dhabi and Fujairah join Dubai. Only the licensed duopoly may
run fiber inside the country, so there is no dark fiber, waves cost 3×, and
POPs need a free-zone license. Most cables land in Fujairah.
- Cape Town, with Atlantic cables up the west coast of Africa and load
shedding: bring a generator.
- New local networks: Clarovision, Vivo-ish, Mercado Livre-ly, Jio-graphy,
Airtel-tale, Chunghwa Tele-calm and do-ish.
- Metro diversity: add a second data center in any POP's metro from the
Infra tab, joined by your own metro ring. A power cut, cleaner or A/C
failure then only takes out half the city. You choose which site each
transit, PNI and IX port plugs into, and metro ring cuts can cut site B
off. Some hyperscaler and AI customers now insist on two sites.
- More Asia-Pacific: Melbourne, Brisbane, Darwin, Osaka, Kuala Lumpur,
Bangkok, Ho Chi Minh City, Karachi, Dhaka and Colombo, with cables to match.
Vietnam's cables break a lot, and Darwin has crocodiles.
- Central and Eastern Europe: Warsaw, Prague, Vienna, Budapest, Bucharest,
Tallinn and Istanbul. Baltic cables meet a lot of anchors.
- The giants: at customer levels 3 and 4, hyperscalers and AI clouds bring
deals only they would ask for. Terabit AI WANs between gigawatt campuses,
training runs spread over three or four sites, week-long dataset ingests,
and hundreds of fiber pairs in a trench you dug yourself. Their campuses,
from Star-Gait Abilene to the Johor-ish Overflow, show up in each city's
"Who's here".
- Dark fiber pairs you lease out now earn even before you light your own
channels on that fiber.
- More local networks: KD-DIY, Opt-Out-Us, Mostly-True Move, Viet-tell,
PTC-hell, Telekom Ma-lazy-sia, Türk Tele-komik, Digi-tally Cheap and
UPC-You-Later.
- Badges: 30 achievements from common to legendary, shown under your goals.
Some take luck (Shark Bait), some take years (Five Nines, Speedrun), and a
couple are secret. Badges from earlier games stay on this device in a hall
of fame.
- Five new goals between Tier 2 and Tier 1: light your own dark fiber, be in
two buildings at once, five continents, sign a giant, and serve 10 Tbps.
- Tap your network's name in the top left for a menu to export or import a
save, or start a new network.
## [1.5.0] — 2026-10-23
- Several transits in the same city now share the load instead of filling one
after the other. The same goes for any exits that are equally close: traffic
is spread by free capacity, and local exits still win over far ones (#4).
- Export your save to a file and import it on another device, from the help
screen or the title screen (#5).
- Full transit ports, IX ports, PNIs, caches and routers are now easy to spot.
They get red badges on the map (T, P, C, R), the IX hexagon blinks red when
its port is full, and the NOC lists everything running hot with a hint on
what to do (#6).
- Some routers take forever to boot. The Infra tab shows each chassis's boot
time and its forwarding chip, including the Junipurr PacketOinker™ in the
Chonk 800 and two of them in the Absolute Unit. On a slow booter, crashes
last a few days longer, a rush repair still needs a day of booting, and
swapping the only router takes three days. Bigger chassis are slow more
often. A second router hides all of it.
## [1.4.0] — 2026-10-23
- Big peers have moods now. In some cities, large selective networks refuse
new peering for a few months, or only take PNIs there, each with a reason
("the peering coordinator is on sabbatical", "a new VP wants to monetise
@ -17,16 +226,14 @@ All notable changes to this project are documented here. The project follows
yours. Goggle, Faceplant, Comecast and several other selective networks
refuse remote members outright. The route server still gets you every open
network, and building a real POP removes all of this.
- Amsterdam has a second exchange: FRIES-IX, run by volunteers out of the
Science Park. Ports up to 400G are free, LAG members too. It has fewer
members than HAMS-IX (Drizzle, Akamaybe, Crowdflare, Slowly and Microsnoft),
and you can join either exchange or both.
- More cities got a second exchange, each with its own members and its own
price: Paella-NIX in Madrid, KleyWrecks in Frankfurt, LO-NAPS in London,
DE-KICKS New York, JINXED-IX in Johannesburg, IX Strayla in Sydney and
BB-Kicks in Tokyo. The community ones charge less for ports.
- New city: Barcelona, home of the Catnip-IX. Local networks find it
impossible to resist.
- DE-KICKS Group (Frankfurt, Madrid, Marseille, Dubai, Mumbai and New York)
really hates open pricing. There is no price list, only a personalised
quote that grows with how big you look. Haggling can get you a discount,
raise the price "after consulting with management", or stall for a week
behind an NDA. Prices are "harmonised" upwards once a year. Add-ons like
Route Server Gold and Premium Port LEDs appear on your invoice until you opt
out, which takes two clicks. Trying to leave gets you a retention discount
that ends with a loyalty fee.
## [1.3.0] — 2026-10-23

View file

@ -50,7 +50,7 @@ site/ everything that is deployed
robots.txt, sitemap.xml, llms.txt, 404.html, CNAME
scripts/build.sh copies site/ to _site/ and stamps __VERSION__ / __BUILD_DATE__
tests/ node:test + jsdom
.github/workflows/ ci.yml (every push) and release.yml (Pages deploy)
.github/workflows/ ci.yml (pushes to main and PRs) and release.yml (Pages deploy)
```
## Releasing
@ -65,13 +65,18 @@ Only published releases reach [seriesoftub.es](https://seriesoftub.es). Pushes t
3. Publish a GitHub release tagged `v<version>`, e.g. `gh release create v1.1.0 --generate-notes`.
The release workflow checks that the tag matches `package.json`, runs the tests,
builds, deploys to GitHub Pages and pings IndexNow. Pre-releases never deploy.
builds, deploys to GitHub Pages and pings IndexNow. It refuses to build when the
CHANGELOG has no `## [<version>]` section (rename `[Unreleased]` first).
Pre-releases never deploy, also not when run by hand, and a version older than
the live one is refused unless you tick `allow_older` (a deliberate rollback).
To redeploy an existing release, run the workflow manually with its tag.
## Hosting setup
GitHub Pages serves the site with **Source: GitHub Actions** and the custom domain
`seriesoftub.es`. DNS for the apex domain:
`seriesoftub.es`. Releases deploy from tags, so in **Settings → Environments →
github-pages → Deployment branches and tags**, add a tag rule for `v*` (by default
only the default branch may deploy). DNS for the apex domain:
```
seriesoftub.es. A 185.199.108.153

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "seriesoftubes",
"version": "1.2.0",
"version": "1.10.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "seriesoftubes",
"version": "1.2.0",
"version": "1.10.0",
"devDependencies": {
"jsdom": "24.1.3"
},

View file

@ -1,12 +1,12 @@
{
"name": "seriesoftubes",
"version": "1.3.0",
"version": "1.10.0",
"description": "A cartoon browser game about building the internet.",
"private": true,
"homepage": "https://seriesoftub.es/",
"repository": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" },
"scripts": {
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js",
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js",
"build": "bash scripts/build.sh",
"serve": "npm run build && npx --yes serve@14.2.4 _site"
},

View file

@ -1,15 +1,22 @@
#!/usr/bin/env bash
# Builds the deployable site into _site/: copies site/ and stamps the version
# (from package.json) and the build date into the pages that carry them.
# Builds the deployable site into _site/ (or $OUT): copies site/ and stamps the
# version (from package.json) and the build date into the pages that carry them.
# Set REQUIRE_NOTES=1 to fail when CHANGELOG.md has no bullets for this version.
set -euo pipefail
cd "$(dirname "$0")/.."
VERSION="${VERSION:-$(node -p "require('./package.json').version")}"
BUILD_DATE="${BUILD_DATE:-$(date -u +%Y-%m-%d)}"
OUT="${OUT:-_site}"
rm -rf _site
cp -R site _site
for f in _site/index.html _site/sitemap.xml _site/llms.txt; do
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$ ]]; then
echo "error: VERSION '$VERSION' is not a semantic version" >&2
exit 1
fi
rm -rf "$OUT"
cp -R site "$OUT"
for f in "$OUT/index.html" "$OUT/sitemap.xml" "$OUT/llms.txt"; do
sed -i.bak -e "s/__VERSION__/${VERSION}/g" -e "s/__BUILD_DATE__/${BUILD_DATE}/g" "$f"
rm -f "$f.bak"
done
@ -17,15 +24,21 @@ done
# Release notes for this version, baked into the page ("What's new") and
# published as version.json so open games can spot a newer release.
NOTES="$(node scripts/release-notes.js "$VERSION")"
node -e '
const fs=require("fs"),[,v,d,notes]=process.argv;
const f="_site/index.html";
fs.writeFileSync(f,fs.readFileSync(f,"utf8").replace("/*__RELEASE_NOTES__*/[]",notes));
fs.writeFileSync("_site/version.json",JSON.stringify({version:v,date:d,notes:JSON.parse(notes)},null,2)+"\n");
' "$VERSION" "$BUILD_DATE" "$NOTES"
if grep -rl "__VERSION__\|__BUILD_DATE__" _site >/dev/null; then
echo "error: unreplaced placeholders left in _site" >&2
if [ "${REQUIRE_NOTES:-}" = "1" ] && [ "$NOTES" = "[]" ]; then
echo "error: CHANGELOG.md has no '## [$VERSION]' section with bullets (still under [Unreleased]?)" >&2
exit 1
fi
echo "Built Series of Tubes ${VERSION} (${BUILD_DATE}) into _site/"
node -e '
const fs=require("fs"),[,out,v,d,notes]=process.argv;
const f=out+"/index.html",ph="/*__RELEASE_NOTES__*/[]",html=fs.readFileSync(f,"utf8");
if(!html.includes(ph)){console.error("error: release-notes placeholder missing from index.html");process.exit(1);}
// Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the <script>.
fs.writeFileSync(f,html.replace(ph,()=>notes.replace(/</g,"\\u003c")));
fs.writeFileSync(out+"/version.json",JSON.stringify({version:v,date:d,notes:JSON.parse(notes)},null,2)+"\n");
' "$OUT" "$VERSION" "$BUILD_DATE" "$NOTES"
if grep -rl "__VERSION__\|__BUILD_DATE__" "$OUT" >/dev/null; then
echo "error: unreplaced placeholders left in $OUT" >&2
exit 1
fi
echo "Built Series of Tubes ${VERSION} (${BUILD_DATE}) into ${OUT}/"

BIN
site/gulf2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

BIN
site/hud1280.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

BIN
site/hud900.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

BIN
site/in.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 KiB

File diff suppressed because one or more lines are too long

BIN
site/menu.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB

BIN
site/sa.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 309 KiB

BIN
site/tw.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 317 KiB

BIN
site/uae.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

BIN
site/za.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

View file

@ -4,22 +4,23 @@ const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-'));
const root = path.join(__dirname, '..');
test('build stamps version and date into the site', () => {
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, VERSION: '9.9.9', BUILD_DATE: '2030-01-01' } });
const html = fs.readFileSync(path.join(root, '_site', 'index.html'), 'utf8');
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '9.9.9', BUILD_DATE: '2030-01-01' } });
const html = fs.readFileSync(path.join(OUT, 'index.html'), 'utf8');
assert.match(html, /const APP_VERSION='9\.9\.9'/);
assert.match(html, /"softwareVersion": "9\.9\.9"/);
assert.match(fs.readFileSync(path.join(root, '_site', 'sitemap.xml'), 'utf8'), /<lastmod>2030-01-01<\/lastmod>/);
assert.match(fs.readFileSync(path.join(OUT, 'sitemap.xml'), 'utf8'), /<lastmod>2030-01-01<\/lastmod>/);
for (const f of ['favicon.svg', 'favicon.ico', 'apple-touch-icon.png', 'icon-192.png', 'icon-512.png', 'site.webmanifest', 'robots.txt', 'images/og-image.png', '404.html', 'CNAME', 'version.json']) {
assert.ok(fs.existsSync(path.join(root, '_site', f)), `${f} is shipped`);
assert.ok(fs.existsSync(path.join(OUT, f)), `${f} is shipped`);
}
});
test('version.json carries the release notes from the changelog', () => {
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, VERSION: '1.0.0', BUILD_DATE: '2026-10-23' } });
const v = JSON.parse(fs.readFileSync(path.join(root, '_site', 'version.json'), 'utf8'));
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.0.0', BUILD_DATE: '2026-10-23' } });
const v = JSON.parse(fs.readFileSync(path.join(OUT, 'version.json'), 'utf8'));
assert.equal(v.version, '1.0.0');
assert.ok(v.notes.length >= 5);
assert.ok(v.notes.every((n) => !n.startsWith('-')));
@ -34,3 +35,8 @@ test('head carries the SEO and social metadata', () => {
JSON.parse(block.replace(/<\/?script[^>]*>/g, ''));
}
});
test('a release build refuses to ship without release notes', () => {
assert.throws(() => execFileSync('bash', ['scripts/build.sh'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '9.9.9', REQUIRE_NOTES: '1' } }));
assert.throws(() => execFileSync('bash', ['scripts/build.sh'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.0; rm -rf /' } }), 'junk versions are rejected');
});

View file

@ -25,7 +25,7 @@ test('a year of scripted play stays healthy', () => {
const { ev, errors } = load();
seed(ev, 7);
ev("ACT.start({})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1});ACT.rs({city:'fra'})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'})");
ev("UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});ACT.launchBB({city:'ams'})");
for (let d = 0; d < 360; d++) {
ev('dayTick()');
@ -43,7 +43,7 @@ test('every incident and event type fires and clears cleanly', () => {
seed(ev, 3);
ev("ACT.start({});S.cash=1e8;S.lvl=4;S.day=100");
ev("for(const c of ['ams','lon','nyc','mos','mnl'])ACT.buildPop({city:c})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1});ACT.rs({city:'fra'})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'})");
ev("UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});UI.via='grace';openLinkModal('nyc','lon');ACT.buildLink({tier:1});closeModal()");
ev("UI.pending={a:'fra',b:'ams'};UI.lmode='df';UI.dfSys='roadm';ACT.orderDf();UI.lmode='wave';S.pops.fra.rgen=2;S.pops.ams.rgen=2");
ev("const df=S.links.find(l=>l.kind==='df');ACT.addCh({id:df.id,o:'zr4'});df.ready=S.day");
@ -97,11 +97,11 @@ test('saves never resurrect a bankrupt game', () => {
test('LAGs add members, capacity and cost to transit, IX ports and PNIs', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e7;S.lvl=4;S.pops.fra.rgen=2;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1})");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true})");
ev("const t=S.transit[0];window.__c0=S.cash;ACT.lagT({id:t.id,d:1});ACT.lagT({id:t.id,d:1});ACT.lagIx({city:'fra',d:1});compute()");
assert.equal(ev('S.transit[0].n'), 3);
assert.equal(ev("S.ixn.fra"), 2);
assert.equal(ev("__c0-S.cash"), 1500 * 2 + 1500, 'two transit members and one IX member were charged');
assert.equal(ev("__c0-S.cash"), 1500 * 2 + ev("ixPortMo('fra',1)"), 'two transit members and one IX member were charged');
assert.equal(ev("ixCap('fra')"), 190);
assert.equal(ev("R.cost.transit>0"), true);
ev("ACT.buyTransit({city:'fra',net:'cog',tier:2})");

View file

@ -20,17 +20,35 @@ function load(opts = {}) {
virtualConsole: vc,
beforeParse(window) {
window.__TUBES_TEST__ = true;
// Seed before the game script runs, so nothing random happens at load time either.
if (opts.seed !== false) { let r = opts.seed || 12345; window.Math.random = () => { r = (r * 16807) % 2147483647; return r / 2147483647; }; window.__reseed = (n) => { r = n; }; }
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
window.Path2D = class { moveTo() {} quadraticCurveTo() {} closePath() {} };
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
const fake = () => { const calls = { n: 0 };
const grad = { addColorStop() {} };
return new Proxy({ calls }, { get(t, k) {
if (k in t) return t[k];
if (k === 'measureText') return (s) => ({ width: String(s).length * 7 });
if (k === 'createLinearGradient' || k === 'createRadialGradient' || k === 'createPattern') return () => grad;
if (k === 'getImageData') return () => ({ data: new Uint8ClampedArray(4) });
if (k === 'canvas') return null;
return (...a) => { calls.n++; };
}, set(t, k, v) { t[k] = v; return true; } }); };
window.HTMLCanvasElement.prototype.getContext = function () { return this.__ctx || (this.__ctx = fake()); };
window.HTMLCanvasElement.prototype.toDataURL = () => 'data:image/png;base64,';
window.HTMLCanvasElement.prototype.toBlob = (cb) => cb(null);
},
});
const ev = (src) => dom.window.eval(src);
// Deterministic by default so a test never passes or fails by luck; pass {seed:false} to opt out.
// (Seeded in beforeParse, so the game's own seeded-games wrapper around Math.random stays in place.)
return { dom, ev, errors };
}
// Deterministic Math.random so failures are reproducible.
function seed(ev, n) {
ev(`Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`);
ev(`if(window.__reseed)__reseed(${n});else Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`);
}
module.exports = { load, seed };

193
tests/issues.test.js Normal file
View file

@ -0,0 +1,193 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function base(ev) {
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
}
test('#4 several transits in one city share the load instead of filling one by one', () => {
const { ev, errors } = load();
base(ev);
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()");
const u = JSON.parse(ev("JSON.stringify(S.transit.map(t=>R.useT[t.id]||0))"));
assert.equal(u.length, 2);
assert.ok(u[0] > 0 && u[1] > 0, `both carry traffic (${u})`);
assert.ok(Math.abs(u[0] - u[1]) / (u[0] + u[1]) < 0.35, `roughly balanced (${u})`);
// local exits still win over far ones: a transit in London is not used while Frankfurt has room
ev("ACT.buildPop({city:'lon'});UI.via=null;openLinkModal('fra','lon');ACT.buildLink({tier:3});closeModal();ACT.buyTransit({city:'lon',net:'tly',tier:1});compute()");
assert.equal(ev("R.useT[S.transit.find(t=>t.city==='lon').id]||0"), 0, 'remote transit stays idle');
// backup-only still means backup only
ev("S.transit[1].pref='low';compute()");
assert.equal(ev("R.useT[S.transit[1].id]||0"), 0);
assert.deepEqual(errors, []);
});
test('#5 export writes a file and import restores it, with checks', () => {
const { ev, dom, errors } = load();
const window = dom.window;
base(ev);
ev("S.name='Export Me';S.cash=1234567;compute()");
let blobText = null;
window.URL.createObjectURL = b => { blobText = b; return 'blob:x'; };
window.URL.revokeObjectURL = () => {};
window.HTMLAnchorElement.prototype.click = function () { window.__dl = this.download; };
ev("ACT.exportSave()");
assert.match(window.__dl, /^series-of-tubes-export-me-\d{4}-\d\d-\d\d\.json$/);
const txt = ev("JSON.stringify({app:'series-of-tubes',version:APP_VERSION,S})");
assert.ok(blobText);
ev("S.cash=1;S.name='Other'");
assert.match(ev(`parseSave('{"nope":1}').err`), /does not look/);
assert.match(ev(`parseSave('not json').err`), /not valid JSON/);
assert.match(ev(`parseSave(JSON.stringify(Object.assign(JSON.parse(${JSON.stringify(txt)}).S,{lost:true}))).err`), /bankrupt/);
ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`);
assert.equal(ev("S.name"), 'Export Me');
assert.equal(ev("S.cash"), 1234567);
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).name"), 'Export Me', 'saved on this device');
ev("showHelp()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Export save.*Import a save/);
assert.deepEqual(errors, []);
});
test('#6 full transit, IX, caches and routers show up in the NOC and on the map', () => {
const { ev, errors } = load();
base(ev);
ev("S.pops.fra.bb.d=5000;ACT.buyTransit({city:'fra',net:'cog',tier:0});ACT.buyIx({city:'ams',tier:0,signed:true});S.caches.push({id:'cx',city:'fra',net:'akm'});compute()");
ev("R.nodeLoad.fra=R.nodeCap.fra;UI.hotMap=hotByCity()");
const ks = JSON.parse(ev("JSON.stringify(hotPorts().map(h=>h.k))"));
for (const k of ['t', 'c', 'r']) assert.ok(ks.includes(k), `${k} is reported hot (${ks})`);
assert.ok(ev("UI.hotMap.fra&&UI.hotMap.fra.t>=0.9"));
ev("ACT.leftTab({t:'noc'})"); // NOC reads R as it is now (router forced hot above)
const noc = ev("document.getElementById('leftBody')?document.getElementById('leftBody').textContent:document.body.textContent");
assert.match(noc, /running hot/);
assert.match(noc, /Akamaybe Box cache/);
assert.match(noc, /transit/);
ev("draw&&draw(performance.now())");
assert.deepEqual(errors, []);
});
test('some routers take forever to boot, PacketOinkers most of all', () => {
const { ev, errors } = load();
base(ev);
const pct = JSON.parse(ev("JSON.stringify(RG.map((G,g)=>{let n=0;for(const c of ALLC){S.pops[c]=S.pops[c]||{rgen:g,routers:1};S.pops[c].rgen=g;if(slowBoot(c))n++;}return n/ALLC.length;}))"));
assert.ok(pct[0] < pct[2] && pct[2] > 0.2 && pct[0] < 0.3, `bigger chassis are slow more often (${pct})`);
assert.match(ev("RG[2].chip"), /PacketOinker/);
// find a slow and a fast POP and crash them
ev("for(const c of ALLC)if(c!=='fra')delete S.pops[c];S.pops.fra.rgen=2;S.pops.fra.routers=1");
const slowCity = ev("ALLC.find(c=>{S.pops[c]={rgen:2,routers:1,down:0};const s=slowBoot(c);if(!s)delete S.pops[c];return s;})");
ev(`for(const c of Object.keys(S.pops))if(c!=='${slowCity}')delete S.pops[c];S.transit=[];S.ixp={};for(let i=0;i<800&&!S.inc.some(x=>x.type==='crash');i++){fireFailure();S.inc=S.inc.filter(x=>x.type==='crash');}`);
const inc = JSON.parse(ev("JSON.stringify(S.inc.find(i=>i.type==='crash'))"));
assert.ok(inc.slow, 'crash on a slow booter is flagged');
assert.ok(inc.until - ev('S.day') >= 4, 'and lasts longer');
ev(`S.cash=1e6;ACT.fixInc({id:'${inc.id}'})`);
assert.equal(ev(`S.inc.find(i=>i.id==='${inc.id}').until`), ev('S.day+1'), 'rushing it still takes a day');
ev(`selectCity('${slowCity}');ACT.tab({t:'infra'})`);
assert.match(ev("document.getElementById('panelBody').textContent"), /a slow one/);
assert.deepEqual(errors, []);
});
test('the network name opens a menu with save, load and start over', () => {
const { ev, errors } = load();
base(ev);
ev("document.querySelector('[data-act=menu]').click()");
const t = ev("document.getElementById('modalCard').textContent");
for (const w of ['Export save', 'Import a save', 'Start a new network', 'Back to the map']) assert.ok(t.includes(w), w);
ev("document.querySelector('#modalCard [data-act=resetAsk]').click()");
assert.match(ev("document.getElementById('modalCard').textContent"), /cannot be undone/);
ev("document.querySelector('#modalCard [data-act=newgame]').click()");
assert.equal(ev("!!localStorage.getItem('sot-save-v1')&&JSON.parse(localStorage.getItem('sot-save-v1')).day>0"), false);
assert.deepEqual(errors, []);
});
test('a rare global outage shows a banner, dents traffic and only happens once', () => {
const { ev, errors } = load();
base(ev);
ev("compute()");const before = ev("R.demand");
ev("elephant();compute();renderAll()");
assert.ok(ev("R.demand") < before * 0.8);
assert.equal(ev("document.getElementById('mega').hidden"), false);
for (let i = 0; i < 5; i++) ev("dayTick()");
ev("renderAll()");
assert.equal(ev("document.getElementById('mega').hidden"), true);
assert.equal(ev("S.phpDone"), true);
assert.deepEqual(errors, []);
});
test('badges unlock with a rarity, persist across games, and secret ones stay hidden', () => {
const { ev, errors } = load();
base(ev);
ev("localStorage.removeItem('sot-badges');S.ach={};compute();checkGoals();ACT.leftTab({t:'goals'})");
let txt = ev("document.body.textContent");
assert.match(txt, /Badges/);
assert.match(txt, /\?\?\?/, 'secret badges are hidden');
ev("ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute();checkGoals()");
assert.ok(ev("S.ach.hello!==undefined"), 'first peering badge');
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-badges')).hello"), 'remembered across games');
ev("S.stats.sharks=3;checkGoals()");
assert.ok(ev("S.ach.bait!==undefined&&S.ach.shark!==undefined"));
ev("ACT.leftTab({t:'goals'})");
txt = ev("document.body.textContent");
assert.match(txt, /Legendary/);
assert.equal(ev("GOALS.some(g=>g.id==='gi')&&GOALS.some(g=>g.id==='t10')"), true);
assert.equal(ev("document.getElementById('hBank').className"), 'badge');
assert.deepEqual(errors, []);
});
test('Auto-TE spills overflow onto an alternate path when the shortest one is full', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("for(const c of ['ams','lon','par'])ACT.buildPop({city:c});const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',0);L('ams','lon',1,'uly');L('fra','par',1);L('par','lon',1,'chn');ACT.buyTransit({city:'lon',net:'lvl',tier:1});compute()");
const dem = ev("R.demand");
assert.ok(ev("R.served") < dem - 1, 'without TE the 10G link caps it');
ev("ACT.buyTE();compute()");
assert.ok(ev("R.served") > dem * 0.97, 'with TE nearly everything is served');
assert.ok(ev("R.teMoved") > 1);
assert.ok(ev("R.load[S.links.find(l=>l.a==='fra'&&l.b==='par').id]") > 1, 'the Paris path carries the overflow');
ev("ACT.leftTab({t:'noc'})");
assert.match(ev("document.body.textContent"), /Auto-TE/);
ev("ACT.teToggle();compute()");
assert.ok(ev("R.served") < dem - 1, 'switching it off goes back to shortest path only');
assert.deepEqual(errors, []);
});
test('rare badges hook into incidents and deals', () => {
const { ev, errors } = load();
base(ev);
ev("addInc({type:'cut',ref:'x',until:S.day+1,msg:'A crocodile took a bite. A ship dragged its anchor.'});checkGoals()");
assert.ok(ev("S.ach.croc!==undefined&&S.ach.anchor!==undefined&&S.ach.backhoe!==undefined"));
ev("S.stats.survived=100;checkGoals()");
assert.ok(ev("S.ach.unbreak!==undefined"));
assert.equal(ev("BADGES.length>=46&&new Set(BADGES.map(b=>b.id)).size===BADGES.length"), true);
assert.deepEqual(errors, []);
});
test('#7 NOC legend, sortable network table and transit destinations', () => {
const { ev, errors } = load();
base(ev);
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();ACT.dash()");
let t = ev("document.getElementById('dashCard').textContent");
assert.match(t, /Who your transit carries/);
assert.match(t, /IX peering/, 'legend explains the colours');
const top = JSON.parse(ev("JSON.stringify(transitTop(S.transit.map(t=>t.id),3))"));
assert.ok(top.length > 0 && top[0][1] > 0);
assert.equal(ev(`typeof offTransitHint('${top[0][0]}','fra')`), 'string');
ev("ACT.dashSort({k:'cost'})");
assert.equal(ev("UI.dashSort"), 'cost');
ev("ACT.dashSort({k:'cost'})");
assert.equal(ev("UI.dashDir"), 1, 'second tap flips the order');
ev("selectCity('fra');ACT.tab({t:'up'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Top destinations on this port/);
assert.deepEqual(errors, []);
});
test('#11 pausing freezes the dots on the links', () => {
const { ev, errors } = load();
base(ev);
ev("ACT.animSet({v:'on'});UI.speed=1;last=1000;frame(1016)");
const t0 = ev("animT");
ev("UI.speed=0;frame(1100);frame(1400)");
assert.equal(ev("animT"), t0, 'clock stands still while paused');
ev("UI.speed=1;frame(1416)");
assert.ok(ev("animT") > t0, 'and moves again on play');
assert.deepEqual(errors, []);
});

170
tests/modes.test.js Normal file
View file

@ -0,0 +1,170 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('sandbox: endless money, every unlock, nothing breaks, no badges', () => {
const { ev, errors } = load();
ev("ACT.modeSet({m:'sandbox'});ACT.start({})");
assert.equal(ev("S.mode"), 'sandbox');
assert.equal(ev("S.lvl"), 4);
ev("S.cash=5;for(let i=0;i<120;i++)dayTick()");
assert.ok(ev("S.cash") >= 1e8, 'money refills');
assert.equal(ev("S.stats.incidents"), 0, 'no failures');
assert.equal(ev("Object.keys(S.ach||{}).length"), 0, 'no badges in sandbox');
assert.match(ev("document.getElementById('hAsn').textContent"), /Sandbox/);
assert.deepEqual(errors, []);
});
test('scenarios: rules apply, goals complete, deadlines fail, seeds repeat', () => {
const { ev, errors } = load();
ev("ACT.scenarios()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Weekly challenge/);
ev("ACT.startScn({id:'stg'})");
assert.equal(ev("S.home"), 'stg');
ev("ACT.buyTransit({city:'stg',net:'drz',tier:1})");
assert.equal(ev("S.transit.length"), 0, 'no transit in the Spätzle-IX scenario');
ev("ACT.startScn({id:'redsea',sure:1})");
assert.equal(ev("cablesOk('mrs','sin').length"), 0, 'Red Sea routes are gone');
assert.ok(ev("cablesFor('mrs','sin').length") > 0);
ev("ACT.startScn({id:'carnaval',sure:1})");
assert.ok(ev("S.biz.some(b=>b.type==='event'&&b.start===90)"), 'Carnaval is pre-booked');
ev("S.day=99;S.scn.done=0;dayTick()");
assert.ok(ev("!!S.scn.failed"), 'deadline passes');
assert.match(ev("document.getElementById('modalCard').textContent"), /Time's up/);
// weekly: same seed gives the same first random numbers
ev("ACT.startWeekly({sure:1})");const a = ev("[Math.random(),Math.random()].join()");
ev("ACT.startWeekly({sure:1})");const b = ev("[Math.random(),Math.random()].join()");
assert.equal(a, b);
ev("S.stats.peak=1234;S.day=364;dayTick()");
assert.match(ev("document.getElementById('modalCard').textContent"), /score/i);
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-scn')).weekly"));
assert.deepEqual(errors, []);
});
test('completing a scenario records it and unlocks a badge', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-scn');ACT.startScn({id:'spat'});R.reach=1;R.served=200;scnTick(10)");
assert.equal(ev("S.scn.done"), 10);
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-scn')).spat"));
ev("checkBadges()");
assert.ok(ev("S.ach.scen1!==undefined"));
assert.deepEqual(errors, []);
});
test('traceroute shows hops, the exit and the AS path', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'ams',net:'lvl',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute()");
let r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'nfx'}))"));
assert.match(r.text, /traceroute to/);
assert.match(r.text, /ams/, 'goes via Amsterdam to transit');
assert.deepEqual(r.asPath.slice(0, 2), [ev('S.asn'), ev("NET.lvl.asn")]);
r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'akm'}))"));
assert.match(r.why, /peering/i, 'open network over the IX route server');
r = JSON.parse(ev("JSON.stringify(traceroute('ams',{city:'fra'}))"));
assert.match(r.text, /fra/);
ev("S.links[0].cut=S.day+3;compute()");
r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'nfx'}))"));
assert.ok(/unreachable/.test(r.text) || /peering/i.test(r.why));
ev("ACT.trace({city:'fra'})");
assert.match(ev("document.getElementById('modalCard').textContent"), /Traceroute/);
ev("ACT.share()");
assert.deepEqual(errors, []);
});
test('conferences: register, attend, and selective peers get easier for a while', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0");
ev("S.day=confDay(CONFS.find(c=>c.c==='fra'),0)-20;ACT.leftTab({t:'deals'})");
assert.match(ev("document.body.textContent"), /DENOG-ish/);
const key = ev("upcomingConfs(30).find(c=>c.c==='fra').key");
ev(`ACT.confGo({key:'${key}'})`);
const need0 = ev("(()=>{R.demTo.nfx=0;return peerOk('nfx','ix','fra').why})()");
ev("for(let i=0;i<21;i++)dayTick()");
assert.ok(ev("S.conf&&S.conf.until>S.day"), 'conference glow is on');
const need1 = ev("(()=>{R.demTo.nfx=0;return peerOk('nfx','ix','fra').why})()");
assert.notEqual(need0, need1, 'threshold dropped');
ev("checkGoals()");
assert.ok(ev("S.ach.hallway!==undefined"));
assert.deepEqual(errors, []);
});
test('the guided tutorial walks through the first steps and can be skipped', () => {
const { ev, dom, errors } = load();
dom.window.__TUBES_TUT__ = true;
ev("localStorage.removeItem('sot-tut');ACT.start({})");
assert.equal(ev("document.getElementById('coach').hidden"), false);
assert.match(ev("document.getElementById('coach').textContent"), /Launch broadband/);
ev("ACT.launchBB({city:S.home});renderAll()");
assert.match(ev("document.getElementById('coach').textContent"), /Step 2/);
ev("ACT.tutSkip()");
assert.equal(ev("document.getElementById('coach').hidden"), true);
assert.equal(ev("localStorage.getItem('sot-tut')"), '1');
assert.deepEqual(errors, []);
});
test('animations can be switched off, on or follow the system, and the choice sticks', () => {
const { ev, errors } = load();
ev("ACT.start({});ACT.menu()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Animations/);
ev("ACT.animSet({v:'off'})");
assert.equal(ev("document.documentElement.classList.contains('no-anim')"), true);
assert.equal(ev("animOn()"), false);
ev("floater(0,0,'x','#000')");
assert.equal(ev("FLOATS.length"), 0, 'no floating text when off');
assert.equal(ev("localStorage.getItem('sot-anim')"), 'off');
ev("ACT.animSet({v:'on'})");
assert.equal(ev("document.documentElement.classList.contains('anim-force')"), true);
assert.equal(ev("animOn()"), true);
ev("ACT.soundSet({v:'off'})");
assert.equal(ev("UI.muted"), true);
assert.deepEqual(errors, []);
});
test('half speed and deeper zoom', () => {
const { ev, errors } = load();
ev("ACT.start({});ACT.speed({v:0.5})");
assert.equal(ev("UI.speed"), 0.5);
assert.equal(ev("document.getElementById('sp0.5').classList.contains('on')"), true);
ev("ACT.speed({v:7})");
assert.equal(ev("UI.speed"), 0.5, 'bogus speeds are ignored');
ev("cam.z=1;for(let i=0;i<40;i++)zoomAt(100,100,1.2)");
assert.equal(ev("cam.z"), 6);
assert.deepEqual(errors, []);
});
test('the map draws at every zoom, with and without animations, without throwing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;ACT.launchBB({city:'fra'});for(const c of ['ams','lon','nyc'])ACT.buildPop({city:c});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();compute()");
for (const z of [0.35, 0.8, 1.4, 3, 6]) ev(`cam.z=${z};draw(performance.now());draw(0)`);
ev("ACT.animSet({v:'off'});frame(performance.now()+16)");
assert.ok(ev("ctx&&ctx.calls.n") > 100, 'the canvas was actually drawn on');
assert.deepEqual(errors, []);
});
test('RouteScript: parses safely, reports errors helpfully, and changes routing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.buyTE();compute()");
let p = JSON.parse(ev("JSON.stringify(teParse('spill at 80%\\ncap transit cogentle at 3 gbps\\nprefer ix for goggle\\nnonsense here\\navoid transit for gogle'))"));
assert.equal(p.errors.length, 2, 'the nonsense line and the typo fail');
assert.match(p.errors[1], /Did you mean Goggle/, 'typos get a suggestion');
p = JSON.parse(ev("JSON.stringify(teParse('avoid transit for zzzzqqq').errors)"));
assert.match(p[0], /unknown network/);
assert.match(ev("teParse('drain pariss').errors[0]"), /Did you mean Paris/);
assert.equal(ev("teParse('alert(1)').n"), 0, 'nothing is ever evaluated');
const cog = "R.useT[S.transit.find(t=>t.net==='cog').id]||0";
const before = ev(cog);
ev("ACT.teEdit();document.getElementById('teSrc').value='cap transit cogentle at 3 gbps';ACT.teDeploy()");
assert.ok(ev(cog) <= 3.0001 && before > 3, `Cogentle capped (${before} -> ${ev(cog)})`);
assert.ok(ev("R.useT[S.transit.find(t=>t.net==='lvl').id]") > 0, 'overflow went to the other upstream');
// a fat-fingered deploy earns its badge
ev("ACT.teEdit();document.getElementById('teSrc').value='drain frankfurt\\ncap transit level tree at 0 gbps\\ncap transit cogentle at 0 gbps';ACT.teDeploy();checkGoals()");
assert.ok(ev("S.ach.fat!==undefined"));
// errors block a deploy
ev("ACT.teEdit();document.getElementById('teSrc').value='spill at 5%';ACT.teDeploy()");
assert.match(ev("document.getElementById('modalCard').textContent"), /commit failed/);
ev("ACT.teClear()");
assert.equal(ev("S.te.script"), '');
assert.deepEqual(errors, []);
});

View file

@ -34,7 +34,7 @@ test('a snubbing peer tears down an existing session and the Request button expl
assert.ok(k, 'found a snub starting at an IX');
const [id, c, d] = k.split('@');
ev(`S.day=${d}`);
ev(`ACT.buildPop({city:'${c}'});ACT.buyIx({city:'${c}',tier:1});S.peers['${id}@${c}']=true;compute()`);
ev(`ACT.buildPop({city:'${c}'});ACT.buyIx({city:'${c}',tier:1,signed:true});S.peers['${id}@${c}']=true;compute()`);
assert.equal(ev(`ixSessions('${c}').has('${id}')`), true);
ev('dayTick()');
assert.equal(ev(`!!S.peers['${id}@${c}']`), false, 'session torn down');
@ -56,9 +56,9 @@ test('remote peering is offered but costs more, gives less and gets refused more
const txt = () => ev("document.getElementById('panelBody').textContent");
ev("ACT.buyIx({city:'ams',tier:1});compute()");
assert.equal(ev("isRemote('ams')"), true);
assert.equal(ev("ixPortMo('ams',1)"), ev("Math.round(PORT[1].ix*1.5)"), 'reseller markup');
assert.equal(ev("ixPortMo('ams',1)"), ev("Math.round(PORT[1].ix*1.5*ixMul('ams'))"), 'reseller markup');
assert.equal(ev("ixCap('ams')"), ev("PORT[1].g*0.8"), 'oversubscribed port');
const refusers = JSON.parse(ev("JSON.stringify(ixMembers('ams').filter(noRemote))"));
const refusers = JSON.parse(ev("JSON.stringify(ixMembers('ams').filter(id=>noRemote(id)&&!snub(id,'ams')))"));
assert.ok(refusers.length > 0, 'some members refuse remote peers');
const r = JSON.parse(ev(`JSON.stringify(peerOk('${refusers[0]}','ix','ams'))`));
assert.equal(r.ok, false); assert.equal(r.remote, true);
@ -73,60 +73,107 @@ test('remote peering is offered but costs more, gives less and gets refused more
assert.deepEqual(errors, []);
});
test('Amsterdam has a second IX, FRIES-IX, with free ports up to 400G', () => {
test('DE-KICKS hides prices, haggles, harmonises upwards, auto-enrolls add-ons and fights to keep you', () => {
const { ev, errors } = load();
setup(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(cityIxes('ams'))")), ['ams', 'ams:fries']);
ev("selectCity('fra');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Price on request/);
ev("ACT.buyIx({city:'fra',tier:1})");
assert.equal(ev("S.ixp.fra===undefined"), true, 'no port without signing');
assert.match(ev("document.getElementById('modalCard').textContent"), /Confidential/);
ev("S.dk.q.m=1.5;ACT.dkAccept()");
assert.equal(ev("S.ixp.fra"), 1);
assert.equal(ev("ixPortMo('fra',1)"), ev("Math.round(PORT[1].ix*1.5*ixMul('fra'))"));
// haggling always moves something
ev("S.dk.q={city:'mad',tier:1,m:1.5,h:0}");
for (let i = 0; i < 3; i++) ev("if(S.dk.q)ACT.dkHaggle()");
assert.ok(ev("!S.dk.q||S.dk.q.m!==1.5||S.dk.stall>S.day"));
// yearly harmonisation
const m0 = ev("S.dk.m.fra");
ev("let n=0;while(n++<400){S.day++;if((S.day+hstr('fra')%90)%365===0)break;}S.day--;dkTick(S.day+1)");
assert.ok(ev("S.dk.m.fra") > m0, 'price went up');
// add-ons show up on the invoice until you opt out (twice)
ev("S.dk.add.fra=[{n:'Route Server Gold',blurb:'gold',mo:500,day:S.day}]");
assert.equal(ev("dkAddonMo('fra')"), 500);
ev("selectCity('fra');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /auto-enrolled/);
ev("ACT.dkOptOut({city:'fra',n:'Route Server Gold'})");
assert.equal(ev("S.dk.add.fra.length"), 1, 'first click only asks');
ev("ACT.dkOptOut({city:'fra',n:'Route Server Gold'})");
assert.equal(ev("S.dk.add.fra.length"), 0);
// leaving: a retention offer first
ev("ACT.cancelIx({city:'fra'});ACT.cancelIx({city:'fra'})");
assert.match(ev("document.getElementById('modalCard').textContent"), /Before you go/);
const full = ev("ixPortMo('fra',1)");
ev("ACT.dkStay({city:'fra'})");
assert.ok(ev("ixPortMo('fra',1)") < full, 'promo price');
ev("ACT.cancelIx({city:'fra'});ACT.cancelIx({city:'fra'})");
assert.equal(ev("S.ixp.fra"), undefined, 'second time you can actually leave');
ev("ACT.buildPop({city:'ams'})");
assert.equal(ev("ixPortMo('ams',1)"), ev("Math.round(PORT[1].ix*ixMul('ams'))"), 'other IXs keep open pricing');
assert.deepEqual(errors, []);
});
test('Amsterdam has FRIES-IX, with free ports up to 400G', () => {
const { ev, errors } = load();
setup(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(ixIdsIn('ams'))")), ['ams', 'ams~2', 'ams~3']);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1;compute()");
const cash = () => ev('S.cash');
let c0 = cash();
ev("ACT.buyIx({city:'ams:fries',tier:2})");
assert.equal(ev("S.ixp['ams:fries']"), 2);
ev("ACT.buyIx({city:'ams~3',tier:2})");
assert.equal(ev("S.ixp['ams~3']"), 2);
assert.equal(cash(), c0, '400G port is free');
assert.equal(ev("S.ixp.ams"), undefined, 'HAMS-IX is separate');
c0 = cash();
ev("ACT.lagIx({city:'ams:fries',d:1})");
ev("ACT.lagIx({city:'ams~3',d:1})");
assert.equal(cash(), c0, 'LAG members are free too');
assert.equal(ev("ixPortMo('ams:fries',3)"), ev('PORT[3].ix'), '800G costs the usual price');
ev("ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams:fries'});compute()");
assert.ok(ev("ixSessions('ams:fries').has('drz')"));
assert.equal(ev("ixSessions('ams:fries').has('ggl')"), false, 'Goggle is not a member');
assert.equal(ev("R.useIx['ams:fries']!==undefined&&R.useIx.ams!==undefined"), true, 'both fabrics carry traffic');
assert.equal(ev("R.cost.ix"), ev("PORT[1].ix"), "only the HAMS-IX port is billed");
assert.equal(ev("ixPortMo('ams~3',3)"), ev("Math.round(PORT[3].ix*ixMul('ams~3'))"), '800G costs the usual price');
ev("ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams~3'});compute()");
assert.ok(ev("ixSessions('ams~3').has('drz')"));
assert.equal(ev("ixSessions('ams~3').has('ggl')"), false, 'Goggle is not a member');
assert.equal(ev("R.useIx['ams~3']!==undefined&&R.useIx.ams!==undefined"), true, 'both fabrics carry traffic');
assert.equal(ev("R.cost.ix"), ev("ixPortMo('ams',1)"), "only the HAMS-IX port is billed");
ev("selectCity('ams');ACT.tab({t:'peer'})");
const txt = ev("document.getElementById('panelBody').textContent");
assert.match(txt, /FRIES-IX/); assert.match(txt, /HAMS-IX/);
ev("S.ev.ixdown={'ams:fries':S.day+2};compute()");
assert.equal(ev("R.useIx['ams:fries']"), undefined, 'a FRIES-IX outage drops only that fabric');
assert.match(ev("ixBlock('ams~3',true)"), /LAG member <small>free/);
ev("save();restored=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));");
assert.equal(ev("restored.ixp['ams~3']"), 2, 'free port survives save migration');
assert.equal(ev("restored.ixn['ams~3']"), 2, 'free LAG survives save migration');
ev("S.ev.ixdown={'ams~3':S.day+2};compute()");
assert.equal(ev("R.useIx['ams~3']"), undefined, 'a FRIES-IX outage drops only that fabric');
assert.notEqual(ev("R.useIx.ams"), undefined);
ev("S.ev.ixdown={};compute()");
ev("ACT.cancelIx({city:'ams:fries'});ACT.cancelIx({city:'ams:fries'})");
assert.equal(ev("S.ixp['ams:fries']"), undefined);
ev("ACT.cancelIx({city:'ams~3'});ACT.cancelIx({city:'ams~3'})");
assert.equal(ev("S.ixp['ams~3']"), undefined);
assert.equal(ev("S.ixp.ams"), 1, 'leaving FRIES-IX keeps the HAMS-IX port');
assert.equal(ev("Object.keys(S.rs).filter(k=>S.rs[k]).length"), 0);
assert.deepEqual(errors, []);
});
test('second exchanges are wired up in every city that has one, and Barcelona has Catnip-IX', () => {
test('community exchanges are wired up in every city, and Barcelona has Catnip-IX', () => {
const { ev, errors } = load();
setup(ev);
const bad = ev("Object.keys(XIX).flatMap(k=>XIX[k].members.filter(id=>!NET[id]||!NET[id].pops.includes(XIX[k].city)).map(id=>k+':'+id)).join()");
const exchanges = ['ams~3', 'mad~2', 'fra~2', 'lon~2', 'nyc~3', 'jnb~2', 'syd~2', 'tok~2'];
const bad = ev("XIX.filter(x=>x.core).map(x=>x.id).flatMap(k=>XIXM[k].members.filter(id=>!NET[id]||!NET[id].pops.includes(XIXM[k].c)).map(id=>k+':'+id)).join()");
assert.equal(bad, '', 'every member has a POP in the city');
assert.ok(ev("Object.keys(XIX).every(k=>CITY[XIX[k].city].ix&&cityIxes(XIX[k].city).includes(k))"), 'each sits beside a main IX');
assert.equal(ev("ixPortMo('mad:paella',1)"), ev("Math.round(ixPortMo('mad',1)*0.6)"), 'Paella-NIX is cheaper than Siesta-IX');
assert.ok(ev("Object.keys(XIXM).every(k=>CITY[XIXM[k].c].ix&&ixIdsIn(XIXM[k].c).includes(k))"), 'each sits beside a main IX');
ev("ACT.buildPop({city:'mad'})");
assert.equal(ev("ixPortMo('mad~2',1)"), ev("Math.round(PORT[1].ix*0.6*IX_REG.EU)"), 'Paella-NIX is cheaper than Siesta-IX');
assert.equal(ev("ixName('bcn')"), 'Catnip-IX');
for (const k of JSON.parse(ev('JSON.stringify(Object.keys(XIX))'))) {
const c = k.split(':')[0];
for (const k of exchanges) {
const c = k.split('~')[0];
ev(`if(!S.pops.${c})ACT.buildPop({city:'${c}'});S.pops.${c}.rgen=RG.length-1;ACT.buyIx({city:'${k}',tier:1});ACT.rs({city:'${k}'})`);
assert.equal(ev(`S.ixp['${k}']`), 1, `port at ${k}`);
}
ev('compute()');
for (const k of JSON.parse(ev('JSON.stringify(Object.keys(XIX))')))
for (const k of exchanges)
assert.ok(ev(`ixSessions('${k}').size`) > 0, `route server sessions at ${k}`);
for (const c of ['ams', 'mad', 'fra', 'lon', 'nyc', 'jnb', 'syd', 'tok', 'bcn']) {
ev(`selectCity('${c}');ACT.tab({t:'peer'})`);
const txt = ev("document.getElementById('panelBody').textContent");
for (const k of JSON.parse(ev(`JSON.stringify(cityIxes('${c}'))`))) assert.ok(txt.includes(ev(`ixName('${k}')`)), `${k} shown in ${c}`);
for (const k of JSON.parse(ev(`JSON.stringify(ixIdsIn('${c}'))`))) assert.ok(txt.includes(ev(`ixName('${k}')`)), `${k} shown in ${c}`);
}
assert.deepEqual(errors, []);
});

View file

@ -4,6 +4,7 @@ const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { load } = require('./harness');
const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-'));
const root = path.join(__dirname, '..');
function playedGame() {
@ -31,8 +32,8 @@ test('leaving the page saves the game', () => {
test('returning players see what is new after an update, once', () => {
const { saved } = playedGame();
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } });
const file = path.join(root, '_site', 'index.html');
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } });
const file = path.join(OUT, 'index.html');
const b = load({ file, storage: { 'sot-save-v1': saved, 'sot-seen-version': '1.0.0' } });
const text = b.ev("document.getElementById('modalCard').textContent");
assert.match(text, /New in Series of Tubes 1\.1\.0/);

324
tests/regions.test.js Normal file
View file

@ -0,0 +1,324 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0"); }
test('new cities exist, sit on land and have sellers, cables and IX members', () => {
const { ev, errors } = load();
start(ev);
const ids = ['for', 'rio', 'bue', 'scl', 'lim', 'bog', 'pan', 'del', 'maa', 'blr', 'hyd', 'tpe', 'auh', 'fuj', 'cpt'];
for (const c of ids) {
assert.ok(ev(`!!CITY['${c}']`), c);
assert.ok(ev(`NETS.some(n=>n.price&&n.pops.includes('${c}'))`), `${c} has a transit seller`);
}
for (const c of ['for', 'rio', 'bue', 'scl', 'lim', 'bog', 'pan', 'maa', 'tpe', 'fuj', 'cpt'])
assert.ok(ev(`CABLE_PAIRS.some(p=>p.a==='${c}'||p.b==='${c}')`), `${c} has a cable`);
assert.ok(ev("ixMembers('sao').includes('clr')&&ixMembers('del').includes('jio')&&ixMembers('tpe').includes('cht')"));
assert.ok(ev("CABLE_PAIRS.some(p=>(p.a==='scl'&&p.b==='syd')||(p.a==='syd'&&p.b==='scl'))"), 'Humboldt-ish cable to Sydney');
assert.deepEqual(errors, []);
});
test('South America: no land route over the Darién Gap, the Andes cost double, IX.brrr is cheap', () => {
const { ev } = load();
start(ev);
assert.equal(ev("isSub('pan','bog')"), true, 'Panama to Bogotá is subsea');
assert.equal(ev("isSub('mia','sao')"), true);
assert.equal(ev("isSub('bue','sao')"), false);
assert.equal(ev("landMult('scl','bue')"), 2);
assert.equal(ev("landMult('bue','sao')"), 1);
assert.match(ev("landWhy('scl','bue')"), /Andes/);
assert.equal(ev("regionMult('sao')"), 1.6);
ev("ACT.buildPop({city:'sao'})");
assert.ok(ev("ixPortMo('sao',1)") < ev("PORT[1].ix*0.5"), 'nonprofit IX ports are cheap');
ev("selectCity('sao');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Run by a nonprofit/);
});
test('Brazilian POPs attract provedores', () => {
const { ev } = load();
start(ev);
ev("ACT.buildPop({city:'rio'})");
const seen = JSON.parse(ev("(()=>{const o=[];for(let i=0;i<300;i++){S.offers=[];spawnOffer();o.push(...S.offers.filter(x=>x.type==='provedor').map(x=>x.city));}return JSON.stringify(o)})()"));
assert.ok(seen.length > 0, 'provedor offers appear');
assert.ok(seen.every(c => c === 'rio'), 'only in Brazilian POPs');
});
test('UAE: duopoly fiber only, no dark fiber, free-zone license', () => {
const { ev, errors } = load();
start(ev);
assert.equal(ev("dfAllowed('dxb','auh')"), false);
assert.equal(ev("dfAllowed('dxb','bom')"), true);
assert.equal(ev("landMult('dxb','fuj')"), 3);
assert.equal(ev("popCost('auh')-popCost('fra')"), ev('UAE_LIC'));
ev("ACT.buildPop({city:'dxb'});UI.lmode='df';openLinkModal('dxb','auh')");
assert.match(ev("document.getElementById('modalCard').textContent"), /No dark fiber inside the UAE/);
ev("UI.lmode='wave';openLinkModal('dxb','auh')");
assert.match(ev("document.getElementById('modalCard').textContent"), /licensed operators/);
ev("closeModal()");
assert.deepEqual(errors, []);
});
test('regional incidents: Taiwan anchors, Andes landslides, load shedding', () => {
const { ev, errors } = load();
start(ev);
ev("for(const c of ['tpe','scl','bue','cpt'])ACT.buildPop({city:c})");
ev("UI.via=null;openLinkModal('tpe','hkg');ACT.buildLink({tier:1});closeModal()");
ev("UI.via='land';openLinkModal('scl','bue');ACT.buildLink({tier:1});closeModal()");
assert.ok(ev("S.links.some(l=>l.a==='tpe'&&l.sub)") && ev("S.links.some(l=>l.a==='scl'&&!l.sub)"), 'links built');
let anchors = 0, andes = 0, shed = 0;
for (let i = 0; i < 400; i++) {
ev("S.inc=[];for(const l of S.links)l.cut=0;for(const c in S.pops){S.pops[c].down=0;S.pops[c].gen=false}fireFailure()");
const m = ev("S.inc.map(x=>x.msg).join(' ')");
if (/anchor/.test(m) && /Taipei/.test(m)) anchors++;
if (/Andes|mountain pass|llama|4,000/.test(m)) andes++;
if (/Load shedding/.test(m)) shed++;
}
assert.ok(anchors > 0, 'anchors drag over Taiwan cables');
assert.ok(andes > 0, 'the Andes break fiber');
assert.ok(shed > 0, 'South Africa sheds load');
assert.deepEqual(errors, []);
});
test('every new city panel renders', () => {
const { ev, errors } = load();
start(ev);
for (const c of ['for', 'pan', 'del', 'tpe', 'auh', 'fuj', 'cpt', 'bog']) {
ev(`selectCity('${c}');for(const t of ['cust','up','peer','links','infra'])ACT.tab({t})`);
}
assert.deepEqual(errors, []);
});
test('Asia-Pacific and Eastern Europe POPs exist with sellers', () => {
const { ev } = load();
start(ev);
for (const c of ['mel', 'bne', 'drw', 'osa', 'kul', 'bkk', 'sgn', 'khi', 'dac', 'cbo', 'waw', 'prg', 'vie', 'bud', 'buh', 'tll', 'ist'])
assert.ok(ev(`!!CITY['${c}']&&NETS.some(n=>n.price&&n.pops.includes('${c}'))`), c);
assert.ok(ev("CABLE_PAIRS.some(p=>p.cid==='balt')&&CABLE_PAIRS.some(p=>p.cid==='darwin')&&CABLE_PAIRS.some(p=>p.cid==='smw4')"));
});
test('metro diversity: a second site keeps half the POP up and uplinks follow their site', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()");
const cap0 = ev("nodeCap('fra')");
ev("ACT.addSite({city:'fra'})");
assert.ok(ev("S.pops.fra.site2"));
ev("ACT.siteSet({k:'t',id:S.transit[1].id,s:'b'})");
assert.equal(ev("S.transit[1].site"), 'b');
// a power cut in site A: the POP stays up at half capacity, only site-B transit works
ev("addInc({type:'site',ref:'fra',site:'a',until:S.day+3,msg:'x',cost:0});compute()");
assert.equal(ev("popUp('fra')"), true);
assert.equal(ev("nodeCap('fra')"), cap0 / 2);
assert.equal(ev("R.useT[S.transit[0].id]||0"), 0, 'site A transit is dark');
assert.ok(ev("R.useT[S.transit[1].id]") > 0, 'site B transit carries traffic');
// the incident path also uses the second site
ev("S.inc=[];S.pops.fra.gen=false;for(let i=0;i<500&&!S.inc.some(x=>x.type==='site'||x.type==='ring');i++){fireFailure();S.inc=S.inc.filter(x=>x.type==='site'||x.type==='ring');for(const c in S.pops)S.pops[c].down=0;}");
assert.ok(ev("S.inc.some(x=>x.type==='site'||x.type==='ring')"), 'site outages and ring cuts happen');
ev("selectCity('fra');ACT.tab({t:'infra'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Metro diversity/);
ev("selectCity('fra');ACT.tab({t:'up'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Site:/);
assert.deepEqual(errors, []);
});
test('the giants ask for AI WANs, multi-site training, ingests and hundreds of fiber pairs', () => {
const { ev, errors } = load();
start(ev);
ev("for(const c of ['ash','dal','chi','nyc'])ACT.buildPop({city:c})");
ev("UI.pending={a:'chi',b:'ash'};UI.lmode='df';UI.dfSrc='build';UI.dfSys='roadm';ACT.orderDf();UI.lmode='wave';S.links.filter(l=>l.kind==='df').forEach(l=>l.ready=S.day)");
const seen = {};
for (let i = 0; i < 600; i++) { ev('S.offers=[];spawnOffer()'); for (const o of JSON.parse(ev("JSON.stringify(S.offers.filter(o=>o.mega).map(o=>({t:o.type,c:bCities(o),r:o.rate,bw:o.bw})))"))) seen[o.t] = o; }
for (const t of ['aiwan', 'mtrain', 'ingest', 'pairs']) assert.ok(seen[t], `${t} offers appear`);
assert.ok(seen.mtrain.c.length >= 3, 'training runs span several sites');
assert.ok(seen.aiwan.bw >= 3200);
// accept one and make sure it earns
ev("for(let i=0;i<400&&!S.offers.some(o=>o.type==='pairs');i++){S.offers=[];spawnOffer();}const o=S.offers.find(o=>o.type==='pairs');ACT.accept({id:o.id});compute()");
assert.ok(ev("S.biz.some(b=>b.type==='pairs')"));
assert.ok(ev("R.revMo") > 0);
ev("selectCity('dal')");
assert.match(ev("document.getElementById('panelBody').textContent+''"), /./);
ev("ACT.leftTab({t:'deals'})");
assert.deepEqual(errors, []);
});
test('#8 ports can be split across both buildings, so one dark site only halves them', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});ACT.addSite({city:'fra'});compute()");
const full = ev("ixCap('fra')");
const cash0 = ev("S.cash");
ev("ACT.siteSet({k:'ix',id:'fra',s:'ab'})");
assert.equal(ev("(S.ixn||{}).fra"), 2, 'choosing Both adds a second member');
assert.equal(ev("S.ixSite.fra"), 'ab');
assert.ok(ev("S.cash") < cash0, 'and charges for it');
const two = ev("ixCap('fra')");
ev("addInc({type:'site',ref:'fra',site:'a',until:S.day+3,msg:'x',cost:0});compute()");
assert.ok(ev("ixCap('fra')") > 0 && ev("ixCap('fra')") < two, 'site A dark: the IX port runs on its site-B half');
assert.ok(ev("R.useIx.fra||0") > 0, 'and still carries traffic');
ev("ACT.siteSet({k:'t',id:S.transit[0].id,s:'ab'});compute()");
assert.equal(ev("S.transit[0].n"), 2);
assert.ok(ev("R.useT[S.transit[0].id]||0") > 0, 'split transit survives the dark site');
ev("ACT.lagT({id:S.transit[0].id,d:-1})");
assert.equal(ev("S.transit[0].site"), 'a', 'one member left: back in one building');
ev("selectCity('fra');ACT.tab({t:'infra'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /split/);
assert.ok(full > 0);
assert.deepEqual(errors, []);
});
test('routers: wave and port sizes match what the box can actually take', () => {
const { ev } = load();
start(ev);
assert.equal(ev("LT.map(t=>t.n).join()"), '10G,100G,400G,800G,1.6T,6.4T');
assert.equal(ev("PORT[RG[3].maxP].n"), '1.6T', 'the 1.6T router has 1.6T ports');
assert.equal(ev("LT[RG[2].maxLT].n"), '800G', 'an 800G router stops at 800G waves');
assert.equal(ev("LT[RG[3].maxLT].n"), '6.4T');
// an old save with a 1.6T wave (old tier 3) keeps its 1.6T wave after migration
const old = ev("(()=>{const s=JSON.parse(JSON.stringify(S));delete s.ltv;s.links=[{id:'x',a:'fra',b:'ams',kind:'wave',tier:3,km:364,mo:1,cut:0}];s.pops.ams={day:0,routers:1};return JSON.stringify(s)})()");
assert.equal(ev(`LT[migrate(JSON.parse(${JSON.stringify(old)})).links[0].tier].n`), '1.6T');
});
test('London–Amsterdam: many cheap cables and dark fiber you can lease under the sea', () => {
const { ev, errors } = load();
start(ev);
assert.ok(ev("cablesFor('lon','ams').length") >= 4);
assert.equal(ev("dfAllowed('lon','ams')"), true);
assert.equal(ev("dfAllowed('lon','nyc')"), false, 'not on long subsea routes');
ev("ACT.buildPop({city:'lon'});ACT.buildPop({city:'ams'});UI.pending={a:'lon',b:'ams'};UI.lmode='df';UI.dfSrc='build';UI.dfSys='lite';ACT.orderDf();UI.lmode='wave'");
const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.kind==='df'))"));
assert.ok(l && l.sub && l.cable && !l.own, 'a subsea IRU, never self-built');
assert.deepEqual(errors, []);
});
test('#10 your own IX fabric can be upgraded, and grows', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.buildPop({city:'mex'});ACT.foundIx({city:'mex'});compute()");
assert.equal(ev("ixCap('mex')"), 400);
ev("ACT.myIxUp({city:'mex'});compute()");
assert.equal(ev("ixCap('mex')"), 1600);
assert.equal(ev("myFab('mex').max"), 20);
ev("selectCity('mex');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Your own fabric · 1.6T/);
assert.deepEqual(errors, []);
});
test('wave prices follow regional markets and fall over time', () => {
const { ev } = load();
start(ev);
const eu = ev("waveMarket('fra','ams',false).reg"), us = ev("waveMarket('nyc','ash',false).reg"), af = ev("waveMarket('lon','lag',true).reg");
assert.ok(eu < us && us < af, `Europe ${eu} < US ${us} < Africa ${af}`);
const m0 = ev("waveMarket('fra','ams',false).m");
ev("S.day=720");
assert.ok(ev("waveMarket('fra','ams',false).m") < m0, 'two years later it is cheaper');
assert.ok(ev("cablesFor('cai','dxb').length") > 0, 'Cairo–Dubai over the Red Sea');
assert.match(ev("marketNote('fra','ams',false)"), /Europe/);
});
test('the Gulf: Saudi licences, and a spat that cuts Qatar off from its neighbours', () => {
const { ev, errors } = load();
start(ev);
assert.equal(ev("popCost('ruh')-popCost('fra')"), ev('KSA_LIC'));
ev("ACT.buildPop({city:'doh'});ACT.buildPop({city:'ruh'});UI.via='land';openLinkModal('doh','ruh');ACT.buildLink({tier:1});closeModal()");
const l = "S.links.find(l=>[l.a,l.b].includes('doh'))";
assert.equal(ev(`linkDown(${l})`), false);
ev("S.ev.gulf=S.day+60");
assert.equal(ev(`linkDown(${l})`), true, 'the border is closed');
ev("ACT.startScn({id:'redsea',sure:1})");
assert.equal(ev("cablesOk('cai','jed').length+cablesOk('jed','bom').length"), 0, 'the Red Sea crisis covers Egypt and Jeddah too');
assert.deepEqual(errors, []);
});
test('Italy, Portugal, Greece and more US cities are on the map and wired up', () => {
const { ev, errors } = load();
for (const c of ['mil', 'rom', 'pmo', 'lis', 'ath', 'atn', 'den', 'phx', 'bos', 'hou', 'slc']) {
assert.ok(ev(`!!CITY.${c}`), c);
assert.ok(ev(`NETS.filter(n=>n.price&&n.pops.includes('${c}')).length`) >= 2, `${c} has transit sellers`);
}
for (const [a, b] of [['lis', 'for'], ['lis', 'atn'], ['mil', 'pmo'], ['pmo', 'cai'], ['ath', 'ist'], ['bos', 'dub']])
assert.ok(ev(`cablesFor('${a}','${b}').length`) > 0, `${a}-${b} cable`);
assert.deepEqual(errors, []);
});
test('network ids are unique, and the long tail is small and spread over exchanges', () => {
const { ev } = load();
assert.equal(ev("new Set(NETS.map(n=>n.id)).size===NETS.length"), true);
const tail = ev("NETS.filter(n=>n.tail).length");
assert.ok(tail >= 50, `${tail} small peers`);
assert.ok(ev("NETS.filter(n=>n.tail).every(n=>n.share<=0.003&&n.pops.every(c=>CITY[c]&&!CITY[c].ixOnly))"));
assert.ok(ev("NETS.filter(n=>n.tail&&n.ix.some(x=>x.includes('~'))).length") >= 5, 'some only sit on challenger IXs');
});
test('several exchanges per city: overlapping members, cheaper challengers, separate ports', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'ams'})");
assert.deepEqual(JSON.parse(ev("JSON.stringify(ixIdsIn('ams'))")), ['ams', 'ams~2', 'ams~3']);
const a = JSON.parse(ev("JSON.stringify(ixMembers('ams'))")), b = JSON.parse(ev("JSON.stringify(ixMembers('ams~2'))"));
assert.ok(a.some(x => b.includes(x)), 'shared members');
assert.ok(b.some(x => !a.includes(x)) && a.some(x => !b.includes(x)), 'and different ones');
assert.ok(ev("ixPortMo('ams~2',1)") < ev("ixPortMo('ams',1)"), 'challenger is cheaper');
ev("ACT.buyIx({city:'ams~2',tier:1});ACT.rs({city:'ams~2'});compute()");
assert.equal(ev("S.ixp['ams~2']"), 1);
assert.equal(ev("S.ixp.ams"), undefined);
assert.ok(ev("ixSessions('ams~2').size") > 3);
assert.ok(ev("R.sessions") > 3);
ev("ACT.peerAll({city:'ams~2'})");
ev("selectCity('ams');ACT.tab({t:'peer'})");
const t = ev("document.getElementById('panelBody').textContent");
assert.match(t, /3 exchanges compete/);
assert.match(t, /NL-Nyx/);
ev("save();load2=JSON.parse(localStorage.getItem('sot-save-v1'));sanitize(load2)");
assert.equal(ev("load2.ixp['ams~2']"), 1, 'saves keep challenger ports');
ev("ACT.cancelIx({city:'ams~2'});ACT.cancelIx({city:'ams~2'})");
assert.equal(ev("S.ixp['ams~2']"), undefined);
assert.equal(ev("Object.keys(S.peers).some(k=>k.endsWith('@ams~2'))"), false);
assert.deepEqual(errors, []);
});
test('Voda-Phony only peers for money now, and EU price wars cut port prices', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'ams'})");
assert.equal(ev("NET.vdp.pol"), 'paid');
assert.equal(ev("peerOk('vdp','ix','ams').ok"), false);
assert.ok(ev("peerOk('vdp','pni','ams').fee") > 0);
assert.ok(ev("ixPortMo('ams',1)") < ev("PORT[1].ix"), 'EU ports are cheaper');
ev("ACT.buyIx({city:'ams',tier:1});const before=ixPortMo('ams',1);const r=Math.random;Math.random=()=>0;ixPriceWar(S.day);Math.random=r;window.__b=before");
assert.ok(ev("ixPortMo('ams',1)") < ev("__b"), 'price cut');
assert.deepEqual(errors, []);
});
test('router ports are finite: plugging in fills them, more routers or bigger models add room', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'ams'})");
assert.equal(ev("portsMax('ams')"), 8, 'one Rusty has 8 ports');
ev("for(const n of ['cog','lvl','tly','ntt','drz','tng'])ACT.buyTransit({city:'ams',net:n,tier:1});ACT.buyIx({city:'ams',tier:1});ACT.buyIx({city:'ams~2',tier:1})");
assert.equal(ev("portsUsed('ams')"), 8);
ev("ACT.buyIx({city:'ams~3',tier:1})");
assert.equal(ev("S.ixp['ams~3']"), undefined, 'no ninth port');
assert.match(ev("document.getElementById('toasts').textContent"), /No free router ports/);
ev("ACT.buyIx({city:'ams~3',tier:0})");
assert.equal(ev("S.ixp['ams~3']"), undefined, 'not even a 10G breakout');
ev("ACT.addRouter({city:'ams'})");
assert.equal(ev("portsMax('ams')"), 16);
ev("ACT.buyIx({city:'ams~3',tier:0})");
assert.equal(ev("S.ixp['ams~3']"), 0);
assert.equal(ev("portsUsed('ams')"), 8.25, '10G rides a breakout');
ev("ACT.rmRouter({city:'ams'})");
assert.equal(ev("S.pops.ams.routers"), 2, 'cannot remove a router whose ports are in use');
const arr = ev("RG.findIndex(r=>/Arrrhipster 7280/.test(r.n))");
assert.ok(arr > 0);
ev(`ACT.upRouter({city:'ams',g:${arr}})`);
assert.equal(ev("S.pops.ams.rgen"), arr, 'swapped to the Arrrhipster');
assert.equal(ev("portsMax('ams')"), 96);
assert.equal(ev("bootMin('ams')") < 30, true, 'boots fast');
ev("selectCity('ams');ACT.tab({t:'infra'});ACT.models()");
assert.match(ev("document.getElementById('panelBody').textContent"), /Knockia/);
const mk = ev("RG.findIndex(r=>/Mikrowtik/.test(r.n))");
ev("ACT.buyTransit({city:'ams',net:'cog',tier:2})");
assert.equal(ev("S.transit.find(t=>t.net==='cog'&&t.city==='ams').tier"), 2);
ev(`ACT.upRouter({city:'ams',g:${mk}})`);
assert.equal(ev("S.pops.ams.rgen"), arr, 'a smaller model that cannot fit is refused');
assert.ok(ev("RG.every(r=>r.ports>0&&r.cls>=0&&r.maxP<PORT.length)"));
assert.deepEqual(errors, []);
});