1#![deny(missing_docs)]
22
23use crate::error::{Error, Result};
24#[cfg(feature = "io")]
25use crate::retry::{RetryPolicy, retry_http};
26#[cfg(feature = "io")]
27use crate::util::SizeCap;
28use serde::{Deserialize, Deserializer, Serialize};
29use std::collections::HashMap;
30
31const BUNDLED_ECOSYSTEM: &[u8] = include_bytes!("../assets/ecosystem-schema.json.zst");
34
35pub const DEFAULT_ECOSYSTEM_URL: &str =
50 "https://thunderstore.io/api/experimental/schema/dev/latest/";
51
52#[cfg(feature = "io")]
56const MAX_ECOSYSTEM_BYTES: u64 = 64 * 1024 * 1024;
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
60#[non_exhaustive]
61pub struct Ecosystem {
62 #[serde(
64 rename = "schemaVersion",
65 default,
66 deserialize_with = "null_as_default"
67 )]
68 pub schema_version: String,
69 #[serde(default, deserialize_with = "null_as_default")]
71 pub games: HashMap<String, GameDef>,
72 #[serde(
74 rename = "modloaderPackages",
75 default,
76 deserialize_with = "null_as_default"
77 )]
78 pub modloader_packages: Vec<ModloaderPackage>,
79}
80
81impl Ecosystem {
82 pub fn bundled() -> Self {
103 Self::try_bundled()
104 .expect("bundled ecosystem snapshot must be valid; this is a build-time invariant")
105 }
106
107 pub fn try_bundled() -> Result<Self> {
110 let json = zstd::decode_all(BUNDLED_ECOSYSTEM)
111 .map_err(|e| Error::Ecosystem(format!("failed to decompress bundled schema: {}", e)))?;
112
113 Self::from_json_slice(&json)
114 }
115
116 pub fn from_json(json: &str) -> Result<Self> {
118 Self::from_json_slice(json.as_bytes())
119 }
120
121 fn from_json_slice(bytes: &[u8]) -> Result<Self> {
123 serde_json::from_slice(bytes).map_err(|e| Error::Ecosystem(format!("failed to parse: {}", e)))
124 }
125
126 #[cfg(feature = "io")]
134 pub async fn fetch_latest(client: &reqwest::Client, url: &str) -> Result<Self> {
135 Self::fetch_latest_bounded(client, url, MAX_ECOSYSTEM_BYTES, &RetryPolicy::default()).await
136 }
137
138 #[cfg(feature = "io")]
142 async fn fetch_latest_bounded(
143 client: &reqwest::Client,
144 url: &str,
145 max_bytes: u64,
146 retry: &RetryPolicy,
147 ) -> Result<Self> {
148 use futures::StreamExt;
149
150 let body = retry_http(retry, async || {
151 let response = client.get(url).send().await?.error_for_status()?;
152
153 let mut cap = SizeCap::new("ecosystem schema", max_bytes);
154
155 cap.check_declared(response.content_length())?;
158
159 let mut stream = response.bytes_stream();
160 let mut body: Vec<u8> = Vec::new();
161
162 while let Some(chunk) = stream.next().await {
163 let chunk = chunk?;
164
165 cap.add(chunk.len() as u64)?;
166
167 body.extend_from_slice(&chunk);
168 }
169
170 Ok(body)
171 })
172 .await?;
173
174 Self::from_json_slice(&body)
175 }
176
177 pub fn game(&self, slug: &str) -> Option<&GameDef> {
179 self.games.get(slug)
180 }
181
182 pub fn require_profile(&self, game: &str) -> Result<&GameProfile> {
202 let def = self.game(game).ok_or_else(|| Error::UnknownGame {
203 game: game.to_string(),
204 })?;
205
206 def.profile().ok_or_else(|| Error::NoGameProfile {
207 game: game.to_string(),
208 })
209 }
210
211 pub fn games(&self) -> impl Iterator<Item = &GameDef> {
213 self.games.values()
214 }
215
216 pub fn modloader_package(&self, package_full_name: &str) -> Option<&ModloaderPackage> {
224 self
225 .modloader_packages
226 .iter()
227 .find(|m| m.package_id == package_full_name)
228 }
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize)]
235#[non_exhaustive]
236pub struct GameDef {
237 #[serde(rename = "label", default, deserialize_with = "null_as_default")]
239 pub slug: String,
240 #[serde(default, deserialize_with = "null_as_default")]
242 pub uuid: String,
243 #[serde(default)]
245 pub meta: Meta,
246 #[serde(default, deserialize_with = "null_as_default")]
248 pub distributions: Vec<Distribution>,
249 #[serde(rename = "r2modman", default, deserialize_with = "null_as_default")]
253 pub profiles: Vec<GameProfile>,
254}
255
256impl GameDef {
257 pub fn display_name(&self) -> &str {
259 &self.meta.display_name
260 }
261
262 pub fn profile(&self) -> Option<&GameProfile> {
265 self
266 .profiles
267 .iter()
268 .find(|p| p.instance_type == InstanceType::Game)
269 .or_else(|| self.profiles.first())
270 }
271
272 pub fn community(&self) -> Option<&str> {
276 self.profile()?.community()
277 }
278
279 pub fn r2modman_folders(&self) -> Vec<&str> {
299 let mut folders: Vec<&str> = Vec::new();
300
301 for folder in self
302 .profiles
303 .iter()
304 .filter_map(|p| p.internal_folder_name.as_deref())
305 {
306 if !folders.contains(&folder) {
307 folders.push(folder);
308 }
309 }
310
311 folders
312 }
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
319#[non_exhaustive]
320pub struct GameProfile {
321 #[serde(default)]
323 pub meta: Meta,
324 #[serde(
326 rename = "packageLoader",
327 default,
328 deserialize_with = "null_as_default"
329 )]
330 pub package_loader: LoaderKind,
331 #[serde(
333 rename = "gameInstanceType",
334 default,
335 deserialize_with = "null_as_default"
336 )]
337 pub instance_type: InstanceType,
338 #[serde(rename = "exeNames", default, deserialize_with = "null_as_default")]
340 pub exe_names: Vec<String>,
341 #[serde(default, deserialize_with = "null_as_default")]
343 pub distributions: Vec<Distribution>,
344 #[serde(
347 rename = "relativeFileExclusions",
348 default,
349 deserialize_with = "null_as_default"
350 )]
351 pub relative_file_exclusions: Vec<String>,
352 #[serde(rename = "installRules", default, deserialize_with = "null_as_default")]
354 pub install_rules: Vec<InstallRule>,
355 #[serde(rename = "dataFolderName", default)]
357 pub data_folder_name: Option<String>,
358 #[serde(rename = "settingsIdentifier", default)]
362 pub settings_identifier: Option<String>,
363 #[serde(rename = "internalFolderName", default)]
370 pub internal_folder_name: Option<String>,
371 #[serde(rename = "packageIndex", default)]
373 pub package_index: Option<String>,
374}
375
376impl GameProfile {
377 pub fn steam_app_id(&self) -> Option<u32> {
379 self
380 .distributions
381 .iter()
382 .find(|d| d.platform == "steam")
383 .and_then(|d| d.identifier.parse().ok())
384 }
385
386 pub fn community(&self) -> Option<&str> {
405 let url = self.package_index.as_deref()?;
406 let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
407 let (_, path) = after_scheme.split_once('/')?;
408 let (community, _) = path.strip_prefix("c/")?.split_once('/')?;
409 let is_slug = !community.is_empty()
410 && community
411 .chars()
412 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
413
414 is_slug.then_some(community)
415 }
416}
417
418#[derive(Debug, Clone, Default, Serialize, Deserialize)]
420#[non_exhaustive]
421pub struct Meta {
422 #[serde(rename = "displayName", default, deserialize_with = "null_as_default")]
424 pub display_name: String,
425 #[serde(rename = "iconUrl", default, deserialize_with = "null_as_default")]
427 pub icon_url: String,
428}
429
430#[derive(Debug, Clone, Serialize, Deserialize)]
432#[non_exhaustive]
433pub struct Distribution {
434 #[serde(default, deserialize_with = "null_as_default")]
436 pub platform: String,
437 #[serde(default, deserialize_with = "null_as_default")]
440 pub identifier: String,
441}
442
443#[derive(Debug, Clone, Serialize, Deserialize)]
450#[non_exhaustive]
451pub struct ModloaderPackage {
452 #[serde(rename = "packageId", default, deserialize_with = "null_as_default")]
454 pub package_id: String,
455 #[serde(rename = "rootFolder", default, deserialize_with = "null_as_default")]
458 pub root_folder: String,
459 #[serde(default, deserialize_with = "null_as_default")]
461 pub loader: LoaderKind,
462}
463
464#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
469#[serde(rename_all = "kebab-case")]
470#[non_exhaustive]
471pub enum TrackingMethod {
472 #[default]
476 Subdir,
477 None,
479 State,
482 SubdirNoFlatten,
484 PackageZip,
486 #[serde(other)]
488 Other,
489}
490
491impl TrackingMethod {
492 pub fn is_namespaced(self) -> bool {
495 matches!(
496 self,
497 TrackingMethod::Subdir | TrackingMethod::SubdirNoFlatten
498 )
499 }
500}
501
502#[derive(Debug, Clone, Serialize, Deserialize)]
506#[non_exhaustive]
507pub struct InstallRule {
508 #[serde(default, deserialize_with = "null_as_default")]
512 pub route: String,
513 #[serde(
516 rename = "defaultFileExtensions",
517 default,
518 deserialize_with = "null_as_default"
519 )]
520 pub default_file_extensions: Vec<String>,
521 #[serde(
523 rename = "trackingMethod",
524 default,
525 deserialize_with = "null_as_default"
526 )]
527 pub tracking_method: TrackingMethod,
528 #[serde(rename = "subRoutes", default, deserialize_with = "null_as_default")]
530 pub sub_routes: Vec<InstallRule>,
531 #[serde(
534 rename = "isDefaultLocation",
535 default,
536 deserialize_with = "null_as_default"
537 )]
538 pub is_default_location: bool,
539}
540
541#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
543#[serde(rename_all = "lowercase")]
544#[non_exhaustive]
545pub enum InstanceType {
546 #[default]
548 Game,
549 Server,
551 #[serde(other)]
553 Other,
554}
555
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
561#[non_exhaustive]
562pub enum LoaderKind {
563 #[serde(rename = "bepinex")]
565 BepInEx,
566 #[serde(rename = "bepisloader")]
569 BepisLoader,
570 #[serde(rename = "gdweave")]
573 GdWeave,
574 #[serde(rename = "godotml")]
577 GodotMl,
578 #[serde(rename = "lovely")]
580 Lovely,
581 #[serde(rename = "melonloader")]
583 MelonLoader,
584 #[serde(rename = "recursive-melonloader")]
588 RecursiveMelonLoader,
589 #[serde(rename = "northstar")]
592 Northstar,
593 #[serde(rename = "return-of-modding")]
596 ReturnOfModding,
597 #[serde(rename = "rivet")]
600 Rivet,
601 #[serde(rename = "shimloader")]
604 Shimloader,
605 #[serde(rename = "umm")]
608 Umm,
609 #[serde(rename = "none")]
611 None,
612 #[default]
614 #[serde(other)]
615 Other,
616}
617
618fn null_as_default<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
621where
622 D: Deserializer<'de>,
623 T: Deserialize<'de> + Default,
624{
625 let opt = Option::<T>::deserialize(deserializer)?;
626
627 Ok(opt.unwrap_or_default())
628}
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633
634 #[test]
635 fn test_bundled_parses() {
636 let eco = Ecosystem::bundled();
637
638 assert!(!eco.games.is_empty());
639 assert!(!eco.modloader_packages.is_empty());
640 assert_eq!(eco.schema_version, "0.3.0");
641 }
642
643 #[test]
644 fn test_valheim_bepinex() {
645 let eco = Ecosystem::bundled();
646 let valheim = eco.game("valheim").expect("valheim present");
647
648 assert_eq!(valheim.slug, "valheim");
649 assert_eq!(valheim.display_name(), "Valheim");
650
651 let profile = valheim.profile().expect("a profile");
652
653 assert_eq!(profile.package_loader, LoaderKind::BepInEx);
654 assert_eq!(profile.instance_type, InstanceType::Game);
655 assert_eq!(profile.steam_app_id(), Some(892970));
656 assert!(!profile.install_rules.is_empty());
657
658 let plugins = profile
659 .install_rules
660 .iter()
661 .find(|r| r.route == "BepInEx/plugins")
662 .expect("plugins rule");
663
664 assert_eq!(plugins.tracking_method, TrackingMethod::Subdir);
665 assert!(plugins.tracking_method.is_namespaced());
666
667 let monomod = profile
668 .install_rules
669 .iter()
670 .find(|r| r.route == "BepInEx/monomod")
671 .expect("monomod rule");
672
673 assert!(
674 monomod
675 .default_file_extensions
676 .iter()
677 .any(|e| e == ".mm.dll")
678 );
679
680 let config = profile
681 .install_rules
682 .iter()
683 .find(|r| r.route == "BepInEx/config")
684 .expect("config rule");
685
686 assert!(!config.tracking_method.is_namespaced());
687 }
688
689 #[test]
690 fn community_comes_from_the_profile_package_index() {
691 let eco = Ecosystem::bundled();
692 let outward = eco.game("outward").expect("outward present");
693 let definitive = outward
694 .profiles
695 .iter()
696 .find(|p| p.settings_identifier.as_deref() == Some("OutwardDe"))
697 .expect("Outward Definitive profile");
698
699 assert_eq!(definitive.community(), Some("outward"));
700 assert_eq!(outward.community(), Some("outward"));
701
702 let server = eco
703 .game("valheim")
704 .expect("valheim present")
705 .profiles
706 .iter()
707 .find(|p| p.instance_type == InstanceType::Server)
708 .expect("valheim server profile");
709
710 assert_eq!(server.settings_identifier.as_deref(), Some("ValheimServer"));
711 assert_eq!(server.community(), Some("valheim"));
712 }
713
714 #[test]
715 fn r2modman_folder_differs_from_settings_identifier_where_the_schema_says() {
716 let eco = Ecosystem::bundled();
717 let cases = [
718 ("disco-elysium", "Disco Elysium", "DiscoElysium"),
719 ("enter-the-gungeon", "EnterTheGungeon", "ETG"),
720 ("i-am-your-beast", "I Am Your Beast", "IAmYourBeast"),
721 (
722 "old-market-simulator",
723 "Old Market Simulator",
724 "OldMarketSimulator",
725 ),
726 ("peaks-of-yore", "Peaks of Yore", "PeaksOfYore"),
727 (
728 "tcg-card-shop-simulator",
729 "TCG Card Shop Simulator",
730 "TCGCardShopSimulator",
731 ),
732 (
733 "totally-accurate-battle-simulator",
734 "TotallyAccurateBattleSimulator",
735 "TABS",
736 ),
737 ];
738
739 for (slug, settings, folder) in cases {
740 let profile = eco.require_profile(slug).unwrap();
741
742 assert_eq!(
743 profile.settings_identifier.as_deref(),
744 Some(settings),
745 "{slug}"
746 );
747 assert_eq!(
748 profile.internal_folder_name.as_deref(),
749 Some(folder),
750 "{slug}"
751 );
752 assert_eq!(
753 eco.game(slug).unwrap().r2modman_folders(),
754 [folder],
755 "{slug}"
756 );
757 }
758 }
759
760 #[test]
761 fn a_server_entry_shares_its_games_r2modman_folder() {
762 let eco = Ecosystem::bundled();
763
764 for (slug, server_settings, folder) in [
765 ("riskofrain2", "RiskOfRain2Server", "RiskOfRain2"),
766 ("valheim", "ValheimServer", "Valheim"),
767 ] {
768 let game = eco.game(slug).unwrap();
769 let server = game
770 .profiles
771 .iter()
772 .find(|p| p.instance_type == InstanceType::Server)
773 .unwrap();
774
775 assert_eq!(
776 server.settings_identifier.as_deref(),
777 Some(server_settings),
778 "{slug}"
779 );
780 assert_eq!(
781 server.internal_folder_name.as_deref(),
782 Some(folder),
783 "{slug}"
784 );
785 assert_eq!(
786 game.profile().unwrap().internal_folder_name.as_deref(),
787 Some(folder),
788 "{slug}"
789 );
790 assert_eq!(game.r2modman_folders(), [folder], "{slug}");
791 }
792 }
793
794 #[test]
795 fn outward_editions_each_have_their_own_r2modman_folder() {
796 let eco = Ecosystem::bundled();
797 let outward = eco.game("outward").unwrap();
798
799 assert!(
800 outward
801 .profiles
802 .iter()
803 .all(|p| p.instance_type == InstanceType::Game)
804 );
805 assert_eq!(outward.r2modman_folders(), ["Outward", "OutwardDe"]);
806 }
807
808 #[test]
809 fn every_bundled_r2modman_entry_names_its_folder() {
810 let eco = Ecosystem::bundled();
811 let unnamed: Vec<&str> = eco
812 .games()
813 .filter(|g| {
814 g.profiles
815 .iter()
816 .any(|p| p.internal_folder_name.as_deref().is_none_or(str::is_empty))
817 })
818 .map(|g| g.slug.as_str())
819 .collect();
820
821 assert!(unnamed.is_empty(), "{unnamed:?}");
822 }
823
824 #[test]
825 fn r2modman_folders_is_empty_without_r2modman_entries() {
826 let eco = Ecosystem::bundled();
827
828 assert!(
829 eco
830 .game("phasmophobia")
831 .unwrap()
832 .r2modman_folders()
833 .is_empty()
834 );
835 }
836
837 #[test]
838 fn community_is_none_without_a_usable_package_index() {
839 let community_of = |index: Option<&str>| {
840 let json = serde_json::json!({
841 "games": { "g": { "r2modman": [{ "packageIndex": index }] } }
842 });
843 let eco = Ecosystem::from_json(&json.to_string()).unwrap();
844
845 eco.game("g").unwrap().community().map(str::to_string)
846 };
847
848 assert_eq!(
849 community_of(Some("https://example.com/c/my-game/api/v1/package/")),
850 Some("my-game".to_string())
851 );
852 assert_eq!(community_of(None), None);
853 assert_eq!(
854 community_of(Some("https://thunderstore.io/api/v1/package/")),
855 None
856 );
857 assert_eq!(
858 community_of(Some("https://thunderstore.io/c/../api/v1/package/")),
859 None
860 );
861 assert_eq!(community_of(Some("https://thunderstore.io/c/")), None);
862 }
863
864 #[test]
865 fn test_modloader_registry_lookup() {
866 let eco = Ecosystem::bundled();
867
868 let pack = eco
869 .modloader_package("denikson-BepInExPack_Valheim")
870 .expect("valheim loader pack present");
871
872 assert_eq!(pack.root_folder, "BepInExPack_Valheim");
873 assert_eq!(pack.loader, LoaderKind::BepInEx);
874
875 assert!(eco.modloader_package("Author-SomeMod").is_none());
876 }
877
878 #[test]
879 fn test_melonloader_game_present() {
880 let eco = Ecosystem::bundled();
881
882 let game = eco
883 .games()
884 .find(|g| {
885 g.profile()
886 .map(|p| p.package_loader == LoaderKind::MelonLoader)
887 .unwrap_or(false)
888 })
889 .expect("at least one MelonLoader game");
890
891 assert!(game.profile().is_some());
892 }
893
894 #[test]
895 fn test_unknown_loader_falls_back_to_other() {
896 let json = r#"{
897 "schemaVersion": "9.9.9",
898 "games": {
899 "x": { "label": "x", "meta": {"displayName": "X"},
900 "r2modman": [ { "packageLoader": "someNewLoader", "installRules": [] } ] }
901 },
902 "modloaderPackages": []
903 }"#;
904
905 let eco = Ecosystem::from_json(json).unwrap();
906 let profile = eco.game("x").unwrap().profile().unwrap();
907
908 assert_eq!(profile.package_loader, LoaderKind::Other);
909 }
910
911 #[test]
912 fn require_profile_tells_an_unknown_game_from_one_without_a_profile() {
913 let json = r#"{
914 "games": {
915 "bare": { "label": "bare", "r2modman": [] },
916 "x": { "label": "x", "r2modman": [ { "packageLoader": "bepinex", "installRules": [] } ] }
917 }
918 }"#;
919 let eco = Ecosystem::from_json(json).unwrap();
920
921 assert!(eco.require_profile("x").is_ok());
922 assert!(matches!(
923 eco.require_profile("ghost"),
924 Err(Error::UnknownGame { game }) if game == "ghost"
925 ));
926 assert!(matches!(
927 eco.require_profile("bare"),
928 Err(Error::NoGameProfile { game }) if game == "bare"
929 ));
930 }
931
932 #[test]
933 fn test_null_relative_file_exclusions_normalizes_to_empty() {
934 let json = r#"{
935 "games": {
936 "x": { "label": "x",
937 "r2modman": [ { "packageLoader": "bepinex", "relativeFileExclusions": null, "installRules": [] } ] }
938 }
939 }"#;
940
941 let eco = Ecosystem::from_json(json).unwrap();
942 let profile = eco.game("x").unwrap().profile().unwrap();
943
944 assert!(profile.relative_file_exclusions.is_empty());
945 }
946
947 #[test]
948 fn test_null_enum_and_bool_fields_normalize_to_defaults() {
949 let json = r#"{
950 "games": {
951 "x": { "label": "x",
952 "r2modman": [ { "packageLoader": null, "gameInstanceType": null,
953 "installRules": [ { "route": "Mods", "trackingMethod": null, "isDefaultLocation": null } ] } ] }
954 }
955 }"#;
956
957 let eco = Ecosystem::from_json(json).unwrap();
958 let profile = eco.game("x").unwrap().profile().unwrap();
959
960 assert_eq!(profile.package_loader, LoaderKind::Other);
961 assert_eq!(profile.instance_type, InstanceType::Game);
962
963 let rule = &profile.install_rules[0];
964
965 assert_eq!(rule.tracking_method, TrackingMethod::Subdir);
966 assert!(!rule.is_default_location);
967 }
968
969 #[test]
970 fn test_unknown_tracking_method_falls_back_to_other() {
971 let json = r#"{
972 "games": {
973 "x": { "label": "x",
974 "r2modman": [ { "packageLoader": "bepinex",
975 "installRules": [ { "route": "Mods", "trackingMethod": "brand-new-method" } ] } ] }
976 }
977 }"#;
978
979 let eco = Ecosystem::from_json(json).unwrap();
980 let rule = &eco.game("x").unwrap().profile().unwrap().install_rules[0];
981
982 assert_eq!(rule.tracking_method, TrackingMethod::Other);
983 assert!(!rule.tracking_method.is_namespaced());
984 }
985
986 #[test]
987 #[cfg(feature = "io")]
988 fn test_fetch_latest_rejects_declared_oversize_body() {
989 let mut server = mockito::Server::new();
990 let body = "x".repeat(1000);
991
992 let mock = server
993 .mock("GET", "/schema")
994 .with_status(200)
995 .with_body(&body)
996 .create();
997
998 let url = format!("{}/schema", server.url());
999 let rt = tokio::runtime::Runtime::new().unwrap();
1000 let client = reqwest::Client::new();
1001
1002 let result = rt.block_on(Ecosystem::fetch_latest_bounded(
1003 &client,
1004 &url,
1005 16,
1006 &RetryPolicy::none(),
1007 ));
1008
1009 assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
1010
1011 mock.assert();
1012 }
1013
1014 #[test]
1015 #[cfg(feature = "io")]
1016 fn test_fetch_latest_rejects_streamed_oversize_body() {
1017 let mut server = mockito::Server::new();
1018
1019 let mock = server
1022 .mock("GET", "/schema")
1023 .with_status(200)
1024 .with_chunked_body(|w| w.write_all(&vec![b'x'; 1000]))
1025 .create();
1026
1027 let url = format!("{}/schema", server.url());
1028 let rt = tokio::runtime::Runtime::new().unwrap();
1029 let client = reqwest::Client::new();
1030
1031 let result = rt.block_on(Ecosystem::fetch_latest_bounded(
1032 &client,
1033 &url,
1034 16,
1035 &RetryPolicy::none(),
1036 ));
1037
1038 assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
1039
1040 mock.assert();
1041 }
1042
1043 #[test]
1044 #[cfg(feature = "io")]
1045 fn test_fetch_latest_parses_network_schema() {
1046 let mut server = mockito::Server::new();
1047
1048 let body = r#"{
1049 "schemaVersion": "0.3.0",
1050 "games": {
1051 "valheim": { "label": "valheim", "meta": {"displayName": "Valheim"},
1052 "r2modman": [ { "packageLoader": "bepinex",
1053 "installRules": [ { "route": "BepInEx/plugins", "trackingMethod": "subdir",
1054 "isDefaultLocation": true, "defaultFileExtensions": [".dll"] } ] } ] }
1055 },
1056 "modloaderPackages": [
1057 { "packageId": "denikson-BepInExPack_Valheim", "rootFolder": "BepInExPack_Valheim", "loader": "bepinex" }
1058 ]
1059 }"#;
1060
1061 let mock = server
1062 .mock("GET", "/schema")
1063 .with_status(200)
1064 .with_header("Content-Type", "application/json")
1065 .with_body(body)
1066 .create();
1067
1068 let url = format!("{}/schema", server.url());
1069 let rt = tokio::runtime::Runtime::new().unwrap();
1070 let client = reqwest::Client::new();
1071 let eco = rt.block_on(Ecosystem::fetch_latest(&client, &url)).unwrap();
1072
1073 assert_eq!(eco.schema_version, "0.3.0");
1074
1075 let profile = eco.game("valheim").unwrap().profile().unwrap();
1076
1077 assert_eq!(profile.package_loader, LoaderKind::BepInEx);
1078 assert!(
1079 eco
1080 .modloader_package("denikson-BepInExPack_Valheim")
1081 .is_some()
1082 );
1083
1084 mock.assert();
1085 }
1086
1087 #[test]
1088 fn steam_app_id_none_when_missing_or_unparseable() {
1089 let no_steam: GameProfile = serde_json::from_str(
1091 r#"{"distributions":[{"platform":"epic-games-store","identifier":"abc"}]}"#,
1092 )
1093 .unwrap();
1094
1095 assert_eq!(no_steam.steam_app_id(), None);
1096
1097 let bad_steam: GameProfile =
1099 serde_json::from_str(r#"{"distributions":[{"platform":"steam","identifier":"nope"}]}"#)
1100 .unwrap();
1101
1102 assert_eq!(bad_steam.steam_app_id(), None);
1103
1104 let steam: GameProfile =
1106 serde_json::from_str(r#"{"distributions":[{"platform":"steam","identifier":"892970"}]}"#)
1107 .unwrap();
1108
1109 assert_eq!(steam.steam_app_id(), Some(892970));
1110 }
1111
1112 #[test]
1113 fn game_profile_prefers_game_instance_then_falls_back() {
1114 let server_only: GameDef =
1116 serde_json::from_str(r#"{"r2modman":[{"gameInstanceType":"server"}]}"#).unwrap();
1117
1118 assert_eq!(
1119 server_only.profile().unwrap().instance_type,
1120 InstanceType::Server
1121 );
1122
1123 let mixed: GameDef = serde_json::from_str(
1125 r#"{"r2modman":[{"gameInstanceType":"server"},{"gameInstanceType":"game"}]}"#,
1126 )
1127 .unwrap();
1128
1129 assert_eq!(mixed.profile().unwrap().instance_type, InstanceType::Game);
1130
1131 let empty: GameDef = serde_json::from_str(r#"{"r2modman":[]}"#).unwrap();
1133
1134 assert!(empty.profile().is_none());
1135 }
1136}