Merge save slots: one network per window, consistent saves

This commit is contained in:
Frederic Jung 2026-10-29 07:57:00 +01:00
commit efb14680cc
No known key found for this signature in database
36 changed files with 1099 additions and 134 deletions

View file

@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network.
- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside.
- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own.
- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner.
- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round.

View file

@ -80,7 +80,7 @@ Development runs on `npm run dev` (assembles on every request, reloads on save);
- **`S`**: the whole saved game (one JSON object). Cash, day, POPs, links, transit,
IX ports, PNIs, caches, customers (`biz`), offers, incidents (`inc`), live events
(`ev`), stats, settings. Saved to `localStorage` key `sot-save-v1`.
(`ev`), stats, settings. Saved to `localStorage` key `sot-save-v1:<slot>` (one per network, see below).
- **`R`**: results of the last `compute()`: per-link load, per-exit use, served and
demanded traffic, reach, costs and revenue. Never saved; always rebuilt.
- **`UI`**: view state (selection, open tabs, speed, confirmations). Not game state.
@ -177,9 +177,19 @@ weekly files from `main` too, so no deploy ever drops a published week.
## Saves, imports and migration
- `save()` writes `S` to localStorage every few seconds and after actions.
- `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot
(`UI.slot`, `src/game/91-slots.js`): `sot-save-v1:<id>`, plain JSON or `gz:`-compressed above a million
characters, with a stamp `sv:{seq,at}` appended. Then the index `sot-slots` (name, ASN, preset, day, tier,
cash, last played, size, seq) is updated; the title screen lists networks from the index alone.
- Each tab keeps its slot in `sessionStorage['sot-slot']`. One window per slot: a Web Lock
(`sot-slot:<id>`) where supported, plus a heartbeat `sot-open:<id>`; BroadcastChannel `sot-slots` asks
another window to hand over, and the `storage` event stops a window whose slot was saved newer elsewhere
(higher seq) or deleted. A window never writes a slot whose index seq is newer than its own.
- The single save of older versions (`sot-save-v1`) is copied to slot `main` and read back before the
index lists it; the old key is removed only by that slot's next successful save.
- `boot()` loads the save through `migrate()` → `sanitize()`. If loading throws, the
damaged save is kept under `sot-save-broken` and the player starts fresh.
slot is kept and marked damaged in the index (it can still be exported or deleted).
- Puzzles never write a slot; while one runs, `save()` writes the network set aside (`UI.pzKeep`).
- `sanitize(s)` is the gate for all untrusted state (saves and imported files): it
drops unknown ids, clamps numbers, repairs references and fills defaults. Every new
field in `S` needs a line there.

View file

@ -1799,14 +1799,9 @@
"game_and_settings.import_a_save_from_a_file":"Spielstand importieren <small>aus einer Datei</small>",
"game_and_settings.import_failed_that_save_is_damaged":"<b>Import fehlgeschlagen.</b><br>Dieser Spielstand ist beschädigt und konnte nicht geladen werden. Dein aktuelles Spiel ist unberührt.",
"game_and_settings.name_and_everything_it_owns_will":"{name} und alles, was dazugehört, wird gelöscht. Das lässt sich nicht rückgängig machen.",
"game_and_settings.name_will_be_replaced_export_it":"{name} wird ersetzt. Exportiere es vorher über das Menü, wenn du es behalten willst.",
"game_and_settings.scenarios_amp_weekly_challenge":"Szenarien &amp; Wochen-Challenge",
"game_and_settings.share_your_network_image_card":"Dein Netz teilen <small>Bildkarte</small>",
"game_and_settings.start_a_new_network":"Ein neues Netz starten?",
"game_and_settings.start_name":"{name} starten?",
"game_and_settings.start_the_challenge":"Challenge starten",
"game_and_settings.start_the_scenario":"Szenario starten",
"game_and_settings.start_the_weekly_challenge":"Die Wochen-Challenge starten?",
"game_and_settings.welcome_back_name_imported_and_saved":"<b>Willkommen zurück, {name}.</b><br>Importiert und auf diesem Gerät gespeichert.",
"game_and_settings.your_game_saves_itself_every_few":"Dein Spiel speichert sich alle paar Sekunden auf diesem Gerät.",
"geography_and_latency.a_to_b":"{a} nach {b}",
@ -3282,7 +3277,6 @@
"save.that_network_went_bankrupt_it_cannot":"Dieses Netz ist pleitegegangen. Es lässt sich nicht zurückholen, nur betrauern.",
"save.that_save_has_a_pop_in":"Dieser Spielstand hat einen POP in einer Stadt, die diese Version nicht kennt ({city}).",
"save.this_browser_is_not_letting_the":"<b>Dein Spiel wird nicht gespeichert.</b> Dieser Browser lässt das Spiel nichts speichern (ein privates Fenster oder deaktivierte Websitedaten). Exportiere einen Spielstand, um dein Netz zu behalten.",
"save.this_replaces_name_export_it_first":"Das ersetzt {name}. Exportiere es vorher, wenn du es behalten willst.",
"save.your_network_is_too_big_to":"<b>Dein Spiel wird nicht gespeichert.</b> Dein Netz ist zu groß für den Speicher dieses Browsers geworden. Exportiere jetzt einen Spielstand und bewahre die Datei auf: Sie ist dein Backup.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Ziel:</b> {goal} · <b>Zeit:</b> {d} Tage · Start in {city}",
"scenario_progress.goal_was_not_reached_in_d":"{goal} wurde in {d} Tagen nicht erreicht. Spiel dieses Netz im freien Spiel weiter oder versuch es nochmal.",
@ -3419,6 +3413,47 @@
"sites_peering_caches.your_account_manager_found_the_order":"<b>Dein Account Manager hat die Bestellung unter einem Schreibtisch gefunden.</b><br>Die Lieferung rückt einen Monat näher.",
"sites_peering_caches.your_account_manager_is_on_paternity":"<b>Dein Account Manager ist in Elternzeit.</b><br>Seine Vertretung ist auch in Elternzeit.",
"sites_peering_caches.your_ticket_was_merged_into_another":"<b>Dein Ticket wurde mit einem anderen Ticket zusammengeführt.</b><br>Das wurde als Duplikat von deinem geschlossen.",
"slots.continue":"Weiterspielen",
"slots.continue_this_network":"Dieses Netz weiterspielen",
"slots.damaged_export_or_delete":"Beschädigt: exportieren oder löschen",
"slots.delete":"Löschen",
"slots.delete_forever":"Für immer löschen",
"slots.delete_name":"{name} löschen?",
"slots.delete_this_network":"Dieses Netz löschen",
"slots.free_up_space":"Platz schaffen",
"slots.here_it_is_name":"<b>Hier ist es: {name}.</b><br>Das ist das Fenster, das du gesucht hast.",
"slots.it_is_open_in_another_window":"Es ist gerade in einem anderen Fenster offen, und das Fenster hört dann auch auf.",
"slots.it_joins_your_networks_on_this":"Es kommt zu deinen Netzen auf diesem Gerät. Das Netz, das du gerade spielst, bleibt gespeichert.",
"slots.just_now":"gerade eben",
"slots.keep_it":"Behalten",
"slots.last_played_ago":"Zuletzt gespielt: {ago}",
"slots.load_the_newest_version":"Neueste Version laden",
"slots.more_for_name":"Mehr zu {name}",
"slots.n_h_ago":{"one":"vor {n} Std.","other":"vor {n} Std."},
"slots.name_is_open_in_another_window":"{name} ist in einem anderen Fenster offen",
"slots.name_is_waiting_in_your_other":"<b>{name} wartet in deinem anderen Fenster.</b><br>Wechsle dorthin, um weiterzuspielen.",
"slots.name_moved_to_another_window_toast":"<b>{name} wird jetzt in einem anderen Fenster gespielt.</b><br>Dieses Puzzle läuft weiter; dein Netz ist dort sicher.",
"slots.name_opened_in_another_window":"{name} wurde in einem anderen Fenster geöffnet",
"slots.name_was_deleted_in_another_window":"<b>{name} wurde in einem anderen Fenster gelöscht.</b>",
"slots.name_was_saved_in_another_window":"{name} wurde in einem anderen Fenster gespeichert",
"slots.no_other_networks_here":"Keine anderen Netze auf diesem Gerät. Ein exportierter Spielstand ist dein bestes Backup.",
"slots.only_one_window_can_play_a":"Ein Netz, ein NOC: Nur ein Fenster kann es gleichzeitig spielen, damit sich zwei Kopien nie gegenseitig überschreiben.",
"slots.open_in_another_window":"In anderem Fenster offen",
"slots.rename":"Umbenennen",
"slots.rename_your_network":"Netz umbenennen",
"slots.renamed_to_name":"<b>Umbenannt.</b><br>Sag hallo zu {name}.",
"slots.size_on_this_device":"{size} auf diesem Gerät",
"slots.storage_on_this_device":"Speicher auf diesem Gerät",
"slots.switch_to_that_window":"Zu diesem Fenster wechseln",
"slots.take_it_back_here":"Hier zurückholen",
"slots.take_over_here":"Hier übernehmen",
"slots.that_network_is_gone":"<b>Dieses Netz gibt es nicht mehr.</b><br>Es wurde gelöscht, vielleicht in einem anderen Fenster.",
"slots.this_window_stepped_aside_so_the":"Du hast es in einem anderen Fenster übernommen, also hat dieses Platz gemacht und speichert nicht mehr. Nichts ist verloren.",
"slots.this_window_stopped_saving_so_it":"In einem anderen Fenster wurde eine neuere Version gespeichert, also speichert dieses nicht mehr, statt sie zu überschreiben.",
"slots.two_windows_one_network":"Zwei Fenster, ein Netz",
"slots.your_networks":"Deine Netze",
"slots.your_networks_switch_or_start_another":"Deine Netze <small>wechseln oder ein neues starten</small>",
"slots.your_other_networks_share_this_browser":"Deine anderen Netze teilen sich den Speicher dieses Browsers. Exportiere die, die du behalten willst, und lösche sie dann hier, um Platz zu schaffen.",
"sold_out.a_hyperscaler_bought_every_wave_of":"Ein Hyperscaler hat letzte Woche jede Wave dieser Größe auf dieser Route gekauft.",
"sold_out.not_big_enough_yet_list":"Noch nicht groß genug: {list}",
"sold_out.only_peers_over_pnis_and_only":"Peert nur über PNIs, und nur mit Netzen, die es für wichtig hält",

View file

@ -1797,14 +1797,9 @@
"game_and_settings.import_a_save_from_a_file":"Importar una partida <small>desde un archivo</small>",
"game_and_settings.import_failed_that_save_is_damaged":"<b>Falló la importación.</b><br>Esa partida está dañada y no se pudo cargar. Tu partida actual sigue intacta.",
"game_and_settings.name_and_everything_it_owns_will":"{name} y todo lo que posee se borrarán. No se puede deshacer.",
"game_and_settings.name_will_be_replaced_export_it":"{name} será reemplazada. Expórtala primero desde el menú si quieres conservarla.",
"game_and_settings.scenarios_amp_weekly_challenge":"Escenarios y desafío semanal",
"game_and_settings.share_your_network_image_card":"Comparte tu red <small>tarjeta de imagen</small>",
"game_and_settings.start_a_new_network":"¿Empezar una red nueva?",
"game_and_settings.start_name":"¿Empezar {name}?",
"game_and_settings.start_the_challenge":"Empezar el desafío",
"game_and_settings.start_the_scenario":"Empezar el escenario",
"game_and_settings.start_the_weekly_challenge":"¿Empezar el desafío semanal?",
"game_and_settings.welcome_back_name_imported_and_saved":"<b>Bienvenido de nuevo, {name}.</b><br>Importada y guardada en este dispositivo.",
"game_and_settings.your_game_saves_itself_every_few":"Tu partida se guarda sola cada pocos segundos en este dispositivo.",
"geography_and_latency.a_to_b":"{a} a {b}",
@ -3280,7 +3275,6 @@
"save.that_network_went_bankrupt_it_cannot":"Esa red quebró. No se puede recuperar, solo llorar.",
"save.that_save_has_a_pop_in":"Esa partida tiene un POP en una ciudad que esta versión no conoce ({city}).",
"save.this_browser_is_not_letting_the":"<b>Tu partida no se está guardando.</b> Este navegador no deja que el juego guarde nada (ventana privada o datos de sitios desactivados). Exporta una partida para no perder tu red.",
"save.this_replaces_name_export_it_first":"Esto reemplaza a {name}. Expórtala primero si quieres conservarla.",
"save.your_network_is_too_big_to":"<b>Tu partida no se está guardando.</b> Tu red se ha vuelto demasiado grande para el almacenamiento de este navegador. Exporta una partida ahora y guarda el archivo: es tu copia de seguridad.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Objetivo:</b> {goal} · <b>Tiempo:</b> {d} días · empiezas en {city}",
"scenario_progress.goal_was_not_reached_in_d":"{goal} no se logró en {d} días. Sigue jugando esta red en modo libre, o inténtalo de nuevo.",
@ -3417,6 +3411,47 @@
"sites_peering_caches.your_account_manager_found_the_order":"<b>Tu gestor de cuenta encontró el pedido bajo un escritorio.</b><br>Está un mes más cerca.",
"sites_peering_caches.your_account_manager_is_on_paternity":"<b>Tu gestor de cuenta está de baja por paternidad.</b><br>Su sustituto también está de baja por paternidad.",
"sites_peering_caches.your_ticket_was_merged_into_another":"<b>Tu ticket se fusionó con otro ticket.</b><br>Ese ticket se cerró como duplicado del tuyo.",
"slots.continue":"Continuar",
"slots.continue_this_network":"Continuar esta red",
"slots.damaged_export_or_delete":"Dañada: expórtala o bórrala",
"slots.delete":"Borrar",
"slots.delete_forever":"Borrar para siempre",
"slots.delete_name":"¿Borrar {name}?",
"slots.delete_this_network":"Borrar esta red",
"slots.free_up_space":"Liberar espacio",
"slots.here_it_is_name":"<b>Aquí está: {name}.</b><br>Esta es la ventana que buscabas.",
"slots.it_is_open_in_another_window":"Ahora mismo está abierta en otra ventana, y esa ventana también se detendrá.",
"slots.it_joins_your_networks_on_this":"Se suma a tus redes en este dispositivo. La que estás jugando sigue guardada.",
"slots.just_now":"ahora mismo",
"slots.keep_it":"Conservarla",
"slots.last_played_ago":"Última partida: {ago}",
"slots.load_the_newest_version":"Cargar la versión más nueva",
"slots.more_for_name":"Más de {name}",
"slots.n_h_ago":{"one":"hace {n} h","other":"hace {n} h"},
"slots.name_is_open_in_another_window":"{name} está abierta en otra ventana",
"slots.name_is_waiting_in_your_other":"<b>{name} te espera en tu otra ventana.</b><br>Cambia a ella para seguir jugando.",
"slots.name_moved_to_another_window_toast":"<b>{name} ahora se juega en otra ventana.</b><br>Este puzle sigue; tu red está a salvo allí.",
"slots.name_opened_in_another_window":"{name} se abrió en otra ventana",
"slots.name_was_deleted_in_another_window":"<b>{name} se borró en otra ventana.</b>",
"slots.name_was_saved_in_another_window":"{name} se guardó en otra ventana",
"slots.no_other_networks_here":"No hay otras redes en este dispositivo. Exportar una partida es tu mejor copia de seguridad.",
"slots.only_one_window_can_play_a":"Una red, un NOC: solo una ventana puede jugarla a la vez, para que dos copias nunca se sobrescriban.",
"slots.open_in_another_window":"Abierta en otra ventana",
"slots.rename":"Renombrar",
"slots.rename_your_network":"Renombrar tu red",
"slots.renamed_to_name":"<b>Renombrada.</b><br>Saluda a {name}.",
"slots.size_on_this_device":"{size} en este dispositivo",
"slots.storage_on_this_device":"Almacenamiento en este dispositivo",
"slots.switch_to_that_window":"Cambiar a esa ventana",
"slots.take_it_back_here":"Recuperarla aquí",
"slots.take_over_here":"Tomar el control aquí",
"slots.that_network_is_gone":"<b>Esa red ya no existe.</b><br>Se borró, quizá en otra ventana.",
"slots.this_window_stepped_aside_so_the":"La abriste en otra ventana, así que esta se hizo a un lado y dejó de guardar. No se perdió nada.",
"slots.this_window_stopped_saving_so_it":"Se guardó una versión más nueva en otra ventana, así que esta dejó de guardar en vez de sobrescribirla.",
"slots.two_windows_one_network":"Dos ventanas, una red",
"slots.your_networks":"Tus redes",
"slots.your_networks_switch_or_start_another":"Tus redes <small>cambia o empieza otra</small>",
"slots.your_other_networks_share_this_browser":"Tus otras redes comparten el almacenamiento de este navegador. Exporta las que quieras conservar y bórralas aquí para hacer sitio.",
"sold_out.a_hyperscaler_bought_every_wave_of":"Un hiperescalador compró la semana pasada todas las ondas de ese tamaño en esta ruta.",
"sold_out.not_big_enough_yet_list":"Aún no es lo bastante grande: {list}",
"sold_out.only_peers_over_pnis_and_only":"Solo hace peering por PNIs, y solo con redes que considera importantes",

View file

@ -1797,14 +1797,9 @@
"game_and_settings.import_a_save_from_a_file":"Importer une sauvegarde <small>depuis un fichier</small>",
"game_and_settings.import_failed_that_save_is_damaged":"<b>Échec de l’import.</b><br>Cette sauvegarde est endommagée et n’a pas pu être chargée. Ta partie en cours est intacte.",
"game_and_settings.name_and_everything_it_owns_will":"{name} et tout ce qu’il possède seront supprimés. Impossible de revenir en arrière.",
"game_and_settings.name_will_be_replaced_export_it":"{name} sera remplacé. Exporte-le d’abord depuis le menu si tu veux le garder.",
"game_and_settings.scenarios_amp_weekly_challenge":"Scénarios &amp; défi de la semaine",
"game_and_settings.share_your_network_image_card":"Partager ton réseau <small>carte image</small>",
"game_and_settings.start_a_new_network":"Créer un nouveau réseau ?",
"game_and_settings.start_name":"Lancer {name} ?",
"game_and_settings.start_the_challenge":"Lancer le défi",
"game_and_settings.start_the_scenario":"Lancer le scénario",
"game_and_settings.start_the_weekly_challenge":"Lancer le défi de la semaine ?",
"game_and_settings.welcome_back_name_imported_and_saved":"<b>Bon retour, {name}.</b><br>Partie importée et sauvegardée sur cet appareil.",
"game_and_settings.your_game_saves_itself_every_few":"Ta partie se sauvegarde toute seule sur cet appareil, toutes les quelques secondes.",
"geography_and_latency.a_to_b":"{a} → {b}",
@ -3280,7 +3275,6 @@
"save.that_network_went_bankrupt_it_cannot":"Ce réseau a fait faillite. Impossible de le ressusciter, on ne peut que le pleurer.",
"save.that_save_has_a_pop_in":"Cette sauvegarde a un POP dans une ville que cette version ne connaît pas ({city}).",
"save.this_browser_is_not_letting_the":"<b>Votre partie n'est pas sauvegardée.</b> Ce navigateur n'autorise pas le jeu à stocker quoi que ce soit (fenêtre privée ou données de sites désactivées). Exportez une sauvegarde pour garder votre réseau.",
"save.this_replaces_name_export_it_first":"Cela remplace {name}. Exporte-le d’abord si tu veux le garder.",
"save.your_network_is_too_big_to":"<b>Votre partie n'est pas sauvegardée.</b> Votre réseau est devenu trop gros pour le stockage de ce navigateur. Exportez une sauvegarde maintenant et gardez le fichier : c'est votre copie de secours.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Objectif :</b> {goal} · <b>Durée :</b> {d} jours · départ à {city}",
"scenario_progress.goal_was_not_reached_in_d":"Objectif non atteint en {d} jours : {goal}. Continue avec ce réseau en partie libre, ou réessaie.",
@ -3417,6 +3411,47 @@
"sites_peering_caches.your_account_manager_found_the_order":"<b>Votre account manager a retrouvé la commande sous un bureau.</b><br>Elle a un mois d’avance.",
"sites_peering_caches.your_account_manager_is_on_paternity":"<b>Votre account manager est en congé paternité.</b><br>Son remplaçant aussi.",
"sites_peering_caches.your_ticket_was_merged_into_another":"<b>Votre ticket a été fusionné avec un autre ticket.</b><br>Ce ticket a été fermé comme doublon du vôtre.",
"slots.continue":"Continuer",
"slots.continue_this_network":"Continuer ce réseau",
"slots.damaged_export_or_delete":"Endommagé : exporte-le ou supprime-le",
"slots.delete":"Supprimer",
"slots.delete_forever":"Supprimer pour de bon",
"slots.delete_name":"Supprimer {name} ?",
"slots.delete_this_network":"Supprimer ce réseau",
"slots.free_up_space":"Libérer de la place",
"slots.here_it_is_name":"<b>Le voici : {name}.</b><br>C'est la fenêtre que tu cherchais.",
"slots.it_is_open_in_another_window":"Il est ouvert dans une autre fenêtre en ce moment, et cette fenêtre s'arrêtera aussi.",
"slots.it_joins_your_networks_on_this":"Il rejoint tes réseaux sur cet appareil. Celui que tu joues reste sauvegardé.",
"slots.just_now":"à l'instant",
"slots.keep_it":"Le garder",
"slots.last_played_ago":"Dernière partie : {ago}",
"slots.load_the_newest_version":"Charger la version la plus récente",
"slots.more_for_name":"Plus pour {name}",
"slots.n_h_ago":{"one":"il y a {n} h","other":"il y a {n} h"},
"slots.name_is_open_in_another_window":"{name} est ouvert dans une autre fenêtre",
"slots.name_is_waiting_in_your_other":"<b>{name} t'attend dans ton autre fenêtre.</b><br>Passe dessus pour continuer à jouer.",
"slots.name_moved_to_another_window_toast":"<b>{name} se joue maintenant dans une autre fenêtre.</b><br>Ce puzzle continue ; ton réseau est en sécurité là-bas.",
"slots.name_opened_in_another_window":"{name} a été ouvert dans une autre fenêtre",
"slots.name_was_deleted_in_another_window":"<b>{name} a été supprimé dans une autre fenêtre.</b>",
"slots.name_was_saved_in_another_window":"{name} a été sauvegardé dans une autre fenêtre",
"slots.no_other_networks_here":"Aucun autre réseau sur cet appareil. Exporter une sauvegarde reste ta meilleure copie de secours.",
"slots.only_one_window_can_play_a":"Un réseau, un NOC : une seule fenêtre peut le jouer à la fois, pour que deux copies ne s'écrasent jamais.",
"slots.open_in_another_window":"Ouvert dans une autre fenêtre",
"slots.rename":"Renommer",
"slots.rename_your_network":"Renommer ton réseau",
"slots.renamed_to_name":"<b>Renommé.</b><br>Dis bonjour à {name}.",
"slots.size_on_this_device":"{size} sur cet appareil",
"slots.storage_on_this_device":"Stockage sur cet appareil",
"slots.switch_to_that_window":"Aller à cette fenêtre",
"slots.take_it_back_here":"Le reprendre ici",
"slots.take_over_here":"Le prendre ici",
"slots.that_network_is_gone":"<b>Ce réseau n'existe plus.</b><br>Il a été supprimé, peut-être dans une autre fenêtre.",
"slots.this_window_stepped_aside_so_the":"Tu l'as repris dans une autre fenêtre, alors celle-ci s'est effacée et ne sauvegarde plus. Rien n'est perdu.",
"slots.this_window_stopped_saving_so_it":"Une version plus récente a été sauvegardée dans une autre fenêtre, alors celle-ci a arrêté de sauvegarder au lieu de l'écraser.",
"slots.two_windows_one_network":"Deux fenêtres, un réseau",
"slots.your_networks":"Tes réseaux",
"slots.your_networks_switch_or_start_another":"Tes réseaux <small>changer, ou en lancer un autre</small>",
"slots.your_other_networks_share_this_browser":"Tes autres réseaux partagent le stockage de ce navigateur. Exporte ceux que tu veux garder, puis supprime-les ici pour faire de la place.",
"sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler a acheté la semaine dernière toutes les ondes de cette taille sur cette route.",
"sold_out.not_big_enough_yet_list":"Pas encore assez gros : {list}",
"sold_out.only_peers_over_pnis_and_only":"Ne fait du peering qu’en PNI, et seulement avec les réseaux qu’il juge importants",

View file

@ -1797,14 +1797,9 @@
"game_and_settings.import_a_save_from_a_file":"Importa un salvataggio <small>da un file</small>",
"game_and_settings.import_failed_that_save_is_damaged":"<b>Importazione fallita.</b><br>Quel salvataggio è danneggiato e non si può caricare. La partita in corso non è stata toccata.",
"game_and_settings.name_and_everything_it_owns_will":"{name} e tutto ciò che possiede verranno cancellati. Non si torna indietro.",
"game_and_settings.name_will_be_replaced_export_it":"La partita con {name} verrà sostituita. Se vuoi tenerla, prima esportala dal menu.",
"game_and_settings.scenarios_amp_weekly_challenge":"Scenari e sfida settimanale",
"game_and_settings.share_your_network_image_card":"Condividi la tua rete <small>come immagine</small>",
"game_and_settings.start_a_new_network":"Vuoi creare una nuova rete?",
"game_and_settings.start_name":"Vuoi iniziare {name}?",
"game_and_settings.start_the_challenge":"Inizia la sfida",
"game_and_settings.start_the_scenario":"Inizia lo scenario",
"game_and_settings.start_the_weekly_challenge":"Vuoi iniziare la sfida settimanale?",
"game_and_settings.welcome_back_name_imported_and_saved":"<b>Bentornato, {name}.</b><br>Importato e salvato su questo dispositivo.",
"game_and_settings.your_game_saves_itself_every_few":"La partita si salva da sola ogni pochi secondi su questo dispositivo.",
"geography_and_latency.a_to_b":"{a} → {b}",
@ -3280,7 +3275,6 @@
"save.that_network_went_bankrupt_it_cannot":"Quella rete è finita in bancarotta. Non si può resuscitare, solo piangere.",
"save.that_save_has_a_pop_in":"Quel salvataggio ha un POP in una città che questa versione non conosce ({city}).",
"save.this_browser_is_not_letting_the":"<b>La partita non viene salvata.</b> Questo browser non permette al gioco di salvare nulla (finestra privata o dati dei siti disattivati). Esporta un salvataggio per non perdere la tua rete.",
"save.this_replaces_name_export_it_first":"Sostituisce {name}. Esportala prima, se vuoi tenerla.",
"save.your_network_is_too_big_to":"<b>La partita non viene salvata.</b> La tua rete è diventata troppo grande per lo spazio di questo browser. Esporta un salvataggio adesso e tieni il file: è il tuo backup.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Obiettivo:</b> {goal} · <b>Tempo:</b> {d} giorni · si parte da {city}",
"scenario_progress.goal_was_not_reached_in_d":"Obiettivo non raggiunto in {d} giorni: {goal}. Continua a giocare questa rete in modalità libera, o riprova.",
@ -3417,6 +3411,47 @@
"sites_peering_caches.your_account_manager_found_the_order":"<b>Il tuo account manager ha trovato l’ordine sotto una scrivania.</b><br>È un mese più vicino.",
"sites_peering_caches.your_account_manager_is_on_paternity":"<b>Il tuo account manager è in congedo di paternità.</b><br>Anche il suo sostituto è in congedo di paternità.",
"sites_peering_caches.your_ticket_was_merged_into_another":"<b>Il tuo ticket è stato unito a un altro ticket.</b><br>Quel ticket è stato chiuso come duplicato del tuo.",
"slots.continue":"Continua",
"slots.continue_this_network":"Continua questa rete",
"slots.damaged_export_or_delete":"Danneggiata: esportala o eliminala",
"slots.delete":"Elimina",
"slots.delete_forever":"Elimina per sempre",
"slots.delete_name":"Eliminare {name}?",
"slots.delete_this_network":"Elimina questa rete",
"slots.free_up_space":"Libera spazio",
"slots.here_it_is_name":"<b>Eccola: {name}.</b><br>È la finestra che cercavi.",
"slots.it_is_open_in_another_window":"In questo momento è aperta in un'altra finestra, e anche quella finestra si fermerà.",
"slots.it_joins_your_networks_on_this":"Si aggiunge alle tue reti su questo dispositivo. Quella che stai giocando resta salvata.",
"slots.just_now":"proprio ora",
"slots.keep_it":"Tienila",
"slots.last_played_ago":"Ultima partita: {ago}",
"slots.load_the_newest_version":"Carica la versione più recente",
"slots.more_for_name":"Altro per {name}",
"slots.n_h_ago":{"one":"{n} h fa","other":"{n} h fa"},
"slots.name_is_open_in_another_window":"{name} è aperta in un'altra finestra",
"slots.name_is_waiting_in_your_other":"<b>{name} ti aspetta nell'altra finestra.</b><br>Passa lì per continuare a giocare.",
"slots.name_moved_to_another_window_toast":"<b>{name} ora si gioca in un'altra finestra.</b><br>Questo puzzle continua; la tua rete è al sicuro di là.",
"slots.name_opened_in_another_window":"{name} è stata aperta in un'altra finestra",
"slots.name_was_deleted_in_another_window":"<b>{name} è stata eliminata in un'altra finestra.</b>",
"slots.name_was_saved_in_another_window":"{name} è stata salvata in un'altra finestra",
"slots.no_other_networks_here":"Nessun'altra rete su questo dispositivo. Esportare un salvataggio è il tuo backup migliore.",
"slots.only_one_window_can_play_a":"Una rete, un NOC: solo una finestra alla volta può giocarla, così due copie non si sovrascrivono mai.",
"slots.open_in_another_window":"Aperta in un'altra finestra",
"slots.rename":"Rinomina",
"slots.rename_your_network":"Rinomina la tua rete",
"slots.renamed_to_name":"<b>Rinominata.</b><br>Saluta {name}.",
"slots.size_on_this_device":"{size} su questo dispositivo",
"slots.storage_on_this_device":"Spazio su questo dispositivo",
"slots.switch_to_that_window":"Passa a quella finestra",
"slots.take_it_back_here":"Riprendila qui",
"slots.take_over_here":"Prendila qui",
"slots.that_network_is_gone":"<b>Quella rete non c'è più.</b><br>È stata eliminata, forse in un'altra finestra.",
"slots.this_window_stepped_aside_so_the":"L'hai presa in un'altra finestra, quindi questa si è fatta da parte e ha smesso di salvare. Non si è perso nulla.",
"slots.this_window_stopped_saving_so_it":"In un'altra finestra è stata salvata una versione più recente, quindi questa ha smesso di salvare invece di sovrascriverla.",
"slots.two_windows_one_network":"Due finestre, una rete",
"slots.your_networks":"Le tue reti",
"slots.your_networks_switch_or_start_another":"Le tue reti <small>cambia o iniziane un'altra</small>",
"slots.your_other_networks_share_this_browser":"Le tue altre reti condividono lo spazio di questo browser. Esporta quelle che vuoi tenere, poi eliminale qui per fare posto.",
"sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler ha comprato la settimana scorsa ogni onda di questa misura su questa tratta.",
"sold_out.not_big_enough_yet_list":"Non sei ancora abbastanza grande: {list}",
"sold_out.only_peers_over_pnis_and_only":"Fa peering solo su PNI, e solo con reti che considera importanti",

View file

@ -1797,14 +1797,9 @@
"game_and_settings.import_a_save_from_a_file":"Importar um save <small>de um arquivo</small>",
"game_and_settings.import_failed_that_save_is_damaged":"<b>Falha na importação.</b><br>Esse save está corrompido e não pôde ser carregado. Seu jogo atual não foi mexido.",
"game_and_settings.name_and_everything_it_owns_will":"{name} e tudo o que ela possui serão apagados. Não dá para desfazer.",
"game_and_settings.name_will_be_replaced_export_it":"{name} será substituído. Exporte pelo menu antes se quiser guardar.",
"game_and_settings.scenarios_amp_weekly_challenge":"Cenários &amp; desafio semanal",
"game_and_settings.share_your_network_image_card":"Compartilhar sua rede <small>card de imagem</small>",
"game_and_settings.start_a_new_network":"Começar uma nova rede?",
"game_and_settings.start_name":"Começar {name}?",
"game_and_settings.start_the_challenge":"Começar o desafio",
"game_and_settings.start_the_scenario":"Começar o cenário",
"game_and_settings.start_the_weekly_challenge":"Começar o desafio semanal?",
"game_and_settings.welcome_back_name_imported_and_saved":"<b>Bem-vindo de volta, {name}.</b><br>Importado e salvo neste dispositivo.",
"game_and_settings.your_game_saves_itself_every_few":"Seu jogo se salva sozinho a cada poucos segundos neste dispositivo.",
"geography_and_latency.a_to_b":"{a} → {b}",
@ -3280,7 +3275,6 @@
"save.that_network_went_bankrupt_it_cannot":"Essa rede foi à falência. Não dá para trazer de volta, só chorar.",
"save.that_save_has_a_pop_in":"Esse save tem um POP numa cidade que esta versão não conhece ({city}).",
"save.this_browser_is_not_letting_the":"<b>Seu jogo não está sendo salvo.</b> Este navegador não deixa o jogo guardar nada (janela anônima ou dados de sites desativados). Exporte um save para não perder sua rede.",
"save.this_replaces_name_export_it_first":"Isso substitui {name}. Exporte antes se quiser guardar.",
"save.your_network_is_too_big_to":"<b>Seu jogo não está sendo salvo.</b> Sua rede ficou grande demais para o armazenamento deste navegador. Exporte um save agora e guarde o arquivo: é o seu backup.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Objetivo:</b> {goal} · <b>Tempo:</b> {d} dias · começa em {city}",
"scenario_progress.goal_was_not_reached_in_d":"Objetivo não alcançado em {d} dias: {goal}. Continue jogando esta rede no modo livre, ou tente de novo.",
@ -3417,6 +3411,47 @@
"sites_peering_caches.your_account_manager_found_the_order":"<b>Seu gerente de contas achou o pedido embaixo de uma mesa.</b><br>Está um mês mais perto.",
"sites_peering_caches.your_account_manager_is_on_paternity":"<b>Seu gerente de contas está de licença-paternidade.</b><br>O substituto dele também está de licença-paternidade.",
"sites_peering_caches.your_ticket_was_merged_into_another":"<b>Seu chamado foi juntado a outro chamado.</b><br>Esse chamado foi fechado como duplicado do seu.",
"slots.continue":"Continuar",
"slots.continue_this_network":"Continuar esta rede",
"slots.damaged_export_or_delete":"Danificada: exporte ou apague",
"slots.delete":"Apagar",
"slots.delete_forever":"Apagar para sempre",
"slots.delete_name":"Apagar {name}?",
"slots.delete_this_network":"Apagar esta rede",
"slots.free_up_space":"Liberar espaço",
"slots.here_it_is_name":"<b>Aqui está: {name}.</b><br>Esta é a janela que você procurava.",
"slots.it_is_open_in_another_window":"Ela está aberta em outra janela agora, e essa janela também vai parar.",
"slots.it_joins_your_networks_on_this":"Ela entra nas suas redes neste dispositivo. A que você está jogando continua salva.",
"slots.just_now":"agora mesmo",
"slots.keep_it":"Manter",
"slots.last_played_ago":"Jogada pela última vez {ago}",
"slots.load_the_newest_version":"Carregar a versão mais nova",
"slots.more_for_name":"Mais para {name}",
"slots.n_h_ago":{"one":"há {n} h","other":"há {n} h"},
"slots.name_is_open_in_another_window":"{name} está aberta em outra janela",
"slots.name_is_waiting_in_your_other":"<b>{name} está esperando na sua outra janela.</b><br>Vá para ela para continuar jogando.",
"slots.name_moved_to_another_window_toast":"<b>{name} agora é jogada em outra janela.</b><br>Este puzzle continua; sua rede está segura lá.",
"slots.name_opened_in_another_window":"{name} foi aberta em outra janela",
"slots.name_was_deleted_in_another_window":"<b>{name} foi apagada em outra janela.</b>",
"slots.name_was_saved_in_another_window":"{name} foi salva em outra janela",
"slots.no_other_networks_here":"Nenhuma outra rede neste dispositivo. Exportar o jogo é o seu melhor backup.",
"slots.only_one_window_can_play_a":"Uma rede, um NOC: só uma janela pode jogá-la por vez, para que duas cópias nunca se sobrescrevam.",
"slots.open_in_another_window":"Aberta em outra janela",
"slots.rename":"Renomear",
"slots.rename_your_network":"Renomear sua rede",
"slots.renamed_to_name":"<b>Renomeada.</b><br>Diga olá para {name}.",
"slots.size_on_this_device":"{size} neste dispositivo",
"slots.storage_on_this_device":"Armazenamento neste dispositivo",
"slots.switch_to_that_window":"Ir para essa janela",
"slots.take_it_back_here":"Trazer de volta para cá",
"slots.take_over_here":"Assumir aqui",
"slots.that_network_is_gone":"<b>Essa rede não existe mais.</b><br>Ela foi apagada, talvez em outra janela.",
"slots.this_window_stepped_aside_so_the":"Você assumiu em outra janela, então esta saiu da frente e parou de salvar. Nada foi perdido.",
"slots.this_window_stopped_saving_so_it":"Uma versão mais nova foi salva em outra janela, então esta parou de salvar em vez de sobrescrevê-la.",
"slots.two_windows_one_network":"Duas janelas, uma rede",
"slots.your_networks":"Suas redes",
"slots.your_networks_switch_or_start_another":"Suas redes <small>trocar ou começar outra</small>",
"slots.your_other_networks_share_this_browser":"Suas outras redes dividem o armazenamento deste navegador. Exporte as que quiser manter e apague-as aqui para abrir espaço.",
"sold_out.a_hyperscaler_bought_every_wave_of":"Um hyperscaler comprou semana passada todas as ondas desse tamanho nesta rota.",
"sold_out.not_big_enough_yet_list":"Você ainda não é grande o bastante: {list}",
"sold_out.only_peers_over_pnis_and_only":"Só faz peering via PNI, e só com redes que considera importantes",

View file

@ -30,7 +30,7 @@ const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chao
function weekly(){const {y,w}=isoWeek(new Date());let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};}
const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]);
function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}}
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}newGame(nm,city);S.mode=o.mode||'normal';
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);S.mode=o.mode||'normal';
// The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules.
{const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);}
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}}

View file

@ -81,9 +81,9 @@ function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==
// ---------- entering and leaving ----------
// Toasts from one world never carry over into the other (their buttons act on the S they came from).
const pzToastsClear=()=>{$('toasts').textContent='';};
// The running game gets its usual save first, so leaving the puzzle can load it back exactly as booting does. A huge
// save is compressed in the background and may not have landed yet, so the game object is kept in memory too.
function pzFlush(){save(true);UI.pzKeep=UI.gzBusy||saveFailing()?S:null;}
// The running game gets its usual save first and is kept in memory, set aside: save() keeps writing it to its slot
// (leaving the page mid-puzzle), and leaving the puzzle picks it up again.
function pzFlush(){save(true);UI.pzKeep=S;}
function pzBegin(def){if(!def)return;
const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null;
S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null};
@ -96,7 +96,9 @@ function pzBegin(def){if(!def)return;
if(live)pzFlush();go();}
function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null;
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){S=null;UI.started=false;}}}
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
// It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told.
if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}}
renderAll();showTitle();}
// The camera frames the puzzle's cities beside the puzzle card: left on wide screens, right on phones on their side, a bottom sheet on phones.
function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity;

View file

@ -9,21 +9,24 @@ Object.assign(ACT,{
// Puzzles live in their own module; until it ships, the door says so.
puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');},
scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();},
startScn:({id,sure})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_name',{name:esc(sc.n)})}</h2><p class="tagline">${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}</p><div class="btns">${btn(tr('game_and_settings.start_the_scenario'),'startScn',{id,sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);return;}beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});},
startWeekly:({sure}={})=>{if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_the_weekly_challenge')}</h2><p class="tagline">${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}</p><div class="btns">${btn(tr('game_and_settings.start_the_challenge'),'startWeekly',{sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);return;}const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});},
startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});},
startWeekly:()=>{const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});},
pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city||(b.classList.contains('own')&&!START5.includes(city))));const s=$('homeSel');if(s&&START5.includes(city))s.value='';const w=$('homeWhat');if(w)w.innerHTML=homeWhat();},
pickHome:({v})=>{if(v)ACT.pickStart({city:v});else ACT.pickStart({city:'fra'});},
cont:()=>{migrate(S);track('game_continue',true);UI.started=true;closeModal();renderAll();},
newgame:()=>{try{localStorage.removeItem('sot-save-v1');}catch(e){}S=null;UI.started=false;UI.sel=null;UI.nm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();},
// Delete this window's network and go back to the title (the other networks stay).
newgame:()=>{if(pzOn())pzLeave();const id=UI.slot;if(id){slotDrop(id);slotFree(id);}gameClear();showTitle();},
keepPlaying:()=>{closeModal();},
exportSave:()=>exportSave(),
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;try{S=migrate(JSON.parse(JSON.stringify(s0)));compute();checkGoals();renderAll();}catch(e){S=prev;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;compute();renderAll();save();toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S;
// An import is a new network next to the others: the one playing here is saved and kept.
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}${isPhone()?installRow():''}
<div class="menu-list">
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}
${btn(tr('game_and_settings.export_save_download_a_file'),'exportSave',{},saveFailing()?'pink':'')}
${btn(tr('slots.your_networks_switch_or_start_another'),'toTitle',{},'')}
${btn(tr('game_and_settings.export_save_download_a_file'),'exportSave',{},saveFailing()?'pink':'')}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''}
${btn(tr('game_and_settings.import_a_save_from_a_file'),'importPick',{},'')}
${btn(tr('game_and_settings.share_your_network_image_card'),'share',{},'')}
${btn(tr('game_and_settings.scenarios_amp_weekly_challenge'),'scenarios',{},'ghost')}

View file

@ -0,0 +1,32 @@
Object.assign(ACT,{
// Continue a network from the list (or the newest one).
cont:({id}={})=>{if(!slotOkId(id)){const t=slotTop(slotIdx(true));if(!t)return;id=t.id;}
if(id===UI.slot&&S&&!pzOn()){UI.started=true;closeModal();renderAll();return;}
slotOpen(id,false,()=>track('game_continue',true));},
// Back to the title with this network kept and saved.
toTitle:()=>{if(pzOn()){pzLeave();}slotLeave();gameClear();showTitle();},
slotBack:()=>{if(S&&UI.started)closeModal();else showTitle();},
slotMenu:({id})=>{const h=slotMenuHtml(id);if(h)openModal(h);},
slotExport:({id})=>exportSlot(id),
slotDel:({id,back})=>{const e=slotIdx().find(x=>x.id===id);if(!e)return;
openModal(`<h2 style="font-size:26px">${tr('slots.delete_name',{name:esc(e.name||tr('common.unnamed_network'))})}</h2><p class="tagline">${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(e.name||tr('common.unnamed_network'))})}</p>${slotBusy(id)?`<p class="note" style="color:var(--bad)">${tr('slots.it_is_open_in_another_window')}</p>`:''}<div class="btns">${btn(tr('slots.delete_forever'),'slotDelGo',{id,back},'red big')}${btn(tr('slots.keep_it'),back==='space'?'slotSpace':'slotBack',{},'ghost big')}</div>`);},
slotDelGo:({id,back})=>{if(!slotIdx().some(e=>e.id===id))return;
if(id===UI.slot){ACT.newgame();return;}
slotDrop(id);try{BC&&BC.postMessage({t:'gone',id});}catch(e){}sfx('click');
if(back==='space')openModal(slotSpaceHtml());else showTitle();},
slotSpace:()=>openModal(slotSpaceHtml()),
// The other window cannot be brought forward from here; it says hello when the player gets there.
slotSwitch:({id})=>{try{BC&&BC.postMessage({t:'focus',id});}catch(e){}const e=slotIdx().find(x=>x.id===id);showTitle();toast(tr('slots.name_is_waiting_in_your_other',{name:esc(e&&e.name||'')}),'goal');},
// Ask the other window to save and step aside, then open it here. Without an answer (it is frozen, or the browser has
// no BroadcastChannel) it is taken anyway after a moment: the other window stops writing the moment it notices.
slotTake:({id})=>{if(!slotOkId(id))return;const w=SLOT.wait={id,go:()=>{if(SLOT.wait!==w)return;SLOT.wait=null;clearTimeout(w.t);slotOpen(id,true);}};
w.t=setTimeout(w.go,BC?1500:0);try{if(BC)BC.postMessage({t:'take',id});}catch(e){w.go();}},
rename:()=>{if(!S||!UI.started||pzOn())return;openModal(`<h2 style="font-size:26px">${tr('slots.rename_your_network')}</h2><label class="f" for="rnIn">${tr('title.name_your_network')}</label><div class="network-name"><input class="t" id="rnIn" maxlength="24" value="${esc(S.name)}" autocomplete="off"></div><div class="btns" style="margin-top:12px">${btn(tr('slots.rename'),'renameGo',{},'pink big')}${btn(tr('common.cancel'),'menu',{},'ghost big')}</div>`);},
renameGo:()=>{const el=$('rnIn');if(!S||!el||pzOn())return;const v=el.value.replace(/\s+/g,' ').trim().slice(0,24);if(!v)return;S.name=v;closeModal();after();toast(tr('slots.renamed_to_name',{name:esc(v)}),'good');},
});
// No game on screen: the map stays empty behind the title.
function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();}
// Back from the title (or a puzzle) into a loaded network.
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}

View file

@ -2,20 +2,25 @@
/* A network too big for the browser's storage fails to save every time, and turning it into text takes a
moment on huge saves, every 5 seconds and after every click. After a failure the autosave waits before trying
again (1 minute, then 2, 4, at most 5); leaving the page, exporting or another game (a new S) still try at once. */
// A puzzle is never saved: only its stars are, under their own key (sot-puzzles).
function save(force){if(!S||S.lost||S.mode==='puzzle')return;S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};const f=UI.saveFail;
if(!force&&f&&f.s===S&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
const txt=JSON.stringify(packSave(S));
const seq=UI.saveSeq=(UI.saveSeq||0)+1;
if(txt.length>=GZ_MIN&&gzOk())gzSave(S,txt,seq);
else try{localStorage.setItem('sot-save-v1',txt);UI.saveFail=null;}catch(e){saveErr(e,S);}
UI.lastSave=performance.now();}
/* A puzzle is never saved: only its stars are, under their own key (sot-puzzles). While one runs, the network it set
aside (UI.pzKeep) is the one saved, to its own slot, so closing the tab mid-puzzle loses nothing. */
function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return;
if(st===S){S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st;
if(!force&&failed&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
UI.lastSave=performance.now();
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.
if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return;
const txt=JSON.stringify(packSave(st));
let tier=null;if(st===S)try{tier=tierLabel();}catch(e){}
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)};
if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));}
function saveErr(e,s){const f=UI.saveFail,again=f&&f.s===s;UI.saveFail={s,at:performance.now(),wait:again?Math.min(300000,f.wait*2):60000,full:saveFull(e)};
// Say so once per game (#176): a save that silently fails loses everything since the last one that worked.
if(!again&&s===S)toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}}]);}
if(!again&&(s===S||s===UI.pzKeep))toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}},...(UI.saveFail.full&&slotOthers().length?[{l:tr('slots.free_up_space'),act:'slotSpace',args:{}}]:[])]);}
/* Saves of huge networks are gzipped by the browser (#176): about ten times smaller, so they fit in its storage.
Compressing runs in the background, one at a time, and the newest save wins; one that a newer save or another
game has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. */
Compressing runs in the background, one at a time, and the newest save of each network wins; one that a newer save
of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. */
const GZ='gz:',GZ_MIN=1e6,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function';
async function gzPipe(bytes,stream){const w=stream.writable.getWriter(),no=()=>{};w.write(bytes).catch(no);w.close().catch(no);// a bad stream is reported by read() below
const r=stream.readable.getReader(),parts=[];let n=0;
@ -25,15 +30,11 @@ const b64=u=>{let s='';for(let i=0;i<u.length;i+=0x8000)s+=String.fromCharCode.a
const unb64=t=>{const s=atob(t),u=new Uint8Array(s.length);for(let i=0;i<s.length;i++)u[i]=s.charCodeAt(i);return u;};
const gzip=async txt=>GZ+b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip')));
const gunzip=async raw=>new TextDecoder().decode(await gzPipe(unb64(raw.slice(GZ.length)),new DecompressionStream('gzip')));
function gzSave(s,txt,seq){if(UI.gzBusy){UI.gzNext={s,txt,seq};return;}UI.gzBusy=true;
gzip(txt).then(v=>{if((s!==S&&s!==UI.pzKeep)||seq!==UI.saveSeq)return;try{localStorage.setItem('sot-save-v1',v);UI.saveFail=null;}catch(e){saveErr(e,s);}})
// Jobs carry their slot, not the game object: a save still compressing lands in its own network whatever S is by then.
function gzSave(j){if(UI.gzBusy){SLOT.gzQ.set(j.id,j);return;}UI.gzBusy=true;
gzip(slotStamp(j.txt,j.seq)).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);})
.catch(e=>{console.error('[tubes] compressing the save failed',e);})
.finally(()=>{UI.gzBusy=false;const n=UI.gzNext;UI.gzNext=null;if(n&&n.s===S)gzSave(n.s,n.txt,n.seq);});}
// A compressed save is unpacked before the game boots, so loadSave() stays synchronous for everything else.
async function gzBoot(go){let raw=null;try{raw=localStorage.getItem('sot-save-v1');}catch(e){}
if(raw&&raw.startsWith(GZ)){try{UI.gzRaw=raw;UI.gzText=await gunzip(raw);}catch(e){console.error('[tubes] unpacking the save failed',e);UI.gzRaw=UI.gzText=null;
try{localStorage.setItem('sot-save-broken',raw);localStorage.removeItem('sot-save-v1');}catch(e2){}UI.gzBroken=true;}}
go();}
.finally(()=>{UI.gzBusy=false;const n=SLOT.gzQ.values().next().value;if(n){SLOT.gzQ.delete(n.id);gzSave(n);}else slotIdle();});}
/* Big networks are mostly customers, and most of a customer record was defaults (#176): no second city, no
requirements, the normal route, no warnings yet. The save leaves defaults out and sanitize() puts them back, so
the game after loading is the same; older versions read a missing field as its default too. An alien wave's
@ -42,7 +43,8 @@ const BIZ_DEF={city2:null,latMax:null,route:'normal',sites:null,slots:0,warned:f
function packBiz(b){const o={};for(const k in b){const v=b[k];if(v===undefined||BIZ_DEF[k]===v||(k==='reqs'&&Array.isArray(v)&&!v.length)||(k==='pm'&&v===b.mood)||(k==='what'&&b.type==='wwave'&&b.link))continue;o[k]=v;}return o;}
function unpackBiz(b,links){for(const k in BIZ_DEF)if(!(k in b))b[k]=BIZ_DEF[k];if(!('pm' in b)&&b.mood!==undefined)b.pm=b.mood;if(!Array.isArray(b.reqs))b.reqs=[];
if(b.type==='wwave'&&b.what===undefined){const l=links.get(b.link);b.what=l?wwWhat(l,b.slots||1):'';}return b;}
const packSave=s=>({...s,biz:s.biz.map(packBiz)});
// sv (the slot's save stamp) is added when the text is written, never carried in the game.
const packSave=s=>({...s,sv:undefined,biz:s.biz.map(packBiz)});
// Out of room (quota) or not allowed to store at all (private window, blocked site data): different advice.
const saveFull=e=>!!e&&(e.name==='QuotaExceededError'||e.name==='NS_ERROR_DOM_QUOTA_REACHED'||e.code===22||e.code===1014);
const saveFailing=()=>!!(UI.saveFail&&UI.saveFail.s===S);
@ -52,10 +54,14 @@ addEventListener('pagehide',()=>save(true));
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save(true);else checkUpdate();});
/* Export / import: move a network to another device or keep a backup. The file is the same
object the autosave writes, wrapped with a little metadata. */
function saveFileName(){const d=new Date().toISOString().slice(0,10),n=(S&&S.name||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;}
function exportSave(){if(!S||S.mode==='puzzle')return;save(true);const blob=new Blob([JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S:packSave(S)},null,1)],{type:'application/json'});
const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName();document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);
toast(tr('save.save_exported_file_is_in_your',{file:esc(saveFileName())}),'good');}
function saveFileName(nm){const d=new Date().toISOString().slice(0,10),n=String(nm||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;}
function saveDl(txt,nm){const blob=new Blob([txt],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName(nm);document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);
toast(tr('save.save_exported_file_is_in_your',{file:esc(saveFileName(nm))}),'good');}
function exportSave(){if(!S||S.mode==='puzzle')return;save(true);saveDl(JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S:packSave(S)},null,1),S.name);}
// Any network on this device, straight from storage: the file wraps the saved text as it is, without loading it.
function exportSlot(id){const e=slotIdx().find(x=>x.id===id),raw=slotRaw(id);if(!e||raw==null)return;
if(id===UI.slot&&S&&!pzOn()){exportSave();return;}
(raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw)).then(t=>saveDl(`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},"exported":"${new Date().toISOString()}","S":${t}}`,e.name),()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));}
function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_is_not_valid_json')};let j;try{j=JSON.parse(txt);}catch(e){return {err:tr('save.that_file_is_not_valid_json')};}
const s=j&&j.app==='series-of-tubes'&&j.S?j.S:j;
if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links))return {err:tr('save.that_does_not_look_like_a')};
@ -64,7 +70,9 @@ function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_
return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};}
function importFile(file){if(!file)return;if(file.size>8e6){toast(tr('save.that_file_is_too_big_to'),'bad');return;}
const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}
UI.importing=r.s;openModal(`<div class="eyebrow">${tr('common.import_a_save')}</div><h2 style="font-size:26px">${tr('save.load_name',{name:esc(r.name)})}</h2><p class="tagline">${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}</p>${S&&UI.started&&!S.lost?`<p class="note" style="color:var(--bad)">${tr('save.this_replaces_name_export_it_first',{name:esc(S.name)})}</p>`:''}<div class="btns">${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}</div>`);};
UI.importing=r.s;openModal(`<div class="eyebrow">${tr('common.import_a_save')}</div><h2 style="font-size:26px">${tr('save.load_name',{name:esc(r.name)})}</h2><p class="tagline">${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}</p><p class="note">${tr('slots.it_joins_your_networks_on_this')}</p><div class="btns">${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}</div>`);};
rd.readAsText(file);}
function loadSave(){try{let t=localStorage.getItem('sot-save-v1');if(t&&t.startsWith(GZ))t=t===UI.gzRaw?UI.gzText:null;if(t){const s=JSON.parse(t);if(s&&s.v===1&&!s.lost)return s;}}catch(e){}return null;}
// This window's network, read synchronously (a compressed one was unpacked before boot). UI.loadBad: there, but unreadable.
function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null;
try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){}
UI.loadBad=true;return null;}

157
src/game/91-slots.js Normal file
View file

@ -0,0 +1,157 @@
/* ================= SAVE SLOTS =================
Several networks per browser, one per window. Each network (a slot) is its own key, sot-save-v1:<id>, plain JSON or
gzipped exactly like the old single save. A small index (sot-slots) describes them for the title screen, so listing
them never reads a save. A write goes to the slot first and to the index after, so the index never points at a save
that is not there yet; each write carries a sequence number (in the save and in its index entry), and a window never
writes over a newer one that another window saved. Each tab keeps its slot in sessionStorage: a reload continues it.
Only one window plays a slot at a time: a Web Lock where the browser has them, else a heartbeat key, sot-open:<id>. */
const SLOT_K='sot-save-v1:',SLOT_IX='sot-slots',SLOT_OLD='sot-save-v1',SLOT_HB='sot-open:',SLOT_SS='sot-slot',SLOT_MAIN='main';
const SLOT={sq:{},top:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''};
function slotRid(){try{const a=new Uint32Array(2);crypto.getRandomValues(a);return (a[0].toString(36)+a[1].toString(36)).slice(0,10);}catch(e){return (Date.now().toString(36)+(uidN++).toString(36)).slice(-10);}}
const WIN=slotRid();// this page load; a reload is a new window that takes its tab's slot back
const lsGet=k=>{try{return localStorage.getItem(k);}catch(e){return null;}};
const lsDel=k=>{try{localStorage.removeItem(k);}catch(e){}};
const ssGet=k=>{try{return sessionStorage.getItem(k);}catch(e){return null;}};
const ssSet=(k,v)=>{try{if(v==null)sessionStorage.removeItem(k);else sessionStorage.setItem(k,v);}catch(e){}};
const slotOkId=id=>typeof id==='string'&&/^[a-z0-9]{1,24}$/.test(id);
const slotRaw=id=>slotOkId(id)?lsGet(SLOT_K+id)??(id===SLOT_MAIN?lsGet(SLOT_OLD):null):null;
// ---------- the index: read like a save, never trusted ----------
function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null;
return {id:e.id,name:String(e.name==null?'':e.name).slice(0,24),asn:int(e.asn,0,4294967294,0),mode:['normal','sandbox','scenario'].includes(e.mode)?e.mode:'normal',
preset:typeof e.preset==='string'&&own(PRESETS,e.preset)?e.preset:'oncall',scn:typeof e.scn==='string'?e.scn.slice(0,60):null,day:int(e.day,0,1e7,0),
tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz,broken:!!e.broken};}
const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier});
function slotKeys(){const out=[];try{for(let i=0;i<localStorage.length;i++){const k=localStorage.key(i);if(k===SLOT_OLD)out.old=true;else if(k&&k.startsWith(SLOT_K)&&slotOkId(k.slice(SLOT_K.length)))out.push(k.slice(SLOT_K.length));}}catch(e){}return out;}
// An index entry rebuilt from the save itself. A compressed one can only be read in the background: slotFix() fills it in.
function slotFromKey(id){const raw=slotRaw(id)||'';if(raw.startsWith(GZ))return slotClean({id,gz:true,size:raw.length});
try{const s=JSON.parse(raw);if(s&&s.v===1&&typeof s.day==='number')return slotClean({id,...slotMeta(s,null),seq:s.sv&&s.sv.seq,at:s.sv&&s.sv.at,size:raw.length});}catch(e){}
return slotClean({id,size:raw.length,broken:true});}
/* The list of networks. scan also looks at the keys themselves (cheap: no save is read unless its entry is missing):
a save whose index write failed is added back, an entry whose save is gone is dropped. A damaged index is rebuilt. */
function slotIdx(scan){const raw=lsGet(SLOT_IX);let list=null;
// The same text as last time (every autosave): no need to parse and check it again.
if(!scan&&raw!=null&&raw===SLOT.ixRaw)return SLOT.ixList.map(e=>({...e}));
if(raw!=null)try{const j=JSON.parse(raw);if(j&&Array.isArray(j.slots))list=j.slots.map(slotClean).filter(Boolean);}catch(e){}
const bad=raw!=null&&!list;if(!list)list=[];{const seen=new Set();list=list.filter(e=>!seen.has(e.id)&&seen.add(e.id));}
if(scan||bad){const ks=slotKeys(),keys=new Set(ks);let ch=bad;const n=list.length;
if(ks.old&&list.some(e=>e.id===SLOT_MAIN))keys.add(SLOT_MAIN);
list=list.filter(e=>keys.has(e.id));if(list.length!==n)ch=true;
for(const id of keys)if(!list.some(e=>e.id===id)){list.push(slotFromKey(id));ch=true;}
if(ch)slotIdxPut(list);if(list.some(e=>e.gz&&!e.name&&!e.broken))slotFix(list);}
else if(raw!=null&&list.length){SLOT.ixRaw=raw;SLOT.ixList=list.map(e=>({...e}));}
return list;}
function slotIdxPut(list){const t=JSON.stringify({v:1,slots:list});try{localStorage.setItem(SLOT_IX,t);SLOT.ixRaw=t;SLOT.ixList=list.map(e=>({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}}
function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id);
gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return;
if(m)Object.assign(x,slotClean({...x,...m}));else x.broken=true;slotIdxPut(l);slotRefresh();});}}
const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at);
// ---------- one writer per slot ----------
// The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a
// minute, so it counts for longer. Tabs remove theirs when they close; a crashed one goes stale.
function slotHb(id){try{const h=JSON.parse(lsGet(SLOT_HB+id));return h&&typeof h.w==='string'&&isFinite(h.t)?h:null;}catch(e){return null;}}
const slotBusy=id=>{const h=slotHb(id);return !!h&&h.w!==WIN&&Date.now()-h.t<(h.h?180000:20000);};
function slotBeat(){const id=UI.slot;if(!id)return;const h=slotHb(id);
// Without Web Locks the heartbeat is the lock: a fresh one from another window means it took over.
if(h&&h.w!==WIN&&!SLOT.locks.has(id)&&Date.now()-h.t<20000){slotLost(id,'take');return;}
try{localStorage.setItem(SLOT_HB+id,JSON.stringify({w:WIN,t:Date.now(),h:document.visibilityState==='hidden'?1:0}));}catch(e){}}
function slotUnbeat(id){const h=slotHb(id);if(h&&h.w===WIN)lsDel(SLOT_HB+id);}
const LOCKS=()=>{try{const l=navigator.locks;return l&&typeof l.request==='function'?l:null;}catch(e){return null;}};
// cb(true) when this window may play the slot, cb(false) when another window has it. steal takes it over.
function slotClaim(id,steal,cb,n=4){const once=v=>{try{cb(v);}catch(e){console.error('[tubes] opening a network failed',e);}};
if(SLOT.locks.has(id)){slotBeatFor(id);once(true);return;}
const L=LOCKS();
if(L){let got=false;
L.request('sot-slot:'+id,steal?{steal:true}:{ifAvailable:true},lock=>{if(!lock){if(n>0&&(SLOT.rel.has(id)||!slotBusy(id)))setTimeout(()=>slotClaim(id,steal,cb,n-1),120);else once(false);return;}got=true;SLOT.rel.delete(id);
return new Promise(r=>{SLOT.locks.set(id,r);slotBeatFor(id);once(true);});})
.catch(()=>{SLOT.locks.delete(id);if(got)slotLost(id,'take');});// stolen: another window took over
return;}
if(!steal&&slotBusy(id)){once(false);return;}
slotBeatFor(id);once(true);}
function slotBeatFor(id){try{localStorage.setItem(SLOT_HB+id,JSON.stringify({w:WIN,t:Date.now(),h:0}));}catch(e){}}
function slotFree(id){if(UI.slot===id)return;slotUnbeat(id);const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r){SLOT.rel.add(id);r();}}
// Saves still compressing land before a slot is handed back.
function whenIdle(f){if(!UI.gzBusy&&!SLOT.gzQ.size)f();else SLOT.idle.push(f);}
function slotIdle(){if(UI.gzBusy||SLOT.gzQ.size)return;const l=SLOT.idle.splice(0);for(const f of l)try{f();}catch(e){console.error(e);}}
// ---------- writing ----------
// The sequence number rides along in the save, appended to the text (no second stringify).
const slotStamp=(txt,seq)=>txt.slice(0,-1)+',"sv":{"seq":'+seq+',"at":'+Date.now()+'}}';
// Throws when the browser refuses (quota): save() reports it. Returns false when it must not write.
function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false;
const list=slotIdx(),ent=list.find(e=>e.id===id);
if(ent&&ent.seq>(SLOT.sq[id]||0)){slotLost(id,'newer');return false;}
let k=SLOT_K+id;
try{localStorage.setItem(k,data);}
catch(e){// A migrated save the browser has no room to copy keeps living in the old key, as it always did.
if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;}
if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed
SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);
const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false}));
slotIdxPut(list);return true;}
function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}}
// ---------- opening, leaving, losing ----------
function slotIn(id,sv){const e=slotIdx().find(x=>x.id===id);UI.slot=id;ssSet(SLOT_SS,id);SLOT.no.delete(id);SLOT.top[id]=0;
SLOT.sq[id]=Math.max(sv&&isFinite(sv.seq)?+sv.seq:0,e?e.seq:0);}
function slotNew(){const id=slotRid();UI.slot=id;ssSet(SLOT_SS,id);SLOT.sq[id]=0;SLOT.no.delete(id);slotClaim(id,true,()=>{});return id;}
// Leave this window's network (saved first); the slot is free for other windows once its last save has landed.
function slotLeave(){const id=UI.slot;if(!id)return;save(true);UI.slot=null;UI.pzKeep=null;ssSet(SLOT_SS,null);whenIdle(()=>slotFree(id));}
// Read a slot and play it. A save that cannot be read or loaded is marked damaged and kept, so it can still be exported.
function slotOpen(id,steal,done){if(!slotIdx(true).some(e=>e.id===id)){showTitle();toast(tr('slots.that_network_is_gone'),'bad');return;}
slotClaim(id,!!steal,ok=>{if(!ok){slotBusyModal(id);return;}
const go=t=>{let s=null;try{s=JSON.parse(t);}catch(e){}
if(!s||s.v!==1||s.lost){slotBroke(id);return;}const sv=s.sv;delete s.sv;
const prev=S;try{S=migrate(s);compute();}catch(e){console.error('[tubes] loading a network failed',e);S=prev;slotBroke(id);return;}
if(UI.slot&&UI.slot!==id){const nw=S;S=prev;slotLeave();S=nw;}
slotIn(id,sv);gameResume();if(done)done();};
const raw=slotRaw(id);if(raw==null){slotFree(id);slotDrop(id);showTitle();toast(tr('slots.that_network_is_gone'),'bad');return;}
if(raw.startsWith(GZ)){if(raw===UI.gzRaw)go(UI.gzText);else gunzip(raw).then(go,()=>slotBroke(id));}else go(raw);});}
function slotBroke(id){const l=slotIdx(),e=l.find(x=>x.id===id);if(e){e.broken=true;slotIdxPut(l);}
if(UI.slot===id){UI.slot=null;ssSet(SLOT_SS,null);}slotFree(id);
S=null;R=emptyR();UI.started=false;UI.sel=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();toast(tr('loop.your_saved_game_could_not_be'),'bad');}
function slotDrop(id){if(!slotOkId(id))return;SLOT.no.add(id);lsDel(SLOT_K+id);if(id===SLOT_MAIN)lsDel(SLOT_OLD);slotUnbeat(id);
const l=slotIdx();slotIdxPut(l.filter(e=>e.id!==id));if(UI.slot===id){UI.slot=null;ssSet(SLOT_SS,null);}}
/* Another window took this network over, or saved a newer version of it: this one stops writing and says so calmly. */
function slotLost(id,why){if(UI.slot!==id)return;SLOT.no.add(id);UI.slot=null;ssSet(SLOT_SS,null);SLOT.gzQ.delete(id);if(why==='gone')slotUnbeat(id);
const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r)r();
const s=pzOn()?UI.pzKeep:S,name=s?s.name:'';
if(pzOn()){UI.pzKeep=null;UI.pzFrom='title';toast(tr('slots.name_moved_to_another_window_toast',{name:esc(name)}),'bad');return;}
gameClear();if(why==='gone'){showTitle();toast(tr('slots.name_was_deleted_in_another_window',{name:esc(name)}),'bad');}else slotLostModal(id,name,why);}
// ---------- the legacy single save becomes the first slot ----------
/* Read old, write new, read it back, then add it to the index. The old key stays as a fallback until the slot's next
save lands; if the browser has no room for a copy, the network keeps living in the old key (slotRaw reads it). */
function slotMigrate(cb){const raw=lsGet(SLOT_OLD);
if(raw==null||slotIdx(true).some(e=>e.id===SLOT_MAIN)){cb();return;}
const done=s=>{if(s&&s.lost){cb();return;}
let ok=false;try{localStorage.setItem(SLOT_K+SLOT_MAIN,raw);ok=localStorage.getItem(SLOT_K+SLOT_MAIN)===raw;}catch(e){}
if(!ok)lsDel(SLOT_K+SLOT_MAIN);
const l=slotIdx();l.push(slotClean({id:SLOT_MAIN,...(s?slotMeta(s,null):{}),seq:0,at:Date.now(),size:raw.length,gz:raw.startsWith(GZ),broken:!s}));slotIdxPut(l);if(!s)UI.bootBroken=true;cb();};
if(!raw.startsWith(GZ)){let s=null;try{s=JSON.parse(raw);}catch(e){}done(s&&s.v===1?s:null);return;}
if(!gzOk()){done(null);return;}
gunzip(raw).then(t=>{UI.gzRaw=raw;UI.gzText=t;let s=null;try{s=JSON.parse(t);}catch(e){}done(s&&s.v===1?s:null);},()=>done(null));}
/* Before the game boots: migrate, then pick this tab's network. A reload continues the tab's own slot; a new tab with
exactly one network continues it as before; with more, the title screen lists them. A compressed save is unpacked
here, so loadSave() stays synchronous for everything else. */
function slotBoot(go){slotMigrate(()=>{const list=slotIdx(true),mine=ssGet(SLOT_SS);
let id=list.some(e=>e.id===mine&&!e.broken)?mine:null;if(!id&&mine)ssSet(SLOT_SS,null);
const auto=!id&&list.length===1&&!list[0].broken&&!slotBusy(list[0].id)?list[0].id:null;
if(!id&&!auto){go();return;}
slotClaim(id||auto,false,ok=>{const w=id||auto;
if(!ok){if(id){ssSet(SLOT_SS,null);UI.bootBusy=id;}go();return;}
UI.slot=w;const raw=slotRaw(w);
if(raw&&raw.startsWith(GZ)&&raw!==UI.gzRaw){if(!gzOk()){go();return;}gunzip(raw).then(t=>{UI.gzRaw=raw;UI.gzText=t;go();},e=>{console.error('[tubes] unpacking the save failed',e);go();});}
else go();});});}
// ---------- other windows ----------
const BC=(()=>{try{return typeof BroadcastChannel==='function'?new BroadcastChannel('sot-slots'):null;}catch(e){return null;}})();
if(BC)BC.onmessage=({data:m})=>{if(!m||typeof m!=='object'||!slotOkId(m.id))return;
if(m.t==='focus'&&UI.slot===m.id){try{window.focus();}catch(e){}toast(tr('slots.here_it_is_name',{name:esc(S?S.name:'')}),'goal');}
// Asked to hand over: save what we have, wait for it to land, then step aside and say so.
if(m.t==='take'&&UI.slot===m.id){save(true);whenIdle(()=>{slotLost(m.id,'take');try{BC.postMessage({t:'gave',id:m.id});}catch(e){}});}
if(m.t==='gave'&&SLOT.wait&&SLOT.wait.id===m.id)SLOT.wait.go();
if(m.t==='gone')slotLost(m.id,'gone');};
addEventListener('storage',e=>{const k=e.key;if(!k)return;const id=UI.slot;
if(id&&k===SLOT_HB+id&&e.newValue){let h=null;try{h=JSON.parse(e.newValue);}catch(_){}if(h&&h.w!==WIN)slotLost(id,'take');}
else if(id&&k===SLOT_K+id&&e.newValue==null)slotLost(id,'gone');// deleted in another window: never written back
else if(id&&k===SLOT_IX){const x=slotIdx().find(y=>y.id===id);if(x&&x.seq>(SLOT.sq[id]||0))slotLost(id,'newer');}
if(k===SLOT_IX||k.startsWith(SLOT_HB))slotRefresh();});
addEventListener('pagehide',()=>{if(UI.slot)slotUnbeat(UI.slot);});
addEventListener('pageshow',e=>{if(e.persisted)slotBeat();});
if(!window.__TUBES_TEST__)setInterval(slotBeat,5000);

View file

@ -8,20 +8,20 @@ function homePick(){const cs=Object.keys(CITY).filter(homeOk),cur=START5.include
// A dropdown can't wrap, so long names (Yuzhno-Sakhalinsk) get cut on phones: the line above it says the whole name.
const homeWhat=()=>START5.includes(UI.startCity)?trn('title.n_more_cities_with_transit',Object.keys(CITY).filter(c=>homeOk(c)&&!START5.includes(c)).length):`${esc(CITY[UI.startCity].name)} · ${esc(REG[CITY[UI.startCity].reg])}`;
function showTitle(){
const sv=loadSave();
const list=slotIdx(true),top=slotTop(list),many=list.length>1||(list.length===1&&list[0]!==top);
if(UI.nm==null)UI.nm=randomNetworkName();
const starts=[['fra',tr('title.crossroads_of_europe_de_kicks_ix')],['nyc',tr('title.huge_eyeball_market_pricey')],['sin',tr('title.asia_hub_great_peering_far_from')],['sao',tr('title.big_hungry_market_few_providers')],['syd',tr('title.hard_mode_pricey_everything')]];
openModal(`<div class="title-art"><svg width="74" height="74" viewBox="0 0 74 74" aria-hidden="true"><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#1E2640" stroke-width="16" stroke-linecap="round"/><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#FFD23F" stroke-width="9" stroke-linecap="round"/><circle cx="58" cy="16" r="11" fill="#FF4F9A" stroke="#1E2640" stroke-width="4"/><circle cx="21" cy="44" r="3" fill="#fff"/><circle cx="30" cy="27" r="3" fill="#fff"/></svg>
<h1>Series<br>of <span>Tubes</span></h1></div>
<p class="tagline">${tr('title.build_an_internet_lay_fiber_between')}</p>${plugHtml(false)}${isPhone()?installRow():''}
${sv?`<div class="btns" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(sv.name),date:dateStr(sv.day)}),'cont',{},'pink big')}</div>`:''}
${top?`<div class="btns" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}</div>`:''}
${many?slotsHtml():''}
${doorsHtml()}
<label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off">${btn(tr('common.another_one'),'randomName',{},'ghost sm')}</div>
<label class="f" id="homeLbl">${tr('title.pick_your_home_city')}</label><div class="starts homes">${starts.map(([c,d])=>`<button class="start ${UI.startCity===c?'on':''}" data-city="${c}" data-act="pickStart" data-args='{"city":"${c}"}'><b>${CITY[c].name}</b><span>${d}</span></button>`).join('')}<label class="start own ${START5.includes(UI.startCity)?'':'on'}" for="homeSel"><b>${tr('title.anywhere_else')}</b><span id="homeWhat">${homeWhat()}</span>${homePick()}</label></div>
<label class="f" for="langTitle">${tr('common.language')}</label>${langPick('langTitle')}
<div class="btns cta tcta" style="margin-top:16px">${btn(sv?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
<div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
$('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;});
if(sv){S=migrate(sv);compute();}
}
// "What's new": shown once to returning players after an update, or on demand.
function whatsNew(returning,force){

View file

@ -0,0 +1,37 @@
/* "Your networks" on the title screen: drawn from the index alone, so it stays instant however big the saves are. */
function slotAgo(t){const m=Math.max(0,Math.round((Date.now()-t)/60000));
return m<1?tr('slots.just_now'):m<60?trn('notifications.n_min_ago',m):m<1440?trn('slots.n_h_ago',Math.round(m/60)):trn('peering_inbox.n_day_ago',Math.round(m/1440));}
const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?'🏖️':(PRESETS[e.preset]||PRESETS.oncall).i;
// The network to continue: the most recent one that is not open in another window (or damaged).
function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;}
function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete');
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);
return bits.filter(Boolean).join(' · ');}
function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network'));
const tag=busy?`<span class="tag">${tr('slots.open_in_another_window')}</span>`:top?`<span class="tag">▶ ${tr('slots.continue')}</span>`:'';
return `<div class="slot${top?' top':''}${busy?' busy':''}${e.broken?' broken':''}" data-slot="${e.id}"><button class="slot-go" data-act="${e.broken?'slotMenu':'cont'}" data-args='{"id":"${e.id}"}'><i aria-hidden="true">${slotIcon(e)}</i><span class="sn">${tag}<b>${nm}</b><small>${slotLine(e)}</small></span><span class="sm">${e.broken?'':`<em>${fmt$(e.cash)}</em>`}<small>${e.at?slotAgo(e.at):''}</small></span></button><button class="slot-more" data-act="slotMenu" data-args='{"id":"${e.id}"}' aria-label="${tr('slots.more_for_name',{name:nm})}">⋯</button></div>`;}
function slotListHtml(){const list=slotByAt(slotIdx()),top=slotTop(list);
return list.map(e=>slotRow(e,e===top)).join('');}
function slotsHtml(){const list=slotIdx(true);if(!list.length)return '';
SLOT.html=slotListHtml();return `<label class="f">${tr('slots.your_networks')}</label><div class="slots" id="slotList">${SLOT.html}</div>`;}
// Another window saved, opened or closed a network: the list follows (only when it is on screen and changed).
function slotRefresh(){const el=$('slotList');if(!el||UI.started)return;const h=slotListHtml();if(h!==SLOT.html){SLOT.html=h;el.innerHTML=h;}}
function slotMenuHtml(id){const e=slotIdx().find(x=>x.id===id);if(!e)return '';const nm=esc(e.name||tr('common.unnamed_network'));
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">${slotIcon(e)} ${slotLine(e)}</div><h2 style="font-size:26px">${nm}</h2></div><button class="x" data-act="slotBack" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${e.at?tr('slots.last_played_ago',{ago:slotAgo(e.at)}):''}${e.size?' · '+tr('slots.size_on_this_device',{size:slotSize(e.size)}):''}</p>
<div class="menu-list">${e.broken?'':btn(tr('slots.continue_this_network'),'cont',{id},'pink big')}${btn(tr('game_and_settings.export_save_download_a_file'),'slotExport',{id},'')}${btn(tr('slots.delete_this_network'),'slotDel',{id},'red')}${btn(tr('common.back'),'slotBack',{},'ghost')}</div>`;}
const slotSize=n=>n>=1e6?(n/1e6).toFixed(1)+' MB':Math.max(1,Math.round(n/1e3))+' kB';
function slotBusyModal(id){const e=slotIdx().find(x=>x.id===id),nm=esc(e&&e.name||tr('common.unnamed_network'));
openModal(`<div class="eyebrow">🪟 ${tr('slots.two_windows_one_network')}</div><h2 style="font-size:26px">${tr('slots.name_is_open_in_another_window',{name:nm})}</h2>
<p class="tagline">${tr('slots.only_one_window_can_play_a')}</p><div class="btns">${btn(tr('slots.switch_to_that_window'),'slotSwitch',{id},'pink big')}${btn(tr('slots.take_over_here'),'slotTake',{id},'big')}${btn(tr('slots.your_networks'),'slotBack',{},'ghost')}</div>`);}
// Shown in the window that stepped aside: calm, and nothing here writes.
function slotLostModal(id,name,why){const nm=esc(name||tr('common.unnamed_network'));
openModal(`<div class="eyebrow">🪟 ${tr('slots.two_windows_one_network')}</div><h2 style="font-size:26px">${why==='newer'?tr('slots.name_was_saved_in_another_window',{name:nm}):tr('slots.name_opened_in_another_window',{name:nm})}</h2>
<p class="tagline">${why==='newer'?tr('slots.this_window_stopped_saving_so_it'):tr('slots.this_window_stepped_aside_so_the')}</p><div class="btns">${btn(why==='newer'?tr('slots.load_the_newest_version'):tr('slots.take_it_back_here'),why==='newer'?'cont':'slotTake',{id},'pink big')}${btn(tr('slots.your_networks'),'slotBack',{},'ghost big')}</div>`);}
const slotOthers=()=>slotIdx().filter(e=>e.id!==UI.slot);
// Out of room: which other networks take space, with export and delete right there.
function slotSpaceHtml(){const l=slotOthers().sort((a,b)=>b.size-a.size);
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">💾 ${tr('slots.storage_on_this_device')}</div><h2 style="font-size:26px">${tr('slots.free_up_space')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('slots.your_other_networks_share_this_browser')}</p>
${l.length?l.map(e=>`<div class="ibx space"><div class="grow"><b>${slotIcon(e)} ${esc(e.name||tr('common.unnamed_network'))}</b><div class="meta">${slotSize(e.size)}${e.at?' · '+slotAgo(e.at):''}</div></div><div class="btns">${btn(tr('common.export_save'),'slotExport',{id:e.id},'ghost sm')}${btn(tr('slots.delete'),'slotDel',{id:e.id,back:'space'},'red sm')}</div></div>`).join(''):`<p class="note">${tr('slots.no_other_networks_here')}</p>`}
<div class="btns" style="margin-top:10px">${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}</div>`;}

View file

@ -21,4 +21,4 @@ function showHelp(){
</dl><h3 style="margin:16px 0 0">${tr('help.want_to_know_how_it_really')}</h3>${plugHtml(true)}${chatHtml()}${issueHtml()}</dl><div class="btns" style="margin-top:14px">${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}</div><div class="btns" style="margin-top:6px">${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}</div>`);
}
function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`<div class="btns" style="margin-top:8px">${btn(tr('help.share_my_network'),'share',{},'pink')}</div><p class="meta" style="margin:12px 0 0">${tr('help.you_built_a_cartoon_internet_now')}</p>${plugHtml(true)}`);},0);openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">${tr('help.you_re_a_tier_1')}</h1><p class="tagline">${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:S.day,n:S.stats.incidents})}</p>${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');}
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">${tr('common.bankrupt')}</h1><p class="tagline">${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}</p>${btn(tr('common.try_again'),'newgame',{},'pink big')}`);try{localStorage.removeItem('sot-save-v1');}catch(e){}}
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">${tr('common.bankrupt')}</h1><p class="tagline">${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}</p>${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}}

View file

@ -11,5 +11,5 @@ let PD={t:0,b:null};
document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true);
function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true;
if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;}
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});

View file

@ -33,16 +33,18 @@ function boot(data){
try{UI.muted=localStorage.getItem('sot-mute')==='1';UI.anim=localStorage.getItem('sot-anim')||'auto';}catch(e){}
applyAnim();
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
else{const sv=loadSave();
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){S=null;UI.started=false;try{localStorage.setItem('sot-save-broken',JSON.stringify(sv));localStorage.removeItem('sot-save-v1');}catch(e2){}}}
if(okSave){UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv;
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
if(okSave){slotIn(UI.slot,stamp);UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}
if(!whatsNew(true))toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}
else{showTitle();whatsNew(false);if(sv||UI.gzBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}}
// A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted.
else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot);
else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}}
renderHUD();renderLeft();
window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}}));
if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);}
}
gzBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));
slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));

View file

@ -1798,14 +1798,9 @@
"game_and_settings.import_a_save_from_a_file":"Import a save <small>from a file</small>",
"game_and_settings.import_failed_that_save_is_damaged":"<b>Import failed.</b><br>That save is damaged and could not be loaded. Your current game is untouched.",
"game_and_settings.name_and_everything_it_owns_will":"{name} and everything it owns will be deleted. This cannot be undone.",
"game_and_settings.name_will_be_replaced_export_it":"{name} will be replaced. Export it from the menu first if you want to keep it.",
"game_and_settings.scenarios_amp_weekly_challenge":"Scenarios &amp; weekly challenge",
"game_and_settings.share_your_network_image_card":"Share your network <small>image card</small>",
"game_and_settings.start_a_new_network":"Start a new network?",
"game_and_settings.start_name":"Start {name}?",
"game_and_settings.start_the_challenge":"Start the challenge",
"game_and_settings.start_the_scenario":"Start the scenario",
"game_and_settings.start_the_weekly_challenge":"Start the weekly challenge?",
"game_and_settings.welcome_back_name_imported_and_saved":"<b>Welcome back, {name}.</b><br>Imported and saved on this device.",
"game_and_settings.your_game_saves_itself_every_few":"Your game saves itself every few seconds on this device.",
"geography_and_latency.a_to_b":"{a} to {b}",
@ -3281,7 +3276,6 @@
"save.that_network_went_bankrupt_it_cannot":"That network went bankrupt. It cannot be brought back, only mourned.",
"save.that_save_has_a_pop_in":"That save has a POP in a city this version does not know ({city}).",
"save.this_browser_is_not_letting_the":"<b>Your game is not being saved.</b> This browser is not letting the game store anything (a private window, or site data turned off). Export a save to keep your network.",
"save.this_replaces_name_export_it_first":"This replaces {name}. Export it first if you want to keep it.",
"save.your_network_is_too_big_to":"<b>Your game is not being saved.</b> Your network has grown too big for this browser's storage. Export a save now and keep the file: it is your backup.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Goal:</b> {goal} · <b>Time:</b> {d} days · start in {city}",
"scenario_progress.goal_was_not_reached_in_d":"{goal} was not reached in {d} days. Keep playing this network as free play, or try again.",
@ -3418,6 +3412,47 @@
"sites_peering_caches.your_account_manager_found_the_order":"<b>Your account manager found the order under a desk.</b><br>It is a month closer.",
"sites_peering_caches.your_account_manager_is_on_paternity":"<b>Your account manager is on paternity leave.</b><br>His replacement is also on paternity leave.",
"sites_peering_caches.your_ticket_was_merged_into_another":"<b>Your ticket was merged into another ticket.</b><br>That ticket was closed as a duplicate of yours.",
"slots.continue":"Continue",
"slots.continue_this_network":"Continue this network",
"slots.damaged_export_or_delete":"Damaged: export it or delete it",
"slots.delete":"Delete",
"slots.delete_forever":"Delete forever",
"slots.delete_name":"Delete {name}?",
"slots.delete_this_network":"Delete this network",
"slots.free_up_space":"Free up space",
"slots.here_it_is_name":"<b>Here it is: {name}.</b><br>This is the window you were looking for.",
"slots.it_is_open_in_another_window":"It is open in another window right now, and that window will stop too.",
"slots.it_joins_your_networks_on_this":"It joins your networks on this device. The one you are playing stays saved.",
"slots.just_now":"just now",
"slots.keep_it":"Keep it",
"slots.last_played_ago":"Last played {ago}",
"slots.load_the_newest_version":"Load the newest version",
"slots.more_for_name":"More for {name}",
"slots.n_h_ago":{"one":"{n} h ago","other":"{n} h ago"},
"slots.name_is_open_in_another_window":"{name} is open in another window",
"slots.name_is_waiting_in_your_other":"<b>{name} is waiting in your other window.</b><br>Switch to it to keep playing.",
"slots.name_moved_to_another_window_toast":"<b>{name} is now played in another window.</b><br>This puzzle carries on; your network is safe over there.",
"slots.name_opened_in_another_window":"{name} opened in another window",
"slots.name_was_deleted_in_another_window":"<b>{name} was deleted in another window.</b>",
"slots.name_was_saved_in_another_window":"{name} was saved in another window",
"slots.no_other_networks_here":"No other networks on this device. Exporting a save is your best backup.",
"slots.only_one_window_can_play_a":"One network, one NOC: only one window can play it at a time, so two copies never overwrite each other.",
"slots.open_in_another_window":"Open in another window",
"slots.rename":"Rename",
"slots.rename_your_network":"Rename your network",
"slots.renamed_to_name":"<b>Renamed.</b><br>Say hello to {name}.",
"slots.size_on_this_device":"{size} on this device",
"slots.storage_on_this_device":"Storage on this device",
"slots.switch_to_that_window":"Switch to that window",
"slots.take_it_back_here":"Take it back here",
"slots.take_over_here":"Take over here",
"slots.that_network_is_gone":"<b>That network is gone.</b><br>It was deleted, maybe in another window.",
"slots.this_window_stepped_aside_so_the":"You took it over in another window, so this one stepped aside and stopped saving. Nothing was lost.",
"slots.this_window_stopped_saving_so_it":"A newer version was saved in another window, so this one stopped saving instead of overwriting it.",
"slots.two_windows_one_network":"Two windows, one network",
"slots.your_networks":"Your networks",
"slots.your_networks_switch_or_start_another":"Your networks <small>switch, or start another</small>",
"slots.your_other_networks_share_this_browser":"Your other networks share this browser's storage. Export the ones you want to keep, then delete them here to make room.",
"sold_out.a_hyperscaler_bought_every_wave_of":"A hyperscaler bought every wave of that size on this route last week.",
"sold_out.not_big_enough_yet_list":"Not big enough yet: {list}",
"sold_out.only_peers_over_pnis_and_only":"Only peers over PNIs, and only with networks it considers important",

View file

@ -154,3 +154,24 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi
.gl dd{margin:2px 0 0;color:var(--ink2);line-height:1.45;font-size:13px}
.kbd{display:inline-block;border:2px solid var(--ink);border-radius:6px;padding:0 5px;font-weight:900;font-size:11px;background:var(--soft)}
/* "Your networks" on the title screen: one big tap target per network, a small ⋯ for export and delete. */
.slots{display:flex;flex-direction:column;gap:7px;margin-bottom:6px;max-height:min(46vh,330px);overflow:auto;padding:2px 2px 5px}
.slot{display:flex;align-items:stretch;border:3px solid var(--ink);border-radius:16px;background:var(--paper);box-shadow:0 4px 0 var(--ink);flex:none;transition:transform .08s ease,box-shadow .08s ease}
.slot:active{transform:translateY(3px);box-shadow:0 1px 0 var(--ink)}
.slot.top{background:#FFE3F0;border-color:var(--me);box-shadow:0 4px 0 var(--me)}
.slot.busy{background:var(--soft);border-style:dashed}
.slot.broken{opacity:.75;border-style:dashed}
.slot-go{flex:1;min-width:0;display:flex;align-items:center;gap:10px;background:none;border:0;padding:8px 6px 8px 11px;font:inherit;color:inherit;text-align:left;cursor:pointer;min-height:52px}
.slot-go>i{font-style:normal;font-size:26px;line-height:1;flex:none}
.slot .sn{flex:1;min-width:0;display:flex;flex-direction:column}
.slot .sn b{font-family:var(--display);font-size:18px;line-height:1.1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.slot .sn small,.slot .sm small{font-size:12px;color:var(--ink2);line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.slot .tag{align-self:flex-start;font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em;color:var(--me);line-height:1.2}
.slot.busy .tag{color:var(--ink2)}
.slot .sm{flex:none;display:flex;flex-direction:column;align-items:flex-end;text-align:right}
.slot .sm em{font:800 15px var(--display);font-style:normal}
.slot-more{flex:none;width:44px;border:0;border-left:2px dashed var(--line);background:none;font:900 22px var(--display);color:var(--ink);cursor:pointer;border-radius:0 13px 13px 0}
.slot-more:hover,.slot-go:hover{background:rgba(255,79,154,.06)}
.slot-go:focus-visible,.slot-more:focus-visible{outline:3px solid #FF4F9A;outline-offset:-3px}
.ibx.space{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.ibx.space .btns{margin:0}
h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px}

View file

@ -58,6 +58,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar
#modal .cta{position:sticky;bottom:calc(-16px - env(safe-area-inset-bottom,0px));z-index:1;background:var(--paper);margin:12px -16px 0 !important;padding:10px 16px calc(10px + env(safe-area-inset-bottom,0px));border-top:2px solid var(--line)}
.title-art h1{font-size:34px}.title-art svg{width:54px;height:54px}
.tagline{font-size:13.5px;margin:8px 0 10px}
.slots{max-height:38vh}.slot-go{padding:7px 4px 7px 9px;gap:8px}.slot-go>i{font-size:22px}.slot .sn b{font-size:16px}.slot .sm em{font-size:13.5px}.slot .sn small,.slot .sm small{font-size:11.5px}
.door{padding:7px 9px 6px}.door i{font-size:22px}.door b{font-size:16px}.door span{font-size:11.5px}
.presets{grid-template-columns:1fr;gap:6px}
.preset{display:grid;grid-template-columns:auto 1fr;column-gap:9px;align-items:center;padding:6px 10px}

View file

@ -100,7 +100,7 @@ test('networks in its own regions buy their transit from it, so a PNI with it re
test('a game saved before it existed gets the courtesy route to it', () => {
const a = load();
a.ev("ACT.start({});S.day=40;S.seen=S.seen.filter(x=>x!=='gsl');save(true)");
const b = load({ storage: { 'sot-save-v1': a.ev("localStorage.getItem('sot-save-v1')") } });
const b = load({ storage: { 'sot-save-v1': a.ev("slotRaw(UI.slot)") } });
assert.equal(b.ev("S.grace.nets.includes('gsl')"), true);
assert.equal(b.ev("S.seen.includes('gsl')"), true);
assert.equal(b.ev("R.reachable.gsl"), true, 'reachable through the courtesy route until you find your own way');

View file

@ -27,6 +27,9 @@ function load(opts = {}) {
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; }; }
// opts.browser (from browser()): windows of one browser share localStorage, its storage events, a broadcast
// channel and Web Locks, like real tabs; opts.tab is one tab's sessionStorage, which survives a reload.
if (opts.browser) opts.browser.attach(window, opts.tab || new Map(), opts);
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage });
// A non-English game: jsdom does not fetch the dictionary script, so register it up front.
@ -62,4 +65,44 @@ function seed(ev, n) {
ev(`if(window.__reseed)__reseed(${n});else Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`);
}
module.exports = { load, seed };
// A fake browser for several windows at once (see opts.browser). Storage events, broadcast messages and lock
// hand-overs arrive asynchronously, as in browsers: await settle() or flush() before checking them.
function browser({ locks = true, channel = true } = {}) {
const ls = new Map(), wins = new Set(), held = new Map(), log = [];
const later = (f) => setTimeout(f, 0);
const store = (map, win, shared) => {
const fire = (key, oldValue, newValue) => { if (shared) for (const w of wins) if (w !== win && !w.closed) later(() => { try { w.dispatchEvent(new w.StorageEvent('storage', { key, oldValue, newValue })); } catch (e) {} }); };
return {
getItem: (k) => { if (shared) log.push(['get', String(k)]); return map.has(String(k)) ? map.get(String(k)) : null; },
setItem: (k, v) => { if (win.closed) return; k = String(k); v = String(v); if (shared && b.quota && k.startsWith('sot-save-v1:') && v.length > b.quota) { const e = new win.Error('full'); e.name = 'QuotaExceededError'; throw e; } const o = map.has(k) ? map.get(k) : null; map.set(k, v); if (shared) { log.push(['set', k]); fire(k, o, v); } },
removeItem: (k) => { k = String(k); if (!map.has(k)) return; const o = map.get(k); map.delete(k); if (shared) fire(k, o, null); },
key: (i) => [...map.keys()][i] ?? null,
get length() { return map.size; },
clear: () => map.clear(),
};
};
const b = { ls, wins, log, quota: 0,
attach(win, tab, opts) {
wins.add(win);
Object.defineProperty(win, 'localStorage', { configurable: true, get: () => store(ls, win, true) });
Object.defineProperty(win, 'sessionStorage', { configurable: true, get: () => store(tab, win, false) });
if (channel) win.BroadcastChannel = class { constructor(name) { this.name = name; (b.chans = b.chans || []).push({ c: this, win }); }
postMessage(data) { const msg = JSON.parse(JSON.stringify(data)); for (const o of b.chans) if (o.c !== this && o.c.name === this.name && !o.win.closed && o.c.onmessage) later(() => o.c.onmessage({ data: msg })); }
close() {} };
if (locks) Object.defineProperty(win.navigator, 'locks', { configurable: true, value: {
request(name, o, cb) {
const cur = held.get(name);
if (cur && !cur.win.closed && !o.steal) { if (o.ifAvailable) return win.Promise.resolve().then(() => cb(null)); return win.Promise.reject(new win.Error('busy')); }
if (cur) { held.delete(name); cur.reject(new win.DOMException('stolen', 'AbortError')); }
return new win.Promise((res, rej) => { const me = { win, reject: rej }; held.set(name, me);
win.Promise.resolve().then(() => cb({ name })).then((v) => { if (held.get(name) === me) held.delete(name); res(v); }, rej); });
} } });
},
// A tab closing: its locks go with it.
close(win) { win.closed = true; for (const [k, v] of held) if (v.win === win) held.delete(k); wins.delete(win); },
};
return b;
}
const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); });
module.exports = { load, seed, browser, flush };

View file

@ -122,7 +122,7 @@ test('picking a language saves the choice and the game, then reloads', () => {
ev('ACT.start({});dayTick()');
ev("ACT.langSet({v:'it'})");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
assert.ok(ev("localStorage.getItem('sot-save-v1')"));
assert.ok(ev("slotRaw(UI.slot)"));
ev("ACT.langSet({v:'klingon'})");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
});
@ -130,7 +130,7 @@ test('picking a language saves the choice and the game, then reloads', () => {
test('a scenario started in English shows its Italian name after switching', () => {
const en = load();
en.ev("ACT.startScn({id:'stg'});save()");
const { ev } = load({ lang: 'it', storage: { 'sot-save-v1': en.ev("localStorage.getItem('sot-save-v1')") } });
const { ev } = load({ lang: 'it', storage: { 'sot-save-v1': en.ev("slotRaw(UI.slot)") } });
const name = ev("SCN.find(x=>x.id==='stg').n");
assert.notEqual(name, en.ev("SCN.find(x=>x.id==='stg').n"));
assert.ok(ev("document.getElementById('hAsn').textContent").includes(name));

View file

@ -43,7 +43,7 @@ test('#5 export writes a file and import restores it, with checks', () => {
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');
assert.equal(ev("JSON.parse(slotRaw(UI.slot)).name"), 'Export Me', 'saved on this device');
ev("showHelp()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Export save.*Import a save/);
assert.deepEqual(errors, []);
@ -95,7 +95,7 @@ test('the network name opens a menu with save, load and start over', () => {
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.equal(ev("!!slotRaw(UI.slot)&&JSON.parse(slotRaw(UI.slot)).day>0"), false);
assert.deepEqual(errors, []);
});
@ -1052,7 +1052,7 @@ test('#104 declining a loan offer clears the bank badge while paused', () => {
assert.equal(ev("$('hBank').hidden"), false);
ev("ACT.declineLoan({id:S.loanOffers[0].id})");
assert.equal(ev("$('hBank').hidden"), true, 'badge gone without a new day');
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).loanOffers.length"), 0, 'saved right away');
assert.equal(ev("JSON.parse(slotRaw(UI.slot)).loanOffers.length"), 0, 'saved right away');
assert.deepEqual(errors, []);
});

View file

@ -27,7 +27,7 @@ test('changing the dropdown in Settings switches language and keeps the game', (
const { ev, errors } = load();
ev("ACT.start({});dayTick();ACT.settings();const s=document.getElementById('langSel');s.value='fr';s.dispatchEvent(new Event('change',{bubbles:true}))");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'fr');
assert.ok(ev("localStorage.getItem('sot-save-v1')"), 'saved before reloading');
assert.ok(ev("slotRaw(UI.slot)"), 'saved before reloading');
assert.deepEqual(errors, []);
});

View file

@ -31,7 +31,7 @@ test('#186 on a phone, play after pause resumes at half speed, not the old game\
test('#186 a saved game still continues at the speed it was saved at', () => {
const a = load();
a.ev("ACT.start({});ACT.speed({v:4});save(true)");
const b = load({ storage: { 'sot-save-v1': a.ev("localStorage.getItem('sot-save-v1')") } });
const b = load({ storage: { 'sot-save-v1': a.ev("slotRaw(UI.slot)") } });
assert.equal(b.ev('UI.speed'), 4);
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);

View file

@ -47,7 +47,7 @@ test('Rackstar boxes survive save migration and appear on phone peering panels i
const { dom, ev, errors } = load(lang === 'en' ? {} : { lang });
setup(ev);
ev('window.matchMedia=()=>({matches:true})');
ev("S.pops.fra.bb={d:10/NSH.cfl};compute();ACT.cache({city:'fra',net:'cfl'});save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()");
ev("S.pops.fra.bb={d:10/NSH.cfl};compute();ACT.cache({city:'fra',net:'cfl'});save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
assert.equal(ev("S.caches.filter(x=>x.net==='cfl').length"), 1, lang);
assert.ok(ev('R.useCache[S.caches[0].id]') > 0, lang);
for (const [width, height] of [[360, 800], [800, 360]]) {
@ -221,7 +221,7 @@ test('Amsterdam has FRIES-IX, with free 10G and 100G ports and paid larger ports
const txt = ev("document.getElementById('panelBody').textContent");
assert.match(txt, /FRIES-IX/); assert.match(txt, /HAMS-IX/);
assert.match(ev("ixBlock('ams~3',true)"), /LAG member <small>free/);
ev("save();restored=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));");
ev("save();restored=migrate(JSON.parse(slotRaw(UI.slot)));");
assert.equal(ev("restored.ixp['ams~3']"), 1, '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()");

View file

@ -10,7 +10,7 @@ const root = path.join(__dirname, '..');
function playedGame() {
const a = load();
a.ev("ACT.start({});ACT.launchBB({city:'fra'});for(let i=0;i<25;i++)dayTick();UI.speed=2;save()");
return { a, saved: a.ev("localStorage.getItem('sot-save-v1')"), day: a.ev('S.day') };
return { a, saved: a.ev("slotRaw(UI.slot)"), day: a.ev('S.day') };
}
test('a reload drops you straight back into your saved network', () => {
@ -25,16 +25,16 @@ test('a reload drops you straight back into your saved network', () => {
test('leaving the page saves the game', () => {
const a = load();
a.ev("ACT.start({});for(let i=0;i<7;i++)dayTick();localStorage.removeItem('sot-save-v1')");
a.ev("ACT.start({});for(let i=0;i<7;i++)dayTick();localStorage.removeItem(SLOT_K+UI.slot)");
a.ev("dispatchEvent(new Event('pagehide'))");
assert.equal(JSON.parse(a.ev("localStorage.getItem('sot-save-v1')")).day, a.ev('S.day'));
assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day'));
});
test('a save too big for the browser is not retried every few seconds, but leaving still tries', () => {
const a = load();
// A storage that counts tries and refuses the game save, like a full quota.
a.ev(`window.__tries=0;window.__full=true;const P=Object.getPrototypeOf(localStorage),set=P.setItem;
P.setItem=function(k,v){if(k==='sot-save-v1'){__tries++;if(__full){const e=new Error('full');e.name='QuotaExceededError';throw e;}}return set.call(this,k,v);};
P.setItem=function(k,v){if(k.startsWith('sot-save-v1')){__tries++;if(__full){const e=new Error('full');e.name='QuotaExceededError';throw e;}}return set.call(this,k,v);};
ACT.start({});for(let i=0;i<7;i++)dayTick();__tries=0;UI.saveFail=null;save()`);
assert.equal(a.ev('__tries'), 1);
a.ev('save();save();after()');
@ -44,7 +44,7 @@ test('a save too big for the browser is not retried every few seconds, but leavi
assert.equal(a.ev('UI.saveFail.wait'), 120000, 'and each failure waits longer');
a.ev('__full=false;UI.saveFail.at-=120001;save()');
assert.equal(a.ev('__tries'), 3, 'tried again once the wait is over');
assert.equal(JSON.parse(a.ev("localStorage.getItem('sot-save-v1')")).day, a.ev('S.day'));
assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day'));
assert.equal(a.ev('UI.saveFail'), null);
a.ev('save()');
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time');

View file

@ -169,16 +169,18 @@ test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => {
test('the main save is byte-identical before and after playing and solving a puzzle', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true)");
const before = ev("localStorage.getItem('sot-save-v1')");
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true);window.__slot=UI.slot");
let before = ev("slotRaw(UI.slot||window.__slot)");
const name = ev('S.name'), day = ev('S.day');
ev('ACT.puzzleMenu({})');
assert.match(ev("document.getElementById('modalCard').textContent"), /Hello, World/);
ev("ACT.pzStart({id:'hello'})");
assert.equal(ev('S.mode'), 'puzzle');
before = ev("slotRaw(window.__slot)");// entering saves the network once more (a new stamp, the same game)
assert.equal(JSON.parse(before).name, name);
build(ev, REF.hello.three);
ev("save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);window.dispatchEvent(new Event('pagehide'));ACT.exportSave({})");
assert.equal(ev("localStorage.getItem('sot-save-v1')"), before, 'untouched while in the puzzle');
assert.equal(ev("slotRaw(UI.slot||window.__slot)"), before, 'untouched while in the puzzle');
assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).s.hello.st"), 3, 'the stars are kept');
ev('ACT.pzLeave({})');
assert.equal(ev('S.mode'), 'normal');
@ -186,7 +188,7 @@ test('the main save is byte-identical before and after playing and solving a puz
assert.equal(ev('S.day'), day);
assert.ok(ev('!!S.pops.ams'));
assert.equal(ev('UI.started'), true);
assert.equal(ev("localStorage.getItem('sot-save-v1')"), before, 'and after');
assert.equal(ev("slotRaw(UI.slot||window.__slot)"), before, 'and after');
assert.deepEqual(errors, []);
});
@ -198,7 +200,7 @@ test('leaving a puzzle with no game goes back to the title screen', () => {
assert.equal(ev('S.mode'), 'puzzle');
ev('ACT.pzLeave({})');
assert.equal(ev('S'), null);
assert.equal(ev("localStorage.getItem('sot-save-v1')"), null, 'no main save appeared');
assert.equal(ev("slotIdx(true).length"), 0, 'no network was saved');
assert.match(ev("document.getElementById('modalCard').textContent"), /Series/);
assert.deepEqual(errors, []);
});
@ -354,8 +356,8 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true)");
ev("toast('main game news','bad',[{l:'Fix',act:'opsOpen',args:{}}]);save(true)");
assert.ok(ev("document.querySelectorAll('#toasts .toast').length") > 0);
const before = ev("localStorage.getItem('sot-save-v1')");
ev("ACT.pzStart({id:'hello'})");
ev("window.__slot=UI.slot;ACT.pzStart({id:'hello'})");
const before = ev("slotRaw(__slot)");
assert.equal(ev("[...document.querySelectorAll('#toasts .toast')].filter(t=>/main game news/.test(t.textContent)).length"), 0, 'main-game toasts are cleared');
ev("ACT.pzPop({city:'lon'})");
const st = () => ev("JSON.stringify({p:S.pops,l:S.links.length,c:S.cash,m:S.mode,te:!!S.te,ops:S.ops,sc:S.scrubs.length,dash:$('dash').hidden,bank:$('bankBox').hidden,left:$('left').hidden,modal:$('modal').hidden,cam:[cam.x,cam.y]})");
@ -373,7 +375,7 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
ev("toast('puzzle news','good')");
ev('ACT.pzLeave({})');
assert.equal(ev("document.querySelectorAll('#toasts .toast').length"), 0, 'puzzle toasts do not follow you home');
assert.equal(ev("localStorage.getItem('sot-save-v1')"), before);
assert.equal(ev("slotRaw(__slot)"), before);
// Back in the main game, the same actions work again.
ev("ACT.addRouter({city:'ams'})");
assert.equal(ev('S.pops.ams.routers'), 2);

View file

@ -268,7 +268,7 @@ test('several exchanges per city: overlapping members, cheaper challengers, sepa
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)");
ev("save();load2=JSON.parse(slotRaw(UI.slot));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);
@ -1035,16 +1035,16 @@ test('an old save with Australian POPs is told once that Australia changed', ()
const a = load();
start(a.ev);
a.ev("ACT.buildPop({city:'syd'});for(let d=0;d<3;d++)dayTick();delete S.auV;save()");
const sv = a.ev("localStorage.getItem('sot-save-v1')");
const sv = a.ev("slotRaw(UI.slot)");
const { ev, errors } = load({ storage: { 'sot-save-v1': sv } });
assert.match(ev("S.log.map(e=>e.t).join(' | ')"), /Australia got more Australian/);
assert.equal(ev("S.auV"), 1);
assert.equal(ev("S.auNews"), undefined, 'only once');
const again = load({ storage: { 'sot-save-v1': ev("save();localStorage.getItem('sot-save-v1')") } });
const again = load({ storage: { 'sot-save-v1': ev("save();slotRaw(UI.slot)") } });
assert.equal(again.ev("S.log.filter(e=>/Australia got more Australian/.test(e.t)).length"), 1, 'not told twice');
// a new game never sees it, and neither does a save without Australia
const b = load(); start(b.ev); b.ev("for(let d=0;d<3;d++)dayTick();delete S.auV;save()");
const c = load({ storage: { 'sot-save-v1': b.ev("localStorage.getItem('sot-save-v1')") } });
const c = load({ storage: { 'sot-save-v1': b.ev("slotRaw(UI.slot)") } });
assert.doesNotMatch(c.ev("S.log.map(e=>e.t).join(' | ')"), /Australia got more/);
assert.deepEqual(errors, []);
});

View file

@ -4,7 +4,7 @@ const { load } = require('./harness');
// Make the browser's storage refuse the save: 'QuotaExceededError' (too big) or 'SecurityError' (not allowed).
const refuse = name => `window.__err=${JSON.stringify(name)};{const P=Object.getPrototypeOf(localStorage),set=P.setItem;
P.setItem=function(k,v){if(k==='sot-save-v1'&&__err){const e=new Error('no');e.name=__err;throw e;}return set.call(this,k,v);};}`;
P.setItem=function(k,v){if(k.startsWith('sot-save-v1')&&__err){const e=new Error('no');e.name=__err;throw e;}return set.call(this,k,v);};}`;
test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => {
const { ev, dom, errors } = load();
@ -55,8 +55,8 @@ test('#176 saves leave customer defaults out, and loading puts them back exactly
assert.deepEqual(norm(after), norm(want));
assert.equal(ev("S.biz.find(b=>b.id==='l2').route"), 'fast', 'a chosen route is kept');
assert.equal(ev("S.biz.find(b=>b.id==='w7').what"), ev("wwWhat(S.links.find(l=>l.id==='df1'),4)"), 'alien waves get their description back');
assert.match(ev("localStorage.getItem('sot-save-v1')"), /"Carrier 1"/);
assert.doesNotMatch(ev("localStorage.getItem('sot-save-v1')"), /alien wave on your/, 'descriptions are not stored');
assert.match(ev("slotRaw(UI.slot)"), /"Carrier 1"/);
assert.doesNotMatch(ev("slotRaw(UI.slot)"), /alien wave on your/, 'descriptions are not stored');
assert.deepEqual(errors, []);
});
@ -77,7 +77,7 @@ const huge = "for(let i=0;i<12000;i++){const slots=1+i%4;S.biz.push({id:'h'+i,ci
test('#176 small saves stay plain JSON, written at once', () => {
const { ev, errors } = load({ gzip: true });
ev("ACT.start({});save(true)");
assert.equal(ev("localStorage.getItem('sot-save-v1')[0]"), '{');
assert.equal(ev("slotRaw(UI.slot)[0]"), '{');
assert.deepEqual(errors, []);
});
@ -86,8 +86,8 @@ test('#176 a huge save is gzipped into storage and the next visit loads it', asy
a.ev(bigBiz + ';' + huge);
assert.ok(a.ev('JSON.stringify(packSave(S)).length') >= a.ev('GZ_MIN'), 'big enough to compress');
a.ev('save(true)');
await settle(a.ev, "(localStorage.getItem('sot-save-v1')||'').startsWith(GZ)");
const raw = a.ev("localStorage.getItem('sot-save-v1')"), full = a.ev('JSON.stringify(packSave(S)).length');
await settle(a.ev, "(slotRaw(UI.slot)||'').startsWith(GZ)");
const raw = a.ev("slotRaw(UI.slot)"), full = a.ev('JSON.stringify(packSave(S)).length');
assert.ok(raw.length < full / 4, `much smaller in storage (${raw.length} vs ${full})`);
const before = a.ev("JSON.stringify([S.name,S.day,S.biz.length,S.biz.find(b=>b.id==='h77').what])");
// The next visit: the page unpacks it before booting and continues the same network.
@ -102,22 +102,22 @@ test('#176 a newer save is never overwritten by an older one still compressing',
const { ev, errors } = load({ gzip: true });
ev(bigBiz + ';' + huge);
ev("save(true);S.name='Newer';save(true);S.name='Newest';save(true)");
await settle(ev, "!UI.gzBusy&&(localStorage.getItem('sot-save-v1')||'').startsWith(GZ)");
ev("gunzip(localStorage.getItem('sot-save-v1')).then(t=>window.__t=JSON.parse(t).name)");
await settle(ev, "!UI.gzBusy&&(slotRaw(UI.slot)||'').startsWith(GZ)");
ev("gunzip(slotRaw(UI.slot)).then(t=>window.__t=JSON.parse(t).name)");
await settle(ev, "!!window.__t");
assert.equal(ev('__t'), 'Newest');
// A new game started while a big save compresses: the old network does not come back.
ev("save(true);ACT.newgame();ACT.start({});window.__new=S.name");
await settle(ev, '!UI.gzBusy');
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).name"), ev('__new'), 'the new game stays saved');
assert.equal(ev("JSON.parse(slotRaw(UI.slot)).name"), ev('__new'), 'the new game stays saved');
assert.deepEqual(errors, []);
});
test('#176 a damaged compressed save is kept aside and the player is told', async () => {
test('#176 a damaged compressed save is kept, marked damaged, and the player is told', async () => {
const { ev, dom, errors } = load({ gzip: true, storage: { 'sot-save-v1': 'gz:bm90IGd6aXA=' } });
await settle(ev, "localStorage.getItem('sot-save-broken')!==null");
assert.match(dom.window.document.body.textContent, /could not be/);
assert.equal(ev("localStorage.getItem('sot-save-broken')"), 'gz:bm90IGd6aXA=');
assert.equal(ev("localStorage.getItem('sot-save-v1')"), null);
await settle(ev, "slotIdx().length===1&&/could not be/.test(document.getElementById('toasts').textContent)");
assert.equal(ev("slotIdx()[0].broken"), true, 'listed as damaged, so it can still be exported or deleted');
assert.equal(ev("slotRaw('main')"), 'gz:bm90IGd6aXA=', 'the damaged save is kept as it was');
assert.equal(ev('!!UI.started'), false);
assert.deepEqual(errors, []);
});

435
tests/save-slots.test.js Normal file
View file

@ -0,0 +1,435 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load, browser, flush } = require('./harness');
// Two windows of one browser share localStorage, its storage events, a BroadcastChannel and Web Locks; a reload is a
// new window with the same tab (sessionStorage).
const settle = async (ev, cond, what) => { for (let i = 0; i < 400 && !ev(cond); i++) await new Promise((r) => setTimeout(r, 5)); assert.ok(ev(cond), what || cond); };
const play = (ev, name, city = 'fra', days = 5) => ev(`UI.pitched=true;UI.nm=${JSON.stringify(name)};if($('nmIn'))$('nmIn').value=UI.nm;ACT.pickStart({city:'${city}'});ACT.start({});ACT.launchBB({city:'${city}'});for(let i=0;i<${days};i++)dayTick();save(true)`);
const idx = (ev) => JSON.parse(ev("JSON.stringify(slotIdx())"));
const card = (ev) => ev("document.getElementById('modalCard').textContent");
// A save as the previous version wrote it: one key, no index.
function legacySave() {
const a = load();
a.ev("$('nmIn').value='Old Faithful';ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<30;i++)dayTick();UI.speed=2");
return { txt: a.ev('JSON.stringify(packSave((S.uiSpeed=UI.speed,S.cam={x:cam.x,y:cam.y,z:cam.z},S)))'), snap: a.ev('JSON.stringify([S.name,S.day,S.cash,S.asn,Object.keys(S.pops),S.transit.length])') };
}
test('the single save of older versions becomes the first network, losslessly, and loads exactly as before', async () => {
const { txt, snap } = legacySave();
const b = browser();
const a = load({ browser: b, storage: { 'sot-save-v1': txt } });
await settle(a.ev, 'UI.started===true');
assert.equal(a.ev('JSON.stringify([S.name,S.day,S.cash,S.asn,Object.keys(S.pops),S.transit.length])'), snap, 'the same network');
assert.equal(a.ev('UI.speed'), 2);
assert.equal(b.ls.get('sot-save-v1:main'), txt, 'copied byte for byte');
assert.equal(b.ls.get('sot-save-v1'), txt, 'the old key stays as a fallback until the network saves again');
const e = idx(a.ev);
assert.equal(e.length, 1);
assert.equal(e[0].id, 'main');
assert.equal(e[0].name, 'Old Faithful');
assert.equal(e[0].day, 30);
// The copy was read back before the index was written.
const i = b.log.findIndex((x) => x[0] === 'set' && x[1] === 'sot-save-v1:main'), r = b.log.findIndex((x, n) => n > i && x[0] === 'get' && x[1] === 'sot-save-v1:main'), w = b.log.findIndex((x) => x[0] === 'set' && x[1] === 'sot-slots');
assert.ok(i >= 0 && r > i && w > r, 'write new, read it back, then the index');
a.ev('dayTick();save(true)');
assert.equal(b.ls.has('sot-save-v1'), false, 'after a later save, the old key is retired');
assert.equal(JSON.parse(b.ls.get('sot-save-v1:main')).day, 31);
assert.deepEqual(a.errors, []);
});
test('a browser with no room for the copy keeps playing from the old key', async () => {
const { txt } = legacySave();
const b = browser();
b.quota = 10;// every slot write is refused
const a = load({ browser: b, storage: { 'sot-save-v1': txt } });
await settle(a.ev, 'UI.started===true');
assert.equal(a.ev('S.name'), 'Old Faithful');
assert.equal(b.ls.has('sot-save-v1:main'), false);
assert.equal(b.ls.get('sot-save-v1'), txt, 'never touched');
assert.deepEqual(a.errors, []);
});
test('a compressed (gz) single save migrates and loads the same network', async () => {
const g = load({ gzip: true });
const raw = await g.dom.window.eval(`(async()=>{$('nmIn').value='Squeezed';ACT.start({});for(let i=0;i<8;i++)dayTick();return gzip(JSON.stringify(packSave(S)));})()`);
const day = g.ev('S.day');
assert.ok(raw.startsWith('gz:'));
const b = browser();
const a = load({ browser: b, gzip: true, storage: { 'sot-save-v1': raw } });
await settle(a.ev, 'UI.started===true');
assert.equal(a.ev('S.name'), 'Squeezed');
assert.equal(a.ev('S.day'), day);
assert.equal(b.ls.get('sot-save-v1:main'), raw);
assert.equal(idx(a.ev)[0].name, 'Squeezed', 'the index knows its name without unpacking it again');
assert.deepEqual(a.errors, []);
});
test('two networks coexist and load independently; the title lists them, newest first', async () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'First Net', 'fra', 4);
const first = a.ev('UI.slot');
a.ev('ACT.toTitle()');
assert.equal(a.ev('S'), null);
play(a.ev, 'Second Net', 'nyc', 9);
const second = a.ev('UI.slot');
assert.notEqual(first, second);
a.ev('ACT.toTitle()');
const list = a.ev("[...document.querySelectorAll('#slotList .slot b')].map(b=>b.textContent).join('|')");
assert.equal(list, 'Second Net|First Net', 'most recent first');
assert.match(card(a.ev), /Your networks/);
a.ev(`ACT.cont({id:'${first}'})`);
await settle(a.ev, 'UI.started===true');
assert.equal(a.ev('S.name'), 'First Net');
assert.equal(a.ev('S.day'), 4);
assert.equal(a.ev('S.home'), 'fra');
a.ev('ACT.toTitle()');
a.ev(`ACT.cont({id:'${second}'})`);
await settle(a.ev, 'UI.started===true');
assert.equal(a.ev('S.name'), 'Second Net');
assert.equal(a.ev('S.day'), 9);
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + first)).name, 'First Net', 'each in its own key');
assert.deepEqual(a.errors, []);
});
test('the title lists networks from the index alone, without reading any save', () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'One');
a.ev('ACT.toTitle()');
play(a.ev, 'Two');
a.ev('ACT.toTitle()');
b.log.length = 0;
a.ev('showTitle()');
assert.deepEqual(b.log.filter((x) => x[1].startsWith('sot-save-v1')), [], 'no save was read');
assert.equal(a.ev("document.querySelectorAll('#slotList .slot').length"), 2);
});
test('each tab continues its own network on reload, and two tabs play two networks at once', async () => {
const b = browser();
const tab1 = new Map(), tab2 = new Map();
const w1 = load({ browser: b, tab: tab1 });
play(w1.ev, 'Tab One', 'fra', 3);
const w2 = load({ browser: b, tab: tab2 });
await flush();
assert.equal(w2.ev('!!UI.started'), false, 'the only network is open in tab one, so tab two shows the title');
play(w2.ev, 'Tab Two', 'sin', 6);
// Both keep saving, each into its own slot.
w1.ev('dayTick();save(true)');w2.ev('dayTick();save(true)');
// Reload tab one: it comes back to its own network, not the newer one.
b.close(w1.dom.window);
const r1 = load({ browser: b, tab: tab1 });
await settle(r1.ev, 'UI.started===true');
assert.equal(r1.ev('S.name'), 'Tab One');
assert.equal(r1.ev('S.day'), 4);
b.close(w2.dom.window);
const r2 = load({ browser: b, tab: tab2 });
await settle(r2.ev, 'UI.started===true');
assert.equal(r2.ev('S.name'), 'Tab Two');
// A brand-new tab: the title with both, and Continue offers neither, since both are open.
const w3 = load({ browser: b });
await flush();
assert.equal(w3.ev('!!UI.started'), false);
assert.equal(w3.ev("document.querySelectorAll('#slotList .slot.busy').length"), 2);
assert.equal(w3.ev("!!document.querySelector('#modalCard [data-act=cont].pink')"), false, 'no Continue for a network open elsewhere');
// Tab two goes back to the title: its network is free again and becomes the one to continue.
r2.ev('ACT.toTitle()');
await flush();
w3.ev('showTitle()');
assert.match(w3.ev("document.querySelector('#modalCard [data-act=cont].pink').textContent"), /Tab Two/);
for (const w of [r1, r2, w3]) assert.deepEqual(w.errors, []);
});
test('opening a network open in another window offers to switch or take over, and take-over hands it across', async () => {
const b = browser();
const w1 = load({ browser: b });
play(w1.ev, 'Shared Net', 'fra', 3);
const id = w1.ev('UI.slot');
const w2 = load({ browser: b });
await flush();
w2.ev(`ACT.cont({id:'${id}'})`);
await flush();
assert.match(card(w2.ev), /open in another window/);
assert.equal(w2.ev('!!UI.started'), false, 'not forked');
assert.ok(w2.ev("!!document.querySelector('#modalCard [data-act=slotSwitch]')&&!!document.querySelector('#modalCard [data-act=slotTake]')"));
// Switch: the other window says hello, this one stays on the title.
w2.ev(`ACT.slotSwitch({id:'${id}'})`);
await flush();
assert.match(w1.ev("document.getElementById('toasts').textContent"), /Here it is/);
// Take over: window one saves what it has, steps aside calmly and stops saving.
w1.ev('dayTick()');
w2.ev(`ACT.slotTake({id:'${id}'})`);
await settle(w2.ev, 'UI.started===true', 'taken over');
assert.equal(w2.ev('S.day'), 4, 'with the last day played in the other window');
await settle(w1.ev, '/opened in another window/.test(document.getElementById(\'modalCard\').textContent)');
assert.equal(w1.ev('UI.slot'), null);
assert.equal(w1.ev('S'), null);
w2.ev('dayTick();save(true)');
const before = b.ls.get('sot-save-v1:' + id);
w1.ev("save(true);dispatchEvent(new Event('pagehide'))");
assert.equal(b.ls.get('sot-save-v1:' + id), before, 'the window that stepped aside never writes again');
assert.equal(JSON.parse(before).day, 5);
assert.deepEqual(w1.errors, []);
assert.deepEqual(w2.errors, []);
});
test('without Web Locks or BroadcastChannel the heartbeat still keeps one writer per network', async () => {
const b = browser({ locks: false, channel: false });
const w1 = load({ browser: b });
play(w1.ev, 'Old Browser Net');
const id = w1.ev('UI.slot');
w1.ev('slotBeat()');
const w2 = load({ browser: b });
await flush();
assert.equal(w2.ev('slotBusy(' + JSON.stringify(id) + ')'), true);
w2.ev(`ACT.cont({id:'${id}'})`);
await flush();
assert.match(card(w2.ev), /open in another window/);
w2.ev(`ACT.slotTake({id:'${id}'})`);
await settle(w2.ev, 'UI.started===true');
w2.ev('slotBeat()');
await settle(w1.ev, 'UI.slot===null', 'the first window notices the new heartbeat');
assert.deepEqual(w1.errors, []);
assert.deepEqual(w2.errors, []);
});
test('a stale write is refused: a newer save of the same network from another window is never overwritten', async () => {
const b = browser();
const w1 = load({ browser: b });
play(w1.ev, 'Contested');
const id = w1.ev('UI.slot');
// Another window (a forked tab, a crashed lock) saves a newer version behind this one's back.
const ix = JSON.parse(b.ls.get('sot-slots'));
const newer = JSON.parse(b.ls.get('sot-save-v1:' + id));newer.day = 99;newer.sv = { seq: 1000, at: Date.now() };
b.ls.set('sot-save-v1:' + id, JSON.stringify(newer));
ix.slots[0].seq = 1000;ix.slots[0].day = 99;b.ls.set('sot-slots', JSON.stringify(ix));
w1.ev('dayTick();save(true)');
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + id)).day, 99, 'the newer save stays');
assert.match(card(w1.ev), /saved in another window/);
assert.equal(w1.ev('UI.slot'), null, 'and this window stops saving');
assert.ok(w1.ev("!!document.querySelector('#modalCard [data-act=cont]')"), 'with a way to load the newest version');
// The storage event alone also stops it, before it even tries.
const w2 = load({ browser: b });
await flush();
play(w2.ev, 'Watcher');
const id2 = w2.ev('UI.slot'), ix2 = JSON.parse(b.ls.get('sot-slots')), e = ix2.slots.find((x) => x.id === id2);
e.seq += 50;
w1.dom.window.localStorage.setItem('sot-slots', JSON.stringify(ix2));// written by another window: w2 gets the event
await settle(w2.ev, 'UI.slot===null');
assert.deepEqual(w1.errors, []);
assert.deepEqual(w2.errors, []);
});
test('saves are written slot first, then the index, and every write moves the sequence on', () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'Ordered');
const id = a.ev('UI.slot');
b.log.length = 0;
a.ev('dayTick();save(true)');
const sets = b.log.filter((x) => x[0] === 'set').map((x) => x[1]);
assert.ok(sets.indexOf('sot-save-v1:' + id) < sets.indexOf('sot-slots'), sets.join());
const s = JSON.parse(b.ls.get('sot-save-v1:' + id)), e = idx(a.ev).find((x) => x.id === id);
assert.equal(s.sv.seq, e.seq, 'the save and its index entry agree');
a.ev('save(true)');
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + id)).sv.seq, e.seq + 1);
assert.equal(a.ev('"sv" in S'), false, 'the stamp lives in storage, not in the game');
});
test('deleting a network removes its save and its line, after a confirmation', async () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'Keeper');
a.ev('ACT.toTitle()');
play(a.ev, 'Goner');
const gone = a.ev('UI.slot');
a.ev('ACT.toTitle()');
a.ev(`document.querySelector('#slotList .slot[data-slot="${gone}"] .slot-more').click()`);
assert.match(card(a.ev), /Goner/);
a.ev("document.querySelector('#modalCard [data-act=slotDel]').click()");
assert.match(card(a.ev), /cannot be undone/);
assert.ok(b.ls.has('sot-save-v1:' + gone), 'nothing deleted before the confirmation');
a.ev("document.querySelector('#modalCard [data-act=slotDelGo]').click()");
assert.equal(b.ls.has('sot-save-v1:' + gone), false);
assert.deepEqual(idx(a.ev).map((e) => e.name), ['Keeper']);
assert.match(card(a.ev), /Continue Keeper/);
assert.deepEqual(a.errors, []);
});
test('a network deleted in another window is never written back by the window playing it', async () => {
const b = browser();
const w1 = load({ browser: b });
play(w1.ev, 'Doomed');
const id = w1.ev('UI.slot');
const w2 = load({ browser: b });
await flush();
w2.ev(`ACT.slotDelGo({id:'${id}'})`);
await settle(w1.ev, 'UI.slot===null');
w1.ev("save(true);dispatchEvent(new Event('pagehide'))");
assert.equal(b.ls.has('sot-save-v1:' + id), false);
assert.equal(idx(w2.ev).length, 0);
assert.match(w1.ev("document.getElementById('toasts').textContent"), /deleted in another window/);
});
test('export the network on screen, or any network from the list; import adds a new network and keeps the old', async () => {
const b = browser();
const a = load({ browser: b });
const files = [];
a.dom.window.URL.createObjectURL = (blob) => { files.push(blob); return 'blob:x'; };
const text = (blob) => new Promise((r) => { const f = new a.dom.window.FileReader(); f.onload = () => r(f.result); f.readAsText(blob); });
a.dom.window.URL.revokeObjectURL = () => {};
play(a.ev, 'Exported Net', 'fra', 7);
const first = a.ev('UI.slot');
a.ev('ACT.exportSave({})');
const txt = await text(files[0]);
// Import it back: a second network, the first untouched.
a.ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`);
assert.notEqual(a.ev('UI.slot'), first, 'a new slot');
assert.equal(a.ev('S.name'), 'Exported Net');
assert.equal(a.ev('S.day'), 7);
assert.equal(idx(a.ev).length, 2);
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + first)).day, 7, 'the first network is still there');
// Export from the list: straight from storage, the same network.
a.ev('ACT.toTitle()');
a.ev(`ACT.slotExport({id:'${first}'})`);
await settle(a.ev, 'true');await flush(5);
const j = JSON.parse(await text(files[1]));
assert.equal(j.app, 'series-of-tubes');
assert.equal(j.S.name, 'Exported Net');
assert.equal(a.ev(`parseSave(${JSON.stringify(JSON.stringify(j))}).err||null`), null, 'and it imports');
assert.deepEqual(a.errors, []);
});
test('renaming the network renames it in the list', () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'Before');
a.ev("ACT.menu();document.querySelector('#modalCard [data-act=rename]').click()");
a.ev("document.getElementById('rnIn').value=' After Rename ';ACT.renameGo()");
assert.equal(a.ev('S.name'), 'After Rename');
assert.equal(idx(a.ev)[0].name, 'After Rename');
});
test('puzzles never write a network, and a tab closed mid-puzzle keeps the network it set aside', async () => {
const b = browser();
const a = load({ browser: b });
// A puzzle from the title: nothing saved at all.
a.ev("ACT.pzStart({id:'hello'})");
a.ev("save(true);dispatchEvent(new Event('pagehide'))");
assert.equal(idx(a.ev).length, 0);
a.ev('ACT.pzLeave({})');
play(a.ev, 'Set Aside', 'fra', 3);
const id = a.ev('UI.slot');
a.ev("ACT.pzStart({id:'hello'})");
const kept = b.ls.get('sot-save-v1:' + id);
a.ev("S.pops.lon={day:0};save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);dispatchEvent(new Event('pagehide'))");
assert.equal(b.ls.get('sot-save-v1:' + id), kept, 'the puzzle never writes the slot');
assert.equal(JSON.parse(kept).name, 'Set Aside');
assert.ok(b.ls.has('sot-puzzles') || true);
// The tab closes mid-puzzle; the next one continues the network.
b.close(a.dom.window);
const r = load({ browser: b });
await settle(r.ev, 'UI.started===true');
assert.equal(r.ev('S.name'), 'Set Aside');
assert.equal(r.ev('S.mode'), 'normal');
assert.deepEqual(a.errors, []);
assert.deepEqual(r.errors, []);
});
test('a big save still compressing when a puzzle starts lands in its network, and so does the next one', async () => {
const b = browser();
const a = load({ browser: b, gzip: true });
play(a.ev, 'Big One', 'fra', 1);
a.ev("S.cash=1e9;ACT.buildPop({city:'ams'});S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:true,km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});for(let i=0;i<12000;i++)S.biz.push({id:'h'+i,city:'fra',city2:'ams',name:'Huge Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots:1,what:''});compute()");
const id = a.ev('UI.slot');
a.ev("S.name='Big One v1';save(true);S.name='Big One v2';save(true)");// one compressing, one queued
a.ev("ACT.pzStart({id:'hello'})");
await settle(a.ev, '!UI.gzBusy&&!SLOT.gzQ.size');
const t = await a.dom.window.eval(`gunzip(slotRaw(${JSON.stringify(id)}))`);
assert.equal(JSON.parse(t).name, 'Big One v2', 'the queued save landed too');
a.ev('ACT.pzLeave({})');
assert.equal(a.ev('S.name'), 'Big One v2');
assert.deepEqual(a.errors, []);
});
test('leaving a puzzle when the network cannot be loaded marks it damaged, and Continue does not crash', async () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'Fragile');
const id = a.ev('UI.slot');
a.ev("ACT.pzStart({id:'hello'})");
// The network set aside is gone from memory and its save is unreadable (another version, a broken disk…).
a.ev(`UI.pzKeep=null;localStorage.setItem(SLOT_K+${JSON.stringify(id)},'{"v":1,"day":"x","pops":7}')`);
a.ev(`window.__m=migrate;migrate=s=>{if(s&&s.pops===7)throw new Error('bad');return __m(s);}`);
a.ev('ACT.pzLeave({})');
a.ev('migrate=__m');
assert.match(a.ev("document.getElementById('toasts').textContent"), /could not be loaded/);
assert.equal(idx(a.ev)[0].broken, true);
assert.ok(b.ls.has('sot-save-v1:' + id), 'kept, so it can be exported');
a.ev(`ACT.cont({id:${JSON.stringify(id)}})`);
await flush();
assert.equal(a.ev('!!UI.started'), false);
a.ev('ACT.cont({})');
assert.match(card(a.ev), /Series/);
assert.deepEqual(a.errors, []);
});
test('a corrupted index is rebuilt from the saves themselves', async () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'Alpha', 'fra', 2);
a.ev('ACT.toTitle()');
play(a.ev, 'Beta', 'nyc', 3);
a.ev('ACT.toTitle()');
b.ls.set('sot-slots', '{not json');
b.ls.set('sot-save-v1:junk1', 'garbage');
const c = load({ browser: b });
await flush();
const names = idx(c.ev).map((e) => e.name || (e.broken ? '(damaged)' : '?')).sort();
assert.deepEqual(names, ['(damaged)', 'Alpha', 'Beta']);
assert.match(c.ev("document.getElementById('slotList').textContent"), /Damaged/);
// An index line whose save is gone is dropped.
const ix = JSON.parse(b.ls.get('sot-slots'));ix.slots.push({ id: 'ghost', name: 'Ghost', day: 1, at: Date.now() });b.ls.set('sot-slots', JSON.stringify(ix));
c.ev('showTitle()');
assert.equal(c.ev("idx=slotIdx().map(e=>e.name).includes('Ghost')"), false);
assert.deepEqual(c.errors, []);
});
test('out of room: the warning offers to free up space, listing the other networks by size', () => {
const b = browser();
const a = load({ browser: b });
play(a.ev, 'Small Other');
a.ev('ACT.toTitle()');
play(a.ev, 'Growing');
b.quota = 100;
a.ev('UI.saveFail=null;dayTick();save(true)');
assert.match(a.ev("document.getElementById('toasts').textContent"), /not being saved/);
a.ev("document.querySelector('#toasts [data-act=slotSpace]').click()");
assert.match(card(a.ev), /Small Other/);
assert.ok(a.ev("!!document.querySelector('#modalCard [data-act=slotExport]')&&!!document.querySelector('#modalCard [data-act=slotDel]')"));
a.ev('ACT.menu()');
assert.ok(a.ev("!!document.querySelector('#modalCard [data-act=slotSpace]')"), 'the menu offers it too');
assert.deepEqual(a.errors, []);
});
test('the networks list fits a 360 px phone and has a tap target and a ⋯ menu per network, in every language', () => {
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
const b = browser();
const a = load({ browser: b, lang: lang === 'en' ? undefined : lang });
a.ev('window.innerWidth=360');
play(a.ev, 'Phone Net One');
a.ev('ACT.toTitle()');
a.ev("UI.mode='sandbox'");
play(a.ev, 'Sandy');
a.ev('ACT.toTitle()');
const rows = a.ev("document.querySelectorAll('#slotList .slot').length");
assert.equal(rows, 2, lang);
assert.ok(a.ev("[...document.querySelectorAll('#slotList .slot')].every(r=>r.querySelector('.slot-go')&&r.querySelector('.slot-more[aria-label]'))"), lang);
assert.match(a.ev("document.getElementById('slotList').textContent"), /🏖️/, `${lang}: preset icon`);
assert.equal(a.ev("document.querySelector('#slotList').previousElementSibling.textContent"), a.ev("tr('slots.your_networks')"));
assert.doesNotMatch(card(a.ev), /slots\.|undefined|NaN|\{[a-z]+\}/, lang);
assert.deepEqual(a.errors, [], lang);
}
});

View file

@ -335,7 +335,7 @@ test('saves: old saves load with no intern and everything off, settings survive
assert.equal(ev('S.ops.intern'), null);
assert.equal(ev('Object.values(S.ops.on).some(Boolean)'), false);
hire(ev);
ev("on=1;S.ops.on.pni=true;S.ops.p.pni={g:50,tier:2,paid:true};S.ops.cap.pni=1e6;S.ops.skip.fra=['caches'];save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')))");
ev("on=1;S.ops.on.pni=true;S.ops.p.pni={g:50,tier:2,paid:true};S.ops.cap.pni=1e6;S.ops.skip.fra=['caches'];save();S=migrate(JSON.parse(slotRaw(UI.slot)))");
assert.equal(ev("S.ops.intern==='kevin'&&S.ops.on.pni&&S.ops.p.pni.tier===2&&S.ops.cap.pni===1e6&&S.ops.skip.fra[0]==='caches'"), true);
ev(`S.ops={intern:'mallory',on:{transit:'yes',hack:true},p:{transit:{x:99,prov:'nobody'}},cap:{transit:-5},spent:{transit:'lots'},skip:{atlantis:['transit'],fra:['ix','transit']},
log:[{d:1,i:'kevin',r:[['transit',2,['fra +1×100G','<img>']],['evil',1,[]]],f:99,c:'fra'},'junk'],floor:3,tpl:{bb:'no'}};S=migrate(S)`);

View file

@ -86,7 +86,7 @@ test('one-site requests add only A, then a new second site gets exactly its miss
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
assert.equal(ev('S.caches.length'), 10);
assert.equal(ev("NETS.filter(n=>n.cache).every(n=>['a','b'].every(s=>S.caches.filter(c=>c.net===n.id&&c.site===s).length===1))"), true);
ev("save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()");
ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
assert.equal(ev('S.caches.length'), 10);
assert.equal(ev("S.caches.filter(c=>c.site==='b').length"), 5);
assert.deepEqual(errors, []);

View file

@ -23,7 +23,7 @@ test('redundancy kit matches normal purchases, including cash, monthly costs and
const before = a.ev('JSON.stringify(S)');
a.ev("ACT.utilityKit({city:'fra',cost:0})");
assert.equal(a.ev('JSON.stringify(S)'), before, 'repeat does not buy more hardware');
a.ev("save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()");
a.ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
assert.equal(a.ev('S.pops.fra.gen && S.pops.fra.site2 && S.pops.fra.routers===2'), true);
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);