@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 9094488
Fork 0

Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.

Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git

Synced Nov 25, 09:15 UTC

Edit Microsoft Store listing text from asc

Add a smbcloud-ascapi-msstore crate for the Store submission API v1.0 and an `asc msstore` command: app, submissions status, listings get and listings update. Auth is Entra client credentials, read from a dotenv file or MSSTORE_* variables. Listing updates reuse the pending submission and only replace the baseListing keys for title, descriptions, release notes, features and search terms, so packages and pricing pass through unchanged. A submission being processed or certified is refused. The update is read back and compared, and --dry-run prints the diff without writing. Committing to certification is not implemented. Three read-only MCP tools are added: msstore_app_get, msstore_submission_status and msstore_listing_get. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Oct 24, 2026 at 18:55 UTC 909448840417cb34fb79b16456351a1317708e11
19 files changed +1623 -6
.agents/AGENTS.md
+38 -1
@@ -129,7 +129,7 @@ cargo fmt --all -- --check
129 cargo clippy --workspace --all-targets --locked -- -D warnings
130 cargo test --workspace --locked
131 RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace --locked
132 -cargo check -p smbcloud-ascapi-core --locked # also -aso, -play, -signing: each lower crate must build alone
132 +cargo check -p smbcloud-ascapi-core --locked # also -aso, -play, -msstore, -signing: each lower crate must build alone
133 ```
134
135 Single test: `cargo test -p smbcloud-ascapi-aso build::tests::<name>`.
@@ -283,3 +283,40 @@ failed upload keeps the old set. MCP exposes only the reads
283 (`play_listing_list`, `play_images_list`, `play_track_get`); every write stays
284 CLI-only, like review submission. The operations live in
285 `crates/frontend/src/play.rs`.
286 +
287 +## Microsoft Store (CLI)
288 +
289 +`crates/msstore` is a sibling of `crates/play` and does not depend on `core`.
290 +Auth is Entra client credentials (`login.microsoftonline.com/{tenant}/oauth2/token`,
291 +resource `https://manage.devcenter.microsoft.com`), cached until expiry. The
292 +credentials come from a dotenv file (`--msstore-env` or `MSSTORE_ENV_PATH`) with
293 +`MSSTORE_TENANT_ID`, `MSSTORE_CLIENT_ID`, `MSSTORE_CLIENT_SECRET`,
294 +`MSSTORE_SELLER_ID` and `MSSTORE_PRODUCT_ID`, or from the same variables set
295 +directly. `asc msstore` does not need the App Store Connect key.
296 +
297 +The package upload stays with CI. This only edits listing text, and it reuses
298 +the pending submission (the CI draft that holds the MSIX) instead of replacing
299 +it; a submission is created only when none is pending. A submission being
300 +processed or certified is refused. Submissions are `serde_json::Value`, and only
301 +the `baseListing` keys title, shortDescription, description, releaseNotes,
302 +features and keywords are replaced, so packages and pricing round-trip. Commit
303 +to certification is deliberately not implemented: it stays a Partner Center
304 +click or the CI `commit_submission` input.
305 +
306 +```sh
307 +asc msstore app [--product-id 9P69PH1K7NXX]
308 +asc msstore submissions status
309 +asc msstore listings get --locale en-us
310 +asc --dry-run msstore listings update --locale en-us \
311 + --title-file t.txt --short-description-file s.txt --description-file d.txt \
312 + --release-notes-file n.txt --features-file f.txt --keywords-file k.txt
313 +```
314 +
315 +`--dry-run` prints the diff and writes nothing; if it had to create a
316 +submission, it deletes it again. After the PUT the listing is read back and
317 +compared exactly. Limits linted before sending: title 256, short description
318 +1000, description 10000, release notes 1500, up to 20 features of 200
319 +characters, up to 7 search terms of 30 characters and 21 words in total; em
320 +dashes and curly quotes warn. MCP exposes only the reads (`msstore_app_get`,
321 +`msstore_submission_status`, `msstore_listing_get`). The operations live in
322 +`crates/frontend/src/msstore.rs`.
Cargo.lock
+13
@@ -1797,6 +1797,7 @@ dependencies = [
1797 "smbcloud-ascapi-core",
1798 "smbcloud-ascapi-frontend",
1799 "smbcloud-ascapi-mcp",
1800 + "smbcloud-ascapi-msstore",
1801 "smbcloud-ascapi-play",
1802 "smbcloud-ascapi-pricing",
1803 "smbcloud-ascapi-reports",
@@ -1827,6 +1828,7 @@ dependencies = [
1828 "smbcloud-ascapi-appgallery",
1829 "smbcloud-ascapi-aso",
1830 "smbcloud-ascapi-core",
1831 + "smbcloud-ascapi-msstore",
1832 "smbcloud-ascapi-play",
1833 "smbcloud-ascapi-signing",
1834 "tokio",
@@ -1848,6 +1850,17 @@ dependencies = [
1850 "tokio",
1851 ]
1852
1853 +[[package]]
1854 +name = "smbcloud-ascapi-msstore"
1855 +version = "0.3.0"
1856 +dependencies = [
1857 + "reqwest",
1858 + "serde",
1859 + "serde_json",
1860 + "thiserror",
1861 + "tokio",
1862 +]
1863 +
1864 [[package]]
1865 name = "smbcloud-ascapi-play"
1866 version = "0.3.0"
Cargo.toml
+2
@@ -5,6 +5,7 @@ members = [
5 "crates/aso",
6 "crates/play",
7 "crates/appgallery",
8 + "crates/msstore",
9 "crates/signing",
10 "crates/pricing",
11 "crates/reports",
@@ -25,6 +26,7 @@ smbcloud-ascapi-core = { version = "0.3.0", path = "crates/core" }
26 smbcloud-ascapi-aso = { version = "0.3.0", path = "crates/aso" }
27 smbcloud-ascapi-play = { version = "0.3.0", path = "crates/play" }
28 smbcloud-ascapi-appgallery = { version = "0.3.0", path = "crates/appgallery" }
29 +smbcloud-ascapi-msstore = { version = "0.3.0", path = "crates/msstore" }
30 smbcloud-ascapi-signing = { version = "0.3.0", path = "crates/signing" }
31 smbcloud-ascapi-pricing = { version = "0.3.0", path = "crates/pricing" }
32 smbcloud-ascapi-reports = { version = "0.3.0", path = "crates/reports" }
README.md
+2 -1
@@ -10,6 +10,7 @@ from the other:
10 | `smbcloud-ascapi-core` | Shared transport: JWT auth, the HTTP client, JSON:API envelopes, error types |
11 | `smbcloud-ascapi-play` | Google Play (Edits v3): store listings, listing images, track release notes; service-account auth, independent of `core` |
12 | `smbcloud-ascapi-appgallery` | Huawei AppGallery Connect Publishing API (Android): app info and listings, file and package upload, submit, phased release, release time, GMS flag, package list and status; Service Account auth (PS256 JWT), independent of `core` |
13 +| `smbcloud-ascapi-msstore` | Microsoft Store submission API v1.0: listing text on an MSIX app's pending submission; Entra client-credentials auth, independent of `core` |
14 | `smbcloud-ascapi-aso` | App Metadata: apps, app infos, versions, builds, pre-release versions, review submissions, bundle IDs, localizations, screenshots |
15 | `smbcloud-ascapi-pricing` | Pricing: app price schedules, and the per-territory prices joined with their price points and currencies |
16 | `smbcloud-ascapi-signing` | Code signing: certificates and provisioning profiles, plus local RSA key pair and CSR generation |
@@ -18,7 +19,7 @@ from the other:
19 | `smbcloud-ascapi-mcp` | The MCP contract and stdio server |
20 | `smbcloud-ascapi-cli` | The `asc` binary: clap command tree, plus `--mcp` |
21
21 -`aso`, `play`, `appgallery`, `pricing`, `signing` and `reports` know nothing about each other, and neither knows
22 +`aso`, `play`, `appgallery`, `msstore`, `pricing`, `signing` and `reports` know nothing about each other, and neither knows
23 anything about the front ends. Each adds its calls to
24 `smbcloud_ascapi_core::Client` as **extension traits**, since Rust only
25 allows inherent impls in the crate that defines a type:
crates/cli/Cargo.toml
+1
@@ -23,6 +23,7 @@ serde_json = { workspace = true }
23 smbcloud-ascapi-aso = { workspace = true }
24 smbcloud-ascapi-core = { workspace = true }
25 smbcloud-ascapi-appgallery = { workspace = true }
26 +smbcloud-ascapi-msstore = { workspace = true }
27 smbcloud-ascapi-play = { workspace = true }
28 smbcloud-ascapi-pricing = { workspace = true }
29 smbcloud-ascapi-signing = { workspace = true }
crates/cli/src/main.rs
+194 -1
@@ -29,6 +29,7 @@ use smbcloud_ascapi_frontend::attach_build::attach_build;
29 use smbcloud_ascapi_frontend::await_processing::{await_processing, AwaitConfig};
30 use smbcloud_ascapi_frontend::review;
31 use smbcloud_ascapi_frontend::upload::{self, upload_package, validate_app, AltoolAuth, AltoolOp};
32 +use smbcloud_ascapi_msstore::ListingFields as MsStoreListingFields;
33 use smbcloud_ascapi_play::{ImageType as PlayImageType, ListingFields as PlayListingFields};
34 use smbcloud_ascapi_pricing::app_price::PriceKind;
35 use smbcloud_ascapi_pricing::prelude::*;
@@ -559,6 +560,86 @@ enum PlayTracksCommand {
560 },
561 }
562
563 +#[derive(Subcommand)]
564 +#[allow(clippy::large_enum_variant)]
565 +enum MsStoreCommand {
566 + /// The app record, including its pending submission when a draft exists.
567 + App {
568 + /// Store product id; defaults to MSSTORE_PRODUCT_ID.
569 + #[arg(long)]
570 + product_id: Option<String>,
571 + },
572 + /// Submissions of the app.
573 + Submissions {
574 + #[command(subcommand)]
575 + command: MsStoreSubmissionsCommand,
576 + },
577 + /// Localized store listing text.
578 + Listings {
579 + #[command(subcommand)]
580 + command: MsStoreListingsCommand,
581 + },
582 +}
583 +
584 +#[derive(Subcommand)]
585 +enum MsStoreSubmissionsCommand {
586 + /// Id and status of the pending submission, if any.
587 + Status {
588 + #[arg(long)]
589 + product_id: Option<String>,
590 + },
591 +}
592 +
593 +#[derive(Subcommand)]
594 +#[allow(clippy::large_enum_variant)]
595 +enum MsStoreListingsCommand {
596 + /// One locale's listing text, from the pending submission or, with no
597 + /// draft, the last published one.
598 + Get {
599 + #[arg(long)]
600 + product_id: Option<String>,
601 + #[arg(long)]
602 + locale: String,
603 + },
604 + /// Write listing text into the pending submission (one is created only
605 + /// when none exists), then read it back. Never commits to certification.
606 + /// With `--dry-run` the diff is printed and nothing is written.
607 + Update {
608 + #[arg(long)]
609 + product_id: Option<String>,
610 + #[arg(long)]
611 + locale: String,
612 + /// Title, up to 256 characters.
613 + #[arg(long, conflicts_with = "title_file")]
614 + title: Option<String>,
615 + /// Read the title from a UTF-8 file; one trailing newline is dropped.
616 + #[arg(long)]
617 + title_file: Option<PathBuf>,
618 + /// Short description, up to 1000 characters.
619 + #[arg(long, conflicts_with = "short_description_file")]
620 + short_description: Option<String>,
621 + #[arg(long)]
622 + short_description_file: Option<PathBuf>,
623 + /// Description, up to 10000 characters.
624 + #[arg(long, conflicts_with = "description_file")]
625 + description: Option<String>,
626 + #[arg(long)]
627 + description_file: Option<PathBuf>,
628 + /// Release notes, up to 1500 characters.
629 + #[arg(long, conflicts_with = "release_notes_file")]
630 + release_notes: Option<String>,
631 + #[arg(long)]
632 + release_notes_file: Option<PathBuf>,
633 + /// UTF-8 file with one feature per line (up to 20, 200 characters each).
634 + #[arg(long)]
635 + features_file: Option<PathBuf>,
636 + /// UTF-8 file with one search term per line (up to 7, 30 characters
637 + /// and 21 words in total).
638 + #[arg(long)]
639 + keywords_file: Option<PathBuf>,
640 + },
641 +}
642 +
643 #[derive(Subcommand)]
644 enum Command {
645 /// Huawei AppGallery listing text. Uses an AppGallery Connect Service
@@ -588,6 +669,16 @@ enum Command {
669 #[command(subcommand)]
670 command: PlayCommand,
671 },
672 + /// Microsoft Store listings: text on the app's pending submission. Uses
673 + /// Partner Center API credentials, not the App Store Connect key.
674 + Msstore {
675 + /// Dotenv file with the MSSTORE_* credentials. Falls back to
676 + /// `MSSTORE_ENV_PATH`, then to the MSSTORE_* variables themselves.
677 + #[arg(long, global = true)]
678 + msstore_env: Option<PathBuf>,
679 + #[command(subcommand)]
680 + command: MsStoreCommand,
681 + },
682 /// Look up apps by bundle ID, or a specific app by its ASC app ID.
683 Apps {
684 #[command(subcommand)]
@@ -903,6 +994,100 @@ async fn run_appgallery(
994 }
995 }
996
997 +/// One non-empty trimmed line per entry, from a UTF-8 file.
998 +fn lines_arg(file: Option<PathBuf>, flag: &str) -> Result<Option<Vec<String>>> {
999 + let Some(path) = file else {
1000 + return Ok(None);
1001 + };
1002 + let text = std::fs::read_to_string(&path)
1003 + .with_context(|| format!("{flag}: cannot read {} as UTF-8 text", path.display()))?;
1004 + Ok(Some(
1005 + text.lines()
1006 + .map(str::trim)
1007 + .filter(|l| !l.is_empty())
1008 + .map(str::to_string)
1009 + .collect(),
1010 + ))
1011 +}
1012 +
1013 +async fn run_msstore(
1014 + env_path: Option<&std::path::Path>,
1015 + command: MsStoreCommand,
1016 + dry_run: bool,
1017 +) -> Result<()> {
1018 + use smbcloud_ascapi_frontend::msstore;
1019 + let client = msstore::msstore_client(env_path).map_err(|e| anyhow::anyhow!(e))?;
1020 + let fail = |e: String| anyhow::anyhow!(e);
1021 + match command {
1022 + MsStoreCommand::App { product_id } => print_json(
1023 + &msstore::read_app(&client, product_id.as_deref())
1024 + .await
1025 + .map_err(fail)?,
1026 + ),
1027 + MsStoreCommand::Submissions { command } => match command {
1028 + MsStoreSubmissionsCommand::Status { product_id } => print_json(
1029 + &msstore::submission_status(&client, product_id.as_deref())
1030 + .await
1031 + .map_err(fail)?,
1032 + ),
1033 + },
1034 + MsStoreCommand::Listings { command } => match command {
1035 + MsStoreListingsCommand::Get { product_id, locale } => print_json(
1036 + &msstore::read_listing(&client, product_id.as_deref(), &locale)
1037 + .await
1038 + .map_err(fail)?,
1039 + ),
1040 + MsStoreListingsCommand::Update {
1041 + product_id,
1042 + locale,
1043 + title,
1044 + title_file,
1045 + short_description,
1046 + short_description_file,
1047 + description,
1048 + description_file,
1049 + release_notes,
1050 + release_notes_file,
1051 + features_file,
1052 + keywords_file,
1053 + } => {
1054 + let fields = MsStoreListingFields {
1055 + title: text_arg(title, title_file, "--title-file")?,
1056 + short_description: text_arg(
1057 + short_description,
1058 + short_description_file,
1059 + "--short-description-file",
1060 + )?,
1061 + description: text_arg(description, description_file, "--description-file")?,
1062 + release_notes: text_arg(
1063 + release_notes,
1064 + release_notes_file,
1065 + "--release-notes-file",
1066 + )?,
1067 + features: lines_arg(features_file, "--features-file")?,
1068 + keywords: lines_arg(keywords_file, "--keywords-file")?,
1069 + };
1070 + let result = msstore::update_listing(
1071 + &client,
1072 + product_id.as_deref(),
1073 + &locale,
1074 + fields,
1075 + dry_run,
1076 + )
1077 + .await
1078 + .map_err(fail)?;
1079 + for warning in &result.warnings {
1080 + eprintln!("warning: {warning}");
1081 + }
1082 + if result.dry_run {
1083 + println!("# dry run: nothing was written; changes that would be made:");
1084 + }
1085 + print_json(&result)
1086 + }
1087 + },
1088 + }
1089 +}
1090 +
1091 async fn run_play(
1092 service_account: Option<&std::path::Path>,
1093 command: PlayCommand,
@@ -2111,6 +2296,14 @@ async fn main() -> Result<()> {
2296 return run_play(play_service_account.as_deref(), command, cli.dry_run).await;
2297 }
2298
2299 + if let Some(Command::Msstore {
2300 + msstore_env,
2301 + command,
2302 + }) = cli.command
2303 + {
2304 + return run_msstore(msstore_env.as_deref(), command, cli.dry_run).await;
2305 + }
2306 +
2307 let key_id = cli
2308 .key_id
2309 .clone()
@@ -2142,7 +2335,7 @@ async fn main() -> Result<()> {
2335 };
2336
2337 match command {
2145 - Command::AppGallery { .. } | Command::Play { .. } => {
2338 + Command::AppGallery { .. } | Command::Msstore { .. } | Command::Play { .. } => {
2339 unreachable!("handled before App Store Connect credentials")
2340 }
2341 Command::Apps { command } => run_apps(&client, &altool_auth, command, cli.dry_run).await,
crates/frontend/Cargo.toml
+1
@@ -19,6 +19,7 @@ serde_json = { workspace = true }
19 sha2 = "0.10"
20 smbcloud-ascapi-appgallery = { workspace = true }
21 smbcloud-ascapi-aso = { workspace = true }
22 +smbcloud-ascapi-msstore = { workspace = true }
23 smbcloud-ascapi-core = { workspace = true }
24 smbcloud-ascapi-play = { workspace = true }
25 smbcloud-ascapi-signing = { workspace = true }
crates/frontend/src/lib.rs
+1
@@ -28,6 +28,7 @@ pub mod enums;
28 pub mod env;
29 #[cfg(target_os = "macos")]
30 pub mod keychain;
31 +pub mod msstore;
32 pub mod play;
33 pub mod profiles;
34 pub mod review;
crates/frontend/src/msstore.rs new
+345
@@ -0,0 +1,345 @@
1 +//! Microsoft Store listing operations shared by `asc msstore` and the MCP tools.
2 +//!
3 +//! The Store keeps at most one pending submission per app. The rule here is
4 +//! to reuse it, never replace it: the pending submission may already hold the
5 +//! uploaded package, so listing text is written into that one. Only when none
6 +//! exists is a submission created (cloned from the last published one). A
7 +//! submission that is being processed or certified is never touched, and
8 +//! nothing here commits a submission to certification.
9 +
10 +use std::path::Path;
11 +
12 +use serde::Serialize;
13 +use serde_json::Value;
14 +use smbcloud_ascapi_msstore::{Credentials, ListingFields, MsStoreClient};
15 +
16 +/// Submission states in which the Store is working on the submission and a
17 +/// write would be refused or lost.
18 +const LOCKED_STATUSES: [&str; 6] = [
19 + "CommitStarted",
20 + "PreProcessing",
21 + "Certification",
22 + "PendingPublish",
23 + "Publishing",
24 + "Release",
25 +];
26 +
27 +/// Resolve the Store client. `path` wins; then `MSSTORE_ENV_PATH`; then the
28 +/// `MSSTORE_*` variables set directly. Per call, so an unconfigured MCP
29 +/// server still lists its tools. The secret never appears in an error.
30 +pub fn msstore_client(path: Option<&Path>) -> Result<MsStoreClient, String> {
31 + let credentials = if let Some(path) = path {
32 + Credentials::from_env_file(path)
33 + } else if let Ok(path) = std::env::var("MSSTORE_ENV_PATH") {
34 + Credentials::from_env_file(path)
35 + } else if std::env::var_os("MSSTORE_CLIENT_SECRET").is_some() {
36 + Credentials::from_process_env()
37 + } else {
38 + return Err(
39 + "no Microsoft Store credentials: pass --msstore-env, or set \
40 + MSSTORE_ENV_PATH (a dotenv file) or the MSSTORE_* variables"
41 + .to_string(),
42 + );
43 + };
44 + credentials
45 + .map(MsStoreClient::new)
46 + .map_err(|e| e.to_string())
47 +}
48 +
49 +fn err(error: impl std::fmt::Display) -> String {
50 + error.to_string()
51 +}
52 +
53 +fn product<'a>(client: &'a MsStoreClient, product_id: Option<&'a str>) -> &'a str {
54 + product_id.unwrap_or_else(|| client.default_product_id())
55 +}
56 +
57 +fn str_at<'a>(value: &'a Value, pointer: &str) -> Option<&'a str> {
58 + value.pointer(pointer).and_then(Value::as_str)
59 +}
60 +
61 +pub async fn read_app(client: &MsStoreClient, product_id: Option<&str>) -> Result<Value, String> {
62 + client
63 + .get_app(product(client, product_id))
64 + .await
65 + .map_err(err)
66 +}
67 +
68 +#[derive(Debug, Serialize)]
69 +#[serde(rename_all = "camelCase")]
70 +pub struct SubmissionStatus {
71 + pub product_id: String,
72 + pub pending_submission_id: Option<String>,
73 + /// The pending submission's status record; `None` when there is no draft.
74 + pub pending: Option<Value>,
75 + pub last_published_submission_id: Option<String>,
76 +}
77 +
78 +pub async fn submission_status(
79 + client: &MsStoreClient,
80 + product_id: Option<&str>,
81 +) -> Result<SubmissionStatus, String> {
82 + let product_id = product(client, product_id);
83 + let app = client.get_app(product_id).await.map_err(err)?;
84 + let pending_id = str_at(&app, "/pendingApplicationSubmission/id").map(str::to_string);
85 + let pending = match &pending_id {
86 + Some(id) => Some(
87 + client
88 + .submission_status(product_id, id)
89 + .await
90 + .map_err(err)?,
91 + ),
92 + None => None,
93 + };
94 + Ok(SubmissionStatus {
95 + product_id: product_id.to_string(),
96 + pending_submission_id: pending_id,
97 + pending,
98 + last_published_submission_id: str_at(&app, "/lastPublishedApplicationSubmission/id")
99 + .map(str::to_string),
100 + })
101 +}
102 +
103 +#[derive(Debug, Serialize)]
104 +#[serde(rename_all = "camelCase")]
105 +pub struct ListingRead {
106 + pub submission_id: String,
107 + /// `pending` or `lastPublished`.
108 + pub source: &'static str,
109 + pub status: Option<String>,
110 + pub locale: String,
111 + pub listing: ListingFields,
112 +}
113 +
114 +/// The listing of the pending submission, or of the last published one when
115 +/// there is no draft.
116 +pub async fn read_listing(
117 + client: &MsStoreClient,
118 + product_id: Option<&str>,
119 + locale: &str,
120 +) -> Result<ListingRead, String> {
121 + let product_id = product(client, product_id);
122 + let app = client.get_app(product_id).await.map_err(err)?;
123 + let (id, source) = match str_at(&app, "/pendingApplicationSubmission/id") {
124 + Some(id) => (id, "pending"),
125 + None => match str_at(&app, "/lastPublishedApplicationSubmission/id") {
126 + Some(id) => (id, "lastPublished"),
127 + None => return Err("the app has no pending or published submission".to_string()),
128 + },
129 + };
130 + let submission = client.get_submission(product_id, id).await.map_err(err)?;
131 + Ok(ListingRead {
132 + submission_id: id.to_string(),
133 + source,
134 + status: str_at(&submission, "/status").map(str::to_string),
135 + locale: locale.to_string(),
136 + listing: ListingFields::read(&submission, locale),
137 + })
138 +}
139 +
140 +#[derive(Debug, Serialize)]
141 +#[serde(rename_all = "camelCase")]
142 +pub struct FieldChange {
143 + pub field: &'static str,
144 + pub before: Value,
145 + pub after: Value,
146 +}
147 +
148 +#[derive(Debug, Serialize)]
149 +#[serde(rename_all = "camelCase")]
150 +pub struct ListingUpdate {
151 + pub dry_run: bool,
152 + pub submission_id: String,
153 + /// True when no draft existed and one was created for this update. On a
154 + /// dry run that submission is deleted again.
155 + pub created_submission: bool,
156 + pub warnings: Vec<String>,
157 + /// The fields that differ from what the submission holds now.
158 + pub changes: Vec<FieldChange>,
159 + /// The listing read back after the write. `None` on a dry run.
160 + pub after: Option<ListingFields>,
161 +}
162 +
163 +fn changes(sent: &ListingFields, before: &ListingFields) -> Vec<FieldChange> {
164 + let mut out = Vec::new();
165 + let mut push = |field, differs: bool, b: Value, a: Value| {
166 + if differs {
167 + out.push(FieldChange {
168 + field,
169 + before: b,
170 + after: a,
171 + });
172 + }
173 + };
174 + macro_rules! field {
175 + ($name:literal, $f:ident) => {
176 + push(
177 + $name,
178 + sent.$f.is_some() && sent.$f != before.$f,
179 + to_value(&before.$f),
180 + to_value(&sent.$f),
181 + );
182 + };
183 + }
184 + field!("title", title);
185 + field!("shortDescription", short_description);
186 + field!("description", description);
187 + field!("releaseNotes", release_notes);
188 + field!("features", features);
189 + field!("keywords", keywords);
190 + out
191 +}
192 +
193 +fn to_value(v: &impl Serialize) -> Value {
194 + serde_json::to_value(v).unwrap_or(Value::Null)
195 +}
196 +
197 +/// Write listing text into the pending submission (creating one only when
198 +/// none exists), then read it back and compare. Never commits.
199 +pub async fn update_listing(
200 + client: &MsStoreClient,
201 + product_id: Option<&str>,
202 + locale: &str,
203 + fields: ListingFields,
204 + dry_run: bool,
205 +) -> Result<ListingUpdate, String> {
206 + let warnings = fields.validate()?;
207 + if fields.is_empty() {
208 + return Err("nothing to update: pass at least one listing field".to_string());
209 + }
210 + let product_id = product(client, product_id);
211 + let app = client.get_app(product_id).await.map_err(err)?;
212 +
213 + let (mut submission, created) = match str_at(&app, "/pendingApplicationSubmission/id") {
214 + Some(id) => {
215 + let submission = client.get_submission(product_id, id).await.map_err(err)?;
216 + if let Some(status) = str_at(&submission, "/status") {
217 + if LOCKED_STATUSES.contains(&status) {
218 + return Err(format!(
219 + "submission {id} is {status}; the Store is working on it, so its \
220 + listing cannot be edited now"
221 + ));
222 + }
223 + }
224 + (submission, false)
225 + }
226 + None => (
227 + client.create_submission(product_id).await.map_err(err)?,
228 + true,
229 + ),
230 + };
231 + let id = str_at(&submission, "/id")
232 + .ok_or("the submission has no id")?
233 + .to_string();
234 +
235 + let outcome = write_and_verify(
236 + client,
237 + product_id,
238 + &id,
239 + &mut submission,
240 + locale,
241 + &fields,
242 + dry_run,
243 + )
244 + .await;
245 + // A submission this call created is removed again unless it holds the
246 + // change: on a dry run, or when the write failed.
247 + if created && (dry_run || outcome.is_err()) {
248 + if let Err(e) = client.delete_submission(product_id, &id).await {
249 + return Err(format!(
250 + "{}submission {id} was created and could not be deleted: {e}",
251 + outcome.err().map(|o| format!("{o}; ")).unwrap_or_default()
252 + ));
253 + }
254 + }
255 + let (changes, after) = outcome?;
256 + Ok(ListingUpdate {
257 + dry_run,
258 + submission_id: id,
259 + created_submission: created,
260 + warnings,
261 + changes,
262 + after,
263 + })
264 +}
265 +
266 +type Outcome = (Vec<FieldChange>, Option<ListingFields>);
267 +
268 +async fn write_and_verify(
269 + client: &MsStoreClient,
270 + product_id: &str,
271 + id: &str,
272 + submission: &mut Value,
273 + locale: &str,
274 + fields: &ListingFields,
275 + dry_run: bool,
276 +) -> Result<Outcome, String> {
277 + let before = ListingFields::read(submission, locale);
278 + let changes = changes(fields, &before);
279 + if dry_run {
280 + return Ok((changes, None));
281 + }
282 + let packages = submission.get("applicationPackages").cloned();
283 + fields.apply(submission, locale).map_err(err)?;
284 + client
285 + .update_submission(product_id, id, submission)
286 + .await
287 + .map_err(err)?;
288 + let stored = client.get_submission(product_id, id).await.map_err(err)?;
289 + let after = ListingFields::read(&stored, locale);
290 + let wrong = fields.diff(&after);
291 + if !wrong.is_empty() {
292 + return Err(format!(
293 + "written, but the read-back differs in: {}",
294 + wrong.join(", ")
295 + ));
296 + }
297 + if stored.get("applicationPackages").cloned() != packages {
298 + return Err(
299 + "written, but applicationPackages changed; check the submission in \
300 + Partner Center"
301 + .to_string(),
302 + );
303 + }
304 + Ok((changes, Some(after)))
305 +}
306 +
307 +#[cfg(test)]
308 +mod tests {
309 + use super::*;
310 +
311 + #[test]
312 + fn locked_statuses_cover_the_in_flight_states() {
313 + for s in ["CommitStarted", "PreProcessing", "Certification"] {
314 + assert!(LOCKED_STATUSES.contains(&s));
315 + }
316 + assert!(!LOCKED_STATUSES.contains(&"PendingCommit"));
317 + }
318 +
319 + #[test]
320 + fn changes_list_only_sent_fields_that_differ() {
321 + let before = ListingFields {
322 + title: Some("A".into()),
323 + description: Some("d".into()),
324 + ..Default::default()
325 + };
326 + let sent = ListingFields {
327 + title: Some("A".into()),
328 + description: Some("e".into()),
329 + keywords: Some(vec!["k".into()]),
330 + ..Default::default()
331 + };
332 + let names: Vec<_> = changes(&sent, &before).iter().map(|c| c.field).collect();
333 + assert_eq!(names, vec!["description", "keywords"]);
334 + }
335 +
336 + #[test]
337 + fn missing_credentials_name_the_options_without_a_secret() {
338 + if std::env::var_os("MSSTORE_ENV_PATH").is_none()
339 + && std::env::var_os("MSSTORE_CLIENT_SECRET").is_none()
340 + {
341 + let error = msstore_client(None).err().unwrap();
342 + assert!(error.contains("MSSTORE_ENV_PATH"));
343 + }
344 + }
345 +}
crates/mcp/src/lib.rs
+70 -1
@@ -75,7 +75,10 @@ macro_rules! ascapi_mcp_tools {
75 $play_track_get_name:literal,
76 $appgallery_app_info_get_name:literal,
77 $appgallery_package_list_name:literal,
78 - $appgallery_package_status_name:literal
78 + $appgallery_package_status_name:literal,
79 + $msstore_app_get_name:literal,
80 + $msstore_submission_status_name:literal,
81 + $msstore_listing_get_name:literal
82 ) => {
83 #[::rmcp::tool_router(router = ascapi_tool_router, vis = "pub(crate)")]
84 impl $server {
@@ -1110,6 +1113,72 @@ macro_rules! ascapi_mcp_tools {
1113 ::rmcp::model::ContentBlock::json(&value)?,
1114 ]))
1115 }
1116 +
1117 + #[::rmcp::tool(
1118 + name = $msstore_app_get_name,
1119 + title = "Get a Microsoft Store app",
1120 + annotations(title = "Get a Microsoft Store app", read_only_hint = true, idempotent_hint = true),
1121 + description = "Purpose: read a Microsoft Store app record, including its pending submission when a draft exists. When to use vs siblings: use msstore_submission_status for the draft's certification state and msstore_listing_get for listing text. Behavior: returns the app's Store record as the submission API reports it. Limitations: read-only; changing a listing is available only through the asc msstore listings update command. Prerequisites: Partner Center API credentials in a dotenv file at MSSTORE_ENV_PATH, or the MSSTORE_TENANT_ID, MSSTORE_CLIENT_ID, MSSTORE_CLIENT_SECRET, MSSTORE_SELLER_ID and MSSTORE_PRODUCT_ID variables. Failure modes: missing credentials return an invalid-request error naming what is absent; Microsoft Store errors are returned verbatim with their status."
1122 + )]
1123 + async fn msstore_app_get(
1124 + &self,
1125 + parameters: ::rmcp::handler::server::wrapper::Parameters<$crate::MsStoreProductRequest>,
1126 + ) -> ::std::result::Result<::rmcp::model::CallToolResult, ::rmcp::model::ErrorData> {
1127 + use ::smbcloud_ascapi_frontend::msstore;
1128 + let client = msstore::msstore_client(None)
1129 + .map_err(|error| ::rmcp::model::ErrorData::invalid_request(error, None))?;
1130 + let request = parameters.0;
1131 + let value = msstore::read_app(&client, request.product_id.as_deref())
1132 + .await
1133 + .map_err(|error| ::rmcp::model::ErrorData::internal_error(error, None))?;
1134 + Ok(::rmcp::model::CallToolResult::success(vec![
1135 + ::rmcp::model::ContentBlock::json(&value)?,
1136 + ]))
1137 + }
1138 +
1139 + #[::rmcp::tool(
1140 + name = $msstore_submission_status_name,
1141 + title = "Get Microsoft Store submission status",
1142 + annotations(title = "Get Microsoft Store submission status", read_only_hint = true, idempotent_hint = true),
1143 + description = "Purpose: read the id and status of the pending Microsoft Store submission, and the id of the last published one. When to use vs siblings: use msstore_app_get for the whole app record and msstore_listing_get for listing text. Behavior: reports no pending submission when there is no draft. Limitations: read-only; the Store does not commit anything from this tool. Prerequisites: Partner Center API credentials in a dotenv file at MSSTORE_ENV_PATH, or the MSSTORE_TENANT_ID, MSSTORE_CLIENT_ID, MSSTORE_CLIENT_SECRET, MSSTORE_SELLER_ID and MSSTORE_PRODUCT_ID variables. Failure modes: missing credentials return an invalid-request error naming what is absent; Microsoft Store errors are returned verbatim with their status."
1144 + )]
1145 + async fn msstore_submission_status(
1146 + &self,
1147 + parameters: ::rmcp::handler::server::wrapper::Parameters<$crate::MsStoreProductRequest>,
1148 + ) -> ::std::result::Result<::rmcp::model::CallToolResult, ::rmcp::model::ErrorData> {
1149 + use ::smbcloud_ascapi_frontend::msstore;
1150 + let client = msstore::msstore_client(None)
1151 + .map_err(|error| ::rmcp::model::ErrorData::invalid_request(error, None))?;
1152 + let request = parameters.0;
1153 + let value = msstore::submission_status(&client, request.product_id.as_deref())
1154 + .await
1155 + .map_err(|error| ::rmcp::model::ErrorData::internal_error(error, None))?;
1156 + Ok(::rmcp::model::CallToolResult::success(vec![
1157 + ::rmcp::model::ContentBlock::json(&value)?,
1158 + ]))
1159 + }
1160 +
1161 + #[::rmcp::tool(
1162 + name = $msstore_listing_get_name,
1163 + title = "Get a Microsoft Store listing",
1164 + annotations(title = "Get a Microsoft Store listing", read_only_hint = true, idempotent_hint = true),
1165 + description = "Purpose: read one locale's listing text (title, short description, description, release notes, features, search terms) from the pending submission, or from the last published one when there is no draft. When to use vs siblings: use msstore_submission_status for state. Behavior: returns the fields the listing holds and the submission id they came from. Limitations: read-only; writing a listing is available only through the asc msstore listings update command. Prerequisites: Partner Center API credentials in a dotenv file at MSSTORE_ENV_PATH, or the MSSTORE_TENANT_ID, MSSTORE_CLIENT_ID, MSSTORE_CLIENT_SECRET, MSSTORE_SELLER_ID and MSSTORE_PRODUCT_ID variables. Failure modes: missing credentials return an invalid-request error naming what is absent; Microsoft Store errors are returned verbatim with their status."
1166 + )]
1167 + async fn msstore_listing_get(
1168 + &self,
1169 + parameters: ::rmcp::handler::server::wrapper::Parameters<$crate::MsStoreListingGetRequest>,
1170 + ) -> ::std::result::Result<::rmcp::model::CallToolResult, ::rmcp::model::ErrorData> {
1171 + use ::smbcloud_ascapi_frontend::msstore;
1172 + let client = msstore::msstore_client(None)
1173 + .map_err(|error| ::rmcp::model::ErrorData::invalid_request(error, None))?;
1174 + let request = parameters.0;
1175 + let value = msstore::read_listing(&client, request.product_id.as_deref(), &request.locale)
1176 + .await
1177 + .map_err(|error| ::rmcp::model::ErrorData::internal_error(error, None))?;
1178 + Ok(::rmcp::model::CallToolResult::success(vec![
1179 + ::rmcp::model::ContentBlock::json(&value)?,
1180 + ]))
1181 + }
1182 }
1183 };
1184 }
crates/mcp/src/requests.rs
+17
@@ -329,3 +329,20 @@ pub struct AppGalleryPackageStatusRequest {
329 /// Package ids (pkgVersion) from appgallery_package_list.
330 pub pkg_ids: Vec<String>,
331 }
332 +
333 +#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
334 +pub struct MsStoreProductRequest {
335 + /// Microsoft Store product id, e.g. 9P69PH1K7NXX. Defaults to
336 + /// MSSTORE_PRODUCT_ID.
337 + #[serde(default)]
338 + pub product_id: Option<String>,
339 +}
340 +
341 +#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
342 +pub struct MsStoreListingGetRequest {
343 + /// Microsoft Store product id. Defaults to MSSTORE_PRODUCT_ID.
344 + #[serde(default)]
345 + pub product_id: Option<String>,
346 + /// Listing locale, e.g. en-us.
347 + pub locale: String,
348 +}
crates/mcp/src/server.rs
+8 -2
@@ -65,7 +65,10 @@ ascapi_mcp_tools!(
65 "play_track_get",
66 "appgallery_app_info_get",
67 "appgallery_package_list",
68 - "appgallery_package_status"
68 + "appgallery_package_status",
69 + "msstore_app_get",
70 + "msstore_submission_status",
71 + "msstore_listing_get"
72 );
73
74 #[rmcp::tool_handler(router = Self::ascapi_tool_router())]
@@ -114,7 +117,7 @@ mod tests {
117 /// The canonical tool names. Adding or renaming one is a
118 /// public-contract change, and this list is what makes that
119 /// deliberate rather than accidental.
117 - const CANONICAL_TOOL_NAMES: [&str; 37] = [
120 + const CANONICAL_TOOL_NAMES: [&str; 40] = [
121 "app_list",
122 "app_get",
123 "app_update",
@@ -152,6 +155,9 @@ mod tests {
155 "appgallery_app_info_get",
156 "appgallery_package_list",
157 "appgallery_package_status",
158 + "msstore_app_get",
159 + "msstore_submission_status",
160 + "msstore_listing_get",
161 ];
162
163 /// Never a tool, at any point, for any caller.
crates/msstore/Cargo.toml new
+19
@@ -0,0 +1,19 @@
1 +[package]
2 +name = "smbcloud-ascapi-msstore"
3 +version.workspace = true
4 +edition.workspace = true
5 +authors.workspace = true
6 +license.workspace = true
7 +repository.workspace = true
8 +description = "Microsoft Store submission API v1.0: store listing text on an MSIX app's submission, authenticated with Entra client credentials."
9 +readme = "README.md"
10 +
11 +[lib]
12 +path = "src/lib.rs"
13 +
14 +[dependencies]
15 +reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots"] }
16 +serde = { workspace = true, features = ["derive"] }
17 +serde_json = { workspace = true }
18 +thiserror = { workspace = true }
19 +tokio = { workspace = true, features = ["sync", "time"] }
crates/msstore/README.md new
+20
@@ -0,0 +1,20 @@
1 +# smbcloud-ascapi-msstore
2 +
3 +Microsoft Store submission API v1.0 for store-listing work: the text of a
4 +listing (title, short description, description, release notes, features and
5 +search terms) on an MSIX app's submission. It is a sibling of
6 +`smbcloud-ascapi-play` and shares nothing with `smbcloud-ascapi-core`: the
7 +Store uses Entra client-credentials tokens and its own error envelope.
8 +
9 +```rust
10 +use smbcloud_ascapi_msstore::{Credentials, MsStoreClient};
11 +
12 +let credentials = Credentials::from_env_file("partner-center.env")?;
13 +let product = credentials.product_id.clone();
14 +let client = MsStoreClient::new(credentials);
15 +let app = client.get_app(&product).await?;
16 +```
17 +
18 +Submissions are kept as `serde_json::Value`. Only the listing keys are
19 +replaced, so packages, pricing and everything else round-trip untouched.
20 +Committing a submission to certification is deliberately not implemented.
crates/msstore/src/auth.rs new
+251
@@ -0,0 +1,251 @@
1 +use std::collections::HashMap;
2 +use std::path::Path;
3 +use std::time::{Duration, Instant};
4 +
5 +use serde::{Deserialize, Deserializer};
6 +use tokio::sync::Mutex;
7 +
8 +use crate::error::{Error, Result};
9 +
10 +/// The audience the submission API accepts tokens for.
11 +pub const RESOURCE: &str = "https://manage.devcenter.microsoft.com";
12 +/// Refresh this long before the token expires.
13 +const REFRESH_MARGIN: Duration = Duration::from_secs(60);
14 +
15 +pub const KEY_TENANT_ID: &str = "MSSTORE_TENANT_ID";
16 +pub const KEY_CLIENT_ID: &str = "MSSTORE_CLIENT_ID";
17 +pub const KEY_CLIENT_SECRET: &str = "MSSTORE_CLIENT_SECRET";
18 +pub const KEY_SELLER_ID: &str = "MSSTORE_SELLER_ID";
19 +pub const KEY_PRODUCT_ID: &str = "MSSTORE_PRODUCT_ID";
20 +
21 +/// Partner Center API credentials plus the app they act on.
22 +#[derive(Clone)]
23 +pub struct Credentials {
24 + pub tenant_id: String,
25 + pub client_id: String,
26 + client_secret: String,
27 + pub seller_id: String,
28 + pub product_id: String,
29 +}
30 +
31 +// Hand-written so `{:?}` can never print the client secret.
32 +impl std::fmt::Debug for Credentials {
33 + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 + f.debug_struct("Credentials")
35 + .field("tenant_id", &self.tenant_id)
36 + .field("client_id", &self.client_id)
37 + .field("client_secret", &"<redacted>")
38 + .field("seller_id", &self.seller_id)
39 + .field("product_id", &self.product_id)
40 + .finish()
41 + }
42 +}
43 +
44 +/// Parse a dotenv file: `KEY=VALUE` lines, `#` comments, an optional
45 +/// `export ` prefix, and one pair of matching quotes around a value.
46 +pub fn parse_dotenv(text: &str) -> HashMap<String, String> {
47 + let mut map = HashMap::new();
48 + for line in text.lines() {
49 + let line = line.trim();
50 + if line.is_empty() || line.starts_with('#') {
51 + continue;
52 + }
53 + let line = line.strip_prefix("export ").unwrap_or(line);
54 + let Some((key, value)) = line.split_once('=') else {
55 + continue;
56 + };
57 + let value = value.trim();
58 + let value = ['"', '\'']
59 + .iter()
60 + .find_map(|q| value.strip_prefix(*q).and_then(|v| v.strip_suffix(*q)))
61 + .unwrap_or(value);
62 + map.insert(key.trim().to_string(), value.to_string());
63 + }
64 + map
65 +}
66 +
67 +impl Credentials {
68 + /// Build from a key lookup. A key that is absent or empty is an error
69 + /// naming the key.
70 + pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self> {
71 + let need = |key: &'static str| {
72 + get(key)
73 + .map(|v| v.trim().to_string())
74 + .filter(|v| !v.is_empty())
75 + .ok_or(Error::MissingCredential(key))
76 + };
77 + Ok(Self {
78 + tenant_id: need(KEY_TENANT_ID)?,
79 + client_id: need(KEY_CLIENT_ID)?,
80 + client_secret: need(KEY_CLIENT_SECRET)?,
81 + seller_id: need(KEY_SELLER_ID)?,
82 + product_id: need(KEY_PRODUCT_ID)?,
83 + })
84 + }
85 +
86 + pub fn from_env_file(path: impl AsRef<Path>) -> Result<Self> {
87 + let path = path.as_ref();
88 + let text = std::fs::read_to_string(path).map_err(|source| Error::EnvRead {
89 + path: path.display().to_string(),
90 + source,
91 + })?;
92 + let map = parse_dotenv(&text);
93 + Self::from_lookup(|key| map.get(key).cloned())
94 + }
95 +
96 + pub fn from_process_env() -> Result<Self> {
97 + Self::from_lookup(|key| std::env::var(key).ok())
98 + }
99 +
100 + pub fn token_url(&self) -> String {
101 + token_url(&self.tenant_id)
102 + }
103 +
104 + /// The client-credentials form body.
105 + pub fn token_form(&self) -> Vec<(&'static str, String)> {
106 + vec![
107 + ("grant_type", "client_credentials".to_string()),
108 + ("client_id", self.client_id.clone()),
109 + ("client_secret", self.client_secret.clone()),
110 + ("resource", RESOURCE.to_string()),
111 + ]
112 + }
113 +}
114 +
115 +pub(crate) fn token_url(tenant: &str) -> String {
116 + format!("https://login.microsoftonline.com/{tenant}/oauth2/token")
117 +}
118 +
119 +/// Entra's v1 endpoint returns `expires_in` as a string; accept a number too.
120 +fn seconds<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<Option<u64>, D::Error> {
121 + #[derive(Deserialize)]
122 + #[serde(untagged)]
123 + enum Secs {
124 + Num(u64),
125 + Text(String),
126 + }
127 + Ok(match Option::<Secs>::deserialize(d)? {
128 + Some(Secs::Num(n)) => Some(n),
129 + Some(Secs::Text(s)) => s.parse().ok(),
130 + None => None,
131 + })
132 +}
133 +
134 +#[derive(Deserialize)]
135 +struct TokenResponse {
136 + access_token: String,
137 + #[serde(default, deserialize_with = "seconds")]
138 + expires_in: Option<u64>,
139 +}
140 +
141 +/// Fetches and caches the access token until shortly before it expires.
142 +pub(crate) struct TokenCache {
143 + cached: Mutex<Option<(String, Instant)>>,
144 +}
145 +
146 +impl TokenCache {
147 + pub(crate) fn new() -> Self {
148 + Self {
149 + cached: Mutex::new(None),
150 + }
151 + }
152 +
153 + pub(crate) async fn get(
154 + &self,
155 + http: &reqwest::Client,
156 + credentials: &Credentials,
157 + ) -> Result<String> {
158 + let mut cached = self.cached.lock().await;
159 + if let Some((token, expires)) = cached.as_ref() {
160 + if Instant::now() < *expires {
161 + return Ok(token.clone());
162 + }
163 + }
164 + let response = http
165 + .post(credentials.token_url())
166 + .form(&credentials.token_form())
167 + .send()
168 + .await?;
169 + let status = response.status();
170 + if !status.is_success() {
171 + return Err(Error::Token {
172 + status: status.as_u16(),
173 + detail: response.text().await.unwrap_or_default(),
174 + });
175 + }
176 + let body: TokenResponse = response.json().await?;
177 + let lifetime = Duration::from_secs(body.expires_in.unwrap_or(3600));
178 + let expires = Instant::now() + lifetime.saturating_sub(REFRESH_MARGIN);
179 + *cached = Some((body.access_token.clone(), expires));
180 + Ok(body.access_token)
181 + }
182 +}
183 +
184 +#[cfg(test)]
185 +mod tests {
186 + use super::*;
187 +
188 + fn sample() -> Credentials {
189 + let map = parse_dotenv(
190 + "MSSTORE_TENANT_ID=tenant-1\nMSSTORE_CLIENT_ID=client-1\n\
191 + MSSTORE_CLIENT_SECRET=\"s3cret\"\nMSSTORE_SELLER_ID=42\nMSSTORE_PRODUCT_ID=9P69\n",
192 + );
193 + Credentials::from_lookup(|k| map.get(k).cloned()).unwrap()
194 + }
195 +
196 + #[test]
197 + fn token_url_embeds_the_tenant() {
198 + assert_eq!(
199 + sample().token_url(),
200 + "https://login.microsoftonline.com/tenant-1/oauth2/token"
201 + );
202 + }
203 +
204 + #[test]
205 + fn token_form_is_client_credentials_for_the_devcenter_resource() {
206 + let form = sample().token_form();
207 + let get = |k: &str| form.iter().find(|(n, _)| *n == k).map(|(_, v)| v.as_str());
208 + assert_eq!(get("grant_type"), Some("client_credentials"));
209 + assert_eq!(get("client_id"), Some("client-1"));
210 + assert_eq!(get("client_secret"), Some("s3cret"));
211 + assert_eq!(
212 + get("resource"),
213 + Some("https://manage.devcenter.microsoft.com")
214 + );
215 + }
216 +
217 + #[test]
218 + fn debug_output_never_contains_the_secret() {
219 + let shown = format!("{:?}", sample());
220 + assert!(!shown.contains("s3cret"));
221 + assert!(shown.contains("client-1"));
222 + }
223 +
224 + #[test]
225 + fn dotenv_handles_comments_export_and_quotes() {
226 + let map = parse_dotenv("# c\n\nexport A='x y'\nB = \"z\"\nC=\nnot a pair\n");
227 + assert_eq!(map["A"], "x y");
228 + assert_eq!(map["B"], "z");
229 + assert_eq!(map["C"], "");
230 + assert_eq!(map.len(), 3);
231 + }
232 +
233 + #[test]
234 + fn an_empty_value_is_reported_by_key_without_any_value() {
235 + let map = parse_dotenv("MSSTORE_TENANT_ID=t\nMSSTORE_CLIENT_ID=\n");
236 + let err = Credentials::from_lookup(|k| map.get(k).cloned()).unwrap_err();
237 + assert_eq!(
238 + err.to_string(),
239 + "missing or empty credential MSSTORE_CLIENT_ID"
240 + );
241 + }
242 +
243 + #[test]
244 + fn expires_in_parses_as_string_or_number() {
245 + let a: TokenResponse =
246 + serde_json::from_str(r#"{"access_token":"t","expires_in":"3599"}"#).unwrap();
247 + let b: TokenResponse =
248 + serde_json::from_str(r#"{"access_token":"t","expires_in":3599}"#).unwrap();
249 + assert_eq!((a.expires_in, b.expires_in), (Some(3599), Some(3599)));
250 + }
251 +}
crates/msstore/src/client.rs new
+136
@@ -0,0 +1,136 @@
1 +use reqwest::Method;
2 +use serde_json::Value;
3 +
4 +use crate::auth::{Credentials, TokenCache};
5 +use crate::error::{Error, Result};
6 +
7 +const API_ROOT: &str = "https://manage.devcenter.microsoft.com";
8 +
9 +/// Build `/v1.0/my/applications/{id}…`. `suffix` carries its own leading `/`.
10 +pub(crate) fn app_path(product_id: &str, suffix: &str) -> String {
11 + format!("/v1.0/my/applications/{product_id}{suffix}")
12 +}
13 +
14 +pub struct MsStoreClient {
15 + http: reqwest::Client,
16 + credentials: Credentials,
17 + tokens: TokenCache,
18 + root: String,
19 +}
20 +
21 +impl MsStoreClient {
22 + pub fn new(credentials: Credentials) -> Self {
23 + Self {
24 + http: reqwest::Client::new(),
25 + credentials,
26 + tokens: TokenCache::new(),
27 + root: API_ROOT.to_string(),
28 + }
29 + }
30 +
31 + /// The product id from the credentials, used when none is passed.
32 + pub fn default_product_id(&self) -> &str {
33 + &self.credentials.product_id
34 + }
35 +
36 + async fn send(&self, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {
37 + let token = self.tokens.get(&self.http, &self.credentials).await?;
38 + let mut request = self
39 + .http
40 + .request(method, format!("{}{path}", self.root))
41 + .bearer_auth(token);
42 + if let Some(body) = body {
43 + request = request.json(body);
44 + }
45 + let response = request.send().await?;
46 + let status = response.status();
47 + if !status.is_success() {
48 + return Err(Error::Api {
49 + status: status.as_u16(),
50 + detail: response.text().await.unwrap_or_default(),
51 + });
52 + }
53 + let text = response.text().await?;
54 + if text.trim().is_empty() {
55 + Ok(Value::Null)
56 + } else {
57 + Ok(serde_json::from_str(&text)?)
58 + }
59 + }
60 +
61 + /// The app, including `pendingApplicationSubmission` when a draft exists.
62 + pub async fn get_app(&self, product_id: &str) -> Result<Value> {
63 + self.send(Method::GET, &app_path(product_id, ""), None)
64 + .await
65 + }
66 +
67 + /// Create a submission cloned from the last published one.
68 + pub async fn create_submission(&self, product_id: &str) -> Result<Value> {
69 + self.send(
70 + Method::POST,
71 + &app_path(product_id, "/submissions"),
72 + Some(&Value::Object(Default::default())),
73 + )
74 + .await
75 + }
76 +
77 + pub async fn get_submission(&self, product_id: &str, submission_id: &str) -> Result<Value> {
78 + self.send(
79 + Method::GET,
80 + &app_path(product_id, &format!("/submissions/{submission_id}")),
81 + None,
82 + )
83 + .await
84 + }
85 +
86 + pub async fn update_submission(
87 + &self,
88 + product_id: &str,
89 + submission_id: &str,
90 + submission: &Value,
91 + ) -> Result<Value> {
92 + self.send(
93 + Method::PUT,
94 + &app_path(product_id, &format!("/submissions/{submission_id}")),
95 + Some(submission),
96 + )
97 + .await
98 + }
99 +
100 + pub async fn submission_status(&self, product_id: &str, submission_id: &str) -> Result<Value> {
101 + self.send(
102 + Method::GET,
103 + &app_path(product_id, &format!("/submissions/{submission_id}/status")),
104 + None,
105 + )
106 + .await
107 + }
108 +
109 + pub async fn delete_submission(&self, product_id: &str, submission_id: &str) -> Result<()> {
110 + self.send(
111 + Method::DELETE,
112 + &app_path(product_id, &format!("/submissions/{submission_id}")),
113 + None,
114 + )
115 + .await?;
116 + Ok(())
117 + }
118 +}
119 +
120 +#[cfg(test)]
121 +mod tests {
122 + use super::*;
123 +
124 + #[test]
125 + fn urls_follow_the_v1_layout() {
126 + assert_eq!(app_path("9P69", ""), "/v1.0/my/applications/9P69");
127 + assert_eq!(
128 + app_path("9P69", "/submissions"),
129 + "/v1.0/my/applications/9P69/submissions"
130 + );
131 + assert_eq!(
132 + app_path("9P69", "/submissions/123/status"),
133 + "/v1.0/my/applications/9P69/submissions/123/status"
134 + );
135 + }
136 +}
crates/msstore/src/error.rs new
+32
@@ -0,0 +1,32 @@
1 +use thiserror::Error;
2 +
3 +#[derive(Debug, Error)]
4 +pub enum Error {
5 + #[error("failed to read the credentials file {path}: {source}")]
6 + EnvRead {
7 + path: String,
8 + #[source]
9 + source: std::io::Error,
10 + },
11 +
12 + /// Names the key only, never a value.
13 + #[error("missing or empty credential {0}")]
14 + MissingCredential(&'static str),
15 +
16 + #[error("http request failed: {0}")]
17 + Http(#[from] reqwest::Error),
18 +
19 + #[error("failed to decode JSON: {0}")]
20 + Json(#[from] serde_json::Error),
21 +
22 + #[error("Entra token request returned {status}: {detail}")]
23 + Token { status: u16, detail: String },
24 +
25 + #[error("Microsoft Store API returned {status}: {detail}")]
26 + Api { status: u16, detail: String },
27 +
28 + #[error("unexpected submission shape: {0}")]
29 + Shape(String),
30 +}
31 +
32 +pub type Result<T> = std::result::Result<T, Error>;
crates/msstore/src/lib.rs new
+22
@@ -0,0 +1,22 @@
1 +//! Microsoft Store submission API v1.0 for store-listing work.
2 +//!
3 +//! Reads an MSIX app and its submissions, and edits the listing text on a
4 +//! submission: title, short description, description, release notes, features
5 +//! and search terms. Authentication is Entra client credentials, cached until
6 +//! shortly before the token expires. Submissions travel as
7 +//! [`serde_json::Value`] so only the listing keys are touched and everything
8 +//! else round-trips. Committing a submission is not implemented.
9 +
10 +pub mod auth;
11 +pub mod client;
12 +pub mod error;
13 +pub mod listing;
14 +
15 +pub use auth::{parse_dotenv, Credentials};
16 +pub use client::MsStoreClient;
17 +pub use error::{Error, Result};
18 +pub use listing::{
19 + ListingFields, DESCRIPTION_MAX_LEN, FEATURES_MAX_COUNT, FEATURE_MAX_LEN, KEYWORDS_MAX_COUNT,
20 + KEYWORDS_MAX_WORDS, KEYWORD_MAX_LEN, RELEASE_NOTES_MAX_LEN, SHORT_DESCRIPTION_MAX_LEN,
21 + TITLE_MAX_LEN,
22 +};
crates/msstore/src/listing.rs new
+451
@@ -0,0 +1,451 @@
1 +use serde::Serialize;
2 +use serde_json::{json, Map, Value};
3 +
4 +use crate::error::{Error, Result};
5 +
6 +/// Maximum `title` length, in characters.
7 +pub const TITLE_MAX_LEN: usize = 256;
8 +/// Maximum `description` length, in characters.
9 +pub const DESCRIPTION_MAX_LEN: usize = 10_000;
10 +/// Maximum `shortDescription` length, in characters.
11 +pub const SHORT_DESCRIPTION_MAX_LEN: usize = 1_000;
12 +/// Maximum `releaseNotes` length, in characters.
13 +pub const RELEASE_NOTES_MAX_LEN: usize = 1_500;
14 +/// Maximum number of `features`.
15 +pub const FEATURES_MAX_COUNT: usize = 20;
16 +/// Maximum length of one feature, in characters.
17 +pub const FEATURE_MAX_LEN: usize = 200;
18 +/// Maximum number of `keywords` (search terms).
19 +pub const KEYWORDS_MAX_COUNT: usize = 7;
20 +/// Maximum length of one search term, in characters.
21 +pub const KEYWORD_MAX_LEN: usize = 30;
22 +/// Maximum number of words across all search terms.
23 +pub const KEYWORDS_MAX_WORDS: usize = 21;
24 +
25 +/// The listing keys this crate edits. Unset fields are left alone.
26 +#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
27 +#[serde(rename_all = "camelCase")]
28 +pub struct ListingFields {
29 + #[serde(skip_serializing_if = "Option::is_none")]
30 + pub title: Option<String>,
31 + #[serde(skip_serializing_if = "Option::is_none")]
32 + pub short_description: Option<String>,
33 + #[serde(skip_serializing_if = "Option::is_none")]
34 + pub description: Option<String>,
35 + #[serde(skip_serializing_if = "Option::is_none")]
36 + pub release_notes: Option<String>,
37 + #[serde(skip_serializing_if = "Option::is_none")]
38 + pub features: Option<Vec<String>>,
39 + #[serde(skip_serializing_if = "Option::is_none")]
40 + pub keywords: Option<Vec<String>>,
41 +}
42 +
43 +fn chars(s: &str) -> usize {
44 + s.chars().count()
45 +}
46 +
47 +impl ListingFields {
48 + pub fn is_empty(&self) -> bool {
49 + *self == Self::default()
50 + }
51 +
52 + /// Check the fields against the Store's limits. `Err` names the first
53 + /// violation; `Ok` carries warnings (non-ASCII punctuation) to show.
54 + pub fn validate(&self) -> std::result::Result<Vec<String>, String> {
55 + let texts = [
56 + ("title", &self.title, TITLE_MAX_LEN),
57 + (
58 + "shortDescription",
59 + &self.short_description,
60 + SHORT_DESCRIPTION_MAX_LEN,
61 + ),
62 + ("description", &self.description, DESCRIPTION_MAX_LEN),
63 + ("releaseNotes", &self.release_notes, RELEASE_NOTES_MAX_LEN),
64 + ];
65 + for (name, value, max) in texts {
66 + let len = value.as_deref().map_or(0, chars);
67 + if len > max {
68 + return Err(format!(
69 + "{name} is {len} characters; the Microsoft Store accepts at most {max}"
70 + ));
71 + }
72 + }
73 + if let Some(features) = &self.features {
74 + if features.len() > FEATURES_MAX_COUNT {
75 + return Err(format!(
76 + "features has {} entries; the Microsoft Store accepts at most {FEATURES_MAX_COUNT}",
77 + features.len()
78 + ));
79 + }
80 + if let Some((i, f)) = features
81 + .iter()
82 + .enumerate()
83 + .find(|(_, f)| chars(f) > FEATURE_MAX_LEN)
84 + {
85 + return Err(format!(
86 + "features[{i}] is {} characters; at most {FEATURE_MAX_LEN}",
87 + chars(f)
88 + ));
89 + }
90 + }
91 + if let Some(keywords) = &self.keywords {
92 + if keywords.len() > KEYWORDS_MAX_COUNT {
93 + return Err(format!(
94 + "keywords has {} entries; the Microsoft Store accepts at most {KEYWORDS_MAX_COUNT}",
95 + keywords.len()
96 + ));
97 + }
98 + if let Some((i, k)) = keywords
99 + .iter()
100 + .enumerate()
101 + .find(|(_, k)| chars(k) > KEYWORD_MAX_LEN)
102 + {
103 + return Err(format!(
104 + "keywords[{i}] is {} characters; at most {KEYWORD_MAX_LEN}",
105 + chars(k)
106 + ));
107 + }
108 + let words: usize = keywords.iter().map(|k| k.split_whitespace().count()).sum();
109 + if words > KEYWORDS_MAX_WORDS {
110 + return Err(format!(
111 + "keywords hold {words} words in total; at most {KEYWORDS_MAX_WORDS}"
112 + ));
113 + }
114 + }
115 + Ok(self.ascii_warnings())
116 + }
117 +
118 + /// Em dashes, en dashes and curly quotes, which the repo's listing note
119 + /// asks to keep out of store copy.
120 + fn ascii_warnings(&self) -> Vec<String> {
121 + let bad = |c: char| {
122 + matches!(
123 + c,
124 + '\u{2014}' | '\u{2013}' | '\u{2018}' | '\u{2019}' | '\u{201C}' | '\u{201D}'
125 + )
126 + };
127 + let mut out = Vec::new();
128 + let mut check = |name: String, text: &str| {
129 + if let Some(c) = text.chars().find(|c| bad(*c)) {
130 + out.push(format!(
131 + "{name} contains {c:?}; use plain ASCII punctuation"
132 + ));
133 + }
134 + };
135 + for (name, value) in [
136 + ("title", &self.title),
137 + ("shortDescription", &self.short_description),
138 + ("description", &self.description),
139 + ("releaseNotes", &self.release_notes),
140 + ] {
141 + if let Some(v) = value {
142 + check(name.to_string(), v);
143 + }
144 + }
145 + for (name, list) in [("features", &self.features), ("keywords", &self.keywords)] {
146 + for (i, v) in list.iter().flatten().enumerate() {
147 + check(format!("{name}[{i}]"), v);
148 + }
149 + }
150 + out
151 + }
152 +
153 + /// Read these fields from a submission's `baseListing` for `locale`.
154 + /// Fields the listing lacks come back `None`.
155 + pub fn read(submission: &Value, locale: &str) -> Self {
156 + let Some(base) = find_locale_key(submission, locale)
157 + .and_then(|key| submission.pointer(&format!("/listings/{}/baseListing", escape(&key))))
158 + else {
159 + return Self::default();
160 + };
161 + let text = |k: &str| base.get(k).and_then(Value::as_str).map(str::to_string);
162 + let list = |k: &str| {
163 + base.get(k).and_then(Value::as_array).map(|a| {
164 + a.iter()
165 + .filter_map(|v| v.as_str().map(str::to_string))
166 + .collect()
167 + })
168 + };
169 + Self {
170 + title: text("title"),
171 + short_description: text("shortDescription"),
172 + description: text("description"),
173 + release_notes: text("releaseNotes"),
174 + features: list("features"),
175 + keywords: list("keywords"),
176 + }
177 + }
178 +
179 + /// Replace only the set keys of `baseListing` for `locale`, creating the
180 + /// locale when the submission lacks it. Every other key is untouched.
181 + pub fn apply(&self, submission: &mut Value, locale: &str) -> Result<()> {
182 + let listings = submission
183 + .as_object_mut()
184 + .ok_or_else(|| Error::Shape("submission is not an object".into()))?
185 + .entry("listings")
186 + .or_insert_with(|| json!({}))
187 + .as_object_mut()
188 + .ok_or_else(|| Error::Shape("listings is not an object".into()))?;
189 + let key = listings
190 + .keys()
191 + .find(|k| k.eq_ignore_ascii_case(locale))
192 + .cloned()
193 + .unwrap_or_else(|| locale.to_ascii_lowercase());
194 + let entry = listings
195 + .entry(key)
196 + .or_insert_with(|| json!({}))
197 + .as_object_mut()
198 + .ok_or_else(|| Error::Shape("listing is not an object".into()))?;
199 + let base = entry
200 + .entry("baseListing")
201 + .or_insert_with(|| Value::Object(Map::new()))
202 + .as_object_mut()
203 + .ok_or_else(|| Error::Shape("baseListing is not an object".into()))?;
204 + let mut set = |k: &str, v: Value| {
205 + base.insert(k.to_string(), v);
206 + };
207 + if let Some(v) = &self.title {
208 + set("title", json!(v));
209 + }
210 + if let Some(v) = &self.short_description {
211 + set("shortDescription", json!(v));
212 + }
213 + if let Some(v) = &self.description {
214 + set("description", json!(v));
215 + }
216 + if let Some(v) = &self.release_notes {
217 + set("releaseNotes", json!(v));
218 + }
219 + if let Some(v) = &self.features {
220 + set("features", json!(v));
221 + }
222 + if let Some(v) = &self.keywords {
223 + set("keywords", json!(v));
224 + }
225 + Ok(())
226 + }
227 +
228 + /// Names of the fields set here whose stored value is not an exact match.
229 + pub fn diff(&self, stored: &Self) -> Vec<&'static str> {
230 + fn differs<T: PartialEq>(sent: &Option<T>, stored: &Option<T>) -> bool {
231 + sent.as_ref().is_some_and(|s| stored.as_ref() != Some(s))
232 + }
233 + [
234 + ("title", differs(&self.title, &stored.title)),
235 + (
236 + "shortDescription",
237 + differs(&self.short_description, &stored.short_description),
238 + ),
239 + (
240 + "description",
241 + differs(&self.description, &stored.description),
242 + ),
243 + (
244 + "releaseNotes",
245 + differs(&self.release_notes, &stored.release_notes),
246 + ),
247 + ("features", differs(&self.features, &stored.features)),
248 + ("keywords", differs(&self.keywords, &stored.keywords)),
249 + ]
250 + .into_iter()
251 + .filter(|(_, d)| *d)
252 + .map(|(n, _)| n)
253 + .collect()
254 + }
255 +}
256 +
257 +/// The key in `listings` matching `locale`, ignoring case (`en-us`/`en-US`).
258 +pub fn find_locale_key(submission: &Value, locale: &str) -> Option<String> {
259 + submission
260 + .get("listings")?
261 + .as_object()?
262 + .keys()
263 + .find(|k| k.eq_ignore_ascii_case(locale))
264 + .cloned()
265 +}
266 +
267 +/// Escape a JSON-pointer segment.
268 +fn escape(segment: &str) -> String {
269 + segment.replace('~', "~0").replace('/', "~1")
270 +}
271 +
272 +#[cfg(test)]
273 +mod tests {
274 + use super::*;
275 +
276 + fn text(len: usize) -> Option<String> {
277 + Some("x".repeat(len))
278 + }
279 +
280 + #[test]
281 + fn each_text_field_over_its_limit_is_rejected_by_name() {
282 + let cases = [
283 + (
284 + ListingFields {
285 + title: text(257),
286 + ..Default::default()
287 + },
288 + "title",
289 + ),
290 + (
291 + ListingFields {
292 + short_description: text(1001),
293 + ..Default::default()
294 + },
295 + "shortDescription",
296 + ),
297 + (
298 + ListingFields {
299 + description: text(10_001),
300 + ..Default::default()
301 + },
302 + "description",
303 + ),
304 + (
305 + ListingFields {
306 + release_notes: text(1501),
307 + ..Default::default()
308 + },
309 + "releaseNotes",
310 + ),
311 + ];
312 + for (fields, name) in cases {
313 + let message = fields.validate().unwrap_err();
314 + assert!(message.starts_with(name), "{message}");
315 + }
316 + }
317 +
318 + #[test]
319 + fn fields_at_their_limits_pass_and_lengths_count_characters() {
320 + let fields = ListingFields {
321 + title: Some("é".repeat(256)),
322 + short_description: text(1000),
323 + description: text(10_000),
324 + release_notes: text(1500),
325 + features: Some(vec!["x".repeat(200); 20]),
326 + keywords: Some(vec!["a b c".into(); 7]),
327 + };
328 + assert!(fields.validate().unwrap().is_empty());
329 + }
330 +
331 + #[test]
332 + fn list_limits_are_enforced() {
333 + let too_many = ListingFields {
334 + features: Some(vec!["f".into(); 21]),
335 + ..Default::default()
336 + };
337 + assert!(too_many
338 + .validate()
339 + .unwrap_err()
340 + .starts_with("features has 21"));
341 + let long = ListingFields {
342 + features: Some(vec!["x".repeat(201)]),
343 + ..Default::default()
344 + };
345 + assert!(long.validate().unwrap_err().starts_with("features[0]"));
346 + let terms = ListingFields {
347 + keywords: Some(vec!["k".into(); 8]),
348 + ..Default::default()
349 + };
350 + assert!(terms.validate().unwrap_err().starts_with("keywords has 8"));
351 + let wide = ListingFields {
352 + keywords: Some(vec!["x".repeat(31)]),
353 + ..Default::default()
354 + };
355 + assert!(wide.validate().unwrap_err().starts_with("keywords[0]"));
356 + let words = ListingFields {
357 + keywords: Some(vec!["a b c d".into(); 6]),
358 + ..Default::default()
359 + };
360 + assert!(words.validate().unwrap_err().contains("24 words"));
361 + }
362 +
363 + #[test]
364 + fn dashes_and_curly_quotes_warn_without_failing() {
365 + let fields = ListingFields {
366 + title: Some("A \u{2014} B".into()),
367 + features: Some(vec!["it\u{2019}s".into()]),
368 + ..Default::default()
369 + };
370 + let warnings = fields.validate().unwrap();
371 + assert_eq!(warnings.len(), 2);
372 + assert!(warnings[0].starts_with("title"));
373 + assert!(warnings[1].starts_with("features[0]"));
374 + }
375 +
376 + fn submission() -> Value {
377 + json!({
378 + "id": "1",
379 + "applicationPackages": [{"fileName": "a.msix", "version": "1.3.1.0"}],
380 + "pricing": {"trialPeriod": "NoFreeTrial"},
381 + "listings": {
382 + "en-us": {
383 + "baseListing": {
384 + "title": "Old",
385 + "description": "old desc",
386 + "images": [{"fileName": "s.png"}],
387 + "copyrightAndTrademarkInfo": "c"
388 + },
389 + "platformOverrides": {}
390 + },
391 + "id": {"baseListing": {"title": "Judul"}}
392 + }
393 + })
394 + }
395 +
396 + #[test]
397 + fn apply_replaces_only_the_set_keys_and_keeps_everything_else() {
398 + let mut sub = submission();
399 + let before = sub.clone();
400 + ListingFields {
401 + title: Some("New".into()),
402 + features: Some(vec!["a".into()]),
403 + ..Default::default()
404 + }
405 + .apply(&mut sub, "en-US")
406 + .unwrap();
407 + assert_eq!(sub["listings"]["en-us"]["baseListing"]["title"], "New");
408 + assert_eq!(
409 + sub["listings"]["en-us"]["baseListing"]["features"],
410 + json!(["a"])
411 + );
412 + // Everything not named is byte-identical.
413 + sub["listings"]["en-us"]["baseListing"]["title"] = json!("Old");
414 + sub["listings"]["en-us"]["baseListing"]
415 + .as_object_mut()
416 + .unwrap()
417 + .remove("features");
418 + assert_eq!(sub, before);
419 + }
420 +
421 + #[test]
422 + fn apply_creates_a_missing_locale_in_lowercase() {
423 + let mut sub = submission();
424 + ListingFields {
425 + title: Some("Hi".into()),
426 + ..Default::default()
427 + }
428 + .apply(&mut sub, "de-DE")
429 + .unwrap();
430 + assert_eq!(sub["listings"]["de-de"]["baseListing"]["title"], "Hi");
431 + }
432 +
433 + #[test]
434 + fn read_and_diff_round_trip() {
435 + let mut sub = submission();
436 + let sent = ListingFields {
437 + title: Some("New".into()),
438 + keywords: Some(vec!["git".into()]),
439 + ..Default::default()
440 + };
441 + sent.apply(&mut sub, "en-us").unwrap();
442 + let stored = ListingFields::read(&sub, "EN-US");
443 + assert!(sent.diff(&stored).is_empty());
444 + assert_eq!(stored.description.as_deref(), Some("old desc"));
445 + let other = ListingFields {
446 + title: Some("New ".into()),
447 + ..Default::default()
448 + };
449 + assert_eq!(other.diff(&stored), vec!["title"]);
450 + }
451 +}