Compare commits
No commits in common. "79fea16016c386199095697bb796def4df23a437" and "417365eda3b7d767a662cea72eca39ae184175eb" have entirely different histories.
79fea16016
...
417365eda3
63 changed files with 150 additions and 3763 deletions
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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 <command>` (`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
|
||||
|
|
|
|||
22
.github/copilot-instructions.md
vendored
22
.github/copilot-instructions.md
vendored
|
|
@ -7,11 +7,10 @@ Mobile game store releases (Google Play, App Store). Skills live in `skills/<nam
|
|||
|
||||
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 <command>` (`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 |
|
||||
|
|
|
|||
22
AGENTS.md
22
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 <command>` (`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
|
||||
|
|
|
|||
44
CHANGELOG.md
44
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.
|
||||
|
|
|
|||
22
GEMINI.md
22
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 <command>` (`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 |
|
||||
|
|
|
|||
161
README.md
161
README.md
|
|
@ -3,11 +3,11 @@
|
|||
**Website: [storebound.dev](https://storebound.dev)**
|
||||
|
||||
[](LICENSE)
|
||||
[](CHANGELOG.md)
|
||||
[](CHANGELOG.md)
|
||||
[](https://bun.sh)
|
||||
[](package.json)
|
||||
[](skills)
|
||||
[](#mcp-server)
|
||||
[](skills)
|
||||
[](#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
|
||||
|
|
@ -45,18 +41,17 @@ your own click.
|
|||
|---|---|---|---|---|
|
||||
| 1 | **Set up** | `init` (config, `store/*.md`, declarations and privacy templates), `install --agent <tool>`, `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 <path>` (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/<date>.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 <id>` |
|
||||
| `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) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>TestFlight</b></summary>
|
||||
|
||||
| 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 |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>After launch</b></summary>
|
||||
|
||||
| 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 |
|
||||
|
||||
</details>
|
||||
|
||||
|
|
@ -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.
|
||||
|
||||
|
|
|
|||
13
SECURITY.md
13
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
|
||||
|
|
|
|||
153
cli/analytics.ts
153
cli/analytics.ts
|
|
@ -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/<date>.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_<id>", 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<J | null> {
|
||||
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<Record<string, string>[]> {
|
||||
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<string, string>[] }[] = [];
|
||||
for (const inst of instances) {
|
||||
const rows: Record<string, string>[] = [];
|
||||
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<string, string>[] = [], inst: Record<string, string>[] = [];
|
||||
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<void> {
|
||||
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');
|
||||
}
|
||||
|
|
@ -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<J> {
|
||||
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<J[]> {
|
||||
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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string, unknown> } } | 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<any>, reqs: Req[], o: { dry: boolean; tag: string }): Promise<unknown[]> {
|
||||
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;
|
||||
}
|
||||
126
cli/apple/ppo.ts
126
cli/apple/ppo.ts
|
|
@ -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
|
||||
// (<renders>/<variant>/<lang>/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<Experiment[]> {
|
||||
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<void> {
|
||||
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 <id>');
|
||||
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}`);
|
||||
}
|
||||
|
|
@ -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<string, string> = { ios69: 'APP_IPHONE_67', ios65: 'APP_IPHONE_65' };
|
||||
/** 13" iPad set, uploaded only when apple.ipad is true. */
|
||||
export const IPAD_DISPLAY: Record<string, string> = { 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<string, string> = { '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<string, string> =>
|
||||
({ ...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<string, string> => ({ ...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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
|||
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<void> {
|
||||
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<void>)[] = [];
|
||||
for (const loc of locs) {
|
||||
|
|
|
|||
|
|
@ -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 <names>';
|
||||
|
||||
async function groups(c: Asc, appId: string): Promise<Group[]> {
|
||||
return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi);
|
||||
}
|
||||
|
||||
async function findBuild(c: Asc, appId: string, number: string, marketing?: string): Promise<ApiBuild & { detail: J }> {
|
||||
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<void> {
|
||||
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<string, { id: string; groupIds: string[]; state?: string }>();
|
||||
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<string, string>;
|
||||
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 <name>[,<name>]: 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}`);
|
||||
}
|
||||
102
cli/health.ts
102
cli/health.ts
|
|
@ -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 <date>.md (+ <date>.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<PlayHealth> {
|
||||
const g = googleClient(root, REPORTING_SCOPE);
|
||||
const app = `${REPORTING_API}/apps/${encodeURIComponent(pkg)}`;
|
||||
log('health', 'play: vitals freshness');
|
||||
const set = await g.json<Parameters<typeof latestDailyEnd>[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<AppleHealth> {
|
||||
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<string, string>(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<HealthSnapshot> {
|
||||
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<void> {
|
||||
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;
|
||||
}
|
||||
|
|
@ -17,10 +17,6 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
|
|||
const COMMANDS: Record<string, [() => Promise<Mod>, 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 <tag>)'],
|
||||
'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<string, [() => Promise<Mod>, 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 ...)'],
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
||||
|
|
|
|||
|
|
@ -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_<id> (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_<package>_<yyyyMM>_country.csv (Store listing acquisitions / visitors)
|
||||
// stats/installs/installs_<package>_<yyyyMM>_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<T extends { attributes?: { name?: string } }>(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<string, string>[] {
|
||||
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<string, string>[] }[]): Record<string, string>[] {
|
||||
const best = new Map<string, string>();
|
||||
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<string, string>[], downloads: Record<string, string>[]): AppleDay[] {
|
||||
const days = new Map<string, AppleDay>();
|
||||
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<string, string>[], installs: Record<string, string>[]): PlayDay[] {
|
||||
const days = new Map<string, PlayDay>();
|
||||
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 = <T extends { date: string }>(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 -- <paths>` -> 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<string, AppleDay>(), p = new Map<string, PlayDay>();
|
||||
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));
|
||||
|
|
@ -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_<number>" (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.website>/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_<number>" (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, ...)`);
|
||||
|
|
|
|||
|
|
@ -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<string, string>[] {
|
||||
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';
|
||||
|
|
@ -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<string, FmValue>; body: string } {
|
||||
const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
||||
if (!m) return { data: {}, body: text };
|
||||
const data: Record<string, FmValue> = {};
|
||||
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<string, FmValue | undefined>, 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}`;
|
||||
}
|
||||
|
|
@ -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<string> {
|
||||
export function tokenSource(sa: ServiceAccount): () => Promise<string> {
|
||||
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' },
|
||||
|
|
|
|||
|
|
@ -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<string, unknown> {
|
||||
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> }[] } }): 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<string, string>; values: Record<string, number> }
|
||||
|
||||
interface ApiRow {
|
||||
startTime?: Partial<Ymd>;
|
||||
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<PlayHealth['devices']> {
|
||||
const agg = new Map<string, { cn: number; cd: number; an: number; ad: number }>();
|
||||
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<string, string>, since: string): AppleHealth['betaCrashes'] {
|
||||
const n = new Map<string, number>();
|
||||
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<Level, string> = { 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');
|
||||
}
|
||||
|
|
@ -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<string, unknown> }): 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 <id>[,<id>]: 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 <name>`);
|
||||
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 } } } };
|
||||
}
|
||||
|
|
@ -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<string>();
|
||||
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<PriceRow, 'product' | 'store' | 'region' | 'startDate'>) => `${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<string, { regionCode: string; price: Money }> | 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<string, Money>();
|
||||
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<string, ScheduleEntry[]>();
|
||||
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<string, PriceRow[]>();
|
||||
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<string, string>): Record<string, unknown> {
|
||||
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))}`;
|
||||
|
|
@ -1,155 +0,0 @@
|
|||
// Store review replies as pure parts: normalising both stores' reviews, the local draft files the owner / agent edit
|
||||
// (.storebound/replies/<store>-<id>.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<ReviewStore, number> = { 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: <store>-<review id>.md with unsafe characters replaced. */
|
||||
export const draftName = (r: Pick<Review, 'store' | 'id'>): string => `${r.store}-${r.id.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120)}.md`;
|
||||
|
||||
export const REPLY_PLACEHOLDER = '<!-- Write the reply below. Plain text, the player\'s language. -->';
|
||||
|
||||
/** 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<string, FmValue> = { 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<string, FmValue> }
|
||||
|
||||
/** 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(/<!--[\s\S]*?-->/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: <iso>` (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 } };
|
||||
}
|
||||
|
|
@ -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)}%`);
|
||||
|
|
@ -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<string, string>;
|
||||
/** 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<string, unknown> }): 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<string>();
|
||||
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<string>();
|
||||
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<string, { id: string; groupIds: string[] }>, 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<string, string[]>();
|
||||
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<string, Set<string>>();
|
||||
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<string, string[]>();
|
||||
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<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
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<string, string>): 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<string, BetaInfo>): 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<string, unknown>)[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<string, unknown> } | 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<string, unknown> = {
|
||||
...(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<string, string> {
|
||||
if (!t?.description) return {};
|
||||
const out: Record<string, string> = {};
|
||||
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;
|
||||
}
|
||||
|
|
@ -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/<date>.md (plus <date>.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/<store>-<id>.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/<date>.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 <variants>")' }, 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/<variant>/<lang>/...) 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<string, unknown> {
|
||||
const props: Record<string, JsonSchema> = { ...(t.props ?? {}) };
|
||||
|
|
|
|||
91
cli/mcp.ts
91
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<string
|
|||
|
||||
const MAX_OUTPUT = 60_000;
|
||||
const CLI = join(import.meta.dir, 'index.ts');
|
||||
const serverInfo = () => ({ 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<string, unknown>;
|
||||
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<Record<string, unknown> | 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<string, unknown>)[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<string, unknown>) => ({ 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<void> {
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -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<Response> {
|
||||
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<T = unknown>(method: string, url: string, body?: unknown): Promise<T> {
|
||||
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*</.test(t) ? '(HTML error page)' : t.slice(0, 800)}`);
|
||||
return (t ? JSON.parse(t) : {}) as T;
|
||||
},
|
||||
async bytes(url: string): Promise<Uint8Array> {
|
||||
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());
|
||||
},
|
||||
};
|
||||
}
|
||||
143
cli/prices.ts
143
cli/prices.ts
|
|
@ -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<string | null> {
|
||||
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<PlayProduct | null> {
|
||||
try { return await play.call<PlayProduct>('GET', `${play.API}/oneTimeProducts/${encodeURIComponent(id)}`); }
|
||||
catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
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<string, { id: string; base: string | null }>();
|
||||
const playProducts = new Map<string, PlayProduct>();
|
||||
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<string, { regionCode: string; price: { currencyCode: string; units: string; nanos?: number } }>; 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)');
|
||||
}
|
||||
143
cli/reviews.ts
143
cli/reviews.ts
|
|
@ -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: <time>` into the file. Replies are public: `send` is not an MCP tool.
|
||||
// Google Play's API only returns reviews created or edited in the last 7 days.
|
||||
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 { confirm } from './lib/ctx';
|
||||
import { done, log, warn } from './lib/log';
|
||||
import {
|
||||
checkReply, type Draft, draftMarkdown, draftName, filterReviews, markSent, parseAppleReviews, parseDraft, parsePlayReviews, replyRequest,
|
||||
type Review, sendPlan,
|
||||
} from './lib/reviews';
|
||||
import { textTable } from './lib/table';
|
||||
import { playClient } from './play/client';
|
||||
|
||||
const TAG = 'reviews';
|
||||
|
||||
async function appleReviews(ctx: Ctx, since: string): Promise<Review[]> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId);
|
||||
const out: Review[] = [];
|
||||
let url: string | null = `/v1/apps/${await c.app()}/customerReviews?sort=-createdDate&include=response&limit=200`;
|
||||
while (url) {
|
||||
const page: J = await c.asc('GET', url);
|
||||
const rs = parseAppleReviews(page);
|
||||
out.push(...rs);
|
||||
if (!rs.length || rs.at(-1)!.date < since) break;
|
||||
url = page.links?.next ?? null;
|
||||
}
|
||||
log(TAG, `apple: ${out.length} reviews read`);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function playReviews(ctx: Ctx): Promise<Review[]> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const play = await playClient(root, config.play!.packageName);
|
||||
const out: Review[] = [];
|
||||
let token = '';
|
||||
do {
|
||||
const r = await play.call<{ reviews?: unknown[]; tokenPagination?: { nextPageToken?: string } }>('GET', `${play.API}/reviews?maxResults=100${token ? `&token=${encodeURIComponent(token)}` : ''}`);
|
||||
out.push(...parsePlayReviews(r as Parameters<typeof parsePlayReviews>[0]));
|
||||
token = r.tokenPagination?.nextPageToken ?? '';
|
||||
} while (token);
|
||||
log(TAG, `play: ${out.length} reviews read (the API covers the last 7 days)`);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function collect(ctx: Ctx, o: { since: string; unanswered: boolean; ratings: number[] }): Promise<Review[]> {
|
||||
const { config } = ctx.loaded;
|
||||
const store = ctx.args.get('store');
|
||||
if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play');
|
||||
const all: Review[] = [];
|
||||
if ((!store || store === 'apple') && config.apple) {
|
||||
try { all.push(...await appleReviews(ctx, o.since)); } catch (e) { if (store) throw e; warn(TAG, `apple: ${(e as Error).message.slice(0, 200)}`); }
|
||||
}
|
||||
if ((!store || store === 'play') && config.play) {
|
||||
try { all.push(...await playReviews(ctx)); } catch (e) { if (store) throw e; warn(TAG, `play: ${(e as Error).message.slice(0, 200)}`); }
|
||||
}
|
||||
return filterReviews(all, o);
|
||||
}
|
||||
|
||||
const snippet = (r: Review) => `${r.title ? r.title + ': ' : ''}${r.body}`.replace(/\s+/g, ' ').slice(0, 70);
|
||||
|
||||
function readDrafts(dir: string): { drafts: Draft[]; texts: Map<string, string> } {
|
||||
const texts = new Map<string, string>();
|
||||
const drafts: Draft[] = [];
|
||||
if (!existsSync(dir)) return { drafts, texts };
|
||||
for (const f of readdirSync(dir).filter(n => /^(apple|play)-.+\.md$/.test(n)).sort()) {
|
||||
const p = join(dir, f);
|
||||
const t = readFileSync(p, 'utf8');
|
||||
texts.set(p, t);
|
||||
try { drafts.push(parseDraft(p, t)); } catch (e) { warn(TAG, (e as Error).message); }
|
||||
}
|
||||
return { drafts, texts };
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
const dir = ctx.loaded.resolve(a.get('dir') ?? '.storebound/replies');
|
||||
const days = a.num('days', 14);
|
||||
const since = new Date(Date.now() - days * 86_400_000).toISOString();
|
||||
const ratings = a.list('rating').map(Number).filter(n => n >= 1 && n <= 5);
|
||||
|
||||
if (sub === 'list') {
|
||||
const rs = await collect(ctx, { since, unanswered: a.has('unanswered'), ratings });
|
||||
if (a.has('json')) { console.log(JSON.stringify(rs.map(({ author: _a, ...r }) => r), null, 2)); return; }
|
||||
console.log(textTable(['store', 'date', 'stars', 'where', 'replied', 'review'], rs.map(r => [r.store, r.date.slice(0, 10), r.rating, r.where ?? '', r.reply ? 'yes' : '', snippet(r)])));
|
||||
done(TAG, `${rs.length} review(s) in the last ${days} days, ${rs.filter(r => !r.reply).length} without a reply`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'draft') {
|
||||
const rs = await collect(ctx, { since, unanswered: !a.has('all'), ratings });
|
||||
let made = 0, kept = 0;
|
||||
if (!a.has('dry')) mkdirSync(dir, { recursive: true });
|
||||
for (const r of rs) {
|
||||
const p = join(dir, draftName(r));
|
||||
if (existsSync(p)) { kept++; continue; }
|
||||
if (a.has('dry')) log(TAG, `would write ${p}`);
|
||||
else writeFileSync(p, draftMarkdown(r));
|
||||
made++;
|
||||
}
|
||||
done(TAG, `${made} new draft(s)${a.has('dry') ? ' (dry run)' : ''}, ${kept} kept as they are, in ${dir}. Next: write each "## Reply", set approved: true, then storebound reviews send`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'send') {
|
||||
const { drafts, texts } = readDrafts(dir);
|
||||
const plan = sendPlan(drafts);
|
||||
for (const s of plan.skip) log(TAG, `skip ${s.file.split('/').pop()}: ${s.why}`);
|
||||
for (const d of plan.send) for (const i of checkReply(d.reply, d.store)) warn(TAG, `${d.file.split('/').pop()}: ${i.msg}`);
|
||||
if (!plan.send.length) { done(TAG, 'nothing to send'); return; }
|
||||
console.log(textTable(['store', 'review', 'chars', 'reply'], plan.send.map(d => [d.store, d.reviewId, [...d.reply].length, d.reply.replace(/\s+/g, ' ').slice(0, 70)])));
|
||||
if (a.has('dry')) { done(TAG, `${plan.send.length} reply(ies) would be sent (dry run)`); return; }
|
||||
if (!(await confirm(ctx, `Send ${plan.send.length} public reply(ies)? Players are notified and the replies show on the store.`))) return;
|
||||
const { config, root } = ctx.loaded;
|
||||
const c = plan.send.some(d => d.store === 'apple') ? await ascClient(root, config.apple!.bundleId, config.apple?.appId) : null;
|
||||
const play = plan.send.some(d => d.store === 'play') ? await playClient(root, config.play!.packageName) : null;
|
||||
let sent = 0;
|
||||
for (const d of plan.send) {
|
||||
const req = replyRequest(d, config.play?.packageName);
|
||||
try {
|
||||
if (d.store === 'apple') await c!.asc(req.method, req.url, req.body);
|
||||
else await play!.call(req.method, req.url, req.body);
|
||||
writeFileSync(d.file, markSent(texts.get(d.file)!, new Date().toISOString()));
|
||||
sent++;
|
||||
log(TAG, `sent ${d.file.split('/').pop()}`);
|
||||
} catch (e) { warn(TAG, `${d.file.split('/').pop()}: ${(e as Error).message.slice(0, 300)}`); }
|
||||
}
|
||||
done(TAG, `${sent}/${plan.send.length} sent (Apple shows replies within about 24 hours)`);
|
||||
return;
|
||||
}
|
||||
throw new Error('usage: storebound reviews list | draft | send');
|
||||
}
|
||||
|
|
@ -1,14 +1,12 @@
|
|||
// Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data.
|
||||
import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config';
|
||||
|
||||
/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), iphone-medium = 6.3" iPhone with
|
||||
* Dynamic Island, medium display (APP_IPHONE_61, only with apple.iphoneMedium), ipad13 = 13" iPad
|
||||
/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), ipad13 = 13" iPad
|
||||
* (APP_IPAD_PRO_3GEN_129, only for apps that run on iPad), play = Play phone 9:16, tab7 / tab10 = Play 7" / 10"
|
||||
* tablets (tablet frames), feature = Play feature graphic. Rules per size: spec.ts. */
|
||||
export const SIZES: Record<string, { w: number; h: number; device?: 'tablet'; feature?: true }> = {
|
||||
ios69: { w: 1320, h: 2868 },
|
||||
ios65: { w: 1284, h: 2778 },
|
||||
'iphone-medium': { w: 1206, h: 2622 },
|
||||
ipad13: { w: 2064, h: 2752, device: 'tablet' },
|
||||
play: { w: 1080, h: 1920 },
|
||||
tab7: { w: 1080, h: 1920, device: 'tablet' },
|
||||
|
|
@ -92,12 +90,11 @@ export function frameDims(config: Pick<ShipConfig, 'apple' | 'shots'>): Record<'
|
|||
return { phone: { ...DEFAULT_PHONE, ...config.shots?.phone }, tablet: { ...tablet, ...config.shots?.tablet } };
|
||||
}
|
||||
|
||||
/** Size keys this project renders by default: Apple sizes only with an apple section (iPad only with apple.ipad, the
|
||||
* 6.3" iPhone only with apple.iphoneMedium),
|
||||
/** Size keys this project renders by default: Apple sizes only with an apple section (iPad only with apple.ipad),
|
||||
* Play sizes only with a play section (both when neither is configured). */
|
||||
export function defaultSizes(config: Pick<ShipConfig, 'apple' | 'play'>): string[] {
|
||||
const apple = !!config.apple || !config.play, play = !!config.play || !config.apple;
|
||||
return Object.keys(SIZES).filter(k => (k === 'ipad13' ? apple && !!config.apple?.ipad : k === 'iphone-medium' ? apple && !!config.apple?.iphoneMedium : k.startsWith('ios') ? apple : play));
|
||||
return Object.keys(SIZES).filter(k => (k === 'ipad13' ? apple && !!config.apple?.ipad : k.startsWith('ios') ? apple : play));
|
||||
}
|
||||
|
||||
/** Scenes of a variant (its order / subset, palette overrides), or the base scenes. */
|
||||
|
|
|
|||
|
|
@ -82,12 +82,12 @@ export function ffprobe(file: string): ProbeInfo | null {
|
|||
|
||||
/** Which sets the stores require for this config (missing ones are errors, others only checked when present). With a
|
||||
* language id: Apple sets only when that language has an App Store locale, Play sets only when it has a Play code. */
|
||||
export function requiredSets(c: { apple?: { ipad?: boolean; iphoneMedium?: boolean } | undefined; play?: unknown; languages?: { id: string; apple?: string; play?: string | string[] }[] },
|
||||
export function requiredSets(c: { apple?: { ipad?: boolean } | undefined; play?: unknown; languages?: { id: string; apple?: string; play?: string | string[] }[] },
|
||||
lang?: string): Record<string, boolean> {
|
||||
const l = lang === undefined ? undefined : c.languages?.find(x => x.id === lang);
|
||||
const apple = !!c.apple && (!l || !!l.apple);
|
||||
const play = !!c.play && (!l || (Array.isArray(l.play) ? l.play.length > 0 : !!l.play));
|
||||
return { ios69: apple, ...(c.apple?.iphoneMedium ? { 'iphone-medium': apple } : {}), ipad13: apple && !!c.apple?.ipad, play, feature: play };
|
||||
return { ios69: apple, ipad13: apple && !!c.apple?.ipad, play, feature: play };
|
||||
}
|
||||
|
||||
export const allIssues = (s: RendersScan): { where: string; issue: Issue }[] => [
|
||||
|
|
|
|||
|
|
@ -37,10 +37,6 @@ const MB = 1024 * 1024;
|
|||
export const IMAGE_SPECS: Record<string, ImageSpec> = {
|
||||
// Apple accepts 1260x2736, 1290x2796 and 1320x2868 for "iPhone with Dynamic Island (large display)" = 6.9".
|
||||
ios69: { store: 'apple', type: 'APP_IPHONE_67', label: 'App Store iPhone 6.9"', sizes: [[1320, 2868], [1290, 2796], [1260, 2736]], min: 1, max: 10, maxBytes: null, alpha: false },
|
||||
// 6.3" iPhone with Dynamic Island, medium display (iPhone 14 Pro .. 18 Pro): optional here (apple.iphoneMedium). Apple
|
||||
// scales the 6.5" (Face ID large) set down for it when it is missing. APP_IPHONE_61 is inferred: the enum has no
|
||||
// descriptions and 61 is the only medium iPhone bucket (NOT VERIFIED against an upload).
|
||||
'iphone-medium': { store: 'apple', type: 'APP_IPHONE_61', label: 'App Store iPhone 6.3"', sizes: [[1206, 2622], [1179, 2556]], min: 1, max: 10, maxBytes: null, alpha: false },
|
||||
ios65: { store: 'apple', type: 'APP_IPHONE_65', label: 'App Store iPhone 6.5"', sizes: [[1284, 2778], [1242, 2688]], min: 1, max: 10, maxBytes: null, alpha: false },
|
||||
// 13" iPad display (iPad Pro M4/M5, iPad Air M2+): required when the app runs on iPad. API display type keeps the old name.
|
||||
ipad13: { store: 'apple', type: 'APP_IPAD_PRO_3GEN_129', label: 'App Store iPad 13"', sizes: [[2064, 2752], [2048, 2732]], min: 1, max: 10, maxBytes: null, alpha: false },
|
||||
|
|
|
|||
|
|
@ -1,21 +1,17 @@
|
|||
// Store readiness report (read-only on both stores): what still blocks a submission, in the order to fix it.
|
||||
// storebound validate [--apple] [--play] [--json] [--src store/renders] [--no-local] [--no-health]
|
||||
// storebound validate [--apple] [--play] [--json] [--src store/renders] [--no-local]
|
||||
// Without --apple / --play: every store the config has. Exit code 1 when there is at least one blocker.
|
||||
// Reads only: GETs on App Store Connect, a Play edit that is opened, read and deleted (never committed), and plain GETs
|
||||
// of the public privacy policy and app-ads.txt URLs. Also checks the local renders folder (if there is one) with the
|
||||
// `shots check` rules: wrong pixel size, alpha, too few / many images, Play 8 MB and feature graphic format are
|
||||
// blockers (the upload would fail), text overflow flags from the last render are warnings. --no-local skips it.
|
||||
// Live apps: crash / ANR vitals (Play Reporting API) and App Store diagnostics, as in `storebound health`: over a Play
|
||||
// bad behavior threshold is a blocker, near it a warning; a store without vitals access is only noted. --no-health skips.
|
||||
import { ascClient, type J } from './apple/asc';
|
||||
import { requiredDisplayTypes } from './apple/screenshots';
|
||||
import { playCodes } from './lib/config';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { checkUrl } from './lib/http';
|
||||
import { collectHealth } from './health';
|
||||
import { healthFindings } from './lib/health';
|
||||
import { log, warn } from './lib/log';
|
||||
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, rendersFindings, sortFindings } from './lib/validate-rules';
|
||||
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, rendersFindings } from './lib/validate-rules';
|
||||
import { rendersCheck } from './shots/check';
|
||||
import { playClient } from './play/client';
|
||||
import { listOneTimeProducts } from './play/products';
|
||||
|
|
@ -122,11 +118,6 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
try { findings.push(...playRules({ ...(await collectPlay(ctx)), renders: local?.play })); }
|
||||
catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('play', local?.play)); }
|
||||
} else if (a.has('play')) warn('validate', 'no play section in the config');
|
||||
if (!a.has('no-health') && (config.apple || config.play)) {
|
||||
log('validate', 'vitals and diagnostics (last 7 days)');
|
||||
const h = await collectHealth(ctx, { apple: (both || a.has('apple')) && !!config.apple, play: (both || a.has('play')) && !!config.play, days: 7 });
|
||||
findings.push(...sortFindings(healthFindings(h, { unreadable: 'ok' })));
|
||||
}
|
||||
const blockers = findings.filter(f => f.level === 'blocker').length;
|
||||
if (a.has('json')) console.log(JSON.stringify({ blockers, findings }, null, 2));
|
||||
else {
|
||||
|
|
|
|||
|
|
@ -2,11 +2,10 @@
|
|||
|
||||
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
|
||||
|
|
@ -18,8 +17,5 @@ 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.
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
"contextFileName": "GEMINI.md",
|
||||
"mcpServers": {
|
||||
"storebound": {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "storebound",
|
||||
"version": "0.4.0",
|
||||
"description": "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 store questionnaire, privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a Bun CLI, an MCP server and Agent Skills for your AI coding agent.",
|
||||
"version": "0.3.1",
|
||||
"description": "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 store questionnaire, privacy, icons, screenshots and previews. One config, a Bun CLI, an MCP server and Agent Skills for your AI coding agent.",
|
||||
"license": "MIT",
|
||||
"author": "CRTkafa",
|
||||
"type": "module",
|
||||
|
|
@ -18,9 +18,7 @@
|
|||
"screenshots",
|
||||
"claude-code-plugin",
|
||||
"agent-skills",
|
||||
"mcp",
|
||||
"testflight",
|
||||
"android-vitals"
|
||||
"mcp"
|
||||
],
|
||||
"bin": {
|
||||
"storebound": "cli/index.ts"
|
||||
|
|
|
|||
|
|
@ -35,9 +35,8 @@ of a first version is the owner's click. Shared agent rules: `docs/agents-core.m
|
|||
automatic. `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION` overrides beat the project values. Take the build
|
||||
number from `storebound apple next-build` right before archiving and **note it**: every later step selects that
|
||||
exact build, never "the latest". Processing takes 5-30 min (`storebound apple status` shows VALID).
|
||||
6. **API · TestFlight.** Put an internal group with `allBuilds: true` in `apple.testflight.groups` and run
|
||||
`storebound apple testflight groups`: every new build reaches the team automatically. External testers, What to
|
||||
Test, Test Information and Beta App Review: the testflight skill. Sandbox testers stay UI: Users and Access > Sandbox.
|
||||
6. **UI · TestFlight.** Create an internal group with "access to all builds" (hasAccessToAllBuilds) once: every new
|
||||
build reaches the testers automatically. Sandbox testers: Users and Access > Sandbox.
|
||||
7. **API · Version + text.** Fill `store/appstore.md`, then `storebound apple listing --version 1.0.0 --build 3`
|
||||
(version, copyright, MANUAL release, the build with exactly that number, name / subtitle / privacy URL,
|
||||
description / keywords / promo / URLs). Then `storebound apple release --phased on`: manual release + phased
|
||||
|
|
|
|||
|
|
@ -40,5 +40,4 @@ true; never use competitor or other games' names, "best / #1", or unrelated popu
|
|||
2. Put the best 1-2 in name / title and subtitle / short description; the rest in the keyword field per locale.
|
||||
3. `storebound check --aso`, fix errors, read warnings.
|
||||
4. Push with `apple listing` / `play listing`; measure after a few weeks (App Store Connect / Play Console acquisition
|
||||
by search term; `storebound analytics snapshot` + `analytics compare` line impressions and conversion up with
|
||||
each committed listing change, store-analytics skill) and change a few terms per release, not all at once.
|
||||
by search term) and change a few terms per release, not all at once.
|
||||
|
|
|
|||
|
|
@ -37,8 +37,7 @@ presses release; you prepare, dry-run and report. `storebound mcp` deliberately
|
|||
4. Problem: `storebound play rollout --halt` (no confirmation needed; stops new installs of the update). Like Apple's
|
||||
pause it is **not a rollback**: updated users keep it. Ship a fixed build with a higher versionCode; resume with
|
||||
`--resume [--fraction x]` only if the halted build is fine after all.
|
||||
5. Done: `storebound play rollout --complete` (100 %). Before each increase, `storebound health --play` (store-health
|
||||
skill): crash / ANR rates near Play's thresholds are a reason to halt, not to widen.
|
||||
5. Done: `storebound play rollout --complete` (100 %).
|
||||
6. Every rollout command runs in an edit: a Console save at the same time makes it retry once.
|
||||
|
||||
## Review wait
|
||||
|
|
|
|||
|
|
@ -1,54 +0,0 @@
|
|||
---
|
||||
name: review-replies
|
||||
description: Reply to App Store and Google Play reviews of a mobile game the safe way - list new reviews, write reply drafts into local files (.storebound/replies), keep the tone human and short, never offer incentives or ask for a better rating, respect the store limits (Play 350 characters), and send only drafts the owner approved. Use when the user asks to answer reviews, handle bad ratings, or check what players are saying.
|
||||
---
|
||||
|
||||
# Review replies
|
||||
|
||||
CLI: `storebound reviews list | draft | send`. MCP: `reviews_list` (read-only) and `reviews_draft` (local files).
|
||||
**Sending is the owner's step**: `storebound reviews send` in a terminal, after reading the drafts; it is not an MCP
|
||||
tool, and an agent never sets `approved: true` by itself.
|
||||
|
||||
## Flow
|
||||
1. `storebound reviews list --unanswered` (or `--rating 1,2`): what came in. Google Play's API only returns reviews
|
||||
created or edited in the **last 7 days**, so run this weekly; the App Store keeps the full history.
|
||||
2. `storebound reviews draft` writes `.storebound/replies/<store>-<review id>.md` per unanswered review (gitignored;
|
||||
existing drafts are never overwritten). Front matter: `store`, `review_id`, `rating`, `where` (territory or
|
||||
language), `limit`, `approved: false`, `sent: null`. Below it the review, then `## Reply`.
|
||||
3. Write each reply under `## Reply` (the agent drafts, the owner edits). Then show the owner the list of drafts.
|
||||
4. The owner sets `approved: true` on the ones to send and runs `storebound reviews send --dry`, then
|
||||
`storebound reviews send` (asks for confirmation). Sent files get `sent: <time>`; re-running skips them.
|
||||
|
||||
## How to write a reply
|
||||
- **In the reviewer's language** (`where`: Play gives the language, Apple the territory; when unsure, mirror the
|
||||
review's language).
|
||||
- **Short and specific**: thank them in one line, answer the actual point, say what changed or what to do. Play
|
||||
allows **350 characters** (HTML is stripped); App Store replies can be longer but rarely should be.
|
||||
- **Bug reports**: name the fix and the version if it is released ("Version 1.2.1 fixes the crash on level 3"); if
|
||||
not, say it is known and being worked on, without dates you cannot keep. Point to in-game Settings > Support or the
|
||||
public support page for details.
|
||||
- **Ads / difficulty / price complaints**: explain the option that exists (e.g. "Remove Ads" in the shop, a setting),
|
||||
no argument, no blame.
|
||||
- **Positive reviews**: a short thanks is enough; do not answer every 5-star review with the same template.
|
||||
- One reply per review. A new send replaces the old one (both stores); the reviewer is notified and may update
|
||||
their review on their own.
|
||||
|
||||
## Never (store policy, and storebound blocks the obvious cases)
|
||||
- **No incentives** for ratings or review changes: no coins, gems, items, discounts or refunds "for" a better review,
|
||||
and no "please give us 5 stars" / "update your rating". Google Play prohibits incentivized or manipulated ratings
|
||||
(Play Console Help, "User Ratings, Reviews, and Installs", answer 9898684); Apple removes apps that manipulate
|
||||
reviews or ratings (App Review Guidelines, Developer Code of Conduct). `reviews send` refuses replies that match
|
||||
these patterns.
|
||||
- **No personal data**: no player names beyond what the store shows, no emails or phone numbers of players, no
|
||||
account details. Your public support address is fine.
|
||||
- **No marketing or spam**: no promo codes, no links to other games, no all-caps or "!!!" (Apple's guidance:
|
||||
https://developer.apple.com/app-store/responding-to-reviews/).
|
||||
- **No arguing or disclosing**: do not dispute facts publicly, do not reveal internal plans, cheats or how anti-cheat
|
||||
works. Hostile or abusive reviews: skip or keep it to one polite line; report policy-violating reviews in the console.
|
||||
|
||||
## Gotchas
|
||||
- Apple shows a reply after up to about 24 hours (`PENDING_PUBLISH` first). Apple documents no maximum length;
|
||||
storebound warns above 5970 characters (commonly reported App Store Connect limit, not verified).
|
||||
- Replying needs the Account Holder, Admin or Customer Support role on Apple's side and the "Reply to reviews"
|
||||
permission for the Play service account.
|
||||
- Drafts contain public reviewer nicknames: keep `.storebound/` out of git (it is gitignored by `storebound init`).
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
---
|
||||
name: store-analytics
|
||||
description: 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. Use when the user asks whether a listing change, new screenshots or a store experiment worked, wants install / conversion numbers, or sets up store reporting.
|
||||
---
|
||||
|
||||
# Store analytics
|
||||
|
||||
CLI: `storebound analytics setup | snapshot | compare`. MCP: `analytics_snapshot`, `analytics_compare` (offline),
|
||||
`analytics_setup`. Read-only on both stores except `setup` (creates the App Store report request). Snapshots go to
|
||||
`.storebound/analytics/<date>.json` (gitignored; they are your business numbers).
|
||||
|
||||
## What is possible (and what is not)
|
||||
- **App Store**: the Analytics Reports API. An Admin key creates one ONGOING report request (`storebound analytics
|
||||
setup`); the first reports come 1-2 days later, then daily, and Apple keeps instances for 35 days, so take a
|
||||
snapshot at least monthly (weekly is better). A request left unread for a long time stops
|
||||
(`stoppedDueToInactivity`); `setup` makes a new one. storebound reads "App Store Discovery and Engagement" (Event
|
||||
Impression / Page view, Counts and Unique Counts) and "App Store Downloads" (First-time Download, Redownload; updates
|
||||
are left out), checks each segment's md5 checksum and keeps, per day, the newest processing of that day.
|
||||
Conversion = (first-time downloads + redownloads) / unique impressions. Source:
|
||||
https://developer.apple.com/documentation/appstoreconnectapi/downloading-analytics-reports
|
||||
- **Google Play**: there is **no API** for store listing statistics (the Play Developer Reporting API only has
|
||||
vitals). Play Console writes monthly CSV exports into your own Cloud Storage bucket; storebound reads them with
|
||||
the service account. Setup: Play Console > Download reports > Statistics > **Copy Cloud Storage URI** and put the
|
||||
bucket into `play.reportsBucket` (`pubsite_prod_rev_<number>`); the service account needs "View app information and
|
||||
download bulk reports" (Play Console Help answer 6135870). Files appear with a few days' delay; the current month's
|
||||
file grows daily. Conversion = store listing acquisitions / store listing visitors.
|
||||
- **Not possible through any API**: Play store listing experiment results and App Store Product Page Optimization
|
||||
results (read them in the consoles; `storebound apple ppo status` shows the App Store test state), Play
|
||||
"Explore" search terms beyond the traffic source file.
|
||||
|
||||
## Flow
|
||||
1. Once: `storebound analytics setup` (App Store) and `play.reportsBucket` (Play).
|
||||
2. Weekly: `storebound analytics snapshot` (default the last 28 days; `--dry` prints totals only).
|
||||
3. Change the listing as usual and commit it (`store/appstore.md`, `store/listing.md`, `store/shots/...`, the config).
|
||||
One change at a time, with a clear commit subject ("new first screenshot: boss fight"), makes the comparison
|
||||
readable.
|
||||
4. `storebound analytics compare` (or `--md` for a report): for every commit that touched the store files, daily
|
||||
impressions (App Store) or visitors (Play) and conversion in the 7 days before vs the 7 days from the change
|
||||
(`--days 14` for small games).
|
||||
|
||||
## Read it honestly
|
||||
- Small numbers swing: under a few hundred page views a week, a 20 % change is noise. Say so.
|
||||
- Seasonality, featuring, ads campaigns, a rating drop and price changes move the same numbers. Look at the same
|
||||
weekday span and mention other things that changed in that window.
|
||||
- A before / after comparison is not an experiment. For a real answer use the store tests: Play store listing
|
||||
experiments (Console) and App Store Product Page Optimization (`storebound apple ppo`, store-screenshots skill).
|
||||
- Never present estimates as facts to the owner, and never put these numbers into public text (listings, replies).
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
---
|
||||
name: store-health
|
||||
description: Watch a released mobile game's crash and ANR health on both stores - Google Play Android vitals (user-perceived crash rate 1.09 % and ANR rate 0.47 % bad behavior thresholds, 8 % per device model) through the Play Developer Reporting API, App Store power and performance metrics, diagnostic signatures and TestFlight crash reports, a weekly Markdown report, and validate blockers when a threshold is crossed. Use when the user asks about crashes, ANRs, vitals, stability, a weekly health check, or why Play shows a quality warning.
|
||||
---
|
||||
|
||||
# Store health (crashes, ANRs, diagnostics)
|
||||
|
||||
CLI: `storebound health` (read-only, both stores; `--apple` / `--play`, `--days 7`), `storebound health --weekly`
|
||||
(also writes `.storebound/health/<date>.md` and `<date>.json`; the next week compares against it; `--dry` prints
|
||||
instead). `storebound validate` runs the same checks for live apps. MCP: `health` (read-only), `health_report`.
|
||||
|
||||
## Setup (once)
|
||||
- **Google Play**: enable the **Google Play Developer Reporting API** in the Google Cloud project of the service
|
||||
account (Cloud Console > APIs & Services > Library). In Play Console > Users and permissions, the service account
|
||||
needs **View app information (read-only)** for the app. Scope used: `playdeveloperreporting`. Reference:
|
||||
https://developers.google.com/play/developer/reporting/reference/rest
|
||||
- **App Store**: the API key that storebound already uses (Admin, App Manager or Developer role reads metrics).
|
||||
Metrics come from users who share analytics with developers; small games may show none.
|
||||
|
||||
## Read the numbers
|
||||
- **Play bad behavior thresholds** (28-day average, user-perceived, checked daily; sources:
|
||||
https://developer.android.com/topic/performance/vitals and Play Console Help answer 9844486):
|
||||
user-perceived crash rate **1.09 %**, user-perceived ANR rate **0.47 %**, and **8 %** on any single phone model.
|
||||
Over a threshold, Play can lower the game's visibility and show a warning on its store listing. storebound marks
|
||||
over = blocker, from 80 % of a threshold = warn.
|
||||
- Daily values swing on small user counts; the 28-day user-weighted rate is what Play judges. Device rows with fewer
|
||||
than 500 users are ignored.
|
||||
- **App Store**: Apple publishes no thresholds. storebound warns on metrics Apple itself rates `poor` (hang rate,
|
||||
launch time, memory, disk writes, battery) and on diagnostic signatures with a large share of reports (Xcode >
|
||||
Organizer shows the stack traces). TestFlight crash reports count crashes testers sent from the beta.
|
||||
|
||||
## Act on it
|
||||
1. Start with the top issues table (Play: cause + location + versionCode; Apple: signature + build).
|
||||
2. Reproduce on the named device model / OS; for ANRs look for main-thread work (I/O, ads SDK init, big asset
|
||||
loads), for crashes the null / out-of-memory paths.
|
||||
3. Ship the fix with a higher versionCode / build number (release-management skill). Halting a rollout stops new
|
||||
installs but is not a rollback.
|
||||
4. Next week: `storebound health --weekly` shows the change in percentage points next to last week.
|
||||
|
||||
## Gotchas
|
||||
- `vitals not readable`: the API is not enabled, the service account lacks the permission, or the app has no release
|
||||
yet. `validate` only notes it; `storebound health` warns.
|
||||
- storebound reads the Reporting API rates as fractions (0.0109 = 1.09 %). The API reference calls them a
|
||||
"percentage of distinct users" without stating the scale (not verified against a live response yet): the first
|
||||
time, compare one number with Play Console > Android vitals and report a mismatch.
|
||||
- Never share crash logs that contain player data outside the team; never paste tester emails from TestFlight crash
|
||||
reports into chats or issues.
|
||||
- Nothing here changes the store: it is safe to run any time.
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: store-iap-setup
|
||||
description: 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 - regional prices, local overrides, a price sheet CSV for many products and regions (diff first, future-dated App Store changes), activation, review screenshots, submitting first IAPs with a version, license/sandbox testers. Use when the user sets up, prices, re-prices or tests in-app products/IAPs, or hits Play onetimeproducts / inappproducts 403 or App Store IAP submission errors.
|
||||
description: 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 - regional prices, local overrides, activation, review screenshots, submitting first IAPs with a version, license/sandbox testers. Use when the user sets up, prices, updates or tests in-app products/IAPs, or hits Play onetimeproducts / inappproducts 403 or App Store IAP submission errors.
|
||||
---
|
||||
|
||||
# In-app purchases on both stores
|
||||
|
|
@ -34,25 +34,6 @@ Apple), `reviewScreenshot`.
|
|||
4. Test: Sandbox testers (Users and Access > Sandbox) on device; or a StoreKit configuration file in Xcode for local
|
||||
runs (those transactions are signed locally and fail server-side receipt checks).
|
||||
|
||||
## Many prices at once: the price sheet (both stores)
|
||||
For price changes after the products exist (sales, regional pricing, a new price everywhere), keep one CSV:
|
||||
`product,store,region,currency,price,start_date` (`store` = apple | play | both; `region` ISO alpha-2; `start_date`
|
||||
App Store only, a future YYYY-MM-DD).
|
||||
1. `storebound prices export` writes the current prices of both stores to `store/prices.csv` (`--with-automatic` adds
|
||||
Apple's equalized prices as `kind=auto`, for reference; they are ignored on import).
|
||||
2. Edit the rows. Apple only takes its own price points: an exact value per territory (the error lists the
|
||||
neighbours); Play takes any price in the region's currency.
|
||||
3. `storebound prices import --dry` (MCP: `prices_diff`) prints the diff table: product, store, region, from, current,
|
||||
new, change %. Show it to the owner.
|
||||
4. The owner runs `storebound prices import` (asks first; not an MCP tool). Apple: one new price schedule per changed
|
||||
product (base territory, default the current one or `prices.baseTerritory`, plus every manual price; territories
|
||||
without one follow Apple's equalization). Play: the purchase option's regional prices are replaced; regions the
|
||||
product has no price for get `convertRegionPrices` from the USD base, `--reconvert` resets every region the CSV
|
||||
does not list.
|
||||
- Future-dated changes (`start_date`) are App Store only; Play has no scheduled prices (change them on the day).
|
||||
- Apple's IAP pricing guide warns that a price **increase cannot be reverted** once it is in effect: tell the owner.
|
||||
- Prices are public the moment the stores apply them. Never import without the owner reading the diff.
|
||||
|
||||
## Gotchas
|
||||
- Play legacy `inappproducts` returns 403 "Please migrate to the new publishing API" -> use
|
||||
`monetization.onetimeproducts`.
|
||||
|
|
|
|||
|
|
@ -36,13 +36,7 @@ Each line: number, level (`BLOCKER`, `warn`, `ok`), store, message, and a `fix:`
|
|||
| app-ads.txt lacks lines / 404 | ad networks cannot verify you | `ads-levelplay-checks`; the file lives at the root of the developer website |
|
||||
| no release on any track | nothing uploaded | `play release <aab>` |
|
||||
| product purchase option DRAFT | not active | `play products` |
|
||||
| user-perceived crash / ANR rate over 1.09 % / 0.47 % (live apps) | Play's bad behavior threshold is crossed | `store-health` skill: `storebound health`, fix the top issues, ship a higher versionCode |
|
||||
| Apple metric rated poor / heavy diagnostic signature | hangs, launches, disk writes | `store-health` skill (Xcode Organizer for the stack) |
|
||||
|
||||
Vitals need the Play Developer Reporting API enabled for the service account; without it `validate` only notes
|
||||
"vitals not readable". `--no-health` skips these checks.
|
||||
|
||||
## What validate cannot see (UI-only, check by hand)
|
||||
App Privacy labels published, Play App content declarations (ads, target audience, content rating, advertising ID),
|
||||
agreements / tax / banking, countries for production on Play. (TestFlight groups and testers: `storebound apple
|
||||
testflight status`.) Tell the owner which are still open.
|
||||
agreements / tax / banking, TestFlight groups, countries for production on Play. Tell the owner which are still open.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: store-screenshots
|
||||
description: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages - capture raw frames from the running game (web build via playwright, iOS Simulator via simctl, Android emulator or device via adb, or a folder of frames from any engine), write per-language marketing copy (incl. RTL Arabic and CJK fonts), render captioned scenes with device frames, review them in a local gallery, A/B variants for Play store listing experiments and App Store Product Page Optimization tests (created and filled through the API), JPEG copies for Play, and upload to both stores. Use when the user needs App Store / Google Play screenshots, preview images, a feature graphic, localized screenshot captions, or screenshot sizes.
|
||||
description: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages - capture raw frames from the running game (web build via playwright, iOS Simulator via simctl, Android emulator or device via adb, or a folder of frames from any engine), write per-language marketing copy (incl. RTL Arabic and CJK fonts), render captioned scenes with device frames, review them in a local gallery, A/B variants for store listing experiments / Product Page Optimization, JPEG copies for Play, and upload to both stores. Use when the user needs App Store / Google Play screenshots, preview images, a feature graphic, localized screenshot captions, or screenshot sizes.
|
||||
---
|
||||
|
||||
# Store screenshots
|
||||
|
|
@ -27,10 +27,8 @@ Sources (re-check before a release; Apple renames display classes often):
|
|||
As of October 2026 the page marks "iPhone with Dynamic Island (medium display)" (1206 x 2622 / 1179 x 2556) as the
|
||||
required iPhone class, and says a class without its own screenshots gets scaled ones from the next class: medium
|
||||
from Face ID large (6.5"), 6.5" from Dynamic Island large (6.9"). So the 6.9" (+ 6.5") set still covers every
|
||||
iPhone, and storebound keeps 6.9" as the default. For pixel-exact art on 6.3" phones (or if App Store Connect ever
|
||||
refuses to submit without the medium set), set `apple.iphoneMedium: true`: the `iphone-medium` size key (1206 x 2622,
|
||||
uploaded as `APP_IPHONE_61`, a mapping inferred from the enum, not verified) is then rendered, checked and uploaded
|
||||
like the others. It stays off by default.
|
||||
iPhone, and storebound keeps 6.9" as the default. If App Store Connect ever refuses to submit without the medium
|
||||
set, render a 1206 x 2622 copy by hand (and open an issue so it becomes a size key).
|
||||
- ASC API `ScreenshotDisplayType`: https://developer.apple.com/documentation/appstoreconnectapi/screenshotdisplaytype
|
||||
(there is no "13 inch" value: the 13" iPad set is `APP_IPAD_PRO_3GEN_129`).
|
||||
- Play graphics: https://support.google.com/googleplay/android-developer/answer/9866151 (screenshots 320-3840 px, at
|
||||
|
|
@ -106,19 +104,9 @@ images there), so only do that after a test has a winner. What the stores offer,
|
|||
treatments against the original, one test at a time, up to 90 days; icon, screenshots and app previews, localized
|
||||
per treatment; new metadata goes through App Review; alternate icons must ship in the binary; shown on iOS / iPadOS
|
||||
15+. https://developer.apple.com/app-store/product-page-optimization/
|
||||
Through the API with storebound (`appStoreVersionExperiments` v2, treatments, treatment localizations and their
|
||||
screenshot sets):
|
||||
1. `storebound shots render --variant b` (and `shots check --variants`, `shots gallery`).
|
||||
2. `storebound apple ppo create --variant b --traffic 30 --dry`, then without `--dry`: one test with one treatment
|
||||
per variant (named after it, max 3 variants: `--variant b,c`) and a localization per App Store locale.
|
||||
3. `storebound apple ppo upload --variant b --dry`, then for real: the variant renders into the treatment's
|
||||
screenshot sets per locale (MD5-idempotent). MCP: `apple_ppo_create`, `apple_ppo_upload`, `apple_ppo_status`.
|
||||
4. **Owner**: `storebound apple ppo start` (asks first; treatments that are not approved yet go to App Review with
|
||||
the next version), later `storebound apple ppo stop` (final: a stopped test cannot be restarted; stopping through
|
||||
the API is `started: false`, not verified against a live test, so if it is refused stop it in App Store
|
||||
Connect). Neither is an MCP tool. Results per treatment are only in App Store Connect.
|
||||
The app must be live (Ready for Distribution); alternate icons and app preview treatments stay App Store Connect
|
||||
clicks.
|
||||
The App Store Connect API has the resources (`appStoreVersionExperiments` v2, treatments, treatment localizations
|
||||
with their own screenshot / preview sets), but storebound does not create or start experiments: set the test up in
|
||||
App Store Connect and upload the treatment screenshots there (the variant folder already has the right sizes).
|
||||
- Test one thing per experiment (usually the first screenshot or the order), give it real traffic, and do not read
|
||||
results early.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,79 +0,0 @@
|
|||
---
|
||||
name: testflight
|
||||
description: Run TestFlight for a mobile game through the App Store Connect API - beta groups (internal / external, public links), testers from a CSV that never enters git, adding a build by its exact number to groups, "What to Test" per locale from the release notes, Test Information, and the Beta App Review submission the owner confirms. Use when the user wants testers on a build, sets up beta groups, writes What to Test, or asks why external testers do not see a build.
|
||||
---
|
||||
|
||||
# TestFlight
|
||||
|
||||
CLI: `storebound apple testflight <status | groups | testers | what-to-test | info | distribute>` (or `bunx storebound`
|
||||
in a project that has it). Every write has `--dry`; run it first and show the plan. API references are cited at the top
|
||||
of `cli/lib/testflight.ts` (developer.apple.com/documentation/appstoreconnectapi: beta groups, beta testers, beta build
|
||||
localizations, beta app localizations, beta app review submissions).
|
||||
|
||||
## Prerequisites
|
||||
- The build is uploaded and processed (`storebound apple status`, `VALID`), with export compliance answered
|
||||
(`storebound apple encryption --build N`, export-compliance skill). A build missing it shows
|
||||
`MISSING_EXPORT_COMPLIANCE` and nobody can test it.
|
||||
- API key role Admin or App Manager.
|
||||
|
||||
## 1. Groups (config, no emails)
|
||||
```ts
|
||||
apple: {
|
||||
testflight: {
|
||||
groups: [
|
||||
{ name: 'Team', internal: true, allBuilds: true }, // App Store Connect users of your team, no review
|
||||
{ name: 'Friends' }, // external, by email, Beta App Review first
|
||||
{ name: 'Public', publicLink: true, publicLinkLimit: 500 },
|
||||
],
|
||||
description: { en: 'Match tiles, clear 60 levels.', tr: '...' }, // Beta App Description per language id
|
||||
reviewNotes: 'No login needed. IAPs are sandbox purchases.',
|
||||
},
|
||||
},
|
||||
```
|
||||
`storebound apple testflight groups --dry`, then without `--dry`. Groups are matched by name; storebound never renames,
|
||||
changes or deletes a group.
|
||||
|
||||
## 2. Testers (CSV in .storebound/, never in git)
|
||||
- Columns: `email,first_name,last_name,groups` (groups separated by `;`). Default path `.storebound/testers.csv`
|
||||
(gitignored); the config refuses a path outside `.storebound/`. Never paste tester emails into chat, docs, issues or
|
||||
commits; storebound masks them in every log line (`j***@example.com`).
|
||||
- `storebound apple testflight testers --dry` shows: new testers, testers added to more groups, (with `--remove`)
|
||||
testers who leave a managed group. The real run **asks first**: Apple emails each new tester an invitation once the
|
||||
group has a build. `--invite` (re)sends invitations to testers still `NOT_INVITED` / `INVITED` (asks again).
|
||||
- Internal groups only take App Store Connect users (Users and Access); add people there first.
|
||||
- Testers are an owner action: not an MCP tool. An agent prepares the CSV format and the dry run, the owner runs it.
|
||||
|
||||
## 3. What to Test
|
||||
- `storebound whats-new` drafts release notes into `store/appstore.md` (`### whatsNew` per locale). For testers you can
|
||||
add a `### whatToTest` block per locale: it wins over `whatsNew` for TestFlight.
|
||||
- `storebound apple testflight what-to-test --build N --dry`, then for real. `--text "..." --locale en-US` sets one
|
||||
text instead. Pick the build by the exact number you uploaded, never "the latest"; `--version x.y.z` when the same
|
||||
build number exists for two versions.
|
||||
- Write it for testers: what changed, what to try, known issues. Short; it is read on a phone. Apple documents no
|
||||
maximum; storebound stops at 4000 characters (assumption, see the README's unverified list).
|
||||
|
||||
## 4. Test Information (needed for external testing)
|
||||
`storebound apple testflight info --dry`: Beta App Description per locale (`apple.testflight.description`), feedback
|
||||
email (`app.contactEmail`), privacy policy and marketing URL, and the Beta App Review contact (from
|
||||
`.storebound/credentials.json` `reviewContact`) plus notes (4000 characters max). Apple requires a description on every
|
||||
beta app localization before a Beta App Review submission, and fields cannot be cleared once set.
|
||||
|
||||
## 5. Distribute
|
||||
- Internal: `storebound apple testflight distribute --build N --group Team --dry`, then for real (MCP:
|
||||
`apple_testflight_distribute`, internal groups only). Groups with `allBuilds: true` get every build automatically.
|
||||
- External: same command with an external group; it asks first. External testers only get the build after **Beta App
|
||||
Review**: add `--submit-review` (asks again) or submit in App Store Connect. The first build of a version is
|
||||
reviewed; later builds of the same version are often approved quickly. Beta review states: `WAITING_FOR_REVIEW`,
|
||||
`IN_REVIEW`, `APPROVED`, `REJECTED` (`storebound apple testflight status` shows internal / external build states).
|
||||
- The Beta App Review submission is public-facing and the owner's call: never through MCP; an agent explains and the
|
||||
owner confirms in the terminal.
|
||||
|
||||
## Gotchas
|
||||
- Builds expire after 90 days in TestFlight; upload a new one (`storebound apple next-build`).
|
||||
- Up to 100 internal testers and 10,000 external testers per app (TestFlight overview in App Store Connect Help:
|
||||
https://developer.apple.com/help/app-store-connect/test-a-beta-version/testflight-overview).
|
||||
- A public link (`publicLink: true`) lets anyone with it join, up to `publicLinkLimit` (1-10000). Share it only where
|
||||
the owner wants; it still needs the approved build.
|
||||
- External testers of a game with IAP buy with sandbox accounts automatically (no charge); say so in What to Test.
|
||||
- Rejected beta review: read the message in App Store Connect > TestFlight, fix, upload a new build, submit again
|
||||
(review-rejections skill for the tone of the reply).
|
||||
|
|
@ -40,16 +40,7 @@ const config: ShipConfig = {
|
|||
// the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.
|
||||
// usesNonExemptEncryption: false,
|
||||
// ipad: true, // the app runs on iPad: 13" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded
|
||||
// iphoneMedium: true, // optional 6.3" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5" set down
|
||||
// screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad)
|
||||
// TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only.
|
||||
testflight: {
|
||||
groups: [
|
||||
{ name: 'Team', internal: true, allBuilds: true },
|
||||
{ name: 'Friends' },
|
||||
],
|
||||
description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' },
|
||||
},
|
||||
info: {
|
||||
categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },
|
||||
ageRating: { advertising: true }, // everything else NONE / false
|
||||
|
|
@ -64,9 +55,6 @@ const config: ShipConfig = {
|
|||
},
|
||||
},
|
||||
|
||||
// Price changes later for many products / regions: storebound prices export, edit store/prices.csv, prices import --dry.
|
||||
// prices: { csv: 'store/prices.csv', baseTerritory: 'USA' },
|
||||
|
||||
// Same ids on both stores. Prices: USD base; Play converts per region, Apple equalizes from the USA. Overrides set a
|
||||
// region by hand (Apple needs an existing price point with exactly that value).
|
||||
products: [
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
email,first_name,last_name,groups
|
||||
|
|
|
@ -1,104 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
appleDaily, appleTotals, bucketName, checksumOk, compareAroundEvents, decodeText, effectMarkdown, effectTable, latestPerDate, mergeSeries, monthsBetween,
|
||||
parseGitLog, parseReport, pickReport, playDaily, playObjects, playTotals, type Snapshot,
|
||||
} from '../cli/lib/analytics';
|
||||
import { validateConfig } from '../cli/lib/config';
|
||||
import { TOOLS, toArgv } from '../cli/mcp-tools';
|
||||
|
||||
const ENG = 'Date\tApp Name\tApp Apple Identifier\tEvent\tPage Type\tSource Type\tEngagement Type\tDevice\tPlatform Version\tTerritory\tCounts\tUnique Counts\n' +
|
||||
'2026-10-01\tExample\t1\tImpression\tProduct page\tApp Store search\t\tiPhone\tiOS 26\tUS\t100\t80\n' +
|
||||
'2026-10-01\tExample\t1\tImpression\tProduct page\tApp Store browse\t\tiPhone\tiOS 26\tTR\t50\t20\n' +
|
||||
'2026-10-01\tExample\t1\tPage view\tProduct page\tApp Store search\t\tiPhone\tiOS 26\tUS\t30\t25\n' +
|
||||
'2026-10-01\tExample\t1\tTap\tProduct page\tApp Store search\t\tiPhone\tiOS 26\tUS\t9\t9\n';
|
||||
const DL = 'Date,App Name,App Apple Identifier,Download Type,App Version,Device,Platform Version,Source Type,Page Type,Pre-Order,Territory,Counts\n' +
|
||||
'2026-10-01,Example,1,First-time Download,1.0,iPhone,iOS 26,App Store search,Product page,,US,10\n' +
|
||||
'2026-10-01,Example,1,Redownload,1.0,iPhone,iOS 26,App Store search,Product page,,US,2\n' +
|
||||
'2026-10-01,Example,1,Auto-update,1.0,iPhone,iOS 26,,,,US,500\n';
|
||||
|
||||
describe('apple analytics reports', () => {
|
||||
test('pick the Standard report by name', () => {
|
||||
const rs = [{ id: 'd', attributes: { name: 'App Store Discovery and Engagement Detailed' } }, { id: 's', attributes: { name: 'App Store Discovery and Engagement Standard' } }, { id: 'x', attributes: { name: 'App Sessions Standard' } }];
|
||||
expect(pickReport(rs, /discovery and engagement/i)!.id).toBe('s');
|
||||
expect(pickReport(rs.slice(0, 1), /discovery and engagement/i)!.id).toBe('d');
|
||||
expect(pickReport(rs, /nope/)).toBeNull();
|
||||
});
|
||||
test('tab and comma files by column name; daily sums', () => {
|
||||
const eng = parseReport(ENG), dl = parseReport(DL);
|
||||
expect(eng[0]!.unique_counts).toBe('80');
|
||||
expect(dl[0]!.download_type).toBe('First-time Download');
|
||||
expect(appleDaily(eng, dl)).toEqual([{ date: '2026-10-01', impressions: 150, uniqueImpressions: 100, pageViews: 30, uniquePageViews: 25, downloads: 12, firstTimeDownloads: 10 }]);
|
||||
expect(appleTotals(appleDaily(eng, dl)).conversion).toBeCloseTo(0.12, 10);
|
||||
});
|
||||
test('a later processingDate replaces the same Date', () => {
|
||||
const rows = latestPerDate([
|
||||
{ processingDate: '2026-10-02', rows: [{ date: '2026-10-01', counts: '1' }] },
|
||||
{ processingDate: '2026-10-04', rows: [{ date: '2026-10-01', counts: '5' }, { date: '2026-10-03', counts: '7' }] },
|
||||
]);
|
||||
expect(rows).toEqual([{ date: '2026-10-01', counts: '5' }, { date: '2026-10-03', counts: '7' }]);
|
||||
});
|
||||
test('md5 checksum and text decoding', () => {
|
||||
const b = new TextEncoder().encode('hello');
|
||||
expect(checksumOk(b, createHash('md5').update(b).digest('hex').toUpperCase())).toBe(true);
|
||||
expect(checksumOk(b, '00')).toBe(false);
|
||||
const utf16 = new Uint8Array([0xff, 0xfe, ...[...'Date,x'].flatMap(c => [c.charCodeAt(0), 0])]);
|
||||
expect(decodeText(utf16)).toBe('Date,x');
|
||||
expect(decodeText(new TextEncoder().encode('ok'))).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
describe('play statistics exports', () => {
|
||||
test('file names, months, bucket', () => {
|
||||
expect(monthsBetween('2026-11-20', '2027-02-01')).toEqual(['202611', '202612', '202701', '202702']);
|
||||
expect(playObjects('com.example.game', '202610')).toEqual({ storePerformance: 'stats/store_performance/store_performance_com.example.game_202610_country.csv', installs: 'stats/installs/installs_com.example.game_202610_country.csv' });
|
||||
expect(bucketName('gs://pubsite_prod_rev_0000/stats')).toBe('pubsite_prod_rev_0000');
|
||||
});
|
||||
test('daily sums across countries', () => {
|
||||
const sp = parseReport('Date,Package name,Country / region,Store listing acquisitions,Store listing visitors,Store listing conversion rate\n2026-10-01,com.example.game,US,10,100,10%\n2026-10-01,com.example.game,TR,5,50,10%\n');
|
||||
const inst = parseReport('Date,Package Name,Country,Daily Device Installs,Daily User Installs\n2026-10-01,com.example.game,US,12,11\n2026-10-02,com.example.game,US,3,3\n');
|
||||
const d = playDaily(sp, inst);
|
||||
expect(d).toEqual([{ date: '2026-10-01', visitors: 150, acquisitions: 15, installs: 11 }, { date: '2026-10-02', visitors: 0, acquisitions: 0, installs: 3 }]);
|
||||
expect(playTotals(d).conversion).toBeCloseTo(0.1, 10);
|
||||
});
|
||||
test('config: reports bucket', () => {
|
||||
const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en' }] };
|
||||
expect(validateConfig({ ...base, play: { packageName: 'com.example.game', reportsBucket: 'gs://pubsite_prod_rev_0000/' } })).toEqual([]);
|
||||
expect(validateConfig({ ...base, play: { packageName: 'com.example.game', reportsBucket: 'my-bucket' } })[0]).toContain('play.reportsBucket');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compare with listing changes', () => {
|
||||
const days = (from: number, n: number, f: (i: number) => { impressions: number; uniqueImpressions: number; downloads: number }) =>
|
||||
Array.from({ length: n }, (_, i) => ({ date: `2026-10-${String(from + i).padStart(2, '0')}`, pageViews: 0, uniquePageViews: 0, firstTimeDownloads: 0, ...f(i) }));
|
||||
const snaps: Snapshot[] = [
|
||||
{ date: '2026-10-08', window: { start: '2026-10-01', end: '2026-10-07', days: 7 }, apple: { daily: days(1, 7, () => ({ impressions: 100, uniqueImpressions: 100, downloads: 5 })), totals: {} } },
|
||||
{ date: '2026-10-15', window: { start: '2026-10-08', end: '2026-10-14', days: 7 }, apple: { daily: days(8, 7, () => ({ impressions: 150, uniqueImpressions: 150, downloads: 12 })), totals: {} }, play: { error: 'no bucket' } },
|
||||
];
|
||||
test('git log parsing', () => {
|
||||
const out = '\x1eabc1234\x1f2026-10-08\x1fnew first screenshot\n\nstore/shots/copy.json\nstore/appstore.md\n\x1edef5678\x1f2026-10-02\x1fsubtitle tweak\n\nstore/appstore.md\n';
|
||||
expect(parseGitLog(out)).toEqual([
|
||||
{ commit: 'abc1234', date: '2026-10-08', subject: 'new first screenshot', files: ['store/shots/copy.json', 'store/appstore.md'] },
|
||||
{ commit: 'def5678', date: '2026-10-02', subject: 'subtitle tweak', files: ['store/appstore.md'] }]);
|
||||
});
|
||||
test('before / after per event', () => {
|
||||
const series = mergeSeries(snaps);
|
||||
expect(series.apple).toHaveLength(14);
|
||||
const fx = compareAroundEvents(series, [{ date: '2026-10-08', commit: 'abc', subject: 'new first screenshot', files: [] }], 7);
|
||||
expect(fx).toHaveLength(1);
|
||||
expect(fx[0]).toMatchObject({ store: 'apple', daysBefore: 7, daysAfter: 7 });
|
||||
expect(fx[0]!.before.conversion).toBeCloseTo(0.05, 10);
|
||||
expect(fx[0]!.after.conversion).toBeCloseTo(0.08, 10);
|
||||
const t = effectTable(fx);
|
||||
expect(t).toContain('100 -> 150 +50%');
|
||||
expect(t).toContain('5.00% -> 8.00%');
|
||||
expect(effectMarkdown(fx)).toContain('| 2026-10-08 | apple | new first screenshot |');
|
||||
expect(effectTable([])).toContain('no listing changes');
|
||||
});
|
||||
test('mcp tools', () => {
|
||||
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||
expect(toArgv(t('analytics_snapshot'), { days: 14 }).argv).toEqual(['analytics', 'snapshot', '--days', '14', '--dry']);
|
||||
expect(t('analytics_compare')).toMatchObject({ write: false, network: false });
|
||||
expect(toArgv(t('analytics_setup'), {}).argv).toEqual(['analytics', 'setup', '--dry']);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,109 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { previousSnapshot } from '../cli/health';
|
||||
import {
|
||||
ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable, issuesQuery,
|
||||
lastValue, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, PLAY_THRESHOLDS, weightedAverage, ymd,
|
||||
} from '../cli/lib/health';
|
||||
import { TOOLS, toArgv } from '../cli/mcp-tools';
|
||||
|
||||
const row = (day: number, values: Record<string, string>, dims: Record<string, string> = {}) => ({
|
||||
startTime: { year: 2026, month: 10, day, timeZone: { id: 'America/Los_Angeles' } },
|
||||
dimensions: Object.entries(dims).map(([dimension, stringValue]) => ({ dimension, stringValue })),
|
||||
metrics: Object.entries(values).map(([metric, value]) => ({ metric, decimalValue: { value } })),
|
||||
});
|
||||
|
||||
describe('reporting api requests', () => {
|
||||
test('DAILY timeline in America/Los_Angeles, exclusive end, the documented metric names', () => {
|
||||
const q = metricQuery(CRASH_METRICS, { year: 2026, month: 10, day: 8 }, 7) as { timelineSpec: Record<string, unknown>; metrics: string[]; dimensions?: string[] };
|
||||
expect(q.timelineSpec).toEqual({ aggregationPeriod: 'DAILY', startTime: { year: 2026, month: 10, day: 1, timeZone: { id: 'America/Los_Angeles' } }, endTime: { year: 2026, month: 10, day: 8, timeZone: { id: 'America/Los_Angeles' } } });
|
||||
expect(q.metrics).toEqual(['userPerceivedCrashRate', 'userPerceivedCrashRate28dUserWeighted', 'crashRate', 'distinctUsers']);
|
||||
expect(ANR_METRICS).toContain('userPerceivedAnrRate28dUserWeighted');
|
||||
expect(q.dimensions).toBeUndefined();
|
||||
expect((metricQuery(['x'], { year: 2026, month: 3, day: 1 }, 1, ['deviceModel']) as { dimensions: string[]; timelineSpec: { startTime: unknown } }).timelineSpec.startTime).toMatchObject({ month: 2, day: 28 });
|
||||
expect(ymd(new Date('2026-01-01T10:00:00Z'), 1)).toEqual({ year: 2025, month: 12, day: 31 });
|
||||
});
|
||||
test('freshness and issue search parameters', () => {
|
||||
expect(latestDailyEnd({ freshnessInfo: { freshnesses: [{ aggregationPeriod: 'HOURLY', latestEndTime: { year: 2026, month: 10, day: 9 } }, { aggregationPeriod: 'DAILY', latestEndTime: { year: 2026, month: 10, day: 8 } }] } })).toEqual({ year: 2026, month: 10, day: 8 });
|
||||
expect(latestDailyEnd({})).toBeNull();
|
||||
const p = new URLSearchParams(issuesQuery({ year: 2026, month: 10, day: 8 }, 7, { type: 'CRASH' }));
|
||||
expect(p.get('interval.startTime.day')).toBe('1');
|
||||
expect(p.get('interval.endTime.timeZone.id')).toBe('America/Los_Angeles');
|
||||
expect(p.get('filter')).toBe('errorIssueType = CRASH');
|
||||
expect(p.get('orderBy')).toBe('errorReportCount desc');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parsing', () => {
|
||||
const crash = parseMetricRows({ rows: [row(2, { userPerceivedCrashRate: '0.004', distinctUsers: '1000', userPerceivedCrashRate28dUserWeighted: '0.006' }), row(1, { userPerceivedCrashRate: '0.010', distinctUsers: '3000' })] });
|
||||
test('rows sorted by date, decimals as numbers, weighted averages', () => {
|
||||
expect(crash.map(r => r.date)).toEqual(['2026-10-01', '2026-10-02']);
|
||||
expect(lastValue(crash, 'userPerceivedCrashRate28dUserWeighted')).toBe(0.006);
|
||||
expect(lastValue(crash, 'nope')).toBeNull();
|
||||
expect(weightedAverage(crash, 'userPerceivedCrashRate')).toBeCloseTo((0.01 * 3000 + 0.004 * 1000) / 4000, 10);
|
||||
});
|
||||
test('devices: weighted per model, small samples dropped, worst first', () => {
|
||||
const c = parseMetricRows({ rows: [row(1, { userPerceivedCrashRate: '0.09', distinctUsers: '600' }, { deviceModel: 'acme/old' }), row(1, { userPerceivedCrashRate: '0.5', distinctUsers: '10' }, { deviceModel: 'acme/rare' }),
|
||||
row(1, { userPerceivedCrashRate: '0.01', distinctUsers: '5000' }, { deviceModel: 'acme/new' })] });
|
||||
const d = deviceBreakdown(c, []);
|
||||
expect(d.map(x => x.model)).toEqual(['acme/old', 'acme/new']);
|
||||
expect(d[0]!.crash).toBeCloseTo(0.09, 10);
|
||||
});
|
||||
test('issues, Apple metrics, TestFlight crashes', () => {
|
||||
expect(parseIssues({ errorIssues: [{ type: 'APPLICATION_NOT_RESPONDING', cause: 'Input dispatching timed out', location: 'com.example.Main', errorReportCount: '12', distinctUsers: '9', lastAppVersion: { versionCode: '42' } }] }))
|
||||
.toEqual([{ type: 'ANR', cause: 'Input dispatching timed out', location: 'com.example.Main', reports: 12, users: 9, lastVersion: '42', uri: undefined }]);
|
||||
const perf = parsePerfPower({ productData: [{ metricCategories: [{ identifier: 'HANG', metrics: [{ identifier: 'hangRate', unit: { displayName: 's/hr' },
|
||||
datasets: [{ filterCriteria: { device: 'all_iphones', percentile: 'percentile.fifty' }, points: [{ version: '1.0', value: 0.5, goal: 'good' }, { version: '1.1', value: 4.2, goal: 'poor' }] }] }] }] }] });
|
||||
expect(perf).toEqual([{ category: 'HANG', metric: 'hangRate', unit: 's/hr', version: '1.1', value: 4.2, goal: 'poor' }]);
|
||||
const subs = [{ attributes: { createdDate: '2026-10-05T10:00:00Z' }, relationships: { build: { data: { id: 'b1' } } } }, { attributes: { createdDate: '2026-10-06T10:00:00Z' }, relationships: { build: { data: { id: 'b1' } } } },
|
||||
{ attributes: { createdDate: '2026-09-01T10:00:00Z' }, relationships: { build: { data: { id: 'b1' } } } }];
|
||||
expect(betaCrashCounts(subs, new Map([['b1', '42']]), '2026-10-01')).toEqual([{ build: '42', count: 2 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findings and report', () => {
|
||||
const play = (crash: string, anr: string) => ({ window: { start: '2026-10-01', end: '2026-10-08', days: 7 },
|
||||
crash: parseMetricRows({ rows: [row(7, { userPerceivedCrashRate: crash, userPerceivedCrashRate28dUserWeighted: crash, distinctUsers: '1000' })] }),
|
||||
anr: parseMetricRows({ rows: [row(7, { userPerceivedAnrRate: anr, userPerceivedAnrRate28dUserWeighted: anr, distinctUsers: '1000' })] }), devices: [], issues: [] });
|
||||
test('thresholds: over = blocker, from 80 % = warn, under = ok', () => {
|
||||
expect(PLAY_THRESHOLDS).toEqual({ crash: 0.0109, anr: 0.0047, perDevice: 0.08 });
|
||||
const levels = (h: HealthSnapshot) => Object.fromEntries(healthFindings(h).map(f => [f.code, f.level]));
|
||||
expect(levels({ date: 'd', play: play('0.0120', '0.0010') })).toEqual({ 'vitals-crash': 'blocker', 'vitals-anr': 'ok' });
|
||||
expect(levels({ date: 'd', play: play('0.0090', '0.0040') })).toEqual({ 'vitals-crash': 'warn', 'vitals-anr': 'warn' });
|
||||
const dev = healthFindings({ date: 'd', play: { ...play('0.001', '0.001'), devices: [{ model: 'acme/old', crash: 0.09, users: 600 }] } });
|
||||
expect(dev.find(f => f.code === 'vitals-device')).toMatchObject({ level: 'blocker' });
|
||||
expect(healthFindings({ date: 'd', play: { error: '403 forbidden' } })[0]).toMatchObject({ level: 'warn', code: 'vitals' });
|
||||
expect(healthFindings({ date: 'd', play: { error: '403' } }, { unreadable: 'ok' })[0]!.level).toBe('ok');
|
||||
expect(healthFindings({ date: 'd', play: { ...play('0', '0'), crash: [], anr: [] } })[0]!.msg).toContain('no vitals data yet');
|
||||
const apple = healthFindings({ date: 'd', apple: { metrics: [{ category: 'HANG', metric: 'hangRate', unit: 's/hr', version: '1.1', value: 4, goal: 'poor' }], signatures: [{ build: '42', type: 'HANGS', signature: 'main thread', weight: 0.4 }], betaCrashes: [] } });
|
||||
expect(apple.map(f => f.level)).toEqual(['warn', 'warn']);
|
||||
});
|
||||
test('table and markdown with week-over-week change', () => {
|
||||
const h: HealthSnapshot = { date: '2026-10-09', play: { ...play('0.0120', '0.0010'), issues: [{ type: 'CRASH', cause: 'NullPointerException', location: 'Main.kt', reports: 5, users: 4, lastVersion: '42' }] },
|
||||
apple: { metrics: [], signatures: [], betaCrashes: [{ build: '42', count: 2 }] } };
|
||||
const t = healthTable(h);
|
||||
expect(t).toContain('1.20%');
|
||||
expect(t).toContain('TestFlight crash reports');
|
||||
const md = healthMarkdown(h, { appName: 'Example Game', previous: { date: '2026-10-02', play: play('0.0100', '0.0010') } });
|
||||
expect(md).toContain('# Health report · Example Game · 2026-10-09');
|
||||
expect(md).toContain('OVER THRESHOLD');
|
||||
expect(md).toContain('+0.20 pt');
|
||||
expect(md).toContain('| CRASH | NullPointerException | Main.kt | 5 | 4 | 42 |');
|
||||
});
|
||||
test('previous snapshot is the newest one before today', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'storebound-health-'));
|
||||
writeFileSync(join(dir, '2026-09-25.json'), JSON.stringify({ date: '2026-09-25' }));
|
||||
writeFileSync(join(dir, '2026-10-02.json'), JSON.stringify({ date: '2026-10-02' }));
|
||||
writeFileSync(join(dir, '2026-10-09.json'), JSON.stringify({ date: '2026-10-09' }));
|
||||
expect(previousSnapshot(dir, '2026-10-09')!.date).toBe('2026-10-02');
|
||||
expect(previousSnapshot(join(dir, 'none'), '2026-10-09')).toBeNull();
|
||||
});
|
||||
test('mcp: health is read-only, the report is a dry-by-default local write', () => {
|
||||
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||
expect(t('health')).toMatchObject({ write: false, network: true });
|
||||
expect(toArgv(t('health'), { store: 'play', days: 28 }).argv).toEqual(['health', '--play', '--days', '28']);
|
||||
expect(toArgv(t('health_report'), {}).argv).toEqual(['health', '--weekly', '--dry']);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { join } from 'node:path';
|
||||
import { eraOf, handle, LEGACY, LEGACY_PROTOCOL, META, PROTOCOL, SUPPORTED, TOOLS_TTL_MS, UNSUPPORTED_PROTOCOL_VERSION } from '../cli/mcp';
|
||||
import { TOOLS } from '../cli/mcp-tools';
|
||||
|
||||
const modernMeta = (v = PROTOCOL, caps: unknown = {}) => ({ [META.protocolVersion]: v, [META.clientCapabilities]: caps, [META.clientInfo]: { name: 'test', version: '1' } });
|
||||
type R = Record<string, unknown>;
|
||||
const res = (r: Record<string, unknown> | null) => r!.result as R;
|
||||
const errOf = (r: Record<string, unknown> | null) => r!.error as { code: number; message: string; data?: R };
|
||||
|
||||
describe('mcp 2026-07-28 (modern, stateless)', () => {
|
||||
test('server/discover: versions, capabilities, instructions, serverInfo in _meta, cacheable', async () => {
|
||||
const r = res(await handle({ jsonrpc: '2.0', id: 'd1', method: 'server/discover', params: { _meta: modernMeta() } }));
|
||||
expect(r.resultType).toBe('complete');
|
||||
expect(r.supportedVersions).toEqual(SUPPORTED);
|
||||
expect((r.supportedVersions as string[])[0]).toBe('2026-07-28');
|
||||
expect(r.capabilities).toEqual({ tools: {} });
|
||||
expect(typeof r.instructions).toBe('string');
|
||||
expect((r._meta as R)[META.serverInfo]).toMatchObject({ name: 'storebound' });
|
||||
expect(r).toMatchObject({ ttlMs: TOOLS_TTL_MS, cacheScope: 'public' });
|
||||
expect(r.protocolVersion).toBeUndefined();
|
||||
});
|
||||
test('tools/list and tools/call without any handshake', async () => {
|
||||
const list = res(await handle({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: { _meta: modernMeta() } }));
|
||||
expect(list.resultType).toBe('complete');
|
||||
expect((list.tools as unknown[]).length).toBe(TOOLS.length);
|
||||
expect(list).toMatchObject({ ttlMs: TOOLS_TTL_MS, cacheScope: 'public' });
|
||||
let seen: string[] = [];
|
||||
const call = res(await handle({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'check', arguments: {}, _meta: modernMeta() } }, async argv => { seen = argv; return { code: 0, out: 'ok' }; }));
|
||||
expect(seen).toEqual(['check']);
|
||||
expect(call).toMatchObject({ resultType: 'complete', isError: false, structuredContent: { exitCode: 0, dryRun: false } });
|
||||
expect((call._meta as R)[META.serverInfo]).toBeDefined();
|
||||
});
|
||||
test('version and _meta errors', async () => {
|
||||
const bad = errOf(await handle({ jsonrpc: '2.0', id: 3, method: 'tools/list', params: { _meta: modernMeta('2099-01-01') } }));
|
||||
expect(bad.code).toBe(UNSUPPORTED_PROTOCOL_VERSION);
|
||||
expect(bad.code).toBe(-32022);
|
||||
expect(bad.data).toEqual({ supported: SUPPORTED, requested: '2099-01-01' });
|
||||
const noCaps = errOf(await handle({ jsonrpc: '2.0', id: 4, method: 'tools/list', params: { _meta: { [META.protocolVersion]: PROTOCOL } } }));
|
||||
expect(noCaps.code).toBe(-32602);
|
||||
expect(noCaps.message).toContain('clientCapabilities');
|
||||
const probe = errOf(await handle({ jsonrpc: '2.0', id: 5, method: 'server/discover', params: {} }));
|
||||
expect(probe.code).toBe(-32602);
|
||||
expect(errOf(await handle({ jsonrpc: '2.0', id: 6, method: 'resources/list', params: { _meta: modernMeta() } })).code).toBe(-32601);
|
||||
const unknownTool = errOf(await handle({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'apple_submit', _meta: modernMeta() } }));
|
||||
expect(unknownTool.code).toBe(-32602);
|
||||
});
|
||||
test('era detection', () => {
|
||||
expect(eraOf({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: { _meta: modernMeta() } })).toEqual({ era: 'modern', version: PROTOCOL });
|
||||
expect(eraOf({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: { _meta: modernMeta(LEGACY_PROTOCOL) } }).era).toBe('legacy');
|
||||
expect(eraOf({ jsonrpc: '2.0', id: 1, method: 'tools/list' })).toEqual({ era: 'legacy', version: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('mcp 2025-11-25 (legacy handshake) stays compatible', () => {
|
||||
test('initialize negotiates a legacy version; results have no resultType', async () => {
|
||||
const init = res(await handle({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'old', version: '1' } } }));
|
||||
expect(init.protocolVersion).toBe('2025-11-25');
|
||||
expect(init.capabilities).toEqual({ tools: { listChanged: false } });
|
||||
expect(res(await handle({ jsonrpc: '2.0', id: 2, method: 'initialize', params: { protocolVersion: '2025-06-18' } })).protocolVersion).toBe('2025-06-18');
|
||||
// a modern client that wrongly sends initialize with the modern version gets the newest legacy version back
|
||||
expect(res(await handle({ jsonrpc: '2.0', id: 3, method: 'initialize', params: { protocolVersion: PROTOCOL } })).protocolVersion).toBe(LEGACY_PROTOCOL);
|
||||
expect(await handle({ jsonrpc: '2.0', method: 'notifications/initialized' })).toBeNull();
|
||||
expect(res(await handle({ jsonrpc: '2.0', id: 4, method: 'ping' }))).toEqual({});
|
||||
const list = res(await handle({ jsonrpc: '2.0', id: 5, method: 'tools/list' }));
|
||||
expect(list.resultType).toBeUndefined();
|
||||
expect(list.ttlMs).toBeUndefined();
|
||||
expect(LEGACY).toEqual(['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stdio end to end', () => {
|
||||
test('one process answers a modern probe and a legacy handshake', async () => {
|
||||
const p = Bun.spawn([process.execPath, join(import.meta.dir, '..', 'cli', 'index.ts'), 'mcp'], { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
|
||||
const lines = [
|
||||
{ jsonrpc: '2.0', id: 'probe', method: 'server/discover', params: { _meta: modernMeta() } },
|
||||
{ jsonrpc: '2.0', id: 'old', method: 'server/discover', params: { _meta: modernMeta('1999-01-01') } },
|
||||
{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'legacy', version: '1' } } },
|
||||
{ jsonrpc: '2.0', method: 'notifications/initialized' },
|
||||
{ jsonrpc: '2.0', id: 2, method: 'tools/list' },
|
||||
{ jsonrpc: '2.0', id: 3, method: 'tools/list', params: { _meta: modernMeta() } },
|
||||
];
|
||||
p.stdin.write(lines.map(l => JSON.stringify(l)).join('\n') + '\n');
|
||||
p.stdin.end();
|
||||
const out = await new Response(p.stdout).text();
|
||||
await p.exited;
|
||||
const byId = new Map(out.trim().split('\n').map(l => JSON.parse(l) as R).map(r => [r.id, r] as const));
|
||||
expect((byId.get('probe')!.result as R).supportedVersions).toContain('2026-07-28');
|
||||
expect((byId.get('old')!.error as R).code).toBe(-32022);
|
||||
expect((byId.get(1)!.result as R).protocolVersion).toBe('2025-11-25');
|
||||
expect((byId.get(2)!.result as R).resultType).toBeUndefined();
|
||||
expect((byId.get(3)!.result as R).resultType).toBe('complete');
|
||||
expect(byId.size).toBe(5);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { displaySets } from '../cli/apple/screenshots';
|
||||
import { checkCreate, createExperimentReq, defaultName, experimentFromApi, pickExperiment, planTreatmentLocales, planTreatments, startStopReq } from '../cli/lib/ppo';
|
||||
import { validateConfig } from '../cli/lib/config';
|
||||
import { FORBIDDEN_ARGS, TOOLS, toArgv, validateInput } from '../cli/mcp-tools';
|
||||
import { requiredSets } from '../cli/shots/report';
|
||||
import { defaultSizes, SIZES } from '../cli/shots/lib';
|
||||
import { checkImage, IMAGE_SPECS, imageInfo } from '../cli/shots/spec';
|
||||
import { png } from './fixtures';
|
||||
|
||||
describe('product page optimization', () => {
|
||||
test('create options', () => {
|
||||
expect(checkCreate(['b'], 30, ['b', 'c'])).toEqual([]);
|
||||
expect(checkCreate([], 30, ['b']).join()).toContain('--variant');
|
||||
expect(checkCreate(['b', 'c', 'd', 'e'], 30, ['b', 'c', 'd', 'e']).join()).toContain('at most 3');
|
||||
expect(checkCreate(['z'], 30, ['b']).join()).toContain('unknown variant "z"');
|
||||
expect(checkCreate(['b'], 0, ['b']).join()).toContain('--traffic');
|
||||
expect(defaultName(['b', 'c'])).toBe('storebound b + c');
|
||||
expect(createExperimentReq('app1', 'T', 30).body).toEqual({ data: { type: 'appStoreVersionExperiments', attributes: { name: 'T', platform: 'IOS', trafficProportion: 30 }, relationships: { app: { data: { type: 'apps', id: 'app1' } } } } });
|
||||
});
|
||||
test('picking a test', () => {
|
||||
const list = [
|
||||
experimentFromApi({ id: 'e1', attributes: { name: 'old', state: 'COMPLETED' } }),
|
||||
experimentFromApi({ id: 'e2', attributes: { name: 'new', state: 'PREPARE_FOR_SUBMISSION', trafficProportion: 30 } }),
|
||||
];
|
||||
expect(pickExperiment(list)!.id).toBe('e2');
|
||||
expect(pickExperiment(list, 'new')!.trafficProportion).toBe(30);
|
||||
expect(pickExperiment(list, 'missing')).toBeNull();
|
||||
expect(() => pickExperiment(list, 'old')).toThrow('cannot be restarted');
|
||||
expect(() => pickExperiment([...list, experimentFromApi({ id: 'e3', attributes: { name: 'x', state: 'READY_FOR_REVIEW' } })])).toThrow('--experiment');
|
||||
});
|
||||
test('treatments and localizations', () => {
|
||||
const t = planTreatments('e2', [{ id: 't1', name: 'b' }], ['b', 'c']);
|
||||
expect(t).toHaveLength(1);
|
||||
expect(t[0]!.body).toEqual({ data: { type: 'appStoreVersionExperimentTreatments', attributes: { name: 'c' }, relationships: { appStoreVersionExperimentV2: { data: { type: 'appStoreVersionExperiments', id: 'e2' } } } } });
|
||||
expect(() => planTreatments('e2', [{ id: '1', name: 'a' }, { id: '2', name: 'b' }, { id: '3', name: 'c' }], ['d'])).toThrow('at most 3');
|
||||
const l = planTreatmentLocales('t1', ['en-US'], ['en-US', 'tr']);
|
||||
expect(l.map(r => (r.body as { data: { attributes: { locale: string } } }).data.attributes.locale)).toEqual(['tr']);
|
||||
expect((l[0]!.body as { data: { relationships: unknown } }).data.relationships).toEqual({ appStoreVersionExperimentTreatment: { data: { type: 'appStoreVersionExperimentTreatments', id: 't1' } } });
|
||||
});
|
||||
test('start / stop', () => {
|
||||
const e = experimentFromApi({ id: 'e2', attributes: { name: 'new', state: 'PREPARE_FOR_SUBMISSION' } });
|
||||
expect(startStopReq(e, true)).toMatchObject({ method: 'PATCH', path: '/v2/appStoreVersionExperiments/e2', body: { data: { type: 'appStoreVersionExperiments', id: 'e2', attributes: { started: true } } } });
|
||||
expect(() => startStopReq({ ...e, state: 'STOPPED' }, false)).toThrow('already STOPPED');
|
||||
expect(() => startStopReq({ ...e, state: 'COMPLETED' }, true)).toThrow('cannot start');
|
||||
});
|
||||
test('mcp: status / create / upload, never start or stop', () => {
|
||||
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||
expect(t('apple_ppo_status').write).toBe(false);
|
||||
expect(toArgv(t('apple_ppo_create'), { variants: 'b,c', traffic: 20 }).argv).toEqual(['apple', 'ppo', 'create', '--variant', 'b,c', '--traffic', '20', '--dry']);
|
||||
expect(toArgv(t('apple_ppo_upload'), { variant: 'b', only: 'en-US' }).argv).toEqual(['apple', 'ppo', 'upload', '--variant', 'b', '--only', 'en-US', '--dry']);
|
||||
expect(validateInput(t('apple_ppo_create'), { variants: 'a,b,c,d' })[0]).toContain('does not match');
|
||||
expect(FORBIDDEN_ARGS).toEqual(expect.arrayContaining(['start', 'stop']));
|
||||
});
|
||||
});
|
||||
|
||||
describe('optional 6.3" iPhone size (iphone-medium)', () => {
|
||||
const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en', apple: 'en-US' }] };
|
||||
test('off by default, on with apple.iphoneMedium', () => {
|
||||
expect(SIZES['iphone-medium']).toEqual({ w: 1206, h: 2622 });
|
||||
expect(defaultSizes({ apple: { bundleId: 'x' } })).not.toContain('iphone-medium');
|
||||
expect(defaultSizes({ apple: { bundleId: 'x', iphoneMedium: true } })).toContain('iphone-medium');
|
||||
expect(defaultSizes({ play: { packageName: 'x' } })).not.toContain('iphone-medium');
|
||||
expect(Object.keys(displaySets({}))).toEqual(['ios69', 'ios65']);
|
||||
expect(displaySets({ iphoneMedium: true, ipad: true })).toEqual({ ios69: 'APP_IPHONE_67', ios65: 'APP_IPHONE_65', 'iphone-medium': 'APP_IPHONE_61', ipad13: 'APP_IPAD_PRO_3GEN_129' });
|
||||
expect(requiredSets({ apple: {} })['iphone-medium']).toBeUndefined();
|
||||
expect(requiredSets({ apple: { iphoneMedium: true } })['iphone-medium']).toBe(true);
|
||||
expect(validateConfig({ ...base, apple: { bundleId: 'com.example.game', iphoneMedium: true } })).toEqual([]);
|
||||
});
|
||||
test('accepted pixel sizes', () => {
|
||||
expect(IMAGE_SPECS['iphone-medium']!.type).toBe('APP_IPHONE_61');
|
||||
expect(checkImage(imageInfo(png(1206, 2622)), 'iphone-medium')).toEqual([]);
|
||||
expect(checkImage(imageInfo(png(1179, 2556)), 'iphone-medium')).toEqual([]);
|
||||
expect(checkImage(imageInfo(png(1320, 2868)), 'iphone-medium').map(i => i.code)).toEqual(['size']);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,140 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
alpha2, appleSchedule, appleScheduleBody, applePriceRows, diffPrices, diffTable, parsePriceCsv, playPatchBody, playPriceRows, playRegions, pointKey,
|
||||
type PriceRow, pricesCsv, sameSchedule,
|
||||
} from '../cli/lib/prices';
|
||||
import { TOOLS, toArgv } from '../cli/mcp-tools';
|
||||
|
||||
const P = 'com.example.game.remove_ads';
|
||||
const csv = `product,store,region,currency,price,start_date
|
||||
${P},both,US,USD,2.99,
|
||||
${P},apple,TR,TRY,99.99,
|
||||
${P},apple,TR,TRY,129.99,2026-12-01
|
||||
${P},play,TR,TRY,109.99,
|
||||
`;
|
||||
|
||||
describe('price csv', () => {
|
||||
test('parse: both expands, apple territory, scheduled change', () => {
|
||||
const rows = parsePriceCsv(csv, { products: [P], today: '2026-10-10' });
|
||||
expect(rows.map(r => `${r.store} ${r.region} ${r.territory ?? '-'} ${r.price} ${r.startDate ?? ''}`)).toEqual([
|
||||
'apple US USA 2.99 ', 'play US - 2.99 ', 'apple TR TUR 99.99 ', 'apple TR TUR 129.99 2026-12-01', 'play TR - 109.99 ']);
|
||||
});
|
||||
test('parse errors are all reported', () => {
|
||||
const bad = `product,store,region,currency,price,start_date
|
||||
nope id,apple,US,USD,1,
|
||||
${P},web,USA,usd,-1,
|
||||
${P},play,TR,TRY,10,2026-12-01
|
||||
${P},apple,TR,TRY,10,2026-01-01
|
||||
${P},apple,US,USD,1,
|
||||
${P},apple,US,USD,1,
|
||||
x.y,apple,ZZ,USD,1,
|
||||
`;
|
||||
try { parsePriceCsv(bad, { products: [P], today: '2026-10-10' }); throw new Error('no'); } catch (e) {
|
||||
const m = String(e);
|
||||
for (const s of ['row 2: product "nope id"', 'store must be apple, play or both', 'must be ISO alpha-2', 'price must be a positive number', 'App Store only (Play has no scheduled prices)',
|
||||
'is not in the future', 'listed twice', 'x.y is not in products[]', 'no App Store territory known for ZZ']) expect(m).toContain(s);
|
||||
}
|
||||
});
|
||||
test('csv round trip', () => {
|
||||
const rows = parsePriceCsv(csv, { today: '2026-10-10' });
|
||||
const out = pricesCsv(rows);
|
||||
expect(out.split('\n')[0]).toBe('product,store,region,currency,price,start_date,kind');
|
||||
expect(out).toContain(`${P},apple,TR,TRY,129.99,2026-12-01,manual`);
|
||||
expect(parsePriceCsv(out, { today: '2026-10-10' })).toHaveLength(rows.length);
|
||||
expect(alpha2('TUR')).toBe('TR');
|
||||
});
|
||||
});
|
||||
|
||||
describe('store state -> rows', () => {
|
||||
test('apple manual prices with included price points and territories', () => {
|
||||
const rows = applePriceRows(P, {
|
||||
data: [{ attributes: { startDate: null }, relationships: { inAppPurchasePricePoint: { data: { id: 'pp-us' } }, territory: { data: { id: 'USA' } } } },
|
||||
{ attributes: { startDate: '2026-12-01' }, relationships: { inAppPurchasePricePoint: { data: { id: 'pp-tr' } }, territory: { data: { id: 'TUR' } } } }],
|
||||
included: [{ type: 'inAppPurchasePricePoints', id: 'pp-us', attributes: { customerPrice: '2.99' } }, { type: 'inAppPurchasePricePoints', id: 'pp-tr', attributes: { customerPrice: '129.99' } },
|
||||
{ type: 'territories', id: 'USA', attributes: { currency: 'USD' } }, { type: 'territories', id: 'TUR', attributes: { currency: 'TRY' } }],
|
||||
});
|
||||
expect(rows).toEqual([
|
||||
{ product: P, store: 'apple', region: 'US', territory: 'USA', currency: 'USD', price: 2.99, pointId: 'pp-us' },
|
||||
{ product: P, store: 'apple', region: 'TR', territory: 'TUR', currency: 'TRY', price: 129.99, pointId: 'pp-tr', startDate: '2026-12-01' }]);
|
||||
});
|
||||
test('play regional configs', () => {
|
||||
expect(playPriceRows({ productId: P, purchaseOptions: [{ purchaseOptionId: 'buy', regionalPricingAndAvailabilityConfigs: [
|
||||
{ regionCode: 'US', price: { currencyCode: 'USD', units: '2', nanos: 990000000 }, availability: 'AVAILABLE' },
|
||||
{ regionCode: 'RU', price: { currencyCode: 'RUB', units: '100' }, availability: 'NO_LONGER_AVAILABLE' }] }] }))
|
||||
.toEqual([{ product: P, store: 'play', region: 'US', currency: 'USD', price: 2.99 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('diff', () => {
|
||||
const current: PriceRow[] = [
|
||||
{ product: P, store: 'apple', region: 'US', territory: 'USA', currency: 'USD', price: 2.99 },
|
||||
{ product: P, store: 'apple', region: 'DE', territory: 'DEU', currency: 'EUR', price: 2.99, kind: 'auto' },
|
||||
{ product: P, store: 'play', region: 'TR', currency: 'TRY', price: 99.99 },
|
||||
];
|
||||
test('same / change / new (auto prices count as new manual ones)', () => {
|
||||
const wanted = parsePriceCsv(`product,store,region,currency,price\n${P},apple,US,USD,2.99\n${P},apple,DE,EUR,3.49\n${P},play,TR,TRY,109.99\n${P},play,JP,JPY,450\n`);
|
||||
expect(diffPrices(current, wanted).map(d => `${d.store} ${d.region} ${d.from} -> ${d.to} ${d.change}`)).toEqual([
|
||||
'apple US 2.99 -> 2.99 same', 'apple DE 2.99 -> 3.49 new', 'play TR 99.99 -> 109.99 change', 'play JP null -> 450 new']);
|
||||
const t = diffTable(diffPrices(current, wanted));
|
||||
expect(t).toContain('+10.0%');
|
||||
expect(t).not.toContain(' US ');
|
||||
expect(diffTable([])).toBe('no price changes');
|
||||
});
|
||||
});
|
||||
|
||||
describe('play regions', () => {
|
||||
const conv = { US: { regionCode: 'US', price: { currencyCode: 'USD', units: '2', nanos: 990000000 } }, TR: { regionCode: 'TR', price: { currencyCode: 'TRY', units: '89', nanos: 990000000 } },
|
||||
JP: { regionCode: 'JP', price: { currencyCode: 'JPY', units: '450' } } };
|
||||
const cur = [{ regionCode: 'US', price: { currencyCode: 'USD', units: '2', nanos: 990000000 } }, { regionCode: 'TR', price: { currencyCode: 'TRY', units: '99', nanos: 990000000 } }];
|
||||
test('csv over current, converted fills new regions, reconvert resets unlisted', () => {
|
||||
const want = parsePriceCsv(`product,store,region,currency,price\n${P},play,TR,TRY,109.99\n`);
|
||||
const r = playRegions(cur, want, conv);
|
||||
expect(r.map(x => `${x.regionCode} ${x.price.units}.${(x.price.nanos ?? 0) / 1e7}`)).toEqual(['JP 450.0', 'TR 109.99', 'US 2.99']);
|
||||
const r2 = playRegions([{ regionCode: 'JP', price: { currencyCode: 'JPY', units: '600' } }], [], conv, { reconvert: true });
|
||||
expect(r2.find(x => x.regionCode === 'JP')!.price.units).toBe('450');
|
||||
expect(() => playRegions(cur, parsePriceCsv(`product,store,region,currency,price\n${P},play,TR,USD,3\n`), conv)).toThrow('prices this region in TRY');
|
||||
expect(() => playRegions(cur, parsePriceCsv(`product,store,region,currency,price\n${P},play,KP,KPW,3\n`), conv)).toThrow('does not sell in region KP');
|
||||
});
|
||||
test('patch body replaces only the purchase option prices and drops output-only state', () => {
|
||||
const body = playPatchBody({ productId: P, listings: [{ languageCode: 'en-US' }], purchaseOptions: [{ purchaseOptionId: 'buy', state: 'ACTIVE', buyOption: { legacyCompatible: true }, regionalPricingAndAvailabilityConfigs: [] }] },
|
||||
[{ regionCode: 'US', availability: 'AVAILABLE', price: { currencyCode: 'USD', units: '1' } }]);
|
||||
expect(body.purchaseOptions![0]).toEqual({ purchaseOptionId: 'buy', buyOption: { legacyCompatible: true }, regionalPricingAndAvailabilityConfigs: [{ regionCode: 'US', availability: 'AVAILABLE', price: { currencyCode: 'USD', units: '1' } }] });
|
||||
expect(body.listings).toEqual([{ languageCode: 'en-US' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('apple schedule', () => {
|
||||
const cur: PriceRow[] = [
|
||||
{ product: P, store: 'apple', region: 'US', territory: 'USA', currency: 'USD', price: 2.99, pointId: 'pp-us' },
|
||||
{ product: P, store: 'apple', region: 'TR', territory: 'TUR', currency: 'TRY', price: 99.99, pointId: 'pp-tr' },
|
||||
{ product: P, store: 'apple', region: 'JP', territory: 'JPN', currency: 'JPY', price: 400, pointId: 'pp-jp' },
|
||||
];
|
||||
test('csv territories replaced, dated rows keep the current price, others kept, base first', () => {
|
||||
const want = parsePriceCsv(`product,store,region,currency,price,start_date\n${P},apple,TR,TRY,129.99,2026-12-01\n${P},apple,JP,JPY,500,\n`, { today: '2026-10-10' });
|
||||
const s = appleSchedule(cur, want, 'USA');
|
||||
expect(s).toEqual([
|
||||
{ territory: 'USA', price: 2.99, startDate: null },
|
||||
{ territory: 'JPN', price: 500, startDate: null },
|
||||
{ territory: 'TUR', price: 99.99, startDate: null },
|
||||
{ territory: 'TUR', price: 129.99, startDate: '2026-12-01' }]);
|
||||
expect(sameSchedule(s, s.slice().reverse())).toBe(true);
|
||||
expect(sameSchedule(s, s.slice(1))).toBe(false);
|
||||
expect(() => appleSchedule([], want, 'USA')).toThrow('base territory USA needs a current price');
|
||||
});
|
||||
test('schedule body with local ids and price point ids', () => {
|
||||
const entries = [{ territory: 'USA', price: 2.99, startDate: null }, { territory: 'TUR', price: 129.99, startDate: '2026-12-01' }];
|
||||
const points = new Map([[pointKey('USA', 2.99), 'pp-us'], [pointKey('TUR', '129.99'), 'pp-tr2']]);
|
||||
const body = appleScheduleBody('iap1', 'USA', entries, points) as { data: { relationships: Record<string, { data: unknown }> }; included: unknown[] };
|
||||
expect(body.data.relationships.baseTerritory!.data).toEqual({ type: 'territories', id: 'USA' });
|
||||
expect(body.data.relationships.manualPrices!.data).toEqual([{ type: 'inAppPurchasePrices', id: '${p0}' }, { type: 'inAppPurchasePrices', id: '${p1}' }]);
|
||||
expect(body.included[1]).toEqual({ type: 'inAppPurchasePrices', id: '${p1}', attributes: { startDate: '2026-12-01' },
|
||||
relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: 'iap1' } }, inAppPurchasePricePoint: { data: { type: 'inAppPurchasePricePoints', id: 'pp-tr2' } } } });
|
||||
expect(() => appleScheduleBody('iap1', 'USA', [{ territory: 'GBR', price: 1, startDate: null }], points)).toThrow('no price point id for GBR 1');
|
||||
});
|
||||
test('mcp: diff is read-only with --dry, export is a dry-by-default local write', () => {
|
||||
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||
expect(t('prices_diff').write).toBe(false);
|
||||
expect(toArgv(t('prices_diff'), { store: 'apple' }).argv).toEqual(['prices', 'import', '--store', 'apple', '--dry']);
|
||||
expect(toArgv(t('prices_export'), {}).argv).toEqual(['prices', 'export', '--dry']);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { parseFrontMatter, stringifyFrontMatter } from '../cli/lib/frontmatter';
|
||||
import {
|
||||
checkReply, draftMarkdown, draftName, filterReviews, markSent, parseAppleReviews, parseDraft, parsePlayReviews, REPLY_LIMITS, REPLY_PLACEHOLDER,
|
||||
replyRequest, sendPlan,
|
||||
} from '../cli/lib/reviews';
|
||||
import { FORBIDDEN_ARGS, TOOLS, toArgv } from '../cli/mcp-tools';
|
||||
|
||||
const appleResp = {
|
||||
data: [
|
||||
{ id: 'r1', attributes: { rating: 2, title: 'Too many ads', body: 'Fun but ads after every level.', reviewerNickname: 'nick1', createdDate: '2026-10-08T09:00:00-07:00', territory: 'USA' }, relationships: { response: { data: { id: 'resp1' } } } },
|
||||
{ id: 'r2', attributes: { rating: 5, title: '', body: 'Love it', reviewerNickname: 'nick2', createdDate: '2026-10-09T09:00:00-07:00', territory: 'TUR' }, relationships: { response: { data: null } } },
|
||||
],
|
||||
included: [{ type: 'customerReviewResponses', id: 'resp1', attributes: { responseBody: 'Thanks!', lastModifiedDate: '2026-10-08T12:00:00-07:00', state: 'PUBLISHED' } }],
|
||||
};
|
||||
const playResp = {
|
||||
reviews: [{ reviewId: 'gp:AOqp-1', authorName: 'A Player', comments: [
|
||||
{ userComment: { text: 'Crashes\tIt crashes on level 3.', lastModified: { seconds: '1791300000' }, starRating: 1, reviewerLanguage: 'en', appVersionName: '1.2.0' } },
|
||||
{ developerComment: { text: 'Sorry, fixed in 1.2.1.', lastModified: { seconds: '1791400000' } } }] },
|
||||
{ reviewId: 'gp:AOqp-2', comments: [{ userComment: { text: 'Nice game', lastModified: { seconds: '1791200000' }, starRating: 4, reviewerLanguage: 'tr' } }] }],
|
||||
};
|
||||
|
||||
describe('front matter', () => {
|
||||
test('round trip with quoting', () => {
|
||||
const t = stringifyFrontMatter({ store: 'play', review_id: 'gp:AOqp-1', rating: 1, approved: false, sent: null, note: 'a: b, "c"' }, 'body\n');
|
||||
expect(t.startsWith('---\nstore: play\nreview_id: gp:AOqp-1\nrating: 1\napproved: false\nsent: null\nnote: "a: b, \\"c\\""\n---\n')).toBe(true);
|
||||
expect(parseFrontMatter(t).data).toEqual({ store: 'play', review_id: 'gp:AOqp-1', rating: 1, approved: false, sent: null, note: 'a: b, "c"' });
|
||||
expect(parseFrontMatter('no front matter').body).toBe('no front matter');
|
||||
expect(parseFrontMatter('---\nx: \'it\'\'s\'\ny: true\n---\n').data).toEqual({ x: "it's", y: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('reviews', () => {
|
||||
test('apple and play responses normalise to one shape', () => {
|
||||
const a = parseAppleReviews(appleResp);
|
||||
expect(a[0]).toMatchObject({ store: 'apple', id: 'r1', rating: 2, title: 'Too many ads', where: 'USA', reply: { text: 'Thanks!', state: 'PUBLISHED' } });
|
||||
expect(a[1]!.title).toBeUndefined();
|
||||
expect(a[1]!.reply).toBeUndefined();
|
||||
const p = parsePlayReviews(playResp);
|
||||
expect(p[0]).toMatchObject({ store: 'play', id: 'gp:AOqp-1', rating: 1, title: 'Crashes', body: 'It crashes on level 3.', where: 'en', appVersion: '1.2.0', reply: { text: 'Sorry, fixed in 1.2.1.' } });
|
||||
expect(p[0]!.date).toBe(new Date(1791300000 * 1000).toISOString());
|
||||
expect(p[1]).toMatchObject({ body: 'Nice game', rating: 4 });
|
||||
const all = [...a, ...p];
|
||||
expect(filterReviews(all, { unanswered: true }).map(r => r.id)).toEqual(['r2', 'gp:AOqp-2']);
|
||||
expect(filterReviews(all, { ratings: [1, 2] }).map(r => r.id).sort()).toEqual(['gp:AOqp-1', 'r1']);
|
||||
expect(filterReviews(all, { since: '2026-10-09' }).map(r => r.id)).toEqual(['r2']);
|
||||
});
|
||||
test('draft file: name, front matter, quote, empty reply; parse back', () => {
|
||||
const r = parsePlayReviews(playResp)[0]!;
|
||||
expect(draftName(r)).toBe('play-gp_AOqp-1.md');
|
||||
const md = draftMarkdown(r);
|
||||
expect(md).toContain('approved: false');
|
||||
expect(md).toContain('limit: 350');
|
||||
expect(md).toContain('> It crashes on level 3.');
|
||||
expect(md).toContain('## Current reply');
|
||||
expect(md).toContain(REPLY_PLACEHOLDER);
|
||||
const d = parseDraft('x.md', md);
|
||||
expect(d).toMatchObject({ store: 'play', reviewId: 'gp:AOqp-1', approved: false, sent: null, reply: '' });
|
||||
const filled = md.replace(REPLY_PLACEHOLDER, 'Thanks for telling us. Version 1.2.1 fixes the crash on level 3.').replace('approved: false', 'approved: true');
|
||||
const d2 = parseDraft('x.md', filled);
|
||||
expect(d2.reply).toBe('Thanks for telling us. Version 1.2.1 fixes the crash on level 3.');
|
||||
expect(d2.approved).toBe(true);
|
||||
const sent = markSent(filled, '2026-10-10T10:00:00.000Z');
|
||||
expect(parseDraft('x.md', sent).sent).toBe('2026-10-10T10:00:00.000Z');
|
||||
expect(() => parseDraft('bad.md', '---\nstore: web\n---\n')).toThrow('apple or play');
|
||||
});
|
||||
test('reply checks: limits, incentives, personal data, tone', () => {
|
||||
expect(REPLY_LIMITS).toEqual({ play: 350, apple: 5970 });
|
||||
expect(checkReply('Thanks! We fixed it in 1.2.1.', 'play')).toEqual([]);
|
||||
expect(checkReply('', 'apple')[0]).toEqual({ level: 'error', msg: 'empty reply' });
|
||||
expect(checkReply('x'.repeat(351), 'play')[0]!.level).toBe('error');
|
||||
expect(checkReply('<b>' + 'x'.repeat(350) + '</b>', 'play')).toEqual([]);
|
||||
expect(checkReply('x'.repeat(5971), 'apple')[0]!.level).toBe('warn');
|
||||
for (const bad of ['Update your rating and get 500 free coins!', 'Please give us 5 stars', 'Could you change your review?', 'We will send you free gems', 'Rate us again'])
|
||||
expect({ bad, err: checkReply(bad, 'apple').some(i => i.level === 'error') }).toEqual({ bad, err: true });
|
||||
expect(checkReply('Write to support@example.com', 'apple')[0]!.level).toBe('warn');
|
||||
expect(checkReply('Call +1 555 010 0199', 'apple')[0]!.msg).toContain('phone');
|
||||
expect(checkReply('See https://example.com/help', 'apple')[0]!.msg).toContain('link');
|
||||
expect(checkReply('SORRY!!!', 'apple').some(i => i.msg.includes('shouting'))).toBe(true);
|
||||
});
|
||||
test('send plan: only approved, unsent, passing drafts; requests per store', () => {
|
||||
const base = { meta: {}, file: 'f' };
|
||||
const plan = sendPlan([
|
||||
{ ...base, file: 'a', store: 'apple', reviewId: 'r1', approved: true, sent: null, reply: 'Thanks for the feedback, we cut the ads in 1.3.' },
|
||||
{ ...base, file: 'b', store: 'play', reviewId: 'p1', approved: false, sent: null, reply: 'ok' },
|
||||
{ ...base, file: 'c', store: 'play', reviewId: 'p2', approved: true, sent: '2026-10-01T00:00:00Z', reply: 'ok' },
|
||||
{ ...base, file: 'd', store: 'play', reviewId: 'p3', approved: true, sent: null, reply: 'Give us 5 stars for free coins' },
|
||||
]);
|
||||
expect(plan.send.map(d => d.file)).toEqual(['a']);
|
||||
expect(plan.skip.map(s => s.file)).toEqual(['b', 'c', 'd']);
|
||||
expect(plan.skip[0]!.why).toContain('not approved');
|
||||
expect(plan.skip[2]!.why).toContain('incentives');
|
||||
expect(replyRequest(plan.send[0]!)).toEqual({ method: 'POST', url: '/v1/customerReviewResponses', body: { data: { type: 'customerReviewResponses', attributes: { responseBody: 'Thanks for the feedback, we cut the ads in 1.3.' }, relationships: { review: { data: { type: 'customerReviews', id: 'r1' } } } } } });
|
||||
const pr = replyRequest({ ...base, store: 'play', reviewId: 'gp:AOqp-1', approved: true, sent: null, reply: 'Hi' }, 'com.example.game');
|
||||
expect(pr.url).toBe('https://androidpublisher.googleapis.com/androidpublisher/v3/applications/com.example.game/reviews/gp%3AAOqp-1:reply');
|
||||
expect(pr.body).toEqual({ replyText: 'Hi' });
|
||||
});
|
||||
test('mcp: list + draft only, never send', () => {
|
||||
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||
expect(t('reviews_list')).toMatchObject({ write: false });
|
||||
expect(toArgv(t('reviews_list'), { store: 'play', unanswered: true, rating: '1,2' }).argv).toEqual(['reviews', 'list', '--store', 'play', '--unanswered', '--rating', '1,2']);
|
||||
expect(toArgv(t('reviews_draft'), { days: 7 }).argv).toEqual(['reviews', 'draft', '--days', '7', '--dry']);
|
||||
expect(FORBIDDEN_ARGS).toContain('send');
|
||||
expect(TOOLS.some(x => x.command.includes('send'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { describeReq } from '../cli/apple/jsonapi';
|
||||
import { parseCsv, parseCsvRecords, toCsv } from '../cli/lib/csv';
|
||||
import { validateConfig } from '../cli/lib/config';
|
||||
import {
|
||||
betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail, parseTesters, pickBuild,
|
||||
planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, validateTestflight, whatToTestFromListing,
|
||||
} from '../cli/lib/testflight';
|
||||
import { TOOLS, toArgv, validateInput } from '../cli/mcp-tools';
|
||||
|
||||
const G: Group[] = [
|
||||
{ id: 'g-int', name: 'Team', internal: true, hasAccessToAllBuilds: false },
|
||||
{ id: 'g-all', name: 'Everyone inside', internal: true, hasAccessToAllBuilds: true },
|
||||
{ id: 'g-ext', name: 'Friends', internal: false },
|
||||
];
|
||||
|
||||
describe('csv', () => {
|
||||
test('quotes, doubled quotes, CRLF, BOM, empty lines', () => {
|
||||
expect(parseCsv('a,b\r\n"x, y","say ""hi"""\r\n\r\nz,\n')).toEqual([['a', 'b'], ['x, y', 'say "hi"'], ['z', '']]);
|
||||
expect(parseCsv('a\tb\n1\t2', '\t')).toEqual([['a', 'b'], ['1', '2']]);
|
||||
expect(parseCsvRecords('Email, First Name\nA@example.com ,Jo')).toEqual([{ email: 'A@example.com', first_name: 'Jo' }]);
|
||||
expect(toCsv([['a', 'b,c'], [1, 'say "x"']])).toBe('a,"b,c"\n1,"say ""x"""\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('testflight config', () => {
|
||||
test('groups and the tester CSV location', () => {
|
||||
expect(validateTestflight({ groups: [{ name: 'Team', internal: true, allBuilds: true }, { name: 'Friends', publicLink: true, publicLinkLimit: 100 }], testers: '.storebound/testers.csv' })).toEqual([]);
|
||||
const e = validateTestflight({ groups: [{ name: 'A', internal: true, publicLink: true }, { name: 'A', allBuilds: true }, { name: 'B', publicLinkLimit: 0 }], testers: 'store/testers.csv' });
|
||||
expect(e.join('\n')).toContain('public links are for external groups only');
|
||||
expect(e.join('\n')).toContain('duplicate "A"');
|
||||
expect(e.join('\n')).toContain('allBuilds: internal groups only');
|
||||
expect(e.join('\n')).toContain('publicLinkLimit: 1-10000');
|
||||
expect(e.join('\n')).toContain('keep the tester CSV in .storebound/');
|
||||
const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en', apple: 'en-US' }] };
|
||||
expect(validateConfig({ ...base, apple: { bundleId: 'com.example.game', testflight: { testers: 'testers.csv' } } }).join()).toContain('.storebound/');
|
||||
});
|
||||
});
|
||||
|
||||
describe('testflight groups', () => {
|
||||
test('creates only missing groups, with the right attributes', () => {
|
||||
const p = planGroups('app1', G, [{ name: 'Team', internal: true }, { name: 'QA', internal: true, allBuilds: true }, { name: 'Public', publicLink: true, publicLinkLimit: 500, feedback: false }]);
|
||||
expect(p.existing).toEqual(['Team']);
|
||||
expect(p.create).toHaveLength(2);
|
||||
expect(p.create[0]!.body).toEqual({ data: { type: 'betaGroups', attributes: { name: 'QA', isInternalGroup: true, hasAccessToAllBuilds: true, feedbackEnabled: true }, relationships: { app: { data: { type: 'apps', id: 'app1' } } } } });
|
||||
expect((p.create[1]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ name: 'Public', publicLinkEnabled: true, publicLinkLimitEnabled: true, publicLinkLimit: 500, feedbackEnabled: false });
|
||||
expect(groupFromApi({ id: 'x', attributes: { name: 'N', isInternalGroup: true, hasAccessToAllBuilds: true } })).toMatchObject({ id: 'x', name: 'N', internal: true, hasAccessToAllBuilds: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('testflight testers', () => {
|
||||
const csv = 'email,first_name,last_name,groups\nJane@Example.com,Jane,Doe,Friends\nbob@example.com,,,Friends;Team\nnew@example.com,New,,\n';
|
||||
test('parse: lower-cases emails, default group, rejects bad rows without leaking emails', () => {
|
||||
const t = parseTesters(csv, 'Friends');
|
||||
expect(t.map(x => [x.email, x.groups])).toEqual([['jane@example.com', ['Friends']], ['bob@example.com', ['Friends', 'Team']], ['new@example.com', ['Friends']]]);
|
||||
expect(() => parseTesters('email\nnot-an-email\n')).toThrow('is not an email');
|
||||
try { parseTesters('email\nsecret.person@example.com\nsecret.person@example.com\n'); } catch (e) { expect(String(e)).toContain('s***@example.com listed twice'); expect(String(e)).not.toContain('secret.person'); }
|
||||
expect(maskEmail('jane.doe@example.com')).toBe('j***@example.com');
|
||||
});
|
||||
test('plan: create new, add existing to more groups, remove only with --remove and only from managed groups', () => {
|
||||
const want = parseTesters(csv, 'Friends');
|
||||
const existing = new Map([
|
||||
['jane@example.com', { id: 't-jane', groupIds: ['g-ext'] }],
|
||||
['bob@example.com', { id: 't-bob', groupIds: ['g-ext'] }],
|
||||
['old@example.com', { id: 't-old', groupIds: ['g-ext', 'g-all'] }],
|
||||
]);
|
||||
const p = planTesters(G, existing, want);
|
||||
expect(p.create).toHaveLength(1);
|
||||
expect(p.create[0]!.body).toEqual({ data: { type: 'betaTesters', attributes: { email: 'new@example.com', firstName: 'New' }, relationships: { betaGroups: { data: [{ type: 'betaGroups', id: 'g-ext' }] } } } });
|
||||
expect(p.add).toEqual([{ method: 'POST', path: '/v1/betaGroups/g-int/relationships/betaTesters', body: { data: [{ type: 'betaTesters', id: 't-bob' }] }, note: '1 existing tester(s) -> "Team"' }]);
|
||||
expect(p.remove).toEqual([]);
|
||||
const r = planTesters(G, existing, want, { remove: true });
|
||||
expect(r.remove).toEqual([{ method: 'DELETE', path: '/v1/betaGroups/g-ext/relationships/betaTesters', body: { data: [{ type: 'betaTesters', id: 't-old' }] }, note: '1 tester(s) leave "Friends"' }]);
|
||||
expect(r.summary).toEqual(['1 new tester(s)', '1 added to groups', '1 removed from groups']);
|
||||
expect(planTesters(G, existing, want, { only: ['Nope'] }).unknownGroups).toEqual(['Nope']);
|
||||
expect(describeReq(p.create[0]!)).not.toContain('new@example.com');
|
||||
expect(describeReq(p.create[0]!)).toContain('n***@example.com');
|
||||
});
|
||||
test('invitation request', () => {
|
||||
expect(inviteReq('app1', 't1', 'x').body).toEqual({ data: { type: 'betaTesterInvitations', relationships: { app: { data: { type: 'apps', id: 'app1' } }, betaTester: { data: { type: 'betaTesters', id: 't1' } } } } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('testflight builds', () => {
|
||||
const resp = {
|
||||
data: [
|
||||
{ id: 'b1', attributes: { version: '42', processingState: 'VALID' }, relationships: { preReleaseVersion: { data: { id: 'p1' } } } },
|
||||
{ id: 'b2', attributes: { version: '42', processingState: 'VALID' }, relationships: { preReleaseVersion: { data: { id: 'p2' } } } },
|
||||
{ id: 'b3', attributes: { version: '43', processingState: 'PROCESSING' }, relationships: { preReleaseVersion: { data: { id: 'p2' } } } },
|
||||
],
|
||||
included: [{ type: 'preReleaseVersions', id: 'p1', attributes: { version: '1.0.0' } }, { type: 'preReleaseVersions', id: 'p2', attributes: { version: '1.1.0' } }],
|
||||
};
|
||||
test('pick by explicit number, ambiguity needs --version', () => {
|
||||
const builds = buildsWithVersion(resp);
|
||||
expect(pickBuild(builds, '43').id).toBe('b3');
|
||||
expect(pickBuild(builds, '42', '1.1.0').id).toBe('b2');
|
||||
expect(() => pickBuild(builds, '42')).toThrow('add --version');
|
||||
expect(() => pickBuild(builds, '99')).toThrow('no build 99');
|
||||
});
|
||||
test('readiness', () => {
|
||||
expect(betaReadiness({ processingState: 'VALID', usesNonExemptEncryption: false }, { internalBuildState: 'READY_FOR_BETA_TESTING' })).toEqual([]);
|
||||
expect(betaReadiness({ processingState: 'PROCESSING' }, null)[0]).toContain('PROCESSING');
|
||||
expect(betaReadiness({ processingState: 'VALID', expired: true }, null)[0]).toContain('expired');
|
||||
expect(betaReadiness({ processingState: 'VALID', usesNonExemptEncryption: null }, { internalBuildState: 'MISSING_EXPORT_COMPLIANCE' })[0]).toContain('export compliance');
|
||||
});
|
||||
test('distribute skips groups that have it and internal all-builds groups', () => {
|
||||
expect(planDistribute('b1', G, ['g-ext']).map(r => r.path)).toEqual(['/v1/betaGroups/g-int/relationships/builds']);
|
||||
expect(planDistribute('b1', G, [])[0]!.body).toEqual({ data: [{ type: 'builds', id: 'b1' }] });
|
||||
expect(betaReviewReq('b1').body).toEqual({ data: { type: 'betaAppReviewSubmissions', relationships: { build: { data: { type: 'builds', id: 'b1' } } } } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('testflight what to test and info', () => {
|
||||
const md = '# App Store\n\n## en-US · English\n\n### whatsNew\n```\nNew: desert world.\n```\n\n### whatToTest\n```\nPlay level 3 twice.\n```\n\n## tr · Türkçe\n\n### whatsNew\n```\nYeni: çöl dünyası.\n```\n\n## Notes\n\ntext\n';
|
||||
test('listing -> per locale text, whatToTest wins over whatsNew', () => {
|
||||
expect(whatToTestFromListing(md)).toEqual({ 'en-US': 'Play level 3 twice.', tr: 'Yeni: çöl dünyası.' });
|
||||
});
|
||||
test('create missing, patch changed, leave equal, refuse over the limit', () => {
|
||||
const reqs = planWhatToTest('b1', [{ id: 'l1', locale: 'en-US', whatsNew: 'old' }, { id: 'l2', locale: 'de-DE', whatsNew: 'x' }, { id: 'l3', locale: 'ja', whatsNew: 'same' }], { 'en-US': 'new', tr: 'yeni', ja: 'same' });
|
||||
expect(reqs.map(r => `${r.method} ${r.path}`)).toEqual(['PATCH /v1/betaBuildLocalizations/l1', 'POST /v1/betaBuildLocalizations']);
|
||||
expect(reqs[1]!.body).toEqual({ data: { type: 'betaBuildLocalizations', attributes: { locale: 'tr', whatsNew: 'yeni' }, relationships: { build: { data: { type: 'builds', id: 'b1' } } } } });
|
||||
expect(() => planWhatToTest('b1', [], { en: 'x'.repeat(4001) })).toThrow('over 4000');
|
||||
});
|
||||
test('test information and beta review details', () => {
|
||||
const want = { 'en-US': { description: 'A puzzle game.', feedbackEmail: 'support@example.com', privacyPolicyUrl: 'https://example.com/p' }, tr: { description: 'Bulmaca.' } };
|
||||
const r = planBetaInfo('app1', [{ id: 'bl1', locale: 'en-US', attributes: { description: 'A puzzle game.', feedbackEmail: 'old@example.com' } }], want);
|
||||
expect(r.map(x => `${x.method} ${x.path}`)).toEqual(['PATCH /v1/betaAppLocalizations/bl1', 'POST /v1/betaAppLocalizations']);
|
||||
expect((r[0]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ feedbackEmail: 'support@example.com', privacyPolicyUrl: 'https://example.com/p' });
|
||||
expect(betaDescriptions({ description: { en: 'Hi' } }, [{ id: 'en', apple: 'en-US' }, { id: 'tr', apple: 'tr' }])).toEqual({ 'en-US': 'Hi' });
|
||||
expect(betaDescriptions({ description: 'All' }, [{ id: 'en', apple: 'en-US' }, { id: 'x' }])).toEqual({ 'en-US': 'All' });
|
||||
const d = planBetaReviewDetail({ id: 'd1', attributes: { contactEmail: 'a@example.com', notes: null } }, { firstName: 'A', lastName: 'B', phone: '+1 555 0100', email: 'a@example.com' }, 'Tap Play.');
|
||||
expect((d[0]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ contactFirstName: 'A', contactLastName: 'B', contactPhone: '+1 555 0100', notes: 'Tap Play.' });
|
||||
expect(describeReq(d[0]!)).not.toContain('555');
|
||||
expect(planBetaReviewDetail(null, null, 'x')).toEqual([]);
|
||||
expect(() => planBetaReviewDetail({ id: 'd', attributes: {} }, null, 'x'.repeat(4001))).toThrow('4000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('testflight mcp tools', () => {
|
||||
const tool = (n: string) => TOOLS.find(t => t.name === n)!;
|
||||
test('status read-only, writes dry by default, distribute is internal-only, testers / review not exposed', () => {
|
||||
expect(tool('apple_testflight_status')).toMatchObject({ write: false, network: true });
|
||||
expect(toArgv(tool('apple_testflight_groups')).argv).toEqual(['apple', 'testflight', 'groups', '--dry']);
|
||||
expect(toArgv(tool('apple_testflight_what_to_test'), { build: '42', locale: 'en-US,tr' }).argv).toEqual(['apple', 'testflight', 'what-to-test', '--build', '42', '--locale', 'en-US,tr', '--dry']);
|
||||
expect(toArgv(tool('apple_testflight_distribute'), { build: '42', groups: 'Team', dry_run: false }).argv).toEqual(['apple', 'testflight', 'distribute', '--build', '42', '--group', 'Team', '--internal-only']);
|
||||
expect(validateInput(tool('apple_testflight_distribute'), { build: 'latest', groups: 'Team' })[0]).toContain('does not match');
|
||||
expect(TOOLS.some(t => t.command.includes('testers'))).toBe(false);
|
||||
for (const t of TOOLS) expect(toArgv(t, { build: '1', groups: 'x', dry_run: false }).argv).not.toContain('--submit-review');
|
||||
});
|
||||
});
|
||||
|
|
@ -5,7 +5,7 @@ import { join } from 'node:path';
|
|||
import { generate, parseSkill, readSkills } from '../tools/gen-adapters';
|
||||
import { scan } from '../tools/scrub';
|
||||
import { FORBIDDEN_ARGS, listTools, TOOLS, toArgv, validateInput } from '../cli/mcp-tools';
|
||||
import { handle, LEGACY_PROTOCOL as PROTOCOL } from '../cli/mcp';
|
||||
import { handle, PROTOCOL } from '../cli/mcp';
|
||||
import { auditAppleKeywords, auditAso, auditPlayListing, crossLocaleHint } from '../cli/lib/aso';
|
||||
import { checkNotes, formatNotes, noteItems, setAppleWhatsNew, setPlayWhatsNew } from '../cli/lib/whats-new';
|
||||
import { parseAppStoreListing, parsePlayListing } from '../cli/lib/copy';
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ export function generate(root: string): Map<string, string> {
|
|||
const out = new Map<string, string>();
|
||||
const homepage = 'https://git.crt.fyi/CRT/storebound';
|
||||
const repository = 'https://git.crt.fyi/CRT/storebound.git';
|
||||
const 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.';
|
||||
const 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.';
|
||||
const keywords = ['google-play', 'app-store', 'app-store-connect', 'mobile-games', 'iap', 'screenshots', 'app-icons', 'release', 'aso', 'mcp'];
|
||||
|
||||
// 1. Claude Code plugin + its MCP server + marketplace
|
||||
|
|
@ -72,7 +72,7 @@ export function generate(root: string): Map<string, string> {
|
|||
'## Tools',
|
||||
'',
|
||||
'- CLI: `storebound <command>` (`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).',
|
||||
].join('\n');
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue