diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 6837f98..66b06f7 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.4.0", + "version": "0.3.1", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8556d41..804182a 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "storebound", - "version": "0.4.0", - "description": "From nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products with regional prices, every questionnaire (Data safety, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", + "version": "0.3.1", + "description": "From nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products with regional prices, every questionnaire (Data safety, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, release management. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" }, diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index b94f7c6..431d54b 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "storebound", - "version": "0.4.0", - "description": "From nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products with regional prices, every questionnaire (Data safety, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", + "version": "0.3.1", + "description": "From nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products with regional prices, every questionnaire (Data safety, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, release management. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" }, diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 4e4bb6d..2fb58d1 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -7,11 +7,10 @@ alwaysApply: false These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal). -1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), - releasing a version, resuming or completing a rollout, canceling a submission, deleting products or listings, - accepting agreements, sending review replies, inviting or removing testers, changing prices, starting or stopping - a store experiment: explain what will happen and let the owner do it (or run the command only after a clear yes in - chat). storebound's MCP server does not offer these at all. +1. **The owner decides public and irreversible steps.** Submitting for review, releasing a version, resuming or + completing a rollout, canceling a submission, deleting products or listings, accepting agreements: explain what + will happen and let the owner do it (or run the command only after a clear yes in chat). storebound's MCP server + does not offer these at all. 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it for real only after the owner agrees. 3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you @@ -23,16 +22,13 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t 6. **Pick builds by explicit number.** Use the build number / versionCode you just uploaded, never "the latest". 7. **Long uploads run in the background with a log** (`storebound play images > .storebound/images.log 2>&1 &`) and you report the progress lines, not guesses. -8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no incentives for ratings, - no hidden features, no misleading screenshots, no keyword stuffing. -9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in - `.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits, - and never ask for tester emails in chat (storebound masks them in its output). +8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no hidden features, no + misleading screenshots, no keyword stuffing. ## Tools - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. -- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. +- MCP: `storebound mcp` (stdio). Write tools default to `dry_run: true`; submit / release / cancel / delete are not exposed. - Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills @@ -49,12 +45,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile games - `skills/release-management/SKILL.md`: Ship updates safely after the first release - `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game -- `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile game the safe way -- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git - `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile game -- `skills/store-health/SKILL.md`: Watch a released mobile game's crash and ANR health on both stores - `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list - `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages -- `skills/testflight/SKILL.md`: Run TestFlight for a mobile game through the App Store Connect API - `skills/whats-new/SKILL.md`: Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index beb173a..dbf4edb 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -7,11 +7,10 @@ Mobile game store releases (Google Play, App Store). Skills live in `skills/ .storebound/images.log 2>&1 &`) and you report the progress lines, not guesses. -8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no incentives for ratings, - no hidden features, no misleading screenshots, no keyword stuffing. -9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in - `.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits, - and never ask for tester emails in chat (storebound masks them in its output). +8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no hidden features, no + misleading screenshots, no keyword stuffing. ## Tools - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. -- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. +- MCP: `storebound mcp` (stdio). Write tools default to `dry_run: true`; submit / release / cancel / delete are not exposed. - Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills @@ -51,12 +47,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile games | | `release-management` | Ship updates safely after the first release | | `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game | -| `review-replies` | Reply to App Store and Google Play reviews of a mobile game the safe way | -| `store-analytics` | Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git | | `store-declarations` | Answer the store compliance forms for a mobile game | -| `store-health` | Watch a released mobile game's crash and ANR health on both stores | | `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list | | `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages | -| `testflight` | Run TestFlight for a mobile game through the App Store Connect API | | `whats-new` | Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag | diff --git a/AGENTS.md b/AGENTS.md index 355f688..cd0b267 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,11 +7,10 @@ file below and follow it step by step. These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal). -1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), - releasing a version, resuming or completing a rollout, canceling a submission, deleting products or listings, - accepting agreements, sending review replies, inviting or removing testers, changing prices, starting or stopping - a store experiment: explain what will happen and let the owner do it (or run the command only after a clear yes in - chat). storebound's MCP server does not offer these at all. +1. **The owner decides public and irreversible steps.** Submitting for review, releasing a version, resuming or + completing a rollout, canceling a submission, deleting products or listings, accepting agreements: explain what + will happen and let the owner do it (or run the command only after a clear yes in chat). storebound's MCP server + does not offer these at all. 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it for real only after the owner agrees. 3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you @@ -23,16 +22,13 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t 6. **Pick builds by explicit number.** Use the build number / versionCode you just uploaded, never "the latest". 7. **Long uploads run in the background with a log** (`storebound play images > .storebound/images.log 2>&1 &`) and you report the progress lines, not guesses. -8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no incentives for ratings, - no hidden features, no misleading screenshots, no keyword stuffing. -9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in - `.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits, - and never ask for tester emails in chat (storebound masks them in its output). +8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no hidden features, no + misleading screenshots, no keyword stuffing. ## Tools - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. -- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. +- MCP: `storebound mcp` (stdio). Write tools default to `dry_run: true`; submit / release / cancel / delete are not exposed. - Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills @@ -49,14 +45,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile games - `skills/release-management/SKILL.md`: Ship updates safely after the first release - `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game -- `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile game the safe way -- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git - `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile game -- `skills/store-health/SKILL.md`: Watch a released mobile game's crash and ANR health on both stores - `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list - `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages -- `skills/testflight/SKILL.md`: Run TestFlight for a mobile game through the App Store Connect API - `skills/whats-new/SKILL.md`: Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag ## Working on storebound itself diff --git a/CHANGELOG.md b/CHANGELOG.md index 135818f..279a440 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,49 +1,5 @@ # Changelog -## 0.4.0 · 2026-10-10 - -Wave 2: TestFlight and life after launch (stability, reviews, prices, analytics, experiments), plus MCP 2026-07-28. - -- **TestFlight through the API** (`apple testflight status | groups | testers | what-to-test | info | distribute`): - beta groups from `apple.testflight.groups` (internal / external, public links; created when missing, never changed - or deleted), testers from a CSV in `.storebound/` (the config refuses a path outside it; emails masked in every log - line; asks before Apple emails invitations; `--remove`, `--invite`), "What to Test" per locale from the App Store - listing (`### whatToTest`, else the `whats-new` notes), Test Information and Beta App Review contact / notes, a build - by its exact number to groups, Beta App Review submission behind `--submit-review` and a confirmation. Skill - `testflight`. -- **Crash and vitals health** (`health [--weekly]`): Play Developer Reporting API (user-perceived crash and ANR rates, - 28-day user-weighted, worst device models, top error issues) and App Store power and performance metrics, - diagnostic signatures and TestFlight crash reports. Play's bad behavior thresholds (1.09 % crash, 0.47 % ANR, 8 % per - device, developer.android.com/topic/performance/vitals): over = blocker, from 80 % = warn, also in `validate` - (`--no-health`). Weekly Markdown report with week-over-week change in `.storebound/health/`. Skill `store-health`. -- **Review replies** (`reviews list | draft | send`): App Store customer reviews / responses and Play reviews; drafts - as Markdown in `.storebound/replies/` (never overwritten), `send` only sends drafts with `approved: true` after a - confirmation and refuses incentives, rating requests and Play replies over 350 characters. Skill `review-replies`. -- **Price sheet** (`prices export | import`): one CSV of product x store x region; diff table first, then (after a - confirmation) one App Store price schedule per changed product (base territory, every manual price, future-dated - changes with `start_date`) and the Play purchase option's regional prices (`convertRegionPrices` for regions without - a price, `--reconvert`). `store-iap-setup` skill: price sheet section. -- **Analytics snapshots** (`analytics setup | snapshot | compare`): App Store Analytics Reports API (Discovery and - Engagement + Downloads, md5-checked segments, newest processing per day) and the Play statistics exports in the - `pubsite_prod_rev_` bucket (`play.reportsBucket`); snapshots in `.storebound/analytics/`, `compare` lines them up - with the git history of the store files. Skill `store-analytics`. -- **MCP 2026-07-28**: stateless requests with per-request `_meta` and `server/discover` (supported versions, - capabilities, instructions; `resultType`, server info in every result's `_meta`, cacheable `tools/list`, -32022 for - unsupported versions); `initialize` clients (2025-11-25 and older) keep working on the same process. -- **Product Page Optimization through the API** (`apple ppo status | create | upload | start | stop`): v2 tests with - one treatment per `shots` variant, a localization per locale and the variant renders in the treatment screenshot - sets; start / stop ask first. Play store listing experiments stay console-only (documented). -- **`iphone-medium` size key** (1206 x 2622, `APP_IPHONE_61`), off by default; `apple.iphoneMedium: true` renders, - checks and uploads it. Apple scales the 6.5" set down when it is missing. -- **MCP tools**: `apple_testflight_status`, `apple_testflight_groups`, `apple_testflight_what_to_test`, - `apple_testflight_info`, `apple_testflight_distribute` (internal groups only), `health`, `health_report`, - `reviews_list`, `reviews_draft`, `prices_diff`, `prices_export`, `analytics_snapshot`, `analytics_compare`, - `analytics_setup`, `apple_ppo_status`, `apple_ppo_create`, `apple_ppo_upload`. Not exposed: tester changes and - invitations, external distribution and Beta App Review, sending replies, applying prices, starting / stopping tests. -- Agent rules: owner-only steps now include review replies, tester invitations, price changes and experiments; personal - data (tester lists, reply drafts, health and analytics files) stays in `.storebound/`. -- `apple screenshots --dry` no longer creates empty screenshot sets. - ## 0.3.1 · 2026-10-10 Positioning: storebound is the whole road from zero to "Submit for review", screenshots are one step of it. diff --git a/GEMINI.md b/GEMINI.md index a6b2b81..fa776b2 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -6,11 +6,10 @@ This extension ships Agent Skills (skills/) and the storebound MCP server for mo These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal). -1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), - releasing a version, resuming or completing a rollout, canceling a submission, deleting products or listings, - accepting agreements, sending review replies, inviting or removing testers, changing prices, starting or stopping - a store experiment: explain what will happen and let the owner do it (or run the command only after a clear yes in - chat). storebound's MCP server does not offer these at all. +1. **The owner decides public and irreversible steps.** Submitting for review, releasing a version, resuming or + completing a rollout, canceling a submission, deleting products or listings, accepting agreements: explain what + will happen and let the owner do it (or run the command only after a clear yes in chat). storebound's MCP server + does not offer these at all. 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it for real only after the owner agrees. 3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you @@ -22,16 +21,13 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t 6. **Pick builds by explicit number.** Use the build number / versionCode you just uploaded, never "the latest". 7. **Long uploads run in the background with a log** (`storebound play images > .storebound/images.log 2>&1 &`) and you report the progress lines, not guesses. -8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no incentives for ratings, - no hidden features, no misleading screenshots, no keyword stuffing. -9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in - `.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits, - and never ask for tester emails in chat (storebound masks them in its output). +8. **No manipulative tactics** with reviewers, players or store policies: no fake reviews, no hidden features, no + misleading screenshots, no keyword stuffing. ## Tools - CLI: `storebound ` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`. -- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed. +- MCP: `storebound mcp` (stdio). Write tools default to `dry_run: true`; submit / release / cancel / delete are not exposed. - Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores). ## Skills @@ -50,12 +46,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile games | | `release-management` | Ship updates safely after the first release | | `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile game | -| `review-replies` | Reply to App Store and Google Play reviews of a mobile game the safe way | -| `store-analytics` | Take store analytics snapshots for a mobile game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git | | `store-declarations` | Answer the store compliance forms for a mobile game | -| `store-health` | Watch a released mobile game's crash and ANR health on both stores | | `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list | | `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages | -| `testflight` | Run TestFlight for a mobile game through the App Store Connect API | | `whats-new` | Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag | diff --git a/README.md b/README.md index a94b984..e0e1ae1 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,11 @@ **Website: [storebound.dev](https://storebound.dev)** [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) -[![version 0.4.0](https://img.shields.io/badge/version-0.4.0-informational)](CHANGELOG.md) +[![version 0.3.1](https://img.shields.io/badge/version-0.3.1-informational)](CHANGELOG.md) [![runtime: Bun](https://img.shields.io/badge/runtime-Bun%201.1%2B-f9f1e1)](https://bun.sh) [![runtime dependencies: 0](https://img.shields.io/badge/runtime%20dependencies-0-brightgreen)](package.json) -[![Agent Skills: 21](https://img.shields.io/badge/Agent%20Skills-21-8a63d2)](skills) -[![MCP: 2026-07-28](https://img.shields.io/badge/MCP-2026--07--28-black)](#mcp-server) +[![Agent Skills: 17](https://img.shields.io/badge/Agent%20Skills-17-8a63d2)](skills) +[![MCP: stdio](https://img.shields.io/badge/MCP-stdio-black)](#mcp-server) **Take a mobile game from nothing to "Submit for review" on Google Play and the App Store: app records, listings in every language, in-app products with regional prices, every questionnaire, privacy, icons, screenshots and previews, @@ -23,10 +23,6 @@ It is not a product: no dashboard, no account, no telemetry. A small Bun CLI tha Agent Skills that walk your AI coding tool (or you) through the parts that are still console clicks, and an MCP server so agents can call the CLI safely. **storebound never presses Submit, Release or Publish for you.** -It keeps going after launch: TestFlight groups and testers, crash and ANR vitals against the store thresholds, review -replies you approve before they go out, prices for many products and regions from one CSV, store analytics next to -your listing changes, and App Store product page tests from your screenshot variants. - ![The journey: config, app records, products, listings, questionnaires, privacy and icons, store art, validate, then you press Submit](https://git.crt.fyi/CRT/storebound/raw/branch/main/docs/img/journey.svg) ## The journey @@ -45,18 +41,17 @@ your own click. |---|---|---|---|---| | 1 | **Set up** | `init` (config, `store/*.md`, declarations and privacy templates), `install --agent `, `check` | Play: service account + API access invite; App Store: API team key (`play-first-release`, `appstore-first-release`) | developer accounts; Paid Applications agreement, banking and tax; Play payments profile | | 2 | **App records and bundle id** | `apple bundle` registers the bundle id, `apple status` finds the app record | App Store Connect > New App (no API); Play Console > Create app; the very first AAB upload when Play needs it from the Console | the declarations you accept when creating the Play app | -| 3 | **Builds and testers** | `play next-version-code`, `play release app.aab` (internal track), `apple next-build`, `xcodebuild` archive + upload with the API key (the skill has the commands), `apple encryption`, `apple testflight groups / what-to-test / info / distribute` (internal groups) | Play internal testers list, Apple sandbox testers (`play-first-release`, `testflight`) | `apple testflight testers` (Apple emails the invitations), external groups and Beta App Review (`distribute --submit-review`) | +| 3 | **Builds** | `play next-version-code`, `play release app.aab` (internal track), `apple next-build`, `xcodebuild` archive + upload with the API key (the skill has the commands), `apple encryption` | TestFlight internal group, internal testers (`appstore-first-release`, `play-first-release`) | | | 4 | **In-app products** | `play products` (regional prices from USD + your overrides, activated), `apple iap` (localizations, price schedule, availability), `apple iap-review` (review screenshots) | Play license testers, Apple sandbox testers, "Add for Review" of the first IAPs into the version's submission (`store-iap-setup`) | | | 5 | **Store listings, every language** | `play listing` (title, short / full description, contact email + website, promo video URL), `apple listing --version x --build N` (name, subtitle, description, keywords, promo text, URLs, privacy URL, manual release), `whats-new`, `check` (limits), `check --aso` | Play store settings: category and tags (`play-first-release`) | | | 6 | **Play questionnaires** | `play data-safety`: the whole Data safety form from `dataSafety` in the config (CSV import through the API) | Policy and programs > App content, answers prepared in `store/declarations.md` (`store-declarations`): privacy policy, app access / sign-in details, ads, content rating (IARC), target audience and content, advertising ID, news, government, financial and health features; Data safety summary check | the answers themselves are your statements: the agent asks when the code does not prove them | | 7 | **App Store questionnaires** | `apple appinfo` (categories, age rating declaration, content rights, Free price, availability), `apple encryption` (export compliance from `apple.usesNonExemptEncryption`, never guessed), `apple review-details` (contact + notes) | App Privacy nutrition labels from `store/app-privacy.md`, then **Publish** (`store-declarations`); encryption documentation when the answer is yes (`export-compliance`); the first availability record if the API refuses it | the export compliance answer (a legal statement, set once in the config) | | 8 | **Privacy** | privacy policy page template (`init`), `privacy-manifest --ios ` (PrivacyInfo.xcprivacy, required-reason APIs, SDK manifests), `validate` checks the policy URL answers | host the page, link it in both consoles and inside the game (`privacy-policy`, `privacy-manifest`) | | | 9 | **Icons** | `icons`: App Store 1024 without alpha, Play 512, adaptive + legacy Android launcher icons, web icons, Capacitor sources | | | -| 10 | **Screenshots and previews** | `shots capture / render / check / gallery`, `play images`, `apple screenshots`, `shots record / video`, `apple previews`, `apple ppo create / upload` (App Store product page tests from `shots` variants; see [Store art](#store-art)) | Play store listing experiments (optional, `store-screenshots`) | uploading the promo video to YouTube; `apple ppo start / stop` | +| 10 | **Screenshots and previews** | `shots capture / render / check / gallery`, `play images`, `apple screenshots`, `shots record / video`, `apple previews` (see [Store art](#store-art)) | Play store listing experiments, App Store Product Page Optimization (optional, `store-screenshots`) | uploading the promo video to YouTube | | 11 | **Validate** | `check` (offline) and `validate` (read-only on both stores: every blocker in fix order, plus the local renders) | the UI-only items `validate` cannot see (`store-preflight` lists them) | | | 12 | **Submit** | `play release --version-code N --production draft`, `apple status` | Play: countries / regions, open the production draft and save it (`play-first-release`) | **Play: Send changes for review. App Store: Submit for Review.** | | 13 | **After review** | `apple status --wait-review`, `apple release --phased on / pause`, `play rollout --halt`, reply drafts (`review-rejections`) | | releasing the approved version, resuming or completing a phased release or rollout (terminal commands that ask first, `release-management`) | -| 14 | **Live game** | `health [--weekly]` (crash / ANR vitals vs Play's thresholds, App Store diagnostics; also in `validate`), `reviews list / draft`, `analytics snapshot / compare`, `prices export`, `prices import --dry`, `apple ppo status` | `store-health`, `review-replies`, `store-analytics`; Play statistics come from the reports bucket (no API) | `reviews send` (approved drafts only), `prices import` (asks first) | New personal Play developer accounts also need a closed test with 12+ testers for 14 days before production; the `play-first-release` skill covers it. @@ -64,19 +59,15 @@ New personal Play developer accounts also need a closed test with 12+ testers fo ### API or console, honestly - **Through the API** (storebound does it): bundle id, builds on tracks, versions and build selection, listings in - every language, graphics, screenshots, app previews, in-app products and prices (also from one CSV), Play Data - safety, Apple age rating, categories, content rights, price and availability, export compliance answer, App Review - details, phased release and staged rollout, TestFlight groups / testers / What to Test / Test Information, crash and - ANR vitals and App Store diagnostics, review replies, App Store analytics reports, App Store Product Page - Optimization tests. + every language, graphics, screenshots, app previews, in-app products and prices, Play Data safety, Apple age rating, + categories, content rights, price and availability, export compliance answer, App Review details, phased release + and staged rollout. - **Console only** (no public API; the skill + your agent's browser, or you): creating the App Store Connect app record and the Play app, Play App content (IARC content rating, target audience, ads, advertising ID, app access, government / financial / health / news), Play category and tags, Play countries, App Privacy labels and their - Publish, adding first IAPs to the submission, Play store listing experiments, test results of both stores' experiments. - Play store statistics have no API either: storebound reads the monthly exports from your Play reports bucket. + Publish, TestFlight groups, adding first IAPs to the submission, store experiments. - **Only you**: agreements, banking and tax, and the final Send for review / Submit for Review. Releases and - rollouts after approval, Beta App Review, tester invitations, sending review replies, applying price changes and - starting / stopping a product page test too. None of these is an MCP tool; the terminal commands ask first. + rollouts after approval too. None of these is an MCP tool. ## 5-minute quick start @@ -103,20 +94,9 @@ bunx storebound shots capture && bunx storebound shots render && bunx storebound bunx storebound validate # read-only: what still blocks a submission, per store, in fix order ``` -After launch: - -```sh -bunx storebound apple testflight what-to-test --build 42 --dry # then distribute --build 42 --group Team -bunx storebound health --weekly # vitals + diagnostics, .storebound/health/.md -bunx storebound reviews draft # reply drafts in .storebound/replies/, then reviews send -bunx storebound prices export && bunx storebound prices import --dry -bunx storebound analytics snapshot && bunx storebound analytics compare -``` - Or ask your agent: "take my game to Google Play and the App Store", "fill in the store questionnaires", "set up the in-app purchases on both stores", "make store screenshots in 5 languages", "is my app ready to submit", "why was my -update rejected", "put build 42 on TestFlight", "how are our crash rates", "answer the new reviews", "did the new -screenshots help". The matching skill takes over. +update rejected". The matching skill takes over. ### Credentials (never in the repo) @@ -194,7 +174,7 @@ run in the background with a log (`storebound shots render > .storebound/render. |---|---|---| | `apple bundle` | API | register the bundle id, find the app record | | `apple listing --version x.y.z [--build N]` | API | version (manual release), the build with exactly that number, texts per locale | -| `apple screenshots [--variant b]` | API | 6.9" + 6.5" (+ 13" iPad with `apple.ipad`, + 6.3" with `apple.iphoneMedium`) per locale, MD5-idempotent | +| `apple screenshots [--variant b]` | API | 6.9" + 6.5" (+ 13" iPad with `apple.ipad`) per locale, MD5-idempotent | | `apple previews [--poster 5]` | API | app preview videos per locale, checked first, MD5-idempotent, poster frame | | `apple iap` / `apple iap-review` | API | IAPs, localizations, price schedules, availability / review screenshots | | `apple appinfo` | API | categories, age rating, content rights, Free, territories | @@ -203,39 +183,6 @@ run in the background with a log (`storebound shots render > .storebound/render. | `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) | | `apple next-build` | API, read-only | next safe build number | | `apple status` | API | versions, builds, IAPs, submissions; `--wait-review` (exit 0 / 1 / 7); `--cancel-submission ` | -| `apple ppo status \| create --variant b \| upload --variant b` | API | Product Page Optimization test from `shots` variants: treatments, localizations, screenshot sets | -| `apple ppo start \| stop` | API | start / stop the test (asks first; a stopped test cannot be restarted) | - - - -
-TestFlight - -| command | kind | what | -|---|---|---| -| `apple testflight status` | API, read-only | groups, testers and builds per group, recent builds with internal / external beta states | -| `apple testflight groups` | API | create the groups of `apple.testflight.groups` that are missing | -| `apple testflight testers [--csv f] [--remove] [--invite]` | API | testers from a CSV in `.storebound/` into their groups (asks first; emails masked) | -| `apple testflight what-to-test --build N` | API | "What to Test" per locale from `store/appstore.md` (`whatToTest`, else `whatsNew`) | -| `apple testflight info` | API | Beta App Description, feedback email, URLs, Beta App Review contact and notes | -| `apple testflight distribute --build N --group a,b [--submit-review]` | API | the build to groups; external groups and Beta App Review ask first | - -
- -
-After launch - -| command | kind | what | -|---|---|---| -| `health [--weekly] [--days 7]` | API, read-only | Play vitals (user-perceived crash / ANR vs 1.09 % / 0.47 %, devices, top issues), App Store metrics, diagnostics, TestFlight crashes; `--weekly` writes a Markdown report | -| `reviews list [--unanswered]` | API, read-only | recent reviews of both stores | -| `reviews draft` | API + local | one reply draft per unanswered review in `.storebound/replies/` | -| `reviews send` | API | sends drafts with `approved: true` (checks length and incentives, asks first) | -| `prices export` | API + local | current prices of every product, both stores, as `store/prices.csv` | -| `prices import [--reconvert]` | API | diff table, then (asks first) Apple price schedules incl. future-dated changes and Play regional prices | -| `analytics setup` | API | App Store analytics report request (once, Admin key) | -| `analytics snapshot [--days 28]` | API + local | impressions, page views, downloads (App Store), visitors, acquisitions, installs (Play reports bucket) -> `.storebound/analytics/` | -| `analytics compare` | local | snapshots vs the git history of the store files: before / after each listing change |
@@ -309,21 +256,17 @@ navigation. |---|---| | `play-first-release` | Google Play from zero to "In review" | | `appstore-first-release` | App Store from API key to "Waiting for review", incl. xcodebuild with the API key | -| `testflight` | beta groups, testers from a CSV that never enters git, What to Test, Test Information, Beta App Review | -| `store-iap-setup` | in-app products on both stores, prices and the price sheet CSV, testers, the first-IAP-with-version rule | +| `store-iap-setup` | in-app products on both stores, prices, testers, the first-IAP-with-version rule | | `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing | | `store-declarations` | every questionnaire: Play Data safety (API) and App content (IARC, target audience, ads, advertising ID, app access, government / financial / health), Apple App Privacy labels and age rating | | `export-compliance` | encryption answer, Info.plist key, declarations; never exempt by default | | `privacy-policy` | one studio-wide policy page with a per-game services table | | `privacy-manifest` | PrivacyInfo.xcprivacy, required-reason APIs, SDK manifests (ITMS-91053 / 91061) | | `app-icons` | one artwork to every icon, adaptive / legacy launcher pitfalls | -| `store-screenshots` | capture from any engine, copy, fonts, render, checks, gallery, variants, App Store product page tests, Play experiments, upload | +| `store-screenshots` | capture from any engine, copy, fonts, render, checks, gallery, variants and store experiments, upload | | `app-previews` | gameplay clips, App Store previews, Play promo video, checks, upload | | `store-preflight` | run and read `check`, `check --aso`, `validate`, `privacy-manifest` before submitting | | `release-management` | updates: Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait | -| `store-health` | crash / ANR vitals vs Play's bad behavior thresholds, App Store diagnostics, weekly report | -| `review-replies` | reply drafts, tone, no incentives, store limits, the owner approves and sends | -| `store-analytics` | App Store analytics reports, Play reports bucket, before / after listing changes | | `whats-new` | player-facing release notes from git, localized, within store limits | | `review-rejections` | triage a rejection (fix / clarify / push back / appeal), reply template, the guidelines games hit | | `ads-levelplay-checks` | LevelPlay / Unity Ads ids, adapters, app-ads.txt, SKAdNetwork, no-fill | @@ -331,23 +274,18 @@ navigation. ## MCP server -`storebound mcp` speaks MCP over stdio, tools only: spec revision **2026-07-28** (stateless: `server/discover`, -per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same process, clients that still open with -`initialize` (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). It runs each tool as a CLI call in the project directory -(the server's working directory, or `STOREBOUND_PROJECT`) and returns the output. +`storebound mcp` speaks MCP over stdio (spec revision 2025-11-25; tools only). It runs each tool as a CLI call in the +project directory (the server's working directory, or `STOREBOUND_PROJECT`) and returns the output. -- One tool per command. Read-only: `check`, `check_aso`, `validate`, `health`, `reviews_list`, `prices_diff`, - `analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`, +- One tool per command. Read-only: `check`, `check_aso`, `validate`, `apple_status`, `apple_next_build`, `play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`. Local writes: `whats_new`, `icons`, - `health_report`, `reviews_draft`, `prices_export`, `analytics_snapshot`, `shots_capture`, `shots_render`, - `shots_gallery`, `shots_record`, `shots_video`. Store writes: `play_listing`, `play_images`, `play_products`, - `play_data_safety`, `play_release_testing`, `apple_bundle`, `apple_iap`, `apple_iap_review`, `apple_listing`, - `apple_screenshots`, `apple_previews`, `apple_appinfo`, `apple_review_details`, `apple_encryption`, - `apple_phased_release`, `apple_testflight_groups`, `apple_testflight_what_to_test`, `apple_testflight_info`, - `apple_testflight_distribute` (internal groups only), `apple_ppo_create`, `apple_ppo_upload`, `analytics_setup`. + `shots_capture`, `shots_render`, `shots_gallery`, `shots_record`, `shots_video`. Store writes: `play_listing`, + `play_images`, `play_products`, `play_data_safety`, `play_release_testing`, `apple_bundle`, `apple_iap`, + `apple_iap_review`, `apple_listing`, `apple_screenshots`, `apple_previews`, `apple_appinfo`, + `apple_review_details`, `apple_encryption`, `apple_phased_release`. - Annotations say what is read-only, destructive (replaces data), idempotent and network-bound. -- No MCP SDK: a small newline-delimited JSON-RPC server (server/discover, initialize, ping, tools/list, tools/call, - cancellation), so storebound keeps zero runtime dependencies. +- No MCP SDK: about 150 lines of newline-delimited JSON-RPC (initialize, ping, tools/list, tools/call, cancellation), + so storebound keeps zero runtime dependencies. Manual config for a tool that `install` does not know: command `bunx` with args `["storebound", "mcp"]` (or the absolute path of `bin/storebound` plus `mcp`). @@ -355,17 +293,12 @@ absolute path of `bin/storebound` plus `mcp`). ## Safety model - **Credentials** live in env vars or the gitignored `.storebound/credentials.json`, never in the config or the repo. - storebound only talks to the official store APIs (plus Google Fonts, your own Play reports bucket and your own URLs); - see [SECURITY.md](SECURITY.md). + storebound only talks to the official store APIs (plus Google Fonts and your own URLs); see [SECURITY.md](SECURITY.md). - **Dry run everywhere.** Every write command takes `--dry`; every MCP write tool has `dry_run`, **default true**. -- **Nothing public or irreversible through an agent.** Submitting for review (App Review and Beta App Review), - releasing a version, production releases, resuming or completing a rollout or phased release, canceling a - submission, deleting, inviting or removing testers, sending review replies, applying prices and starting or - stopping a product page test are not MCP tools. They stay terminal commands that ask for confirmation, and the skills tell every agent to ask the owner +- **Nothing public or irreversible through an agent.** Submitting for review, releasing a version, production + releases, resuming or completing a rollout or phased release, canceling a submission and deleting are not MCP + tools. They stay terminal commands that ask for confirmation, and the skills tell every agent to ask the owner first ([docs/agents-core.md](docs/agents-core.md)). -- **Personal data stays local.** Tester lists, reply drafts, health reports and analytics snapshots live in the - gitignored `.storebound/`; tester emails are masked in every log line, and the config refuses a tester CSV path - outside `.storebound/`. - **Idempotent writes.** Re-running a command converges (MD5 checks for screenshots and previews, one Play edit per language), so a failed upload is fixed by running it again. - **Simulators and emulators**: storebound shuts down only a simulator it booted itself and never boots, wipes or @@ -402,25 +335,21 @@ zero runtime dependencies. It needs Bun installed (it does not run on plain Node **Does it upload my video to YouTube?** No. Play only takes a YouTube URL, and uploading to YouTube needs your Google account; `shots video` makes the file, you upload it and paste the URL into `play.video`. -**Can it run store experiments for me?** On the App Store, mostly: `apple ppo create / upload` builds a Product Page -Optimization test from your `shots` variants (treatments, locales, screenshots) and you start it (`apple ppo start` -asks first). Results per treatment are only shown in App Store Connect. Play store listing experiments have no API: -storebound renders and checks the variant images, you set the experiment up in Play Console. - -**Does it answer reviews by itself?** No. It drafts one file per review, your agent helps write the replies, and only -the drafts you mark `approved: true` are sent, by you, after a confirmation. Replies that offer something for a rating -are refused. +**Can it run store experiments for me?** Not yet. It renders and checks the variant images; Play store listing +experiments are Console-only, and App Store Product Page Optimization tests are set up in App Store Connect. ## Roadmap -Wave 2 (TestFlight, vitals, review replies, price sheets, analytics, MCP 2026-07-28, Product Page Optimization) shipped -in 0.4.0. Next, roughly in this order: +Wave 2, roughly in this order: -- Subscriptions (groups, levels, introductory offers) on both stores from the same product list. -- App Store custom product pages and in-app events from the same copy and renders. -- Play store listing experiments and their results, as soon as Google offers an API. -- App preview treatments and alternate icons in Product Page Optimization tests. -- The iPhone Duo screenshot classes Apple lists for apps built with the iOS 27.1 SDK (required from April 2027). +- TestFlight through the API: beta groups, testers, build distribution, "What to Test". +- Crash and vitals reports: Play Android vitals, App Store Connect diagnostics, in `validate` and a weekly summary. +- Review replies on both stores, drafted by the agent, sent only after you approve. +- Prices from a CSV for many products and regions at once. +- Store analytics snapshots (installs, conversion) next to the listing changes and experiments. +- MCP 2026-07-28 (stateless revision: `server/discover`, per-request `_meta`). +- Product Page Optimization through the App Store Connect API, and a medium iPhone size key if Apple starts to + require it strictly. ## Contributing @@ -443,16 +372,7 @@ Checked against each tool's own docs in October 2026: `install --agent gemini` is not verified (the extension route is). - **Windsurf**: the current docs name `~/.config/devin/mcp_config.json`; `install` keeps using `~/.codeium/windsurf/mcp_config.json` when that file already exists (older installs). -- **MCP**: built for 2026-07-28 (final, modelcontextprotocol.io) and dual-era: `initialize` clients get 2025-11-25 - (or 2025-06-18 / 2025-03-26 / 2024-11-05). Tested with both handshakes on one stdio process, not yet against every - client listed above. -- **Not verified against a live account yet** (no credentials during development; request builders are tested with - fixtures from the official docs): the scale of the Play Reporting API rates (read as fractions, 0.0109 = 1.09 %), - the App Store review reply limit (5970 characters is commonly reported; Apple documents none, storebound only - warns), the TestFlight "What to Test" limit (4000 assumed), whether an analytics segment checksum covers the gzip - file or its content (both are accepted), that a new App Store price schedule replaces the old one (Apple's example - implies it), stopping a Product Page Optimization test with `started: false`, and `APP_IPHONE_61` for the 6.3" - iPhone set. +- **MCP**: built for 2025-11-25 (also answers clients asking for 2025-06-18 / 2025-03-26 / 2024-11-05). - **Apple IAP description**: 45 characters (App Store Connect Help, "In-app purchase information"); an older App Store marketing page says 55. storebound checks 45. @@ -482,8 +402,7 @@ Some skills were sparked by other people's open work. I wrote my own text; the i - [rshankras/claude-code-apple-skills](https://github.com/rshankras/claude-code-apple-skills) (MIT): Apple platform and App Store topic ideas. -Built with Bun and plain `fetch` against the Google Play Developer API v3, the Play Developer Reporting API and the App -Store Connect API. Screenshot +Built with Bun and plain `fetch` against the Google Play Developer API v3 and the App Store Connect API. Screenshot fonts come from Google Fonts at render time (Noto, Lilita One, Montserrat; SIL Open Font License 1.1). Not affiliated with Google or Apple. diff --git a/SECURITY.md b/SECURITY.md index 5c6ff27..fb85011 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,15 +14,10 @@ published. - Credentials come only from environment variables or `.storebound/credentials.json` in your project; `init` adds `.storebound/` to `.gitignore`. storebound does not print them or copy them anywhere. - The CLI talks to the official store endpoints (`androidpublisher.googleapis.com` and `www.googleapis.com` uploads, - `oauth2.googleapis.com`, `playdeveloperreporting.googleapis.com` for vitals, `storage.googleapis.com` for your own - Play reports bucket, `api.appstoreconnect.apple.com` and the upload / analytics download URLs it hands out), Google - Fonts for `shots fonts`, your own game URL for capture / record, and your own website when `validate` checks the - privacy policy URL and `app-ads.txt`. -- The MCP server exposes no tool that submits for review (App Review or Beta App Review), releases, resumes or - completes a rollout, cancels a submission, deletes anything, invites or removes testers, sends review replies, - applies prices or starts / stops a store experiment; every write tool is a dry run unless `dry_run: false` is passed. -- Personal data the CLI handles (tester emails, reviewer names in reply drafts, crash reports, analytics) stays in - the gitignored `.storebound/`; tester emails are masked in its output. + `oauth2.googleapis.com`, `api.appstoreconnect.apple.com` and the upload URLs it hands out), Google Fonts for + `shots fonts`, your own game URL for capture / record, and your own website when `validate` checks the privacy policy URL and `app-ads.txt`. +- The MCP server exposes no tool that submits for review, releases, resumes or completes a rollout, cancels a + submission or deletes anything; every write tool is a dry run unless `dry_run: false` is passed. - `bun run ci` scrubs the repository for keys, issuer ids, emails and private names before every release. ## Supported versions diff --git a/cli/analytics.ts b/cli/analytics.ts deleted file mode 100644 index 2df81f7..0000000 --- a/cli/analytics.ts +++ /dev/null @@ -1,153 +0,0 @@ -// Store analytics snapshots next to the listing changes. -// storebound analytics setup [--dry] App Store: create the ONGOING analytics report request (Admin key; once) -// storebound analytics snapshot [--days 28] [--store apple|play] [--dry] -> .storebound/analytics/.json -// storebound analytics compare [--days 7] [--paths store,storebound.config.ts] [--md] -// App Store: Analytics Reports API (Discovery and Engagement: impressions, product page views; Downloads: first-time -// downloads and redownloads), every segment checked against its md5 checksum. Google Play has no statistics API: -// the monthly CSV exports in your Cloud Storage bucket (play.reportsBucket = "pubsite_prod_rev_", Play Console > -// Download reports > Statistics > Copy Cloud Storage URI) are read with the service account (store listing visitors, -// acquisitions, daily user installs). compare lines the snapshots up with the git history of the store files (listing -// text, screenshots, config): the days before vs after each change. Read-only on both stores except `setup`. -import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { ascClient, type Asc, type J } from './apple/asc'; -import type { Ctx } from './lib/ctx'; -import { - type AppleDay, APPLE_REPORTS, appleDaily, appleTotals, bucketName, checksumOk, compareAroundEvents, decodeText, effectMarkdown, effectTable, inWindow, - latestPerDate, mergeSeries, monthsBetween, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot, -} from './lib/analytics'; -import { STORAGE_READ_SCOPE } from './lib/google-auth'; -import { done, log, warn } from './lib/log'; -import { pct, textTable } from './lib/table'; -import { googleClient } from './play/google'; - -const TAG = 'analytics'; -const day = (d: Date) => d.toISOString().slice(0, 10); - -async function ongoingRequest(c: Asc, appId: string): Promise { - const reqs = await c.all(`/v1/apps/${appId}/analyticsReportRequests?filter[accessType]=ONGOING&limit=50`); - return reqs.find(r => !r.attributes?.stoppedDueToInactivity) ?? null; -} - -async function reportRows(c: Asc, report: J, start: string, tag: string): Promise[]> { - const instances = (await c.all(`/v1/analyticsReports/${report.id}/instances?filter[granularity]=DAILY&limit=200`)) - .filter(i => (i.attributes?.processingDate ?? '') >= start).sort((a, b) => a.attributes.processingDate.localeCompare(b.attributes.processingDate)); - log(TAG, `apple: ${tag}: ${instances.length} daily instance(s) since ${start}`); - const parts: { processingDate: string; rows: Record[] }[] = []; - for (const inst of instances) { - const rows: Record[] = []; - for (const seg of await c.all(`/v1/analyticsReportInstances/${inst.id}/segments?limit=200`)) { - // Segment URLs are pre-signed (valid 5 minutes): fetched without the API token. - const r = await fetch(seg.attributes.url); - if (!r.ok) throw new Error(`segment ${seg.id}: HTTP ${r.status}`); - const gz = new Uint8Array(await r.arrayBuffer()); - const raw = gz[0] === 0x1f && gz[1] === 0x8b ? Bun.gunzipSync(gz) : gz; - // Apple documents an md5 checksum per segment without saying of which bytes: accept the file or its content. - if (seg.attributes.checksum && !checksumOk(gz, seg.attributes.checksum) && !checksumOk(raw, seg.attributes.checksum)) throw new Error(`segment ${seg.id}: md5 checksum mismatch`); - rows.push(...parseReport(decodeText(raw))); - } - parts.push({ processingDate: inst.attributes.processingDate, rows }); - } - return latestPerDate(parts); -} - -async function appleSnapshot(ctx: Ctx, start: string, end: string): Promise<{ daily: AppleDay[] }> { - const { config, root } = ctx.loaded; - const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId); - const appId = await c.app(); - const req = await ongoingRequest(c, appId); - if (!req) throw new Error('no active ONGOING analytics report request: run storebound analytics setup (Admin key), data starts 1-2 days later'); - const reports = await c.all(`/v1/analyticsReportRequests/${req.id}/reports?limit=200`); - const eng = pickReport(reports.filter(r => r.attributes?.category === APPLE_REPORTS.engagement.category), APPLE_REPORTS.engagement.match); - const dl = pickReport(reports.filter(r => r.attributes?.category === APPLE_REPORTS.downloads.category), APPLE_REPORTS.downloads.match); - if (!eng || !dl) throw new Error(`reports not found yet (${reports.length} listed): wait a day after setup`); - const daily = appleDaily(await reportRows(c, eng, start, eng.attributes.name), await reportRows(c, dl, start, dl.attributes.name)); - return { daily: inWindow(daily, start, end) }; -} - -async function playSnapshot(ctx: Ctx, start: string, end: string): Promise<{ daily: PlayDay[] }> { - const { config, root } = ctx.loaded; - const bucket = config.play?.reportsBucket; - if (!bucket) throw new Error('play.reportsBucket is not set (Play Console > Download reports > Statistics > Copy Cloud Storage URI)'); - const g = googleClient(root, STORAGE_READ_SCOPE); - const sp: Record[] = [], inst: Record[] = []; - for (const month of monthsBetween(start, end)) { - const o = playObjects(config.play!.packageName, month); - for (const [name, into] of [[o.storePerformance, sp], [o.installs, inst]] as const) { - const url = `https://storage.googleapis.com/storage/v1/b/${encodeURIComponent(bucketName(bucket))}/o/${encodeURIComponent(name)}?alt=media`; - try { into.push(...parseReport(decodeText(await g.bytes(url)))); log(TAG, `play: ${name}`); } - catch (e) { if (/-> 404/.test(String(e))) warn(TAG, `play: ${name} not there (yet)`); else throw e; } - } - } - return { daily: inWindow(playDaily(sp, inst), start, end) }; -} - -function readSnapshots(dir: string): Snapshot[] { - if (!existsSync(dir)) return []; - return readdirSync(dir).filter(n => /^\d{4}-\d{2}-\d{2}\.json$/.test(n)).sort().map(n => JSON.parse(readFileSync(join(dir, n), 'utf8')) as Snapshot); -} - -export async function run(ctx: Ctx): Promise { - const { config, root, resolve } = ctx.loaded; - const a = ctx.args; - const sub = a._[0]; - const dir = resolve(a.get('dir') ?? '.storebound/analytics'); - const dry = a.has('dry'); - - if (sub === 'setup') { - if (!config.apple) throw new Error('no apple section in the config (Google Play needs no setup: set play.reportsBucket)'); - const c = await ascClient(root, config.apple.bundleId, config.apple.appId); - const appId = await c.app(); - const cur = await ongoingRequest(c, appId); - if (cur) { done(TAG, `apple: ONGOING report request exists (${cur.id})`); return; } - const body = { data: { type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, relationships: { app: { data: { type: 'apps', id: appId } } } } }; - if (dry) { log(TAG, 'would POST /v1/analyticsReportRequests {accessType=ONGOING} (dry)'); return; } - await c.asc('POST', '/v1/analyticsReportRequests', body); - done(TAG, 'apple: ONGOING report request created; the first reports appear after 1-2 days, then daily'); - return; - } - - if (sub === 'snapshot') { - const days = a.num('days', 28); - if (!(days >= 1 && days <= 120)) throw new Error('--days: 1-120'); - const store = a.get('store'); - const now = new Date(); - const end = day(new Date(now.getTime() - 86_400_000)), start = day(new Date(now.getTime() - days * 86_400_000)); - const snap: Snapshot = { date: day(now), window: { start, end, days } }; - if ((!store || store === 'apple') && config.apple) { - try { const r = await appleSnapshot(ctx, start, end); snap.apple = { daily: r.daily, totals: appleTotals(r.daily) }; } - catch (e) { snap.apple = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `apple: ${snap.apple.error}`); } - } - if ((!store || store === 'play') && config.play) { - try { const r = await playSnapshot(ctx, start, end); snap.play = { daily: r.daily, totals: playTotals(r.daily) }; } - catch (e) { snap.play = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `play: ${snap.play.error}`); } - } - const rows: (string | number)[][] = []; - if (snap.apple && !('error' in snap.apple)) { const t = snap.apple.totals; rows.push(['apple', `${t.impressions} impressions`, `${t.pageViews} page views`, `${t.downloads} downloads`, pct(t.conversion ?? null)]); } - if (snap.play && !('error' in snap.play)) { const t = snap.play.totals; rows.push(['play', `${t.visitors} visitors`, `${t.acquisitions} acquisitions`, `${t.installs} installs`, pct(t.conversion ?? null)]); } - if (rows.length) console.log(textTable(['store', 'reach', 'interest', 'installs', 'conversion'], rows)); - const file = join(dir, `${snap.date}.json`); - if (dry) { done(TAG, `dry run: would write ${file} (${start} to ${end})`); return; } - mkdirSync(dir, { recursive: true }); - writeFileSync(file, JSON.stringify(snap, null, 2) + '\n'); - done(TAG, `snapshot ${file} (${start} to ${end})`); - return; - } - - if (sub === 'compare') { - const snaps = readSnapshots(dir); - if (!snaps.length) throw new Error(`no snapshots in ${dir} (storebound analytics snapshot)`); - const series = mergeSeries(snaps); - const first = [series.apple[0]?.date, series.play[0]?.date].filter(Boolean).sort()[0] ?? snaps[0]!.window.start; - const paths = a.list('paths').length ? a.list('paths') : ['store', 'storebound.config.ts', ...(config.shots?.copy ? [config.shots.copy] : [])]; - const g = Bun.spawnSync(['git', 'log', `--since=${first}`, '--date=short', '--format=%x1e%h%x1f%ad%x1f%s', '--name-only', '--', ...paths], { cwd: root, stdout: 'pipe', stderr: 'pipe' }); - if (g.exitCode !== 0) throw new Error(`git log: ${g.stderr.toString().trim()}`); - const events = parseGitLog(g.stdout.toString()).reverse(); - log(TAG, `${snaps.length} snapshot(s), ${series.apple.length} App Store day(s), ${series.play.length} Play day(s), ${events.length} store change(s) since ${first}`); - const fx = compareAroundEvents(series, events, a.num('days', 7)); - console.log(a.has('md') ? effectMarkdown(fx) : effectTable(fx)); - log(TAG, 'reading: a change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too'); - return; - } - throw new Error('usage: storebound analytics setup | snapshot | compare'); -} diff --git a/cli/apple/asc.ts b/cli/apple/asc.ts index 11a0adf..3ce3eba 100644 --- a/cli/apple/asc.ts +++ b/cli/apple/asc.ts @@ -46,17 +46,6 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri return t ? JSON.parse(t) : {}; } - /** GET with a vendor media type, e.g. perfPowerMetrics (application/vnd.apple.xcode-metrics+json). Parsed JSON. */ - async function getAs(path: string, accept: string): Promise { - for (let attempt = 1; ; attempt++) { - const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } }); - const t = await r.text(); - if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); continue; } - if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${t.slice(0, 800)}`); - return t ? JSON.parse(t) : {}; - } - } - /** Every item of a paged GET. */ async function all(path: string): Promise { const out: J[] = []; @@ -106,5 +95,5 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri return res.id; } - return { asc, all, maybe, getAs, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId }; + return { asc, all, maybe, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId }; } diff --git a/cli/apple/jsonapi.ts b/cli/apple/jsonapi.ts deleted file mode 100644 index 7276464..0000000 --- a/cli/apple/jsonapi.ts +++ /dev/null @@ -1,29 +0,0 @@ -// JSON:API request builders for App Store Connect. Pure: commands build `Req`s, print them on --dry and send them -// with the client otherwise. Request / response format: https://developer.apple.com/documentation/appstoreconnectapi -import { log } from '../lib/log'; - -export interface Req { method: 'GET' | 'POST' | 'PATCH' | 'DELETE'; path: string; body?: unknown; note?: string } - -export const one = (type: string, id: string) => ({ data: { type, id } }); -export const many = (type: string, ids: string[]) => ({ data: ids.map(id => ({ type, id })) }); - -/** One-line description of a request for dry runs and logs. Attribute values are cut short; `hide` keys (emails, - * passwords) are masked. */ -export function describeReq(r: Req, hide: string[] = ['email', 'demoAccountPassword', 'contactEmail', 'contactPhone']): string { - const attrs = (r.body as { data?: { attributes?: Record } } | undefined)?.data?.attributes; - const show = (k: string, v: unknown) => (hide.includes(k) ? '"***"' : typeof v === 'string' && v.length > 40 ? JSON.stringify(v.slice(0, 37) + '...') : JSON.stringify(v)); - const keys = attrs ? Object.entries(attrs).map(([k, v]) => `${k}=${show(k, v)}`) : []; - return `${r.method} ${r.path}${keys.length ? ` {${keys.join(', ')}}` : ''}${r.note ? ` # ${r.note}` : ''}`; -} - -/** Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export async function execute(asc: (m: string, p: string, b?: unknown) => Promise, reqs: Req[], o: { dry: boolean; tag: string }): Promise { - const out: unknown[] = []; - for (const r of reqs) { - if (o.dry) { log(o.tag, `would ${describeReq(r)}`); continue; } - out.push(await asc(r.method, r.path, r.body)); - log(o.tag, `${describeReq(r)}: done`); - } - return out; -} diff --git a/cli/apple/ppo.ts b/cli/apple/ppo.ts deleted file mode 100644 index e637123..0000000 --- a/cli/apple/ppo.ts +++ /dev/null @@ -1,126 +0,0 @@ -// App Store Product Page Optimization through the App Store Connect API, wired to the `shots` variants. -// storebound apple ppo status -// storebound apple ppo create --variant b[,c] [--name "..."] [--traffic 30] [--dry] -// storebound apple ppo upload --variant b [--experiment "..."] [--only en-US,tr] [--src store/renders] [--dry] -// storebound apple ppo start | stop [--experiment "..."] [--dry] [--yes] -// create: one test (v2 experiment, platform IOS) with one treatment per variant (named after the variant, at most 3) -// and a treatment localization per App Store locale of the config. upload: the variant renders -// (///ios69 ... from `storebound shots render --variant b`) into each treatment localization's -// screenshot sets, MD5-idempotent like `apple screenshots`. start / stop change what players see (stop is final, a test -// cannot be restarted) and ask first; they are not MCP tools. Google Play store listing experiments have no API: they -// stay in Play Console (store-screenshots skill). Pure planners: cli/lib/ppo.ts. -import { existsSync } from 'node:fs'; -import { join } from 'node:path'; -import type { Ctx } from '../lib/ctx'; -import { byAppleLocale, confirm, need } from '../lib/ctx'; -import { done, log, warn } from '../lib/log'; -import { - checkCreate, createExperimentReq, defaultName, type Experiment, experimentFromApi, pickExperiment, planTreatmentLocales, planTreatments, startStopReq, -} from '../lib/ppo'; -import { textTable } from '../lib/table'; -import { numberedImages } from '../play/images'; -import { variantRoot } from '../shots/lib'; -import { type Asc, ascClient, type J } from './asc'; -import { execute } from './jsonapi'; -import { displaySets, syncScreenshotSet } from './screenshots'; - -const TAG = 'ppo'; -const USAGE = 'usage: storebound apple ppo status | create --variant b | upload --variant b | start | stop'; - -async function experiments(c: Asc, appId: string): Promise { - return (await c.all(`/v1/apps/${appId}/appStoreVersionExperimentsV2?limit=50`)).map(experimentFromApi); -} -const treatments = (c: Asc, expId: string) => c.all(`/v2/appStoreVersionExperiments/${expId}/appStoreVersionExperimentTreatments?limit=50`); -const treatmentLocs = (c: Asc, tId: string) => c.all(`/v1/appStoreVersionExperimentTreatments/${tId}/appStoreVersionExperimentTreatmentLocalizations?limit=50`); - -export async function run(ctx: Ctx): Promise { - const { config, root, resolve } = ctx.loaded; - const a = ctx.args; - const sub = a._[0]; - if (!sub) throw new Error(USAGE); - const dry = a.has('dry'); - const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); - const appId = await c.app(); - const list = await experiments(c, appId); - const locales = config.languages.map(l => l.apple).filter((x): x is string => !!x); - - if (sub === 'status') { - if (!list.length) { done(TAG, 'no Product Page Optimization tests (storebound apple ppo create --variant b)'); return; } - console.log(textTable(['test', 'state', 'traffic', 'start', 'end'], list.map(x => [x.name, x.state, x.trafficProportion !== undefined ? `${x.trafficProportion}%` : '', (x.startDate ?? '').slice(0, 10), (x.endDate ?? '').slice(0, 10)]))); - for (const x of list.filter(e => !['COMPLETED', 'STOPPED'].includes(e.state))) { - for (const t of await treatments(c, x.id)) { - const locs = await treatmentLocs(c, t.id); - let shots = 0; - for (const l of locs) for (const s of await c.all(`/v1/appStoreVersionExperimentTreatmentLocalizations/${l.id}/appScreenshotSets?limit=50`)) shots += (await c.all(`/v1/appScreenshotSets/${s.id}/appScreenshots?limit=50`)).length; - log(TAG, `"${x.name}" treatment "${t.attributes.name}": ${locs.length} locale(s), ${shots} screenshot(s)`); - } - } - log(TAG, 'results (conversion per treatment) are in App Store Connect > Product Page Optimization; no API returns them'); - return; - } - - if (sub === 'create') { - const variants = a.list('variant'); - const traffic = a.num('traffic', 30); - const problems = checkCreate(variants, traffic, Object.keys(config.shots?.variants ?? {})); - if (problems.length) throw new Error(problems.join('; ')); - const name = a.get('name') ?? defaultName(variants); - let exp = pickExperiment(list, name); - if (!exp) { - if (dry) { await execute(c.asc, [createExperimentReq(appId, name, traffic)], { dry, tag: TAG }); log(TAG, `then: ${variants.length} treatment(s) x ${locales.length} locale(s)`); done(TAG, 'create checked (dry run)'); return; } - const r = (await execute(c.asc, [createExperimentReq(appId, name, traffic)], { dry, tag: TAG }))[0] as J; - exp = experimentFromApi(r.data); - } else log(TAG, `experiment "${name}": exists (${exp.state})`); - const ts = await treatments(c, exp.id); - const created = (await execute(c.asc, planTreatments(exp.id, ts.map((t: J) => ({ id: t.id, name: t.attributes.name })), variants), { dry, tag: TAG })) as J[]; - const all = [...ts, ...created.map(r => r.data)].filter(t => variants.includes(t.attributes.name)); - for (const t of all) await execute(c.asc, planTreatmentLocales(t.id, (await treatmentLocs(c, t.id)).map((l: J) => l.attributes.locale), locales), { dry, tag: TAG }); - done(TAG, dry ? 'create checked (dry run)' : `test "${name}" ready: storebound apple ppo upload --variant ${variants[0]}`); - return; - } - - if (sub === 'upload') { - const variant = need(a.get('variant'), '--variant '); - const exp = pickExperiment(list, a.get('experiment')); - if (!exp) throw new Error('no editable Product Page Optimization test (storebound apple ppo create --variant ' + variant + ')'); - const t = (await treatments(c, exp.id)).find((x: J) => x.attributes.name === variant); - if (!t) throw new Error(`test "${exp.name}" has no treatment "${variant}" (storebound apple ppo create --variant ${variant} --name "${exp.name}")`); - const src = variantRoot(resolve(a.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders'), variant, config.shots?.variants); - const only = a.list('only'); - const langOf = byAppleLocale(config.languages); - let sets = 0; - for (const loc of await treatmentLocs(c, t.id)) { - const locale: string = loc.attributes.locale; - if (only.length && !only.includes(locale)) continue; - const lang = langOf.get(locale); - if (!lang) { warn(TAG, `${locale}: no language with apple: "${locale}", skipped`); continue; } - const existing = await c.all(`/v1/appStoreVersionExperimentTreatmentLocalizations/${loc.id}/appScreenshotSets?limit=50`); - for (const [dir, type] of Object.entries(displaySets(config.apple))) { - const d = join(src, lang.id, dir); - const files = existsSync(d) ? numberedImages(d).filter(f => f.endsWith('.png')).slice(0, 10) : []; - if (!files.length) { warn(TAG, `${locale}: nothing in ${d} (storebound shots render --variant ${variant}), skipped`); continue; } - await syncScreenshotSet(c, { rel: 'appStoreVersionExperimentTreatmentLocalization', type: 'appStoreVersionExperimentTreatmentLocalizations', id: loc.id }, existing, type, files, `${variant} ${locale} ${type}`, dry); - sets++; - } - } - done(TAG, `${sets} screenshot set(s) ${dry ? 'checked (dry run)' : 'synced'} for treatment "${variant}" of "${exp.name}"`); - return; - } - - if (sub === 'start' || sub === 'stop') { - const start = sub === 'start'; - const name = a.get('experiment'); - const exp = name ? list.find(x => x.name === name) ?? null : start ? pickExperiment(list) : list.find(x => ['WAITING_FOR_REVIEW', 'IN_REVIEW', 'ACCEPTED', 'APPROVED'].includes(x.state) || (x.startDate && !x.endDate && !['COMPLETED', 'STOPPED'].includes(x.state))) ?? null; - if (!exp) throw new Error(`no test to ${sub}${name ? ` named "${name}"` : ''} (storebound apple ppo status)`); - const req = startStopReq(exp, start); - if (dry) { await execute(c.asc, [req], { dry, tag: TAG }); return; } - const q = start - ? `Start "${exp.name}" (${exp.trafficProportion ?? '?'}% of App Store visitors see a treatment)? Treatments not yet approved go to App Review with your next version first.` - : `Stop "${exp.name}" now? A stopped test cannot be restarted.`; - if (!(await confirm(ctx, q))) return; - await execute(c.asc, [req], { dry, tag: TAG }); - done(TAG, `${sub} requested for "${exp.name}" (storebound apple ppo status)`); - return; - } - throw new Error(`unknown ppo command "${sub}"\n${USAGE}`); -} diff --git a/cli/apple/screenshots.ts b/cli/apple/screenshots.ts index 300983d..4f98f58 100644 --- a/cli/apple/screenshots.ts +++ b/cli/apple/screenshots.ts @@ -14,40 +14,20 @@ import { byAppleLocale, need } from '../lib/ctx'; import { done, log, warn } from '../lib/log'; import { numberedImages } from '../play/images'; import { variantRoot } from '../shots/lib'; -import { type Asc, ascClient, md5, setUpToDate, type J } from './asc'; +import { ascClient, md5, setUpToDate, type J } from './asc'; /** Render size key -> ASC screenshotDisplayType (iPhone sets). */ export const DISPLAY: Record = { ios69: 'APP_IPHONE_67', ios65: 'APP_IPHONE_65' }; /** 13" iPad set, uploaded only when apple.ipad is true. */ export const IPAD_DISPLAY: Record = { ipad13: 'APP_IPAD_PRO_3GEN_129' }; -/** 6.3" iPhone (Dynamic Island, medium display), uploaded only when apple.iphoneMedium is true. */ -export const MEDIUM_DISPLAY: Record = { 'iphone-medium': 'APP_IPHONE_61' }; - -/** Display sets this project uploads: the iPhone sets, plus the 6.3" set with apple.iphoneMedium and the 13" iPad set - * with apple.ipad. */ -export const displaySets = (apple: { ipad?: boolean; iphoneMedium?: boolean } | undefined): Record => - ({ ...DISPLAY, ...(apple?.iphoneMedium ? MEDIUM_DISPLAY : {}), ...(apple?.ipad ? IPAD_DISPLAY : {}) }); +/** Display sets this project uploads: the iPhone sets, plus the 13" iPad set with apple.ipad. */ +export const displaySets = (apple: { ipad?: boolean } | undefined): Record => ({ ...DISPLAY, ...(apple?.ipad ? IPAD_DISPLAY : {}) }); /** Display types `validate` requires on every locale: apple.screenshotTypes, else 6.9" iPhone (+ 13" iPad with ipad). */ export const requiredDisplayTypes = (apple: { ipad?: boolean; screenshotTypes?: string[] } | undefined): string[] => apple?.screenshotTypes ?? ['APP_IPHONE_67', ...(apple?.ipad ? ['APP_IPAD_PRO_3GEN_129'] : [])]; -/** Makes one screenshot set (of a version localization, or of a Product Page Optimization treatment localization) - * hold exactly `files`, in order: left alone when the MD5s match, else emptied and re-uploaded. Creates the set. */ -export async function syncScreenshotSet(c: Asc, parent: { rel: string; type: string; id: string }, sets: J[], type: string, files: string[], tag: string, dry: boolean): Promise { - let set = sets.find(s => s.attributes.screenshotDisplayType === type); - const existing = set ? await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots`) : []; - const want = files.map(f => md5(readFileSync(f))); - if (set && setUpToDate(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: s.attributes.assetDeliveryState?.state })), want)) { log('apple', `${tag}: ${files.length} up to date`); return; } - if (dry) { log('apple', `${tag}: would ${set ? `replace ${existing.length}` : 'create the set and upload'} with ${files.length}`); return; } - if (!set) set = (await c.asc('POST', '/v1/appScreenshotSets', { data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: type }, - relationships: { [parent.rel]: { data: { type: parent.type, id: parent.id } } } } })).data; - for (const s of existing) await c.asc('DELETE', `/v1/appScreenshots/${s.id}`); - for (const f of files) await c.uploadAsset('appScreenshots', { appScreenshotSet: { data: { type: 'appScreenshotSets', id: set.id } } }, f); - log('apple', `${tag}: uploaded ${files.length} (removed ${existing.length})`); -} - export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; const src = variantRoot(resolve(ctx.args.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders'), ctx.args.get('variant'), config.shots?.variants); @@ -60,8 +40,18 @@ export async function run(ctx: Ctx): Promise { const langOf = byAppleLocale(config.languages); const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); - const syncSet = (locId: string, sets: J[], type: string, files: string[], tag: string) => - syncScreenshotSet(c, { rel: 'appStoreVersionLocalization', type: 'appStoreVersionLocalizations', id: locId }, sets, type, files, tag, ctx.args.has('dry')); + async function syncSet(locId: string, sets: J[], type: string, files: string[], tag: string): Promise { + let set = sets.find(s => s.attributes.screenshotDisplayType === type); + if (!set) set = (await c.asc('POST', '/v1/appScreenshotSets', { data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: type }, + relationships: { appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: locId } } } } })).data; + const existing = await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots`); + const want = files.map(f => md5(readFileSync(f))); + if (setUpToDate(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: s.attributes.assetDeliveryState?.state })), want)) { log('apple', `${tag}: ${files.length} up to date`); return; } + if (ctx.args.has('dry')) { log('apple', `${tag}: would replace ${existing.length} with ${files.length}`); return; } + for (const s of existing) await c.asc('DELETE', `/v1/appScreenshots/${s.id}`); + for (const f of files) await c.uploadAsset('appScreenshots', { appScreenshotSet: { data: { type: 'appScreenshotSets', id: set.id } } }, f); + log('apple', `${tag}: uploaded ${files.length} (removed ${existing.length})`); + } const tasks: (() => Promise)[] = []; for (const loc of locs) { diff --git a/cli/apple/testflight.ts b/cli/apple/testflight.ts deleted file mode 100644 index 626b55f..0000000 --- a/cli/apple/testflight.ts +++ /dev/null @@ -1,182 +0,0 @@ -// TestFlight through the App Store Connect API. -// storebound apple testflight status groups, testers per group, recent builds + beta states -// storebound apple testflight groups [--dry] create the groups of apple.testflight.groups that are missing -// storebound apple testflight testers [--csv f] [--group a,b] [--remove] [--invite] [--dry] [--yes] -// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry] -// storebound apple testflight info [--dry] Test Information + Beta App Review contact / notes -// storebound apple testflight distribute --build N --group a,b [--version x.y.z] [--internal-only] [--submit-review] [--dry] [--yes] -// Testers come from a CSV in .storebound/ (gitignored; never commit tester emails): email, first_name, last_name, -// groups (";"-separated). Emails are masked in every log line. Adding testers makes Apple email TestFlight invitations -// (once the group has a build), so `testers` asks first; `--remove` takes testers out of the managed groups. -// `distribute --submit-review` sends the build to Beta App Review (external groups) after a confirmation; neither -// testers nor external distribution nor the review submission are MCP tools. Pure planning: cli/lib/testflight.ts. -import { existsSync, readFileSync } from 'node:fs'; -import type { Ctx } from '../lib/ctx'; -import { confirm, need } from '../lib/ctx'; -import { reviewContact } from '../lib/credentials'; -import { done, log, warn } from '../lib/log'; -import { textTable } from '../lib/table'; -import { - type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail, - parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing, -} from '../lib/testflight'; -import { type Asc, ascClient, type J } from './asc'; -import { execute } from './jsonapi'; - -const TAG = 'testflight'; -const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group '; - -async function groups(c: Asc, appId: string): Promise { - return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi); -} - -async function findBuild(c: Asc, appId: string, number: string, marketing?: string): Promise { - const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': number, 'filter[preReleaseVersion.platform]': 'IOS', include: 'preReleaseVersion,buildBetaDetail', limit: '50' }); - if (marketing) q.set('filter[preReleaseVersion.version]', marketing); - const resp = await c.asc('GET', `/v1/builds?${q}`); - const b = pickBuild(buildsWithVersion(resp), number, marketing); - const detail = (resp.included ?? []).find((x: J) => x.type === 'buildBetaDetails' && x.id === (b as J).relationships?.buildBetaDetail?.data?.id)?.attributes ?? null; - return { ...b, detail }; -} - -export async function run(ctx: Ctx): Promise { - const { config, root, resolve } = ctx.loaded; - const a = ctx.args; - const sub = a._[0]; - if (!sub) throw new Error(USAGE); - const dry = a.has('dry'); - const tf = config.apple?.testflight; - const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); - const appId = await c.app(); - - if (sub === 'status') { - const gs = await groups(c, appId); - const rows: (string | number)[][] = []; - for (const g of gs) { - const testers = await c.all(`/v1/betaGroups/${g.id}/betaTesters?limit=200`); - const builds = await c.all(`/v1/betaGroups/${g.id}/builds?limit=200`); - rows.push([g.name, g.internal ? 'internal' : 'external', testers.length, g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, g.publicLinkEnabled ? 'public link on' : '']); - } - console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows)); - const q = new URLSearchParams({ 'filter[app]': appId, include: 'preReleaseVersion,buildBetaDetail', sort: '-uploadedDate', limit: '8' }); - const resp = await c.asc('GET', `/v1/builds?${q}`); - const details = new Map((resp.included ?? []).filter((x: J) => x.type === 'buildBetaDetails').map((x: J) => [x.id, x.attributes] as const)); - console.log('\n' + textTable(['version', 'build', 'processing', 'internal', 'external', 'uploaded'], buildsWithVersion(resp).map(b => { - const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J; - return [b.marketing ?? '', b.attributes.version ?? '', b.attributes.processingState ?? '', d?.internalBuildState ?? '', d?.externalBuildState ?? '', (b.attributes.uploadedDate ?? '').slice(0, 10)]; - }))); - const missing = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name); - if (missing.length) warn(TAG, `configured but not on App Store Connect: ${missing.join(', ')} (storebound apple testflight groups)`); - return; - } - - if (sub === 'groups') { - const plan = planGroups(appId, await groups(c, appId), tf?.groups ?? []); - if (!tf?.groups?.length) warn(TAG, 'apple.testflight.groups is empty: nothing to create'); - for (const n of plan.existing) log(TAG, `group "${n}": exists`); - await execute(c.asc, plan.create, { dry, tag: TAG }); - done(TAG, dry ? `groups checked (dry run): ${plan.create.length} to create` : `groups done (${plan.create.length} created)`); - return; - } - - if (sub === 'testers') { - const csvPath = resolve(a.get('csv') ?? tf?.testers ?? '.storebound/testers.csv'); - if (!existsSync(csvPath)) throw new Error(`no tester CSV at ${csvPath} (columns: email, first_name, last_name, groups; keep it in .storebound/)`); - const only = a.list('group'); - const want = parseTesters(readFileSync(csvPath, 'utf8'), only.length === 1 ? only[0] : undefined); - const gs = await groups(c, appId); - const existing = new Map(); - const resp = await c.all(`/v1/betaTesters?filter[apps]=${appId}&include=betaGroups&limit=200`); - for (const t of resp) existing.set(String(t.attributes.email ?? '').toLowerCase(), { id: t.id, groupIds: (t.relationships?.betaGroups?.data ?? []).map((g: J) => g.id), state: t.attributes.state }); - const plan = planTesters(gs, existing, want, { remove: a.has('remove'), only }); - if (plan.unknownGroups.length) throw new Error(`unknown group(s): ${plan.unknownGroups.join(', ')} (storebound apple testflight groups creates the configured ones)`); - const internal = gs.filter(g => g.internal && want.some(t => t.groups.includes(g.name))); - if (internal.length) warn(TAG, `internal groups (${internal.map(g => g.name).join(', ')}) only take App Store Connect users of your team (Users and Access)`); - log(TAG, `${want.length} testers in the CSV: ${plan.summary.join(', ')}`); - const reqs = [...plan.create, ...plan.add, ...plan.remove]; - if (!reqs.length && !a.has('invite')) { done(TAG, 'testers up to date'); return; } - if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, 'testers checked (dry run)'); return; } - if (reqs.length && !(await confirm(ctx, `Apply ${plan.summary.join(', ')}? New testers get a TestFlight invitation email from Apple.`))) return; - await execute(c.asc, reqs, { dry, tag: TAG }); - if (a.has('invite')) { - const fresh = new Map((await c.all(`/v1/betaTesters?filter[apps]=${appId}&limit=200`)).map((t: J) => [String(t.attributes.email ?? '').toLowerCase(), t] as const)); - const pending = want.map(t => fresh.get(t.email)).filter((t): t is J => !!t && ['NOT_INVITED', 'INVITED'].includes(t.attributes.state)); - if (pending.length && await confirm(ctx, `(Re)send the TestFlight invitation email to ${pending.length} tester(s)?`)) - await execute(c.asc, pending.map(t => inviteReq(appId, t.id, maskEmail(String(t.attributes.email)))), { dry: false, tag: TAG }); - } - done(TAG, 'testers done'); - return; - } - - if (sub === 'what-to-test') { - const number = need(a.get('build'), '--build N (the exact build number)'); - const b = await findBuild(c, appId, number, a.get('version')); - let want: Record; - const locales = a.list('locale'); - if (a.get('text')) { - const ls = locales.length ? locales : [config.apple?.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US']; - want = Object.fromEntries(ls.map(l => [l, a.get('text')!])); - } else { - const f = resolve(config.apple?.listing ?? 'store/appstore.md'); - want = whatToTestFromListing(readFileSync(f, 'utf8')); - if (locales.length) want = Object.fromEntries(Object.entries(want).filter(([l]) => locales.includes(l))); - if (!Object.keys(want).length) throw new Error(`${f}: no "### whatToTest" or "### whatsNew" block (storebound whats-new drafts one), or pass --text`); - } - const existing = (await c.all(`/v1/builds/${b.id}/betaBuildLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, whatsNew: l.attributes.whatsNew })); - const reqs = planWhatToTest(b.id, existing, want); - if (!reqs.length) { done(TAG, `build ${number}: What to Test up to date (${Object.keys(want).join(', ')})`); return; } - await execute(c.asc, reqs, { dry, tag: TAG }); - done(TAG, dry ? `build ${number}: ${reqs.length} locale(s) to set (dry run)` : `build ${number}: What to Test set for ${reqs.length} locale(s)`); - return; - } - - if (sub === 'info') { - const desc = betaDescriptions(tf, config.languages); - if (!Object.keys(desc).length) warn(TAG, 'apple.testflight.description is not set: external testing needs a Beta App Description per locale'); - const want = Object.fromEntries(Object.entries(desc).map(([locale, description]) => [locale, { description, feedbackEmail: config.app.contactEmail, - privacyPolicyUrl: config.app.privacyPolicyUrl, marketingUrl: config.app.marketingUrl ?? config.app.website }])); - const locs = (await c.all(`/v1/apps/${appId}/betaAppLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, attributes: l.attributes })); - const detail = (await c.maybe(`/v1/apps/${appId}/betaAppReviewDetail`))?.data ?? null; - const contact = reviewContact(root); - if (!contact) warn(TAG, 'no reviewContact in .storebound/credentials.json: Beta App Review contact left as it is'); - const reqs = [...planBetaInfo(appId, locs, want), ...planBetaReviewDetail(detail, contact, tf?.reviewNotes ?? config.apple?.info?.reviewNotes)]; - await execute(c.asc, reqs, { dry, tag: TAG }); - done(TAG, reqs.length ? (dry ? `${reqs.length} change(s) (dry run)` : `test information updated (${reqs.length})`) : 'test information up to date'); - return; - } - - if (sub === 'distribute') { - const number = need(a.get('build'), '--build N (the exact build number you uploaded)'); - const names = a.list('group'); - if (!names.length) throw new Error('--group [,]: which beta groups get the build'); - const gs = await groups(c, appId); - const target = names.map(n => gs.find(g => g.name === n) ?? (() => { throw new Error(`unknown group "${n}" (${gs.map(g => g.name).join(', ')})`); })()); - const external = target.filter(g => !g.internal); - if (a.has('internal-only') && external.length) throw new Error(`external group(s) ${external.map(g => g.name).join(', ')}: distribute to external testers from the terminal (asks first)`); - const b = await findBuild(c, appId, number, a.get('version')); - const problems = betaReadiness(b.attributes, b.detail); - if (problems.length) throw new Error(`build ${number}: ${problems.join('; ')}`); - log(TAG, `build ${number} (${b.marketing ?? '?'}): internal ${b.detail?.internalBuildState ?? '?'}, external ${b.detail?.externalBuildState ?? '?'}`); - const inGroups = (await c.all(`/v1/betaGroups?filter[app]=${appId}&filter[builds]=${b.id}&limit=200`)).map((g: J) => g.id); - const reqs = planDistribute(b.id, target, inGroups); - const review = a.has('submit-review') && external.length ? (await c.maybe(`/v1/builds/${b.id}/betaAppReviewSubmission`))?.data ?? null : null; - const wantsReview = a.has('submit-review') && external.length > 0 && !review && !['BETA_APPROVED', 'IN_BETA_REVIEW', 'WAITING_FOR_BETA_REVIEW', 'IN_BETA_TESTING'].includes(b.detail?.externalBuildState); - if (a.has('submit-review') && review) log(TAG, `beta review: already submitted (${review.attributes?.betaReviewState ?? '?'})`); - if (external.length && !a.has('submit-review') && b.detail?.externalBuildState === 'READY_FOR_BETA_SUBMISSION') - warn(TAG, 'external testers only get the build after Beta App Review: add --submit-review (asks first) or submit it in App Store Connect'); - if (dry) { - await execute(c.asc, [...reqs, ...(wantsReview ? [betaReviewReq(b.id)] : [])], { dry, tag: TAG }); - done(TAG, 'distribute checked (dry run)'); - return; - } - if (external.length && reqs.some(r => external.some(g => r.path.includes(g.id))) && !(await confirm(ctx, `Give build ${number} to external group(s) ${external.map(g => g.name).join(', ')}? Testers are notified once Beta App Review approves it.`))) return; - await execute(c.asc, reqs, { dry, tag: TAG }); - if (wantsReview) { - if (await confirm(ctx, `Submit build ${number} to Beta App Review now? Apple reviews it for external testing (Test Information must be complete: storebound apple testflight info).`)) - await execute(c.asc, [betaReviewReq(b.id)], { dry: false, tag: TAG }); - } - done(TAG, `build ${number}: ${reqs.length ? `added to ${reqs.length} group(s)` : 'already in every group'}`); - return; - } - throw new Error(`unknown testflight command "${sub}"\n${USAGE}`); -} diff --git a/cli/health.ts b/cli/health.ts deleted file mode 100644 index 67631f1..0000000 --- a/cli/health.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Crash and vitals health of the released game, read-only on both stores. -// storebound health [--apple] [--play] [--days 7] [--json] -// storebound health --weekly [--out .storebound/health] [--dry] also writes .md (+ .json for the next -// comparison); --dry prints the report instead of writing it -// Google Play: Play Developer Reporting API (user-perceived crash and ANR rates, 28-day user-weighted, the worst -// device models, top error issues). The service account needs "View app information (read-only)" and the API enabled -// in its Cloud project. App Store: power and performance metrics (perfPowerMetrics), diagnostic signatures of the -// latest builds, TestFlight crash submissions. Thresholds and sources: cli/lib/health.ts. `validate` reuses the -// same collection and adds the findings (over a Play bad behavior threshold = blocker). -import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { ascClient, type J } from './apple/asc'; -import type { Ctx } from './lib/ctx'; -import { REPORTING_SCOPE } from './lib/google-auth'; -import { - type AppleHealth, ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable, - issuesQuery, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, ymd, ymdString, -} from './lib/health'; -import { done, log, warn } from './lib/log'; -import { formatFindings } from './lib/validate-rules'; -import { googleClient, REPORTING_API } from './play/google'; - -export async function collectPlayHealth(root: string, pkg: string, days: number): Promise { - const g = googleClient(root, REPORTING_SCOPE); - const app = `${REPORTING_API}/apps/${encodeURIComponent(pkg)}`; - log('health', 'play: vitals freshness'); - const set = await g.json[0]>('GET', `${app}/crashRateMetricSet`); - const end = latestDailyEnd(set) ?? ymd(new Date(), 2); - log('health', `play: crash and ANR rates to ${ymdString(end)} (${days} days, America/Los_Angeles days)`); - const crash = parseMetricRows(await g.json('POST', `${app}/crashRateMetricSet:query`, metricQuery(CRASH_METRICS, end, days))); - const anr = parseMetricRows(await g.json('POST', `${app}/anrRateMetricSet:query`, metricQuery(ANR_METRICS, end, days))); - log('health', 'play: per device model (28 days) and top issues'); - const crashDev = parseMetricRows(await g.json('POST', `${app}/crashRateMetricSet:query`, metricQuery(['userPerceivedCrashRate', 'distinctUsers'], end, 28, ['deviceModel']))); - const anrDev = parseMetricRows(await g.json('POST', `${app}/anrRateMetricSet:query`, metricQuery(['userPerceivedAnrRate', 'distinctUsers'], end, 28, ['deviceModel']))); - const issues = parseIssues(await g.json('GET', `${app}/errorIssues:search?${issuesQuery(end, days)}`)); - const start = ymd(new Date(Date.UTC(end.year, end.month - 1, end.day)), days); - return { window: { start: ymdString(start), end: ymdString(end), days }, crash, anr, devices: deviceBreakdown(crashDev, anrDev), issues }; -} - -export async function collectAppleHealth(root: string, bundleId: string, appIdHint: string | undefined, days: number): Promise { - const c = await ascClient(root, bundleId, appIdHint); - const appId = await c.app(); - log('health', 'apple: power and performance metrics'); - const metrics = parsePerfPower(await c.getAs(`/v1/apps/${appId}/perfPowerMetrics?filter[platform]=IOS`, 'application/vnd.apple.xcode-metrics+json')); - const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&filter[processingState]=VALID&sort=-uploadedDate&limit=3`)).data as J[]; - const signatures: AppleHealth['signatures'] = []; - for (const b of builds) { - log('health', `apple: diagnostic signatures of build ${b.attributes.version}`); - for (const s of (await c.asc('GET', `/v1/builds/${b.id}/diagnosticSignatures?limit=10`)).data as J[]) - signatures.push({ build: b.attributes.version, type: s.attributes.diagnosticType, signature: s.attributes.signature ?? '', weight: Number(s.attributes.weight ?? 0) }); - } - signatures.sort((a, b) => b.weight - a.weight); - log('health', 'apple: TestFlight crash reports'); - const since = new Date(Date.now() - days * 86_400_000).toISOString(); - const subs = await c.all(`/v1/apps/${appId}/betaFeedbackCrashSubmissions?sort=-createdDate&limit=200`).catch(e => { warn('health', `TestFlight crash reports: ${(e as Error).message.slice(0, 160)}`); return []; }); - const buildNo = new Map(builds.map(b => [b.id, b.attributes.version] as const)); - return { metrics, signatures: signatures.slice(0, 15), betaCrashes: betaCrashCounts(subs, buildNo, since) }; -} - -/** Both stores (or the chosen one); a store that cannot be read becomes { error } instead of failing the run. */ -export async function collectHealth(ctx: Ctx, o: { apple: boolean; play: boolean; days: number }): Promise { - const { config, root } = ctx.loaded; - const h: HealthSnapshot = { date: new Date().toISOString().slice(0, 10) }; - if (o.play && config.play) { - try { h.play = await collectPlayHealth(root, config.play.packageName, o.days); } catch (e) { h.play = { error: (e as Error).message }; } - } - if (o.apple && config.apple) { - try { h.apple = await collectAppleHealth(root, config.apple.bundleId, config.apple.appId, o.days); } catch (e) { h.apple = { error: (e as Error).message }; } - } - return h; -} - -/** Newest earlier snapshot in the health folder (for week-over-week). */ -export function previousSnapshot(dir: string, before: string): HealthSnapshot | null { - if (!existsSync(dir)) return null; - const f = readdirSync(dir).filter(n => /^\d{4}-\d{2}-\d{2}\.json$/.test(n) && n.slice(0, 10) < before).sort().at(-1); - return f ? JSON.parse(readFileSync(join(dir, f), 'utf8')) as HealthSnapshot : null; -} - -export async function run(ctx: Ctx): Promise { - const a = ctx.args; - const both = !a.has('apple') && !a.has('play'); - const weekly = a.has('weekly'); - const days = a.num('days', 7); - if (!(days >= 1 && days <= 90)) throw new Error('--days: 1-90'); - const h = await collectHealth(ctx, { apple: both || a.has('apple'), play: both || a.has('play'), days }); - if (a.has('json')) { console.log(JSON.stringify(h, null, 2)); return; } - console.log(healthTable(h)); - console.log('\n' + formatFindings(healthFindings(h))); - if (weekly) { - const dir = ctx.loaded.resolve(a.get('out') ?? '.storebound/health'); - const md = healthMarkdown(h, { appName: ctx.loaded.config.app.name, previous: previousSnapshot(dir, h.date) }); - if (a.has('dry')) { console.log('\n' + md); log('health', `dry run: would write ${join(dir, `${h.date}.md`)}`); return; } - mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, `${h.date}.md`), md); - writeFileSync(join(dir, `${h.date}.json`), JSON.stringify(h, null, 2) + '\n'); - log('health', `report: ${join(dir, `${h.date}.md`)}`); - } - const over = healthFindings(h).filter(f => f.level === 'blocker').length; - done('health', over ? `${over} metric(s) over a store threshold` : 'no metric over a store threshold'); - if (over) process.exitCode = 1; -} diff --git a/cli/index.ts b/cli/index.ts index 66ef70e..5552234 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -17,10 +17,6 @@ const PLAIN: Record Promise, string]> = { const COMMANDS: Record Promise, string]> = { 'check': [() => import('./check'), 'validate config, copy files, data safety answers and products (offline); --aso keyword audit'], 'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'], - 'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'], - 'health': [() => import('./health'), 'crash / ANR vitals (Play) and diagnostics (App Store), read-only; --weekly writes a markdown report; exit 1 over a threshold'], - 'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes)'], - 'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'], 'whats-new': [() => import('./whats-new'), 'draft player-facing release notes from git log into the listing files (--since )'], 'play products': [() => import('./play/products'), 'one-time products: create / update, regional prices, activate'], 'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language'], @@ -42,8 +38,6 @@ const COMMANDS: Record Promise, string]> = { 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'], 'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'], 'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'], - 'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'], - 'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review]'], 'icons': [() => import('./icons'), 'App Store / Play / web / adaptive / legacy launcher icons from one artwork'], 'shots capture': [() => import('./shots/capture'), 'raw frames: --source web (playwright) | ios-sim (simctl) | android-emu (adb) | folder; --dry'], 'shots fonts': [() => import('./shots/fonts'), 'download font subsets for the copy (CJK / Arabic / Cyrillic ...)'], diff --git a/cli/init.ts b/cli/init.ts index fbf4ff9..55e1c15 100644 --- a/cli/init.ts +++ b/cli/init.ts @@ -15,7 +15,6 @@ const FILES: [string, string][] = [ ['declarations.md', 'store/declarations.md'], ['privacy-policy.html', 'store/privacy-policy.html'], ['credentials.example.json', '.storebound/credentials.json'], - ['testers.csv', '.storebound/testers.csv'], ]; export async function run(args: Args): Promise { diff --git a/cli/lib/analytics.ts b/cli/lib/analytics.ts deleted file mode 100644 index f27b0fb..0000000 --- a/cli/lib/analytics.ts +++ /dev/null @@ -1,186 +0,0 @@ -// Store analytics snapshots (impressions, product page views, downloads / installs, conversion) and their comparison -// with listing changes, as pure parts. `storebound analytics` downloads the data (read-only) and writes the snapshots. -// Sources (checked October 2026): -// App Store Connect Analytics Reports API: an ONGOING analyticsReportRequest (Admin creates it once; first data after -// 1-2 days, then daily; instances kept 35 days; a request stops after long inactivity: stoppedDueToInactivity), -// reports -> instances (DAILY) -> segments (url valid 5 minutes, md5 checksum, gzip text files; every segment of -// an instance is needed). A later processingDate replaces rows of the same Date: never sum one Date across instances. -// https://developer.apple.com/documentation/appstoreconnectapi/downloading-analytics-reports -// https://developer.apple.com/documentation/analytics-reports/app-store-discovery-and-engagement -// https://developer.apple.com/documentation/analytics-reports/app-download -// Google Play: no API for store listing statistics (the Reporting API has vitals only). Monthly CSV exports in the -// developer's Cloud Storage bucket gs://pubsite_prod_rev_ (Play Console > Download reports > Statistics, "Copy -// Cloud Storage URI"), UTF-16, read with the service account (Play Console permission "View app information and -// download bulk reports", scope devstorage.read_only): -// stats/store_performance/store_performance___country.csv (Store listing acquisitions / visitors) -// stats/installs/installs___country.csv (Daily User Installs, ...) -// https://support.google.com/googleplay/android-developer/answer/6135870 -import { createHash } from 'node:crypto'; -import { parseCsvRecords } from './csv'; -import { mdTable, pct, textTable } from './table'; - -export const APPLE_REPORTS = { - engagement: { category: 'APP_STORE_ENGAGEMENT', match: /discovery and engagement/i }, - downloads: { category: 'COMMERCE', match: /download/i }, -} as const; - -/** Standard over Detailed (Detailed adds noise for privacy and splits by campaign). */ -export function pickReport(reports: T[], match: RegExp): T | null { - const hits = reports.filter(r => match.test(r.attributes?.name ?? '')); - return hits.find(r => /standard/i.test(r.attributes?.name ?? '')) ?? hits[0] ?? null; -} - -/** Bytes of a downloaded segment vs its md5 checksum. */ -export const checksumOk = (b: Uint8Array, checksum: string): boolean => createHash('md5').update(b).digest('hex').toLowerCase() === checksum.toLowerCase(); - -/** Text of a report file: UTF-16 with a BOM (Play exports), else UTF-8. */ -export function decodeText(b: Uint8Array): string { - if (b[0] === 0xff && b[1] === 0xfe) return new TextDecoder('utf-16le').decode(b.subarray(2)); - if (b[0] === 0xfe && b[1] === 0xff) return new TextDecoder('utf-16be').decode(b.subarray(2)); - return new TextDecoder('utf-8').decode(b); -} - -/** Tab- or comma-separated report text -> records keyed by lower-case column name (by name: Apple may reorder). */ -export function parseReport(text: string): Record[] { - const first = text.replace(/^/, '').split(/\r?\n/, 1)[0] ?? ''; - return parseCsvRecords(text, first.includes('\t') ? '\t' : ','); -} - -/** Rows of several instances: per Date only the rows of the newest processingDate (later instances restate days). */ -export function latestPerDate(instances: { processingDate: string; rows: Record[] }[]): Record[] { - const best = new Map(); - for (const i of instances) for (const r of i.rows) { const d = r.date ?? ''; if (!best.has(d) || best.get(d)! < i.processingDate) best.set(d, i.processingDate); } - return instances.flatMap(i => i.rows.filter(r => best.get(r.date ?? '') === i.processingDate)); -} - -export interface AppleDay { date: string; impressions: number; uniqueImpressions: number; pageViews: number; uniquePageViews: number; downloads: number; firstTimeDownloads: number } -export interface PlayDay { date: string; visitors: number; acquisitions: number; installs: number } - -const num = (v: string | undefined) => { const n = Number((v ?? '').replace(/,/g, '')); return Number.isFinite(n) ? n : 0; }; - -/** Discovery and Engagement + Downloads rows -> one line per day (App Store, every territory and source summed). */ -export function appleDaily(engagement: Record[], downloads: Record[]): AppleDay[] { - const days = new Map(); - const day = (d: string) => days.get(d) ?? days.set(d, { date: d, impressions: 0, uniqueImpressions: 0, pageViews: 0, uniquePageViews: 0, downloads: 0, firstTimeDownloads: 0 }).get(d)!; - for (const r of engagement) { - if (!r.date) continue; - const ev = (r.event ?? '').toLowerCase(); - const x = day(r.date); - if (ev === 'impression') { x.impressions += num(r.counts); x.uniqueImpressions += num(r.unique_counts); } - else if (ev === 'page view') { x.pageViews += num(r.counts); x.uniquePageViews += num(r.unique_counts); } - } - for (const r of downloads) { - if (!r.date) continue; - const t = (r.download_type ?? '').toLowerCase(); - const x = day(r.date); - if (t === 'first-time download') { x.firstTimeDownloads += num(r.counts); x.downloads += num(r.counts); } - else if (t === 'redownload') x.downloads += num(r.counts); - } - return [...days.values()].sort((a, b) => a.date.localeCompare(b.date)); -} - -/** Play store performance + installs CSV rows (country files) -> one line per day. Dates are YYYY-MM-DD. */ -export function playDaily(storePerformance: Record[], installs: Record[]): PlayDay[] { - const days = new Map(); - const day = (d: string) => days.get(d) ?? days.set(d, { date: d, visitors: 0, acquisitions: 0, installs: 0 }).get(d)!; - for (const r of storePerformance) if (r.date) { const x = day(r.date); x.visitors += num(r.store_listing_visitors); x.acquisitions += num(r.store_listing_acquisitions); } - for (const r of installs) if (r.date) day(r.date).installs += num(r.daily_user_installs); - return [...days.values()].sort((a, b) => a.date.localeCompare(b.date)); -} - -/** Months (yyyyMM) a date window touches, for the Play file names. */ -export function monthsBetween(start: string, end: string): string[] { - const out: string[] = []; - let y = Number(start.slice(0, 4)), m = Number(start.slice(5, 7)); - const ey = Number(end.slice(0, 4)), em = Number(end.slice(5, 7)); - while (y < ey || (y === ey && m <= em)) { out.push(`${y}${String(m).padStart(2, '0')}`); if (++m > 12) { m = 1; y++; } } - return out; -} - -export const playObjects = (pkg: string, month: string) => ({ - storePerformance: `stats/store_performance/store_performance_${pkg}_${month}_country.csv`, - installs: `stats/installs/installs_${pkg}_${month}_country.csv`, -}); - -/** "gs://pubsite_prod_rev_123/" or "pubsite_prod_rev_123" -> bucket name. */ -export const bucketName = (b: string): string => b.replace(/^gs:\/\//, '').replace(/\/.*$/, ''); - -export interface Totals { impressions?: number; pageViews?: number; downloads?: number; conversion?: number | null; visitors?: number; acquisitions?: number; installs?: number } - -export function appleTotals(days: AppleDay[]): Totals { - const s = (k: keyof AppleDay) => days.reduce((n, d) => n + (d[k] as number), 0); - const uniq = s('uniqueImpressions'); - return { impressions: s('impressions'), pageViews: s('pageViews'), downloads: s('downloads'), conversion: uniq ? s('downloads') / uniq : null }; -} -export function playTotals(days: PlayDay[]): Totals { - const s = (k: keyof PlayDay) => days.reduce((n, d) => n + (d[k] as number), 0); - const v = s('visitors'); - return { visitors: v, acquisitions: s('acquisitions'), installs: s('installs'), conversion: v ? s('acquisitions') / v : null }; -} - -export interface Snapshot { - date: string; - window: { start: string; end: string; days: number }; - apple?: { daily: AppleDay[]; totals: Totals } | { error: string }; - play?: { daily: PlayDay[]; totals: Totals } | { error: string }; -} - -export const inWindow = (rows: T[], start: string, end: string): T[] => rows.filter(r => r.date >= start && r.date <= end); - -// ---- compare with listing changes ---- - -export interface Event { date: string; commit: string; subject: string; files: string[] } - -/** `git log --date=short --format=%x1e%h%x1f%ad%x1f%s --name-only -- ` -> events. */ -export function parseGitLog(out: string): Event[] { - return out.split('\x1e').map(s => s.trim()).filter(Boolean).map(block => { - const [head, ...files] = block.split('\n'); - const [commit = '', date = '', subject = ''] = (head ?? '').split('\x1f'); - return { date, commit, subject, files: files.map(f => f.trim()).filter(Boolean) }; - }).filter(e => /^\d{4}-\d{2}-\d{2}$/.test(e.date)); -} - -/** Snapshots -> one series per store (newest snapshot wins for a date). */ -export function mergeSeries(snaps: Snapshot[]): { apple: AppleDay[]; play: PlayDay[] } { - const a = new Map(), p = new Map(); - for (const s of [...snaps].sort((x, y) => x.date.localeCompare(y.date))) { - if (s.apple && !('error' in s.apple)) for (const d of s.apple.daily) a.set(d.date, d); - if (s.play && !('error' in s.play)) for (const d of s.play.daily) p.set(d.date, d); - } - return { apple: [...a.values()].sort((x, y) => x.date.localeCompare(y.date)), play: [...p.values()].sort((x, y) => x.date.localeCompare(y.date)) }; -} - -const addDays = (d: string, n: number) => new Date(Date.parse(d + 'T00:00:00Z') + n * 86_400_000).toISOString().slice(0, 10); - -export interface EventEffect { event: Event; store: 'apple' | 'play'; before: Totals; after: Totals; daysBefore: number; daysAfter: number } - -/** For every event: the `days` before it (excluding the event day) vs the `days` from it, per store, where data exists. */ -export function compareAroundEvents(series: { apple: AppleDay[]; play: PlayDay[] }, events: Event[], days = 7): EventEffect[] { - const out: EventEffect[] = []; - for (const e of events) { - const bs = addDays(e.date, -days), be = addDays(e.date, -1), as = e.date, ae = addDays(e.date, days - 1); - const ab = inWindow(series.apple, bs, be), aa = inWindow(series.apple, as, ae); - if (ab.length || aa.length) out.push({ event: e, store: 'apple', before: appleTotals(ab), after: appleTotals(aa), daysBefore: ab.length, daysAfter: aa.length }); - const pb = inWindow(series.play, bs, be), pa = inWindow(series.play, as, ae); - if (pb.length || pa.length) out.push({ event: e, store: 'play', before: playTotals(pb), after: playTotals(pa), daysBefore: pb.length, daysAfter: pa.length }); - } - return out; -} - -const perDay = (v: number | undefined, n: number) => (v === undefined || !n ? null : v / n); -const fmtN = (v: number | null) => (v === null ? 'n/a' : v >= 100 ? Math.round(v).toString() : v.toFixed(1)); -const delta = (a: number | null | undefined, b: number | null | undefined) => (a == null || b == null || a === 0 ? '' : `${b >= a ? '+' : ''}${(((b - a) / a) * 100).toFixed(0)}%`); - -/** Rows for the comparison table: per event and store, daily averages before / after and the conversion change. */ -export function effectRows(fx: EventEffect[]): (string | number)[][] { - return fx.map(f => { - const top = f.store === 'apple' ? 'impressions' : 'visitors'; - const b = perDay(f.before[top], f.daysBefore), a = perDay(f.after[top], f.daysAfter); - return [f.event.date, f.store, f.event.subject.slice(0, 48), `${fmtN(b)} -> ${fmtN(a)} ${delta(b, a)}`.trim(), - `${pct(f.before.conversion ?? null)} -> ${pct(f.after.conversion ?? null)}`, `${f.daysBefore}/${f.daysAfter}`]; - }); -} - -export const EFFECT_HEAD = ['date', 'store', 'change', 'impressions or visitors / day', 'conversion', 'days before/after']; -export const effectTable = (fx: EventEffect[]): string => (fx.length ? textTable(EFFECT_HEAD, effectRows(fx)) : 'no listing changes inside the snapshot data yet'); -export const effectMarkdown = (fx: EventEffect[]): string => mdTable(EFFECT_HEAD, effectRows(fx)); diff --git a/cli/lib/config.ts b/cli/lib/config.ts index a320f21..219c954 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -3,7 +3,6 @@ import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { validateCapture, validateRecord } from '../shots/devices'; -import { type TfConfig, validateTestflight } from './testflight'; export type ProductType = 'consumable' | 'non_consumable'; @@ -271,9 +270,6 @@ export interface ShipConfig { packageName: string; defaultLanguage?: string; listing?: string; icon?: string; /** Promo video: a YouTube URL (public or unlisted, ads off, embeddable). Play takes no video upload. Sent by `play listing`. */ video?: string; - /** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_" (Play Console > - * Download reports > Statistics > Copy Cloud Storage URI). Used by `storebound analytics snapshot`. */ - reportsBucket?: string; }; apple?: { bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string; @@ -287,24 +283,8 @@ export interface ShipConfig { screenshotTypes?: string[]; /** The app runs on iPad: renders, checks and uploads 13" iPad screenshots (2064 x 2752) and iPad app previews. */ ipad?: boolean; - /** - * Also render, check and upload a 6.3" iPhone set (Dynamic Island, medium display, 1206 x 2622 -> APP_IPHONE_61). - * Off by default: App Store Connect lists a medium-display screenshot as required for iPhone but fills it by - * scaling the 6.5" set down when it is missing, and the 6.9" set covers the large displays. Turn it on for - * pixel-exact art on 6.3" phones, or if Apple stops scaling. (Screenshot specifications, App Store Connect Help.) - */ - iphoneMedium?: boolean; - /** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */ - testflight?: TfConfig; }; products?: Product[]; - /** Price sheet for `storebound prices export | import` (product x store x region). */ - prices?: { - /** CSV path. Default store/prices.csv. */ - csv?: string; - /** App Store base territory of every price schedule (alpha-3). Default: the current one, else USA. */ - baseTerritory?: string; - }; dataSafety?: DataSafety; /** Ads: `validate` checks that /app-ads.txt is reachable and contains every line listed here. */ ads?: { appAdsTxt?: string[] }; @@ -345,15 +325,12 @@ export function validateConfig(c: unknown): string[] { if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)'); if (cfg.play?.video && !/^https:\/\/(www\.youtube\.com\/watch\?v=[\w-]{6,}|youtu\.be\/[\w-]{6,})$/.test(cfg.play.video)) e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters'); - if (cfg.play?.reportsBucket && !/^(gs:\/\/)?pubsite_prod(_rev)?_\d+\/?$/.test(cfg.play.reportsBucket)) - e.push('play.reportsBucket: the Play reports bucket, e.g. "pubsite_prod_rev_" (Play Console > Download reports > Copy Cloud Storage URI)'); if (cfg.apple) { if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)'); if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)'); const enc = cfg.apple.usesNonExemptEncryption; if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false'); if (cfg.apple.screenshotTypes && !cfg.apple.screenshotTypes.every(t => /^APP_[A-Z0-9_]+$/.test(t))) e.push('apple.screenshotTypes: display types like APP_IPHONE_67'); - e.push(...validateTestflight(cfg.apple.testflight)); } if (cfg.ads?.appAdsTxt && !cfg.ads.appAdsTxt.every(l => typeof l === 'string' && l.split(',').length >= 3)) e.push('ads.appAdsTxt: lines like "example-network.com, pub-123, DIRECT, abc123"'); @@ -378,7 +355,6 @@ export function validateConfig(c: unknown): string[] { if (!(o.price > 0)) e.push(`${at}.overrides: price must be positive`); } } - if (cfg.prices?.baseTerritory && !/^[A-Z]{3}$/.test(cfg.prices.baseTerritory)) e.push('prices.baseTerritory: App Store territory, alpha-3 (USA)'); if (cfg.dataSafety) { for (const [t, u] of Object.entries(cfg.dataSafety.data ?? {})) { if (!/^PSL_[A-Z_]+$/.test(t)) e.push(`dataSafety.data.${t}: use the Play type id (PSL_DEVICE_ID, ...)`); diff --git a/cli/lib/csv.ts b/cli/lib/csv.ts deleted file mode 100644 index f39b6a1..0000000 --- a/cli/lib/csv.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Small RFC 4180 CSV reader / writer (quotes, doubled quotes, CR LF, a UTF-8 BOM). Pure. Used for tester lists, -// price sheets and the Play statistics exports. -import { csvCell } from './data-safety'; - -/** Rows of cells. Empty lines are dropped. */ -export function parseCsv(text: string, sep = ','): string[][] { - const rows: string[][] = []; - let row: string[] = []; - let cell = ''; - let quoted = false; - const s = text.replace(/^/, ''); - for (let i = 0; i < s.length; i++) { - const ch = s[i]!; - if (quoted) { - if (ch === '"') { if (s[i + 1] === '"') { cell += '"'; i++; } else quoted = false; } - else cell += ch; - continue; - } - if (ch === '"' && cell === '') { quoted = true; continue; } - if (ch === sep) { row.push(cell); cell = ''; continue; } - if (ch === '\n' || ch === '\r') { - if (ch === '\r' && s[i + 1] === '\n') i++; - row.push(cell); cell = ''; - if (row.some(c => c !== '')) rows.push(row); - row = []; - continue; - } - cell += ch; - } - row.push(cell); - if (row.some(c => c !== '')) rows.push(row); - return rows; -} - -/** Header row -> objects keyed by the lower-cased, trimmed header (spaces and dashes become "_"). */ -export function parseCsvRecords(text: string, sep = ','): Record[] { - const [head, ...rest] = parseCsv(text, sep); - if (!head) return []; - const keys = head.map(h => h.trim().toLowerCase().replace(/[\s-]+/g, '_')); - return rest.map(r => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? '').trim()]))); -} - -export const toCsv = (rows: (string | number)[][]): string => rows.map(r => r.map(c => csvCell(String(c))).join(',')).join('\n') + '\n'; diff --git a/cli/lib/frontmatter.ts b/cli/lib/frontmatter.ts deleted file mode 100644 index f9e0f22..0000000 --- a/cli/lib/frontmatter.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Minimal front matter for the local Markdown drafts storebound writes (review replies): "---", one `key: value` per -// line (strings, numbers, true / false, null; strings JSON-quoted when needed), "---", then the body. Pure. - -export type FmValue = string | number | boolean | null; - -export function parseFrontMatter(text: string): { data: Record; body: string } { - const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text); - if (!m) return { data: {}, body: text }; - const data: Record = {}; - for (const line of m[1]!.split(/\r?\n/)) { - const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line); - if (!kv) continue; - data[kv[1]!] = scalar(kv[2]!.trim()); - } - return { data, body: text.slice(m[0].length) }; -} - -function scalar(v: string): FmValue { - if (v === 'true') return true; - if (v === 'false') return false; - if (v === 'null' || v === '~' || v === '') return null; - if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v); - if (v.startsWith('"')) { try { return JSON.parse(v) as string; } catch { return v; } } - if (v.startsWith("'") && v.endsWith("'")) return v.slice(1, -1).replace(/''/g, "'"); - return v; -} - -const plain = (s: string) => /^[\w./@+-][\w ./@:+-]*$/.test(s) && !/^(true|false|null|~|-?\d+(\.\d+)?)$/.test(s) && !/ $/.test(s); - -export function stringifyFrontMatter(data: Record, body: string): string { - const lines = Object.entries(data).filter(([, v]) => v !== undefined) - .map(([k, v]) => `${k}: ${v === null ? 'null' : typeof v === 'string' ? (plain(v) ? v : JSON.stringify(v)) : String(v)}`); - return `---\n${lines.join('\n')}\n---\n${body.startsWith('\n') ? body : '\n' + body}`; -} diff --git a/cli/lib/google-auth.ts b/cli/lib/google-auth.ts index 106f798..9d8843e 100644 --- a/cli/lib/google-auth.ts +++ b/cli/lib/google-auth.ts @@ -2,10 +2,6 @@ import type { ServiceAccount } from './credentials'; export const PLAY_SCOPE = 'https://www.googleapis.com/auth/androidpublisher'; -/** Play Developer Reporting API (vitals): https://developers.google.com/play/developer/reporting/reference/rest */ -export const REPORTING_SCOPE = 'https://www.googleapis.com/auth/playdeveloperreporting'; -/** Cloud Storage read-only (Play statistics exports in the pubsite_prod_rev_ bucket). */ -export const STORAGE_READ_SCOPE = 'https://www.googleapis.com/auth/devstorage.read_only'; const b64u = (b: ArrayBuffer | string): string => Buffer.from(typeof b === 'string' ? b : new Uint8Array(b)).toString('base64url'); function pemToDer(pem: string): ArrayBuffer { @@ -24,12 +20,12 @@ export async function signAssertion(sa: ServiceAccount, nowS: number, scope = PL } /** Cached access token getter (refreshes 5 minutes before expiry). */ -export function tokenSource(sa: ServiceAccount, scope = PLAY_SCOPE): () => Promise { +export function tokenSource(sa: ServiceAccount): () => Promise { let token = ''; let until = 0; return async () => { if (token && Date.now() < until) return token; - const assertion = await signAssertion(sa, Math.floor(Date.now() / 1000), scope); + const assertion = await signAssertion(sa, Math.floor(Date.now() / 1000)); const r = await fetch(sa.token_uri || 'https://oauth2.googleapis.com/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, diff --git a/cli/lib/health.ts b/cli/lib/health.ts deleted file mode 100644 index a5b618a..0000000 --- a/cli/lib/health.ts +++ /dev/null @@ -1,253 +0,0 @@ -// Crash and vitals health of a released game, as pure parts: request builders, response parsers, threshold findings -// and the report. `storebound health` and `storebound validate` collect the data (read-only) and use these. -// -// Google Play Developer Reporting API v1beta1 (scope playdeveloperreporting; the service account needs "View app -// information (read-only)" for the app in Play Console, and the API enabled in its Cloud project): -// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.crashrate -// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.anrrate -// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.issues/search -// DAILY timelines only take the America/Los_Angeles time zone, dates without hours; endTime is exclusive. -// Bad behavior thresholds (user-perceived, 28-day average, checked daily): crash 1.09 %, ANR 0.47 % overall; 8 % on a -// single phone model. https://developer.android.com/topic/performance/vitals and Play Console Help answer 9844486 -// https://support.google.com/googleplay/android-developer/answer/9844486 -// App Store Connect (power and performance, read-only): -// https://developer.apple.com/documentation/appstoreconnectapi/power-and-performance-metrics-and-logs -// GET /v1/apps/{id}/perfPowerMetrics (application/vnd.apple.xcode-metrics+json), GET /v1/builds/{id}/diagnosticSignatures -// (HANGS, DISK_WRITES, LAUNCHES), GET /v1/apps/{id}/betaFeedbackCrashSubmissions (TestFlight crash reports, API 4.0+). -import type { Finding, Level } from './validate-rules'; -import { mdTable, pct, textTable } from './table'; - -export const PLAY_THRESHOLDS = { crash: 0.0109, anr: 0.0047, perDevice: 0.08 } as const; -/** Warn when a rate reaches this share of its threshold. */ -export const WARN_AT = 0.8; - -export const CRASH_METRICS = ['userPerceivedCrashRate', 'userPerceivedCrashRate28dUserWeighted', 'crashRate', 'distinctUsers'] as const; -export const ANR_METRICS = ['userPerceivedAnrRate', 'userPerceivedAnrRate28dUserWeighted', 'anrRate', 'distinctUsers'] as const; - -export interface Ymd { year: number; month: number; day: number } -const LA = { id: 'America/Los_Angeles' }; - -/** Calendar date `days` before `d` (UTC arithmetic on the date only). */ -export function ymd(d: Date, minusDays = 0): Ymd { - const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - minusDays)); - return { year: t.getUTCFullYear(), month: t.getUTCMonth() + 1, day: t.getUTCDate() }; -} -export const ymdString = (x: Ymd): string => `${x.year}-${String(x.month).padStart(2, '0')}-${String(x.day).padStart(2, '0')}`; - -/** Body of POST v1beta1/apps/{package}/{crashRate|anrRate}MetricSet:query: a DAILY timeline [end - days, end). */ -export function metricQuery(metrics: readonly string[], end: Ymd, days: number, dimensions: string[] = []): Record { - const start = ymd(new Date(Date.UTC(end.year, end.month - 1, end.day)), days); - return { - timelineSpec: { aggregationPeriod: 'DAILY', startTime: { ...start, timeZone: LA }, endTime: { ...end, timeZone: LA } }, - ...(dimensions.length ? { dimensions } : {}), - metrics: [...metrics], - pageSize: 100000, - }; -} - -/** Latest complete day of a metric set (freshnessInfo.freshnesses[DAILY].latestEndTime, exclusive). */ -export function latestDailyEnd(metricSet: { freshnessInfo?: { freshnesses?: { aggregationPeriod?: string; latestEndTime?: Partial }[] } }): Ymd | null { - const f = metricSet.freshnessInfo?.freshnesses?.find(x => x.aggregationPeriod === 'DAILY')?.latestEndTime; - return f?.year && f.month && f.day ? { year: f.year, month: f.month, day: f.day } : null; -} - -export interface MetricRow { date: string; dims: Record; values: Record } - -interface ApiRow { - startTime?: Partial; - dimensions?: { dimension: string; stringValue?: string; int64Value?: string; valueLabel?: string }[]; - metrics?: { metric: string; decimalValue?: { value?: string } }[]; -} - -/** Query response rows -> plain rows (rates as fractions, e.g. 0.0109 = 1.09 %). */ -export function parseMetricRows(resp: { rows?: ApiRow[] }): MetricRow[] { - return (resp.rows ?? []).map(r => ({ - date: r.startTime?.year ? ymdString(r.startTime as Ymd) : '', - dims: Object.fromEntries((r.dimensions ?? []).map(d => [d.dimension, d.valueLabel ?? d.stringValue ?? d.int64Value ?? ''])), - values: Object.fromEntries((r.metrics ?? []).filter(m => m.decimalValue?.value !== undefined).map(m => [m.metric, Number(m.decimalValue!.value)])), - })).sort((a, b) => a.date.localeCompare(b.date)); -} - -/** errorIssues:search query string: the top issues of a window, most reports first. */ -export function issuesQuery(end: Ymd, days: number, o: { type?: 'CRASH' | 'ANR'; pageSize?: number } = {}): string { - const start = ymd(new Date(Date.UTC(end.year, end.month - 1, end.day)), days); - const p = new URLSearchParams(); - for (const [k, v] of Object.entries({ start, end })) { - const x = v as Ymd; - p.set(`interval.${k}Time.year`, String(x.year)); p.set(`interval.${k}Time.month`, String(x.month)); p.set(`interval.${k}Time.day`, String(x.day)); - p.set(`interval.${k}Time.timeZone.id`, LA.id); - } - if (o.type) p.set('filter', `errorIssueType = ${o.type}`); - p.set('orderBy', 'errorReportCount desc'); - p.set('pageSize', String(o.pageSize ?? 10)); - return p.toString(); -} - -export interface Issue { type: string; cause: string; location: string; reports: number; users: number; lastVersion?: string; uri?: string } - -export function parseIssues(resp: { errorIssues?: { type?: string; cause?: string; location?: string; errorReportCount?: string; distinctUsers?: string; lastAppVersion?: { versionCode?: string }; issueUri?: string }[] }): Issue[] { - return (resp.errorIssues ?? []).map(i => ({ type: i.type === 'APPLICATION_NOT_RESPONDING' ? 'ANR' : i.type ?? '?', cause: i.cause ?? '', location: i.location ?? '', - reports: Number(i.errorReportCount ?? 0), users: Number(i.distinctUsers ?? 0), lastVersion: i.lastAppVersion?.versionCode, uri: i.issueUri })); -} - -export interface PlayHealth { - window: { start: string; end: string; days: number }; - crash: MetricRow[]; - anr: MetricRow[]; - /** Worst device models by user-perceived crash / ANR rate over the window (optional). */ - devices?: { model: string; crash?: number; anr?: number; users?: number }[]; - issues: Issue[]; -} - -export interface AppleHealth { - /** Latest values per metric identifier (e.g. hangRate, launchTime) from perfPowerMetrics, with the app version. */ - metrics: { category: string; metric: string; unit: string; version: string; value: number; goal?: string }[]; - /** Top diagnostic signatures of the latest builds. */ - signatures: { build: string; type: string; signature: string; weight: number }[]; - /** TestFlight crash submissions in the window (count per build). */ - betaCrashes: { build: string; count: number }[]; -} - -export interface HealthSnapshot { date: string; play?: PlayHealth | { error: string }; apple?: AppleHealth | { error: string } } - -/** Last value of a metric over the rows (the 28-day rolling metrics: the latest row is the store's current view). */ -export function lastValue(rows: MetricRow[], metric: string): number | null { - for (let i = rows.length - 1; i >= 0; i--) { const v = rows[i]!.values[metric]; if (v !== undefined && !Number.isNaN(v)) return v; } - return null; -} - -/** Distinct-users-weighted average of a daily metric. */ -export function weightedAverage(rows: MetricRow[], metric: string): number | null { - let num = 0, den = 0; - for (const r of rows) { const v = r.values[metric], u = r.values.distinctUsers ?? 1; if (v === undefined) continue; num += v * u; den += u; } - return den ? num / den : null; -} - -/** Per device model over the window: users-weighted user-perceived crash / ANR rates, only models with at least - * `minUsers` (summed daily distinct users, so small samples do not raise alarms), worst first, top `n`. */ -export function deviceBreakdown(crash: MetricRow[], anr: MetricRow[], o: { minUsers?: number; n?: number } = {}): NonNullable { - const agg = new Map(); - const add = (rows: MetricRow[], metric: string, which: 'c' | 'a') => { - for (const r of rows) { - const m = r.dims.deviceModel; - const v = r.values[metric], u = r.values.distinctUsers ?? 0; - if (!m || v === undefined) continue; - const x = agg.get(m) ?? { cn: 0, cd: 0, an: 0, ad: 0 }; - if (which === 'c') { x.cn += v * u; x.cd += u; } else { x.an += v * u; x.ad += u; } - agg.set(m, x); - } - }; - add(crash, 'userPerceivedCrashRate', 'c'); - add(anr, 'userPerceivedAnrRate', 'a'); - return [...agg.entries()].filter(([, x]) => Math.max(x.cd, x.ad) >= (o.minUsers ?? 500)) - .map(([model, x]) => ({ model, crash: x.cd ? x.cn / x.cd : undefined, anr: x.ad ? x.an / x.ad : undefined, users: Math.max(x.cd, x.ad) })) - .sort((a, b) => Math.max(b.crash ?? 0, b.anr ?? 0) - Math.max(a.crash ?? 0, a.anr ?? 0)).slice(0, o.n ?? 5); -} - -/** TestFlight crash submissions -> count per build number within [since, now]. */ -export function betaCrashCounts(subs: { attributes?: { createdDate?: string }; relationships?: { build?: { data?: { id: string } } } }[], builds: Map, since: string): AppleHealth['betaCrashes'] { - const n = new Map(); - for (const s of subs) { - if ((s.attributes?.createdDate ?? '') < since) continue; - const b = builds.get(s.relationships?.build?.data?.id ?? '') ?? '?'; - n.set(b, (n.get(b) ?? 0) + 1); - } - return [...n.entries()].map(([build, count]) => ({ build, count })).sort((a, b) => b.count - a.count); -} - -/** perfPowerMetrics (xcode-metrics JSON) -> latest point per metric. */ -export function parsePerfPower(j: { productData?: { metricCategories?: { identifier?: string; metrics?: { identifier?: string; unit?: { displayName?: string; identifier?: string }; datasets?: { filterCriteria?: { device?: string; percentile?: string }; points?: { version?: string; value?: number; goal?: string }[] }[] }[] }[] }[] }): AppleHealth['metrics'] { - const out: AppleHealth['metrics'] = []; - for (const p of j.productData ?? []) for (const c of p.metricCategories ?? []) for (const m of c.metrics ?? []) { - const ds = (m.datasets ?? []).find(d => (d.filterCriteria?.device ?? 'all_iphones') === 'all_iphones' && /fifty|50|typical/i.test(d.filterCriteria?.percentile ?? 'percentile.fifty')) ?? m.datasets?.[0]; - const pt = ds?.points?.at(-1); - if (!pt || pt.value === undefined) continue; - out.push({ category: c.identifier ?? '', metric: m.identifier ?? '', unit: m.unit?.displayName ?? m.unit?.identifier ?? '', version: pt.version ?? '', value: pt.value, goal: pt.goal }); - } - return out; -} - -const levelFor = (v: number | null, limit: number): Level => (v === null ? 'ok' : v >= limit ? 'blocker' : v >= limit * WARN_AT ? 'warn' : 'ok'); - -/** Health -> validate findings. Over a Play bad behavior threshold = blocker (Play lowers discoverability and may - * warn users on the listing), from 80 % of it = warn. Apple publishes no thresholds: "poor" goals and heavy - * diagnostic signatures are warnings. */ -export function healthFindings(h: HealthSnapshot, o: { unreadable?: Level } = {}): Finding[] { - const f: Finding[] = []; - const play = h.play; - if (play && 'error' in play) f.push({ store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${play.error.slice(0, 200)}`, fix: 'store-health skill (Reporting API access)' }); - else if (play) { - const crash = lastValue(play.crash, 'userPerceivedCrashRate28dUserWeighted') ?? weightedAverage(play.crash, 'userPerceivedCrashRate'); - const anr = lastValue(play.anr, 'userPerceivedAnrRate28dUserWeighted') ?? weightedAverage(play.anr, 'userPerceivedAnrRate'); - const fix = 'storebound health; fix the top issues, ship a build with a higher versionCode (store-health skill)'; - if (crash === null && anr === null) f.push({ store: 'play', level: 'ok', code: 'vitals', msg: 'no vitals data yet (too few users or no release)' }); - else { - f.push({ store: 'play', level: levelFor(crash, PLAY_THRESHOLDS.crash), code: 'vitals-crash', msg: `user-perceived crash rate (28 d) ${pct(crash)} (bad behavior threshold ${pct(PLAY_THRESHOLDS.crash)})`, fix }); - f.push({ store: 'play', level: levelFor(anr, PLAY_THRESHOLDS.anr), code: 'vitals-anr', msg: `user-perceived ANR rate (28 d) ${pct(anr)} (bad behavior threshold ${pct(PLAY_THRESHOLDS.anr)})`, fix }); - } - for (const d of play.devices ?? []) { - const worst = Math.max(d.crash ?? 0, d.anr ?? 0); - const lv = levelFor(worst, PLAY_THRESHOLDS.perDevice); - if (lv !== 'ok') f.push({ store: 'play', level: lv, code: 'vitals-device', msg: `${d.model}: crash ${pct(d.crash ?? null)}, ANR ${pct(d.anr ?? null)} (per-device threshold ${pct(PLAY_THRESHOLDS.perDevice)})`, fix }); - } - } - const apple = h.apple; - if (apple && 'error' in apple) f.push({ store: 'apple', level: o.unreadable ?? 'warn', code: 'diagnostics', msg: `diagnostics not readable: ${apple.error.slice(0, 200)}` }); - else if (apple) { - const poor = apple.metrics.filter(m => m.goal === 'poor'); - for (const m of poor) f.push({ store: 'apple', level: 'warn', code: 'perf', msg: `${m.metric} ${m.value} ${m.unit} on ${m.version}: Apple rates it poor`, fix: 'Xcode Organizer > Metrics; store-health skill' }); - const heavy = apple.signatures.filter(s => s.weight >= 0.25); - for (const s of heavy) f.push({ store: 'apple', level: 'warn', code: 'diagnostics', msg: `build ${s.build} ${s.type}: ${s.signature.slice(0, 120)} (${Math.round(s.weight * 100)} % of reports)`, fix: 'Xcode Organizer > Hangs / Disk Writes / Launches' }); - if (!poor.length && !heavy.length) f.push({ store: 'apple', level: 'ok', code: 'diagnostics', msg: `${apple.metrics.length} metrics, ${apple.signatures.length} diagnostic signatures, nothing rated poor` }); - } - return f; -} - -/** Terminal summary table of a snapshot. */ -export function healthTable(h: HealthSnapshot): string { - const rows: (string | number)[][] = []; - if (h.play && !('error' in h.play)) { - const p = h.play; - rows.push(['play', 'crash rate (user-perceived, 28 d)', pct(lastValue(p.crash, 'userPerceivedCrashRate28dUserWeighted')), pct(PLAY_THRESHOLDS.crash)]); - rows.push(['play', `crash rate (user-perceived, ${p.window.days} d avg)`, pct(weightedAverage(p.crash, 'userPerceivedCrashRate')), '']); - rows.push(['play', 'ANR rate (user-perceived, 28 d)', pct(lastValue(p.anr, 'userPerceivedAnrRate28dUserWeighted')), pct(PLAY_THRESHOLDS.anr)]); - rows.push(['play', `ANR rate (user-perceived, ${p.window.days} d avg)`, pct(weightedAverage(p.anr, 'userPerceivedAnrRate')), '']); - rows.push(['play', 'top issues', p.issues.length, '']); - } else if (h.play) rows.push(['play', 'error', h.play.error.slice(0, 80), '']); - if (h.apple && !('error' in h.apple)) { - for (const m of h.apple.metrics.slice(0, 12)) rows.push(['apple', `${m.metric} (${m.version})`, `${m.value} ${m.unit}`.trim(), m.goal ?? '']); - rows.push(['apple', 'diagnostic signatures', h.apple.signatures.length, '']); - rows.push(['apple', 'TestFlight crash reports', h.apple.betaCrashes.reduce((n, b) => n + b.count, 0), '']); - } else if (h.apple) rows.push(['apple', 'error', h.apple.error.slice(0, 80), '']); - return textTable(['store', 'metric', 'value', 'threshold / goal'], rows); -} - -/** Markdown report (weekly summary): table, findings, top issues, week-over-week change when `previous` is given. */ -export function healthMarkdown(h: HealthSnapshot, o: { appName: string; previous?: HealthSnapshot | null } = { appName: '' }): string { - const out: string[] = [`# Health report · ${o.appName} · ${h.date}`, '']; - const f = healthFindings(h); - const icon: Record = { blocker: 'OVER THRESHOLD', warn: 'watch', ok: 'ok' }; - out.push('## Summary', '', mdTable(['store', 'status', 'finding'], f.map(x => [x.store, icon[x.level], x.msg])), ''); - const p = h.play && !('error' in h.play) ? h.play : null; - const prev = o.previous?.play && !('error' in o.previous.play) ? o.previous.play : null; - if (p) { - out.push(`## Google Play vitals (${p.window.start} to ${p.window.end})`, ''); - const delta = (cur: number | null, old: number | null) => (cur === null || old === null ? '' : `${cur >= old ? '+' : ''}${((cur - old) * 100).toFixed(2)} pt`); - const c = weightedAverage(p.crash, 'userPerceivedCrashRate'), a = weightedAverage(p.anr, 'userPerceivedAnrRate'); - out.push(mdTable(['metric', 'this window', 'previous', 'change', 'threshold'], [ - ['user-perceived crash rate', pct(c), pct(prev ? weightedAverage(prev.crash, 'userPerceivedCrashRate') : null), delta(c, prev ? weightedAverage(prev.crash, 'userPerceivedCrashRate') : null), pct(PLAY_THRESHOLDS.crash)], - ['user-perceived ANR rate', pct(a), pct(prev ? weightedAverage(prev.anr, 'userPerceivedAnrRate') : null), delta(a, prev ? weightedAverage(prev.anr, 'userPerceivedAnrRate') : null), pct(PLAY_THRESHOLDS.anr)], - ]), ''); - if (p.issues.length) out.push('### Top issues', '', mdTable(['type', 'cause', 'location', 'reports', 'users', 'last versionCode'], - p.issues.map(i => [i.type, i.cause.slice(0, 80), i.location.slice(0, 80), i.reports, i.users, i.lastVersion ?? ''])), ''); - } - const ap = h.apple && !('error' in h.apple) ? h.apple : null; - if (ap) { - out.push('## App Store diagnostics', ''); - if (ap.metrics.length) out.push(mdTable(['category', 'metric', 'version', 'value', 'goal'], ap.metrics.map(m => [m.category, m.metric, m.version, `${m.value} ${m.unit}`.trim(), m.goal ?? ''])), ''); - if (ap.signatures.length) out.push('### Diagnostic signatures', '', mdTable(['build', 'type', 'signature', 'weight'], ap.signatures.map(s => [s.build, s.type, s.signature.slice(0, 100), `${Math.round(s.weight * 100)} %`])), ''); - if (ap.betaCrashes.length) out.push('### TestFlight crash reports', '', mdTable(['build', 'reports'], ap.betaCrashes.map(b => [b.build, b.count])), ''); - } - out.push('Sources: Play Developer Reporting API (vitals, 28-day user-weighted rates, America/Los_Angeles days) and App Store Connect power and performance metrics. Thresholds: developer.android.com/topic/performance/vitals.', ''); - return out.join('\n'); -} diff --git a/cli/lib/ppo.ts b/cli/lib/ppo.ts deleted file mode 100644 index e65f78f..0000000 --- a/cli/lib/ppo.ts +++ /dev/null @@ -1,77 +0,0 @@ -// App Store Product Page Optimization (PPO) through the App Store Connect API, as pure planners. The command -// (cli/apple/ppo.ts) reads the state, plans, prints on --dry and sends; start / stop ask first and are not MCP tools. -// Sources (checked October 2026): -// https://developer.apple.com/documentation/appstoreconnectapi/app-store-version-experiments -// POST /v2/appStoreVersionExperiments {name, platform, trafficProportion; app}; PATCH {name, started, -// trafficProportion}; GET /v1/apps/{id}/appStoreVersionExperimentsV2; states PREPARE_FOR_SUBMISSION, READY_FOR_REVIEW, -// WAITING_FOR_REVIEW, IN_REVIEW, ACCEPTED, APPROVED, REJECTED, COMPLETED, STOPPED. -// Treatments: POST /v1/appStoreVersionExperimentTreatments {name; appStoreVersionExperimentV2}; localizations: POST -// /v1/appStoreVersionExperimentTreatmentLocalizations {locale; appStoreVersionExperimentTreatment}; screenshot sets: -// POST /v1/appScreenshotSets with the appStoreVersionExperimentTreatmentLocalization relationship. -// App Store Connect Help (Product Page Optimization): up to 3 treatments; traffic proportion = share of users who -// see a treatment, split evenly; a test runs up to 90 days or until stopped and cannot be restarted; the app must be -// live; treatments not yet approved go through App Review with the next version. -// https://developer.apple.com/help/app-store-connect/create-product-page-optimization-tests/overview-of-product-page-optimization -import { type Req, one } from '../apple/jsonapi'; - -export const MAX_TREATMENTS = 3; -export const EDITABLE_STATES = ['PREPARE_FOR_SUBMISSION', 'READY_FOR_REVIEW', 'REJECTED']; -export const RUNNING_STATES = ['WAITING_FOR_REVIEW', 'IN_REVIEW', 'ACCEPTED', 'APPROVED']; -export const DONE_STATES = ['COMPLETED', 'STOPPED']; - -export interface Experiment { id: string; name: string; state: string; trafficProportion?: number; started?: boolean; startDate?: string | null; endDate?: string | null } - -export const experimentFromApi = (x: { id: string; attributes: Record }): Experiment => ({ - id: x.id, name: String(x.attributes.name ?? ''), state: String(x.attributes.state ?? ''), trafficProportion: x.attributes.trafficProportion as number | undefined, - startDate: (x.attributes.startDate as string | null | undefined) ?? null, endDate: (x.attributes.endDate as string | null | undefined) ?? null, -}); - -/** Problems with the create options. */ -export function checkCreate(variants: string[], traffic: number, known: string[]): string[] { - const e: string[] = []; - if (!variants.length) e.push('--variant [,]: which shots.variants become treatments'); - if (variants.length > MAX_TREATMENTS) e.push(`at most ${MAX_TREATMENTS} treatments per test`); - for (const v of variants) if (!known.includes(v)) e.push(`unknown variant "${v}" (${known.join(', ') || 'none in shots.variants'})`); - if (!(Number.isInteger(traffic) && traffic >= 1 && traffic <= 100)) e.push('--traffic: whole percent 1-100 (share of users who see a treatment, split evenly between treatments)'); - return e; -} - -export const defaultName = (variants: string[]): string => `storebound ${variants.join(' + ')}`.slice(0, 64); - -export const createExperimentReq = (appId: string, name: string, traffic: number): Req => ({ method: 'POST', path: '/v2/appStoreVersionExperiments', note: `experiment "${name}"`, - body: { data: { type: 'appStoreVersionExperiments', attributes: { name, platform: 'IOS', trafficProportion: traffic }, relationships: { app: one('apps', appId) } } } }); - -/** The experiment to work on: by name, else the one test that can still be edited. Never a finished one. */ -export function pickExperiment(list: Experiment[], name?: string): Experiment | null { - if (name) { - const hit = list.find(x => x.name === name); - if (hit && DONE_STATES.includes(hit.state)) throw new Error(`experiment "${name}" is ${hit.state} (a stopped or completed test cannot be restarted; create a new one)`); - return hit ?? null; - } - const open = list.filter(x => EDITABLE_STATES.includes(x.state)); - if (open.length > 1) throw new Error(`several experiments can be edited (${open.map(x => `"${x.name}"`).join(', ')}): pass --experiment `); - return open[0] ?? null; -} - -/** Treatments named after the variants that are missing. */ -export function planTreatments(experimentId: string, existing: { id: string; name: string }[], variants: string[]): Req[] { - const have = new Set(existing.map(t => t.name)); - const missing = variants.filter(v => !have.has(v)); - if (existing.length + missing.length > MAX_TREATMENTS) throw new Error(`a test takes at most ${MAX_TREATMENTS} treatments (has ${existing.length}, wants ${missing.length} more)`); - return missing.map(v => ({ method: 'POST', path: '/v1/appStoreVersionExperimentTreatments', note: `treatment "${v}"`, - body: { data: { type: 'appStoreVersionExperimentTreatments', attributes: { name: v }, relationships: { appStoreVersionExperimentV2: one('appStoreVersionExperiments', experimentId) } } } })); -} - -/** Treatment localizations for every App Store locale that is missing. */ -export function planTreatmentLocales(treatmentId: string, existing: string[], locales: string[]): Req[] { - return locales.filter(l => !existing.includes(l)).map(locale => ({ method: 'POST', path: '/v1/appStoreVersionExperimentTreatmentLocalizations', note: locale, - body: { data: { type: 'appStoreVersionExperimentTreatmentLocalizations', attributes: { locale }, relationships: { appStoreVersionExperimentTreatment: one('appStoreVersionExperimentTreatments', treatmentId) } } } })); -} - -/** PATCH started true / false. Starting sends unapproved treatments to App Review with the app; stopping is final. */ -export function startStopReq(e: Experiment, start: boolean): Req { - if (start && !EDITABLE_STATES.includes(e.state) && e.state !== 'APPROVED' && e.state !== 'ACCEPTED') throw new Error(`experiment "${e.name}" is ${e.state}: cannot start`); - if (!start && DONE_STATES.includes(e.state)) throw new Error(`experiment "${e.name}" is already ${e.state}`); - return { method: 'PATCH', path: `/v2/appStoreVersionExperiments/${e.id}`, note: `${start ? 'start' : 'stop'} "${e.name}"`, - body: { data: { type: 'appStoreVersionExperiments', id: e.id, attributes: { started: start } } } }; -} diff --git a/cli/lib/prices.ts b/cli/lib/prices.ts deleted file mode 100644 index 43fd12b..0000000 --- a/cli/lib/prices.ts +++ /dev/null @@ -1,227 +0,0 @@ -// Prices of in-app products as one CSV (product x store x region), as pure parts: parsing and checking the sheet, -// reading the current store prices into the same rows, the diff, and the request bodies `storebound prices import` -// sends after a confirmation. -// Sources (checked October 2026): -// Apple: price points GET /v2/inAppPurchases/{id}/pricePoints; schedule POST /v1/inAppPurchasePriceSchedules with -// baseTerritory + every manual price (startDate null = current, YYYY-MM-DD = scheduled change); a POST sends the -// whole manual schedule (Apple's "Update In-App Purchase prices" example sends the current and the future price -// together). https://developer.apple.com/documentation/appstoreconnectapi/managing-in-app-purchases -// Territories without a manual price follow the base territory (Apple equalizes them, "automatic prices"). -// Google Play: monetization.onetimeproducts PATCH (updateMask, regionsVersion.version, allowMissing) with -// purchaseOptions[].regionalPricingAndAvailabilityConfigs {regionCode, price Money in the region currency, -// availability}; pricing:convertRegionPrices for regions without a price. -// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.onetimeproducts -// Play has no scheduled prices: start_date is Apple only. -import { parseCsvRecords, toCsv } from './csv'; -import { ALPHA3, fromMoney, type Money, type RegionConfig, toMoney } from './money'; -import { textTable } from './table'; - -export interface PriceRow { - product: string; - store: 'apple' | 'play'; - /** ISO 3166-1 alpha-2 (Play region; Apple territory is looked up, or given as `territory`). */ - region: string; - territory?: string; - currency: string; - price: number; - /** Apple only: the date a scheduled price starts (YYYY-MM-DD); empty = the current price. */ - startDate?: string; - /** Exported Apple prices: "manual" (set by you) or "auto" (equalized from the base territory, read-only). */ - kind?: 'manual' | 'auto'; - /** Apple price point id when read from the store (not in the CSV). */ - pointId?: string; -} - -export const CSV_HEAD = ['product', 'store', 'region', 'currency', 'price', 'start_date', 'kind']; -const ALPHA2 = Object.fromEntries(Object.entries(ALPHA3).map(([a2, a3]) => [a3, a2])); -export const alpha2 = (territory: string): string => ALPHA2[territory] ?? territory; - -/** CSV -> rows. `store` may be apple, play or both (both = one row per store). Throws with every problem at once. */ -export function parsePriceCsv(text: string, o: { products?: string[]; today?: string } = {}): PriceRow[] { - const out: PriceRow[] = []; - const errors: string[] = []; - const seen = new Set(); - const today = o.today ?? new Date().toISOString().slice(0, 10); - for (const [i, r] of parseCsvRecords(text).entries()) { - const at = `row ${i + 2}`; - const product = r.product ?? ''; - const stores = (r.store || 'both').toLowerCase(); - const region = (r.region ?? '').toUpperCase(); - const currency = (r.currency ?? '').toUpperCase(); - const price = Number((r.price ?? '').replace(',', '.')); - const startDate = r.start_date || undefined; - const kind = r.kind === 'auto' ? 'auto' : r.kind === 'manual' || !r.kind ? 'manual' : undefined; - if (!/^[A-Za-z0-9._]+$/.test(product)) { errors.push(`${at}: product "${product}"`); continue; } - if (o.products && !o.products.includes(product)) errors.push(`${at}: ${product} is not in products[] of the config`); - if (!['apple', 'play', 'both'].includes(stores)) errors.push(`${at}: store must be apple, play or both`); - if (!/^[A-Z]{2}$/.test(region)) errors.push(`${at}: region "${r.region}" must be ISO alpha-2 (US, TR, ...)`); - if (!/^[A-Z]{3}$/.test(currency)) errors.push(`${at}: currency "${r.currency}" must be ISO 4217 (USD, TRY, ...)`); - if (!(price > 0)) errors.push(`${at}: price must be a positive number`); - if (!kind) errors.push(`${at}: kind must be manual or auto`); - if (startDate !== undefined) { - if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate)) errors.push(`${at}: start_date must be YYYY-MM-DD`); - else if (startDate <= today) errors.push(`${at}: start_date ${startDate} is not in the future (leave it empty for the current price)`); - if (stores !== 'apple') errors.push(`${at}: start_date is App Store only (Play has no scheduled prices): set store to apple`); - } - for (const store of stores === 'both' ? ['apple', 'play'] as const : [stores as 'apple' | 'play']) { - const key = `${product}|${store}|${region}|${startDate ?? ''}`; - if (seen.has(key)) errors.push(`${at}: ${product} ${store} ${region}${startDate ? ` ${startDate}` : ''} listed twice`); - seen.add(key); - if (store === 'apple' && !ALPHA3[region]) errors.push(`${at}: no App Store territory known for ${region}`); - out.push({ product, store, region, ...(store === 'apple' ? { territory: ALPHA3[region] } : {}), currency, price, ...(startDate ? { startDate } : {}), ...(kind === 'auto' ? { kind } : {}) }); - } - } - if (errors.length) throw new Error(`prices CSV: ${errors.join('; ')}`); - return out; -} - -export function pricesCsv(rows: PriceRow[]): string { - const sorted = [...rows].sort((a, b) => a.product.localeCompare(b.product) || a.store.localeCompare(b.store) || a.region.localeCompare(b.region) || (a.startDate ?? '').localeCompare(b.startDate ?? '')); - return toCsv([CSV_HEAD, ...sorted.map(r => [r.product, r.store, r.region, r.currency, fmt(r.price), r.startDate ?? '', r.kind ?? 'manual'])]); -} - -const fmt = (n: number) => (Math.round(n * 100) / 100).toFixed(2).replace(/\.00$/, ''); - -// ---- reading the stores into rows ---- - -interface ApplePricesResp { - data?: { attributes?: { startDate?: string | null; endDate?: string | null }; relationships?: { inAppPurchasePricePoint?: { data?: { id: string } }; territory?: { data?: { id: string } } } }[]; - included?: { type: string; id: string; attributes?: { customerPrice?: string; currency?: string } }[]; -} - -/** GET /v1/inAppPurchasePriceSchedules/{id}/manualPrices (or automaticPrices) ?include=inAppPurchasePricePoint,territory -> rows. */ -export function applePriceRows(product: string, resp: ApplePricesResp, kind: 'manual' | 'auto' = 'manual'): PriceRow[] { - const points = new Map((resp.included ?? []).filter(x => x.type === 'inAppPurchasePricePoints').map(x => [x.id, x.attributes?.customerPrice] as const)); - const curr = new Map((resp.included ?? []).filter(x => x.type === 'territories').map(x => [x.id, x.attributes?.currency] as const)); - const out: PriceRow[] = []; - for (const p of resp.data ?? []) { - const territory = p.relationships?.territory?.data?.id; - const price = Number(points.get(p.relationships?.inAppPurchasePricePoint?.data?.id ?? '') ?? NaN); - if (!territory || Number.isNaN(price)) continue; - out.push({ product, store: 'apple', region: alpha2(territory), territory, currency: curr.get(territory) ?? '', price, pointId: p.relationships?.inAppPurchasePricePoint?.data?.id, ...(p.attributes?.startDate ? { startDate: p.attributes.startDate } : {}), ...(kind === 'auto' ? { kind } : {}) }); - } - return out; -} - -export interface PlayProduct { - productId: string; - purchaseOptions?: { purchaseOptionId: string; state?: string; regionalPricingAndAvailabilityConfigs?: { regionCode: string; price?: Money; availability?: string }[]; newRegionsConfig?: unknown; [k: string]: unknown }[]; - [k: string]: unknown; -} - -export function playPriceRows(p: PlayProduct, optionId = 'buy'): PriceRow[] { - const o = p.purchaseOptions?.find(x => x.purchaseOptionId === optionId) ?? p.purchaseOptions?.[0]; - return (o?.regionalPricingAndAvailabilityConfigs ?? []).filter(c => c.price && c.availability !== 'NO_LONGER_AVAILABLE') - .map(c => ({ product: p.productId, store: 'play' as const, region: c.regionCode, currency: c.price!.currencyCode, price: fromMoney(c.price!) })); -} - -// ---- diff ---- - -export interface DiffRow { product: string; store: 'apple' | 'play'; region: string; startDate?: string; currency: string; from: number | null; to: number; change: 'new' | 'change' | 'same' } - -const key = (r: Pick) => `${r.product}|${r.store}|${r.region}|${r.startDate ?? ''}`; -const cents = (n: number) => Math.round(n * 100); - -/** Wanted rows (auto rows ignored) vs current rows. */ -export function diffPrices(current: PriceRow[], wanted: PriceRow[]): DiffRow[] { - const cur = new Map(current.filter(r => r.kind !== 'auto').map(r => [key(r), r] as const)); - const auto = new Map(current.filter(r => r.kind === 'auto').map(r => [key(r), r] as const)); - return wanted.filter(w => w.kind !== 'auto').map(w => { - const c = cur.get(key(w)); - // An equalized (auto) Apple price becomes a manual one: "new", shown with the equalized price as "current". - const from = c ? c.price : auto.get(key(w))?.price ?? null; - const change: DiffRow['change'] = !c ? 'new' : cents(c.price) === cents(w.price) && (!c.currency || c.currency === w.currency) ? 'same' : 'change'; - return { product: w.product, store: w.store, region: w.region, ...(w.startDate ? { startDate: w.startDate } : {}), currency: w.currency, from, to: w.price, change }; - }); -} - -export function diffTable(d: DiffRow[], o: { all?: boolean } = {}): string { - const rows = d.filter(x => o.all || x.change !== 'same').map(x => [x.product, x.store, x.region, x.startDate ?? 'now', x.currency, x.from === null ? '-' : fmt(x.from), fmt(x.to), - x.from ? `${x.to >= x.from ? '+' : ''}${(((x.to - x.from) / x.from) * 100).toFixed(1)}%` : x.change]); - return rows.length ? textTable(['product', 'store', 'region', 'from', 'currency', 'current', 'new', 'change'], rows) : 'no price changes'; -} - -// ---- Play: the regional configs to PATCH ---- - -/** - * Final regional configs of one product: CSV prices on top of the current ones; regions Play sells in that the product - * has no price for yet come from convertRegionPrices (USD base); `reconvert` also resets every region the CSV does not - * list to the converted price. Throws on a CSV region Play does not sell in or a currency that does not match it. - */ -export function playRegions(current: { regionCode: string; price?: Money; availability?: string }[], wanted: PriceRow[], converted: Record | null, o: { reconvert?: boolean } = {}): RegionConfig[] { - const conv = new Map(Object.values(converted ?? {}).map(r => [r.regionCode, r.price] as const)); - const cur = new Map(current.filter(c => c.price).map(c => [c.regionCode, c.price!] as const)); - const out = new Map(); - for (const code of new Set([...cur.keys(), ...conv.keys()])) { - const c = cur.get(code), v = conv.get(code); - const pick = o.reconvert ? v ?? c : c ?? v; - if (pick) out.set(code, pick); - } - for (const w of wanted) { - const known = cur.get(w.region) ?? conv.get(w.region); - if (!known && converted) throw new Error(`${w.product}: Play does not sell in region ${w.region}`); - if (known && known.currencyCode !== w.currency) throw new Error(`${w.product} ${w.region}: Play prices this region in ${known.currencyCode}, the CSV says ${w.currency}`); - out.set(w.region, toMoney(w.currency, w.price)); - } - return [...out.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([regionCode, price]) => ({ regionCode, availability: 'AVAILABLE' as const, price })); -} - -/** The product with its purchase option's regional configs replaced (output-only `state` dropped) for the PATCH. */ -export function playPatchBody(p: PlayProduct, regions: RegionConfig[], optionId = 'buy'): PlayProduct { - return { ...p, purchaseOptions: (p.purchaseOptions ?? []).map(o => { - const { state: _s, ...rest } = o; - return o.purchaseOptionId === optionId ? { ...rest, regionalPricingAndAvailabilityConfigs: regions } : rest; - }) }; -} - -// ---- Apple: the manual schedule to POST ---- - -export interface ScheduleEntry { territory: string; price: number; startDate: string | null } - -/** - * The full manual schedule after the import: territories the CSV names get exactly the CSV's entries (a row without - * start_date = the current price; dated rows = scheduled changes; dated rows alone keep the current price), every - * other territory keeps its entries. The base territory must end up with a current price. - */ -export function appleSchedule(current: PriceRow[], wanted: PriceRow[], base: string): ScheduleEntry[] { - const byTerr = new Map(); - for (const c of current.filter(r => r.kind !== 'auto')) byTerr.set(c.territory!, [...(byTerr.get(c.territory!) ?? []), { territory: c.territory!, price: c.price, startDate: c.startDate ?? null }]); - const touched = new Map(); - for (const w of wanted.filter(r => r.kind !== 'auto')) touched.set(w.territory!, [...(touched.get(w.territory!) ?? []), w]); - for (const [t, rows] of touched) { - const now = rows.find(r => !r.startDate); - const keepNow = (byTerr.get(t) ?? []).find(e => e.startDate === null); - const entries: ScheduleEntry[] = []; - if (now) entries.push({ territory: t, price: now.price, startDate: null }); - else if (keepNow) entries.push(keepNow); - for (const r of rows.filter(x => x.startDate).sort((a, b) => a.startDate!.localeCompare(b.startDate!))) entries.push({ territory: t, price: r.price, startDate: r.startDate! }); - byTerr.set(t, entries); - } - if (!(byTerr.get(base) ?? []).some(e => e.startDate === null)) throw new Error(`base territory ${base} needs a current price (a row without start_date)`); - return [...byTerr.values()].flat().sort((a, b) => (a.territory === base ? -1 : b.territory === base ? 1 : a.territory.localeCompare(b.territory)) || (a.startDate ?? '').localeCompare(b.startDate ?? '')); -} - -/** POST /v1/inAppPurchasePriceSchedules body. `points` maps "territory|price" to the price point id. */ -export function appleScheduleBody(iapId: string, base: string, entries: ScheduleEntry[], points: Map): Record { - const ids = entries.map((_, i) => `\${p${i}}`); - return { - data: { type: 'inAppPurchasePriceSchedules', relationships: { - inAppPurchase: { data: { type: 'inAppPurchases', id: iapId } }, - baseTerritory: { data: { type: 'territories', id: base } }, - manualPrices: { data: ids.map(id => ({ type: 'inAppPurchasePrices', id })) } } }, - included: entries.map((e, i) => { - const point = points.get(`${e.territory}|${cents(e.price)}`); - if (!point) throw new Error(`no price point id for ${e.territory} ${e.price}`); - return { type: 'inAppPurchasePrices', id: ids[i], attributes: { startDate: e.startDate }, - relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: iapId } }, inAppPurchasePricePoint: { data: { type: 'inAppPurchasePricePoints', id: point } } } }; - }), - }; -} - -/** Same schedule (ignoring order)? Then nothing is sent. */ -export function sameSchedule(a: ScheduleEntry[], b: ScheduleEntry[]): boolean { - const k = (x: ScheduleEntry[]) => x.map(e => `${e.territory}|${cents(e.price)}|${e.startDate ?? ''}`).sort().join(';'); - return k(a) === k(b); -} - -export const pointKey = (territory: string, price: number | string): string => `${territory}|${cents(Number(price))}`; diff --git a/cli/lib/reviews.ts b/cli/lib/reviews.ts deleted file mode 100644 index 4fa7411..0000000 --- a/cli/lib/reviews.ts +++ /dev/null @@ -1,155 +0,0 @@ -// Store review replies as pure parts: normalising both stores' reviews, the local draft files the owner / agent edit -// (.storebound/replies/-.md, front matter + the review + "## Reply"), and the checks a reply must pass -// before `storebound reviews send` sends it (only drafts with `approved: true`, after a confirmation). -// Sources (checked October 2026): -// App Store: GET /v1/apps/{id}/customerReviews, POST /v1/customerReviewResponses (one response per review; a new POST -// replaces it; it shows after up to 24 hours) https://developer.apple.com/documentation/appstoreconnectapi/customer-review-responses -// Guidance: https://developer.apple.com/app-store/responding-to-reviews/ (no personal info, marketing or spam) -// Length: Apple documents no maximum; 5970 characters is the limit App Store Connect is commonly reported to -// enforce (NOT VERIFIED), so storebound warns above it instead of blocking. -// Google Play: reviews.list returns reviews created or edited in the last week only; reviews.reply {replyText}, -// at most 350 characters (HTML tags stripped, not counted) https://developers.google.com/android-publisher/reply-to-reviews -import { len } from './copy'; -import { type FmValue, parseFrontMatter, stringifyFrontMatter } from './frontmatter'; - -export type ReviewStore = 'apple' | 'play'; -export const REPLY_LIMITS: Record = { play: 350, apple: 5970 }; - -export interface Review { - store: ReviewStore; - id: string; - rating: number; - title?: string; - body: string; - author?: string; - /** Apple: territory (alpha-3); Play: reviewer language. */ - where?: string; - date: string; - appVersion?: string; - reply?: { text: string; date?: string; state?: string }; -} - -interface AppleReviewsResp { - data?: { id: string; attributes: { rating?: number; title?: string; body?: string; reviewerNickname?: string; createdDate?: string; territory?: string }; relationships?: { response?: { data?: { id: string } | null } } }[]; - included?: { type: string; id: string; attributes?: { responseBody?: string; lastModifiedDate?: string; state?: string } }[]; -} - -export function parseAppleReviews(resp: AppleReviewsResp): Review[] { - const responses = new Map((resp.included ?? []).filter(x => x.type === 'customerReviewResponses').map(x => [x.id, x.attributes ?? {}] as const)); - return (resp.data ?? []).map(r => { - const resp1 = responses.get(r.relationships?.response?.data?.id ?? ''); - return { store: 'apple' as const, id: r.id, rating: r.attributes.rating ?? 0, title: r.attributes.title || undefined, body: r.attributes.body ?? '', - author: r.attributes.reviewerNickname, where: r.attributes.territory, date: r.attributes.createdDate ? new Date(r.attributes.createdDate).toISOString() : '', - ...(resp1?.responseBody ? { reply: { text: resp1.responseBody, date: resp1.lastModifiedDate, state: resp1.state } } : {}) }; - }); -} - -interface PlayReviewsResp { - reviews?: { reviewId: string; authorName?: string; comments?: { userComment?: { text?: string; lastModified?: { seconds?: string }; starRating?: number; reviewerLanguage?: string; appVersionName?: string }; - developerComment?: { text?: string; lastModified?: { seconds?: string } } }[] }[]; -} - -const isoFromSeconds = (s?: string) => (s ? new Date(Number(s) * 1000).toISOString() : ''); - -export function parsePlayReviews(resp: PlayReviewsResp): Review[] { - return (resp.reviews ?? []).map(r => { - const u = r.comments?.find(c => c.userComment)?.userComment ?? {}; - const d = r.comments?.find(c => c.developerComment)?.developerComment; - // A review with a separate title comes as "title\tbody". - const [title, body] = (u.text ?? '').includes('\t') ? (u.text ?? '').split('\t', 2) as [string, string] : [undefined, u.text ?? '']; - return { store: 'play' as const, id: r.reviewId, rating: u.starRating ?? 0, title: title?.trim() || undefined, body: body.trim(), author: r.authorName, - where: u.reviewerLanguage, date: isoFromSeconds(u.lastModified?.seconds), appVersion: u.appVersionName, - ...(d?.text ? { reply: { text: d.text, date: isoFromSeconds(d.lastModified?.seconds) } } : {}) }; - }); -} - -/** Reviews newer than `sinceIso`, optional filters, newest first. */ -export function filterReviews(rs: Review[], o: { since?: string; unanswered?: boolean; ratings?: number[] } = {}): Review[] { - return rs.filter(r => (!o.since || r.date >= o.since) && (!o.unanswered || !r.reply) && (!o.ratings?.length || o.ratings.includes(r.rating))) - .sort((a, b) => b.date.localeCompare(a.date)); -} - -/** File name of a draft: -.md with unsafe characters replaced. */ -export const draftName = (r: Pick): string => `${r.store}-${r.id.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120)}.md`; - -export const REPLY_PLACEHOLDER = ''; - -/** A new draft: front matter (approved: false), the review as a quote, an empty "## Reply" section. */ -export function draftMarkdown(r: Review): string { - const quote = (t: string) => t.split('\n').map(l => `> ${l}`).join('\n'); - const body = [ - `# ${'★'.repeat(Math.max(0, Math.min(5, r.rating)))}${'☆'.repeat(Math.max(0, 5 - r.rating))} ${r.title ?? ''}`.trimEnd(), '', - quote(r.body || '(no text)'), '', - `${r.where ? `${r.where} · ` : ''}${r.date.slice(0, 10)}${r.appVersion ? ` · version ${r.appVersion}` : ''}`, '', - ...(r.reply ? ['## Current reply', '', quote(r.reply.text), ''] : []), - '## Reply', '', REPLY_PLACEHOLDER, '', '', - ].join('\n'); - const meta: Record = { store: r.store, review_id: r.id, rating: r.rating, where: r.where ?? null, date: r.date, limit: REPLY_LIMITS[r.store], approved: false, sent: null }; - return stringifyFrontMatter(meta, body); -} - -export interface Draft { file: string; store: ReviewStore; reviewId: string; approved: boolean; sent: string | null; reply: string; meta: Record } - -/** A draft file -> its reply text (after "## Reply", HTML comments removed) and state. */ -export function parseDraft(file: string, text: string): Draft { - const { data, body } = parseFrontMatter(text); - const store = data.store; - if (store !== 'apple' && store !== 'play') throw new Error(`${file}: front matter "store" must be apple or play`); - if (!data.review_id) throw new Error(`${file}: front matter "review_id" missing`); - const at = body.search(/^## Reply\s*$/m); - const reply = at < 0 ? '' : body.slice(at).replace(/^## Reply\s*$/m, '').replace(//g, '').trim(); - return { file, store, reviewId: String(data.review_id), approved: data.approved === true, sent: typeof data.sent === 'string' ? data.sent : null, reply, meta: data }; -} - -/** Front matter `sent: ` (and approved kept) after a successful send. */ -export function markSent(text: string, iso: string): string { - const { data, body } = parseFrontMatter(text); - return stringifyFrontMatter({ ...data, sent: iso }, body); -} - -const INCENTIVE = [ - /\b(free|bonus|extra|gift|reward|compensat\w*)\b[^.!?\n]{0,40}\b(coins?|gems?|diamonds?|credits?|lives|items?|currency|refund)\b/i, - /\b(change|update|raise|edit|improve|revise)\s+(your\s+)?(rating|review|stars?|score)\b/i, - /\b(5|five)[ -]?stars?\b/i, - /\b(rate|review)\s+us\b/i, -]; - -export interface ReplyIssue { level: 'error' | 'warn'; msg: string } - -/** Problems with a reply before sending. Errors block `reviews send`; warnings are shown. */ -export function checkReply(reply: string, store: ReviewStore): ReplyIssue[] { - const e: ReplyIssue[] = []; - const text = store === 'play' ? reply.replace(/<[^>]*>/g, '') : reply; - if (!text.trim()) e.push({ level: 'error', msg: 'empty reply' }); - const n = len(text); - if (store === 'play' && n > REPLY_LIMITS.play) e.push({ level: 'error', msg: `${n} > ${REPLY_LIMITS.play} characters (Google Play limit)` }); - if (store === 'apple' && n > REPLY_LIMITS.apple) e.push({ level: 'warn', msg: `${n} characters: App Store Connect is reported to stop at ${REPLY_LIMITS.apple}` }); - if (INCENTIVE.some(re => re.test(text))) e.push({ level: 'error', msg: 'offers something for a rating or asks to change / give stars: not allowed (no incentives, no rating manipulation)' }); - if (/[^@\s]+@[^@\s]+\.[a-z]{2,}/i.test(text)) e.push({ level: 'warn', msg: 'contains an email address: only your public support address, never a player\'s' }); - if (/(\+?\d[\d\s().-]{7,}\d)/.test(text)) e.push({ level: 'warn', msg: 'contains a phone-like number: no personal data in public replies' }); - if (/https?:\/\//i.test(text)) e.push({ level: 'warn', msg: 'contains a link: support pages only, no marketing' }); - if (/[A-Z]{6,}/.test(text) || /!{3,}/.test(text)) e.push({ level: 'warn', msg: 'shouting (caps / !!!): keep it calm' }); - return e; -} - -/** Which drafts `send` would send, and why the others are skipped. */ -export function sendPlan(drafts: Draft[]): { send: Draft[]; skip: { file: string; why: string }[] } { - const send: Draft[] = []; - const skip: { file: string; why: string }[] = []; - for (const d of drafts) { - if (d.sent) { skip.push({ file: d.file, why: `already sent ${d.sent.slice(0, 10)}` }); continue; } - if (!d.approved) { skip.push({ file: d.file, why: 'not approved (set approved: true after reading it)' }); continue; } - const errors = checkReply(d.reply, d.store).filter(i => i.level === 'error'); - if (errors.length) { skip.push({ file: d.file, why: errors.map(i => i.msg).join('; ') }); continue; } - send.push(d); - } - return { send, skip }; -} - -/** The request that sends one reply. Apple: a POST replaces an earlier response; Play: :reply creates or updates. */ -export function replyRequest(d: Draft, packageName?: string): { method: 'POST'; url: string; body: unknown } { - if (d.store === 'apple') return { method: 'POST', url: '/v1/customerReviewResponses', body: { data: { type: 'customerReviewResponses', attributes: { responseBody: d.reply }, - relationships: { review: { data: { type: 'customerReviews', id: d.reviewId } } } } } }; - if (!packageName) throw new Error('play.packageName is not set'); - return { method: 'POST', url: `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}/reviews/${encodeURIComponent(d.reviewId)}:reply`, body: { replyText: d.reply } }; -} diff --git a/cli/lib/table.ts b/cli/lib/table.ts deleted file mode 100644 index d2f082c..0000000 --- a/cli/lib/table.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Aligned text tables for the terminal and Markdown tables for reports. Pure. - -export function textTable(head: string[], rows: (string | number)[][]): string { - const all = [head, ...rows.map(r => r.map(String))]; - const w = head.map((_, i) => Math.max(...all.map(r => [...(r[i] ?? '')].length))); - const line = (r: string[]) => r.map((c, i) => c + ' '.repeat(w[i]! - [...c].length)).join(' ').trimEnd(); - return [line(head), line(w.map(n => '-'.repeat(n))), ...all.slice(1).map(line)].join('\n'); -} - -const md = (c: string | number) => String(c).replace(/\|/g, '\\|').replace(/\n/g, ' '); -export function mdTable(head: string[], rows: (string | number)[][]): string { - return [`| ${head.map(md).join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map(r => `| ${r.map(md).join(' | ')} |`)].join('\n'); -} - -/** 0.01234 -> "1.23%" */ -export const pct = (x: number | null | undefined, digits = 2): string => (x === null || x === undefined || Number.isNaN(x) ? 'n/a' : `${(x * 100).toFixed(digits)}%`); diff --git a/cli/lib/testflight.ts b/cli/lib/testflight.ts deleted file mode 100644 index cb7d073..0000000 --- a/cli/lib/testflight.ts +++ /dev/null @@ -1,297 +0,0 @@ -// TestFlight through the App Store Connect API, as pure planners: what exists (read with GETs) + what the config / CSV -// wants -> the requests to send. The command (cli/apple/testflight.ts) reads, plans, prints the plan on --dry and sends. -// API references (checked October 2026): -// beta groups https://developer.apple.com/documentation/appstoreconnectapi/beta-groups -// beta testers https://developer.apple.com/documentation/appstoreconnectapi/beta-testers -// invitations https://developer.apple.com/documentation/appstoreconnectapi/beta-tester-invitations -// What to Test https://developer.apple.com/documentation/appstoreconnectapi/beta-build-localizations -// beta review https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-submissions -// test information https://developer.apple.com/documentation/appstoreconnectapi/beta-app-localizations -// https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-details -import { type Req, many, one } from '../apple/jsonapi'; -import { parseCsvRecords } from './csv'; -import { len } from './copy'; - -/** "What to Test" per build and locale (betaBuildLocalizations.whatsNew). Apple's API docs state no maximum; 4000 is - * assumed (the App Store "What's New" limit). NOT VERIFIED: keep it well below, testers read it on a phone. */ -export const WHAT_TO_TEST_LIMIT = 4000; -/** Beta App Review notes (betaAppReviewDetails.notes): "Review notes have a maximum of 4,000 characters." */ -export const BETA_NOTES_LIMIT = 4000; -/** Beta App Description (betaAppLocalizations.description) shown to external testers. */ -export const BETA_DESCRIPTION_LIMIT = 4000; - -export interface TfGroupSpec { - name: string; - /** Internal group (App Store Connect users of your team; no beta review). Default false = external. */ - internal?: boolean; - /** Internal groups only: every new build is available to the group automatically. */ - allBuilds?: boolean; - /** External groups only: public TestFlight link (anyone with the link can join, up to publicLinkLimit). */ - publicLink?: boolean; - publicLinkLimit?: number; - /** Testers can send feedback (screenshots, comments) from TestFlight. Default true. */ - feedback?: boolean; -} - -export interface TfConfig { - groups?: TfGroupSpec[]; - /** CSV of testers: email, first_name, last_name, groups (";"-separated group names). Must live in .storebound/ - * (gitignored): tester emails are personal data and never go into the repo. Default .storebound/testers.csv. */ - testers?: string; - /** Beta App Description per language id (or one text for every locale); shown to external testers. */ - description?: string | Record; - /** Notes for Beta App Review (where to find what, test account hints). The contact comes from - * .storebound/credentials.json reviewContact like for App Review. */ - reviewNotes?: string; -} - -export interface Group { id: string; name: string; internal: boolean; publicLinkEnabled?: boolean; publicLink?: string | null; hasAccessToAllBuilds?: boolean } - -export const groupFromApi = (g: { id: string; attributes: Record }): Group => ({ - id: g.id, name: String(g.attributes.name ?? ''), internal: g.attributes.isInternalGroup === true, - publicLinkEnabled: g.attributes.publicLinkEnabled as boolean | undefined, publicLink: (g.attributes.publicLink as string | null | undefined) ?? null, - hasAccessToAllBuilds: g.attributes.hasAccessToAllBuilds as boolean | undefined, -}); - -/** Problems with the testflight config. Pure. */ -export function validateTestflight(t: TfConfig | undefined): string[] { - if (!t) return []; - const e: string[] = []; - const names = new Set(); - for (const [i, g] of (t.groups ?? []).entries()) { - const at = `apple.testflight.groups[${i}]`; - if (!g.name || len(g.name) > 50) e.push(`${at}.name: 1-50 characters`); - if (names.has(g.name)) e.push(`${at}.name: duplicate "${g.name}"`); - names.add(g.name); - if (g.internal && (g.publicLink || g.publicLinkLimit !== undefined)) e.push(`${at}: public links are for external groups only`); - if (!g.internal && g.allBuilds !== undefined) e.push(`${at}.allBuilds: internal groups only (external builds go through beta review one by one)`); - if (g.publicLinkLimit !== undefined && !(Number.isInteger(g.publicLinkLimit) && g.publicLinkLimit >= 1 && g.publicLinkLimit <= 10000)) e.push(`${at}.publicLinkLimit: 1-10000`); - } - if (t.testers !== undefined && !/^\.storebound\//.test(t.testers.replace(/^\.\//, ''))) - e.push('apple.testflight.testers: keep the tester CSV in .storebound/ (gitignored); emails never go into the repo'); - return e; -} - -/** POST /v1/betaGroups for every configured group missing on App Store Connect (matched by name). Existing groups are - * never renamed, changed or deleted. */ -export function planGroups(appId: string, existing: Group[], want: TfGroupSpec[]): { create: Req[]; existing: string[] } { - const have = new Set(existing.map(g => g.name)); - const create: Req[] = want.filter(g => !have.has(g.name)).map(g => ({ - method: 'POST', path: '/v1/betaGroups', note: `${g.internal ? 'internal' : 'external'} group "${g.name}"`, - body: { data: { type: 'betaGroups', attributes: { - name: g.name, - ...(g.internal ? { isInternalGroup: true, hasAccessToAllBuilds: g.allBuilds ?? false } : {}), - ...(!g.internal && g.publicLink ? { publicLinkEnabled: true, publicLinkLimitEnabled: g.publicLinkLimit !== undefined, ...(g.publicLinkLimit !== undefined ? { publicLinkLimit: g.publicLinkLimit } : {}) } : {}), - feedbackEnabled: g.feedback ?? true, - }, relationships: { app: one('apps', appId) } } }, - })); - return { create, existing: want.filter(g => have.has(g.name)).map(g => g.name) }; -} - -export interface Tester { email: string; firstName?: string; lastName?: string; groups: string[] } - -const EMAIL = /^[^@\s,;]+@[^@\s,;]+\.[^@\s,;]+$/; - -/** Tester CSV -> testers. Columns (header row, any order): email, first_name (or firstname / first), last_name, - * groups (";"-separated group names; empty = `defaultGroup`). Throws on bad emails or duplicates. */ -export function parseTesters(csv: string, defaultGroup?: string): Tester[] { - const out: Tester[] = []; - const seen = new Set(); - const errors: string[] = []; - for (const [i, r] of parseCsvRecords(csv).entries()) { - const email = (r.email ?? '').toLowerCase(); - if (!EMAIL.test(email)) { errors.push(`row ${i + 2}: "${maskEmail(email)}" is not an email`); continue; } - if (seen.has(email)) { errors.push(`row ${i + 2}: ${maskEmail(email)} listed twice`); continue; } - seen.add(email); - const groups = (r.groups ?? r.group ?? '').split(';').map(s => s.trim()).filter(Boolean); - if (!groups.length && defaultGroup) groups.push(defaultGroup); - out.push({ email, firstName: r.first_name || r.firstname || r.first || undefined, lastName: r.last_name || r.lastname || r.last || undefined, groups }); - } - if (errors.length) throw new Error(`testers CSV: ${errors.join('; ')}`); - return out; -} - -/** "jane.doe@example.com" -> "j***@example.com": emails in logs and MCP output stay readable but not harvestable. */ -export function maskEmail(e: string): string { - const at = e.indexOf('@'); - if (at < 1) return '***'; - return `${e[0]}***${e.slice(at)}`; -} - -export interface TesterPlan { - /** New testers: POST /v1/betaTesters with their groups (Apple emails the invitation once a build is available). */ - create: Req[]; - /** Existing testers added to more groups: POST /v1/betaGroups/{id}/relationships/betaTesters. */ - add: Req[]; - /** Testers in a managed group but not in the CSV (only with remove): DELETE .../relationships/betaTesters. */ - remove: Req[]; - unknownGroups: string[]; - summary: string[]; -} - -/** - * Testers of the managed groups (those named in the CSV or `only`) vs the CSV. `existing` maps a beta tester (by - * lower-case email) to its id and current group ids. Removal only with `remove` (it ends their access to the builds - * of that group; the tester record itself is kept). - */ -export function planTesters(groups: Group[], existing: Map, want: Tester[], o: { remove?: boolean; only?: string[] } = {}): TesterPlan { - const byName = new Map(groups.map(g => [g.name, g] as const)); - const plan: TesterPlan = { create: [], add: [], remove: [], unknownGroups: [], summary: [] }; - const managed = new Set(o.only?.length ? o.only : want.flatMap(t => t.groups)); - for (const n of managed) if (!byName.has(n)) plan.unknownGroups.push(n); - const addTo = new Map(); - for (const t of want) { - const target = t.groups.filter(n => managed.has(n) && byName.has(n)).map(n => byName.get(n)!); - if (!target.length) continue; - const cur = existing.get(t.email); - if (!cur) { - plan.create.push({ method: 'POST', path: '/v1/betaTesters', note: `${maskEmail(t.email)} -> ${target.map(g => g.name).join(', ')}`, - body: { data: { type: 'betaTesters', attributes: { email: t.email, ...(t.firstName ? { firstName: t.firstName } : {}), ...(t.lastName ? { lastName: t.lastName } : {}) }, - relationships: { betaGroups: many('betaGroups', target.map(g => g.id)) } } } }); - continue; - } - for (const g of target) if (!cur.groupIds.includes(g.id)) addTo.set(g.id, [...(addTo.get(g.id) ?? []), cur.id]); - } - for (const [gid, ids] of addTo) { - const g = groups.find(x => x.id === gid)!; - plan.add.push({ method: 'POST', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} existing tester(s) -> "${g.name}"` }); - } - if (o.remove) { - const wanted = new Map>(); - for (const t of want) for (const n of t.groups) if (byName.has(n)) wanted.set(byName.get(n)!.id, (wanted.get(byName.get(n)!.id) ?? new Set()).add(t.email)); - const drop = new Map(); - for (const [email, cur] of existing) for (const gid of cur.groupIds) { - const g = groups.find(x => x.id === gid); - if (!g || !managed.has(g.name)) continue; - if (!wanted.get(gid)?.has(email)) drop.set(gid, [...(drop.get(gid) ?? []), cur.id]); - } - for (const [gid, ids] of drop) { - const g = groups.find(x => x.id === gid)!; - plan.remove.push({ method: 'DELETE', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} tester(s) leave "${g.name}"` }); - } - } - plan.summary.push(`${plan.create.length} new tester(s)`, `${plan.add.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} added to groups`, - `${plan.remove.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} removed from groups`); - return plan; -} - -/** POST /v1/betaTesterInvitations: (re)send the TestFlight invitation email of one tester for this app. */ -export const inviteReq = (appId: string, testerId: string, label: string): Req => ({ method: 'POST', path: '/v1/betaTesterInvitations', note: `invite ${label}`, - body: { data: { type: 'betaTesterInvitations', relationships: { app: one('apps', appId), betaTester: one('betaTesters', testerId) } } } }); - -/** POST /v1/betaGroups/{id}/relationships/builds for every group that does not have the build yet. */ -export function planDistribute(buildId: string, groups: Group[], buildGroupIds: string[]): Req[] { - return groups.filter(g => !buildGroupIds.includes(g.id) && !(g.internal && g.hasAccessToAllBuilds)).map(g => ({ method: 'POST', path: `/v1/betaGroups/${g.id}/relationships/builds`, - body: many('builds', [buildId]), note: `build -> ${g.internal ? 'internal' : 'external'} group "${g.name}"` })); -} - -/** - * "What to Test" texts for TestFlight per App Store locale from the App Store listing file: a `### whatToTest` block - * when a locale section has one, else its `### whatsNew` block (what `storebound whats-new` drafts). Pure. - */ -export function whatToTestFromListing(md: string): Record { - const out: Record = {}; - for (const sec of md.split(/^## /m).slice(1)) { - const locale = sec.split(/[\s·]/)[0]!.trim(); - if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(locale)) continue; - const block = (name: string) => new RegExp(`^### ${name}[^\\n]*\\n\`\`\`[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, 'm').exec(sec)?.[1]?.trim(); - const text = block('whatToTest') ?? block('whatsNew'); - if (text) out[locale] = text; - } - return out; -} - -/** betaBuildLocalizations to create (POST) or update (PATCH) so the build has exactly these texts. Locales on the - * build that are not in `want` are left alone. Throws when a text is over the limit. */ -export function planWhatToTest(buildId: string, existing: { id: string; locale: string; whatsNew?: string | null }[], want: Record): Req[] { - const tooLong = Object.entries(want).filter(([, t]) => len(t) > WHAT_TO_TEST_LIMIT).map(([l, t]) => `${l} ${len(t)}`); - if (tooLong.length) throw new Error(`What to Test over ${WHAT_TO_TEST_LIMIT} characters: ${tooLong.join(', ')}`); - const have = new Map(existing.map(l => [l.locale, l] as const)); - const out: Req[] = []; - for (const [locale, whatsNew] of Object.entries(want)) { - const cur = have.get(locale); - if (!cur) out.push({ method: 'POST', path: '/v1/betaBuildLocalizations', note: locale, - body: { data: { type: 'betaBuildLocalizations', attributes: { locale, whatsNew }, relationships: { build: one('builds', buildId) } } } }); - else if ((cur.whatsNew ?? '') !== whatsNew) out.push({ method: 'PATCH', path: `/v1/betaBuildLocalizations/${cur.id}`, note: locale, - body: { data: { type: 'betaBuildLocalizations', id: cur.id, attributes: { whatsNew } } } }); - } - return out; -} - -/** POST /v1/betaAppReviewSubmissions: send one build to Beta App Review (needed once per version for external - * testing; later builds of the same version are often approved automatically). */ -export const betaReviewReq = (buildId: string): Req => ({ method: 'POST', path: '/v1/betaAppReviewSubmissions', note: 'submit for Beta App Review', - body: { data: { type: 'betaAppReviewSubmissions', relationships: { build: one('builds', buildId) } } } }); - -/** Build states in which a build can be tested / sent to beta review. */ -export function betaReadiness(b: { processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null }, detail: { externalBuildState?: string; internalBuildState?: string } | null): string[] { - const p: string[] = []; - if (b.processingState !== 'VALID') p.push(`processing state ${b.processingState ?? 'unknown'} (wait for VALID)`); - if (b.expired) p.push('expired (TestFlight builds expire after 90 days)'); - if (b.usesNonExemptEncryption === null || b.usesNonExemptEncryption === undefined) { - if (detail?.internalBuildState === 'MISSING_EXPORT_COMPLIANCE' || detail?.externalBuildState === 'MISSING_EXPORT_COMPLIANCE') - p.push('export compliance missing (storebound apple encryption --build N)'); - } - return p; -} - -export interface BetaInfo { description?: string; feedbackEmail?: string; privacyPolicyUrl?: string; marketingUrl?: string } - -/** Test Information per locale (betaAppLocalizations): POST missing locales, PATCH changed fields. Apple requires a - * description on every beta app localization before a build can go to Beta App Review; fields cannot be cleared. */ -export function planBetaInfo(appId: string, existing: { id: string; locale: string; attributes: BetaInfo }[], want: Record): Req[] { - const have = new Map(existing.map(l => [l.locale, l] as const)); - const out: Req[] = []; - for (const [locale, w] of Object.entries(want)) { - const attrs = Object.fromEntries(Object.entries(w).filter(([, v]) => v !== undefined && v !== '')) as BetaInfo; - if (attrs.description && len(attrs.description) > BETA_DESCRIPTION_LIMIT) throw new Error(`beta description ${locale}: over ${BETA_DESCRIPTION_LIMIT} characters`); - const cur = have.get(locale); - if (!cur) { out.push({ method: 'POST', path: '/v1/betaAppLocalizations', note: locale, body: { data: { type: 'betaAppLocalizations', attributes: { locale, ...attrs }, relationships: { app: one('apps', appId) } } } }); continue; } - const changed = Object.fromEntries(Object.entries(attrs).filter(([k, v]) => (cur.attributes as Record)[k] !== v)); - if (Object.keys(changed).length) out.push({ method: 'PATCH', path: `/v1/betaAppLocalizations/${cur.id}`, note: locale, body: { data: { type: 'betaAppLocalizations', id: cur.id, attributes: changed } } }); - } - return out; -} - -export interface ReviewContactLike { firstName: string; lastName: string; phone: string; email: string } - -/** Beta App Review contact + notes (PATCH /v1/betaAppReviewDetails/{id}; the record exists for every app). */ -export function planBetaReviewDetail(detail: { id: string; attributes: Record } | null, contact: ReviewContactLike | null, notes?: string): Req[] { - if (!detail) return []; - if (notes && len(notes) > BETA_NOTES_LIMIT) throw new Error(`beta review notes: over ${BETA_NOTES_LIMIT} characters`); - const want: Record = { - ...(contact ? { contactFirstName: contact.firstName, contactLastName: contact.lastName, contactPhone: contact.phone, contactEmail: contact.email } : {}), - ...(notes ? { notes } : {}), - }; - const changed = Object.fromEntries(Object.entries(want).filter(([k, v]) => v && detail.attributes[k] !== v)); - return Object.keys(changed).length ? [{ method: 'PATCH', path: `/v1/betaAppReviewDetails/${detail.id}`, note: 'Beta App Review contact / notes', - body: { data: { type: 'betaAppReviewDetails', id: detail.id, attributes: changed } } }] : []; -} - -export interface ApiBuild { id: string; attributes: { version?: string; processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null; uploadedDate?: string }; marketing?: string } - -/** The one build with this number (CFBundleVersion), optionally of one marketing version. Never "the latest". */ -export function pickBuild(builds: ApiBuild[], number: string, marketing?: string): ApiBuild { - const hits = builds.filter(b => b.attributes.version === number && (!marketing || b.marketing === marketing)); - if (!hits.length) throw new Error(`no build ${number}${marketing ? ` of version ${marketing}` : ''} on App Store Connect (still processing? storebound apple status)`); - if (hits.length > 1) throw new Error(`build number ${number} exists for several versions (${hits.map(b => b.marketing ?? '?').join(', ')}): add --version x.y.z`); - return hits[0]!; -} - -/** Builds response with include=preReleaseVersion -> builds tagged with their marketing version. */ -export function buildsWithVersion(resp: { data?: ApiBuild[]; included?: { type: string; id: string; attributes?: { version?: string } }[] }): ApiBuild[] { - const pre = new Map((resp.included ?? []).filter(x => x.type === 'preReleaseVersions').map(x => [x.id, x.attributes?.version] as const)); - return (resp.data ?? []).map(b => ({ ...b, marketing: pre.get((b as unknown as { relationships?: { preReleaseVersion?: { data?: { id: string } } } }).relationships?.preReleaseVersion?.data?.id ?? '') })); -} - -/** Beta App Description per App Store locale from the config (a string = every locale). */ -export function betaDescriptions(t: TfConfig | undefined, langs: { id: string; apple?: string }[]): Record { - if (!t?.description) return {}; - const out: Record = {}; - for (const l of langs) { - if (!l.apple) continue; - const d = typeof t.description === 'string' ? t.description : t.description[l.id]; - if (d) out[l.apple] = d; - } - return out; -} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index a73c3c3..a555d21 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -42,42 +42,6 @@ export const TOOLS: ToolDef[] = [ description: 'Read-only readiness report for App Store Connect and/or Google Play with ordered blockers (build, encryption, metadata, screenshots, review details, age rating, prices, IAPs, privacy URL, app-ads.txt, tracks, products).', props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) }, - { name: 'health', title: 'Crash and vitals health', command: ['health'], write: false, network: true, - description: 'Read-only crash / ANR vitals from the Play Developer Reporting API (user-perceived rates vs the bad behavior thresholds 1.09 % / 0.47 %, worst device models, top issues) and App Store power and performance metrics, diagnostic signatures and TestFlight crash reports. Exit 1 when a metric is over a store threshold.', - props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' }, days: { type: 'integer', minimum: 1, maximum: 90, default: 7 } }, - args: i => [...(i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []), ...opt('days', i.days)] }, - { name: 'health_report', title: 'Weekly health report', command: ['health', '--weekly'], write: true, network: true, idempotent: true, - description: 'Weekly health summary as Markdown in .storebound/health/.md (plus .json for the next week-over-week comparison). Local files only; dry_run prints the report.', - props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, - args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) }, - { name: 'reviews_list', title: 'Store reviews', command: ['reviews', 'list'], write: false, network: true, - description: 'Read-only list of recent App Store and Google Play reviews (date, stars, territory / language, replied or not, text). Google Play only returns reviews from the last 7 days.', - props: { store: { type: 'string', enum: ['apple', 'play'], description: 'Default: both' }, days: { type: 'integer', minimum: 1, maximum: 365, default: 14 }, - unanswered: { type: 'boolean', default: false }, rating: { type: 'string', pattern: '^[1-5](,[1-5])*$', description: 'e.g. 1,2' } }, - args: i => [...opt('store', i.store), ...opt('days', i.days), ...flag('unanswered', i.unanswered), ...opt('rating', i.rating)] }, - { name: 'reviews_draft', title: 'Draft review replies', command: ['reviews', 'draft'], write: true, network: true, idempotent: true, - description: 'Write one local Markdown draft per unanswered review into .storebound/replies/-.md (approved: false; existing drafts are kept). Then write the reply under "## Reply" following the review-replies skill; the owner approves and sends from the terminal. Nothing is sent to a store.', - props: { store: { type: 'string', enum: ['apple', 'play'], description: 'Default: both' }, days: { type: 'integer', minimum: 1, maximum: 365, default: 14 }, - rating: { type: 'string', pattern: '^[1-5](,[1-5])*$', description: 'Only these star ratings, e.g. 1,2,3' } }, - args: i => [...opt('store', i.store), ...opt('days', i.days), ...opt('rating', i.rating)] }, - { name: 'prices_diff', title: 'Price sheet diff', command: ['prices', 'import'], write: false, network: true, - description: 'Read-only: compare the prices CSV (product, store, region, currency, price, start_date) with the current App Store and Google Play prices and print the diff table. Applying it is an owner-only terminal command (storebound prices import, asks first).', - props: { csv: { type: 'string', description: 'CSV path (default prices.csv in the config, else store/prices.csv)' }, store: { type: 'string', enum: ['apple', 'play'] }, only, all: { type: 'boolean', default: false, description: 'Also list unchanged rows' } }, - args: i => [...opt('csv', i.csv), ...opt('store', i.store), ...opt('only', i.only), ...flag('all', i.all), '--dry'] }, - { name: 'prices_export', title: 'Export prices to CSV', command: ['prices', 'export'], write: true, network: true, idempotent: true, - description: 'Read the current prices of every product on both stores and write them as the prices CSV (local file only; Apple equalized prices with with_automatic, marked kind=auto). dry_run prints the CSV.', - props: { out: { type: 'string', description: 'CSV path' }, store: { type: 'string', enum: ['apple', 'play'] }, only, with_automatic: { type: 'boolean', default: false } }, - args: i => [...opt('out', i.out), ...opt('store', i.store), ...opt('only', i.only), ...flag('with-automatic', i.with_automatic)] }, - { name: 'analytics_snapshot', title: 'Store analytics snapshot', command: ['analytics', 'snapshot'], write: true, network: true, idempotent: true, - description: 'Read store analytics (App Store: impressions, product page views, downloads via the Analytics Reports API; Google Play: store listing visitors, acquisitions, installs from the Play reports bucket) and write .storebound/analytics/.json. Local file only; dry_run reads and prints the totals.', - props: { days: { type: 'integer', minimum: 1, maximum: 120, default: 28 }, store: { type: 'string', enum: ['apple', 'play'] } }, - args: i => [...opt('days', i.days), ...opt('store', i.store)] }, - { name: 'analytics_compare', title: 'Analytics vs listing changes', command: ['analytics', 'compare'], write: false, network: false, - description: 'Offline: line the analytics snapshots up with the git history of the store files (listing text, screenshots, config) and show daily impressions / visitors and conversion in the days before vs after each change.', - props: { days: { type: 'integer', minimum: 1, maximum: 60, default: 7 }, md: { type: 'boolean', default: false, description: 'Markdown table' } }, - args: i => [...opt('days', i.days), ...flag('md', i.md)] }, - { name: 'analytics_setup', title: 'Start App Store analytics reports', command: ['analytics', 'setup'], write: true, network: true, idempotent: true, - description: 'Create the ONGOING App Store Connect analytics report request once (needs an Admin key; reports start 1-2 days later). Changes nothing public.' }, { name: 'apple_status', title: 'App Store status', command: ['apple', 'status'], write: false, network: true, description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' }, { name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true, @@ -146,7 +110,7 @@ export const TOOLS: ToolDef[] = [ args: i => [...opt('lang', i.lang), ...opt('only', i.only), ...opt('device', i.device), ...opt('source', i.source)] }, { name: 'shots_render', title: 'Render store screenshots', command: ['shots', 'render'], write: true, network: false, idempotent: true, description: 'Store screenshots + Play feature graphic in every size and language from the frames and the copy file (local PNGs, needs Playwright + ffmpeg; slow for many languages). dry_run lists what would be rendered.', - props: { lang, size: { type: 'string', description: 'Comma-separated size keys: ios69, ios65, iphone-medium, ipad13, play, tab7, tab10, feature' }, + props: { lang, size: { type: 'string', description: 'Comma-separated size keys: ios69, ios65, ipad13, play, tab7, tab10, feature' }, scenes: { type: 'string', description: 'Comma-separated scene ids' }, variant, all_variants: { type: 'boolean', default: false, description: 'Base + every variant' } }, args: i => [...opt('lang', i.lang), ...opt('size', i.size), ...opt('scenes', i.scenes), ...(i.all_variants === true ? ['--variants'] : opt('variant', i.variant))] }, { name: 'shots_gallery', title: 'Review gallery', command: ['shots', 'gallery'], write: true, network: false, idempotent: true, @@ -165,40 +129,12 @@ export const TOOLS: ToolDef[] = [ description: 'Sync app preview videos per locale to the editable App Store version (checked locally first; MD5-idempotent, changed sets are replaced; poster frame time code). Not public until the version is submitted and released. Slow: prefer the terminal with a log.', props: { only, poster: { type: 'integer', minimum: 0, maximum: 29, description: 'Poster frame second (default shots.video.poster or 5)' } }, args: i => [...opt('only', i.only), ...opt('poster', i.poster)] }, - { name: 'apple_testflight_status', title: 'TestFlight status', command: ['apple', 'testflight', 'status'], write: false, network: true, - description: 'Read-only TestFlight overview: beta groups (internal / external, tester and build counts, public link), recent builds with processing, internal and external beta states.' }, - { name: 'apple_testflight_groups', title: 'Create TestFlight groups', command: ['apple', 'testflight', 'groups'], write: true, network: true, idempotent: true, - description: 'Create the beta groups of apple.testflight.groups that are missing on App Store Connect (matched by name; existing groups are never changed or deleted). Sends nothing to testers.' }, - { name: 'apple_testflight_what_to_test', title: 'TestFlight What to Test', command: ['apple', 'testflight', 'what-to-test'], write: true, network: true, idempotent: true, - description: 'Set "What to Test" (betaBuildLocalizations) of one build, by its exact number, per locale from the App Store listing file (### whatToTest, else ### whatsNew) or from text.', - props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number (CFBundleVersion) you uploaded' }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'Marketing version when the build number repeats' }, - locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale with text)' }, text: { type: 'string', description: 'Same text for the given locales instead of the listing file' } }, - required: ['build'], args: i => [...opt('build', i.build), ...opt('version', i.version), ...opt('locale', i.locale), ...opt('text', i.text)] }, - { name: 'apple_testflight_info', title: 'TestFlight test information', command: ['apple', 'testflight', 'info'], write: true, network: true, idempotent: true, - description: 'Beta App Description per locale (apple.testflight.description), feedback email, privacy and marketing URLs, and the Beta App Review contact (.storebound/credentials.json) and notes. Needed before external testing.' }, - { name: 'apple_testflight_distribute', title: 'Build to internal TestFlight groups', command: ['apple', 'testflight', 'distribute'], write: true, network: true, idempotent: true, - description: 'Add one build (exact number) to INTERNAL beta groups (your App Store Connect team; they get the TestFlight notification). External groups and Beta App Review submissions are owner-only terminal commands.', - props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number you uploaded' }, groups: { type: 'string', description: 'Comma-separated internal group names' }, - version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } }, - required: ['build', 'groups'], args: i => [...opt('build', i.build), ...opt('group', i.groups), ...opt('version', i.version), '--internal-only'] }, - { name: 'apple_ppo_status', title: 'Product Page Optimization status', command: ['apple', 'ppo', 'status'], write: false, network: true, - description: 'Read-only list of App Store Product Page Optimization tests (state, traffic, dates) with their treatments, locales and screenshot counts. Results per treatment are only in App Store Connect.' }, - { name: 'apple_ppo_create', title: 'Create a PPO test', command: ['apple', 'ppo', 'create'], write: true, network: true, idempotent: true, - description: 'Create an App Store Product Page Optimization test (not started) with one treatment per shots variant (max 3) and a treatment localization per App Store locale. Starting it is an owner-only terminal command.', - props: { variants: { type: 'string', pattern: '^[a-z0-9][a-z0-9-]*(,[a-z0-9][a-z0-9-]*){0,2}$', description: 'Comma-separated shots.variants ids, e.g. b or b,c' }, - name: { type: 'string', description: 'Test name (default "storebound ")' }, traffic: { type: 'integer', minimum: 1, maximum: 100, default: 30, description: 'Percent of visitors who see a treatment' } }, - required: ['variants'], args: i => [...opt('variant', i.variants), ...opt('name', i.name), ...opt('traffic', i.traffic)] }, - { name: 'apple_ppo_upload', title: 'Upload PPO treatment screenshots', command: ['apple', 'ppo', 'upload'], write: true, destructive: true, network: true, idempotent: true, - description: 'Sync the screenshots of one shots variant (renders///...) into the matching treatment of the editable Product Page Optimization test, per locale (MD5-idempotent; changed sets are replaced). Nothing is shown to players until the owner starts the test.', - props: { variant, experiment: { type: 'string', description: 'Test name (default: the one editable test)' }, only }, - required: ['variant'], args: i => [...opt('variant', i.variant), ...opt('experiment', i.experiment), ...opt('only', i.only)] }, { name: 'icons', title: 'Generate icons', command: ['icons'], write: true, network: false, idempotent: true, description: 'Write every store / launcher / web icon from the artwork in the config (local files, needs ffmpeg).' }, ]; /** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */ -export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete', - '--submit-review', '--remove', '--invite', 'testers', 'send', 'start', 'stop']; +export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete']; export function inputSchema(t: ToolDef): Record { const props: Record = { ...(t.props ?? {}) }; diff --git a/cli/mcp.ts b/cli/mcp.ts index a6812af..a5694e7 100644 --- a/cli/mcp.ts +++ b/cli/mcp.ts @@ -1,21 +1,8 @@ -// `storebound mcp`: a stdio MCP server (tools only) that wraps the CLI, so any agent tool with MCP support (Claude Code, -// Codex, Gemini CLI, Cursor, VS Code / Copilot, Windsurf, OpenCode, ...) can call it. +// `storebound mcp`: a stdio MCP server (spec revision 2025-11-25, tools only) that wraps the CLI, so any agent tool +// with MCP support (Claude Code, Codex, Gemini CLI, Cursor, VS Code / Copilot, Windsurf, OpenCode, ...) can call it. // -// Dual-era, as the 2026-07-28 spec allows ("Versioning: Backward Compatibility with Initialization-Based Versions"): -// - modern 2026-07-28: no handshake. Every request carries `_meta["io.modelcontextprotocol/protocolVersion"]` and -// `_meta["io.modelcontextprotocol/clientCapabilities"]`; `server/discover` answers the supported versions, -// capabilities and instructions; results carry `resultType: "complete"` and -// `_meta["io.modelcontextprotocol/serverInfo"]`; tools/list is cacheable (ttlMs, cacheScope). An unknown version -// gets -32022 (UnsupportedProtocolVersionError, data { supported, requested }), a missing required _meta key -32602. -// https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning -// https://modelcontextprotocol.io/specification/2026-07-28/server/discover -// https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio -// - legacy 2025-11-25 (and 2025-06-18 / 2025-03-26 / 2024-11-05): initialize, notifications/initialized, ping and -// the results without resultType, as before. Requests without the per-request version are served this way. -// The server keeps no session state, so both eras can share one process. -// -// Why no SDK: newline-delimited JSON-RPC with a handful of methods is a few hundred lines and keeps storebound at -// zero runtime dependencies (the official SDK pulls in zod, express, ...). +// Why no SDK: the server needs initialize, ping, tools/list and tools/call over newline-delimited JSON-RPC. That is +// ~150 lines, and keeps storebound at zero runtime dependencies (the official SDK pulls in zod, express, ...). // // Every tool runs the CLI as a child process in the project directory (STOREBOUND_PROJECT or the server's cwd) and // returns its output. stdout of this process carries protocol messages only; logs go to stderr. @@ -24,28 +11,13 @@ import { join } from 'node:path'; import pkg from '../package.json' with { type: 'json' }; import { listTools, TOOLS, toArgv, validateInput } from './mcp-tools'; -/** Current (modern, stateless) revision. */ -export const PROTOCOL = '2026-07-28'; -export const MODERN = [PROTOCOL]; -/** Handshake-based revisions, answered through `initialize`. */ -export const LEGACY_PROTOCOL = '2025-11-25'; -export const LEGACY = [LEGACY_PROTOCOL, '2025-06-18', '2025-03-26', '2024-11-05']; -export const SUPPORTED = [...MODERN, ...LEGACY]; - -export const META = { - protocolVersion: 'io.modelcontextprotocol/protocolVersion', - clientCapabilities: 'io.modelcontextprotocol/clientCapabilities', - clientInfo: 'io.modelcontextprotocol/clientInfo', - serverInfo: 'io.modelcontextprotocol/serverInfo', -} as const; -export const UNSUPPORTED_PROTOCOL_VERSION = -32022; -/** The tool list never changes while the server runs; modern clients may cache it this long. */ -export const TOOLS_TTL_MS = 300_000; +export const PROTOCOL = '2025-11-25'; +export const SUPPORTED = [PROTOCOL, '2025-06-18', '2025-03-26', '2024-11-05']; export const INSTRUCTIONS = [ 'storebound ships mobile games to Google Play and the App Store.', 'Write tools default to dry_run: show the dry run to the owner and only call again with dry_run false after they agree.', - 'Nothing here submits for review, releases, cancels, deletes or sends anything public (review replies, tester invitations, price changes, experiment starts): tell the owner which terminal command or console click does that.', + 'Nothing here submits for review, releases, cancels or deletes: tell the owner which terminal command or console click does that.', 'Credentials come only from env or .storebound/ in the project; never ask for keys in chat or write them into files.', 'Run `check` (offline) and `validate` (read-only) before writes. Long uploads (images, screenshots) are better run in a terminal with a log.', ].join(' '); @@ -55,50 +27,27 @@ interface Msg { jsonrpc: '2.0'; id?: Id; method?: string; params?: Record ({ name: 'storebound', title: 'storebound', version: pkg.version }); - -/** Era of one request: modern when its _meta names a modern (or unknown) protocol version, else legacy. */ -export function eraOf(m: Msg): { era: 'modern' | 'legacy'; version: string | null } { - const meta = (m.params?._meta ?? {}) as Record; - const v = meta[META.protocolVersion]; - if (typeof v !== 'string') return { era: 'legacy', version: null }; - return { era: LEGACY.includes(v) ? 'legacy' : 'modern', version: v }; -} /** Handles one message; returns the response object (or null for notifications). Exported for tests. */ export async function handle(m: Msg, run: (argv: string[], id: Id) => Promise<{ code: number; out: string }> = runCli): Promise | null> { - const err = (code: number, message: string, data?: unknown) => ({ jsonrpc: '2.0', id: m.id ?? null, error: { code, message, ...(data === undefined ? {} : { data }) } }); + const ok = (result: unknown) => ({ jsonrpc: '2.0', id: m.id, result }); + const err = (code: number, message: string) => ({ jsonrpc: '2.0', id: m.id ?? null, error: { code, message } }); if (m.id === undefined) { if (m.method === 'notifications/cancelled') cancel(m.params?.requestId as Id); return null; // notifications/initialized and any other notification } - if (m.method === 'initialize') { - const asked = String(m.params?.protocolVersion ?? ''); - return { jsonrpc: '2.0', id: m.id, result: { - protocolVersion: LEGACY.includes(asked) ? asked : LEGACY_PROTOCOL, - capabilities: { tools: { listChanged: false } }, - serverInfo: { ...serverInfo(), description: pkg.description }, - instructions: INSTRUCTIONS, - } }; - } - - const { era, version } = eraOf(m); - if (era === 'modern') { - if (!MODERN.includes(version!)) return err(UNSUPPORTED_PROTOCOL_VERSION, 'Unsupported protocol version', { supported: SUPPORTED, requested: version }); - const caps = ((m.params?._meta ?? {}) as Record)[META.clientCapabilities]; - if (typeof caps !== 'object' || caps === null) return err(-32602, `Invalid params: _meta["${META.clientCapabilities}"] is required`); - } else if (m.method === 'server/discover') { - return err(-32602, `Invalid params: _meta["${META.protocolVersion}"] is required`); - } - // Modern results carry resultType and name the server in _meta; legacy results stay as they were. - const ok = (result: Record) => ({ jsonrpc: '2.0', id: m.id, - result: era === 'modern' ? { resultType: 'complete', ...result, _meta: { [META.serverInfo]: serverInfo() } } : result }); - switch (m.method) { - case 'server/discover': - return ok({ supportedVersions: SUPPORTED, capabilities: { tools: {} }, instructions: INSTRUCTIONS, ttlMs: TOOLS_TTL_MS, cacheScope: 'public' }); + case 'initialize': { + const asked = String(m.params?.protocolVersion ?? ''); + return ok({ + protocolVersion: SUPPORTED.includes(asked) ? asked : PROTOCOL, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: 'storebound', title: 'storebound', version: pkg.version, description: pkg.description }, + instructions: INSTRUCTIONS, + }); + } case 'ping': return ok({}); - case 'tools/list': return ok({ tools: listTools(), ...(era === 'modern' ? { ttlMs: TOOLS_TTL_MS, cacheScope: 'public' } : {}) }); + case 'tools/list': return ok({ tools: listTools() }); case 'tools/call': { const name = String(m.params?.name ?? ''); const tool = TOOLS.find(t => t.name === name); @@ -132,7 +81,7 @@ async function runCli(argv: string[], id: Id): Promise<{ code: number; out: stri export async function serve(): Promise { const send = (o: unknown) => process.stdout.write(JSON.stringify(o) + '\n'); - console.error(`[storebound mcp] ${pkg.version} on stdio (MCP ${PROTOCOL}, legacy ${LEGACY.join(', ')}), project ${process.env.STOREBOUND_PROJECT || process.cwd()}`); + console.error(`[storebound mcp] ${pkg.version} on stdio, project ${process.env.STOREBOUND_PROJECT || process.cwd()}`); let buf = ''; const decoder = new TextDecoder(); const reader = Bun.stdin.stream().getReader(); diff --git a/cli/play/google.ts b/cli/play/google.ts deleted file mode 100644 index 561b3fb..0000000 --- a/cli/play/google.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Small client for the other Google APIs storebound reads with the same Play service account: the Play Developer -// Reporting API (vitals) and Cloud Storage (Play statistics exports). Read-only callers; retries 429 / 5xx. -import { playServiceAccount } from '../lib/credentials'; -import { tokenSource } from '../lib/google-auth'; - -export const REPORTING_API = 'https://playdeveloperreporting.googleapis.com/v1beta1'; - -export function googleClient(root: string, scope: string) { - const token = tokenSource(playServiceAccount(root), scope); - async function send(method: string, url: string, body?: unknown): Promise { - for (let attempt = 0; ; attempt++) { - const r = await fetch(url, { method, headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, - body: body === undefined ? undefined : JSON.stringify(body) }); - if ((r.status === 429 || r.status >= 500) && attempt < 4) { await r.body?.cancel(); await Bun.sleep(2000 * (attempt + 1)); continue; } - return r; - } - } - return { - async json(method: string, url: string, body?: unknown): Promise { - const r = await send(method, url, body); - const t = await r.text(); - if (!r.ok) throw new Error(`${method} ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${/^\s* { - const r = await send('GET', url); - if (!r.ok) throw new Error(`GET ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${(await r.text()).slice(0, 300)}`); - return new Uint8Array(await r.arrayBuffer()); - }, - }; -} diff --git a/cli/prices.ts b/cli/prices.ts deleted file mode 100644 index 44573d5..0000000 --- a/cli/prices.ts +++ /dev/null @@ -1,143 +0,0 @@ -// In-app product prices for many products and regions from one CSV (both stores). -// storebound prices export [--out store/prices.csv] [--store apple|play] [--only ids] [--with-automatic] [--dry] -// storebound prices import [--csv store/prices.csv] [--store apple|play] [--only ids] [--reconvert] [--all] [--dry] [--yes] -// CSV columns: product, store (apple | play | both), region (ISO alpha-2), currency, price, start_date (App Store -// only, a future YYYY-MM-DD = scheduled change), kind (manual | auto; auto rows are Apple's equalized prices, exported -// for reference and ignored on import). -// import: reads the current prices, prints the diff table, and (not --dry) asks before writing. Apple: one new price -// schedule per changed product (base territory + every manual price; territories without one are equalized by Apple; -// an increase cannot be undone once it starts). Play: the purchase option's regional prices are replaced: CSV regions -// on top of the current ones; regions without a price get convertRegionPrices from the USD base (CSV US row, else the -// config's usd); --reconvert resets every region the CSV does not list to Play's converted price. Pure parts: lib/prices.ts. -import { existsSync, readFileSync, writeFileSync } from 'node:fs'; -import { ascClient, type Asc, type J } from './apple/asc'; -import type { Ctx } from './lib/ctx'; -import { confirm, need } from './lib/ctx'; -import { done, log, step, warn } from './lib/log'; -import { toMoney } from './lib/money'; -import { - appleSchedule, appleScheduleBody, applePriceRows, diffPrices, diffTable, parsePriceCsv, type PlayProduct, playPatchBody, playPriceRows, playRegions, - pointKey, type PriceRow, pricesCsv, sameSchedule, -} from './lib/prices'; -import { playClient, type PlayClient } from './play/client'; - -const TAG = 'prices'; - -async function iapId(c: Asc, appId: string, productId: string): Promise { - return (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(productId)}`)).data?.[0]?.id ?? null; -} - -async function appleCurrent(c: Asc, id: string, product: string, withAuto: boolean): Promise<{ rows: PriceRow[]; base: string | null }> { - const q = 'include=inAppPurchasePricePoint,territory&limit=200'; - const rows = applePriceRows(product, await pages(c, `/v1/inAppPurchasePriceSchedules/${id}/manualPrices?${q}`)); - if (withAuto) rows.push(...applePriceRows(product, await pages(c, `/v1/inAppPurchasePriceSchedules/${id}/automaticPrices?${q}`), 'auto')); - const base = (await c.maybe(`/v1/inAppPurchasePriceSchedules/${id}/baseTerritory`))?.data?.id ?? null; - return { rows, base }; -} - -/** data + included of every page of a paged GET (c.all keeps only data). */ -async function pages(c: Asc, path: string): Promise<{ data: J[]; included: J[] }> { - const out = { data: [] as J[], included: [] as J[] }; - let url: string | null = path; - while (url) { const page: J = await c.asc('GET', url); out.data.push(...(page.data ?? [])); out.included.push(...(page.included ?? [])); url = page.links?.next ?? null; } - return out; -} - -async function playProduct(play: PlayClient, id: string): Promise { - try { return await play.call('GET', `${play.API}/oneTimeProducts/${encodeURIComponent(id)}`); } - catch (e) { if (/-> 404/.test(String(e))) return null; throw e; } -} - -export async function run(ctx: Ctx): Promise { - const { config, root, resolve } = ctx.loaded; - const a = ctx.args; - const sub = a._[0]; - if (sub !== 'export' && sub !== 'import') throw new Error('usage: storebound prices export | import [--csv store/prices.csv] [--dry]'); - const store = a.get('store'); - if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play'); - const useApple = (!store || store === 'apple') && !!config.apple; - const usePlay = (!store || store === 'play') && !!config.play; - const only = a.list('only'); - const products = need(config.products, 'products').filter(p => !only.length || only.includes(p.id)); - const csvPath = resolve(a.get(sub === 'export' ? 'out' : 'csv') ?? config.prices?.csv ?? 'store/prices.csv'); - const dry = a.has('dry'); - - const c = useApple ? await ascClient(root, config.apple!.bundleId, config.apple?.appId) : null; - const appId = c ? await c.app() : ''; - const play = usePlay ? await playClient(root, config.play!.packageName) : null; - - // current state of every product on the chosen stores - const current: PriceRow[] = []; - const iaps = new Map(); - const playProducts = new Map(); - for (const [i, p] of products.entries()) { - log(TAG, `${step(i + 1, products.length, p.id)}: reading current prices`); - if (c) { - const id = await iapId(c, appId, p.id); - if (!id) warn(TAG, `${p.id}: not on App Store Connect (storebound apple iap creates it)`); - else { const cur = await appleCurrent(c, id, p.id, sub === 'export' && a.has('with-automatic')); current.push(...cur.rows); iaps.set(p.id, { id, base: cur.base }); } - } - if (play) { - const pp = await playProduct(play, p.id); - if (!pp) warn(TAG, `${p.id}: not on Google Play (storebound play products creates it)`); - else { current.push(...playPriceRows(pp)); playProducts.set(p.id, pp); } - } - } - - if (sub === 'export') { - const csv = pricesCsv(current); - if (dry) { console.log(csv); done(TAG, `dry run: would write ${current.length} rows to ${csvPath}`); return; } - writeFileSync(csvPath, csv); - done(TAG, `${current.length} rows -> ${csvPath} (edit, then storebound prices import --dry)`); - return; - } - - if (!existsSync(csvPath)) throw new Error(`no prices CSV at ${csvPath} (storebound prices export writes one)`); - const wantedAll = parsePriceCsv(readFileSync(csvPath, 'utf8'), { products: config.products!.map(p => p.id) }) - .filter(r => products.some(p => p.id === r.product) && ((r.store === 'apple' && useApple) || (r.store === 'play' && usePlay))); - const diff = diffPrices(current, wantedAll); - console.log(diffTable(diff, { all: a.has('all') })); - const changed = new Set(diff.filter(d => d.change !== 'same').map(d => `${d.product}|${d.store}`)); - const reconvert = a.has('reconvert'); - if (reconvert && usePlay) for (const p of products) if (playProducts.has(p.id)) changed.add(`${p.id}|play`); - if (!changed.size) { done(TAG, 'prices up to date'); return; } - log(TAG, `${changed.size} product / store pair(s) to update`); - if (dry) { done(TAG, 'dry run: nothing written'); return; } - if (!(await confirm(ctx, `Write the new prices for ${changed.size} product / store pair(s)? Players see them as soon as the stores apply them; an App Store price increase cannot be undone once it starts.`))) return; - - for (const p of products) { - const wanted = wantedAll.filter(r => r.product === p.id); - if (c && changed.has(`${p.id}|apple`)) { - const iap = iaps.get(p.id); - if (!iap) { warn(TAG, `${p.id}: no App Store product, skipped`); continue; } - const cur = current.filter(r => r.product === p.id && r.store === 'apple'); - const base = config.prices?.baseTerritory ?? iap.base ?? 'USA'; - const entries = appleSchedule(cur, wanted.filter(r => r.store === 'apple'), base); - if (sameSchedule(entries, cur.filter(r => r.kind !== 'auto').map(r => ({ territory: r.territory!, price: r.price, startDate: r.startDate ?? null })))) { log(TAG, `${p.id} apple: schedule unchanged`); } - else { - const points = new Map(cur.filter(r => r.pointId).map(r => [pointKey(r.territory!, r.price), r.pointId!] as const)); - for (const t of new Set(entries.filter(e => !points.has(pointKey(e.territory, e.price))).map(e => e.territory))) { - for (const pp of await c.all(`/v2/inAppPurchases/${iap.id}/pricePoints?filter[territory]=${t}&limit=8000`)) points.set(pointKey(t, pp.attributes.customerPrice), pp.id); - } - const missing = entries.filter(e => !points.has(pointKey(e.territory, e.price))); - if (missing.length) throw new Error(`${p.id}: no App Store price point for ${missing.map(e => `${e.territory} ${e.price}`).join(', ')} (Apple only takes its own price points; storebound prices export --with-automatic shows the equalized ones)`); - await c.asc('POST', '/v1/inAppPurchasePriceSchedules', appleScheduleBody(iap.id, base, entries, points)); - log(TAG, `${p.id} apple: schedule set (${entries.length} manual price(s), base ${base})`); - } - } - if (play && changed.has(`${p.id}|play`)) { - const pp = playProducts.get(p.id); - if (!pp) { warn(TAG, `${p.id}: no Play product, skipped`); continue; } - const usd = wanted.find(r => r.store === 'play' && r.region === 'US')?.price ?? p.usd; - const conv = await play.call<{ convertedRegionPrices?: Record; regionVersion?: { version: string } }>( - 'POST', `${play.API}/pricing:convertRegionPrices`, { price: toMoney('USD', usd) }); - const opt = pp.purchaseOptions?.find(o => o.purchaseOptionId === 'buy') ?? pp.purchaseOptions?.[0]; - if (!opt) { warn(TAG, `${p.id}: Play product has no purchase option, skipped`); continue; } - const regions = playRegions(opt.regionalPricingAndAvailabilityConfigs ?? [], wanted.filter(r => r.store === 'play'), conv.convertedRegionPrices ?? null, { reconvert }); - const v = encodeURIComponent(conv.regionVersion?.version ?? '2022/02'); - await play.call('PATCH', `${play.API}/onetimeproducts/${encodeURIComponent(p.id)}?regionsVersion.version=${v}&updateMask=purchaseOptions`, playPatchBody(pp, regions, opt.purchaseOptionId)); - log(TAG, `${p.id} play: ${regions.length} regions set`); - } - } - done(TAG, 'prices imported (storebound prices export shows the stores\' view)'); -} diff --git a/cli/reviews.ts b/cli/reviews.ts deleted file mode 100644 index 7a17a18..0000000 --- a/cli/reviews.ts +++ /dev/null @@ -1,143 +0,0 @@ -// Store reviews and replies. -// storebound reviews list [--store apple|play] [--days 14] [--unanswered] [--rating 1,2] [--json] -// storebound reviews draft [--store apple|play] [--days 14] [--rating 1,2,3] [--all] [--dir .storebound/replies] [--dry] -// storebound reviews send [--dir .storebound/replies] [--dry] [--yes] -// `draft` writes one Markdown file per unanswered review into .storebound/replies/ (gitignored): front matter -// (store, review_id, rating, approved: false), the review, and an empty "## Reply" section. Existing files are never -// overwritten (your edits stay). The owner or an agent with the review-replies skill writes the reply; the owner sets -// `approved: true`. `send` sends only approved, unsent drafts that pass the checks (length, no incentives), after a -// confirmation, then writes `sent: