From b1ae86e12426784611257ce39b647926e17490e6 Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 03:35:17 -0700 Subject: [PATCH 1/8] Port PlannerDefaultsTest to Rust (port stage 13a) Adds rust/contract/tests/planner_defaults.rs, which builds the same payload as the C# PlannerDefaultsTest and writes it in Verify's strict JSON layout (BOM, two-space indent, no final newline), with doubles through blueprint::json_out::format_f64. The bytes match the committed src/vue/src/lib/plannerDefaults.verified.json exactly. The test compares and fails on any difference. UPDATE_PLANNER_DEFAULTS=1 rewrites the file instead. An exhaustive destructure of OilFieldOptions stands in for EmitsEveryOilFieldOptionsProperty: a new field that is not emitted fails to compile. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- rust/contract/tests/planner_defaults.rs | 332 ++++++++++++++++++++++++ 1 file changed, 332 insertions(+) create mode 100644 rust/contract/tests/planner_defaults.rs diff --git a/rust/contract/tests/planner_defaults.rs b/rust/contract/tests/planner_defaults.rs new file mode 100644 index 00000000..9db1a27f --- /dev/null +++ b/rust/contract/tests/planner_defaults.rs @@ -0,0 +1,332 @@ +//! `PlannerDefaultsTest`, from `test/FactorioTools.Test/OilField/PlannerDefaultsTest.cs`. +//! +//! Emits the planner constants the Vue app needs, so they are not typed out a second time in +//! TypeScript. The Vue app imports the generated file directly (issue #54). +//! +//! This test is the generator. It compares the committed file byte for byte and fails on any +//! difference. Run it with `UPDATE_PLANNER_DEFAULTS=1` to rewrite the file instead, then +//! commit the result. CI never sets the variable, so a stale file fails there. +//! +//! The bytes match what the C# test wrote through Verify's `VerifyJson(...).UseStrictJson()`: +//! a UTF-8 byte order mark, two-space indent, `"key": value`, one array item per line, LF +//! line ends and no newline at the end. + +use std::path::PathBuf; + +use blueprint::json_out::format_f64; +use planner::models::{BeaconStrategy, PipeStrategy}; +use planner::options::{ALL_BEACON_STRATEGIES, ALL_PIPE_STRATEGIES, OilFieldOptions}; +use planner::quality::Quality; + +/// Set to `1` to rewrite the committed file rather than compare against it. +const UPDATE_ENV: &str = "UPDATE_PLANNER_DEFAULTS"; + +/// The generated file the Vue app imports. +fn planner_defaults_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../src/vue/src/lib/plannerDefaults.verified.json") +} + +#[test] +fn planner_defaults() { + let generated = render_file(&build_payload()); + let path = planner_defaults_path(); + + if std::env::var(UPDATE_ENV).is_ok_and(|value| value == "1") { + std::fs::write(&path, &generated) + .unwrap_or_else(|e| panic!("could not write {}: {e}", path.display())); + return; + } + + let committed = + std::fs::read(&path).unwrap_or_else(|e| panic!("could not read {}: {e}", path.display())); + if committed != generated { + let committed = String::from_utf8_lossy(&committed); + let generated = String::from_utf8_lossy(&generated); + let first_difference = committed + .lines() + .zip(generated.lines()) + .enumerate() + .find(|(_, (old, new))| old != new) + .map(|(index, (old, new))| { + format!( + "first different line is {}:\n committed: {old}\n generated: {new}", + index + 1 + ) + }) + .unwrap_or_else(|| "the files differ in length or in their last bytes".to_string()); + panic!( + "{} is stale: it no longer matches OilFieldOptions.\n{first_difference}\n\ + Rerun with {UPDATE_ENV}=1 to rewrite it from the Rust, then commit the file. \ + From rust/:\n {UPDATE_ENV}=1 cargo test -p contract --test planner_defaults", + path.canonicalize().unwrap_or(path).display() + ); + } +} + +/// `BuildOptions`. Every field of `OilFieldOptions` is taken apart by name with no `..`, so a +/// new field that is not emitted here fails to compile. That is the C#'s +/// `EmitsEveryOilFieldOptionsProperty` test, done by the compiler. To leave a field out on +/// purpose, bind it as `field: _` with a comment saying why. +fn build_options() -> Json { + let OilFieldOptions { + use_underground_pipes, + add_beacons, + optimize_pipes, + overlap_beacons, + add_electric_poles, + add_heat_pipes, + heat_pipe_entity_name, + pipe_strategies, + beacon_strategies, + electric_pole_entity_name, + electric_pole_supply_width, + electric_pole_supply_height, + electric_pole_wire_reach, + electric_pole_width, + electric_pole_height, + beacon_entity_name, + beacon_supply_width, + beacon_supply_height, + beacon_width, + beacon_height, + validate_solution, + pumpjack_modules, + beacon_modules, + pumpjack_quality, + beacon_quality, + electric_pole_quality, + pumpjack_module_quality, + beacon_module_quality, + } = OilFieldOptions::default(); + + Json::object([ + ("useUndergroundPipes", Json::Bool(use_underground_pipes)), + ("addBeacons", Json::Bool(add_beacons)), + ("optimizePipes", Json::Bool(optimize_pipes)), + ("overlapBeacons", Json::Bool(overlap_beacons)), + ("addElectricPoles", Json::Bool(add_electric_poles)), + ("addHeatPipes", Json::Bool(add_heat_pipes)), + ("heatPipeEntityName", Json::Str(heat_pipe_entity_name)), + ("pipeStrategies", pipe_strategy_names(&pipe_strategies)), + ( + "beaconStrategies", + beacon_strategy_names(&beacon_strategies), + ), + ( + "electricPoleEntityName", + Json::Str(electric_pole_entity_name), + ), + ( + "electricPoleSupplyWidth", + Json::Int(electric_pole_supply_width), + ), + ( + "electricPoleSupplyHeight", + Json::Int(electric_pole_supply_height), + ), + ( + "electricPoleWireReach", + Json::Double(electric_pole_wire_reach), + ), + ("electricPoleWidth", Json::Int(electric_pole_width)), + ("electricPoleHeight", Json::Int(electric_pole_height)), + ("beaconEntityName", Json::Str(beacon_entity_name)), + ("beaconSupplyWidth", Json::Int(beacon_supply_width)), + ("beaconSupplyHeight", Json::Int(beacon_supply_height)), + ("beaconWidth", Json::Int(beacon_width)), + ("beaconHeight", Json::Int(beacon_height)), + ("validateSolution", Json::Bool(validate_solution)), + ("pumpjackModules", modules(pumpjack_modules)), + ("beaconModules", modules(beacon_modules)), + ("pumpjackQuality", quality_name(pumpjack_quality)), + ("beaconQuality", quality_name(beacon_quality)), + ("electricPoleQuality", quality_name(electric_pole_quality)), + ( + "pumpjackModuleQuality", + quality_name(pumpjack_module_quality), + ), + ("beaconModuleQuality", quality_name(beacon_module_quality)), + ]) +} + +/// `BuildPayload`. +fn build_payload() -> Json { + let presets = [ + OilFieldOptions::for_small_iron_electric_pole(), + OilFieldOptions::for_small_electric_pole(), + OilFieldOptions::for_medium_electric_pole(), + OilFieldOptions::for_big_electric_pole(), + OilFieldOptions::for_substation(), + ]; + + Json::object([ + ("options", build_options()), + ( + "electricPolePresets", + Json::Object( + presets + .iter() + .map(|options| (options.electric_pole_entity_name.clone(), preset(options))) + .collect(), + ), + ), + ( + "qualityLevels", + Json::Object( + Quality::ALL + .iter() + .map(|quality| (quality_text(*quality), Json::Int(quality.level()))) + .collect(), + ), + ), + ( + "allPipeStrategies", + pipe_strategy_names(&ALL_PIPE_STRATEGIES), + ), + ( + "allBeaconStrategies", + beacon_strategy_names(&ALL_BEACON_STRATEGIES), + ), + ]) +} + +/// `Preset`. +fn preset(options: &OilFieldOptions) -> Json { + Json::object([ + ("width", Json::Int(options.electric_pole_width)), + ("height", Json::Int(options.electric_pole_height)), + ("supplyWidth", Json::Int(options.electric_pole_supply_width)), + ( + "supplyHeight", + Json::Int(options.electric_pole_supply_height), + ), + ("wireReach", Json::Double(options.electric_pole_wire_reach)), + ]) +} + +fn pipe_strategy_names(strategies: &[PipeStrategy]) -> Json { + Json::Array( + strategies + .iter() + .map(|s| Json::Str(s.name().to_string())) + .collect(), + ) +} + +fn beacon_strategy_names(strategies: &[BeaconStrategy]) -> Json { + Json::Array( + strategies + .iter() + .map(|s| Json::Str(s.name().to_string())) + .collect(), + ) +} + +/// A `Dictionary` of modules serializes as an object, in insertion order. +fn modules(modules: Vec<(String, i32)>) -> Json { + Json::Object( + modules + .into_iter() + .map(|(name, count)| (name, Json::Int(count))) + .collect(), + ) +} + +/// `Enum.ToString()`: the member name, or the number for a value the enum does not name. +fn quality_text(quality: Quality) -> String { + quality + .name() + .map_or_else(|| quality.level().to_string(), str::to_string) +} + +fn quality_name(quality: Quality) -> Json { + Json::Str(quality_text(quality)) +} + +/// Just enough of a JSON tree to write the file in Verify's layout. Objects keep their keys +/// in insertion order, as the C#'s anonymous types and dictionaries do. +enum Json { + Bool(bool), + Int(i32), + /// A C# `double`, written as .NET writes it: 9.0 is `9`, not `9.0`. + Double(f64), + Str(String), + Array(Vec), + Object(Vec<(String, Json)>), +} + +impl Json { + fn object(entries: [(&str, Json); N]) -> Json { + Json::Object( + entries + .into_iter() + .map(|(key, value)| (key.to_string(), value)) + .collect(), + ) + } +} + +/// The whole file: a UTF-8 byte order mark, then the document with no newline at the end. +fn render_file(root: &Json) -> Vec { + let mut text = String::new(); + render(root, 0, &mut text); + let mut bytes = vec![0xEF, 0xBB, 0xBF]; + bytes.extend_from_slice(text.as_bytes()); + bytes +} + +fn render(value: &Json, depth: usize, out: &mut String) { + match value { + Json::Bool(value) => out.push_str(if *value { "true" } else { "false" }), + Json::Int(value) => out.push_str(&value.to_string()), + Json::Double(value) => out.push_str(&format_f64(*value)), + Json::Str(value) => push_string(value, out), + Json::Array(items) => render_container('[', ']', items, depth, out, |item, out| { + render(item, depth + 1, out) + }), + Json::Object(entries) => { + render_container('{', '}', entries, depth, out, |(key, value), out| { + push_string(key, out); + out.push_str(": "); + render(value, depth + 1, out); + }) + } + } +} + +/// Writes each item on its own line, indented one level past `depth`. An empty container +/// stays on one line (`[]`, `{}`). +fn render_container( + open: char, + close: char, + items: &[T], + depth: usize, + out: &mut String, + mut render_item: impl FnMut(&T, &mut String), +) { + out.push(open); + for (index, item) in items.iter().enumerate() { + if index > 0 { + out.push(','); + } + out.push('\n'); + push_indent(depth + 1, out); + render_item(item, out); + } + if !items.is_empty() { + out.push('\n'); + push_indent(depth, out); + } + out.push(close); +} + +fn push_indent(depth: usize, out: &mut String) { + out.push_str(&" ".repeat(depth)); +} + +/// Every string here is a plain ASCII name, so standard JSON escaping gives the same text as +/// Verify's writer. +fn push_string(value: &str, out: &mut String) { + out.push_str(&serde_json::to_string(value).expect("a string always serializes")); +} From d7a7457259302a7b743e13ce886d1d5486b5f205 Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 03:35:51 -0700 Subject: [PATCH 2/8] Port FactorioOracleTest to Rust (port stage 13a) rust/planner/tests/factorio_oracle.rs checks the planner's hardcoded Factorio facts against test/FactorioTools.Test/OilField/factorio-oracle.json, as FactorioOracleTest.cs does: vanilla entity and module names, the pumpjack terminal offsets, direction values, raw pole and beacon geometry, and MAX_UNDERGROUND against max_underground_distance. It also checks the planner's own footprints (PUMPJACK_WIDTH and the options presets) against the collision boxes. EntityNameToSize lives in the blueprint crate as a private function, so its check is a unit test in rust/blueprint/src/write.rs. Rust has no reflection, so entity_names::vanilla and item_names::vanilla gain ALL arrays, and a data.rs unit test counts the constants in each module's source so a constant missing from ALL fails. MAX_UNDERGROUND is now pub, matching the rest of the planner crate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- rust/blueprint/src/write.rs | 54 ++++ rust/planner/src/data.rs | 64 ++++ .../src/steps/plan_underground_pipes.rs | 3 +- rust/planner/tests/factorio_oracle.rs | 275 ++++++++++++++++++ 4 files changed, 395 insertions(+), 1 deletion(-) create mode 100644 rust/planner/tests/factorio_oracle.rs diff --git a/rust/blueprint/src/write.rs b/rust/blueprint/src/write.rs index 5772d3a9..851b047d 100644 --- a/rust/blueprint/src/write.rs +++ b/rust/blueprint/src/write.rs @@ -429,3 +429,57 @@ pub fn encode_blueprint_json(json: &str) -> String { let compressed = encoder.finish().expect("writing to memory cannot fail"); format!("0{}", STANDARD.encode(compressed)) } + +#[cfg(test)] +mod tests { + use super::*; + + /// The Factorio oracle (`tools/capture-factorio-oracle.sh`). The planner crate's + /// `tests/factorio_oracle.rs` checks the rest of it. + fn factorio_oracle_path() -> std::path::PathBuf { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../test/FactorioTools.Test/OilField/factorio-oracle.json") + } + + /// `FactorioOracleTest.EntityNameToSizeMatchesTheDerivedCollisionBoxFootprint`: each + /// footprint is the collision box rounded up to whole tiles, as the game derives it. + /// Names absent from the fixture are skipped, which covers the AAI Industry pole: the + /// oracle is captured with mods disabled on purpose. + #[test] + fn entity_size_matches_the_derived_collision_box_footprint() { + let text = std::fs::read_to_string(factorio_oracle_path()).unwrap(); + let oracle: serde_json::Value = serde_json::from_str(&text).unwrap(); + let names = entity_names::vanilla::ALL + .into_iter() + .chain([entity_names::aai_industry::SMALL_IRON_ELECTRIC_POLE]); + + let mut mismatches = Vec::new(); + for name in names { + let Some(entity) = oracle["entities"].get(name) else { + continue; + }; + let corner = |i: usize| { + let point = &entity["collision_box"][i]; + (point[0].as_f64().unwrap(), point[1].as_f64().unwrap()) + }; + let (min, max) = (corner(0), corner(1)); + let width = (max.0 - min.0).ceil() as f32; + let height = (max.1 - min.1).ceil() as f32; + + let size = entity_size(name); + if size != (width, height) { + mismatches.push(format!( + "{name}: entity_size says {}x{}, collision_box derives {width}x{height}", + size.0, size.1 + )); + } + } + + assert!( + mismatches.is_empty(), + "{}. Either Factorio changed (re-run tools/capture-factorio-oracle.sh and review \ + the diff), or the footprint table is wrong.", + mismatches.join("; ") + ); + } +} diff --git a/rust/planner/src/data.rs b/rust/planner/src/data.rs index 299870f3..d008232f 100644 --- a/rust/planner/src/data.rs +++ b/rust/planner/src/data.rs @@ -149,6 +149,22 @@ pub mod entity_names { pub const BEACON: &str = "beacon"; pub const HEAT_PIPE: &str = "heat-pipe"; pub const WALL: &str = "stone-wall"; + + /// Every constant above, for the tests that check each name against Factorio. The + /// C# gets this list by reflection. `all_arrays_match_their_constants` fails if a + /// constant is added here and not to this array. + pub const ALL: [&str; 10] = [ + PUMPJACK, + PIPE, + PIPE_TO_GROUND, + SMALL_ELECTRIC_POLE, + MEDIUM_ELECTRIC_POLE, + BIG_ELECTRIC_POLE, + SUBSTATION, + BEACON, + HEAT_PIPE, + WALL, + ]; } pub mod aai_industry { @@ -164,6 +180,14 @@ pub mod item_names { pub const PRODUCTIVITY_MODULE_3: &str = "productivity-module-3"; pub const SPEED_MODULE_3: &str = "speed-module-3"; pub const BLUEPRINT: &str = "blueprint"; + + /// Every constant above, as `entity_names::vanilla::ALL` is. + pub const ALL: [&str; 4] = [ + EFFICIENCY_MODULE_3, + PRODUCTIVITY_MODULE_3, + SPEED_MODULE_3, + BLUEPRINT, + ]; } } @@ -188,4 +212,44 @@ mod tests { assert_eq!(Direction::default(), Direction::Up); assert_eq!(Direction::Right.to_string(), "Right"); } + + /// The source text inside the `pub mod vanilla {` block that follows `parent` in this + /// file. These blocks hold no nested braces, so the first `}` closes them. + fn vanilla_source(parent: &str) -> &'static str { + let source = include_str!("data.rs"); + let open = "pub mod vanilla {"; + let start = source.find(parent).expect("parent module"); + let start = start + source[start..].find(open).expect("vanilla module") + open.len(); + let end = start + source[start..].find('}').expect("closing brace"); + &source[start..end] + } + + /// Rust has no reflection, so the `ALL` arrays are kept by hand. This counts the + /// constants declared in each block's source and checks that every array value is + /// declared there exactly once. A constant left out of `ALL`, or one listed twice, fails. + #[test] + fn all_arrays_match_their_constants() { + let cases: [(&str, &[&str]); 2] = [ + ("pub mod entity_names {", &entity_names::vanilla::ALL), + ("pub mod item_names {", &item_names::vanilla::ALL), + ]; + for (parent, all) in cases { + let block = vanilla_source(parent); + // Every `pub const` except `ALL` itself. + let declared = block.matches("pub const ").count() - 1; + assert_eq!( + declared, + all.len(), + "{parent}: a constant is missing from ALL" + ); + for name in all { + let literal = format!("\"{name}\""); + assert_eq!( + block.matches(&literal).count(), + 1, + "{parent}: {name} is not declared exactly once" + ); + } + } + } } diff --git a/rust/planner/src/steps/plan_underground_pipes.rs b/rust/planner/src/steps/plan_underground_pipes.rs index b023bda9..dc6d4b58 100644 --- a/rust/planner/src/steps/plan_underground_pipes.rs +++ b/rust/planner/src/steps/plan_underground_pipes.rs @@ -20,7 +20,8 @@ use crate::steps::validate; const MIN_UNDERGROUND: usize = 3; /// The longest underground pipe, ends included (9 cells between the ends, per the wiki). -const MAX_UNDERGROUND: usize = 11; +/// Public only so `tests/factorio_oracle.rs` can check it against the game. +pub const MAX_UNDERGROUND: usize = 11; /// `Execute(context, pipes)`: the underground pipes and the direction each end faces. The /// cells between each pair of ends are removed from `pipes`. diff --git a/rust/planner/tests/factorio_oracle.rs b/rust/planner/tests/factorio_oracle.rs new file mode 100644 index 00000000..c572c6eb --- /dev/null +++ b/rust/planner/tests/factorio_oracle.rs @@ -0,0 +1,275 @@ +//! `test/FactorioTools.Test/OilField/FactorioOracleTest.cs`, ported: the planner's hardcoded +//! Factorio facts checked against an oracle captured from the game itself +//! (`tools/capture-factorio-oracle.sh`). +//! +//! This reads the COMMITTED fixture, never the game, so CI needs no Factorio install. +//! Re-capture after a Factorio update and commit the diff; a changed fixture failing here is +//! the signal that a constant needs review. +//! +//! `EntityNameToSize` lives in the blueprint crate, so its check is a unit test there +//! (`blueprint::write::tests`). This file checks the footprints the planner itself uses. + +use std::collections::HashSet; +use std::path::PathBuf; + +use planner::Location; +use planner::data::{Direction, entity_names, item_names}; +use planner::helpers::{PUMPJACK_HEIGHT, PUMPJACK_WIDTH, TERMINAL_OFFSETS}; +use planner::options::OilFieldOptions; +use planner::steps::plan_underground_pipes::MAX_UNDERGROUND; +use serde_json::Value; + +use entity_names::vanilla; + +/// The one place this file names the fixture's location. +fn factorio_oracle_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../test/FactorioTools.Test/OilField/factorio-oracle.json") +} + +const RE_CAPTURE_HINT: &str = "Two likely causes: either Factorio changed (re-run \ + tools/capture-factorio-oracle.sh and review the diff), or a name was added to \ + entity_names::vanilla without adding it to WANTED_ENTITIES in tools/trim-factorio-oracle.py."; + +fn oracle() -> Value { + let text = std::fs::read_to_string(factorio_oracle_path()).unwrap(); + serde_json::from_str(&text).unwrap() +} + +/// `Names`: the keys of an object or the strings of an array. +fn names(parent: &Value, property: &str) -> HashSet { + match &parent[property] { + Value::Object(map) => map.keys().cloned().collect(), + Value::Array(items) => items + .iter() + .map(|x| x.as_str().unwrap().to_string()) + .collect(), + other => panic!("{property} is neither an object nor an array: {other}"), + } +} + +fn coordinates(point: &Value) -> Vec { + point + .as_array() + .unwrap() + .iter() + .map(|x| x.as_f64().unwrap()) + .collect() +} + +/// `EveryVanillaEntityNameExistsInFactorio`. This checks `entity_names::vanilla` only, so +/// `entity_names::aai_industry` is deliberately NOT checked. Those names come from the AAI +/// Industry mod, and the oracle is captured with mods disabled on purpose, so their absence +/// is expected rather than drift. +#[test] +fn every_vanilla_entity_name_exists_in_factorio() { + let entities = names(&oracle(), "entities"); + + let missing: Vec<_> = vanilla::ALL + .into_iter() + .filter(|name| !entities.contains(*name)) + .collect(); + + assert!( + missing.is_empty(), + "Not in Factorio: {}. {RE_CAPTURE_HINT}", + missing.join(", ") + ); +} + +/// `EveryVanillaModuleNameExistsInFactorio`. +#[test] +fn every_vanilla_module_name_exists_in_factorio() { + let modules = names(&oracle(), "modules"); + + let missing: Vec<_> = item_names::vanilla::ALL + .into_iter() + // "blueprint" is an item, not a module, so it is not in the module list. + .filter(|name| *name != item_names::vanilla::BLUEPRINT) + .filter(|name| !modules.contains(*name)) + .collect(); + + assert!( + missing.is_empty(), + "Not a Factorio module: {}. {RE_CAPTURE_HINT}", + missing.join(", ") + ); +} + +/// `TerminalOffsetsMatchTheFactorioOutputCorners`. `TERMINAL_OFFSETS` says which tile a +/// pumpjack's pipe occupies, one entry per rotation. The fixture records the prototype's +/// `output_fluid_box.pipe_connections` positions, also one per rotation in north, east, +/// south, west order. The position is the connection point inside the entity, and the pipe +/// sits one tile further out in the direction the entity faces. +/// +/// That step-one-tile-outward rule was measured, not assumed: a probe mod read +/// `PipeConnection.target_position` out of running 2.0.77 and 2.1.14 games and the rule +/// reproduced both. Factorio 2.1 gave each rotation its own output corner (FFF #442), which +/// is why the east and west offsets moved. See issue #81 and the C# comment. +#[test] +fn terminal_offsets_match_the_factorio_output_corners() { + let cases = [ + (0, Direction::Up, 0, -1), + (1, Direction::Right, 1, 0), + (2, Direction::Down, 0, 1), + (3, Direction::Left, -1, 0), + ]; + let oracle = oracle(); + let positions = &oracle["entities"][vanilla::PUMPJACK]["output_fluid_box"]["pipe_connections"] + [0]["positions"]; + + for (rotation, direction, step_x, step_y) in cases { + let position = coordinates(&positions[rotation]); + let expected = Location::new(position[0] as i32 + step_x, position[1] as i32 + step_y); + + let actual = TERMINAL_OFFSETS + .iter() + .find(|(d, _)| *d == direction) + .map(|(_, offset)| *offset) + .unwrap(); + + assert!( + expected == actual, + "Factorio puts the {direction} pumpjack's pipe at {expected:?}, but TERMINAL_OFFSETS \ + says {actual:?}. Every plan would attach the pipe to the wrong corner. \ + {RE_CAPTURE_HINT}" + ); + } +} + +/// `InternalDirectionDoublesToTheFactorioValue`. The internal enum is deliberately 1.1-style +/// four-way (N=0, E=2, S=4, W=6). Factorio 2.0 is 16-way, so the blueprint value is always +/// exactly double. +#[test] +fn internal_direction_doubles_to_the_factorio_value() { + let cases = [ + (Direction::Up, "north"), + (Direction::Right, "east"), + (Direction::Down, "south"), + (Direction::Left, "west"), + ]; + let oracle = oracle(); + + for (direction, factorio_name) in cases { + let expected = oracle["directions"][factorio_name].as_i64().unwrap(); + assert_eq!( + expected, + i64::from(direction.value() * 2), + "{direction} vs {factorio_name}" + ); + } +} + +/// `RawGeometryBehindTheOptionsPresetsIsUnchanged`. As in the C#, the values are pinned +/// here rather than read from `OilFieldOptions`: the presets derive tile counts from these, +/// so a move here means the presets need review. +#[test] +fn raw_geometry_behind_the_options_presets_is_unchanged() { + let cases = [ + (vanilla::SMALL_ELECTRIC_POLE, "supply_area_distance", 2.5), + (vanilla::MEDIUM_ELECTRIC_POLE, "supply_area_distance", 3.5), + (vanilla::BIG_ELECTRIC_POLE, "supply_area_distance", 2.0), + (vanilla::SUBSTATION, "supply_area_distance", 9.0), + (vanilla::SMALL_ELECTRIC_POLE, "maximum_wire_distance", 7.5), + (vanilla::MEDIUM_ELECTRIC_POLE, "maximum_wire_distance", 9.0), + (vanilla::BIG_ELECTRIC_POLE, "maximum_wire_distance", 32.0), + (vanilla::SUBSTATION, "maximum_wire_distance", 18.0), + (vanilla::BEACON, "supply_area_distance", 3.0), + // Beacon strength itself, not just its supply area. distribution_effectivity is the + // multiplier a beacon applies to the module effects it broadcasts (1.5 = 150%). + // Nothing in the planner reads this value today, but pinning it means a Factorio + // balance change that alters beacon strength is noticed here rather than silently + // changing plan quality. + (vanilla::BEACON, "distribution_effectivity", 1.5), + ]; + let oracle = oracle(); + + for (entity, field, expected) in cases { + let actual = oracle["entities"][entity][field].as_f64().unwrap(); + assert!( + expected == actual, + "{entity}.{field} moved from {expected} to {actual}, so the OilFieldOptions presets \ + need review. {RE_CAPTURE_HINT}" + ); + } +} + +/// The planner's own footprints, checked the way +/// `EntityNameToSizeMatchesTheDerivedCollisionBoxFootprint` checks the blueprint writer's: +/// the collision box rounded up to whole tiles. The C# has no such test; it is here because +/// the planner keeps these sizes apart from `EntityNameToSize`, in `PUMPJACK_WIDTH` and the +/// `OilFieldOptions` presets. The AAI Industry preset is left out, as its pole is a mod +/// entity. +#[test] +fn planner_footprints_match_the_derived_collision_box_footprint() { + let mut sizes = vec![(vanilla::PUMPJACK, PUMPJACK_WIDTH, PUMPJACK_HEIGHT)]; + for options in [ + OilFieldOptions::for_small_electric_pole(), + OilFieldOptions::for_medium_electric_pole(), + OilFieldOptions::for_big_electric_pole(), + OilFieldOptions::for_substation(), + ] { + sizes.push(( + vanilla::ALL + .into_iter() + .find(|name| *name == options.electric_pole_entity_name) + .unwrap(), + options.electric_pole_width, + options.electric_pole_height, + )); + } + let options = OilFieldOptions::default(); + assert_eq!(options.beacon_entity_name, vanilla::BEACON); + sizes.push((vanilla::BEACON, options.beacon_width, options.beacon_height)); + + let oracle = oracle(); + let mut mismatches = Vec::new(); + for (name, width, height) in sizes { + let collision_box = &oracle["entities"][name]["collision_box"]; + let (min, max) = ( + coordinates(&collision_box[0]), + coordinates(&collision_box[1]), + ); + let derived = ( + (max[0] - min[0]).ceil() as i32, + (max[1] - min[1]).ceil() as i32, + ); + if (width, height) != derived { + mismatches.push(format!( + "{name}: the planner says {width}x{height}, collision_box derives {}x{}", + derived.0, derived.1 + )); + } + } + + assert!( + mismatches.is_empty(), + "{}. {RE_CAPTURE_HINT}", + mismatches.join("; ") + ); +} + +/// `MaxUndergroundIsOneMoreThanFactoriosGapDistance`. `MAX_UNDERGROUND` (11) counts both +/// underground ends of a run, while Factorio's `max_underground_distance` (10, on +/// pipe-to-ground) counts only the gap between them. So the two are off by exactly one, and +/// that relationship is the thing worth pinning. +#[test] +fn max_underground_is_one_more_than_factorios_gap_distance() { + let oracle = oracle(); + let max_underground_distance = + oracle["entities"][vanilla::PIPE_TO_GROUND]["fluid_box"]["pipe_connections"] + .as_array() + .unwrap() + .iter() + .find_map(|c| c.get("max_underground_distance")) + .unwrap() + .as_u64() + .unwrap() as usize; + + assert!( + MAX_UNDERGROUND == max_underground_distance + 1, + "MAX_UNDERGROUND is {MAX_UNDERGROUND} but max_underground_distance is now \ + {max_underground_distance}, so the relationship (MAX_UNDERGROUND == \ + max_underground_distance + 1) no longer holds. {RE_CAPTURE_HINT}" + ); +} From ee8f6c30df668567fb720772a2d24b314860a0b5 Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 03:35:43 -0700 Subject: [PATCH 3/8] Freeze the TS API types and check them against the contract fixtures (port stage 13a) FactorioToolsApi.ts was generated from the WebApp's swagger.json, which goes away with the .NET code in 13b. It is now a hand-maintained file: the unused HTTP client plumbing is gone, along with @ts-nocheck and the generated banner, and it is linted and formatted like the rest of src/. FactorioToolsApi.test.ts checks it against the plan and normalize responses in rust/contract/fixtures/contract.jsonl: typed samples the compiler checks with `satisfies Required<...>`, the key shape and value types of every recorded response, every strategy and quality name the contract writes, and the error envelope shape. Also drops the swagger-gen script and the swagger-typescript-api dependency, the CI step that regenerated the client, the client's .gitattributes line, and ApiError.response, which nothing has set since the site moved to the in-browser planner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- .gitattributes | 8 +- .github/workflows/ci.yml | 16 - src/vue/.prettierignore | 1 - src/vue/eslint.config.ts | 5 +- src/vue/package-lock.json | 1019 ------------------ src/vue/package.json | 4 +- src/vue/src/components/ResponseErrorView.vue | 3 - src/vue/src/lib/FactorioToolsApi.test.ts | 291 +++++ src/vue/src/lib/FactorioToolsApi.ts | 485 ++------- src/vue/src/lib/OilFieldPlanner.ts | 2 - 10 files changed, 384 insertions(+), 1450 deletions(-) create mode 100644 src/vue/src/lib/FactorioToolsApi.test.ts diff --git a/.gitattributes b/.gitattributes index 4f9c807d..fa5627f0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,12 +3,10 @@ # produce CRLF and fail that check for no real reason. *.lua text eol=lf -# Same deal for the other two committed generated files CI now checks against a -# fresh regeneration: swagger.json (Swashbuckle CLI) and the TS client generated -# from it (swagger-typescript-api). Both are LF today; pinning them keeps a regen -# on a Windows checkout from failing those checks on line endings alone. +# Same deal for swagger.json (Swashbuckle CLI), another committed generated file +# CI checks against a fresh regeneration. It is LF today; pinning it keeps a regen +# on a Windows checkout from failing that check on line endings alone. src/WebApp/swagger.json text eol=lf -src/vue/src/lib/FactorioToolsApi.ts text eol=lf *.verified.txt text eol=lf working-tree-encoding=UTF-8 *.verified.xml text eol=lf working-tree-encoding=UTF-8 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a972939b..c14bc4c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,22 +55,6 @@ jobs: run: npm run build working-directory: ${{ env.BUILD_PATH }} - # "npm run build" runs swagger-gen first, so the build above has already - # regenerated the committed TS client from the committed swagger.json. - # This is the second link in the chain the swagger.json check below guards: - # WebApp C# -> swagger.json -> src/vue/src/lib -> the deployed front-end. - # Without this, the client could keep describing an older contract than the - # swagger.json sitting next to it. Only FactorioToolsApi.ts is generated - - # everything else in src/lib is hand-written. - - name: Check the committed API client is up to date - run: | - if [ -n "$(git status --porcelain -- src/vue/src/lib/FactorioToolsApi.ts)" ]; then - echo "::error::src/vue/src/lib/FactorioToolsApi.ts does not match what swagger.json generates. Run 'npm run swagger-gen' in src/vue and commit the result." - git diff -- src/vue/src/lib/FactorioToolsApi.ts - exit 1 - fi - echo "src/vue/src/lib/FactorioToolsApi.ts matches the generated client." - - name: Test run: npm run test working-directory: ${{ env.BUILD_PATH }} diff --git a/src/vue/.prettierignore b/src/vue/.prettierignore index 63b96bf2..e937d82b 100644 --- a/src/vue/.prettierignore +++ b/src/vue/.prettierignore @@ -1,5 +1,4 @@ node_modules/ dist/ public/framework/ -src/lib/FactorioToolsApi.ts src/lib/plannerDefaults.verified.json diff --git a/src/vue/eslint.config.ts b/src/vue/eslint.config.ts index c44d0118..1557f1b8 100644 --- a/src/vue/eslint.config.ts +++ b/src/vue/eslint.config.ts @@ -11,9 +11,8 @@ export default defineConfigWithVueTs( }, { name: 'app/files-to-ignore', - // Generated swagger client (@ts-nocheck, regenerated by `npm run swagger-gen`), - // build output, and the .NET WASM bundle. - ignores: ['**/dist/**', '**/public/framework/**', 'src/lib/FactorioToolsApi.ts', 'src/lib/plannerDefaults.verified.json'], + // Build output, the .NET WASM bundle, and the generated planner defaults. + ignores: ['**/dist/**', '**/public/framework/**', 'src/lib/plannerDefaults.verified.json'], }, pluginVue.configs['flat/essential'], vueTsConfigs.recommended, diff --git a/src/vue/package-lock.json b/src/vue/package-lock.json index a5959c56..567a7fe6 100644 --- a/src/vue/package-lock.json +++ b/src/vue/package-lock.json @@ -26,7 +26,6 @@ "prettier": "^3.9.6", "sass": "^1.102.0", "shx": "^0.4.0", - "swagger-typescript-api": "^13.12.6", "typescript": "^6.0.3", "vite": "^8.1.5", "vitest": "^5.0.0", @@ -35,97 +34,6 @@ "wrangler": "^4.141.0" } }, - "node_modules/@apidevtools/json-schema-ref-parser": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/@apidevtools/json-schema-ref-parser/-/json-schema-ref-parser-14.0.1.tgz", - "integrity": "sha512-Oc96zvmxx1fqoSEdUmfmvvb59/KDOnUoJ7s2t7bISyAn0XEz57LCCw8k2Y4Pf3mwKaZLMciESALORLgfe2frCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/json-schema": "^7.0.15", - "js-yaml": "^4.1.0" - }, - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/philsturgeon" - } - }, - "node_modules/@apidevtools/openapi-schemas": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@apidevtools/openapi-schemas/-/openapi-schemas-2.1.0.tgz", - "integrity": "sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/@apidevtools/swagger-methods": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@apidevtools/swagger-methods/-/swagger-methods-3.0.2.tgz", - "integrity": "sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@apidevtools/swagger-parser": { - "version": "12.1.0", - "resolved": "https://registry.npmjs.org/@apidevtools/swagger-parser/-/swagger-parser-12.1.0.tgz", - "integrity": "sha512-e5mJoswsnAX0jG+J09xHFYQXb/bUc5S3pLpMxUuRUA2H8T2kni3yEoyz2R3Dltw5f4A6j6rPNMpWTK+iVDFlng==", - "dev": true, - "license": "MIT", - "dependencies": { - "@apidevtools/json-schema-ref-parser": "14.0.1", - "@apidevtools/openapi-schemas": "^2.1.0", - "@apidevtools/swagger-methods": "^3.0.2", - "ajv": "^8.17.1", - "ajv-draft-04": "^1.0.0", - "call-me-maybe": "^1.0.2" - }, - "peerDependencies": { - "openapi-types": ">=7" - } - }, - "node_modules/@apidevtools/swagger-parser/node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@apidevtools/swagger-parser/node_modules/ajv-draft-04": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/ajv-draft-04/-/ajv-draft-04-1.0.0.tgz", - "integrity": "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "ajv": "^8.5.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, - "node_modules/@apidevtools/swagger-parser/node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true, - "license": "MIT" - }, "node_modules/@babel/helper-string-parser": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", @@ -172,36 +80,6 @@ "node": ">=6.9.0" } }, - "node_modules/@biomejs/js-api": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@biomejs/js-api/-/js-api-6.0.0.tgz", - "integrity": "sha512-8HP7wexjQo5Np1J9h0B2x8L5G0GZpCacgjykxLHtvLPvF0hNqSG754oh8bxo+OSFDpVGMfSjmLO+ZY/5KbfjmQ==", - "dev": true, - "license": "MIT OR Apache-2.0", - "peerDependencies": { - "@biomejs/wasm-bundler": "^2.5.0", - "@biomejs/wasm-nodejs": "^2.5.0", - "@biomejs/wasm-web": "^2.5.0" - }, - "peerDependenciesMeta": { - "@biomejs/wasm-bundler": { - "optional": true - }, - "@biomejs/wasm-nodejs": { - "optional": true - }, - "@biomejs/wasm-web": { - "optional": true - } - } - }, - "node_modules/@biomejs/wasm-nodejs": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/@biomejs/wasm-nodejs/-/wasm-nodejs-2.5.2.tgz", - "integrity": "sha512-B0r7jLdCmXhq4+jnx1oA0/SChLy5G283r35HJr276T+w6qgqAPAhqfnlKs+UobclAfidNDbfj9ZmcuCijaHDxQ==", - "dev": true, - "license": "MIT OR Apache-2.0" - }, "node_modules/@cacheable/memory": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", @@ -919,13 +797,6 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, - "node_modules/@exodus/schemasafe": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@exodus/schemasafe/-/schemasafe-1.3.0.tgz", - "integrity": "sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==", - "dev": true, - "license": "MIT" - }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -2430,21 +2301,6 @@ "undici-types": ">=7.24.0 <7.24.7" } }, - "node_modules/@types/swagger-schema-official": { - "version": "2.0.25", - "resolved": "https://registry.npmjs.org/@types/swagger-schema-official/-/swagger-schema-official-2.0.25.tgz", - "integrity": "sha512-T92Xav+Gf/Ik1uPW581nA+JftmjWPgskw/WBf4TJzxRG/SJ+DfNnNE+WuZ4mrXuzflQMqMkm1LSYjzYW7MB1Cg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/trusted-types": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", - "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.71.2", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.2.tgz", @@ -3069,39 +2925,6 @@ "dev": true, "license": "MIT" }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -3294,35 +3117,6 @@ "node": ">=8" } }, - "node_modules/c12": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz", - "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==", - "dev": true, - "license": "MIT", - "dependencies": { - "chokidar": "^5.0.0", - "confbox": "^0.2.4", - "defu": "^6.1.6", - "dotenv": "^17.3.1", - "exsolve": "^1.0.8", - "giget": "^3.2.0", - "jiti": "^2.6.1", - "ohash": "^2.0.11", - "pathe": "^2.0.3", - "perfect-debounce": "^2.1.0", - "pkg-types": "^2.3.0", - "rc9": "^3.0.1" - }, - "peerDependencies": { - "magicast": "*" - }, - "peerDependenciesMeta": { - "magicast": { - "optional": true - } - } - }, "node_modules/cacheable": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", @@ -3337,13 +3131,6 @@ "qified": "^0.10.1" } }, - "node_modules/call-me-maybe": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz", - "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==", - "dev": true, - "license": "MIT" - }, "node_modules/chai": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", @@ -3370,26 +3157,6 @@ "url": "https://paulmillr.com/funding/" } }, - "node_modules/citty": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", - "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", - "dev": true, - "license": "MIT" - }, - "node_modules/class-variance-authority": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", - "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "clsx": "^2.1.1" - }, - "funding": { - "url": "https://polar.sh/cva" - } - }, "node_modules/clipboard-image": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/clipboard-image/-/clipboard-image-0.1.0.tgz", @@ -3430,68 +3197,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/clsx": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", - "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/confbox": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", - "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/consola": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", - "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.18.0 || >=16.10.0" - } - }, "node_modules/cookie": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", @@ -3569,13 +3274,6 @@ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, - "node_modules/dayjs": { - "version": "1.11.23", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", - "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", - "dev": true, - "license": "MIT" - }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -3608,13 +3306,6 @@ "dev": true, "license": "MIT" }, - "node_modules/destr": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", - "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", - "dev": true, - "license": "MIT" - }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -3625,36 +3316,6 @@ "node": ">=8" } }, - "node_modules/dompurify": { - "version": "3.4.17", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz", - "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==", - "dev": true, - "license": "(MPL-2.0 OR Apache-2.0)", - "optionalDependencies": { - "@types/trusted-types": "^2.0.7" - } - }, - "node_modules/dotenv": { - "version": "17.4.2", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", - "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, "node_modules/end-of-stream": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", @@ -3704,26 +3365,6 @@ "dev": true, "license": "MIT" }, - "node_modules/es-toolkit": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", - "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", - "dev": true, - "license": "MIT", - "workspaces": [ - "docs", - "benchmarks", - "tests/types", - "tests/browser-compat" - ] - }, - "node_modules/es6-promise": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", - "integrity": "sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==", - "dev": true, - "license": "MIT" - }, "node_modules/esbuild": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", @@ -3766,16 +3407,6 @@ "@esbuild/win32-x64": "0.28.2" } }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -4059,19 +3690,6 @@ "node": ">=0.10.0" } }, - "node_modules/eta": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/eta/-/eta-3.5.0.tgz", - "integrity": "sha512-e3x3FBvGzeCIHhF+zhK8FZA2vC5uFn6b4HJjegUbIWrDb4mJ7JjTGMJY9VGIbRVpmSwHopNiaJibhjIr+HfLug==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - }, - "funding": { - "url": "https://github.com/eta-dev/eta?sponsor=1" - } - }, "node_modules/execa": { "version": "9.6.1", "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.1.tgz", @@ -4174,30 +3792,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-safe-stringify": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-uri": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", - "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, "node_modules/fastq": { "version": "1.20.3", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", @@ -4308,16 +3902,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, "node_modules/get-stream": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz", @@ -4335,16 +3919,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/giget": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz", - "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==", - "dev": true, - "license": "MIT", - "bin": { - "giget": "dist/cli.mjs" - } - }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -4398,13 +3972,6 @@ "dev": true, "license": "MIT" }, - "node_modules/http2-client": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/http2-client/-/http2-client-1.3.5.tgz", - "integrity": "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==", - "dev": true, - "license": "MIT" - }, "node_modules/human-signals": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz", @@ -4494,16 +4061,6 @@ "node": ">=0.10.0" } }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -4647,29 +4204,6 @@ "jiti": "lib/jiti-cli.mjs" } }, - "node_modules/js-yaml": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", - "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/puzrin" - }, - { - "type": "github", - "url": "https://github.com/sponsors/nodeca" - } - ], - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -5208,25 +4742,6 @@ "dev": true, "license": "MIT" }, - "node_modules/nanoid": { - "version": "5.1.16", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz", - "integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.js" - }, - "engines": { - "node": "^18 || >=20" - } - }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -5249,50 +4764,6 @@ "license": "MIT", "optional": true }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-fetch-h2": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/node-fetch-h2/-/node-fetch-h2-2.3.0.tgz", - "integrity": "sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==", - "dev": true, - "license": "MIT", - "dependencies": { - "http2-client": "^1.2.5" - }, - "engines": { - "node": "4.x || >=6.0.0" - } - }, - "node_modules/node-readfiles": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/node-readfiles/-/node-readfiles-0.2.0.tgz", - "integrity": "sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es6-promise": "^3.2.1" - } - }, "node_modules/nostics": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/nostics/-/nostics-1.3.0.tgz", @@ -5343,111 +4814,6 @@ "url": "https://github.com/fb55/nth-check?sponsor=1" } }, - "node_modules/oas-kit-common": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/oas-kit-common/-/oas-kit-common-1.0.8.tgz", - "integrity": "sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "fast-safe-stringify": "^2.0.7" - } - }, - "node_modules/oas-linter": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/oas-linter/-/oas-linter-3.2.2.tgz", - "integrity": "sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@exodus/schemasafe": "^1.0.0-rc.2", - "should": "^13.2.1", - "yaml": "^1.10.0" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/oas-linter/node_modules/yaml": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", - "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 6" - } - }, - "node_modules/oas-resolver": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/oas-resolver/-/oas-resolver-2.5.6.tgz", - "integrity": "sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "node-fetch-h2": "^2.3.0", - "oas-kit-common": "^1.0.8", - "reftools": "^1.1.9", - "yaml": "^1.10.0", - "yargs": "^17.0.1" - }, - "bin": { - "resolve": "resolve.js" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/oas-resolver/node_modules/yaml": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", - "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 6" - } - }, - "node_modules/oas-schema-walker": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/oas-schema-walker/-/oas-schema-walker-1.1.5.tgz", - "integrity": "sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==", - "dev": true, - "license": "BSD-3-Clause", - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/oas-validator": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/oas-validator/-/oas-validator-5.0.8.tgz", - "integrity": "sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "call-me-maybe": "^1.0.1", - "oas-kit-common": "^1.0.8", - "oas-linter": "^3.2.2", - "oas-resolver": "^2.5.6", - "oas-schema-walker": "^1.1.5", - "reftools": "^1.1.9", - "should": "^13.2.1", - "yaml": "^1.10.0" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/oas-validator/node_modules/yaml": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", - "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 6" - } - }, "node_modules/obug": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", @@ -5462,13 +4828,6 @@ "node": ">=12.20.0" } }, - "node_modules/ohash": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", - "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", - "dev": true, - "license": "MIT" - }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -5495,13 +4854,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/openapi-types": { - "version": "12.1.3", - "resolved": "https://registry.npmjs.org/openapi-types/-/openapi-types-12.1.3.tgz", - "integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==", - "dev": true, - "license": "MIT" - }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -5927,17 +5279,6 @@ ], "license": "MIT" }, - "node_modules/rc9": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.1.0.tgz", - "integrity": "sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "defu": "^6.1.7", - "destr": "^2.0.5" - } - }, "node_modules/readdirp": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", @@ -5964,36 +5305,6 @@ "node": ">= 0.10" } }, - "node_modules/reftools": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/reftools/-/reftools-1.1.9.tgz", - "integrity": "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==", - "dev": true, - "license": "BSD-3-Clause", - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/resolve": { "version": "1.22.13", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz", @@ -6462,66 +5773,6 @@ "which": "bin/which" } }, - "node_modules/should": { - "version": "13.2.3", - "resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz", - "integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-equal": "^2.0.0", - "should-format": "^3.0.3", - "should-type": "^1.4.0", - "should-type-adaptors": "^1.0.1", - "should-util": "^1.0.0" - } - }, - "node_modules/should-equal": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz", - "integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-type": "^1.4.0" - } - }, - "node_modules/should-format": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz", - "integrity": "sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-type": "^1.3.0", - "should-type-adaptors": "^1.0.1" - } - }, - "node_modules/should-type": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz", - "integrity": "sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/should-type-adaptors": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz", - "integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-type": "^1.3.0", - "should-util": "^1.0.0" - } - }, - "node_modules/should-util": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.1.tgz", - "integrity": "sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==", - "dev": true, - "license": "MIT" - }, "node_modules/shx": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/shx/-/shx-0.4.0.tgz", @@ -6568,34 +5819,6 @@ "dev": true, "license": "MIT" }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/strip-eof": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", @@ -6675,99 +5898,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/swagger-schema-official": { - "version": "2.0.0-bab6bed", - "resolved": "https://registry.npmjs.org/swagger-schema-official/-/swagger-schema-official-2.0.0-bab6bed.tgz", - "integrity": "sha512-rCC0NWGKr/IJhtRuPq/t37qvZHI/mH4I4sxflVM+qgVe5Z2uOCivzWaVbuioJaB61kvm5UvB7b49E+oBY0M8jA==", - "dev": true, - "license": "ISC" - }, - "node_modules/swagger-typescript-api": { - "version": "13.13.0", - "resolved": "https://registry.npmjs.org/swagger-typescript-api/-/swagger-typescript-api-13.13.0.tgz", - "integrity": "sha512-4CEj48R1Kk3Zvul4c8NVeLOUQ86WIRq1MgqRaB12jKI70IT/UUc4/xn+vd9pWK+I8eRALX2UnUI1ld0YQHn16A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@apidevtools/swagger-parser": "12.1.0", - "@biomejs/js-api": "6.0.0", - "@biomejs/wasm-nodejs": "2.5.2", - "@types/swagger-schema-official": "^2.0.25", - "c12": "^3.3.4", - "citty": "^0.2.2", - "consola": "^3.4.2", - "es-toolkit": "^1.49.0", - "eta": "^3.5.0", - "nanoid": "^5.1.16", - "openapi-types": "^12.1.3", - "swagger-schema-official": "2.0.0-bab6bed", - "swagger2openapi": "^7.0.8", - "type-fest": "^5.7.0", - "typescript": "^6.0.3", - "yaml": "^2.9.0", - "yummies": "7.20.1" - }, - "bin": { - "swagger-typescript-api": "dist/cli.mjs" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/swagger-typescript-api/node_modules/type-fest": { - "version": "5.10.0", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz", - "integrity": "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "dependencies": { - "tagged-tag": "^1.0.0" - }, - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/swagger2openapi": { - "version": "7.0.8", - "resolved": "https://registry.npmjs.org/swagger2openapi/-/swagger2openapi-7.0.8.tgz", - "integrity": "sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "call-me-maybe": "^1.0.1", - "node-fetch": "^2.6.1", - "node-fetch-h2": "^2.3.0", - "node-readfiles": "^0.2.0", - "oas-kit-common": "^1.0.8", - "oas-resolver": "^2.5.6", - "oas-schema-walker": "^1.1.5", - "oas-validator": "^5.0.8", - "reftools": "^1.1.9", - "yaml": "^1.10.0", - "yargs": "^17.0.1" - }, - "bin": { - "boast": "boast.js", - "oas-validate": "oas-validate.js", - "swagger2openapi": "swagger2openapi.js" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/swagger2openapi/node_modules/yaml": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", - "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 6" - } - }, "node_modules/synckit": { "version": "0.12.3", "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.12.3.tgz", @@ -6798,30 +5928,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/tagged-tag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", - "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/tailwind-merge": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.7.0.tgz", - "integrity": "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/dcastil" - } - }, "node_modules/tinybench": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", @@ -6903,13 +6009,6 @@ "node": ">=8.0" } }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true, - "license": "MIT" - }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -7515,13 +6614,6 @@ "typescript": ">=5.0.0" } }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true, - "license": "BSD-2-Clause" - }, "node_modules/webpack-virtual-modules": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", @@ -7529,17 +6621,6 @@ "dev": true, "license": "MIT" }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "dev": true, - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -7636,24 +6717,6 @@ } } }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -7693,61 +6756,6 @@ "node": ">=18" } }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/yaml": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", - "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", - "dev": true, - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } - }, - "node_modules/yargs": { - "version": "17.7.3", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", - "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", @@ -7798,33 +6806,6 @@ "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } - }, - "node_modules/yummies": { - "version": "7.20.1", - "resolved": "https://registry.npmjs.org/yummies/-/yummies-7.20.1.tgz", - "integrity": "sha512-H/AxRy+SjVlfpeI0TkiVkU/M2n+XpR1XGt5yS5r7GsP9Iz3mr17dbq9DLW18PmMlyKO78+yvH/9Z9VAnVuV3og==", - "dev": true, - "license": "MIT", - "dependencies": { - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "dayjs": "^1.11.21", - "dompurify": "^3.4.11", - "nanoid": "^5.1.15", - "tailwind-merge": "^3.6.0" - }, - "peerDependencies": { - "mobx": "^6.12.4", - "react": "^18 || ^19" - }, - "peerDependenciesMeta": { - "mobx": { - "optional": true - }, - "react": { - "optional": true - } - } } } } diff --git a/src/vue/package.json b/src/vue/package.json index 6d9e6e99..a1029cb9 100644 --- a/src/vue/package.json +++ b/src/vue/package.json @@ -5,12 +5,11 @@ "type": "module", "scripts": { "dev": "vite", - "build": "npm run swagger-gen && vue-tsc && vite build && cd dist && shx cp index.html 404.html", + "build": "vue-tsc && vite build && cd dist && shx cp index.html 404.html", "build-all": "npm run build-wasm && npm run build", "preview": "vite preview", "lint": "eslint . --fix", "format": "prettier --write src/", - "swagger-gen": "swagger-typescript-api generate --path ../WebApp/swagger.json --output src/lib --name FactorioToolsApi", "build-wasm": "cd ../../rust && cargo build --release -p planner-wasm --target wasm32-unknown-unknown && shx cp target/wasm32-unknown-unknown/release/planner_wasm.wasm planner-wasm/js/planner.js ../src/vue/src/lib/planner-wasm/", "test": "vitest run", "test:watch": "vitest" @@ -34,7 +33,6 @@ "prettier": "^3.9.6", "sass": "^1.102.0", "shx": "^0.4.0", - "swagger-typescript-api": "^13.12.6", "typescript": "^6.0.3", "vite": "^8.1.5", "vitest": "^5.0.0", diff --git a/src/vue/src/components/ResponseErrorView.vue b/src/vue/src/components/ResponseErrorView.vue index b1e98cb4..b0d3cf23 100644 --- a/src/vue/src/components/ResponseErrorView.vue +++ b/src/vue/src/components/ResponseErrorView.vue @@ -19,9 +19,6 @@
{{ value }}
-
-
{{ JSON.stringify(error.response.error, null, "  ") }}
-
diff --git a/src/vue/src/lib/FactorioToolsApi.test.ts b/src/vue/src/lib/FactorioToolsApi.test.ts new file mode 100644 index 00000000..439f422b --- /dev/null +++ b/src/vue/src/lib/FactorioToolsApi.test.ts @@ -0,0 +1,291 @@ +// TypeScript 6 no longer loads every @types package by default, and this is the only file +// under src/ that uses Node APIs. +/// +import { readFileSync } from "node:fs" +import { describe, expect, it } from "vitest" +import { + BeaconStrategy, + OilFieldNormalizeResponse, + OilFieldPlan, + OilFieldPlanRequestResponse, + OilFieldPlanResponse, + OilFieldPlanSummary, + PipeStrategy, + Quality, +} from "./FactorioToolsApi" + +// Checks the hand-maintained types in FactorioToolsApi.ts against the responses the Rust +// contract test replays (rust/contract/FIXTURES.md has the line format). The samples below +// are checked by the compiler (`npm run build` runs vue-tsc over this file): `satisfies +// Required<...>` fails on a missing or extra property. The tests then check every recorded +// response has exactly the samples' keys and value types, so a field renamed on either side +// fails here. +const CONTRACT_FIXTURES = new URL( + "../../../../rust/contract/fixtures/contract.jsonl", + import.meta.url, +) + +const planSample = { + pipeStrategy: PipeStrategy.Fbe, + optimizePipes: true, + beaconStrategy: BeaconStrategy.Snug, + beaconEffectCount: 1, + beaconCount: 1, + pipeCount: 1, + pipeCountWithoutUnderground: 1, +} satisfies Required + +const planResponseSample = { + request: { + useUndergroundPipes: true, + addBeacons: true, + optimizePipes: true, + overlapBeacons: true, + addElectricPoles: true, + addHeatPipes: false, + heatPipeEntityName: "heat-pipe", + pipeStrategies: [PipeStrategy.Fbe], + beaconStrategies: [BeaconStrategy.Fbe], + electricPoleEntityName: "medium-electric-pole", + electricPoleSupplyWidth: 7, + electricPoleSupplyHeight: 7, + electricPoleWireReach: 9, + electricPoleWidth: 1, + electricPoleHeight: 1, + beaconEntityName: "beacon", + beaconSupplyWidth: 9, + beaconSupplyHeight: 9, + beaconWidth: 3, + beaconHeight: 3, + validateSolution: false, + pumpjackModules: { "productivity-module-3": 2 }, + beaconModules: { "speed-module-3": 2 }, + pumpjackQuality: Quality.Normal, + beaconQuality: Quality.Normal, + electricPoleQuality: Quality.Normal, + pumpjackModuleQuality: Quality.Normal, + beaconModuleQuality: Quality.Normal, + blueprint: "0e...", + addFbeOffset: false, + } satisfies Required, + blueprint: "0e...", + summary: { + missingPumpjacks: 0, + rotatedPumpjacks: 0, + heatDroppedPumpjacks: 0, + unheatedPumpjacks: 0, + unheatedPipes: 0, + selectedPlans: [planSample], + alternatePlans: [planSample], + unusedPlans: [planSample], + } satisfies Required, +} satisfies Required + +const normalizeResponseSample = { + request: { blueprint: "0e..." }, + blueprint: "0e...", +} satisfies Required + +// Map-typed fields: the keys are module names, so only the values are checked. +const RECORD_FIELDS = new Set(["pumpjackModules", "beaconModules"]) + +// Fields the contract may write as null. +const NULLABLE_FIELDS = new Set(["beaconStrategy"]) + +// The C# echoes a quality integer it has no name for as that integer, and the Rust port +// matches it. The site only ever sends names, so the type stays Quality and this one +// recorded case may hold a number there. +const NUMBER_QUALITY = { name: "read_quality-undefined-integer", path: ".request.pumpjackQuality" } + +type Line = { name: string; op: string; outcome: string; response: string } +type Envelope = { title: unknown; status: unknown; errors: unknown } + +function readFixtures(): { name: string; op: "plan" | "normalize"; response: unknown }[] { + return readFileSync(CONTRACT_FIXTURES, "utf8") + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as Line) + .filter((line) => (line.op === "plan" || line.op === "normalize") && line.outcome === "ok") + .map((line) => ({ + name: line.name, + op: line.op as "plan" | "normalize", + response: JSON.parse(line.response), + })) +} + +// The same check runWasm in OilFieldPlanner.ts uses to tell an error envelope from a response. +function isEnvelope(value: unknown): value is Envelope { + return ( + typeof value === "object" && + value !== null && + "status" in value && + "errors" in value && + !("blueprint" in value) + ) +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} + +// Collects every place `actual` differs in shape from `sample`: a key missing or extra, a +// value of another type, or an array element unlike the sample's one element. `seen` gets +// every sample path that some value was checked against, so the caller can tell whether +// the fixtures reached all of a sample (an empty array checks nothing). +function compareShape( + actual: unknown, + sample: unknown, + path: string, + key: string, + problems: string[], + seen: Set, +): void { + seen.add(path) + if (actual === null && NULLABLE_FIELDS.has(key)) { + return + } + if (Array.isArray(sample)) { + if (!Array.isArray(actual)) { + problems.push(`${path}: expected an array, got ${JSON.stringify(actual)}`) + return + } + for (const element of actual) { + compareShape(element, sample[0], `${path}[]`, key, problems, seen) + } + } else if (isObject(sample)) { + if (!isObject(actual)) { + problems.push(`${path}: expected an object, got ${JSON.stringify(actual)}`) + } else if (RECORD_FIELDS.has(key)) { + for (const [name, value] of Object.entries(actual)) { + if (typeof value !== "number") { + problems.push(`${path}.${name}: expected a number, got ${JSON.stringify(value)}`) + } + } + } else { + const actualKeys = Object.keys(actual).sort() + const sampleKeys = Object.keys(sample).sort() + if (actualKeys.join() !== sampleKeys.join()) { + problems.push(`${path}: keys [${actualKeys}] differ from the sample's [${sampleKeys}]`) + } + for (const name of sampleKeys) { + if (name in actual) { + compareShape(actual[name], sample[name], `${path}.${name}`, name, problems, seen) + } + } + } + } else if (typeof actual !== typeof sample) { + problems.push(`${path}: expected ${typeof sample}, got ${JSON.stringify(actual)}`) + } +} + +// Every path in the sample, in the form compareShape adds to `seen`. +function samplePaths(sample: unknown, path: string, key: string, out: Set): Set { + out.add(path) + if (Array.isArray(sample)) { + samplePaths(sample[0], `${path}[]`, key, out) + } else if (isObject(sample) && !RECORD_FIELDS.has(key)) { + for (const [name, value] of Object.entries(sample)) { + samplePaths(value, `${path}.${name}`, name, out) + } + } + return out +} + +function checkShapes(op: "plan" | "normalize", sample: object) { + const cases = readFixtures().filter((c) => c.op === op && !isEnvelope(c.response)) + const problems: string[] = [] + const seen = new Set() + for (const c of cases) { + const caseProblems: string[] = [] + compareShape(c.response, sample, "", "", caseProblems, seen) + const allowed = `${NUMBER_QUALITY.path}: expected string, got ` + const isAllowed = (p: string) => + c.name === NUMBER_QUALITY.name && + p.startsWith(allowed) && + /^-?\d+$/.test(p.slice(allowed.length)) + problems.push(...caseProblems.filter((p) => !isAllowed(p)).map((p) => `${c.name} ${p}`)) + } + return { count: cases.length, problems, seen } +} + +describe("FactorioToolsApi types against the contract fixtures", () => { + it("match every recorded plan response", () => { + const { count, problems, seen } = checkShapes("plan", planResponseSample) + expect(count).toBeGreaterThan(200) + expect(problems).toEqual([]) + expect( + [...samplePaths(planResponseSample, "", "", new Set())].filter((p) => !seen.has(p)), + ).toEqual([]) + }) + + it("match every recorded normalize response", () => { + const { count, problems, seen } = checkShapes("normalize", normalizeResponseSample) + expect(count).toBeGreaterThan(100) + expect(problems).toEqual([]) + expect( + [...samplePaths(normalizeResponseSample, "", "", new Set())].filter((p) => !seen.has(p)), + ).toEqual([]) + }) + + it("name every strategy and quality the contract writes, and no others", () => { + const pipe = new Set() + const beacon = new Set() + const quality = new Set() + const numberQualities: string[] = [] + for (const c of readFixtures()) { + if (c.op !== "plan" || isEnvelope(c.response)) { + continue + } + const response = c.response as OilFieldPlanResponse + const request = response.request + request.pipeStrategies.forEach((s) => pipe.add(s)) + request.beaconStrategies.forEach((s) => beacon.add(s)) + for (const q of [ + request.pumpjackQuality, + request.beaconQuality, + request.electricPoleQuality, + request.pumpjackModuleQuality, + request.beaconModuleQuality, + ]) { + if (typeof q === "number" && c.name === NUMBER_QUALITY.name) { + numberQualities.push(c.name) + } else { + quality.add(q) + } + } + const { selectedPlans, alternatePlans, unusedPlans } = response.summary + for (const plan of [...selectedPlans, ...alternatePlans, ...unusedPlans]) { + pipe.add(plan.pipeStrategy) + if (plan.beaconStrategy !== null) { + beacon.add(plan.beaconStrategy) + } + } + } + + const sorted = (values: Iterable) => [...values].map(String).sort() + expect(sorted(pipe)).toEqual(sorted(Object.values(PipeStrategy))) + expect(sorted(beacon)).toEqual(sorted(Object.values(BeaconStrategy))) + expect(sorted(quality)).toEqual(sorted(Object.values(Quality))) + // If this case goes away, so can NUMBER_QUALITY. + expect(numberQualities).toEqual([NUMBER_QUALITY.name]) + }) + + it("read every recorded error envelope as title, status and errors", () => { + const envelopes = readFixtures() + .map((c) => c.response) + .filter(isEnvelope) + expect(envelopes.length).toBeGreaterThan(20) + for (const envelope of envelopes) { + expect(Object.keys(envelope).sort()).toEqual(["errors", "status", "title"]) + expect(typeof envelope.title).toBe("string") + expect(typeof envelope.status).toBe("number") + expect(isObject(envelope.errors)).toBe(true) + for (const messages of Object.values(envelope.errors as object)) { + expect(Array.isArray(messages)).toBe(true) + for (const message of messages as unknown[]) { + expect(typeof message).toBe("string") + } + } + } + }) +}) diff --git a/src/vue/src/lib/FactorioToolsApi.ts b/src/vue/src/lib/FactorioToolsApi.ts index 9eb2e6c8..02a57792 100644 --- a/src/vue/src/lib/FactorioToolsApi.ts +++ b/src/vue/src/lib/FactorioToolsApi.ts @@ -1,14 +1,8 @@ -/* eslint-disable */ -/* tslint:disable */ -// @ts-nocheck -/* - * --------------------------------------------------------------- - * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ## - * ## ## - * ## AUTHOR: acacode ## - * ## SOURCE: https://github.com/acacode/swagger-typescript-api ## - * --------------------------------------------------------------- - */ +// The JSON shapes the Rust planner (rust/contract, through planner-wasm) reads and writes. +// Hand-maintained: this started as the client swagger-typescript-api generated from the +// C# WebApp's swagger.json, and was frozen when the site moved to the Rust planner. +// FactorioToolsApi.test.ts checks these types against the responses recorded in +// rust/contract/fixtures/contract.jsonl, so a change to the contract shows up there. /** * A Factorio 2.0 quality tier. The integer value is the quality bonus level used to scale @@ -44,7 +38,7 @@ export interface OilFieldNormalizeRequest { * The input blueprint containing at least one pumpjack. * @minLength 1 */ - blueprint: string; + blueprint: string } /** The properties needed to normalize a oil field blueprint. */ @@ -53,45 +47,45 @@ export interface OilFieldNormalizeRequestResponse { * The input blueprint containing at least one pumpjack. * @minLength 1 */ - blueprint: string; + blueprint: string } /** The normalized oil field blueprint. */ export interface OilFieldNormalizeResponse { /** The original request provided, included expanded defaults. */ - request: OilFieldNormalizeRequestResponse; + request: OilFieldNormalizeRequestResponse /** The output normalized blueprint. */ - blueprint: string; + blueprint: string } /** A particular attempt oil field plan. */ export interface OilFieldPlan { /** The pipe strategy used to generate the plan. */ - pipeStrategy: PipeStrategy; + pipeStrategy: PipeStrategy /** Whether or not the pipe optimized was used. */ - optimizePipes: boolean; + optimizePipes: boolean /** Which beacon strategy, if any, was used. */ - beaconStrategy?: BeaconStrategy | null; + beaconStrategy?: BeaconStrategy | null /** * The number of effects the beacons provided to pumpjacks. Higher is better. * @format int32 */ - beaconEffectCount: number; + beaconEffectCount: number /** * The number of beacons in the plan. For the same number of beacon effects, lower is better. * @format int32 */ - beaconCount: number; + beaconCount: number /** * The number of pipes in the plan. For the same number of beacon effects and beacons, lower is better. If underground pipes are used, this only counts the upwards and downwards connections for the underground stretches of pipes. * @format int32 */ - pipeCount: number; + pipeCount: number /** * The number of pipes before beacons or underground pipes are placed. * @format int32 */ - pipeCountWithoutUnderground: number; + pipeCountWithoutUnderground: number } /** The properties needed to generate an oil field plan. */ @@ -100,30 +94,30 @@ export interface OilFieldPlanRequest { * Whether or not underground pipes (pipe-to-ground) should be used. * @default true */ - useUndergroundPipes?: boolean; + useUndergroundPipes?: boolean /** * Whether or not to add beacons around the pumpjacks. * @default true */ - addBeacons?: boolean; + addBeacons?: boolean /** * Whether or not to use the pipe optimizer after each pipe strategy is executed. If set to true, the best solution * found will still be used, meaning if the unoptimized pipe plan performs better, it will be preferred over the * corresponding optimized pipe plan. * @default true */ - optimizePipes?: boolean; + optimizePipes?: boolean /** * Whether or to allow beacon effects to overlap. For Factorio mods like Space Exploration, beacon effects cannot * overlap otherwise pumpjacks will break down with a beacon overload. For vanilla Factorio, this should be true. * @default true */ - overlapBeacons?: boolean; + overlapBeacons?: boolean /** * Whether or not to add electric poles around the pumpjacks and (optionally) beacons. * @default true */ - addElectricPoles?: boolean; + addElectricPoles?: boolean /** * Whether or not to route a heat pipe network adjacent to every pumpjack and pipe. This is required on Aquilo * (Factorio 2.0 / Space Age) where unheated entities freeze. When enabled, the output blueprint is emitted in the @@ -134,168 +128,168 @@ export interface OilFieldPlanRequest { * best-effort and may be reduced (even to none) on tight fields where heat needs the contested tiles. * @default false */ - addHeatPipes?: boolean; + addHeatPipes?: boolean /** * The internal entity name for the heat pipe to use. * @default "heat-pipe" */ - heatPipeEntityName?: string; + heatPipeEntityName?: string /** * The pipe planning strategies to attempt. * @default ["Fbe","ConnectedCentersDelaunay","ConnectedCentersDelaunayMst","ConnectedCentersFlute"] */ - pipeStrategies?: PipeStrategy[]; + pipeStrategies?: PipeStrategy[] /** * The beacon planning strategies to attempt. This will have no affect if Knapcode.FactorioTools.OilField.OilFieldOptions.AddBeacons is false. * @default ["Fbe","Snug"] */ - beaconStrategies?: BeaconStrategy[]; + beaconStrategies?: BeaconStrategy[] /** * The internal entity name for the electric pole to use. * @default "medium-electric-pole" */ - electricPoleEntityName?: string; + electricPoleEntityName?: string /** * The supply width (horizontal) for the electric pole. This is the width of the area that the electric pole will * provide power to. * @format int32 * @default 7 */ - electricPoleSupplyWidth?: number; + electricPoleSupplyWidth?: number /** * The supply height (vertical) for the electric pole. This is the height of the area that the electric pole will * provide power to. * @format int32 * @default 7 */ - electricPoleSupplyHeight?: number; + electricPoleSupplyHeight?: number /** * The wire reach for the electric pole. This is how far apart electric poles can be but still be connected. * @format double * @default 9 */ - electricPoleWireReach?: number; + electricPoleWireReach?: number /** * The width of the electric pole entity. * @format int32 * @default 1 */ - electricPoleWidth?: number; + electricPoleWidth?: number /** * The height of the electric pole entity. * @format int32 * @default 1 */ - electricPoleHeight?: number; + electricPoleHeight?: number /** * The internal entity name for the beacon to use. * @default "beacon" */ - beaconEntityName?: string; + beaconEntityName?: string /** * The supply width (horizontal) for the beacon. This is the width of the area that the beacon will provide * module effects to. * @format int32 * @default 9 */ - beaconSupplyWidth?: number; + beaconSupplyWidth?: number /** * The supply height (vertical) for the beacon. This is the height of the area that the beacon will provide * module effects to. * @format int32 * @default 9 */ - beaconSupplyHeight?: number; + beaconSupplyHeight?: number /** * The width of the beacon entity. * @format int32 * @default 3 */ - beaconWidth?: number; + beaconWidth?: number /** * The height of the beacon entity. * @format int32 * @default 3 */ - beaconHeight?: number; + beaconHeight?: number /** * Whether or not additional validations should be perform on the blueprint correctness. In most cases this should * be false. If you see an invalid blueprint returned, try setting this to true and reporting a bug. * @default false */ - validateSolution?: boolean; + validateSolution?: boolean /** * The modules to add to the pumpjacks. The string key is the internal item name for the module. The value is the * count that kind of module to add to each pumpjack. There can be multiple module types provided. * @default {"productivity-module-3":2} */ - pumpjackModules?: Record; + pumpjackModules?: Record /** * The modules to add to the beacons. The string key is the internal item name for the module. The value is the * count that kind of module to add to each beacon. There can be multiple module types provided. * @default {"speed-module-3":2} */ - beaconModules?: Record; + beaconModules?: Record /** * The quality of the pumpjack entities in the output blueprint. Output-only; does not affect planning. * @default "Normal" */ - pumpjackQuality?: Quality; + pumpjackQuality?: Quality /** * The quality of the beacon entities in the output blueprint. Output-only; does not affect planning. * @default "Normal" */ - beaconQuality?: Quality; + beaconQuality?: Quality /** * The quality of the electric pole entities. Higher quality enlarges the supply area and wire reach * the planner uses (see Context), so this affects planning, not just output. * @default "Normal" */ - electricPoleQuality?: Quality; + electricPoleQuality?: Quality /** * The quality of the modules inserted into pumpjacks. Output-only; does not affect planning. * @default "Normal" */ - pumpjackModuleQuality?: Quality; + pumpjackModuleQuality?: Quality /** * The quality of the modules inserted into beacons. Output-only; does not affect planning. * @default "Normal" */ - beaconModuleQuality?: Quality; + beaconModuleQuality?: Quality /** * The input blueprint containing at least one pumpjack. * @minLength 1 * @example "0eJyMj70OwjAMhN/lZg8NbHkVhFB/rMrQuFGSIqoq707aMiCVgcWSz+fP5wXNMLEPogl2gbSjRtjLgii91sOqae0YFn5y/l63DxDS7FdFEjtkgmjHL1iTrwTWJEl4Z2zNfNPJNRyKgX6w/BjLwqjrpQI5E+ZSC7WTwO0+qTIdYKc/YKbaaOaAK0G38Pbre8KTQ/wY8hsAAP//AwAEfF3F" */ - blueprint: string; + blueprint: string /** * Whether or not to add a placeholder entity to the output grid so that the planning grid entity coordinates match * the entity coordinate when the output blueprint is pasted into Factorio Blueprint Editor (FBE). This helps with * debugging the planner. * @default false */ - addFbeOffset?: boolean; + addFbeOffset?: boolean } /** The properties needed to generate an oil field plan. */ export interface OilFieldPlanRequestResponse { /** Whether or not underground pipes (pipe-to-ground) should be used. */ - useUndergroundPipes: boolean; + useUndergroundPipes: boolean /** Whether or not to add beacons around the pumpjacks. */ - addBeacons: boolean; + addBeacons: boolean /** * Whether or not to use the pipe optimizer after each pipe strategy is executed. If set to true, the best solution * found will still be used, meaning if the unoptimized pipe plan performs better, it will be preferred over the * corresponding optimized pipe plan. */ - optimizePipes: boolean; + optimizePipes: boolean /** * Whether or to allow beacon effects to overlap. For Factorio mods like Space Exploration, beacon effects cannot * overlap otherwise pumpjacks will break down with a beacon overload. For vanilla Factorio, this should be true. */ - overlapBeacons: boolean; + overlapBeacons: boolean /** Whether or not to add electric poles around the pumpjacks and (optionally) beacons. */ - addElectricPoles: boolean; + addElectricPoles: boolean /** * Whether or not to route a heat pipe network adjacent to every pumpjack and pipe. This is required on Aquilo * (Factorio 2.0 / Space Age) where unheated entities freeze. When enabled, the output blueprint is emitted in the @@ -305,115 +299,115 @@ export interface OilFieldPlanRequestResponse { * heat network first and then places beacons around it, choosing a pipe layout it can fully heat. Beacons are * best-effort and may be reduced (even to none) on tight fields where heat needs the contested tiles. */ - addHeatPipes: boolean; + addHeatPipes: boolean /** The internal entity name for the heat pipe to use. */ - heatPipeEntityName: string; + heatPipeEntityName: string /** The pipe planning strategies to attempt. */ - pipeStrategies: PipeStrategy[]; + pipeStrategies: PipeStrategy[] /** The beacon planning strategies to attempt. This will have no affect if Knapcode.FactorioTools.OilField.OilFieldOptions.AddBeacons is false. */ - beaconStrategies: BeaconStrategy[]; + beaconStrategies: BeaconStrategy[] /** The internal entity name for the electric pole to use. */ - electricPoleEntityName: string; + electricPoleEntityName: string /** * The supply width (horizontal) for the electric pole. This is the width of the area that the electric pole will * provide power to. * @format int32 */ - electricPoleSupplyWidth: number; + electricPoleSupplyWidth: number /** * The supply height (vertical) for the electric pole. This is the height of the area that the electric pole will * provide power to. * @format int32 */ - electricPoleSupplyHeight: number; + electricPoleSupplyHeight: number /** * The wire reach for the electric pole. This is how far apart electric poles can be but still be connected. * @format double */ - electricPoleWireReach: number; + electricPoleWireReach: number /** * The width of the electric pole entity. * @format int32 */ - electricPoleWidth: number; + electricPoleWidth: number /** * The height of the electric pole entity. * @format int32 */ - electricPoleHeight: number; + electricPoleHeight: number /** The internal entity name for the beacon to use. */ - beaconEntityName: string; + beaconEntityName: string /** * The supply width (horizontal) for the beacon. This is the width of the area that the beacon will provide * module effects to. * @format int32 */ - beaconSupplyWidth: number; + beaconSupplyWidth: number /** * The supply height (vertical) for the beacon. This is the height of the area that the beacon will provide * module effects to. * @format int32 */ - beaconSupplyHeight: number; + beaconSupplyHeight: number /** * The width of the beacon entity. * @format int32 */ - beaconWidth: number; + beaconWidth: number /** * The height of the beacon entity. * @format int32 */ - beaconHeight: number; + beaconHeight: number /** * Whether or not additional validations should be perform on the blueprint correctness. In most cases this should * be false. If you see an invalid blueprint returned, try setting this to true and reporting a bug. */ - validateSolution: boolean; + validateSolution: boolean /** * The modules to add to the pumpjacks. The string key is the internal item name for the module. The value is the * count that kind of module to add to each pumpjack. There can be multiple module types provided. */ - pumpjackModules: Record; + pumpjackModules: Record /** * The modules to add to the beacons. The string key is the internal item name for the module. The value is the * count that kind of module to add to each beacon. There can be multiple module types provided. */ - beaconModules: Record; + beaconModules: Record /** The quality of the pumpjack entities in the output blueprint. Output-only; does not affect planning. */ - pumpjackQuality: Quality; + pumpjackQuality: Quality /** The quality of the beacon entities in the output blueprint. Output-only; does not affect planning. */ - beaconQuality: Quality; + beaconQuality: Quality /** * The quality of the electric pole entities. Higher quality enlarges the supply area and wire reach * the planner uses (see Context), so this affects planning, not just output. */ - electricPoleQuality: Quality; + electricPoleQuality: Quality /** The quality of the modules inserted into pumpjacks. Output-only; does not affect planning. */ - pumpjackModuleQuality: Quality; + pumpjackModuleQuality: Quality /** The quality of the modules inserted into beacons. Output-only; does not affect planning. */ - beaconModuleQuality: Quality; + beaconModuleQuality: Quality /** * The input blueprint containing at least one pumpjack. * @minLength 1 */ - blueprint: string; + blueprint: string /** * Whether or not to add a placeholder entity to the output grid so that the planning grid entity coordinates match * the entity coordinate when the output blueprint is pasted into Factorio Blueprint Editor (FBE). This helps with * debugging the planner. */ - addFbeOffset: boolean; + addFbeOffset: boolean } /** The resulting oil field plan. */ export interface OilFieldPlanResponse { /** The original request provided, included expanded defaults. */ - request: OilFieldPlanRequestResponse; + request: OilFieldPlanRequestResponse /** The output blueprint, containing the planned oil field. */ - blueprint: string; + blueprint: string /** A summary of different oil field plans attempted and their performance. */ - summary: OilFieldPlanSummary; + summary: OilFieldPlanSummary } /** A summary of the various oil field plans attempted. */ @@ -422,336 +416,31 @@ export interface OilFieldPlanSummary { * The number of pumpjacks removed to allow for electric poles. This must be zero. * @format int32 */ - missingPumpjacks: number; + missingPumpjacks: number /** * The number of pumpjacks that were rotated from their original position. * @format int32 */ - rotatedPumpjacks: number; + rotatedPumpjacks: number /** * Pumpjacks dropped so the rest of the field could be fully heated on Aquilo. Zero unless heat pipes are enabled. * @format int32 */ - heatDroppedPumpjacks: number; + heatDroppedPumpjacks: number /** * Pumpjacks still left without an adjacent heat pipe in the final output (normally zero). * @format int32 */ - unheatedPumpjacks: number; + unheatedPumpjacks: number /** * Pipe tiles still left without an adjacent heat pipe in the final output (normally zero). * @format int32 */ - unheatedPipes: number; + unheatedPipes: number /** The set of plans which exactly the same and determined to be the best. */ - selectedPlans: OilFieldPlan[]; + selectedPlans: OilFieldPlan[] /** The set of plans which are equivalent to the selected plans by ranking but not exactly the same. */ - alternatePlans: OilFieldPlan[]; + alternatePlans: OilFieldPlan[] /** The set of plans that were not the best and were discarded. */ - unusedPlans: OilFieldPlan[]; -} - -export type QueryParamsType = Record; -export type ResponseFormat = keyof Omit; - -export interface FullRequestParams extends Omit { - /** set parameter to `true` for call `securityWorker` for this request */ - secure?: boolean; - /** request path */ - path: string; - /** content type of request body */ - type?: ContentType; - /** query params */ - query?: QueryParamsType; - /** format of response (i.e. response.json() -> format: "json") */ - format?: ResponseFormat; - /** request body */ - body?: unknown; - /** base url */ - baseUrl?: string; - /** request cancellation token */ - cancelToken?: CancelToken; -} - -export type RequestParams = Omit< - FullRequestParams, - "body" | "method" | "query" | "path" ->; - -export interface ApiConfig { - baseUrl?: string; - baseApiParams?: Omit; - securityWorker?: ( - securityData: SecurityDataType | null, - ) => Promise | RequestParams | void; - customFetch?: typeof fetch; -} - -export interface HttpResponse - extends Response { - data: D; - error: E; -} - -type CancelToken = Symbol | string | number; - -export enum ContentType { - Json = "application/json", - JsonApi = "application/vnd.api+json", - FormData = "multipart/form-data", - UrlEncoded = "application/x-www-form-urlencoded", - Text = "text/plain", -} - -export class HttpClient { - public baseUrl: string = ""; - private securityData: SecurityDataType | null = null; - private securityWorker?: ApiConfig["securityWorker"]; - private abortControllers = new Map(); - private customFetch = (...fetchParams: Parameters) => - fetch(...fetchParams); - - private baseApiParams: RequestParams = { - credentials: "same-origin", - headers: {}, - redirect: "follow", - referrerPolicy: "no-referrer", - }; - - constructor(apiConfig: ApiConfig = {}) { - Object.assign(this, apiConfig); - } - - public setSecurityData = (data: SecurityDataType | null) => { - this.securityData = data; - }; - - protected encodeQueryParam(key: string, value: any) { - const encodedKey = encodeURIComponent(key); - return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`; - } - - protected addQueryParam(query: QueryParamsType, key: string) { - return this.encodeQueryParam(key, query[key]); - } - - protected addArrayQueryParam(query: QueryParamsType, key: string) { - const value = query[key]; - return value.map((v: any) => this.encodeQueryParam(key, v)).join("&"); - } - - protected toQueryString(rawQuery?: QueryParamsType): string { - const query = rawQuery || {}; - const keys = Object.keys(query).filter( - (key) => "undefined" !== typeof query[key], - ); - return keys - .map((key) => - Array.isArray(query[key]) - ? this.addArrayQueryParam(query, key) - : this.addQueryParam(query, key), - ) - .join("&"); - } - - protected addQueryParams(rawQuery?: QueryParamsType): string { - const queryString = this.toQueryString(rawQuery); - return queryString ? `?${queryString}` : ""; - } - - private contentFormatters: Record any> = { - [ContentType.Json]: (input: any) => - input !== null && (typeof input === "object" || typeof input === "string") - ? JSON.stringify(input) - : input, - [ContentType.JsonApi]: (input: any) => - input !== null && (typeof input === "object" || typeof input === "string") - ? JSON.stringify(input) - : input, - [ContentType.Text]: (input: any) => - input !== null && typeof input !== "string" - ? JSON.stringify(input) - : input, - [ContentType.FormData]: (input: any) => { - if (input instanceof FormData) { - return input; - } - - return Object.keys(input || {}).reduce((formData, key) => { - const property = input[key]; - formData.append( - key, - property instanceof Blob - ? property - : typeof property === "object" && property !== null - ? JSON.stringify(property) - : `${property}`, - ); - return formData; - }, new FormData()); - }, - [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input), - }; - - protected mergeRequestParams( - params1: RequestParams, - params2?: RequestParams, - ): RequestParams { - return { - ...this.baseApiParams, - ...params1, - ...(params2 || {}), - headers: { - ...(this.baseApiParams.headers || {}), - ...(params1.headers || {}), - ...((params2 && params2.headers) || {}), - }, - }; - } - - protected createAbortSignal = ( - cancelToken: CancelToken, - ): AbortSignal | undefined => { - if (this.abortControllers.has(cancelToken)) { - const abortController = this.abortControllers.get(cancelToken); - if (abortController) { - return abortController.signal; - } - return void 0; - } - - const abortController = new AbortController(); - this.abortControllers.set(cancelToken, abortController); - return abortController.signal; - }; - - public abortRequest = (cancelToken: CancelToken) => { - const abortController = this.abortControllers.get(cancelToken); - - if (abortController) { - abortController.abort(); - this.abortControllers.delete(cancelToken); - } - }; - - public request = async ({ - body, - secure, - path, - type, - query, - format, - baseUrl, - cancelToken, - ...params - }: FullRequestParams): Promise> => { - const secureParams = - ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) && - this.securityWorker && - (await this.securityWorker(this.securityData))) || - {}; - const requestParams = this.mergeRequestParams(params, secureParams); - const queryString = query && this.toQueryString(query); - const payloadFormatter = this.contentFormatters[type || ContentType.Json]; - const responseFormat = format || requestParams.format; - - return this.customFetch( - `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, - { - ...requestParams, - headers: { - ...(requestParams.headers || {}), - ...(type && type !== ContentType.FormData - ? { "Content-Type": type } - : {}), - }, - signal: - (cancelToken - ? this.createAbortSignal(cancelToken) - : requestParams.signal) || null, - body: - typeof body === "undefined" || body === null - ? null - : payloadFormatter(body), - }, - ).then(async (response) => { - const r = response as HttpResponse; - r.data = null as unknown as T; - r.error = null as unknown as E; - - const responseToParse = responseFormat ? response.clone() : response; - const data = !responseFormat - ? r - : await responseToParse[responseFormat]() - .then((data) => { - if (r.ok) { - r.data = data; - } else { - r.error = data; - } - return r; - }) - .catch((e) => { - r.error = e; - return r; - }); - - if (cancelToken) { - this.abortControllers.delete(cancelToken); - } - - if (!response.ok) throw data; - return data; - }); - }; -} - -/** - * @title Knapcode.FactorioTools.WebApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - * @version 1.0 - */ -export class Api< - SecurityDataType extends unknown, -> extends HttpClient { - api = { - /** - * No description - * - * @tags OilField - * @name V1OilFieldNormalizeCreate - * @request POST:/api/v1/oil-field/normalize - */ - v1OilFieldNormalizeCreate: ( - data: OilFieldNormalizeRequest, - params: RequestParams = {}, - ) => - this.request({ - path: `/api/v1/oil-field/normalize`, - method: "POST", - body: data, - type: ContentType.Json, - format: "json", - ...params, - }), - - /** - * No description - * - * @tags OilField - * @name V1OilFieldPlanCreate - * @request POST:/api/v1/oil-field/plan - */ - v1OilFieldPlanCreate: ( - data: OilFieldPlanRequest, - params: RequestParams = {}, - ) => - this.request({ - path: `/api/v1/oil-field/plan`, - method: "POST", - body: data, - type: ContentType.Json, - format: "json", - ...params, - }), - }; + unusedPlans: OilFieldPlan[] } diff --git a/src/vue/src/lib/OilFieldPlanner.ts b/src/vue/src/lib/OilFieldPlanner.ts index d418fff0..0c3a14aa 100644 --- a/src/vue/src/lib/OilFieldPlanner.ts +++ b/src/vue/src/lib/OilFieldPlanner.ts @@ -1,7 +1,6 @@ import { OilFieldStoreState, useOilFieldStore } from "../stores/OilFieldStore" import { BeaconStrategy, - HttpResponse, OilFieldNormalizeRequest, OilFieldNormalizeResponse, OilFieldPlan, @@ -88,7 +87,6 @@ export type ApiError = { title: string errors?: Record errorDetails?: string[] - response?: HttpResponse } export interface ApiResult { From afe56f01cdf99a5df3495b11d8c3a188883acd46 Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 03:39:07 -0700 Subject: [PATCH 4/8] Load the contract fixtures with a Vite raw import, not node:fs The node:fs read needed a `/// `, which puts Node's globals into the type-check of the whole app. vite/client already types `*?raw` imports as strings, and vitest resolves the file outside src/vue, so the test now imports the jsonl that way. The production build does not include it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- src/vue/src/lib/FactorioToolsApi.test.ts | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/vue/src/lib/FactorioToolsApi.test.ts b/src/vue/src/lib/FactorioToolsApi.test.ts index 439f422b..191a3048 100644 --- a/src/vue/src/lib/FactorioToolsApi.test.ts +++ b/src/vue/src/lib/FactorioToolsApi.test.ts @@ -1,7 +1,3 @@ -// TypeScript 6 no longer loads every @types package by default, and this is the only file -// under src/ that uses Node APIs. -/// -import { readFileSync } from "node:fs" import { describe, expect, it } from "vitest" import { BeaconStrategy, @@ -13,6 +9,9 @@ import { PipeStrategy, Quality, } from "./FactorioToolsApi" +// The contract fixtures, as text. A Vite raw import rather than node:fs keeps Node's types +// out of the app's type-check; vite/client (src/vite-env.d.ts) types `*?raw` as a string. +import contractJsonl from "../../../../rust/contract/fixtures/contract.jsonl?raw" // Checks the hand-maintained types in FactorioToolsApi.ts against the responses the Rust // contract test replays (rust/contract/FIXTURES.md has the line format). The samples below @@ -20,11 +19,6 @@ import { // Required<...>` fails on a missing or extra property. The tests then check every recorded // response has exactly the samples' keys and value types, so a field renamed on either side // fails here. -const CONTRACT_FIXTURES = new URL( - "../../../../rust/contract/fixtures/contract.jsonl", - import.meta.url, -) - const planSample = { pipeStrategy: PipeStrategy.Fbe, optimizePipes: true, @@ -101,7 +95,7 @@ type Line = { name: string; op: string; outcome: string; response: string } type Envelope = { title: unknown; status: unknown; errors: unknown } function readFixtures(): { name: string; op: "plan" | "normalize"; response: unknown }[] { - return readFileSync(CONTRACT_FIXTURES, "utf8") + return contractJsonl .split("\n") .filter((line) => line.length > 0) .map((line) => JSON.parse(line) as Line) From 672bf7190f1e0a69f325876c4d6d3ce39e0a317d Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 03:45:38 -0700 Subject: [PATCH 5/8] Port oil-field normalize to a Rust bin, normalize-lists (port stage 13a) `cargo run --release -p snapshots --bin normalize-lists` rewrites big-list.txt and small-list.txt the way the C# CLI's `oil-field normalize` does: big less small, then small less the new big, blueprints cleaned to their pumpjacks, repeats dropped, comments kept in the small list only. Two differences on purpose: - A blueprint's identity is its normalized JSON, the text SerializeBlueprint compresses. A line whose own data decodes strictly to exactly that text is kept as written, and lines are compared by that text. Neither flate2 nor .NET 10 reproduces the committed compressed bytes, so a literal port (or the C# itself today) would rewrite all 1,208 blueprint lines with no change. - No console prompt for a line that does not normalize: it fails naming the file and line, and --keep-invalid keeps such lines as the C#'s "y" does. tests/normalize.rs checks the committed lists are already normalized: no blueprint twice (by JSON, so a recompressed copy counts), none in both lists, and the tool's logic changes neither file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- rust/Cargo.lock | 2 + rust/snapshots/Cargo.toml | 8 + rust/snapshots/src/lib.rs | 4 + rust/snapshots/src/normalize.rs | 276 ++++++++++++++++++++++++ rust/snapshots/tests/normalize.rs | 73 +++++++ rust/snapshots/tools/normalize-lists.rs | 75 +++++++ 6 files changed, 438 insertions(+) create mode 100644 rust/snapshots/src/normalize.rs create mode 100644 rust/snapshots/tests/normalize.rs create mode 100644 rust/snapshots/tools/normalize-lists.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index e8eef596..8053352b 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -195,7 +195,9 @@ checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" name = "snapshots" version = "0.0.0" dependencies = [ + "base64", "blueprint", + "flate2", "planner", ] diff --git a/rust/snapshots/Cargo.toml b/rust/snapshots/Cargo.toml index bbca78ca..5ca1b19c 100644 --- a/rust/snapshots/Cargo.toml +++ b/rust/snapshots/Cargo.toml @@ -10,6 +10,14 @@ repository.workspace = true [lints] workspace = true +# Not in src/bin, which the repository's .gitignore ignores as a .NET output folder. +[[bin]] +name = "normalize-lists" +path = "tools/normalize-lists.rs" + [dependencies] +# normalize-lists reads a line's own compressed data strictly, beside blueprint's reader. +base64 = "0.22" blueprint = { path = "../blueprint" } +flate2 = "1" planner = { path = "../planner" } diff --git a/rust/snapshots/src/lib.rs b/rust/snapshots/src/lib.rs index 3565cc18..f94b1c94 100644 --- a/rust/snapshots/src/lib.rs +++ b/rust/snapshots/src/lib.rs @@ -4,8 +4,12 @@ //! //! It lives in its own crate because it needs both the planner and the blueprint parser, //! and because the full set is slow enough to want a release build of its own. +//! +//! [`normalize`] and the `normalize-lists` binary keep the two blueprint lists those tests +//! read normalized, in place of the C# CLI's `oil-field normalize`. pub mod issue_cases; +pub mod normalize; use std::path::{Path, PathBuf}; use std::sync::Mutex; diff --git a/rust/snapshots/src/normalize.rs b/rust/snapshots/src/normalize.rs new file mode 100644 index 00000000..ae75bfcc --- /dev/null +++ b/rust/snapshots/src/normalize.rs @@ -0,0 +1,276 @@ +//! `NormalizeBlueprints` (`src/FactorioTools.Serialization/OilField/Steps/NormalizeBlueprints.cs`), +//! the C# CLI's `oil-field normalize`: rewrites `big-list.txt` and `small-list.txt` so every +//! blueprint is cleaned to its pumpjacks, none appears twice, and none is in both lists. +//! +//! Two things differ on purpose. First, the C# writes each blueprint as it re-serializes +//! it, and zlib builds compress the same text to different bytes: flate2's output differs +//! from the committed lines, and so does .NET 10's, so either tool written literally would +//! rewrite every blueprint line with no change to any blueprint. Here a blueprint's +//! identity is its normalized JSON: the text `SerializeBlueprint` compresses for the +//! cleaned blueprint. A line whose own compressed data already decodes to exactly that text +//! is kept as it is, and lines are compared by that text, so two copies of one blueprint +//! compressed differently are duplicates. Second, where the C# asks on the console whether +//! to keep a line that does not normalize, this fails unless told to keep such lines. + +use std::collections::HashSet; +use std::io::Read; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use planner::error::FactorioToolsError; +use planner::steps::clean_blueprint; + +/// What a line of a list file holds. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Content { + /// An empty line or a `#` comment (`Valid` false in the C#). + Text, + /// A blueprint. `json` is its normalized JSON, the identity lines are compared by. + /// `output` is the line to write: the trimmed line itself when it is already + /// normalized, otherwise the blueprint re-serialized. + Blueprint { json: String, output: String }, + /// A line that failed to normalize, kept with `--keep-invalid` (the C#'s "y" answer). + Invalid, +} + +/// One line, as `NormalizeFile` reads it. +#[derive(Clone, Debug)] +struct Line { + original: String, + index: usize, + content: Content, +} + +/// What two lines are compared by: the normalized JSON for a blueprint, the line itself +/// otherwise. In the C# both are the one output string, `Normalized ?? Original`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Key<'a> { + Json(&'a str), + Raw(&'a str), +} + +impl Line { + /// `Valid`: a blueprint, or an invalid line the user chose to keep. + fn valid(&self) -> bool { + !matches!(self.content, Content::Text) + } + + fn key(&self) -> Key<'_> { + match &self.content { + Content::Blueprint { json, .. } => Key::Json(json), + Content::Text | Content::Invalid => Key::Raw(&self.original), + } + } + + /// `Normalized ?? Original`. + fn output(&self) -> &str { + match &self.content { + Content::Blueprint { output, .. } => output, + Content::Text | Content::Invalid => &self.original, + } + } +} + +/// The lines of a file as `File.ReadLines` gives them: a UTF-8 byte order mark dropped, +/// split on `\r\n`, `\n` and `\r`, with no empty line after a final line break. +pub fn file_lines(text: &str) -> Vec<&str> { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut lines: Vec<&str> = text + .split("\r\n") + .flat_map(|line| line.split(['\n', '\r'])) + .collect(); + if lines.last() == Some(&"") { + lines.pop(); + } + lines +} + +/// The decompressed bytes of a blueprint string, read strictly: canonical base64 with no +/// whitespace or missing padding, and one zlib stream that uses every byte. `None` when +/// the string is anything else, even if the lenient reader would accept it. +fn strict_payload(blueprint_string: &str) -> Option> { + let compressed = STANDARD.decode(blueprint_string.strip_prefix('0')?).ok()?; + let mut decoder = flate2::read::ZlibDecoder::new(&compressed[..]); + let mut payload = Vec::new(); + decoder.read_to_end(&mut payload).ok()?; + (decoder.total_in() == compressed.len() as u64).then_some(payload) +} + +fn describe(error: &FactorioToolsError) -> String { + let mut text = error.message.clone(); + for inner in &error.inner_messages { + text.push_str(" ---> "); + text.push_str(inner); + } + text +} + +/// `TryNormalize`: `None` for an empty line or a comment, otherwise the blueprint's +/// normalized JSON and the line to write for it. +fn try_normalize(line: &str) -> Result, String> { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + return Ok(None); + } + + let parsed = blueprint::parse_blueprint(trimmed).map_err(|e| describe(&e))?; + let clean = clean_blueprint::execute(parsed).map_err(|e| describe(&e))?; + if clean.entities.is_empty() { + return Err("There are no pumpjacks in the blueprint.".to_string()); + } + + let json = blueprint::write::output_blueprint_json(&clean, false); + let output = if strict_payload(trimmed).as_deref() == Some(json.as_bytes()) { + trimmed.to_string() + } else { + blueprint::write::encode_blueprint_json(&json) + }; + Ok(Some((json, output))) +} + +/// `NormalizeFile`. The C# asks on the console whether to keep a line that fails; this +/// fails instead, naming the file and line, unless `keep_invalid` keeps such lines as +/// they are. +fn normalize_file(name: &str, text: &str, keep_invalid: bool) -> Result, String> { + let mut lines = Vec::new(); + for (index, original) in file_lines(text).into_iter().enumerate() { + let content = match try_normalize(original) { + Ok(None) => Content::Text, + Ok(Some((json, output))) => Content::Blueprint { json, output }, + Err(_) if keep_invalid => Content::Invalid, + Err(error) => { + return Err(format!( + "{name} line {}: {error}\nFix or remove the line, or run with --keep-invalid to keep lines like it unchanged.", + index + 1 + )); + } + }; + lines.push(Line { + original: original.to_string(), + index, + content, + }); + } + Ok(lines) +} + +/// `NormalizeBlueprints.Execute`: the new text of the input file. The input's blueprints +/// stay in order, less those in the exclude file and repeats. With `allow_comments`, +/// comments and empty lines are kept, and the exclude file's are merged in by line number. +pub fn execute( + input: (&str, &str), + exclude: (&str, &str), + allow_comments: bool, + keep_invalid: bool, +) -> Result { + let exclude_lines = normalize_file(exclude.0, exclude.1, keep_invalid)?; + let input_lines = normalize_file(input.0, input.1, keep_invalid)?; + let excluded: HashSet> = exclude_lines + .iter() + .filter(|line| line.valid()) + .map(Line::key) + .collect(); + + let mut ordered: Vec<&Line> = input_lines + .iter() + .chain(&exclude_lines) + .filter(|line| allow_comments || line.valid()) + .filter(|line| !line.valid() || !excluded.contains(&line.key())) + .collect(); + // `OrderBy` is stable, so on a tie the input's line comes first. + ordered.sort_by_key(|line| line.index); + + let mut added = HashSet::new(); + let mut output = String::new(); + for line in ordered { + if added.insert(line.key()) { + output.push_str(line.output()); + output.push('\n'); + } + } + Ok(output) +} + +/// The CLI's `oil-field normalize`: the big list less the small list's blueprints and its +/// comments, then the small list less the new big list's blueprints. So a blueprint in +/// both lists ends up in the small list only. Each list is a `(name, text)` pair, the name +/// used in error messages. Returns the new big and small list texts. +pub fn normalize_lists( + big: (&str, &str), + small: (&str, &str), + keep_invalid: bool, +) -> Result<(String, String), String> { + let new_big = execute(big, small, false, keep_invalid)?; + let new_small = execute(small, (big.0, &new_big), true, keep_invalid)?; + Ok((new_big, new_small)) +} + +/// The normalized JSON of every blueprint line in a list file, with its 1-based line +/// number, for tests that look for repeats without rewriting anything. +pub fn blueprint_keys(name: &str, text: &str) -> Result, String> { + Ok(normalize_file(name, text, false)? + .into_iter() + .filter_map(|line| match line.content { + Content::Blueprint { json, .. } => Some((line.index + 1, json)), + Content::Text | Content::Invalid => None, + }) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + /// The first blueprint of the committed small list, which is already normalized. + fn first_small_blueprint() -> String { + crate::small_list().swap_remove(0) + } + + /// The same payload as `line`, compressed at a different level, so the string differs. + fn recompressed(line: &str) -> String { + let payload = strict_payload(line).expect("a strict blueprint string"); + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + encoder.write_all(&payload).unwrap(); + format!("0{}", STANDARD.encode(encoder.finish().unwrap())) + } + + #[test] + fn file_lines_matches_read_lines() { + assert_eq!(file_lines(""), Vec::<&str>::new()); + assert_eq!(file_lines("a"), ["a"]); + assert_eq!(file_lines("\u{feff}a\r\nb\rc\n"), ["a", "b", "c"]); + assert_eq!(file_lines("a\n\n"), ["a", ""]); + } + + #[test] + fn a_normalized_line_is_kept_as_it_is() { + let line = first_small_blueprint(); + let other = recompressed(&line); + assert_ne!(line, other); + for kept in [&line, &other] { + let (json, output) = try_normalize(&format!(" {kept} ")).unwrap().unwrap(); + assert_eq!(&output, kept); + assert_eq!(strict_payload(kept).unwrap(), json.as_bytes()); + } + } + + #[test] + fn differently_compressed_copies_are_duplicates() { + let line = first_small_blueprint(); + let text = format!("{line}\n{}\n", recompressed(&line)); + let output = execute(("in", &text), ("ex", ""), false, false).unwrap(); + assert_eq!(output, format!("{line}\n")); + } + + #[test] + fn an_invalid_line_fails_unless_kept() { + let text = "# comment\nnot a blueprint\n"; + let error = execute(("in.txt", text), ("ex", ""), true, false).unwrap_err(); + assert!(error.starts_with("in.txt line 2: "), "{error}"); + assert_eq!( + execute(("in.txt", text), ("ex", ""), true, true).unwrap(), + text + ); + } +} diff --git a/rust/snapshots/tests/normalize.rs b/rust/snapshots/tests/normalize.rs new file mode 100644 index 00000000..08a91723 --- /dev/null +++ b/rust/snapshots/tests/normalize.rs @@ -0,0 +1,73 @@ +//! The committed blueprint lists are already normalized: `normalize-lists` would change +//! nothing. The contract tests check that each blueprint survives `CleanBlueprint` +//! unchanged; this checks the lists as a whole, so it also catches a repeated blueprint, +//! one in both lists, a line that does not parse, or a line written differently from how +//! the tool writes it. + +use std::collections::HashMap; + +use snapshots::normalize::{blueprint_keys, file_lines, normalize_lists}; +use snapshots::oil_field_test_dir; + +fn read(name: &str) -> String { + std::fs::read_to_string(oil_field_test_dir().join(name)).expect("the list reads") +} + +/// The first place two texts differ, as line numbers and the two lines. +fn first_difference(old: &str, new: &str) -> String { + let (old, new) = (file_lines(old), file_lines(new)); + let at = old + .iter() + .zip(&new) + .position(|(a, b)| a != b) + .unwrap_or(old.len().min(new.len())); + let line = |lines: &[&str]| { + lines.get(at).map_or("(end of file)".to_string(), |l| { + l.chars().take(60).collect() + }) + }; + format!( + "line {}: was {:?}, would be {:?} ({} lines, would be {})", + at + 1, + line(&old), + line(&new), + old.len(), + new.len() + ) +} + +#[test] +fn committed_lists_are_normalized() { + let big = read("big-list.txt"); + let small = read("small-list.txt"); + let big_keys = blueprint_keys("big-list.txt", &big).unwrap_or_else(|e| panic!("{e}")); + let small_keys = blueprint_keys("small-list.txt", &small).unwrap_or_else(|e| panic!("{e}")); + + // Named failures first, since the rewrite check below only says where the text moves. + let mut problems = Vec::new(); + let mut seen: HashMap<&str, (&str, usize)> = HashMap::new(); + for (name, keys) in [("small-list.txt", &small_keys), ("big-list.txt", &big_keys)] { + for (line, json) in keys { + if let Some((first_name, first_line)) = seen.insert(json, (name, *line)) { + problems.push(format!( + "{name} line {line} is the same blueprint as {first_name} line {first_line}" + )); + } + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); + + let (new_big, new_small) = + normalize_lists(("big-list.txt", &big), ("small-list.txt", &small), false) + .unwrap_or_else(|e| panic!("{e}")); + assert!( + new_big == big, + "normalize-lists would rewrite big-list.txt, {}", + first_difference(&big, &new_big) + ); + assert!( + new_small == small, + "normalize-lists would rewrite small-list.txt, {}", + first_difference(&small, &new_small) + ); +} diff --git a/rust/snapshots/tools/normalize-lists.rs b/rust/snapshots/tools/normalize-lists.rs new file mode 100644 index 00000000..34d3df85 --- /dev/null +++ b/rust/snapshots/tools/normalize-lists.rs @@ -0,0 +1,75 @@ +//! Rewrites `big-list.txt` and `small-list.txt` the way the C# CLI's `oil-field normalize` +//! does: `cargo run --release -p snapshots --bin normalize-lists`. See +//! [`snapshots::normalize`] for what it changes and how it differs from the C#. +//! +//! `--keep-invalid` keeps a line that does not normalize, where the C# would ask. +//! `--dir ` works on the lists in another directory instead of the test directory. + +use std::path::PathBuf; +use std::process::ExitCode; + +const USAGE: &str = "usage: normalize-lists [--keep-invalid] [--dir ]"; + +fn main() -> ExitCode { + let mut keep_invalid = false; + let mut dir = snapshots::oil_field_test_dir(); + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "--keep-invalid" => keep_invalid = true, + "--dir" => match args.next() { + Some(path) => dir = PathBuf::from(path), + None => { + eprintln!("{USAGE}"); + return ExitCode::FAILURE; + } + }, + _ => { + eprintln!("{USAGE}"); + return ExitCode::FAILURE; + } + } + } + + let big_path = dir.join("big-list.txt"); + let small_path = dir.join("small-list.txt"); + let read = |path: &PathBuf| { + std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) + }; + let big = read(&big_path); + let small = read(&small_path); + + let big_name = big_path.display().to_string(); + let small_name = small_path.display().to_string(); + let (new_big, new_small) = match snapshots::normalize::normalize_lists( + (&big_name, &big), + (&small_name, &small), + keep_invalid, + ) { + Ok(lists) => lists, + Err(error) => { + eprintln!("{error}"); + return ExitCode::FAILURE; + } + }; + + for (path, old, new) in [ + (&big_path, &big, &new_big), + (&small_path, &small, &new_small), + ] { + let count = |text: &str| snapshots::normalize::file_lines(text).len(); + if old == new { + println!("{}: unchanged, {} lines", path.display(), count(new)); + } else { + std::fs::write(path, new).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + println!( + "{}: rewritten, {} lines, was {}", + path.display(), + count(new), + count(old) + ); + } + } + + ExitCode::SUCCESS +} From a54005dd551c5b7ec3705325beb54fd391498fa9 Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 03:56:06 -0700 Subject: [PATCH 6/8] Add UPDATE_SNAPSHOTS=1 to write the planner snapshots from Rust (port stage 13a) The snapshot tests compared every *.verified.txt with the Rust output, but only .NET Verify could write them. With UPDATE_SNAPSHOTS=1 the same tests write instead: they create missing files, rewrite changed ones (a UTF-8 byte order mark, then the text with LF line ends, as Verify writes) and delete *.verified.txt files no case produces any more. Without it nothing changes, except that failures now name the command. The pinned count of 2,748 snapshot files is replaced by a count derived from the two blueprint lists, so a new test blueprint needs no edit there, and update mode checks the case set before deleting by it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- rust/snapshots/src/lib.rs | 120 ++++++++++++++++++++++++++---- rust/snapshots/tests/score.rs | 23 ++++-- rust/snapshots/tests/snapshots.rs | 81 +++++++++++++++----- 3 files changed, 187 insertions(+), 37 deletions(-) diff --git a/rust/snapshots/src/lib.rs b/rust/snapshots/src/lib.rs index f94b1c94..8f29403b 100644 --- a/rust/snapshots/src/lib.rs +++ b/rust/snapshots/src/lib.rs @@ -7,6 +7,11 @@ //! //! [`normalize`] and the `normalize-lists` binary keep the two blueprint lists those tests //! read normalized, in place of the C# CLI's `oil-field normalize`. +//! +//! With `UPDATE_SNAPSHOTS=1` the tests write the snapshots instead of comparing them: they +//! create missing files, rewrite changed ones and delete files no case produces any more. +//! The bytes are what Verify writes: a UTF-8 byte order mark, then the text, LF line ends. +//! See [`UPDATE_COMMAND`]. pub mod issue_cases; pub mod normalize; @@ -36,6 +41,29 @@ pub fn oil_field_test_dir() -> PathBuf { repo_root().join("test/FactorioTools.Test/OilField") } +/// Set to `1` to write the snapshots rather than compare against them. +pub const UPDATE_ENV: &str = "UPDATE_SNAPSHOTS"; + +/// The command that rewrites every snapshot, run from `rust/`. +pub const UPDATE_COMMAND: &str = + "UPDATE_SNAPSHOTS=1 cargo test --release -p snapshots -- --include-ignored"; + +/// The scoreboard snapshot `tests/score.rs` checks, relative to [`oil_field_test_dir`]. +pub const SCORE_SNAPSHOT: &str = "Score.HasExpectedScore.verified.txt"; + +/// Whether [`UPDATE_ENV`] is `1`. Any other value, or none, compares. +pub fn update_mode() -> bool { + std::env::var(UPDATE_ENV).is_ok_and(|value| value == "1") +} + +/// What a failure message ends with: how to accept the Rust output instead. +pub fn update_hint() -> String { + format!( + "If the new output is right, rewrite the snapshots from it, then review and commit the \ + diff. From rust/:\n {UPDATE_COMMAND}" + ) +} + /// `BasePlannerTest.SmallListBlueprintStrings`. pub fn small_list() -> Vec { blueprint::read_blueprint_file(oil_field_test_dir().join("small-list.txt")) @@ -384,6 +412,61 @@ pub fn read_snapshot(relative: &str) -> std::io::Result { Ok(text.strip_prefix('\u{feff}').unwrap_or(&text).to_string()) } +/// What [`write_snapshot`] did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Written { + /// The file already held exactly these bytes, so it was left alone. + Unchanged, + Created, + Updated, +} + +/// The bytes Verify writes for a snapshot: a UTF-8 byte order mark, then the text as it +/// is. The text's own `\n` line ends are kept, which is what `*.verified.txt eol=lf` checks +/// out on every platform. +pub fn snapshot_bytes(text: &str) -> Vec { + let mut bytes = "\u{feff}".as_bytes().to_vec(); + bytes.extend_from_slice(text.as_bytes()); + bytes +} + +/// Writes a snapshot, relative to [`oil_field_test_dir`], unless it already holds exactly +/// [`snapshot_bytes`]. A file with the same text but no byte order mark is rewritten. +pub fn write_snapshot(relative: &str, text: &str) -> std::io::Result { + let path = oil_field_test_dir().join(relative); + let bytes = snapshot_bytes(text); + let written = match std::fs::read(&path) { + Ok(existing) if existing == bytes => return Ok(Written::Unchanged), + Ok(_) => Written::Updated, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Written::Created, + Err(error) => return Err(error), + }; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&path, bytes)?; + Ok(written) +} + +/// Compares a case's output with its snapshot, or in [`update_mode`] writes it. Two tests +/// run the `PlannerTest` cases at once, so both can write one of those files, but always +/// with the same bytes, so the file ends up whole either way. +fn compare_or_write(relative: &str, actual: &str) -> Outcome { + if update_mode() { + return match write_snapshot(relative, actual) { + Ok(Written::Unchanged) => Outcome::Matched, + Ok(written) => Outcome::Written(written), + Err(error) => Outcome::Error(format!("snapshot unwritable: {error}")), + }; + } + + match read_snapshot(relative) { + Err(error) => Outcome::Error(format!("snapshot unreadable: {error}")), + Ok(expected) if expected == actual => Outcome::Matched, + Ok(expected) => Outcome::Mismatch(first_difference(&expected, actual)), + } +} + /// The first lines where two texts differ, for a failure message. pub fn first_difference(expected: &str, actual: &str) -> String { let expected_lines: Vec<&str> = expected.split('\n').collect(); @@ -411,6 +494,8 @@ pub enum Outcome { Matched, Mismatch(String), Error(String), + /// In [`update_mode`], the snapshot was created or rewritten. + Written(Written), } /// Runs cases on all cores, returning each case's outcome in case order. Each case is @@ -445,18 +530,7 @@ pub fn run_cases(cases: &[SnapshotCase]) -> Vec { Ok(Err(error)) => { Outcome::Error(format!("planner error: {}", error.message)) } - Ok(Ok(result)) => { - let actual = grid_string(&result); - match read_snapshot(&case.snapshot) { - Err(error) => { - Outcome::Error(format!("snapshot unreadable: {error}")) - } - Ok(expected) if expected == actual => Outcome::Matched, - Ok(expected) => { - Outcome::Mismatch(first_difference(&expected, &actual)) - } - } - } + Ok(Ok(result)) => compare_or_write(&case.snapshot, &grid_string(&result)), }; outcomes.lock().unwrap()[i] = Some(outcome); } @@ -472,11 +546,13 @@ pub fn run_cases(cases: &[SnapshotCase]) -> Vec { .collect() } -/// Runs cases and returns a report grouped by snapshot folder, plus how many failed. +/// Runs cases and returns a report grouped by snapshot folder, plus how many failed. In +/// [`update_mode`] a written snapshot is not a failure, and the report lists it. pub fn check(cases: &[SnapshotCase]) -> (String, usize) { let outcomes = run_cases(cases); let mut groups: Vec<(String, usize, usize)> = Vec::new(); let mut failures = Vec::new(); + let mut written = Vec::new(); for (case, outcome) in cases.iter().zip(&outcomes) { let group = case.snapshot.split_once('/').map_or_else( || case.snapshot.split('.').next().unwrap().to_string(), @@ -496,6 +572,7 @@ pub fn check(cases: &[SnapshotCase]) -> (String, usize) { failures.push(format!("{}: mismatch\n{diff}", case.snapshot)) } Outcome::Error(error) => failures.push(format!("{}: {error}", case.snapshot)), + Outcome::Written(how) => written.push(format!("{how:?}: {}", case.snapshot)), } } @@ -503,6 +580,19 @@ pub fn check(cases: &[SnapshotCase]) -> (String, usize) { for (group, matched, total) in &groups { report.push_str(&format!("{group}: {matched}/{total} matched\n")); } + if update_mode() { + report.push_str(&format!( + "{UPDATE_ENV}=1: wrote {} snapshots\n", + written.len() + )); + for line in written.iter().take(20) { + report.push_str(line); + report.push('\n'); + } + if written.len() > 20 { + report.push_str(&format!("... and {} more\n", written.len() - 20)); + } + } for failure in failures.iter().take(10) { report.push_str(failure); report.push('\n'); @@ -510,6 +600,10 @@ pub fn check(cases: &[SnapshotCase]) -> (String, usize) { if failures.len() > 10 { report.push_str(&format!("... and {} more failures\n", failures.len() - 10)); } + if !failures.is_empty() && !update_mode() { + report.push_str(&update_hint()); + report.push('\n'); + } (report, failures.len()) } diff --git a/rust/snapshots/tests/score.rs b/rust/snapshots/tests/score.rs index 637f8d25..27307c51 100644 --- a/rust/snapshots/tests/score.rs +++ b/rust/snapshots/tests/score.rs @@ -1,17 +1,30 @@ //! `Score.HasExpectedScore`: the planner-quality scoreboard over the small list. -use snapshots::{first_difference, read_snapshot, score_text}; +use snapshots::{ + SCORE_SNAPSHOT, UPDATE_ENV, first_difference, read_snapshot, score_text, update_hint, + update_mode, write_snapshot, +}; /// 732 plans with every strategy. Run in release: -/// `cargo test --release -p snapshots --test score -- --ignored`. +/// `cargo test --release -p snapshots --test score -- --ignored`. With `UPDATE_SNAPSHOTS=1` +/// it writes the scoreboard instead. #[test] #[ignore] fn score_matches_the_scoreboard() { - let expected = read_snapshot("Score.HasExpectedScore.verified.txt").unwrap(); let actual = score_text(); + if update_mode() { + let written = write_snapshot(SCORE_SNAPSHOT, &actual) + .unwrap_or_else(|e| panic!("could not write {SCORE_SNAPSHOT}: {e}")); + println!("{UPDATE_ENV}=1: {SCORE_SNAPSHOT} {written:?}"); + return; + } + + let expected = read_snapshot(SCORE_SNAPSHOT) + .unwrap_or_else(|e| panic!("could not read {SCORE_SNAPSHOT}: {e}\n{}", update_hint())); assert!( expected == actual, - "{}", - first_difference(&expected, &actual) + "{SCORE_SNAPSHOT}: mismatch\n{}{}", + first_difference(&expected, &actual), + update_hint() ); } diff --git a/rust/snapshots/tests/snapshots.rs b/rust/snapshots/tests/snapshots.rs index c6707ef4..81596ab5 100644 --- a/rust/snapshots/tests/snapshots.rs +++ b/rust/snapshots/tests/snapshots.rs @@ -1,6 +1,12 @@ -//! The Rust planner against the C# planner's committed Verify snapshots. +//! The Rust planner against the C# planner's committed Verify snapshots. With +//! `UPDATE_SNAPSHOTS=1` these tests write the snapshots instead; see +//! [`snapshots::UPDATE_COMMAND`]. -use snapshots::{all_cases, check, planner_test_cases}; +use planner::models::PipeStrategy; +use snapshots::{ + SCORE_SNAPSHOT, UPDATE_ENV, all_cases, big_list, check, electric_pole_options, + planner_test_cases, small_list, update_hint, update_mode, +}; /// The `PlannerTest` and `PlannerIssueTest` snapshots, which run quickly enough in a debug /// build. @@ -11,8 +17,8 @@ fn planner_test_snapshots_match() { assert_eq!(failures, 0, "{report}"); } -/// Every planner snapshot: 2,747 files. Slow in a debug build, so run it in release: -/// `cargo test --release -p snapshots --test snapshots -- --ignored`. +/// Every planner snapshot, all but the scoreboard. Slow in a debug build, so run it in +/// release: `cargo test --release -p snapshots --test snapshots -- --ignored`. #[test] #[ignore] fn all_snapshots_match() { @@ -22,7 +28,9 @@ fn all_snapshots_match() { } /// Every committed `*.verified.txt` under the test directory must be one the Rust harness -/// checks, so a snapshot added on the C# side can't be skipped here without failing. +/// checks, so a snapshot added on the C# side can't be skipped here without failing, and +/// every one it checks must be committed. With `UPDATE_SNAPSHOTS=1` it deletes the files no +/// case produces any more instead, and leaves creating the missing ones to the tests above. #[test] fn every_committed_snapshot_is_checked() { use std::collections::BTreeSet; @@ -40,27 +48,62 @@ fn every_committed_snapshot_is_checked() { } } + // `all_cases` includes `planner_test_cases`; the scoreboard is checked by tests/score.rs. + let cases = all_cases(1); + let checked: BTreeSet = cases + .iter() + .map(|case| case.snapshot.clone()) + .chain([SCORE_SNAPSHOT.to_string()]) + .collect(); + + // Update mode deletes by this set, so check its size before trusting it, in place of a + // pinned file count that every new blueprint would have to edit. Each small-list + // blueprint makes 24 PlannerWithAllOptions snapshots (4 poles, 3 beacon settings, with + // and without underground pipes) and one each in AllStrategiesOnSmallList and + // NonStandardBeacon. Each big-list blueprint makes one in AllStrategiesOnBigList. Then + // one per pipe strategy for the isolated-area theory, the PlannerTest and + // PlannerIssueTest methods, and the scoreboard. + assert_eq!( + checked.len(), + cases.len() + 1, + "two cases write the same snapshot file" + ); + let expected = small_list().len() * (electric_pole_options().len() * 3 * 2 + 2) + + big_list().len() + + PipeStrategy::ALL.len() + + planner_test_cases().len() + + 1; + assert_eq!( + checked.len(), + expected, + "all_cases no longer makes the snapshots this test expects from the two lists; \ + if a theory was added or removed on purpose, update this count's formula" + ); + let root = snapshots::oil_field_test_dir(); let mut on_disk = BTreeSet::new(); walk(&root, &root, &mut on_disk); + let unchecked: Vec<_> = on_disk.difference(&checked).collect(); - let mut checked: BTreeSet = all_cases(1) - .into_iter() - .chain(planner_test_cases()) - .map(|case| case.snapshot) - .collect(); - // Checked by tests/score.rs. - checked.insert("Score.HasExpectedScore.verified.txt".to_string()); + if update_mode() { + for stale in &unchecked { + let path = root.join(stale); + std::fs::remove_file(&path) + .unwrap_or_else(|e| panic!("could not delete {}: {e}", path.display())); + println!("{UPDATE_ENV}=1: deleted {stale}"); + } + println!( + "{UPDATE_ENV}=1: deleted {} stale snapshots", + unchecked.len() + ); + return; + } - let unchecked: Vec<_> = on_disk.difference(&checked).collect(); let missing: Vec<_> = checked.difference(&on_disk).collect(); assert!( unchecked.is_empty() && missing.is_empty(), - "snapshots on disk but not checked: {unchecked:?}; checked but not on disk: {missing:?}" - ); - assert_eq!( - on_disk.len(), - 2748, - "the committed snapshot count changed; update this test" + "snapshots on disk but not checked: {unchecked:?}; checked but not on disk: \ + {missing:?}\n{}", + update_hint() ); } From 6deb95eb6861a5a20de8df99a5cfcf4d9a057e57 Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 03:58:07 -0700 Subject: [PATCH 7/8] Add Rust to the devcontainer (port stage 13a) The site builds the Rust planner with `npm run build-wasm`, and the devcontainer had no Rust, so the Devcontainer job built the planner on the runner and copied it in. Now the image carries the toolchain and the job builds and tests Rust inside the container. - Dockerfile: rustup-init 1.29.1, pinned and checksummed like Node, with the rust-toolchain.toml pin (1.98.1, rustfmt, clippy, wasm32) pre-installed for the ubuntu user, plus rust-src for rust-analyzer. gcc and libc6-dev for linking. Self-update is off so the rustup pin holds. - devcontainer.json: named volumes for rust/target and the cargo registry and git caches, chowned in postCreate; postCreate ends with build-wasm; rust-analyzer added. - devcontainer.yml: rust/rust-toolchain.toml in the paths filter; the toolchain step checks RUST_VERSION against the toolchain file, rustc and cargo in rust/, and the wasm32 target; the runner-side planner build is gone, replaced by build-wasm in the front-end step; new cargo test step. - CLAUDE.md Devcontainer section: what the container covers now, with measured timings. .NET, Lua and PowerShell stay until stage 13b removes the C#. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- .devcontainer/Dockerfile | 57 +++++++++++++++++++++- .devcontainer/devcontainer.json | 51 ++++++++++++++++---- .github/workflows/devcontainer.yml | 76 +++++++++++++++++++++++------- CLAUDE.md | 24 +++++++++- 4 files changed, 179 insertions(+), 29 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 561c89cb..2fed41a7 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,5 +1,6 @@ # A Linux container carrying every toolchain this repo's dev loop needs: the -# pinned .NET SDK plus wasm-tools, Node, PowerShell, Lua 5.2 and python3. +# pinned Rust toolchain, Node and python3, plus (until the C# is removed) the +# pinned .NET SDK with wasm-tools, PowerShell and Lua 5.2. # CLAUDE.md's "Devcontainer" section says what it covers and what still needs # the host (benchmarks and the Factorio oracle capture). # @@ -28,11 +29,17 @@ FROM mcr.microsoft.com/dotnet/sdk:10.0.402@sha256:0d99ebf1ccad15037b5c98c9fe8979 # # python3 is only for trim-factorio-oracle.py. The capture itself cannot run in # here - it needs a real Factorio install - but the trim half is worth having. +# +# gcc and libc6-dev are for Rust: cargo links native code (build scripts, proc +# macros, the test binaries) with `cc`. Nothing in rust/Cargo.lock compiles C, +# so the rest of build-essential (g++, make) is not needed. RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates \ curl \ + gcc \ git \ + libc6-dev \ lua5.2 \ python3 \ sudo \ @@ -94,3 +101,51 @@ ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 \ DOTNET_NOLOGO=1 USER ubuntu + +# Rust, for rust/ and for `npm run build-wasm` in src/vue, which builds the +# planner the site loads. Installed as ubuntu into its home, so cargo can write +# its caches and rustup can add a toolchain without sudo. +# +# rustup-init is pinned and checksummed the same way Node is above. The +# checksums are the .sha256 files published beside each binary, and match a +# download of both. Self-update is off so the pin holds: otherwise +# `rustup toolchain install` checks for a newer rustup and installs it. +# +# rust/rust-toolchain.toml is the authority on the compiler: rustup reads it +# inside rust/, and installs whatever it names on first use. RUST_VERSION only +# decides what is ALREADY in the image, so that creating the container, and +# every run of the CI job, does not download a toolchain. rustfmt, clippy and +# the wasm32 target are what the toolchain file asks for; rust-src is extra, +# for rust-analyzer, which cannot index std without it. +# +# WHEN rust-toolchain.toml MOVES, RUST_VERSION SHOULD MOVE WITH IT. A stale one +# still works - rustup just downloads the new pin on first use - which is +# exactly why nobody would notice. The Devcontainer CI job checks the two agree. +ARG RUSTUP_VERSION=1.29.1 +ARG RUSTUP_SHA256_ARM64=15f6e4ce9f583b929c996c91562bad6d4454f3281de858b02cdfdef615fac433 +ARG RUSTUP_SHA256_AMD64=dda7234360b7f578ca8b0ddcb80145646fa61a67c1720a5abc7051b35c9fcb71 +ENV RUST_VERSION=1.98.1 \ + CARGO_HOME=/home/ubuntu/.cargo \ + RUSTUP_HOME=/home/ubuntu/.rustup +ENV PATH=${CARGO_HOME}/bin:${PATH} +RUN set -eux; \ + case "$(dpkg --print-architecture)" in \ + arm64) rust_triple=aarch64-unknown-linux-gnu; rustup_sha="${RUSTUP_SHA256_ARM64}" ;; \ + amd64) rust_triple=x86_64-unknown-linux-gnu; rustup_sha="${RUSTUP_SHA256_AMD64}" ;; \ + *) echo "unsupported architecture: $(dpkg --print-architecture)" >&2; exit 1 ;; \ + esac; \ + curl -fsSLo /tmp/rustup-init \ + "https://static.rust-lang.org/rustup/archive/${RUSTUP_VERSION}/${rust_triple}/rustup-init"; \ + echo "${rustup_sha} /tmp/rustup-init" | sha256sum -c -; \ + chmod +x /tmp/rustup-init; \ + /tmp/rustup-init -y --no-modify-path \ + --profile minimal \ + --default-toolchain "${RUST_VERSION}" \ + --component rustfmt,clippy,rust-src \ + --target wasm32-unknown-unknown; \ + rm /tmp/rustup-init; \ + rustup set auto-self-update disable; \ + mkdir -p "${CARGO_HOME}/registry" "${CARGO_HOME}/git"; \ + rustup --version; \ + rustc --version; \ + cargo --version diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index a1fc49d2..a3f3ea4f 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,11 +1,13 @@ -// A Linux container for the whole dev loop: dotnet build/test, the Lua -// transpile and its 5.2 checks, and the Vue front-end including the WASM -// bundle. CLAUDE.md's "Devcontainer" section says what it covers and what -// still needs the host - benchmarks and the Factorio oracle capture. +// A Linux container for the whole dev loop: the Rust planner (cargo build and +// test in rust/, and the WASM build the site loads), the Vue front-end, and, +// until the C# is removed, dotnet build/test and the Lua transpile with its 5.2 +// checks. CLAUDE.md's "Devcontainer" section says what it covers and what still +// needs the host - benchmarks and the Factorio oracle capture. // // The Dockerfile pins the SDK from global.json by digest. That is the reason // this exists: `rollForward: latestMajor` only rolls forward, so a host whose -// package manager trails the pin cannot build the repo at all. +// package manager trails the pin cannot build the repo at all. It also carries +// the Rust toolchain rust/rust-toolchain.toml pins, already installed. { "name": "FactorioTools", "build": { "dockerfile": "Dockerfile" }, @@ -32,6 +34,28 @@ "source": "factoriotools-nuget-${devcontainerId}", "target": "/home/ubuntu/.cache/nuget", "type": "volume" + }, + // rust/target is the same problem as node_modules: Linux build output + // in the bind mount would sit beside, and invalidate, a Mac host's own + // cargo builds. A volume keeps them apart and survives a rebuild. + { + "source": "factoriotools-rust-target-${devcontainerId}", + "target": "${containerWorkspaceFolder}/rust/target", + "type": "volume" + }, + // The crates.io index and downloaded crates, so a rebuilt container + // does not fetch them again. Only these two folders of CARGO_HOME: + // its bin/ holds rustup and cargo from the image, and a volume over + // all of it would keep serving the old ones after an image update. + { + "source": "factoriotools-cargo-registry-${devcontainerId}", + "target": "/home/ubuntu/.cargo/registry", + "type": "volume" + }, + { + "source": "factoriotools-cargo-git-${devcontainerId}", + "target": "/home/ubuntu/.cargo/git", + "type": "volume" } ], // Vite's dev server. Reaching it from the host needs `--host`, and that is @@ -43,21 +67,30 @@ "5173": { "label": "Vite (needs --host)" } }, // A new volume is root-owned, hence the chown. Submodules are required to - // build at all - FluteSharp and delaunator-sharp are referenced by the core + // build the C# - FluteSharp and delaunator-sharp are referenced by the core // library, CSharp.lua by the transpile - and a fresh clone has none of them. // The safe.directory line is a no-op under OrbStack, where the mount already // appears owned by uid 1000; it is insurance on a Linux host whose own uid // is not 1000, where git otherwise refuses with "dubious ownership" and // vite.config.ts's `git describe` call takes the build down with it. - "postCreateCommand": "sudo chown ubuntu:ubuntu src/vue/node_modules /home/ubuntu/.cache/nuget && git config --global --add safe.directory \"${containerWorkspaceFolder}\" && git submodule update --init --recursive && npm --prefix src/vue ci", + // build-wasm runs last because the Vite build and `npm run dev` import the + // planner it produces, and fail without it. It is a release build of the + // planner and its dependencies, so it is the slow step here; the + // Devcontainer section in CLAUDE.md has the measured time. + "postCreateCommand": "sudo chown ubuntu:ubuntu src/vue/node_modules /home/ubuntu/.cache/nuget rust/target /home/ubuntu/.cargo/registry /home/ubuntu/.cargo/git && git config --global --add safe.directory \"${containerWorkspaceFolder}\" && git submodule update --init --recursive && npm --prefix src/vue ci && npm --prefix src/vue run build-wasm", "customizations": { "vscode": { "extensions": [ - "ms-dotnettools.csdevkit", + "rust-lang.rust-analyzer", "Vue.volar", + "ms-dotnettools.csdevkit", "ms-vscode.powershell", "sumneko.lua" - ] + ], + "settings": { + // The Cargo workspace is in rust/, not at the repository root. + "rust-analyzer.linkedProjects": ["rust/Cargo.toml"] + } } } } diff --git a/.github/workflows/devcontainer.yml b/.github/workflows/devcontainer.yml index 1bddc423..d600ee2a 100644 --- a/.github/workflows/devcontainer.yml +++ b/.github/workflows/devcontainer.yml @@ -6,11 +6,17 @@ on: - '.devcontainer/**' - '.github/workflows/devcontainer.yml' - 'global.json' - # Weekly, because two of this image's pins rot without anything under - # .devcontainer/ changing, so the paths filter above cannot catch either: - # - the Node tarball and its two checksums, if a release is ever re-cut - # - the SDK digest, once global.json moves (that one IS covered by the - # paths filter now, but only if the bump goes through a pull request) + # Not all of rust/: ci.yml's Rust job already builds and tests every Rust + # change. What this job adds is the container, and the only Rust file the + # container has to agree with is the toolchain pin. + - 'rust/rust-toolchain.toml' + # Weekly, because some of this image's pins rot without anything under + # .devcontainer/ changing, so the paths filter above cannot catch them: + # - the Node tarball and the rustup-init binaries, and their checksums, if + # a release is ever re-cut + # - the SDK digest and RUST_VERSION, once global.json or + # rust/rust-toolchain.toml moves (both ARE covered by the paths filter + # now, but only if the bump goes through a pull request) # A rotted pin fails the build for everyone who opens the container, so it is # better found here. schedule: @@ -35,7 +41,7 @@ jobs: - name: Create the development container run: npx --yes @devcontainers/cli@0.89.0 up --workspace-folder "$GITHUB_WORKSPACE" - - name: Every toolchain resolves, and the SDK matches global.json + - name: Every toolchain resolves, and the SDK and Rust match their pins run: | npx --yes @devcontainers/cli@0.89.0 exec --workspace-folder "$GITHUB_WORKSPACE" bash -ec ' # The check that matters: global.json pins an exact SDK and @@ -62,6 +68,40 @@ jobs: echo "::error::wasm-tools workload missing - BrowserWasm cannot publish." exit 1 } + + # The same idea for Rust, with one difference. A stale RUST_VERSION + # in the Dockerfile does not fail anything: rustup reads + # rust/rust-toolchain.toml and downloads the pin on first use. So + # checking what rustc resolves to proves nothing on its own; compare + # what the image pre-installed against what the file asks for. + rust_pinned=$(python3 -c "import tomllib;print(tomllib.load(open(\"rust/rust-toolchain.toml\",\"rb\"))[\"toolchain\"][\"channel\"])") + echo "rust-toolchain.toml pins $rust_pinned, the image pre-installs $RUST_VERSION" + [ "$rust_pinned" = "$RUST_VERSION" ] || { + echo "::error::The devcontainer pre-installs Rust $RUST_VERSION but rust/rust-toolchain.toml pins $rust_pinned. Update RUST_VERSION in .devcontainer/Dockerfile." + exit 1 + } + rustup --version + rustup toolchain list + # Run inside rust/, so these resolve through the toolchain file the + # way cargo does there. + rustc_version=$(cd rust && rustc --version) + cargo_version=$(cd rust && cargo --version) + echo "$rustc_version" + echo "$cargo_version" + case "$rustc_version" in "rustc $rust_pinned "*) ;; *) + echo "::error::rustc in rust/ is not $rust_pinned." + exit 1 ;; + esac + case "$cargo_version" in "cargo $rust_pinned "*) ;; *) + echo "::error::cargo in rust/ is not $rust_pinned." + exit 1 ;; + esac + # build-wasm needs this target, and the planner the site loads is + # built with it. + rustup target list --installed --toolchain "$rust_pinned" | grep -qx wasm32-unknown-unknown || { + echo "::error::The wasm32-unknown-unknown target is missing - npm run build-wasm cannot build the planner." + exit 1 + } ' - name: The core dev loop runs @@ -83,23 +123,25 @@ jobs: echo "Transpile reproduced the committed output, and it parses and runs under 5.2." ' - # The site now loads the Rust planner (rust/planner-wasm), and the Vite build - # imports it from src/vue/src/lib/planner-wasm. The devcontainer image has no - # Rust toolchain yet (adding one belongs with stage 13 of #138, when .NET - # leaves the image), so build it on the runner, whose rustup honours - # rust/rust-toolchain.toml. The checkout is mounted into the container, so the - # copied files are visible there. This is what `npm run build-wasm` does, - # minus shx, which the runner does not have outside the container. - - name: Build the Rust planner on the runner - working-directory: rust + # Debug only. The release gates (every planner snapshot, the contract + # replay) stay in ci.yml's Rust job: they test the planner, not the + # container, and would add their release build to this job's time. + - name: The Rust tests pass run: | - cargo build --release -p planner-wasm --target wasm32-unknown-unknown - cp target/wasm32-unknown-unknown/release/planner_wasm.wasm planner-wasm/js/planner.js ../src/vue/src/lib/planner-wasm/ + npx --yes @devcontainers/cli@0.89.0 exec --workspace-folder "$GITHUB_WORKSPACE" bash -ec ' + cd rust + cargo test --all-targets + ' + # The site loads the Rust planner (rust/planner-wasm), and the Vite build + # imports it from src/vue/src/lib/planner-wasm, so build-wasm comes first. + # postCreateCommand already ran it, so here it only confirms the output is + # up to date, and keeps this step honest if postCreate ever stops running it. - name: The front-end builds and tests run: | npx --yes @devcontainers/cli@0.89.0 exec --workspace-folder "$GITHUB_WORKSPACE" bash -ec ' cd src/vue + npm run build-wasm npm run build npm run test ' diff --git a/CLAUDE.md b/CLAUDE.md index 51a6b372..3ca9effb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -71,12 +71,32 @@ A full-solution `dotnet build` also builds `BrowserWasm`/`BlazorWebApp`, which n ### Devcontainer -`.devcontainer/` builds a Linux container carrying every toolchain this repo needs, which is more than the SDK: **dotnet 10.0.402 plus wasm-tools, Node 24.21.0, PowerShell 7.6.5, Lua 5.2.4 and python3**. Before it, a full local loop meant five separate host installs, one of which (`tools/check-lua.sh`) started a second container of its own. +`.devcontainer/` builds a Linux container carrying every toolchain this repo needs, which is more than the SDK: **Rust 1.98.1 (rustup 1.29.1, with rustfmt, clippy, rust-src and the wasm32 target), Node 24.21.0 and python3, plus dotnet 10.0.402 with wasm-tools, PowerShell 7.6.5 and Lua 5.2.4** for the C#, until it is removed. Before it, a full local loop meant separate host installs of each, one of which (`tools/check-lua.sh`) started a second container of its own. It is not a replacement for `docker-build.sh`. That script is the quick way to run one `dotnet` command in the pinned SDK; this is the whole environment, with an editor attached. **The Dockerfile pins the SDK from `global.json` by digest**, which is the point. `rollForward: latestMajor` only rolls forward, so a host whose package manager trails the pin cannot build the repo at all - that is what happened on 2026-09-21 when the pin moved to 10.0.401 and Homebrew still shipped 10.0.400. **When `global.json` moves, the `FROM` line must move with it.** The Devcontainer CI job compares `dotnet --version` against `global.json` and fails if they disagree, so a forgotten re-pin is a red check rather than a container that quietly contradicts the repo. +**Rust is pre-installed, and `rust/rust-toolchain.toml` still decides.** The image installs the toolchain named by `RUST_VERSION` in the Dockerfile, so creating the container downloads no compiler. Inside `rust/`, rustup reads the toolchain file as it does anywhere else. A stale `RUST_VERSION` therefore breaks nothing - rustup just installs the new pin on first use (about 10 s, measured) - which is exactly why nobody would notice. So the Devcontainer CI job compares `RUST_VERSION` with the toolchain file, checks that `rustc` and `cargo` in `rust/` report that version, and checks that the wasm32 target is installed. **When `rust/rust-toolchain.toml` moves, move `RUST_VERSION` with it.** The toolchain file is in that job's paths filter for this reason. + +The container keeps its own `rust/target`, cargo registry and cargo git cache in named volumes, for the same reason as `node_modules`: Linux build output in the bind mount would fight a Mac host's own. `postCreateCommand` ends with `npm run build-wasm`, so `npm run dev` and `npm run build` work as soon as the container is up. The VS Code extension list includes rust-analyzer, pointed at `rust/Cargo.toml`. + +Do not try to change the pre-installed toolchain's components from inside the container. `rustup target remove` failed there with `Invalid cross-device link (os error 18)`, because the files sit in a read-only image layer. Change the Dockerfile and rebuild instead. Installing another toolchain works. + +Measured 2026-10-21 on tealc (Linux x86-64, 8 cores, Docker Desktop), with `@devcontainers/cli@0.89.0` running the Devcontainer job's own steps against a fresh clone with tags. Two full runs; where they differ, both times are shown: + +| step | result | +| --- | --- | +| image build with `--no-cache`, base image already pulled | 2 min 58 s; the Rust layer took 17 s of it | +| `devcontainer up` | 45 s with the image cached, 88 s when the Rust layer had to be rebuilt. `postCreateCommand` took 34 s and 52 s, of which `build-wasm` took 17 s and 33 s and `npm ci` 10 s | +| toolchain check | Rust 1.98.1 in the image and in the toolchain file; `rustc` and `cargo` 1.98.1 in `rust/`; wasm32 target present | +| `cargo test --all-targets` in `rust/` | 175 passed, 7 ignored; 152 s and 188 s, of which about 11 s is compiling | +| `npm run build-wasm && npm run build && npm run test` in `src/vue` | build OK, 51 tests passed; 12.5 s and 14 s (`build-wasm` already up to date) | +| `dotnet test` on the test project | 4302 passed; 307 s and 241 s | +| Lua transpile step | reproduced the committed `src/lua`, parses and runs under 5.2; 41 s and 29 s | + +The release gates (`cargo test --release -p snapshots -p contract -- --include-ignored`) also pass in the container, in 96 s. The Devcontainer job leaves them to `ci.yml`'s Rust job: they test the planner, not the container. + Measured 2026-09-21 in the built image on macOS arm64 (OrbStack), against a real clone with tags: | step | result | @@ -87,7 +107,7 @@ Measured 2026-09-21 in the built image on macOS arm64 (OrbStack), against a real | `luac5.2 -p` over the generated Lua | all 127 files parse | | `lua5.2 sample.lua` | runs, prints the grid | | `npm ci && npm run build && npm test` in `src/vue` | build OK, 51 tests passed | -| `npm run build-wasm` | Release publish OK, bundle lands at `public/framework/dotnet.js` | +| `npm run build-wasm` | Release publish OK, bundle lands at `public/framework/dotnet.js` (the .NET planner; `build-wasm` has built the Rust planner since stage 12b) | Two notes on why specific things are the way they are: From 7d05e8341912c0814219fd7fc6b9b873bfe9f4a0 Mon Sep 17 00:00:00 2001 From: Eric J Date: Wed, 21 Oct 2026 04:13:19 -0700 Subject: [PATCH 8/8] Document the stage 13a Rust tools in CLAUDE.md Covers the plannerDefaults generator, the hand-maintained API types and their test, adding a test blueprint with normalize-lists and UPDATE_SNAPSHOTS, changing planner output on purpose, and the Rust port of the Factorio oracle test. The .NET and Lua docs stay until 13b removes those builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PTSQFMEdmByebgkoa9RiqH --- CLAUDE.md | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 3ca9effb..87674c63 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,7 +27,7 @@ dotnet test --filter "FullyQualifiedName~PlannerTest.ExecuteSample" # single t # Run the planner sample from the CLI (prints the grid) dotnet run --project src/FactorioTools.Cli -- oil-field sample -dotnet run --project src/FactorioTools.Cli -- oil-field normalize # re-normalize test blueprint lists +# Re-normalize the test blueprint lists: now a Rust bin, see "Adding a test blueprint" under Testing notes # Benchmarks dotnet run --project src/Benchmark -c Release @@ -35,8 +35,7 @@ dotnet run --project src/Benchmark -c Release # Vue front-end (from src/vue) npm install npm run dev # vite dev server -npm run build # regenerates TS API client from swagger, type-checks, builds -npm run swagger-gen # regenerate src/lib API client from ../WebApp/swagger.json +npm run build # type-checks (vue-tsc), builds npm run build-wasm # build the Rust planner (rust/planner-wasm) and copy it into src/lib/planner-wasm ``` @@ -140,8 +139,10 @@ Pure planning logic with **no JSON/serialization dependencies** - this is intent Blueprint string parsing and emitting live here, separate from the core lib: `ParseBlueprint`, `GridToBlueprintString`, `NormalizeBlueprints`, plus the `System.Text.Json` source-gen context. Front-ends and the CLI reference this project, not just the core. ### Front-ends and hosts -- `src/WebApp` - ASP.NET Core API (`OilFieldController`, routes under `api/v1/oil-field`: `normalize`, `plan`; the actions delegate to `PlanOrchestrator`). Produces `swagger.json` consumed by the Vue client's `swagger-gen`. No longer deployed (the Azure target was retired when the front-end moved to in-browser WASM); kept for local API use, swagger generation, and the `Dockerfile` if self-hosting is wanted. -- `src/vue` - the primary front-end (Vue 3 + Vite + Pinia, persisted settings). This is what's deployed, as a Cloudflare Worker with static assets (see "Deployment" below); it plans in-browser via the WASM bundle and no longer calls a hosted API. Planner constants (pole presets, geometry defaults, strategy defaults, quality levels) are not retyped in TypeScript - they come from `src/vue/src/lib/plannerDefaults.verified.json`, which `PlannerDefaultsTest` generates from `OilFieldOptions` (most fields) and the `Quality` enum (`qualityLevels`). Change a default in the C# and `dotnet test` rewrites that file; commit it with your change. +- `src/WebApp` - ASP.NET Core API (`OilFieldController`, routes under `api/v1/oil-field`: `normalize`, `plan`; the actions delegate to `PlanOrchestrator`). Produces `swagger.json`, which the front-end no longer uses (its API types are hand-maintained since stage 13a). No longer deployed (the Azure target was retired when the front-end moved to in-browser WASM); kept for local API use, swagger generation, and the `Dockerfile` if self-hosting is wanted. +- `src/vue` - the primary front-end (Vue 3 + Vite + Pinia, persisted settings). This is what's deployed, as a Cloudflare Worker with static assets (see "Deployment" below); it plans in-browser via the WASM bundle and no longer calls a hosted API. Planner constants (pole presets, geometry defaults, strategy defaults, quality levels) are not retyped in TypeScript - they come from `src/vue/src/lib/plannerDefaults.verified.json`, which the Rust test `rust/contract/tests/planner_defaults.rs` generates from `OilFieldOptions` and `Quality`, byte for byte the same as the C# `PlannerDefaultsTest` (both exist until stage 13b removes the C#). The test fails when the file is stale. After changing a default, run `UPDATE_PLANNER_DEFAULTS=1 cargo test -p contract --test planner_defaults` from `rust/` and commit the rewritten file. Adding a field to `OilFieldOptions` without emitting it fails to compile. + + `src/vue/src/lib/FactorioToolsApi.ts` holds the request and response types for the planner. It began as a client generated from `WebApp/swagger.json` and is hand-maintained since stage 13a. `FactorioToolsApi.test.ts` checks it against the plan and normalize responses in `rust/contract/fixtures/contract.jsonl`: key shape, value types, and every strategy and quality name. When the contract changes, update the types and the test's samples together. **Keep the FLUTE credit in the footer of `src/vue/src/App.vue`.** FLUTE (the `ConnectedCentersFlute` strategy, via the FluteSharp submodule) is under Chris Chu's Attribution Assurance License, `submodules/FluteSharp/flute-c/license.txt`. It requires a prominent display of "Dr. Chris C. N. Chu", "Iowa State University" and `http://home.engineering.iastate.edu/~cnchu/` every time the program launches. The footer shows on every page, which is what meets that. A Rust port of FLUTE would be under the same terms (#138). - `src/BrowserWasm` - the planner as .NET WASM (trimmed). **The site no longer loads it**: it loads `rust/planner-wasm` instead (see the Rust port section). It stays until stage 13 of #138 removes the .NET projects, and the notes below describe how it was built. @@ -165,7 +166,7 @@ The planner is being ported to Rust/WASM, one stage per PR, following the plan o - **The port must reproduce the C# output exactly**, including how ties are broken. That depends on .NET details: `HashSet`/`Dictionary` enumeration order (insertion order, with freed slots reused last-in first-out), the 4-ary `PriorityQueue`, the unstable introsort behind `List.Sort`, and `Math.Round` rounding half to even. `rust/dotnet-compat` holds Rust copies of these. Use them, not std's `HashMap`, `BinaryHeap` or `sort_by`, wherever the C# result depends on order. - **Those copies are tested against fixtures recorded from real .NET** (`rust/dotnet-compat/fixtures`, format in `rust/dotnet-compat/FIXTURES.md`). The `test-default` CI job reruns the recorder on the pinned SDK and fails if the fixtures drift, so an SDK bump that changes .NET's behavior shows up as a red check. - **`rust/delaunator-net` and `rust/flute` are ports of the two submodules**, DelaunatorSharp and FluteSharp, kept byte-for-byte compatible with them. Do not swap in the `delaunator` crate: it is a newer algorithm whose tie-breaking differs, which changes the planner's pipes. `rust/flute` is under FLUTE's Attribution Assurance License (`rust/flute/LICENSE-FLUTE`), the same terms as the C#, so the site's footer credit covers it too. -- **`rust/snapshots` is the end-to-end gate.** It plans every case the C# Verify tests plan, from the same `small-list.txt` and `big-list.txt`, and compares the output with the committed `*.verified.txt` files byte for byte, plus `Score.HasExpectedScore`. It also fails if a snapshot file exists that no Rust case checks. Run it in release: `cargo test --release -p snapshots -- --include-ignored` (about a minute). `rust/blueprint` parses blueprint strings for it. +- **`rust/snapshots` is the end-to-end gate.** It plans every case the C# Verify tests plan, from the same `small-list.txt` and `big-list.txt`, and compares the output with the committed `*.verified.txt` files byte for byte, plus `Score.HasExpectedScore`. It also fails if a snapshot file exists that no Rust case checks. Run it in release: `cargo test --release -p snapshots -- --include-ignored` (about a minute). `rust/blueprint` parses blueprint strings for it. Since stage 13a it can also write the snapshots: see "Changing planner output on purpose" under Testing notes. - **`rust/contract` and `rust/planner-wasm` are what the site loads.** `contract` is the JSON the site sends and gets back (`PlanOrchestrator`'s `Plan` and `Normalize`, the error envelope), checked against responses recorded from the C# (`rust/contract/fixtures`). `planner-wasm` builds it to WebAssembly with no extra toolchain, and `planner-wasm/js/planner.js` exposes `plan(json)` and `normalize(json)` with the same signatures as `src/vue/src/lib/wasmPlanner.ts`. CI checks the WebAssembly build's output against the native contract byte for byte. **The site loads this module** (stage 12b of #138), through `src/vue/src/lib/wasmPlanner.ts` and a Web Worker. - **Commands**, from `rust/`: `cargo fmt --all`, `cargo clippy --all-targets -- -D warnings`, `cargo test --all-targets`, and `cargo build --workspace --target wasm32-unknown-unknown`. The toolchain is pinned in `rust/rust-toolchain.toml`; rustup installs it on first use. - **A change to the C# planner during the port** has to land in the Rust version too, or wait for it. `rust/planner/fixtures` are recorded from the C# planner (format and the command to regenerate them in `rust/planner/FIXTURES.md`), and the `test-default` CI job reruns every recorder under `rust/`. So a C# change that alters planner output turns CI red until the fixtures are regenerated and the Rust port matches them. @@ -261,7 +262,7 @@ Two more sources are *reference* rather than authoritative. They say **why** som Worked example: the pumpjack change behind issue #81 shows up in a dump as `output_fluid_box` pipe connections going from `[[1,-1],[1,-1],[-1,1],[-1,1]]` to `[[1,-1],[1,1],[-1,1],[-1,-1]]`. The dump does not say why. FFF #442, "Flip, Flow, and Fresh Paint", does, and the same release added `use_mirroring` and `migrate_horizontal_mirroring` to that prototype - which is how you learn the change is about entity mirroring rather than a typo fix. -`tools/capture-factorio-oracle.sh` pulls those three into `test/FactorioTools.Test/OilField/factorio-oracle.json`: +`tools/capture-factorio-oracle.sh` pulls those three into `test/FactorioTools.Test/OilField/factorio-oracle.json`. Two tests read it: the C# `FactorioOracleTest`, and its Rust port, `rust/planner/tests/factorio_oracle.rs`, plus an entity-size check in the tests module of `rust/blueprint/src/write.rs`. Rust has no reflection, so `entity_names::vanilla::ALL` and `item_names::vanilla::ALL` in `rust/planner/src/data.rs` list the names by hand, and `data::tests::all_arrays_match_their_constants` fails if a name constant is added without adding it to `ALL`. ```bash tools/capture-factorio-oracle.sh # auto-detects a Steam or /Applications install @@ -272,7 +273,7 @@ tools/capture-factorio-oracle.sh --factorio /path/to/factorio.app Notes on using it: - **The committed fixture targets the experimental branch**, currently 2.1.14, not stable. That is deliberate: the bug reports come from 2.1 and that is where the game is heading. `captureInfo.factorioVersion` in the fixture records which build it came from. -- **Stable and experimental are not identical.** Comparing 2.0.77 stable against 2.1.14 experimental, everything the planner reads is byte-identical except one thing: the pumpjack's output fluid box went from 2 distinct corners to 4, one per rotation (FFF #442). That difference did mean the hardcoded terminal offsets in `Helpers.cs` were wrong for 2.1 on east and west, which is issue #81, now fixed. A probe mod settled it by reading `PipeConnection.target_position` out of both running games rather than deriving it; `FactorioOracleTest.TerminalOffsetsMatchTheFactorioOutputCorners` now pins the offsets to the fixture so the next corner move fails a test. Capture any second version with `--factorio ` and `--out ` to compare. +- **Stable and experimental are not identical.** Comparing 2.0.77 stable against 2.1.14 experimental, everything the planner reads is byte-identical except one thing: the pumpjack's output fluid box went from 2 distinct corners to 4, one per rotation (FFF #442). That difference did mean the hardcoded terminal offsets in `Helpers.cs` were wrong for 2.1 on east and west, which is issue #81, now fixed. A probe mod settled it by reading `PipeConnection.target_position` out of both running games rather than deriving it; `FactorioOracleTest.TerminalOffsetsMatchTheFactorioOutputCorners` (and its Rust port, `terminal_offsets_match_the_factorio_output_corners` in `rust/planner/tests/factorio_oracle.rs`) now pins the offsets to the fixture so the next corner move fails a test. Capture any second version with `--factorio ` and `--out ` to compare. - **Re-capture after every Factorio update and commit the diff.** A changed fixture is the signal that a hardcoded constant needs review. `--check` answers "has the game moved past what we committed?" without dirtying the tree. - **The installed binary is the authority** on which version gets captured. Steam updates it without asking, so it decides and everything else follows. Same convention as `scripts/sync-factorio-refs.sh` in FactorioMapWebUI. - **It runs with user mods disabled** (`--mod-directory` pointed at an empty directory). Mods rewrite prototypes freely, so a capture that loads them describes one person's modded game rather than Factorio. The script prints which mods loaded; expect only `core base elevated-rails quality recycler space-age`. @@ -310,7 +311,16 @@ Two related sources, for when the game binary is not the easiest thing to reach: - Tests use **xUnit v3 + Verify** (`xunit.v3` + `Verify.XunitV3`). Many tests assert against committed `*.verified.txt` snapshots under `test/FactorioTools.Test/OilField`. When behavior legitimately changes, update snapshots via Verify's accept workflow (received vs verified) rather than editing expected files by hand. A stale committed snapshot **does** fail on CI: `AutoVerify` is off there, so the test itself throws `VerifyException` with the diff (confirmed on a real runner, not just inferred - note that setting `CI`/`GITHUB_ACTIONS` locally does *not* reproduce the build-server detection, so local simulation of this is misleading). A "Check no Verify snapshots drifted" step backs that up by failing if `dotnet test` leaves any `*.verified.*` file dirty, in case the detection ever regresses. Commit regenerated snapshots with your change. - `Score.HasExpectedScore.verified.txt` is the planner-quality scoreboard across the 61 blueprints in `small-list.txt` (the file also holds 11 `#` comment lines, so do not read its line count as the blueprint count). `small-list.txt` / `big-list.txt` hold the blueprint corpus; `big-list.txt` is 1147 blueprints and is not scored. -- Test data blueprints are normalized via the CLI `oil-field normalize` command. +- **Adding a test blueprint.** Paste the blueprint string as a new line at the end of `small-list.txt` (scored, may hold `#` comments), or in `big-list.txt` (not scored, blueprints only). Then, from `rust/`: + + ```bash + cargo run --release -p snapshots --bin normalize-lists + UPDATE_SNAPSHOTS=1 cargo test --release -p snapshots -- --include-ignored + cargo test --release -p snapshots -p contract -- --include-ignored + ``` + + The first command cleans each blueprint down to its pumpjacks, drops repeats, and moves a blueprint found in both lists to the small list only. It compares blueprints by their decoded JSON, not the compressed string, and leaves a line that is already normalized exactly as written, so the diff shows only real changes. A line that does not parse stops it with the file and line number; fix or remove the line, or pass `--keep-invalid`. (It replaces the C# `oil-field normalize`, which on .NET 10 would rewrite all 1,208 lines because the committed strings came from an older zlib.) The second command writes the new snapshots, and the third checks everything in compare mode. A new small-list blueprint at index N creates 26 files: 24 `PlannerWithAllOptions/Theory.E__{_b}{_o}{_u}.verified.txt`, plus `AllStrategiesOnSmallList/Theory.E_.verified.txt` and `NonStandardBeacon/Theory.E_.verified.txt`. It also changes `Score.HasExpectedScore.verified.txt`. If the blueprint came out of `big-list.txt` at index M, every `AllStrategiesOnBigList/Theory.E_` from M on shifts down one and the last is deleted. No test has a count to edit. Commit the lists and every new, changed and deleted snapshot together. +- **Changing planner output on purpose.** From `rust/`, `UPDATE_SNAPSHOTS=1 cargo test --release -p snapshots -- --include-ignored` rewrites every snapshot and the scoreboard from the Rust output: it creates missing files, overwrites changed ones, and deletes any `*.verified.txt` no case produces. Only the value `1` turns it on, and CI never sets it, so a stale snapshot fails there. Run it in release and with `--include-ignored`, or only the quick `PlannerTest` snapshots are written. The bytes are what Verify writes (UTF-8 BOM, LF); stage 13a checked that Rust regenerates all 2,748 files byte for byte and that Verify accepts files Rust writes. Read the diff before committing: it is the only record of what the change did to real plans. ## Dependency automation