Merge origin/main into idempotency

This commit is contained in:
CRTkafa 2026-10-12 04:01:25 +08:00
commit 8f41ed4c02
52 changed files with 1787 additions and 249 deletions

View file

@ -7,13 +7,16 @@ alwaysApply: false
These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal). These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), 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, 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 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 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. 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 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run (the rows that
for real only after the owner agrees. change, not just a count), then run it for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile** 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
@ -71,6 +74,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game - `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game
- `skills/store-health/SKILL.md`: Watch a released mobile app's or game's crash and ANR health on both stores - `skills/store-health/SKILL.md`: Watch a released mobile app's or 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" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list - `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
- `skills/store-pitfalls/SKILL.md`: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile app or game - `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile app or game
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages
- `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config - `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config

View file

@ -7,13 +7,16 @@ format; `storebound install --agent copilot` copies them to `.github/skills/` of
These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal). These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), 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, 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 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 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. 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 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run (the rows that
for real only after the owner agrees. change, not just a count), then run it for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile** 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
@ -73,6 +76,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| `store-declarations` | Answer the store compliance forms for a mobile app or game | | `store-declarations` | Answer the store compliance forms for a mobile app or game |
| `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores | | `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores |
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list | | `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
| `store-pitfalls` | Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each |
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile app or game | | `store-preflight` | Run and read the storebound readiness checks before submitting a mobile app or game |
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages |
| `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config | | `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config |

View file

@ -8,13 +8,16 @@ 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). These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), 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, 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 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 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. 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 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run (the rows that
for real only after the owner agrees. change, not just a count), then run it for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile** 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
@ -72,6 +75,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game - `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game
- `skills/store-health/SKILL.md`: Watch a released mobile app's or game's crash and ANR health on both stores - `skills/store-health/SKILL.md`: Watch a released mobile app's or 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" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list - `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
- `skills/store-pitfalls/SKILL.md`: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile app or game - `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile app or game
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages
- `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config - `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config

View file

@ -2,6 +2,45 @@
## Unreleased ## Unreleased
- Faster `shots capture` (web) and `shots render` (a 22-language game took about 50 min to capture, serially, with a
new context and a full game boot per frame):
- `--concurrency N` (and `shots.capture.concurrency`): parallel browser contexts in one Chromium; defaults from the
CPU count (capture min(3, cores / 4), render min(4, cores / 2)). Output files do not depend on the order; progress
lines carry language / device / frame, n/total and an ETA. Render runs ffmpeg asynchronously and makes the contact
sheets after the images.
- Per-frame timing (goto, waitFor, eval, delay, screenshot, total) in each progress line and in
`.storebound/capture-report.json`, with time per step and the slowest frames at the end.
- `shots.capture.session: 'per-language'`: one page per language and device, booted once; shots switch with
`navigate: 'spa'` (pushState + popstate, then waitFor / eval) or `'reload'`; a failed precondition falls back to a
fresh page (`reuseTimeoutMs`).
- Input-hash cache (`.storebound/capture-cache.json`: shot entry, URL, frame size, session, copy text, app build from
`shots.capture.build` or the served HTML + scripts, fonts): unchanged frames are skipped; `--only-missing`,
`--force`. MCP `shots_capture` (`concurrency`, `mode`) and `shots_render` (`concurrency`).
- `apple listing --dry`, `play listing --dry` and `apple appinfo --dry` print a real plan (also `--json`), read-only:
the version decision of `apple listing` (keep, update the editable version's string while PREPARE_FOR_SUBMISSION,
create, or refuse: number taken, not higher than a reviewed version, another version in review / pending release),
the build to attach, and per locale / language create or update with old -> new per field (long text cut with its
length, unchanged fields summarized); app info name / subtitle / privacy URL, categories, age rating and content
rights the same way. Locales whose section is `status=draft` or `status=translate` (`listing translate`) are skipped
with the reason; `--include-drafts` sends them. The real run prints the same plan, asks in a terminal and applies
exactly it (unchanged localizations are no longer PATCHed, Play PUTs only changed languages); what's new is left out
on an app's first version.
- `apple.name`: the App Store name in the primary locale (at most 30 characters, validated) for when the plain name is
taken on the App Store ("already being used"). `app.name` stays the Play and on-device name. `console fill
apple-app-record` fills Name from it (else `app.name`), and `apple listing`, `apple listing pull` (a pulled name equal
to it is not written into the file), the listing completeness view, `check --aso`, the console app picker and `scan`'s
beta-wording rule use it for every locale without its own `### name` block. `check` reports an App Store name over 30
characters in any locale and hints when every locale uses the plain `app.name` (`hints` in `--json`).
- Pitfalls from real use become guardrails: new skill `store-pitfalls` (read before any store task, linked from the
agent rules) and `docs/pitfalls.md` (changelog of lessons; CONTRIBUTING: every real-use bug adds an entry and,
where possible, a check or test).
- `apple iap-review` names config products missing from App Store Connect's list (it lags a minute after a create)
and exits 1 instead of skipping them silently; `apple iap` and `play products` re-read the list after creating
and warn when a new product is not in it yet.
- `cli/lib/dry.ts` `dryPlan(title, rows)`: the standard dry-run plan table. `apple iap --dry` now reads
localizations, price schedule and availability and prints what a real run would add; `apple iap-review` and
`play products` end their dry runs with the table. A test scans `cli/**` for `--dry` branches that print only a
count (allowlist with TODOs for commands being fixed elsewhere).
- Screenshot glyphs (a Turkish render showed fallback glyphs for "ş" / "ğ" while `shots check` passed): the cause was - Screenshot glyphs (a Turkish render showed fallback glyphs for "ş" / "ğ" while `shots check` passed): the cause was
not subsetting (css2 `text=` already takes glyphs from every subset) but the title font: Lilita One has no ş ğ İ and not subsetting (css2 `text=` already takes glyphs from every subset) but the title font: Lilita One has no ş ğ İ and
most of Latin Extended-A, so Chrome silently drew them with another font. most of Latin Extended-A, so Chrome silently drew them with another font.

View file

@ -39,6 +39,10 @@ Try the screenshot and video pipeline on the demo game without any store account
fails on new inline `<svg>` / `<path>` drawing in `apps/desktop/src` and `site/*.html` and on SVG files that are fails on new inline `<svg>` / `<path>` drawing in `apps/desktop/src` and `site/*.html` and on SVG files that are
not vendored or rendered. These libraries are desktop not vendored or rendered. These libraries are desktop
dependencies (bundled by Vite) or devDependencies; the CLI package keeps zero runtime dependencies. dependencies (bundled by Vite) or devDependencies; the CLI package keeps zero runtime dependencies.
- **Every bug found in real use becomes a guardrail.** Add an entry to `docs/pitfalls.md` and to
`skills/store-pitfalls/SKILL.md` (symptom, cause, what to do, what guards it) and, where possible, a check or a test
with recorded store answers that fails without the fix. A `--dry` run prints the plan (`dryPlan` in
`cli/lib/dry.ts`), not only a count; `tests/pitfalls.test.ts` enforces it.
- Plain English in docs and messages, short sentences, no marketing words. - Plain English in docs and messages, short sentences, no marketing words.
## Pull requests ## Pull requests

View file

@ -6,13 +6,16 @@ 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). These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), 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, 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 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 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. 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 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run (the rows that
for real only after the owner agrees. change, not just a count), then run it for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile** 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
@ -72,6 +75,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| `store-declarations` | Answer the store compliance forms for a mobile app or game | | `store-declarations` | Answer the store compliance forms for a mobile app or game |
| `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores | | `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores |
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list | | `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
| `store-pitfalls` | Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each |
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile app or game | | `store-preflight` | Run and read the storebound readiness checks before submitting a mobile app or game |
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages |
| `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config | | `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config |

View file

@ -340,7 +340,7 @@ run in the background with a log (`storebound shots render > .storebound/render.
| command | kind | what | | command | kind | what |
|---|---|---| |---|---|---|
| `play listing` | API | app details, title / short / full description per language, promo video URL (`play.video`) | | `play listing [--include-drafts]` | API | app details, title / short / full description per language, promo video URL (`play.video`); prints the plan first (old -> new per field, draft languages skipped), `--dry` stops there, the real run asks and sends only changes |
| `play listing pull [--write]` | API, read-only + local | live listings back into `store/listing.md`: diff first, writes only with `--write` | | `play listing pull [--write]` | API, read-only + local | live listings back into `store/listing.md`: diff first, writes only with `--write` |
| `play images [--variant b]` | API | icon, feature graphic, phone / 7" / 10" screenshots, one edit per language | | `play images [--variant b]` | API | icon, feature graphic, phone / 7" / 10" screenshots, one edit per language |
| `play products` | API | one-time products: regional prices from `convertRegionPrices` + your overrides, activate | | `play products` | API | one-time products: regional prices from `convertRegionPrices` + your overrides, activate |
@ -361,7 +361,7 @@ run in the background with a log (`storebound shots render > .storebound/render.
| command | kind | what | | command | kind | what |
|---|---|---| |---|---|---|
| `apple bundle` | API | register the bundle id, find the app record | | `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 listing --version x.y.z [--build N] [--include-drafts]` | API | prints the plan first (version: keep / update / create / refuse with the reason; per locale create / update, old -> new per field; draft locales skipped), `--dry` stops there, the real run asks and applies exactly it: version (manual release), the build with exactly that number, texts per locale (name: the locale's `### name`, else `apple.name`, else `app.name`) |
| `apple listing pull [--version x.y.z] [--write]` | API, read-only + local | live texts back into `store/appstore.md`: diff first, writes only with `--write` | | `apple listing pull [--version x.y.z] [--write]` | API, read-only + local | live texts back into `store/appstore.md`: diff first, writes only with `--write` |
| `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`, + 6.3" with `apple.iphoneMedium`) per locale, MD5-idempotent |
| `apple previews [--poster 5]` | API | app preview videos per locale, checked first, MD5-idempotent, poster frame | | `apple previews [--poster 5]` | API | app preview videos per locale, checked first, MD5-idempotent, poster frame |
@ -374,7 +374,7 @@ run in the background with a log (`storebound shots render > .storebound/render.
| `apple cpp list \| create \| upload \| submit \| visible` | API | custom product pages from the config and a shots variant; submit / visible ask first | | `apple cpp list \| create \| upload \| submit \| visible` | API | custom product pages from the config and a shots variant; submit / visible ask first |
| `apple events list \| create \| upload \| submit` | API | in-app events with schedule, localizations, card and details images; submit asks first | | `apple events list \| create \| upload \| submit` | API | in-app events with schedule, localizations, card and details images; submit asks first |
| `apple subscriptions [--csv] [--codes]` | API | groups, subscriptions, levels, localizations, availability, equalized prices + overrides + CSV (scheduled changes), introductory and promotional offers, offer code campaigns, review screenshots (plan first, asks; custom codes only with `--codes`) | | `apple subscriptions [--csv] [--codes]` | API | groups, subscriptions, levels, localizations, availability, equalized prices + overrides + CSV (scheduled changes), introductory and promotional offers, offer code campaigns, review screenshots (plan first, asks; custom codes only with `--codes`) |
| `apple appinfo` | API | categories, age rating, content rights, Free, territories | | `apple appinfo` | API | categories, age rating, content rights, Free, territories; plan first (old -> new), only changes are sent |
| `apple review-details` | API | App Review contact, demo account (from `.storebound/`, masked), notes (+ sign-in steps, where account deletion is) | | `apple review-details` | API | App Review contact, demo account (from `.storebound/`, masked), notes (+ sign-in steps, where account deletion is) |
| `apple encryption` | API | export compliance answer from `apple.usesNonExemptEncryption` (never guessed) | | `apple encryption` | API | export compliance answer from `apple.usesNonExemptEncryption` (never guessed) |
| `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) | | `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) |
@ -430,9 +430,9 @@ run in the background with a log (`storebound shots render > .storebound/render.
| command | kind | what | | command | kind | what |
|---|---|---| |---|---|---|
| `shots capture [--source web\|ios-sim\|android-emu\|folder]` | local | raw frames from your running app or game | | `shots capture [--source web\|ios-sim\|android-emu\|folder] [--concurrency N] [--only-missing \| --force]` | local | raw frames from your running app or game; web: parallel contexts, optional one boot per language (`capture.session`), skips unchanged frames, timing per step |
| `shots fonts` | network | font subsets for your copy (Noto for CJK / Arabic / Cyrillic / Devanagari ...) and the glyph coverage check per language | | `shots fonts` | network | font subsets for your copy (Noto for CJK / Arabic / Cyrillic / Devanagari ...) and the glyph coverage check per language |
| `shots render [--variant b \| --variants]` | local | every store size and language in the game or app style, feature graphic, contact sheet, overflow report | | `shots render [--variant b \| --variants] [--concurrency N]` | local | every store size and language in the game or app style, feature graphic, contact sheet, overflow report |
| `shots jpeg` | local | JPEG q92 copies of the Play renders (about 4x faster uploads) | | `shots jpeg` | local | JPEG q92 copies of the Play renders (about 4x faster uploads) |
| `shots check [--variants] [--json]` | local, read-only | store rules: sizes, alpha, format, bytes, counts, overflow, fallback / missing glyphs, videos, folder frames | | `shots check [--variants] [--json]` | local, read-only | store rules: sizes, alpha, format, bytes, counts, overflow, fallback / missing glyphs, videos, folder frames |
| `shots gallery` | local | `<renders>/index.html` review page | | `shots gallery` | local | `<renders>/index.html` review page |

View file

@ -28,8 +28,9 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appEvents_createInstance': 'apple/events', 'appEvents_createInstance': 'apple/events',
'appEvents_getInstance': 'apple/events', 'appEvents_getInstance': 'apple/events',
'appEvents_localizations_getToManyRelated': 'apple/events', 'appEvents_localizations_getToManyRelated': 'apple/events',
'appInfos_ageRatingDeclaration_getToOneRelated': 'validate', 'appInfos_ageRatingDeclaration_getToOneRelated': 'apple/appinfo validate',
'appInfos_appInfoLocalizations_getToManyRelated': 'apple/listing validate', 'appInfos_appInfoLocalizations_getToManyRelated': 'apple/listing validate',
'appInfos_getInstance': 'apple/appinfo',
'appInfos_updateInstance': 'apple/appinfo', 'appInfos_updateInstance': 'apple/appinfo',
'appPreviewSets_appPreviews_getToManyRelated': 'apple/previews', 'appPreviewSets_appPreviews_getToManyRelated': 'apple/previews',
'appPreviewSets_createInstance': 'apple/previews', 'appPreviewSets_createInstance': 'apple/previews',
@ -56,7 +57,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appStoreVersions_appStoreReviewDetail_getToOneRelated': 'apple/review-details validate', 'appStoreVersions_appStoreReviewDetail_getToOneRelated': 'apple/review-details validate',
'appStoreVersions_appStoreVersionLocalizations_getToManyRelated': 'apple/listing apple/previews apple/screenshots validate', 'appStoreVersions_appStoreVersionLocalizations_getToManyRelated': 'apple/listing apple/previews apple/screenshots validate',
'appStoreVersions_appStoreVersionPhasedRelease_getToOneRelated': 'apple/release apple/status', 'appStoreVersions_appStoreVersionPhasedRelease_getToOneRelated': 'apple/release apple/status',
'appStoreVersions_build_getToOneRelated': 'validate', 'appStoreVersions_build_getToOneRelated': 'apple/listing validate',
'appStoreVersions_build_updateToOneRelationship': 'apple/listing', 'appStoreVersions_build_updateToOneRelationship': 'apple/listing',
'appStoreVersions_createInstance': 'apple/listing', 'appStoreVersions_createInstance': 'apple/listing',
'appStoreVersions_updateInstance': 'apple/listing', 'appStoreVersions_updateInstance': 'apple/listing',
@ -76,7 +77,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'apps_buildUploads_getToManyRelated': 'apple/upload', 'apps_buildUploads_getToManyRelated': 'apple/upload',
'apps_customerReviews_getToManyRelated': 'reviews', 'apps_customerReviews_getToManyRelated': 'reviews',
'apps_getCollection': 'apple/asc apple/bundle apps lib/store-apps', 'apps_getCollection': 'apple/asc apple/bundle apps lib/store-apps',
'apps_getInstance': 'apple/status', 'apps_getInstance': 'apple/appinfo apple/status',
'apps_inAppPurchasesV2_getToManyRelated': 'apple/iap apple/iap-review apple/iap-submit apple/offer-codes apple/promoted apple/status catalog prices validate', 'apps_inAppPurchasesV2_getToManyRelated': 'apple/iap apple/iap-review apple/iap-submit apple/offer-codes apple/promoted apple/status catalog prices validate',
'apps_perfPowerMetrics_getToManyRelated': 'health', 'apps_perfPowerMetrics_getToManyRelated': 'health',
'apps_promotedPurchases_getToManyRelated': 'apple/promoted', 'apps_promotedPurchases_getToManyRelated': 'apple/promoted',

View file

@ -1,13 +1,16 @@
// App-level App Store settings (idempotent), from apple.info in storebound.config.ts: // App-level App Store settings (idempotent), from apple.info in storebound.config.ts:
// storebound apple appinfo [--dry] // storebound apple appinfo [--dry] [--json]
// Every run first reads the current values and prints the plan (old -> new per field); --dry stops there, the real run
// asks in a terminal and changes only what differs.
// - categories (primary + up to two subcategories for games, secondary) // - categories (primary + up to two subcategories for games, secondary)
// - age rating declaration: every content question NONE / false unless overridden in apple.info.ageRating // - age rating declaration: every content question NONE / false unless overridden in apple.info.ageRating
// - content rights declaration // - content rights declaration
// - price Free (USA base) and availability in every territory + new ones (when apple.info.free !== false) // - price Free (USA base) and availability in every territory + new ones (when apple.info.free !== false)
// App Privacy ("nutrition label") has no API: web UI only (store-declarations skill). // App Privacy ("nutrition label") has no API: web UI only (store-declarations skill).
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { confirm, need } from '../lib/ctx';
import { done, log } from '../lib/log'; import { type ItemPlan, itemLines, planItem } from '../lib/listing-plan';
import { done, log, printJson, warn } from '../lib/log';
import { ascClient } from './asc'; import { ascClient } from './asc';
/** Every question of the current age rating declaration at its "nothing" answer. */ /** Every question of the current age rating declaration at its "nothing" answer. */
@ -20,52 +23,97 @@ export const AGE_RATING_NONE: Record<string, string | boolean | null> = {
violenceRealisticProlongedGraphicOrSadistic: 'NONE', kidsAgeBand: null, violenceRealisticProlongedGraphicOrSadistic: 'NONE', kidsAgeBand: null,
}; };
const CATEGORY_RELS = ['primaryCategory', 'primarySubcategoryOne', 'primarySubcategoryTwo', 'secondaryCategory'] as const;
const str = (v: unknown): string => (v === null || v === undefined ? '' : String(v));
/** The plan of one `apple appinfo` run, from read-only GETs. */
export interface AppInfoPlan { appInfoId: string; items: ItemPlan[]; freePricePointId: string | null; territories: string[]; changes: number }
/** The plan as text lines. Pure. */
export function appInfoPlanLines(p: AppInfoPlan): string[] {
return p.items.flatMap(i => itemLines(i.key, i, ''));
}
async function planAppInfo(ctx: Ctx, c: Awaited<ReturnType<typeof ascClient>>, appId: string): Promise<AppInfoPlan> {
const info = ctx.loaded.config.apple?.info ?? {};
const appInfo = await c.editableAppInfo();
const items: ItemPlan[] = [];
if (info.categories) {
const k = info.categories;
const cur = await c.maybe(`/v1/appInfos/${appInfo.id}?include=${CATEGORY_RELS.join(',')}`);
const rel = cur?.data?.relationships ?? appInfo.relationships ?? {};
const want = { primaryCategory: k.primary, primarySubcategoryOne: k.primarySubOne ?? '', primarySubcategoryTwo: k.primarySubTwo ?? '', secondaryCategory: k.secondary ?? '' };
items.push(planItem('categories', { attributes: Object.fromEntries(CATEGORY_RELS.map(r => [r, str(rel[r]?.data?.id)])) }, want));
}
const attributes = { ...AGE_RATING_NONE, ...(info.ageRating ?? {}) };
const age = await c.maybe(`/v1/appInfos/${appInfo.id}/ageRatingDeclaration`);
items.push(planItem('age rating declaration', age?.data ? { attributes: Object.fromEntries(Object.keys(attributes).map(q => [q, str(age.data.attributes?.[q])])) } : null,
Object.fromEntries(Object.entries(attributes).map(([q, v]) => [q, str(v)]))));
if (info.contentRights) {
const app = await c.maybe(`/v1/apps/${appId}`);
items.push(planItem('content rights', { attributes: { contentRightsDeclaration: str(app?.data?.attributes?.contentRightsDeclaration) } }, { contentRightsDeclaration: info.contentRights }));
}
let freePricePointId: string | null = null, territories: string[] = [];
if (info.free !== false) {
const sched = await c.maybe(`/v1/apps/${appId}/appPriceSchedule?include=manualPrices`);
if (!sched?.included?.some((x: { type: string }) => x.type === 'appPrices')) {
const free = (await c.all(`/v1/apps/${appId}/appPricePoints?filter[territory]=USA&limit=200`)).find(p => Number(p.attributes.customerPrice) === 0);
if (!free) throw new Error('no free price point for USA');
freePricePointId = free.id;
items.push(planItem('price', null, { price: 'Free', baseTerritory: 'USA' }));
} else items.push(planItem('price', { attributes: { schedule: 'exists' } }, { schedule: 'exists' }));
const avail = await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`);
if (!avail?.data) {
territories = (await c.all('/v1/territories?limit=200')).map(t => t.id);
items.push(planItem('availability', null, { territories: `${territories.length} (all)`, availableInNewTerritories: 'true' }));
} else items.push(planItem('availability', { attributes: { availability: 'exists' } }, { availability: 'exists' }));
}
return { appInfoId: appInfo.id, items, freePricePointId, territories, changes: items.filter(i => i.action !== 'same').length };
}
export async function run(ctx: Ctx): Promise<void> { export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded; const { config, root } = ctx.loaded;
const info = config.apple?.info ?? {}; const info = config.apple?.info ?? {};
const dry = ctx.args.has('dry'); const dry = ctx.args.has('dry');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app(); const appId = await c.app();
const appInfo = await c.editableAppInfo(); const p = await planAppInfo(ctx, c, appId);
const say = (m: string) => log('apple', dry ? `${m} (dry)` : m); if (ctx.args.has('json')) printJson({ dry, ...p });
else for (const line of appInfoPlanLines(p)) console.log(line);
if (dry) { done('apple', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('apple', 'appinfo already up to date (App Privacy is UI-only: store-declarations skill)'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to App Store Connect?`))) { warn('apple', 'nothing written'); return; }
const changed = (key: string) => p.items.some(i => i.key === key && i.action !== 'same');
if (info.categories) { if (info.categories && changed('categories')) {
const k = info.categories; const k = info.categories;
const rel = (id?: string) => ({ data: id ? { type: 'appCategories', id } : null }); const rel = (id?: string) => ({ data: id ? { type: 'appCategories', id } : null });
if (!dry) await c.asc('PATCH', `/v1/appInfos/${appInfo.id}`, { data: { type: 'appInfos', id: appInfo.id, relationships: { await c.asc('PATCH', `/v1/appInfos/${p.appInfoId}`, { data: { type: 'appInfos', id: p.appInfoId, relationships: {
primaryCategory: rel(k.primary), primarySubcategoryOne: rel(k.primarySubOne), primarySubcategoryTwo: rel(k.primarySubTwo), secondaryCategory: rel(k.secondary) } } }); primaryCategory: rel(k.primary), primarySubcategoryOne: rel(k.primarySubOne), primarySubcategoryTwo: rel(k.primarySubTwo), secondaryCategory: rel(k.secondary) } } });
say(`categories: ${[k.primary, k.primarySubOne, k.primarySubTwo].filter(Boolean).join(' / ')}${k.secondary ? `, secondary ${k.secondary}` : ''}`); log('apple', `categories: ${[k.primary, k.primarySubOne, k.primarySubTwo].filter(Boolean).join(' / ')}${k.secondary ? `, secondary ${k.secondary}` : ''}`);
} }
if (changed('age rating declaration')) {
const attributes = { ...AGE_RATING_NONE, ...(info.ageRating ?? {}) }; const attributes = { ...AGE_RATING_NONE, ...(info.ageRating ?? {}) };
if (!dry) await c.asc('PATCH', `/v1/ageRatingDeclarations/${appInfo.id}`, { data: { type: 'ageRatingDeclarations', id: appInfo.id, attributes } }); await c.asc('PATCH', `/v1/ageRatingDeclarations/${p.appInfoId}`, { data: { type: 'ageRatingDeclarations', id: p.appInfoId, attributes } });
say(`age rating declaration: ${Object.entries(info.ageRating ?? {}).map(([q, v]) => `${q}=${v}`).join(', ') || 'all NONE'}`); log('apple', `age rating declaration: ${Object.entries(info.ageRating ?? {}).map(([q, v]) => `${q}=${v}`).join(', ') || 'all NONE'}`);
if (info.contentRights) {
if (!dry) await c.asc('PATCH', `/v1/apps/${appId}`, { data: { type: 'apps', id: appId, attributes: { contentRightsDeclaration: info.contentRights } } });
say(`content rights: ${info.contentRights}`);
} }
if (info.contentRights && changed('content rights')) {
if (info.free !== false) { await c.asc('PATCH', `/v1/apps/${appId}`, { data: { type: 'apps', id: appId, attributes: { contentRightsDeclaration: info.contentRights } } });
const sched = await c.maybe(`/v1/apps/${appId}/appPriceSchedule?include=manualPrices`); log('apple', `content rights: ${info.contentRights}`);
if (!sched?.included?.some((x: { type: string }) => x.type === 'appPrices')) { }
const free = (await c.all(`/v1/apps/${appId}/appPricePoints?filter[territory]=USA&limit=200`)).find(p => Number(p.attributes.customerPrice) === 0); if (p.freePricePointId) {
if (!free) throw new Error('no free price point for USA'); await c.asc('POST', '/v1/appPriceSchedules', { data: { type: 'appPriceSchedules', relationships: {
if (!dry) await c.asc('POST', '/v1/appPriceSchedules', { data: { type: 'appPriceSchedules', relationships: {
app: { data: { type: 'apps', id: appId } }, baseTerritory: { data: { type: 'territories', id: 'USA' } }, app: { data: { type: 'apps', id: appId } }, baseTerritory: { data: { type: 'territories', id: 'USA' } },
manualPrices: { data: [{ type: 'appPrices', id: '${free}' }] } } }, manualPrices: { data: [{ type: 'appPrices', id: '${free}' }] } } },
included: [{ type: 'appPrices', id: '${free}', attributes: { startDate: null }, relationships: { appPricePoint: { data: { type: 'appPricePoints', id: free.id } } } }] }); included: [{ type: 'appPrices', id: '${free}', attributes: { startDate: null }, relationships: { appPricePoint: { data: { type: 'appPricePoints', id: p.freePricePointId } } } }] });
say('price: Free (USA base)'); log('apple', 'price: Free (USA base)');
} else log('apple', 'price schedule exists'); }
if (p.territories.length) {
const avail = await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`); const ts = p.territories;
if (!avail?.data) { await c.asc('POST', '/v2/appAvailabilities', { data: { type: 'appAvailabilities', attributes: { availableInNewTerritories: true },
const ts: string[] = (await c.all('/v1/territories?limit=200')).map(t => t.id);
if (!dry) await c.asc('POST', '/v2/appAvailabilities', { data: { type: 'appAvailabilities', attributes: { availableInNewTerritories: true },
relationships: { app: { data: { type: 'apps', id: appId } }, territoryAvailabilities: { data: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}' })) } } }, relationships: { app: { data: { type: 'apps', id: appId } }, territoryAvailabilities: { data: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}' })) } } },
included: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}', attributes: { available: true }, relationships: { territory: { data: { type: 'territories', id: t } } } })) }); included: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}', attributes: { available: true }, relationships: { territory: { data: { type: 'territories', id: t } } } })) });
say(`availability: ${ts.length} territories + new ones`); log('apple', `availability: ${ts.length} territories + new ones`);
} else log('apple', 'availability exists');
} }
done('apple', 'appinfo done (App Privacy is UI-only: store-declarations skill)'); done('apple', 'appinfo done (App Privacy is UI-only: store-declarations skill)');
} }

View file

@ -5,11 +5,16 @@
// Size: an App Store screenshot size (iPhone or iPad, e.g. 1320 x 2868 or 1290 x 2796); Apple processes the upload // Size: an App Store screenshot size (iPhone or iPad, e.g. 1320 x 2868 or 1290 x 2796); Apple processes the upload
// after it is committed and fails other sizes with IMAGE_INCORRECT_DIMENSIONS, so the size is checked before the // after it is committed and fails other sizes with IMAGE_INCORRECT_DIMENSIONS, so the size is checked before the
// upload and the delivery state is read back after it (an upload is only "done" when Apple says COMPLETE). // upload and the delivery state is read back after it (an upload is only "done" when Apple says COMPLETE).
// Config products missing from the store's list (it lags a minute after `apple iap` creates them) are named with a
// warning and the exit code is 1, so nothing is skipped silently (docs/pitfalls.md). --dry ends with the plan table.
import { existsSync, readFileSync } from 'node:fs'; import { existsSync, readFileSync } from 'node:fs';
import { join, relative } from 'node:path'; import { join, relative } from 'node:path';
import { sellsOn } from '../lib/config';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { need } from '../lib/ctx';
import { dryPlan, type PlanRow } from '../lib/dry';
import { done, log, warn } from '../lib/log'; import { done, log, warn } from '../lib/log';
import { reportMissing } from '../lib/store-lag';
import { IMAGE_SPECS, imageInfo } from '../shots/spec'; import { IMAGE_SPECS, imageInfo } from '../shots/spec';
import { ascClient, md5 } from './asc'; import { ascClient, md5 } from './asc';
@ -39,28 +44,27 @@ export async function run(ctx: Ctx): Promise<void> {
const defs = new Map((config.products ?? []).map(p => [p.id, p])); const defs = new Map((config.products ?? []).map(p => [p.id, p]));
const shotOf = (id: string) => c.maybe(`/v2/inAppPurchases/${id}/appStoreReviewScreenshot`).then(r => r?.data as Shot | undefined); const shotOf = (id: string) => c.maybe(`/v2/inAppPurchases/${id}/appStoreReviewScreenshot`).then(r => r?.data as Shot | undefined);
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`); const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
const seen = new Set(iaps.map((p: any) => p.attributes.productId)); const want = (config.products ?? []).filter(p => sellsOn(config, p, 'apple')).map(p => p.id);
const missingInStore = [...defs.keys()].filter(id => !seen.has(id)); const missing = reportMissing('apple', 'products', want, iaps.map(p => p.attributes.productId as string), { fail: true });
if (missingInStore.length) const rows: PlanRow[] = missing.map(id => ({ item: id, action: 'skip', detail: 'not in the store\'s list yet (run apple iap first, or re-run in a minute)' }));
warn('apple', `not in App Store Connect yet: ${missingInStore.join(', ')} (created moments ago? the store's list can lag a minute; run again)`);
let problems = 0; let problems = 0;
for (const p of iaps) { for (const p of iaps) {
const sku: string = p.attributes.productId; const sku: string = p.attributes.productId;
const def = defs.get(sku); const def = defs.get(sku);
const file = def?.reviewScreenshot ? resolve(def.reviewScreenshot) const file = def?.reviewScreenshot ? resolve(def.reviewScreenshot)
: ['png', 'jpg', 'jpeg'].map(e => resolve(join(config.apple?.reviewShots ?? 'store/iap-review', `${sku}.${e}`))).find(existsSync); : ['png', 'jpg', 'jpeg'].map(e => resolve(join(config.apple?.reviewShots ?? 'store/iap-review', `${sku}.${e}`))).find(existsSync);
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); problems++; continue; } if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); rows.push({ item: sku, action: 'skip', detail: 'no review screenshot' }); problems++; continue; }
const buf = readFileSync(file); const buf = readFileSync(file);
const bad = reviewShotProblem(buf); const bad = reviewShotProblem(buf);
const cur = await shotOf(p.id); const cur = await shotOf(p.id);
const curState = stateOf(cur); const curState = stateOf(cur);
if (bad) { if (bad) {
warn('apple', `${sku}: ${relative(root, file)}: ${bad}${cur ? `; App Store Connect has ${curState}${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : ''}`); warn('apple', `${sku}: ${relative(root, file)}: ${bad}${cur ? `; App Store Connect has ${curState}${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : ''}`);
problems++; continue; rows.push({ item: sku, action: 'skip', detail: bad }); problems++; continue;
} }
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && curState !== 'FAILED') { log('apple', `${sku}: screenshot up to date (${curState})`); continue; } if (cur && cur.attributes.sourceFileChecksum === md5(buf) && curState !== 'FAILED') { log('apple', `${sku}: screenshot up to date (${curState})`); rows.push({ item: sku, action: 'keep' }); continue; }
const why = !cur ? 'none in App Store Connect' : curState === 'FAILED' ? `the one there FAILED${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : 'a different file is there'; const why = !cur ? 'none in App Store Connect' : curState === 'FAILED' ? `the one there FAILED${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : 'a different file is there';
if (dry) { log('apple', `${sku}: would upload ${relative(root, file)} (${why})`); continue; } if (dry) { log('apple', `${sku}: would upload ${relative(root, file)} (${why})`); rows.push({ item: sku, action: cur ? 'replace' : 'upload', detail: `${relative(root, file)} (${why})` }); continue; }
if (cur) await c.asc('DELETE', `/v1/inAppPurchaseAppStoreReviewScreenshots/${cur.id}`); if (cur) await c.asc('DELETE', `/v1/inAppPurchaseAppStoreReviewScreenshots/${cur.id}`);
await c.uploadAsset('inAppPurchaseAppStoreReviewScreenshots', { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: p.id } } }, file); await c.uploadAsset('inAppPurchaseAppStoreReviewScreenshots', { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: p.id } } }, file);
// Apple processes the asset after the commit: read the state back (COMPLETE, or FAILED with the reason) // Apple processes the asset after the commit: read the state back (COMPLETE, or FAILED with the reason)
@ -90,6 +94,7 @@ export async function run(ctx: Ctx): Promise<void> {
else if (stateOf(shot) !== 'COMPLETE') lack.push(`Apple to finish processing the screenshot (${stateOf(shot)}; check again in a minute)`); else if (stateOf(shot) !== 'COMPLETE') lack.push(`Apple to finish processing the screenshot (${stateOf(shot)}; check again in a minute)`);
log('apple', `${p.attributes.productId}: MISSING_METADATA${lack.length ? `: needs ${lack.join(', ')}` : ' (all parts present: Apple may still be updating the state)'}`); log('apple', `${p.attributes.productId}: MISSING_METADATA${lack.length ? `: needs ${lack.join(', ')}` : ' (all parts present: Apple may still be updating the state)'}`);
} }
if (dry) console.log(dryPlan('apple iap-review', rows));
if (problems) process.exitCode = 1; if (problems) process.exitCode = 1;
done('apple', dry ? 'iap-review dry run (nothing uploaded)' : 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)'); done('apple', dry ? 'iap-review dry run (nothing uploaded)' : 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
} }

View file

@ -4,11 +4,16 @@
// storebound apple iap [--dry] [--only id1,id2] // storebound apple iap [--dry] [--only id1,id2]
// Then `apple iap-review` for the review screenshots. First IAPs can only be submitted together with an app version, // Then `apple iap-review` for the review screenshots. First IAPs can only be submitted together with an app version,
// from the IAP page in the web UI (see the store-iap-setup skill). // from the IAP page in the web UI (see the store-iap-setup skill).
// --dry reads everything (read-only) and prints one plan row per product. After a real run the store's product list
// is read again: a product created a moment ago can be missing from it for a minute, and `apple iap-review` would
// then skip it, so that gap is named (docs/pitfalls.md).
import { sellsOn } from '../lib/config'; import { sellsOn } from '../lib/config';
import { APPLE_IAP_LIMITS } from '../lib/copy'; import { APPLE_IAP_LIMITS } from '../lib/copy';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { need } from '../lib/ctx';
import { dryPlan, type PlanRow } from '../lib/dry';
import { done, log, step } from '../lib/log'; import { done, log, step } from '../lib/log';
import { LAG_HINT, reportMissing } from '../lib/store-lag';
import { appleTerritory, nearestPrices, samePrice } from '../lib/money'; import { appleTerritory, nearestPrices, samePrice } from '../lib/money';
import { createOnce, findOrCreate, getById } from '../lib/upsert'; import { createOnce, findOrCreate, getById } from '../lib/upsert';
import { ascClient, type J } from './asc'; import { ascClient, type J } from './asc';
@ -36,11 +41,13 @@ export async function run(ctx: Ctx): Promise<void> {
throw new Error(`${territory} has no ${price} price point (nearest ${nearestPrices(seen, price).join(', ')})`); throw new Error(`${territory} has no ${price} price point (nearest ${nearestPrices(seen, price).join(', ')})`);
} }
const rows: PlanRow[] = [];
const created: string[] = [];
for (const [i, p] of products.entries()) { for (const [i, p] of products.entries()) {
const tag = step(i + 1, products.length, p.id); const tag = step(i + 1, products.length, p.id);
const lookup = async (): Promise<J | null> => (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`)).data const lookup = async (): Promise<J | null> => (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`)).data
?.find((x: J) => x.attributes?.productId === p.id) ?? null; ?.find((x: J) => x.attributes?.productId === p.id) ?? null;
if (dry) { const f = await lookup(); log('apple', `${tag}: ${f ? `exists (${f.attributes.state})` : 'missing'} (dry)`); continue; } if (dry) { const f = await lookup(); rows.push(await planProduct(p, f?.id, f?.attributes?.state)); continue; }
// product ids are unique per app: a 409 finds the existing one; the journal covers the list lag after a create // product ids are unique per app: a 409 finds the existing one; the journal covers the list lag after a create
const first = Object.values(p.listings)[0]!; const first = Object.values(p.listings)[0]!;
const made = await findOrCreate<J>({ what: `in-app purchase ${p.id}`, tag: 'apple', unique: true, find: lookup, const made = await findOrCreate<J>({ what: `in-app purchase ${p.id}`, tag: 'apple', unique: true, find: lookup,
@ -50,6 +57,7 @@ export async function run(ctx: Ctx): Promise<void> {
familySharable: p.familySharable ?? false, ...(p.reviewNote ? { reviewNote: p.reviewNote } : {}) }, familySharable: p.familySharable ?? false, ...(p.reviewNote ? { reviewNote: p.reviewNote } : {}) },
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data }); relationships: { app: { data: { type: 'apps', id: appId } } } } })).data });
const id: string = made.value.id; const id: string = made.value.id;
if (made.created) created.push(p.id);
log('apple', `${tag}: ${made.created ? 'created' : 'exists'}`); log('apple', `${tag}: ${made.created ? 'created' : 'exists'}`);
const locsOf = async () => await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`); const locsOf = async () => await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`);
@ -88,5 +96,30 @@ export async function run(ctx: Ctx): Promise<void> {
log('apple', ` available in ${territories.length} territories + new ones`); log('apple', ` available in ${territories.length} territories + new ones`);
} }
} }
done('apple', dry ? 'iap checked (dry run)' : 'iap done (next: apple iap-review for the review screenshots)'); if (dry) {
console.log(dryPlan('apple iap', rows));
const absent = rows.filter(r => r.action === 'create').map(r => r.item);
if (absent.length) log('apple', `not on App Store Connect: ${absent.join(', ')}. If you created them in the last minutes, ${LAG_HINT} before acting on this plan`);
done('apple', 'iap checked (dry run)');
return;
}
if (created.length) {
await Bun.sleep(Number(process.env.STOREBOUND_LIST_SETTLE_MS ?? 3000));
const listed = (await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)).map((x: J) => x.attributes.productId as string);
if (reportMissing('apple', 'new products', created, listed, { fail: false }).length) log('apple', 'wait a minute before apple iap-review, or it cannot see them');
}
done('apple', 'iap done (next: apple iap-review for the review screenshots)');
/** What a real run would do to one product, from read-only calls. */
async function planProduct(p: (typeof products)[number], id: string | undefined, state: string | undefined): Promise<PlanRow> {
const locales = Object.keys(p.listings).map(l => langs.get(l)?.apple).filter((l): l is string => !!l);
const prices = [`USA ${p.usd}`, ...(p.overrides ?? []).map(o => `${appleTerritory(o)} ${o.price}`)].join(', ');
if (!id) return { item: p.id, action: 'create', detail: `${APPLE_IAP_TYPE[p.type]}; localizations ${locales.join(', ')}; prices ${prices}; ${territories.length} territories + new ones` };
const have = new Set((await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`)).map((l: J) => l.attributes.locale));
const add = locales.filter(l => !have.has(l));
const sched = await c.maybe(`/v2/inAppPurchases/${id}/iapPriceSchedule?include=manualPrices`);
const avail = await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`);
const parts = [add.length ? `localizations ${add.join(', ')}` : '', sched?.included?.length ? '' : `prices ${prices}`, avail?.data ? '' : `availability ${territories.length} territories + new ones`].filter(Boolean);
return parts.length ? { item: p.id, action: 'update', detail: `${parts.join('; ')} (state ${state ?? '?'})` } : { item: p.id, action: 'keep' };
}
} }

View file

@ -1,5 +1,9 @@
// App Store version + listing text (idempotent; re-run after editing the App Store listing file). // App Store version + listing text (idempotent; re-run after editing the App Store listing file).
// storebound apple listing --version 1.0.0 [--build 3] [--dry] // storebound apple listing --version 1.0.0 [--build 3] [--include-drafts] [--dry] [--json]
// Every run first reads App Store Connect and prints the plan: the version (keep, update the editable one, create, or
// refuse with the reason), the build, and per locale create / update with old -> new per field. --dry stops there
// (read-only); the real run asks in a terminal and applies exactly that plan. Locales marked status=draft or
// status=translate (listing translate) are skipped unless --include-drafts.
// - the editable iOS version: versionString, copyright, release type MANUAL; with --build that processed build is attached // - the editable iOS version: versionString, copyright, release type MANUAL; with --build that processed build is attached
// - appInfoLocalizations: name, subtitle, privacy policy URL per locale // - appInfoLocalizations: name, subtitle, privacy policy URL per locale
// - appStoreVersionLocalizations: description, keywords, promotional text, what's new (not on a first version), // - appStoreVersionLocalizations: description, keywords, promotional text, what's new (not on a first version),
@ -12,8 +16,10 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { type AppleCopy, parseAppStoreListing } from '../lib/copy'; import { type AppleCopy, parseAppStoreListing } from '../lib/copy';
import { compactDiff } from '../lib/diff'; import { compactDiff } from '../lib/diff';
import { mergeAppleListing, overLimits } from '../lib/listing-pull'; import { mergeAppleListing, overLimits } from '../lib/listing-pull';
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
import { appleName } from '../lib/config';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log'; import { done, log, printJson, warn } from '../lib/log';
import { ascClient, type J } from './asc'; import { ascClient, type J } from './asc';
@ -24,22 +30,6 @@ export function readAppleCopy(ctx: Ctx) {
return Object.fromEntries(Object.entries(all).filter(([l]) => !only.length || only.includes(l))); return Object.fromEntries(Object.entries(all).filter(([l]) => !only.length || only.includes(l)));
} }
async function upsertLocs(c: Awaited<ReturnType<typeof ascClient>>, list: string, type: string, parentRel: string, parentType: string, parentId: string,
want: Record<string, Record<string, string | undefined>>): Promise<void> {
const have = new Map((await c.all(`${list}?limit=200`)).map((l: J) => [l.attributes.locale, l] as const));
for (const [locale, raw] of Object.entries(want)) {
const attributes = Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== undefined));
const cur = have.get(locale);
if (!cur) {
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale, ...attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
log('apple', `${type} ${locale}: created`);
} else if (Object.entries(attributes).some(([k, v]) => cur.attributes[k] !== v)) {
await c.asc('PATCH', `/v1/${type}/${cur.id}`, { data: { type, id: cur.id, attributes } });
log('apple', `${type} ${locale}: updated`);
} else log('apple', `${type} ${locale}: up to date`);
}
}
/** apple listing pull: live texts -> diff -> (with --write) the App Store listing file. */ /** apple listing pull: live texts -> diff -> (with --write) the App Store listing file. */
async function pull(ctx: Ctx): Promise<void> { async function pull(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded; const { config, root, resolve } = ctx.loaded;
@ -65,7 +55,7 @@ async function pull(ctx: Ctx): Promise<void> {
} }
const file = resolve(config.apple?.listing ?? 'store/appstore.md'); const file = resolve(config.apple?.listing ?? 'store/appstore.md');
const before = existsSync(file) ? readFileSync(file, 'utf8') : '# App Store listing copy\n\nPulled from App Store Connect by `storebound apple listing pull`.\n'; const before = existsSync(file) ? readFileSync(file, 'utf8') : '# App Store listing copy\n\nPulled from App Store Connect by `storebound apple listing pull`.\n';
const r = mergeAppleListing(before, remote); const r = mergeAppleListing(before, remote, appleName(config));
const over = overLimits(r.changes, 'apple'); const over = overLimits(r.changes, 'apple');
const diff = compactDiff(before, r.md); const diff = compactDiff(before, r.md);
if (a.has('json')) printJson({ version: v.attributes.versionString, state: live, file, write: a.has('write') && !a.has('dry'), changes: r.changes, added: r.added, overLimits: over, diff }); if (a.has('json')) printJson({ version: v.attributes.versionString, state: live, file, write: a.has('write') && !a.has('dry'), changes: r.changes, added: r.added, overLimits: over, diff });
@ -81,45 +71,137 @@ async function pull(ctx: Ctx): Promise<void> {
done('apple', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new locales ${r.added.join(', ')}` : ''}`); done('apple', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new locales ${r.added.join(', ')}` : ''}`);
} }
/** The plan of one `apple listing --version` run, from read-only GETs. */
export interface AppleListingPlan {
version: string;
versionPlan: VersionPlan;
build: { number: string; id: string | null; current: string | null; action: 'attach' | 'same' | 'refuse'; reason: string } | null;
appInfo: { id: string; state: string; locales: ItemPlan[] };
/** null: the version is created first; App Store Connect copies the previous version's texts, then these are applied. */
versionLocales: ItemPlan[] | null;
wanted: Record<string, Record<string, string | undefined>>;
skipped: Skipped[];
notes: string[];
changes: number;
}
type Asc = Awaited<ReturnType<typeof ascClient>>;
async function planListing(ctx: Ctx, c: Asc, appId: string, version: string): Promise<AppleListingPlan> {
const { config, resolve } = ctx.loaded;
const app = config.app;
const listing = readAppleCopy(ctx);
const md = readFileSync(resolve(config.apple?.listing ?? 'store/appstore.md'), 'utf8');
const drafts = draftSections(md, 'apple');
const include = ctx.args.has('include-drafts');
const skipped: Skipped[] = [];
const notes: string[] = [];
for (const l of Object.keys(listing)) {
const st = drafts.get(l);
if (!st) continue;
if (include) notes.push(`${l}: ${st === 'draft' ? 'machine-translated draft' : 'untranslated (status=translate)'} included (--include-drafts)`);
else { skipped.push({ key: l, reason: draftReason(st) }); delete listing[l]; }
}
const copyright = app.copyright ?? `${new Date().getFullYear()} ${app.name}`;
const rows = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`);
const versionPlan = planVersion(rows, version, { copyright, releaseType: 'MANUAL' });
let build: AppleListingPlan['build'] = null;
const number = ctx.args.get('build');
if (number) {
const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${number}&filter[preReleaseVersion.version]=${version}&filter[preReleaseVersion.platform]=IOS`))[0];
const cur = versionPlan.id ? (await c.maybe(`/v1/appStoreVersions/${versionPlan.id}/build`))?.data : null;
const current = cur ? String(cur.attributes?.version ?? cur.id) : null;
build = !b ? { number, id: null, current, action: 'refuse', reason: `build ${version} (${number}) not found (still uploading? check TestFlight)` }
: b.attributes.processingState !== 'VALID' ? { number, id: b.id, current, action: 'refuse', reason: `build ${number} is ${b.attributes.processingState}; wait until VALID` }
: cur?.id === b.id ? { number, id: b.id, current, action: 'same', reason: `build ${number} is already attached` }
: { number, id: b.id, current, action: 'attach', reason: `attach build ${version} (${number})${current ? ` instead of ${current}` : ''}` };
}
const info = await c.editableAppInfo();
const infoWant = Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { name: f.name ?? appleName(config), subtitle: f.subtitle, privacyPolicyUrl: app.privacyPolicyUrl }]));
const infoLocs = planLocales(await c.all(`/v1/appInfos/${info.id}/appInfoLocalizations?limit=200`), infoWant);
if (versionPlan.first && Object.values(listing).some(f => f.whatsNew)) notes.push('what\'s new is left out: App Store Connect has no what\'s new on the first version');
const wanted = Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { description: f.description, keywords: f.keywords, promotionalText: f.promotionalText,
whatsNew: versionPlan.first ? undefined : f.whatsNew, supportUrl: app.supportUrl, marketingUrl: app.marketingUrl ?? app.website }]));
const versionLocales = versionPlan.id ? planLocales(await c.all(`/v1/appStoreVersions/${versionPlan.id}/appStoreVersionLocalizations?limit=200`), wanted) : null;
if (!versionLocales && versionPlan.action === 'create') notes.push('the new version gets the previous version\'s texts from App Store Connect; the version texts below are applied after it is created');
const changes = (versionPlan.action === 'create' || versionPlan.action === 'update' ? 1 : 0) + (build?.action === 'attach' ? 1 : 0)
+ infoLocs.filter(x => x.action !== 'same').length + (versionLocales ? versionLocales.filter(x => x.action !== 'same').length : Object.keys(wanted).length);
return { version, versionPlan, build, appInfo: { id: info.id, state: String(info.attributes?.state ?? info.attributes?.appStoreState ?? ''), locales: infoLocs },
versionLocales, wanted, skipped, notes, changes };
}
/** The plan as text lines. Pure. */
export function listingPlanLines(p: AppleListingPlan): string[] {
const v = p.versionPlan;
const out = [`Version (App Store Connect has: ${v.existing.length ? v.existing.map(x => `${x.versionString} ${x.state} ${x.platform}`).join(', ') : 'no iOS version yet'})`];
out.push(` ${v.action === 'refuse' ? 'REFUSE' : v.action.toUpperCase()}: ${v.reason}`);
for (const ch of v.changes) out.push(` ${ch.field}: ${v.action === 'create' ? short(ch.to) : `${short(ch.from)} -> ${short(ch.to)}`}`);
if (p.build) out.push(`Build: ${p.build.action === 'refuse' ? 'REFUSE: ' : ''}${p.build.reason}`);
out.push(`App info ${p.appInfo.state ? `(${p.appInfo.state})` : ''}: name, subtitle, privacy policy URL per locale · ${counts(p.appInfo.locales)}`);
for (const l of p.appInfo.locales) out.push(...itemLines(l.key, l));
if (p.versionLocales) {
out.push(`Version texts: description, keywords, promotional text, what's new, support / marketing URL · ${counts(p.versionLocales)}`);
for (const l of p.versionLocales) out.push(...itemLines(l.key, l));
} else if (v.action === 'refuse') {
out.push('Version texts: not planned (the version is refused)');
} else {
out.push(`Version texts (applied after the version is created): ${Object.keys(p.wanted).join(', ')}`);
}
for (const s of p.skipped) out.push(`Skipped ${s.key}: ${s.reason}`);
for (const n of p.notes) out.push(`Note: ${n}`);
return out;
}
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, plan: ItemPlan[]): Promise<void> {
for (const l of plan) {
if (l.action === 'create') {
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
log('apple', `${type} ${l.key}: created`);
} else if (l.action === 'update') {
await c.asc('PATCH', `/v1/${type}/${l.id}`, { data: { type, id: l.id, attributes: Object.fromEntries(l.changes.map(ch => [ch.field, ch.to ?? ''])) } });
log('apple', `${type} ${l.key}: updated ${l.changes.map(ch => ch.field).join(', ')}`);
}
}
}
export async function run(ctx: Ctx): Promise<void> { export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded; const { config, root } = ctx.loaded;
const a = ctx.args; const a = ctx.args;
if (a._[0] === 'pull') return pull(ctx); if (a._[0] === 'pull') return pull(ctx);
const version = a.get('version'); const version = a.get('version');
if (!version) throw new Error('usage: apple listing --version 1.0.0 [--build N] [--dry]'); if (!version) throw new Error('usage: apple listing --version 1.0.0 [--build N] [--include-drafts] [--dry] [--json]');
const listing = readAppleCopy(ctx); const dry = a.has('dry');
log('apple', `listing: ${Object.keys(listing).length} locales (${Object.keys(listing).join(', ')})`);
if (a.has('dry')) return;
const app = config.app;
const copyright = app.copyright ?? `${new Date().getFullYear()} ${app.name}`;
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app(); const appId = await c.app();
const p = await planListing(ctx, c, appId, version);
const refused = [p.versionPlan.action === 'refuse' ? p.versionPlan.reason : '', p.build?.action === 'refuse' ? p.build.reason : ''].filter(Boolean);
if (a.has('json')) printJson({ dry, ...p, refused });
else for (const line of listingPlanLines(p)) console.log(line);
if (refused.length) { if (dry) { process.exitCode = 1; warn('apple', `dry run: would refuse: ${refused.join('; ')}`); return; } throw new Error(refused.join('; ')); }
if (dry) { done('apple', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('apple', 'listing already up to date'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to App Store Connect?`))) { warn('apple', 'nothing written'); return; }
let v = await c.editableVersion(); const vp = p.versionPlan;
if (!v) { let versionId = vp.id;
v = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions', if (vp.action === 'create') {
attributes: { platform: 'IOS', versionString: version, copyright, releaseType: 'MANUAL' }, versionId = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data; attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
log('apple', `version ${version} created`); log('apple', `version ${version} created`);
} else if (v.attributes.versionString !== version || v.attributes.copyright !== copyright || v.attributes.releaseType !== 'MANUAL') { } else if (vp.action === 'update') {
await c.asc('PATCH', `/v1/appStoreVersions/${v.id}`, { data: { type: 'appStoreVersions', id: v.id, attributes: { versionString: version, copyright, releaseType: 'MANUAL' } } }); await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(vp.changes.map(ch => [ch.field, ch.to])) } });
log('apple', `version ${v.attributes.versionString} -> ${version}, copyright, release MANUAL`); log('apple', `version: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`);
} }
if (p.build?.action === 'attach') {
const build = a.get('build'); await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } });
if (build) { log('apple', `build ${version} (${p.build.number}) attached`);
const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${build}&filter[preReleaseVersion.version]=${version}&filter[preReleaseVersion.platform]=IOS`))[0];
if (!b) throw new Error(`build ${version} (${build}) not found (still uploading? check TestFlight)`);
if (b.attributes.processingState !== 'VALID') throw new Error(`build ${build} is ${b.attributes.processingState}; wait until VALID`);
await c.asc('PATCH', `/v1/appStoreVersions/${v.id}/relationships/build`, { data: { type: 'builds', id: b.id } });
log('apple', `build ${version} (${build}) attached`);
} }
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, p.appInfo.locales);
const info = await c.editableAppInfo(); const vl = p.versionLocales ?? planLocales(await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=200`), p.wanted);
await upsertLocs(c, `/v1/appInfos/${info.id}/appInfoLocalizations`, 'appInfoLocalizations', 'appInfo', 'appInfos', info.id, await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vl);
Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { name: f.name ?? app.name, subtitle: f.subtitle, privacyPolicyUrl: app.privacyPolicyUrl }])));
await upsertLocs(c, `/v1/appStoreVersions/${v.id}/appStoreVersionLocalizations`, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', v.id,
Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { description: f.description, keywords: f.keywords, promotionalText: f.promotionalText,
whatsNew: f.whatsNew, supportUrl: app.supportUrl, marketingUrl: app.marketingUrl ?? app.website }])));
done('apple', 'listing done'); done('apple', 'listing done');
} }

View file

@ -3,12 +3,12 @@
// subscriptions + terms URL) and the files the config points at. No network; credentials are only checked for presence. // subscriptions + terms URL) and the files the config points at. No network; credentials are only checked for presence.
// storebound check everything above // storebound check everything above
// storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors // storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors
// --json structured result ({ ok, items, warnings, problems } or { findings, errors }), exit 1 on problems // --json structured result ({ ok, items, warnings, hints, problems } or { findings, errors }), exit 1 on problems
import { existsSync, readFileSync } from 'node:fs'; import { existsSync, readFileSync } from 'node:fs';
import { relative } from 'node:path'; import { relative } from 'node:path';
import { type AsoFinding, auditAso } from './lib/aso'; import { type AsoFinding, auditAso } from './lib/aso';
import { playCodes } from './lib/config'; import { appleName, playCodes } from './lib/config';
import { APPLE_IAP_LIMITS, len, parseAppStoreListing, parsePlayListing } from './lib/copy'; import { APPLE_IAP_LIMITS, appleNameIssues, len, parseAppStoreListing, parsePlayListing } from './lib/copy';
import type { Ctx } from './lib/ctx'; import type { Ctx } from './lib/ctx';
import { dataSafetyRows } from './lib/data-safety'; import { dataSafetyRows } from './lib/data-safety';
import { reviewDemoAccount } from './lib/credentials'; import { reviewDemoAccount } from './lib/credentials';
@ -22,7 +22,7 @@ function aso(ctx: Ctx): void {
const { config, resolve } = ctx.loaded; const { config, resolve } = ctx.loaded;
const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined; const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined;
const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined; const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined;
const f: AsoFinding[] = auditAso({ apple, play, appName: config.app.name, storefront: ctx.args.get('storefront') ?? 'US' }); const f: AsoFinding[] = auditAso({ apple, play, appName: appleName(config), storefront: ctx.args.get('storefront') ?? 'US' });
if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; } if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; }
const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const; const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const;
for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`); for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`);
@ -38,6 +38,7 @@ export async function run(ctx: Ctx): Promise<void> {
const problems: string[] = []; const problems: string[] = [];
const items: { what: string; detail: string }[] = []; const items: { what: string; detail: string }[] = [];
const warnings: string[] = []; const warnings: string[] = [];
const hints: string[] = [];
const note = (msg: string): void => { warnings.push(msg); warn('check', msg); }; const note = (msg: string): void => { warnings.push(msg); warn('check', msg); };
const tryDo = (what: string, fn: () => string): void => { const tryDo = (what: string, fn: () => string): void => {
try { const detail = fn(); items.push({ what, detail }); log('check', `${what}: ${detail}`); } catch (e) { try { const detail = fn(); items.push({ what, detail }); log('check', `${what}: ${detail}`); } catch (e) {
@ -64,6 +65,9 @@ export async function run(ctx: Ctx): Promise<void> {
const copy = parseAppStoreListing(readFileSync(f, 'utf8')); const copy = parseAppStoreListing(readFileSync(f, 'utf8'));
const missing = config.languages.filter(l => l.apple && !copy[l.apple]).map(l => l.apple); const missing = config.languages.filter(l => l.apple && !copy[l.apple]).map(l => l.apple);
if (missing.length) note(`appstore listing has no section for ${missing.join(', ')}`); if (missing.length) note(`appstore listing has no section for ${missing.join(', ')}`);
for (const i of appleNameIssues(copy, config.languages.flatMap(l => l.apple ? [l.apple] : []), appleName(config), config.app.name)) {
if (i.level === 'error') problems.push(i.msg); else { hints.push(i.msg); log('check', `hint: ${i.msg}`); }
}
return `${Object.keys(copy).length} locales`; return `${Object.keys(copy).length} locales`;
}); });
// listing translation drafts (storebound listing translate): fine to keep working on, not to push unreviewed // listing translation drafts (storebound listing translate): fine to keep working on, not to push unreviewed
@ -103,7 +107,7 @@ export async function run(ctx: Ctx): Promise<void> {
if (existsSync(resolve('.gitignore')) && !/^\/?\.storebound\/?$/m.test(readFileSync(resolve('.gitignore'), 'utf8'))) if (existsSync(resolve('.gitignore')) && !/^\/?\.storebound\/?$/m.test(readFileSync(resolve('.gitignore'), 'utf8')))
problems.push('.gitignore does not ignore .storebound/ (credentials live there)'); problems.push('.gitignore does not ignore .storebound/ (credentials live there)');
if (ctx.args.has('json')) { printJson({ config: path, ok: !problems.length, items, warnings, problems }); if (problems.length) process.exitCode = 1; return; } if (ctx.args.has('json')) { printJson({ config: path, ok: !problems.length, items, warnings, hints, problems }); if (problems.length) process.exitCode = 1; return; }
if (problems.length) { for (const p of problems) console.error(` - ${p}`); throw new Error(`${problems.length} problems`); } if (problems.length) { for (const p of problems) console.error(` - ${p}`); throw new Error(`${problems.length} problems`); }
log('check', 'all good'); log('check', 'all good');
} }

View file

@ -15,7 +15,7 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args {
const repeated = new Map<string, string[]>(); const repeated = new Map<string, string[]>();
const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); }; const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); };
const _: string[] = []; const _: string[] = [];
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'force-unlock', ...booleans]); const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'force-unlock', 'include-drafts', ...booleans]);
for (let i = 0; i < argv.length; i++) { for (let i = 0; i < argv.length; i++) {
const a = argv[i]!; const a = argv[i]!;
if (!a.startsWith('--')) { _.push(a); continue; } if (!a.startsWith('--')) { _.push(a); continue; }

View file

@ -146,6 +146,10 @@ export interface ShotSpec {
/** Web: JS run in the page before the screenshot. */ /** Web: JS run in the page before the screenshot. */
eval?: string[]; eval?: string[];
device?: 'phone' | 'tablet' | 'both'; device?: 'phone' | 'tablet' | 'both';
/** Web, capture.session "per-language": how this shot is reached in the already booted page. "spa" (default):
* history.pushState to its path + a popstate event, then waitFor / eval (switch scenes from those); "reload":
* page.goto in the same page. A failing waitFor there falls back to a fresh page. */
navigate?: 'spa' | 'reload';
/** ios-sim: extra launch arguments, e.g. ["-shotScene", "{shot}", "-seed", "1"] (read them with UserDefaults / your engine). */ /** ios-sim: extra launch arguments, e.g. ["-shotScene", "{shot}", "-seed", "1"] (read them with UserDefaults / your engine). */
args?: string[]; args?: string[];
/** android-emu: intent extras for `am start` (string / int / float / boolean), "{lang}" replaced in strings. */ /** android-emu: intent extras for `am start` (string / int / float / boolean), "{lang}" replaced in strings. */
@ -194,6 +198,18 @@ export interface ShotsCapture {
* every device, or per device class. Default: the frame's bar share of the height (phone 54 / 956 = 162 px on a 6.9" * every device, or per device class. Default: the frame's bar share of the height (phone 54 / 956 = 162 px on a 6.9"
* iPhone, 13" iPad 24 / 1376 = 48 px). */ * iPhone, 13" iPad 24 / 1376 = 48 px). */
cropTop?: number | { phone?: number; tablet?: number }; cropTop?: number | { phone?: number; tablet?: number };
/** Web: parallel browser contexts (one headless Chromium). Default min(3, CPU cores / 4): game boots are GPU-heavy.
* `--concurrency N` overrides. */
concurrency?: number;
/** Web: "per-shot" (default: new context + full boot per frame) or "per-language" (one page per language and
* device, booted once; shots switch in it, see ShotSpec.navigate). */
session?: 'per-shot' | 'per-language';
/** Web, per-language: how long a reused page may take to reach a shot's waitFor before a fresh page is used.
* Default 15000 ms. */
reuseTimeoutMs?: number;
/** Web: files or folders of the app build (e.g. "apps/game/src" or "apps/game/dist") hashed into the capture cache,
* so a code change re-captures. Default: the HTML at baseUrl and the scripts it loads. */
build?: string | string[];
shots: Record<string, ShotSpec>; shots: Record<string, ShotSpec>;
} }
@ -493,6 +509,10 @@ export interface ShipConfig {
}; };
apple?: { apple?: {
bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string; bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string;
/** App Store name in the primary locale (at most 30 characters) when it differs from app.name, e.g. because the plain
* name is taken on the App Store ("STAR DASH: Stone Age to 2100"). Default app.name. A `### name` block in the
* App Store listing file wins for its locale. app.name stays the Play / on-device name. */
name?: string;
/** Apple Developer Team ID (10 characters, Membership details). apple-app-site-association and ad-hoc export use it. */ /** Apple Developer Team ID (10 characters, Membership details). apple-app-site-association and ad-hoc export use it. */
teamId?: string; teamId?: string;
/** Ad-hoc / release-testing export (`storebound apple adhoc`). */ /** Ad-hoc / release-testing export (`storebound apple adhoc`). */
@ -684,6 +704,12 @@ function validateConsole(c: ConsoleConfig): string[] {
} }
/** Platforms of the app (app identity): app.platforms, else from the store sections. */ /** Platforms of the app (app identity): app.platforms, else from the store sections. */
/** App Store name limit (characters). */
export const APPLE_NAME_MAX = 30;
/** The App Store name in the primary locale: apple.name, else app.name. Per-locale `### name` blocks win over it. */
export const appleName = (c: Pick<ShipConfig, 'app' | 'apple'>): string => c.apple?.name?.trim() || c.app.name;
export const platformsOf = (c: Pick<ShipConfig, 'app' | 'apple' | 'play'>): Platform[] => export const platformsOf = (c: Pick<ShipConfig, 'app' | 'apple' | 'play'>): Platform[] =>
c.app.platforms ?? [...(c.apple ? ['ios' as const] : []), ...(c.play ? ['android' as const] : [])]; c.app.platforms ?? [...(c.apple ? ['ios' as const] : []), ...(c.play ? ['android' as const] : [])];
@ -757,6 +783,9 @@ export function validateConfig(c: unknown): string[] {
e.push(`play.billingPrograms: a list of ${PLAY_BILLING_PROGRAMS.join(' | ')}`); e.push(`play.billingPrograms: a list of ${PLAY_BILLING_PROGRAMS.join(' | ')}`);
if (cfg.apple) { if (cfg.apple) {
if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)'); if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)');
const an = cfg.apple.name;
if (an !== undefined && (typeof an !== 'string' || !an.trim())) e.push('apple.name: the App Store name (text), or leave it out to use app.name');
else if (an !== undefined && [...an].length > APPLE_NAME_MAX) e.push(`apple.name: ${[...an].length} characters > ${APPLE_NAME_MAX} (App Store limit)`);
if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)'); 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; const enc = cfg.apple.usesNonExemptEncryption;
if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false'); if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false');

View file

@ -14,7 +14,7 @@
// https://support.google.com/googleplay/android-developer/answer/9859655 (content ratings) // https://support.google.com/googleplay/android-developer/answer/9859655 (content ratings)
// https://support.google.com/googleplay/android-developer/answer/9867159 (target audience and content) // https://support.google.com/googleplay/android-developer/answer/9867159 (target audience and content)
import { AGE_RATING_NONE } from '../apple/appinfo'; import { AGE_RATING_NONE } from '../apple/appinfo';
import { type AgeGroup, AGE_GROUPS, IARC_QUESTIONS, type IarcQuestion, profileOf, type ShipConfig } from './config'; import { type AgeGroup, AGE_GROUPS, appleName, IARC_QUESTIONS, type IarcQuestion, profileOf, type ShipConfig } from './config';
import { APPLE_PRIVACY, applePurpose } from './declarations'; import { APPLE_PRIVACY, applePurpose } from './declarations';
import { maskUser } from './credentials'; import { maskUser } from './credentials';
@ -86,7 +86,8 @@ function appRecord(config: ShipConfig): Answer[] {
const lang = locale ? LANGUAGE_NAMES[locale] : undefined; const lang = locale ? LANGUAGE_NAMES[locale] : undefined;
return [ return [
a ? ok('platform:ios', 'Platforms: iOS', true, 'apple section') : ask('platform:ios', 'Platforms: iOS', 'config', 'The config has no apple section.'), a ? ok('platform:ios', 'Platforms: iOS', true, 'apple section') : ask('platform:ios', 'Platforms: iOS', 'config', 'The config has no apple section.'),
ok('name', 'Name', config.app.name, 'app.name', 'Must be unique on the App Store; App Store Connect says so when it is taken.'), ok('name', 'Name', appleName(config), a?.name?.trim() ? 'apple.name' : 'app.name',
`Must be unique on the App Store (at most 30 characters); when App Store Connect says it is already being used, set apple.name (e.g. "${config.app.name}: <short tagline>") and fill again.`),
lang ? ok('language', 'Primary Language', lang, a?.primaryLocale ? 'apple.primaryLocale' : 'languages[0].apple') lang ? ok('language', 'Primary Language', lang, a?.primaryLocale ? 'apple.primaryLocale' : 'languages[0].apple')
: ask('language', 'Primary Language', 'apple.primaryLocale', locale ? `Pick the language of locale "${locale}".` : 'Set apple.primaryLocale (e.g. en-US).'), : ask('language', 'Primary Language', 'apple.primaryLocale', locale ? `Pick the language of locale "${locale}".` : 'Set apple.primaryLocale (e.g. en-US).'),
a?.bundleId ? ok('bundleId', 'Bundle ID', a.bundleId, 'apple.bundleId', 'Register it first if it is not in the list: storebound apple bundle.') a?.bundleId ? ok('bundleId', 'Bundle ID', a.bundleId, 'apple.bundleId', 'Register it first if it is not in the list: storebound apple bundle.')

View file

@ -5,7 +5,7 @@
// The names are modeled on Apple's and Google's public help pages (sources in console-answers.ts), not recorded from a // The names are modeled on Apple's and Google's public help pages (sources in console-answers.ts), not recorded from a
// signed-in console: the exact App Privacy dialog titles, the IARC question wording and the Play category names could // signed-in console: the exact App Privacy dialog titles, the IARC question wording and the Play category names could
// not be verified without an account, which is why every field has candidates and the engine falls back on a miss. // not be verified without an account, which is why every field has candidates and the engine falls back on a miss.
import { AGE_GROUPS, type ShipConfig } from './config'; import { AGE_GROUPS, appleName, type ShipConfig } from './config';
import { AGE_LABELS, type Answer, APPLE_PURPOSES, type FormId } from './console-answers'; import { AGE_LABELS, type Answer, APPLE_PURPOSES, type FormId } from './console-answers';
/** An accessible name: a string matches exactly, a RegExp matches the name. */ /** An accessible name: a string matches exactly, a RegExp matches the name. */
@ -188,12 +188,13 @@ const POLICY: Name[] = ['Policy and programs', 'Policy', 'Politika ve programlar
/** /**
* The steps that open a form after sign-in, built from the config only (apple.appId, apple.bundleId, play.packageName, * The steps that open a form after sign-in, built from the config only (apple.appId, apple.bundleId, play.packageName,
* app.name). The last step waits for the form itself. Pure. * apple.name / app.name). The last step waits for the form itself. Pure.
*/ */
export function navPlan(id: FormId, config: ShipConfig, bases: NavBases = NAV_BASES): NavStep[] { export function navPlan(id: FormId, config: ShipConfig, bases: NavBases = NAV_BASES): NavStep[] {
const asc = bases.asc.replace(/\/$/, ''), play = bases.play.replace(/\/$/, ''); const asc = bases.asc.replace(/\/$/, ''), play = bases.play.replace(/\/$/, '');
const name = config.app?.name; const name = config.app?.name;
const named = name ? { name } : {}; const named = name ? { name } : {};
const appleNamed = name ? { name: appleName(config) } : {};
switch (id) { switch (id) {
case 'apple-app-record': return [ case 'apple-app-record': return [
{ kind: 'goto', label: 'open Apps', url: `${asc}/apps` }, { kind: 'goto', label: 'open Apps', url: `${asc}/apps` },
@ -206,7 +207,7 @@ export function navPlan(id: FormId, config: ShipConfig, bases: NavBases = NAV_BA
const appId = config.apple?.appId; const appId = config.apple?.appId;
const open: NavStep[] = appId ? [{ kind: 'goto', label: 'open App Privacy of the app (apple.appId)', url: `${asc}/apps/${encodeURIComponent(appId)}/distribution/privacy` }] : [ const open: NavStep[] = appId ? [{ kind: 'goto', label: 'open App Privacy of the app (apple.appId)', url: `${asc}/apps/${encodeURIComponent(appId)}/distribution/privacy` }] : [
{ kind: 'goto', label: 'open Apps', url: `${asc}/apps` }, { kind: 'goto', label: 'open Apps', url: `${asc}/apps` },
{ kind: 'pickApp', label: 'the app in the list', tokens: config.apple?.bundleId ? [config.apple.bundleId] : [], ...named }, { kind: 'pickApp', label: 'the app in the list', tokens: config.apple?.bundleId ? [config.apple.bundleId] : [], ...appleNamed },
{ kind: 'click', label: 'App Privacy in the sidebar', roles: ['link', 'tab'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] }, { kind: 'click', label: 'App Privacy in the sidebar', roles: ['link', 'tab'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] },
]; ];
return [...open, { kind: 'wait', label: 'the App Privacy page', roles: ['heading'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] }]; return [...open, { kind: 'wait', label: 'the App Privacy page', roles: ['heading'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] }];

View file

@ -83,3 +83,21 @@ export function parseAppStoreListing(md: string): Record<string, AppleCopy> {
if (errors.length) throw new Error('appstore listing: ' + errors.join('; ')); if (errors.length) throw new Error('appstore listing: ' + errors.join('; '));
return out; return out;
} }
export interface NameIssue { level: 'error' | 'info'; msg: string }
/**
* The App Store name per locale (a `### name` block, else `fallback` = apple.name, else app.name) against the 30-char
* limit, plus a hint when every locale uses the plain app.name: App Store names are unique, so a taken name stops the
* app record ("already being used"). Pure.
*/
export function appleNameIssues(copy: Record<string, AppleCopy>, locales: string[], fallback: string, appName: string): NameIssue[] {
const out: NameIssue[] = [];
const all = [...new Set([...locales, ...Object.keys(copy)])];
const names = all.map(l => ({ l, name: (copy[l]?.name ?? fallback).trim(), own: !!copy[l]?.name }));
for (const n of names) if (len(n.name) > APPLE_LIMITS.name)
out.push({ level: 'error', msg: `App Store name of ${n.l} is ${len(n.name)} > ${APPLE_LIMITS.name} characters: "${n.name}" (${n.own ? 'its ### name block' : fallback === appName ? 'app.name; set apple.name' : 'apple.name'})` });
if (names.length && names.every(n => n.name === appName))
out.push({ level: 'info', msg: `the App Store name is "${appName}" in every locale: App Store names are unique, so if it is taken App Store Connect refuses the record ("already being used"). Then set apple.name with a short suffix, e.g. "${appName}: <tagline>" (30 characters at most); app.name stays the Play and on-device name` });
return out;
}

61
cli/lib/dry.ts Normal file
View file

@ -0,0 +1,61 @@
// Dry-run plans every write command shows the same way, so the owner sees WHAT would change, not only how many
// things ("listing: 20 locales" is not a plan). Pure. `tests/dry-plan.test.ts` scans cli/** for --dry branches that
// print nothing but a count (docs/pitfalls.md, "Dry runs that print no plan").
import { textTable } from './table';
export interface PlanRow {
/** What is changed: a product id, a locale, a file, a build. */
item: string;
/** create, update, upload, replace, delete, keep ... */
action: string;
/** The concrete change: fields, values, old -> new. */
detail?: string;
}
/**
* Standard dry-run plan: a title line and one aligned row per change. Rows whose action is "keep" are counted in the
* title but left out of the table, so a long "nothing to do" list does not hide the real changes.
*/
export function dryPlan(title: string, rows: PlanRow[]): string {
const change = rows.filter(r => r.action !== 'keep');
const kept = rows.length - change.length;
const head = `dry run: ${title}: ${change.length ? `${change.length} change(s)` : 'nothing to change'}${kept ? `, ${kept} unchanged` : ''}; nothing written`;
if (!change.length) return head;
return `${head}\n${textTable(['item', 'action', 'detail'], change.map(r => [r.item, r.action, r.detail ?? '']))}`;
}
/** A source line that leaves a --dry branch (`if (dry) return` / `if (a.has('dry')) { ...; return; }`) at the top level of a function. */
const DRY = String.raw`(?:dry|(?:ctx\.)?a(?:rgs)?\.has\('dry'\))`;
const EXIT = new RegExp(String.raw`^ (?:\} )?if \(${DRY}\) (?:\{ )?(?:.*\b)?return\b`);
/** Output that is a plan by itself: the shared table, the request lister, JSON, or printing the content that would be written. */
const RICH = /dryPlan\(|execute\(|printJson\(|describeReq\(|console\.log\((?!['`])|process\.stdout\.write\(/;
const OUT = /\b(?:log|done|say|warn|console\.log)\(\s*(?:[A-Za-z_'".]+,\s*)?(['`])(.*)\1/;
/** Interpolations that only count or name sections: `${x.length}`, `${n}`, `${Object.keys(listing).join(', ')}`, `${dry ? ...}`. */
const countOnly = (e: string): boolean => /(?:\.length|\.size|\bn|count|total)\s*$/.test(e.trim()) || /Object\.keys\(/.test(e) || /\bdry\s*\?|^\s*(?:TAG|tag)\s*$/.test(e);
/** True when the line prints something that names the concrete change (not only a count). */
export function isPlanLine(line: string): boolean {
if (RICH.test(line)) return true;
const m = OUT.exec(line);
if (!m) return false;
const parts = [...m[2]!.matchAll(/\$\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g)].map(x => x[1]!);
if (parts.some(p => !countOnly(p))) return true;
// a literal that spells out the one request ("would POST /v1/analyticsReportRequests {accessType=ONGOING}")
return !parts.length && /\bwould\b/.test(m[2]!) && !/nothing|\d+ \w+\(s\)/.test(m[2]!);
}
/**
* --dry exits in one source file that print nothing but a count before them (scanning back to the start of the
* enclosing top-level function, at most 40 lines). Returns 1-based line numbers. Pure; heuristic by design.
*/
export function countOnlyDryExits(source: string): number[] {
const lines = source.split('\n');
const out: number[] = [];
lines.forEach((l, i) => {
if (!EXIT.test(l)) return;
let from = i;
while (from > 0 && i - from < 40 && !/^(?:export )?(?:async )?function |^\}/.test(lines[from - 1]!)) from--;
if (!lines.slice(from, i + 1).some(isPlanLine)) out.push(i + 1);
});
return out;
}

View file

@ -471,7 +471,7 @@ export function planImport(scan: FastlaneScan, o: PlanOptions): ImportPlan {
const md = `# ${appName} · App Store listing copy const md = `# ${appName} · App Store listing copy
Imported from fastlane deliver (\`storebound import fastlane\`). Source for \`storebound apple listing\`. One Imported from fastlane deliver (\`storebound import fastlane\`). Source for \`storebound apple listing\`. One
\`## <ASC locale>\` section per locale, one fenced block per \`### <field>\`: \`name\` (optional, defaults to \`app.name\`), \`## <ASC locale>\` section per locale, one fenced block per \`### <field>\`: \`name\` (optional, defaults to \`apple.name\`, else \`app.name\`),
\`subtitle\` (30), \`promotionalText\` (170), \`keywords\` (100 bytes, comma separated, no spaces after commas), \`subtitle\` (30), \`promotionalText\` (170), \`keywords\` (100 bytes, comma separated, no spaces after commas),
\`description\` (4000), \`whatsNew\` (optional). Privacy policy, support and marketing URL come from \`description\` (4000), \`whatsNew\` (optional). Privacy policy, support and marketing URL come from
\`storebound.config.ts\`. \`storebound.config.ts\`.

137
cli/lib/listing-plan.ts Normal file
View file

@ -0,0 +1,137 @@
// Write plans for the listing commands (apple listing, play listing, apple appinfo): what the store has now, what a
// run would send, field by field (old -> new). The dry run prints the plan; the real run applies exactly that plan.
// Pure: the commands read the store, this file decides and formats.
import { EDITABLE } from '../apple/asc';
import { appleLocaleOf, markerOf, playCodesOf, sections, type TStatus } from './listing-translate';
export interface FieldDiff { field: string; from: string | null; to: string | null }
/** One localization (or one settings object): create, update the changed fields, or leave it. */
export interface ItemPlan { key: string; action: 'create' | 'update' | 'same'; id?: string; changes: FieldDiff[]; unchanged: string[]; attributes: Record<string, string> }
export interface Skipped { key: string; reason: string }
const norm = (v: unknown): string | null => (v === undefined || v === null || v === '' ? null : String(v));
/** Create / update / same for one wanted attribute set against the current one (null when it does not exist). Only
* defined wanted values count; an empty and a missing value are the same. Pure. */
export function planItem(key: string, current: { id?: string; attributes: Record<string, unknown> } | null, want: Record<string, string | undefined>): ItemPlan {
const attributes = Object.fromEntries(Object.entries(want).filter((e): e is [string, string] => e[1] !== undefined));
if (!current) return { key, action: 'create', changes: Object.entries(attributes).map(([field, to]) => ({ field, from: null, to })), unchanged: [], attributes };
const changes: FieldDiff[] = [], unchanged: string[] = [];
for (const [field, to] of Object.entries(attributes)) {
const from = norm(current.attributes[field]);
if (from === norm(to)) unchanged.push(field); else changes.push({ field, from, to });
}
return { key, action: changes.length ? 'update' : 'same', ...(current.id ? { id: current.id } : {}), changes, unchanged, attributes };
}
/** Localizations: every wanted locale against the ones the store has (by `locale`). Pure. */
export function planLocales(have: { id: string; attributes: Record<string, unknown> }[], want: Record<string, Record<string, string | undefined>>): ItemPlan[] {
const byLocale = new Map(have.map(h => [String(h.attributes.locale), h] as const));
return Object.entries(want).map(([locale, w]) => planItem(locale, byLocale.get(locale) ?? null, w));
}
// ---- App Store version ----
export interface VersionInfo { id: string; versionString: string; state: string; platform: string }
export interface VersionPlan {
action: 'create' | 'update' | 'keep' | 'refuse';
/** The editable version that is kept or updated. */
id?: string;
reason: string;
existing: VersionInfo[];
changes: FieldDiff[];
attributes: Record<string, string>;
/** No version of the app went through review before: what's new cannot be set on the first version. */
first: boolean;
}
/** Versions App Store Connect still lets you edit (texts, build, version string). */
export const EDITABLE_STATES = EDITABLE;
/** A version in these states blocks a new one (App Store Connect allows one version in progress). */
const IN_PROGRESS = new Set(['WAITING_FOR_REVIEW', 'IN_REVIEW', 'READY_FOR_REVIEW', 'WAITING_FOR_EXPORT_COMPLIANCE', 'PENDING_APPLE_RELEASE',
'PENDING_DEVELOPER_RELEASE', 'PROCESSING_FOR_APP_STORE', 'PROCESSING_FOR_DISTRIBUTION', 'ACCEPTED']);
/** -1 / 0 / 1 by numeric segments ("1.0" < "1.0.1", "1.10" > "1.9"). */
export function compareVersions(a: string, b: string): number {
const x = a.split('.').map(Number), y = b.split('.').map(Number);
for (let i = 0; i < Math.max(x.length, y.length); i++) { const d = (x[i] ?? 0) - (y[i] ?? 0); if (d) return d < 0 ? -1 : 1; }
return 0;
}
/** Version rows of GET /v1/apps/{id}/appStoreVersions. */
export const versionInfos = (rows: { id: string; attributes: Record<string, unknown> }[]): VersionInfo[] =>
rows.map(r => ({ id: r.id, versionString: String(r.attributes.versionString ?? ''), state: String(r.attributes.appVersionState ?? r.attributes.appStoreState ?? ''), platform: String(r.attributes.platform ?? 'IOS') }));
/**
* What `apple listing --version <want>` does with the app's iOS versions: keep / update the editable one (its version
* string changes only while PREPARE_FOR_SUBMISSION), create a new one, or refuse (the number exists, is not higher than
* a version that went through review, or another version is in review / pending release). Pure.
*/
export function planVersion(rows: { id: string; attributes: Record<string, unknown> }[], want: string, attrs: { copyright: string; releaseType: string }): VersionPlan {
const existing = versionInfos(rows);
const editable = existing.find(v => EDITABLE_STATES.has(v.state));
const others = existing.filter(v => v !== editable);
const first = !others.length;
const base = { existing, first, changes: [] as FieldDiff[], attributes: {} as Record<string, string> };
const refuse = (reason: string): VersionPlan => ({ ...base, action: 'refuse', reason });
const taken = others.find(v => v.versionString === want);
if (taken) return refuse(`version ${want} already exists (${taken.state}); a new version needs a higher number`);
const higher = others.filter(v => compareVersions(v.versionString, want) >= 0).sort((a, b) => compareVersions(b.versionString, a.versionString))[0];
if (higher && (!editable || editable.versionString !== want))
return refuse(`version ${want} is not higher than ${higher.versionString} (${higher.state}); App Store versions only go up`);
if (editable) {
const cur = rows.find(r => r.id === editable.id)!.attributes;
const wantAttrs = { versionString: want, copyright: attrs.copyright, releaseType: attrs.releaseType };
const p = planItem(editable.id, { id: editable.id, attributes: cur }, wantAttrs);
if (editable.versionString !== want && editable.state !== 'PREPARE_FOR_SUBMISSION')
return refuse(`the editable version ${editable.versionString} is ${editable.state}; its version string changes only while PREPARE_FOR_SUBMISSION (use --version ${editable.versionString}, or change it in App Store Connect)`);
if (editable.versionString !== want) return { ...base, action: 'update', id: editable.id, changes: p.changes, attributes: p.attributes,
reason: `update the editable version ${editable.versionString} (${editable.state}) to ${want}` };
return { ...base, action: p.changes.length ? 'update' : 'keep', id: editable.id, changes: p.changes, attributes: p.attributes,
reason: p.changes.length ? `update version ${want} (${editable.state}): ${p.changes.map(c => c.field).join(', ')}` : `version ${want} (${editable.state}) is up to date` };
}
const busy = others.find(v => IN_PROGRESS.has(v.state));
if (busy) return refuse(`version ${busy.versionString} is ${busy.state}; App Store Connect allows one version in progress (wait for its release or remove it from review)`);
const attributes = { platform: 'IOS', versionString: want, copyright: attrs.copyright, releaseType: attrs.releaseType };
return { ...base, action: 'create', reason: `create version ${want} (no editable iOS version)`, changes: Object.entries(attributes).map(([field, to]) => ({ field, from: null, to })), attributes };
}
// ---- translation drafts ----
/** Locales (App Store) or Play language codes whose section is a translation draft or still untranslated, with why. */
export function draftSections(md: string, store: 'apple' | 'play'): Map<string, TStatus> {
const out = new Map<string, TStatus>();
for (const sec of sections(md)) {
const m = markerOf(sec);
if (!m) continue;
const keys = store === 'apple' ? [appleLocaleOf(sec)].filter((x): x is string => !!x) : playCodesOf(sec);
for (const k of keys) out.set(k, m.status);
}
return out;
}
export const draftReason = (s: TStatus): string => s === 'draft'
? 'machine-translated draft, not reviewed (storebound listing check, then listing reviewed --lang <id>; or --include-drafts)'
: 'not translated yet (status=translate: still the source text; translate it, or --include-drafts)';
// ---- formatting ----
/** One value for a plan line: quoted, long text cut with its length. */
export function short(v: string | null, max = 60): string {
if (v === null) return '(none)';
const flat = v.replace(/\s*\n\s*/g, ' ⏎ ');
const n = [...v].length;
return [...flat].length > max ? `"${[...flat].slice(0, max).join('')}…" (${n} chars)` : `"${flat}"`;
}
/** Plan lines of one item: a header and one line per changed field; unchanged fields summarized. */
export function itemLines(label: string, p: ItemPlan, indent = ' '): string[] {
if (p.action === 'same') return [`${indent}${label}: unchanged (${p.unchanged.length} field${p.unchanged.length === 1 ? '' : 's'})`];
const head = `${indent}${label}: ${p.action === 'create' ? 'create' : 'update'}${p.unchanged.length ? ` (${p.unchanged.length} unchanged: ${p.unchanged.join(', ')})` : ''}`;
return [head, ...p.changes.map(c => `${indent} ${c.field}: ${p.action === 'create' ? short(c.to) : `${short(c.from)} -> ${short(c.to)}`}`)];
}
export const counts = (items: ItemPlan[]): string => {
const n = (a: ItemPlan['action']) => items.filter(i => i.action === a).length;
return `${n('create')} create, ${n('update')} update, ${n('same')} unchanged`;
};

View file

@ -29,8 +29,9 @@ function setBlock(sec: string, heading: RegExp, newHeading: string, text: string
const APPLE_ORDER: AppleField[] = ['name', 'subtitle', 'promotionalText', 'keywords', 'description', 'whatsNew']; const APPLE_ORDER: AppleField[] = ['name', 'subtitle', 'promotionalText', 'keywords', 'description', 'whatsNew'];
/** Live App Store texts per locale merged into the App Store listing file. Pure. */ /** Live App Store texts per locale merged into the App Store listing file. A name equal to `defaultName` (apple.name,
export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>): MergeResult { * else app.name) is only written where the section already has a name block. Pure. */
export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>, defaultName?: string): MergeResult {
const parts = md.split(/^(?=## )/m); const parts = md.split(/^(?=## )/m);
const res: MergeResult = { md: '', changes: [], added: [], conflicts: [] }; const res: MergeResult = { md: '', changes: [], added: [], conflicts: [] };
const seen = new Set<string>(); const seen = new Set<string>();
@ -43,6 +44,7 @@ export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>)
for (const f of APPLE_ORDER) { for (const f of APPLE_ORDER) {
const v = r[f]; const v = r[f];
if (v === undefined || v === null || v === '') continue; if (v === undefined || v === null || v === '') continue;
if (f === 'name' && v === defaultName && !BLOCK(/name\b/).test(sec)) continue;
const { sec: next, from } = setBlock(sec, new RegExp(`${f}\\b`), f, v); const { sec: next, from } = setBlock(sec, new RegExp(`${f}\\b`), f, v);
if (from !== v.trim()) res.changes.push({ section: loc, field: f, from, to: v }); if (from !== v.trim()) res.changes.push({ section: loc, field: f, from, to: v });
sec = next; sec = next;
@ -52,7 +54,7 @@ export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>)
let text = out.join(''); let text = out.join('');
for (const [loc, r] of Object.entries(remote).sort(([a], [b]) => a.localeCompare(b))) { for (const [loc, r] of Object.entries(remote).sort(([a], [b]) => a.localeCompare(b))) {
if (seen.has(loc)) continue; if (seen.has(loc)) continue;
const fields = APPLE_ORDER.filter(f => r[f]); const fields = APPLE_ORDER.filter(f => r[f] && !(f === 'name' && r[f] === defaultName));
if (!fields.length) continue; if (!fields.length) continue;
res.added.push(loc); res.added.push(loc);
text = text.replace(/\s*$/, '') + `\n\n## ${loc}\n\n` + fields.map(f => `### ${f}\n${fence(r[f]!)}`).join('\n\n') + '\n'; text = text.replace(/\s*$/, '') + `\n\n## ${loc}\n\n` + fields.map(f => `### ${f}\n${fence(r[f]!)}`).join('\n\n') + '\n';

View file

@ -3,7 +3,7 @@
// line, never an exception, so one bad section does not hide the rest ("unknown, never false"). // line, never an exception, so one bad section does not hide the rest ("unknown, never false").
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { extname, isAbsolute, join, resolve } from 'node:path'; import { extname, isAbsolute, join, resolve } from 'node:path';
import { type ShipConfig, playCodes } from './config'; import { appleName, type ShipConfig, playCodes } from './config';
import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy'; import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy';
import type { DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, ListingText, RenderImage, ReplyDraft } from './desktop-protocol'; import type { DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, ListingText, RenderImage, ReplyDraft } from './desktop-protocol';
import { parseFrontMatter, stringifyFrontMatter } from './frontmatter'; import { parseFrontMatter, stringifyFrontMatter } from './frontmatter';
@ -136,7 +136,7 @@ export function listingCompleteness(config: ShipConfig, root: string): ListingsR
const applePart = config.apple ? { const applePart = config.apple ? {
code: ac, code: ac,
fields: tally([ fields: tally([
field('name', as?.name ?? (as ? config.app.name : undefined), APPLE_LIMITS.name, true), field('name', as?.name ?? (as ? appleName(config) : undefined), APPLE_LIMITS.name, true),
field('subtitle', as?.subtitle, APPLE_LIMITS.subtitle, true), field('subtitle', as?.subtitle, APPLE_LIMITS.subtitle, true),
field('promotionalText', as?.promotionalText, APPLE_LIMITS.promotionalText, true), field('promotionalText', as?.promotionalText, APPLE_LIMITS.promotionalText, true),
field('keywords', as?.keywords, APPLE_LIMITS.keywords, true), field('keywords', as?.keywords, APPLE_LIMITS.keywords, true),

View file

@ -333,6 +333,7 @@ export function scanRules(inp: ScanInput): ScanFinding[] {
const BETA = /\b(beta|demo|trial version|test (version|build|app)|testing build|early access|prototype|preview (build|version)|alpha (build|version))\b/i; const BETA = /\b(beta|demo|trial version|test (version|build|app)|testing build|early access|prototype|preview (build|version)|alpha (build|version))\b/i;
const betaName: Hit[] = []; const betaName: Hit[] = [];
if (c?.app?.name && BETA.test(c.app.name)) betaName.push(...cfg(c.app.name, `app.name: ${c.app.name}`)); if (c?.app?.name && BETA.test(c.app.name)) betaName.push(...cfg(c.app.name, `app.name: ${c.app.name}`));
if (c?.apple?.name && c.apple.name !== c.app?.name && BETA.test(c.apple.name)) betaName.push(...cfg(c.apple.name, `apple.name: ${c.apple.name}`));
for (const k of ['CFBundleDisplayName', 'CFBundleName']) { for (const k of ['CFBundleDisplayName', 'CFBundleName']) {
const v = plistVal(k); const v = plistVal(k);
if (typeof v?.value === 'string' && BETA.test(v.value) && !/\$\(/.test(v.value)) betaName.push({ ...v.at, text: `${k}: ${v.value}` }); if (typeof v?.value === 'string' && BETA.test(v.value) && !/\$\(/.test(v.value)) betaName.push({ ...v.at, text: `${k}: ${v.value}` });

25
cli/lib/store-lag.ts Normal file
View file

@ -0,0 +1,25 @@
// Store lists lag right after a create: App Store Connect's /inAppPurchasesV2 (and Play's oneTimeProducts list) can
// leave out a product created a minute ago. A command that walks the store's list then silently skips it. These
// helpers compare the config's product ids with what the store returned, so the gap is said out loud
// (docs/pitfalls.md, "Store lists lag right after create").
import { warn } from './log';
export const LAG_HINT = "the store's list can lag a minute after creating; re-run";
/** Config ids the store's list does not contain, in config order. Pure. */
export function missingFromStore(want: string[], got: Iterable<string>): string[] {
const have = new Set(got);
return [...new Set(want)].filter(id => !have.has(id));
}
/**
* Warns with the missing ids and the lag hint. `fail` sets a non-zero exit code (the command could not do its job for
* them, e.g. a dry-run plan that would skip them). Returns the missing ids.
*/
export function reportMissing(tag: string, what: string, want: string[], got: Iterable<string>, o: { fail: boolean }): string[] {
const missing = missingFromStore(want, got);
if (!missing.length) return missing;
warn(tag, `${missing.length} of ${want.length} ${what} not in the store's list: ${missing.join(', ')} (${LAG_HINT})`);
if (o.fail) process.exitCode = 1;
return missing;
}

View file

@ -150,7 +150,7 @@ export const TOOLS: ToolDef[] = [
props: { since: { type: 'string', description: 'Git tag or ref (default: latest tag)' }, lang: { type: 'string' }, all_languages: { type: 'boolean', default: false } }, props: { since: { type: 'string', description: 'Git tag or ref (default: latest tag)' }, lang: { type: 'string' }, all_languages: { type: 'boolean', default: false } },
args: i => [...opt('since', i.since), ...opt('lang', i.lang), ...flag('all', i.all_languages)] }, args: i => [...opt('since', i.since), ...opt('lang', i.lang), ...flag('all', i.all_languages)] },
{ name: 'play_listing', title: 'Push Play listing text', command: ['play', 'listing'], write: true, network: true, idempotent: true, { name: 'play_listing', title: 'Push Play listing text', command: ['play', 'listing'], write: true, network: true, idempotent: true,
description: 'Google Play app details + title / short / full description per language from the listing file. Not public until the next review / publish.', description: 'Google Play app details + title / short / full description per language from the listing file. dry_run prints the plan (old -> new per field); draft languages are skipped (owner terminal run with --include-drafts). Not public until the next review / publish.',
props: { only }, args: i => opt('only', i.only) }, props: { only }, args: i => opt('only', i.only) },
{ name: 'play_images', title: 'Upload Play graphics', command: ['play', 'images'], write: true, destructive: true, network: true, idempotent: true, { name: 'play_images', title: 'Upload Play graphics', command: ['play', 'images'], write: true, destructive: true, network: true, idempotent: true,
description: 'Replace icon, feature graphic and screenshots per Play language from the renders folder (or an A/B variant folder). Slow (minutes): prefer the terminal with a log for many languages.', description: 'Replace icon, feature graphic and screenshots per Play language from the renders folder (or an A/B variant folder). Slow (minutes): prefer the terminal with a log for many languages.',
@ -181,7 +181,7 @@ export const TOOLS: ToolDef[] = [
{ name: 'apple_iap_review', title: 'IAP review screenshots', command: ['apple', 'iap-review'], write: true, destructive: true, network: true, idempotent: true, { name: 'apple_iap_review', title: 'IAP review screenshots', command: ['apple', 'iap-review'], write: true, destructive: true, network: true, idempotent: true,
description: 'Upload (replace when changed) the App Review screenshot of every in-app purchase. Never submits.' }, description: 'Upload (replace when changed) the App Review screenshot of every in-app purchase. Never submits.' },
{ name: 'apple_listing', title: 'Push App Store version + text', command: ['apple', 'listing'], write: true, network: true, idempotent: true, { name: 'apple_listing', title: 'Push App Store version + text', command: ['apple', 'listing'], write: true, network: true, idempotent: true,
description: 'Create / update the editable version (manual release), attach a build by explicit number, and push name / subtitle / description / keywords / promo / what\'s new per locale.', description: 'Create / update the editable version (manual release), attach a build by explicit number, and push name / subtitle / description / keywords / promo / what\'s new per locale. dry_run prints the plan: version keep / update / create / refuse with the reason, per locale old -> new per field; draft locales are skipped (owner terminal run with --include-drafts).',
props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' }, build: { type: 'string', description: 'Exact build number to attach (use the number you just uploaded, never "latest")' }, only }, props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' }, build: { type: 'string', description: 'Exact build number to attach (use the number you just uploaded, never "latest")' }, only },
required: ['version'], args: i => [...opt('version', i.version), ...opt('build', i.build), ...opt('only', i.only)] }, required: ['version'], args: i => [...opt('version', i.version), ...opt('build', i.build), ...opt('only', i.only)] },
{ name: 'apple_screenshots', title: 'Upload App Store screenshots', command: ['apple', 'screenshots'], write: true, destructive: true, network: true, idempotent: true, { name: 'apple_screenshots', title: 'Upload App Store screenshots', command: ['apple', 'screenshots'], write: true, destructive: true, network: true, idempotent: true,
@ -200,13 +200,18 @@ export const TOOLS: ToolDef[] = [
args: i => ['--phased', String(i.action), ...opt('version', i.version)] }, args: i => ['--phased', String(i.action), ...opt('version', i.version)] },
{ name: 'shots_capture', title: 'Capture raw frames', command: ['shots', 'capture'], write: true, network: false, idempotent: true, { name: 'shots_capture', title: 'Capture raw frames', command: ['shots', 'capture'], write: true, network: false, idempotent: true,
description: 'Raw app or game frames per language into shots.frames from a web build (Playwright), the iOS Simulator (simctl), an Android emulator / device (adb) or a folder check. Local files only; a simulator it boots is shut down again, an emulator is never booted. dry_run lists the plan and the simctl / adb commands.', description: 'Raw app or game frames per language into shots.frames from a web build (Playwright), the iOS Simulator (simctl), an Android emulator / device (adb) or a folder check. Local files only; a simulator it boots is shut down again, an emulator is never booted. dry_run lists the plan and the simctl / adb commands.',
props: { lang, only: { type: 'string', description: 'Comma-separated shot names' }, device: { type: 'string', enum: ['phone', 'tablet'] }, source }, props: { lang, only: { type: 'string', description: 'Comma-separated shot names' }, device: { type: 'string', enum: ['phone', 'tablet'] }, source,
args: i => [...opt('lang', i.lang), ...opt('only', i.only), ...opt('device', i.device), ...opt('source', i.source)] }, concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'Web: parallel browser contexts (default from the CPU count)' },
mode: { type: 'string', enum: ['changed', 'only-missing', 'force'], default: 'changed', description: 'Web: skip frames with unchanged inputs (default), only missing ones, or capture all' } },
args: i => [...opt('lang', i.lang), ...opt('only', i.only), ...opt('device', i.device), ...opt('source', i.source),
...(i.concurrency ? ['--concurrency', String(i.concurrency)] : []), ...(i.mode === 'force' ? ['--force'] : i.mode === 'only-missing' ? ['--only-missing'] : [])] },
{ name: 'shots_render', title: 'Render store screenshots', command: ['shots', 'render'], write: true, network: false, idempotent: true, { 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.', 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, iphone-medium, ipad13, play, tab7, tab10, feature' },
scenes: { type: 'string', description: 'Comma-separated scene ids' }, variant, all_variants: { type: 'boolean', default: false, description: 'Base + every variant' } }, 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))] }, concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'Parallel pages (default min(4, CPU cores / 2))' } },
args: i => [...opt('lang', i.lang), ...opt('size', i.size), ...opt('scenes', i.scenes), ...(i.all_variants === true ? ['--variants'] : opt('variant', i.variant)),
...(i.concurrency ? ['--concurrency', String(i.concurrency)] : [])] },
{ name: 'shots_gallery', title: 'Review gallery', command: ['shots', 'gallery'], write: true, network: false, idempotent: true, { name: 'shots_gallery', title: 'Review gallery', command: ['shots', 'gallery'], write: true, network: false, idempotent: true,
description: 'Write <renders>/index.html: one self-contained page with every language, size, scene, variant and app preview, store check issues highlighted. Open it in a browser to review before uploading.', description: 'Write <renders>/index.html: one self-contained page with every language, size, scene, variant and app preview, store check issues highlighted. Open it in a browser to review before uploading.',
props: { lang }, args: i => opt('lang', i.lang) }, props: { lang }, args: i => opt('lang', i.lang) },

View file

@ -1,7 +1,9 @@
// Play store listing text + app details in one edit. // Play store listing text + app details in one edit.
// storebound play listing [--dry] [--only en-US,de-DE] // storebound play listing [--dry] [--json] [--only en-US,de-DE] [--include-drafts]
// --dry is read-only: a throwaway edit is opened, the current details and listings are read and compared with the file, // Every run first reads Play in a throwaway edit (deleted again) and prints the plan: app details and per language
// and the edit is deleted. Nothing is written, not even into that edit. // create / update with old -> new per field. --dry stops there (nothing is written, not even into that edit); the real
// run asks in a terminal and PUTs only what the plan changes, in one committed edit. Languages whose section is
// status=draft or status=translate (listing translate) are skipped unless --include-drafts.
// App details: default language, contact email, website (must be the domain that serves app-ads.txt). // App details: default language, contact email, website (must be the domain that serves app-ads.txt).
// Listings: title, short and full description of every `<!-- play: ... -->` section of the listing file, plus the promo // Listings: title, short and full description of every `<!-- play: ... -->` section of the listing file, plus the promo
// video (play.video, a YouTube URL) on every language. Play has no video upload: make the video with // video (play.video, a YouTube URL) on every language. Play has no video upload: make the video with
@ -12,8 +14,9 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { parsePlayListing } from '../lib/copy'; import { parsePlayListing } from '../lib/copy';
import { compactDiff } from '../lib/diff'; import { compactDiff } from '../lib/diff';
import { mergePlayListing, overLimits } from '../lib/listing-pull'; import { mergePlayListing, overLimits } from '../lib/listing-pull';
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, type Skipped } from '../lib/listing-plan';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { confirm, need } from '../lib/ctx';
import { done, log, printJson, step, warn } from '../lib/log'; import { done, log, printJson, step, warn } from '../lib/log';
import { playClient } from './client'; import { playClient } from './client';
@ -75,36 +78,77 @@ async function pull(ctx: Ctx): Promise<void> {
done('play', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new languages ${r.added.join(', ')}` : ''}`); done('play', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new languages ${r.added.join(', ')}` : ''}`);
} }
export async function run(ctx: Ctx): Promise<void> { /** The plan of one `play listing` run, from a read-only edit. */
const { config, root } = ctx.loaded; export interface PlayListingPlan { details: ItemPlan; listings: ItemPlan[]; other: string[]; skipped: Skipped[]; notes: string[]; changes: number }
if (ctx.args._[0] === 'pull') return pull(ctx);
const pkg = need(config.play?.packageName, 'play.packageName'); /** Plan from what Play has now. The listing PUT replaces the whole listing: a promo video on Play that play.video leaves
const copy = readPlayCopy(ctx); * out is shown as cleared. Pure. */
const details = { defaultLanguage: config.play?.defaultLanguage ?? 'en-US', contactEmail: config.app.contactEmail, contactWebsite: config.app.website }; export function playPlan(curDetails: Record<string, unknown>, details: Record<string, string | undefined>, now: PlayListing[], bodies: Record<string, string>[],
if (!copy.some(c => c.lang === details.defaultLanguage) && !ctx.args.has('only')) throw new Error(`listing has no section for the default language ${details.defaultLanguage}`); o: { skipped?: Skipped[]; notes?: string[]; only?: boolean } = {}): PlayListingPlan {
log('play', `${copy.length} listings: ${copy.map(c => c.lang).join(', ')}${config.play?.video ? ` · promo video ${config.play.video}` : ''}`); const d = planItem('details', { attributes: curDetails }, details);
const play = await playClient(root, pkg); const byLang = new Map(now.map(l => [l.language, l]));
if (ctx.args.has('dry')) { const listings = bodies.map(b => {
await play.read(async id => { const cur = byLang.get(b.language!);
const cur = await play.call<Record<string, string>>('GET', `${play.API}/edits/${id}/details`); const { language, ...want } = b;
const dc = detailsChanges(cur, details); const w: Record<string, string | undefined> = { ...want, video: want.video ?? (cur?.video ? '' : undefined) };
log('play', `details: ${dc.length ? 'would change ' + dc.join(', ') : 'unchanged'}`); return planItem(language!, cur ? { attributes: cur as unknown as Record<string, unknown> } : null, w);
const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? [];
const changes = listingChanges(now, copy.map(c => listingBody(c, config.play?.video)));
for (const c of changes) log('play', `${c.lang}: ${c.change === 'update' ? 'would update ' + c.fields.join(', ') : c.change === 'new' ? 'would add (new language)' : 'unchanged'}`);
const other = now.filter(l => !copy.some(c => c.lang === l.language)).map(l => l.language);
if (other.length && !ctx.args.has('only')) log('play', `${other.length} languages on Play not in the listing file (left as they are): ${other.join(', ')}`);
const n = changes.filter(c => c.change !== 'same').length + (dc.length ? 1 : 0);
done('play', `dry run: ${n ? n + ' change(s)' : 'nothing to change'}; read-only, nothing written`);
}); });
return; const other = o.only ? [] : now.filter(l => !bodies.some(b => b.language === l.language)).map(l => l.language);
} const changes = (d.action === 'same' ? 0 : 1) + listings.filter(l => l.action !== 'same').length;
return { details: d, listings, other, skipped: o.skipped ?? [], notes: o.notes ?? [], changes };
}
/** The plan as text lines. Pure. */
export function playPlanLines(p: PlayListingPlan): string[] {
const out = [...itemLines('App details (default language, contact email, website)', p.details, '')];
out.push(`Listings: title, short and full description, promo video · ${counts(p.listings)}`);
for (const l of p.listings) out.push(...itemLines(l.key, l));
if (p.other.length) out.push(`Left as they are (on Play, not in the listing file): ${p.other.join(', ')}`);
for (const s of p.skipped) out.push(`Skipped ${s.key}: ${s.reason}`);
for (const n of p.notes) out.push(`Note: ${n}`);
return out;
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
if (a._[0] === 'pull') return pull(ctx);
const pkg = need(config.play?.packageName, 'play.packageName');
const all = readPlayCopy(ctx);
const drafts = draftSections(readFileSync(resolve(config.play?.listing ?? 'store/listing.md'), 'utf8'), 'play');
const skipped: Skipped[] = [], notes: string[] = [];
const copy = all.filter(c => {
const st = drafts.get(c.lang);
if (!st) return true;
if (a.has('include-drafts')) { notes.push(`${c.lang}: ${st === 'draft' ? 'machine-translated draft' : 'untranslated (status=translate)'} included (--include-drafts)`); return true; }
skipped.push({ key: c.lang, reason: draftReason(st) });
return false;
});
const details = { defaultLanguage: config.play?.defaultLanguage ?? 'en-US', contactEmail: config.app.contactEmail, contactWebsite: config.app.website };
if (!all.some(c => c.lang === details.defaultLanguage) && !a.has('only')) throw new Error(`listing has no section for the default language ${details.defaultLanguage}`);
if (!a.has('json')) log('play', `${copy.length} listings: ${copy.map(c => c.lang).join(', ')}${config.play?.video ? ` · promo video ${config.play.video}` : ''}`);
const play = await playClient(root, pkg);
const bodies = copy.map(c => listingBody(c, config.play?.video));
const p = await play.read(async id => {
const cur = await play.call<Record<string, string>>('GET', `${play.API}/edits/${id}/details`);
const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? [];
return playPlan(cur, details, now, bodies, { skipped, notes, only: a.has('only') });
});
const dry = a.has('dry');
if (a.has('json')) printJson({ dry, ...p });
else for (const line of playPlanLines(p)) console.log(line);
if (dry) { done('play', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('play', 'listing already up to date'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to Google Play (one edit, committed)?`))) { warn('play', 'nothing written'); return; }
const todo = p.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
await play.edit(async id => { await play.edit(async id => {
if (p.details.action !== 'same') {
await play.call('PUT', `${play.API}/edits/${id}/details`, details); await play.call('PUT', `${play.API}/edits/${id}/details`, details);
log('play', `details: ${details.defaultLanguage} · ${details.contactEmail} · ${details.contactWebsite}`); log('play', `details: ${p.details.changes.map(ch => ch.field).join(', ')}`);
for (const [i, c] of copy.entries()) { }
await play.call('PUT', `${play.API}/edits/${id}/listings/${c.lang}`, listingBody(c, config.play?.video)); for (const [i, b] of todo.entries()) {
log('play', step(i + 1, copy.length, c.lang)); await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b);
log('play', step(i + 1, todo.length, b.language!));
} }
}); });
done('play', 'listing done'); done('play', 'listing done');

View file

@ -10,10 +10,14 @@
// confirm token. Without one (MCP, CI, serve) those changes are skipped with a warning; listing changes still go. // confirm token. Without one (MCP, CI, serve) those changes are skipped with a warning; listing changes still go.
// Play has no non-renewing type: a `non_renewing` product is a plain one-time product here (your app consumes it // Play has no non-renewing type: a `non_renewing` product is a plain one-time product here (your app consumes it
// when the access ends). Products with `platforms` that leave out android are skipped. // when the access ends). Products with `platforms` that leave out android are skipped.
// --dry ends with the standard plan table (lib/dry.ts). After a real run the product list is read again: a product
// created a moment ago can be missing from it for a minute, and that gap is named (docs/pitfalls.md).
import { playCodes, sellsOn } from '../lib/config'; import { playCodes, sellsOn } from '../lib/config';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx'; import { confirm, need } from '../lib/ctx';
import { dryPlan } from '../lib/dry';
import { done, log, step, warn } from '../lib/log'; import { done, log, step, warn } from '../lib/log';
import { LAG_HINT, reportMissing } from '../lib/store-lag';
import { fromMoney, type Money, playRegionConfigs, type RegionConfig, toMoney } from '../lib/money'; import { fromMoney, type Money, playRegionConfigs, type RegionConfig, toMoney } from '../lib/money';
import { playClient } from './client'; import { playClient } from './client';
@ -116,7 +120,15 @@ export async function run(ctx: Ctx): Promise<void> {
log('play', `${tag}: ${what}${dry ? ' (dry)' : ''}`); log('play', `${tag}: ${what}${dry ? ' (dry)' : ''}`);
plan.push({ p, tag, body, version: conv.regionVersion?.version ?? '2022/02', cur, changes, regions: regions.length, listings: listings.length }); plan.push({ p, tag, body, version: conv.regionVersion?.version ?? '2022/02', cur, changes, regions: regions.length, listings: listings.length });
} }
if (dry) { done('play', 'products checked (dry run, nothing written)'); return; } if (dry) {
console.log(dryPlan('play products', plan.map(x => !x.changes.length ? { item: x.p.id, action: 'keep' }
: !x.cur ? { item: x.p.id, action: 'create', detail: `${x.regions} regions, ${x.listings} listings, USD ${x.p.usd}` }
: { item: x.p.id, action: x.changes.some(c => c.owner) ? 'update (owner confirms)' : 'update', detail: x.changes.map(c => c.text).join('; ') })));
const absent = plan.filter(x => !x.cur).map(x => x.p.id);
if (absent.length) log('play', `not on Google Play: ${absent.join(', ')}. If you created them in the last minutes, ${LAG_HINT} before acting on this plan`);
done('play', 'products checked (dry run, nothing written)');
return;
}
// prices, regions and activation of existing products: the owner confirms the diff above first // prices, regions and activation of existing products: the owner confirms the diff above first
const gated = plan.filter(x => x.cur && x.changes.some(c => c.owner)); const gated = plan.filter(x => x.cur && x.changes.some(c => c.owner));
@ -146,5 +158,7 @@ export async function run(ctx: Ctx): Promise<void> {
log('play', `${x.tag}: purchase option activated`); log('play', `${x.tag}: purchase option activated`);
} catch (e) { warn('play', `${x.tag}: activate failed: ${(e as Error).message}`); } } catch (e) { warn('play', `${x.tag}: activate failed: ${(e as Error).message}`); }
} }
const created = plan.filter(x => !x.cur && x.changes.length).map(x => x.p.id);
if (created.length) reportMissing('play', 'new products', created, (await listOneTimeProducts(play)).map(p => p.productId), { fail: false });
done('play', 'products done'); done('play', 'products done');
} }

231
cli/shots/capture-web.ts Normal file
View file

@ -0,0 +1,231 @@
// Web capture (shots.capture.source "web"), parallel and incremental:
// --concurrency N browser contexts in one headless Chromium (default shots.capture.concurrency, else from the CPU
// count: a WebGL game is GPU-bound, so capture defaults lower than render). Files do not depend on
// the order: every frame has its own path.
// session shots.capture.session "per-shot" (default: a new context + page and a full boot per frame) or
// "per-language": one page per language and device, booted once; the next shots switch scenes in
// that page (navigate "spa": history.pushState + popstate to the shot's path, then waitFor / eval;
// navigate "reload": page.goto in the same page). A precondition that fails there (waitFor times out
// after reuseTimeoutMs) falls back to a fresh page.
// cache .storebound/capture-cache.json: per frame a hash of its inputs (shot entry, URL + query, frame
// size, session, the copy text of its language, the app build (shots.capture.build files, else
// the HTML and scripts at baseUrl), fonts.css). Unchanged frames that exist are skipped;
// --only-missing only captures frames that do not exist; --force captures everything.
// timing per frame: goto, waitFor, eval, delay, screenshot, total, in the progress line and in
// .storebound/capture-report.json, with the slowest frames and steps at the end.
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { availableParallelism, cpus } from 'node:os';
import { join } from 'node:path';
import type { ShotSpec, ShotsCapture } from '../lib/config';
import { log, warn } from '../lib/log';
import { shotsFor } from './devices';
import type { FrameDims } from './lib';
type Device = 'phone' | 'tablet';
export const STEPS = ['goto', 'waitFor', 'eval', 'delay', 'screenshot'] as const;
export type Step = typeof STEPS[number];
export type Timing = Record<Step | 'total', number>;
/** frame = path relative to shots.frames (cache and report key), out = absolute file. */
export interface WebJob { lang: string; device: Device; name: string; spec: ShotSpec; url: string; path: string; out: string; frame: string; hash: string }
/** CPU cores (availableParallelism where Bun has it). */
export const coreCount = (): number => { try { return availableParallelism(); } catch { return cpus().length || 2; } };
/** Default parallel workers: render min(4, cores / 2); capture (GPU-heavy WebGL / game boots) min(3, cores / 4). */
export function defaultConcurrency(kind: 'render' | 'capture', cores = coreCount()): number {
return Math.max(1, kind === 'render' ? Math.min(4, Math.floor(cores / 2)) : Math.min(3, Math.floor(cores / 4)));
}
/** Runs fn over items with at most n at a time; results keep the input order. */
export async function pool<T, R>(items: T[], n: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {
const out = new Array<R>(items.length);
let next = 0;
const worker = async (): Promise<void> => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]!, i); } };
await Promise.all(Array.from({ length: Math.max(1, Math.min(n, items.length)) }, worker));
return out;
}
const fmtS = (ms: number): string => (ms >= 60_000 ? `${Math.floor(ms / 60_000)}m${String(Math.round((ms % 60_000) / 1000)).padStart(2, '0')}s` : `${(ms / 1000).toFixed(1)}s`);
/** "n/total, ETA" progress for parallel work: ETA = remaining items x average wall time per finished item. */
export function progressLine(done: number, total: number, startedMs: number, nowMs = Date.now()): string {
const w = String(total).length;
const eta = done ? ((nowMs - startedMs) / done) * (total - done) : 0;
return `${String(done).padStart(w)}/${total}${done < total && done ? ` ETA ${fmtS(eta)}` : ''}`;
}
export const timingText = (t: Timing): string => `goto ${fmtS(t.goto)} wait ${fmtS(t.waitFor)} eval ${fmtS(t.eval)} delay ${fmtS(t.delay)} shot ${fmtS(t.screenshot)} = ${fmtS(t.total)}`;
/** Slowest frames and the time per step over all frames (for the end of the log and the report). */
export function timingSummary(frames: { frame: string; timing: Timing }[], top = 5): { slowest: { frame: string; total: number; step: Step }[]; steps: Record<Step, number>; total: number } {
const steps = Object.fromEntries(STEPS.map(s => [s, 0])) as Record<Step, number>;
for (const f of frames) for (const s of STEPS) steps[s] += f.timing[s];
const slowest = [...frames].sort((a, b) => b.timing.total - a.timing.total).slice(0, top)
.map(f => ({ frame: f.frame, total: f.timing.total, step: STEPS.reduce((m, s) => (f.timing[s] > f.timing[m] ? s : m), STEPS[0] as Step) }));
return { slowest, steps, total: frames.reduce((t, f) => t + f.timing.total, 0) };
}
const sha = (s: string | Uint8Array): string => createHash('sha256').update(s).digest('hex').slice(0, 16);
/** Content hash of build files (a file or folder; node_modules / dot folders skipped): paths, sizes and mtimes. */
export function hashPaths(paths: string[]): string {
const h = createHash('sha256');
const walk = (p: string): void => {
if (!existsSync(p)) { h.update(`missing:${p}`); return; }
const st = statSync(p);
if (st.isDirectory()) { for (const e of readdirSync(p).sort()) if (e !== 'node_modules' && !e.startsWith('.')) walk(join(p, e)); return; }
h.update(`${p}:${st.size}:${st.mtimeMs}\n`);
};
for (const p of paths) walk(p);
return h.digest('hex').slice(0, 16);
}
/** App build fingerprint from the running server: the HTML at baseUrl and the scripts it loads (dev servers too). */
export async function hashServed(baseUrl: string): Promise<string> {
try {
const html = await (await fetch(baseUrl, { signal: AbortSignal.timeout(10_000) })).text();
const h = createHash('sha256').update(html);
for (const m of html.matchAll(/<script[^>]+src=["']([^"']+)["']/g)) {
try { h.update(await (await fetch(new URL(m[1]!, baseUrl), { signal: AbortSignal.timeout(10_000) })).text()); } catch { h.update(`unreachable:${m[1]}`); }
}
return h.digest('hex').slice(0, 16);
} catch { return 'unreachable'; }
}
/** Every web frame to capture, in a fixed order (lang, device, shot), with its URL and its input hash. */
export function planWeb(cap: ShotsCapture, o: { langs: string[]; devices: Device[]; only: string[]; dims: Record<Device, FrameDims>; framesDir: string;
build: string; copyText?: (lang: string) => string; fonts?: string }): WebJob[] {
const jobs: WebJob[] = [];
for (const lang of o.langs) for (const device of o.devices) for (const [name, spec] of shotsFor(cap, device, o.only)) {
const q = (cap.query ?? '').replaceAll('{lang}', lang);
const path = (spec.path ?? '/').replaceAll('{lang}', lang) + (q ? ((spec.path ?? '/').includes('?') ? '&' : '?') + q : '');
const url = (cap.baseUrl ?? '').replace(/\/$/, '') + path;
const hash = sha(JSON.stringify({ spec, url, dims: o.dims[device], session: cap.session ?? 'per-shot', build: o.build, copy: o.copyText?.(lang) ?? '', fonts: o.fonts ?? '' }));
const frame = `${lang}/${device}/${name}.png`;
jobs.push({ lang, device, name, spec, url, path, out: join(o.framesDir, frame), frame, hash });
}
return jobs;
}
export type Cache = Record<string, string>;
export const cachePath = (root: string): string => join(root, '.storebound', 'capture-cache.json');
export function readCache(root: string): Cache { try { return JSON.parse(readFileSync(cachePath(root), 'utf8')) as Cache; } catch { return {}; } }
/** Which jobs to run: --force all; --only-missing the ones whose file is missing; else missing or changed inputs. */
export function selectJobs(jobs: WebJob[], cache: Cache, mode: 'force' | 'only-missing' | 'changed', exists: (file: string) => boolean = existsSync): { run: WebJob[]; skipped: WebJob[] } {
const run: WebJob[] = [], skipped: WebJob[] = [];
for (const j of jobs) {
const keep = mode === 'force' ? false : mode === 'only-missing' ? exists(j.out) : exists(j.out) && cache[j.frame] === j.hash;
(keep ? skipped : run).push(j);
}
return { run, skipped };
}
export interface CaptureReport {
at: string; concurrency: number; session: string; wallMs: number;
frames: { frame: string; ok: boolean; reused: boolean; timing: Timing; error?: string }[];
skipped: string[];
summary: ReturnType<typeof timingSummary>;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
/** Captures the jobs in a browser: per-shot contexts, or one page per language + device in per-language sessions. */
export async function captureWeb(browser: any, cap: ShotsCapture, jobs: WebJob[], o: { concurrency: number; dims: Record<Device, FrameDims> }): Promise<CaptureReport> {
const started = Date.now();
const perLang = cap.session === 'per-language';
const report: CaptureReport['frames'] = [];
let finished = 0;
const total = jobs.length;
const newPage = async (j: WebJob): Promise<{ c: any; page: any; errs: string[] }> => {
const d = o.dims[j.device];
const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: j.lang });
const page = await c.newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
return { c, page, errs };
};
const shoot = async (s: { page: any; errs: string[] }, j: WebJob, how: 'goto' | 'spa', waitTimeout: number): Promise<Timing> => {
const t: Timing = { goto: 0, waitFor: 0, eval: 0, delay: 0, screenshot: 0, total: 0 };
let t0 = Date.now();
if (how === 'goto') await s.page.goto(j.url, { waitUntil: 'domcontentloaded', timeout: 90000 });
else await s.page.evaluate(`(p => { if (location.pathname + location.search !== p) { history.pushState(null, '', p); dispatchEvent(new PopStateEvent('popstate', { state: null })); } })(${JSON.stringify(j.path)})`);
t.goto = Date.now() - t0; t0 = Date.now();
if (j.spec.waitFor) await s.page.waitForFunction(j.spec.waitFor, null, { timeout: waitTimeout, polling: 50 });
t.waitFor = Date.now() - t0; t0 = Date.now();
for (const js of j.spec.eval ?? []) await s.page.evaluate(js);
t.eval = Date.now() - t0; t0 = Date.now();
await s.page.waitForTimeout(j.spec.delayMs ?? 1000);
t.delay = Date.now() - t0; t0 = Date.now();
mkdirSync(join(j.out, '..'), { recursive: true });
await s.page.screenshot({ path: j.out });
t.screenshot = Date.now() - t0;
t.total = t.goto + t.waitFor + t.eval + t.delay + t.screenshot;
return t;
};
const record = (j: WebJob, r: { ok: boolean; reused: boolean; timing: Timing; error?: string; errs?: string[] }): void => {
finished++;
report.push({ frame: j.frame, ok: r.ok, reused: r.reused, timing: r.timing, ...(r.error ? { error: r.error } : {}) });
const head = `${progressLine(finished, total, started)} ${j.lang}/${j.device}/${j.name}`;
if (r.ok) log('shots', `${head}.png ${r.reused ? '(reused page) ' : ''}${timingText(r.timing)}${r.errs?.length ? ' (page errors: ' + r.errs.join(' | ').slice(0, 200) + ')' : ''}`);
else warn('shots', `${head}: ${r.error}`);
};
const zero = (): Timing => ({ goto: 0, waitFor: 0, eval: 0, delay: 0, screenshot: 0, total: 0 });
if (!perLang) {
await pool(jobs, o.concurrency, async j => {
const s = await newPage(j);
try { const timing = await shoot(s, j, 'goto', 120000); record(j, { ok: true, reused: false, timing, errs: s.errs }); }
catch (e) { record(j, { ok: false, reused: false, timing: zero(), error: (e as Error).message.split('\n')[0]!.slice(0, 300) }); }
await s.c.close();
});
} else {
// one group per language + device, its shots in order on one booted page
const groups = new Map<string, WebJob[]>();
for (const j of jobs) { const k = `${j.lang}/${j.device}`; groups.set(k, [...(groups.get(k) ?? []), j]); }
await pool([...groups.values()], o.concurrency, async group => {
let s: Awaited<ReturnType<typeof newPage>> | null = null;
for (const j of group) {
const nav = j.spec.navigate ?? 'spa';
if (s) {
try {
const timing = await shoot(s, j, nav === 'reload' ? 'goto' : 'spa', cap.reuseTimeoutMs ?? 15000);
record(j, { ok: true, reused: true, timing, errs: s.errs });
continue;
} catch (e) {
warn('shots', `${j.lang}/${j.device}/${j.name}: reused page failed (${(e as Error).message.split('\n')[0]!.slice(0, 120)}), fresh page`);
await s.c.close(); s = null;
}
}
s = await newPage(j);
try { const timing = await shoot(s, j, 'goto', 120000); record(j, { ok: true, reused: false, timing, errs: s.errs }); }
catch (e) { record(j, { ok: false, reused: false, timing: zero(), error: (e as Error).message.split('\n')[0]!.slice(0, 300) }); await s.c.close(); s = null; }
}
if (s) await s.c.close();
});
}
const order = new Map(jobs.map((j, i) => [j.frame, i] as const));
report.sort((a, b) => order.get(a.frame)! - order.get(b.frame)!);
const ok = report.filter(f => f.ok);
return { at: new Date().toISOString(), concurrency: o.concurrency, session: cap.session ?? 'per-shot', wallMs: Date.now() - started, frames: report, skipped: [],
summary: timingSummary(ok.map(f => ({ frame: f.frame, timing: f.timing }))) };
}
/* eslint-enable @typescript-eslint/no-explicit-any */
/** Log lines for the end of a capture: wall time, sum of frame time, slowest frames and steps. */
export function summaryLines(r: CaptureReport): string[] {
const s = r.summary;
const lines = [`${r.frames.filter(f => f.ok).length} frames in ${fmtS(r.wallMs)} wall (${fmtS(s.total)} of frame time, ${r.concurrency} at a time, session ${r.session})`];
if (s.total) lines.push('time per step: ' + STEPS.map(st => `${st} ${fmtS(s.steps[st])} (${Math.round((100 * s.steps[st]) / s.total)} %)`).join(', '));
for (const f of s.slowest) lines.push(`slowest: ${f.frame} ${fmtS(f.total)} (mostly ${f.step})`);
return lines;
}
export function writeCaptureState(root: string, report: CaptureReport, cache: Cache, captured: WebJob[]): void {
mkdirSync(join(root, '.storebound'), { recursive: true });
const okFrames = new Set(report.frames.filter(f => f.ok).map(f => f.frame));
for (const j of captured) if (okFrames.has(j.frame)) cache[j.frame] = j.hash;
writeFileSync(cachePath(root), JSON.stringify(Object.fromEntries(Object.entries(cache).sort()), null, 1) + '\n');
writeFileSync(join(root, '.storebound', 'capture-report.json'), JSON.stringify(report, null, 1) + '\n');
}

View file

@ -1,11 +1,12 @@
// Raw frames from a running build of your app or game, from any engine. // Raw frames from a running build of your app or game, from any engine.
// storebound shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet] [--source web|ios-sim|android-emu|folder] // storebound shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet] [--source web|ios-sim|android-emu|folder]
// [--dry] [--keep-booted] // [--dry] [--keep-booted] [--concurrency N] [--only-missing | --force]
// Frames go to <shots.frames>/<lang>/<device>/<name>.png: the screen BELOW the status bar (the template draws one). // Frames go to <shots.frames>/<lang>/<device>/<name>.png: the screen BELOW the status bar (the template draws one).
// shots.capture.source (default web): // shots.capture.source (default web):
// web headless Chromium (playwright), mobile viewport + touch at phone / tablet size. Each shot: // web headless Chromium (playwright), mobile viewport + touch at phone / tablet size. Each shot:
// { path, waitFor?: JS expression that turns true, eval?: [JS], delayMs?, device? }; URL = baseUrl + path + // { path, waitFor?: JS expression that turns true, eval?: [JS], delayMs?, device? }; URL = baseUrl + path +
// query, "{lang}" replaced. // query, "{lang}" replaced. Parallel contexts, per-language page reuse, the input-hash cache and the
// per-frame timing (goto / waitFor / eval / delay / screenshot): capture-web.ts.
// ios-sim xcrun simctl: boots the simulator (ios.device / ios.devices.tablet), optional install of ios.app, status // ios-sim xcrun simctl: boots the simulator (ios.device / ios.devices.tablet), optional install of ios.app, status
// bar 9:41 / full battery / full bars, one warm-up launch after a cold boot (ios.warmupMs), then per shot: // bar 9:41 / full battery / full bars, one warm-up launch after a cold boot (ios.warmupMs), then per shot:
// launch ios.bundleId with -AppleLanguages (xx) -AppleLocale + ios.args + shot.args, open shot.url // launch ios.bundleId with -AppleLanguages (xx) -AppleLocale + ios.args + shot.args, open shot.url
@ -33,7 +34,8 @@ import { checkFrameFolder } from './check';
import { adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, adbInstallArgs, adbScreencapArgs, adbStartArgs, adbStateArgs, adbTarget, import { adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, adbInstallArgs, adbScreencapArgs, adbStartArgs, adbStateArgs, adbTarget,
cropArgs, cropTopFor, fill, pickSimulator, shotsFor, simBootArgs, simBootStatusArgs, simInstallArgs, simLaunchArgs, simOpenUrlArgs, cropArgs, cropTopFor, fill, pickSimulator, shotsFor, simBootArgs, simBootStatusArgs, simInstallArgs, simLaunchArgs, simOpenUrlArgs,
simScreenshotArgs, simShutdownArgs, simStatusBarArgs, simStatusBarClearArgs, simTarget, SOURCES, type Source, TOOL_HINTS, validateCapture } from './devices'; simScreenshotArgs, simShutdownArgs, simStatusBarArgs, simStatusBarClearArgs, simTarget, SOURCES, type Source, TOOL_HINTS, validateCapture } from './devices';
import { type FrameDims, frameDims } from './lib'; import { type CopyFile, copyText, type FrameDims, frameDims } from './lib';
import { captureWeb, defaultConcurrency, hashPaths, hashServed, planWeb, readCache, selectJobs, summaryLines, writeCaptureState } from './capture-web';
import { imageInfo } from './spec'; import { imageInfo } from './spec';
type Device = 'phone' | 'tablet'; type Device = 'phone' | 'tablet';
@ -120,29 +122,29 @@ export async function run(ctx: Ctx): Promise<void> {
for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) progress(`${lang}/${device}/${name}.png <- ${cap.baseUrl}${(s.path ?? '/').replaceAll('{lang}', lang)}`); for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) progress(`${lang}/${device}/${name}.png <- ${cap.baseUrl}${(s.path ?? '/').replaceAll('{lang}', lang)}`);
return done('shots', `capture planned (dry run): ${total} frames from web`); return done('shots', `capture planned (dry run): ${total} frames from web`);
} }
need(cap.baseUrl, 'shots.capture.baseUrl');
const concurrency = a.num('concurrency', cap.concurrency ?? defaultConcurrency('capture'));
const builds = cap.build ? (Array.isArray(cap.build) ? cap.build : [cap.build]).map(p => resolve(p)) : [];
const build = builds.length ? hashPaths(builds) : await hashServed(cap.baseUrl!);
let copy: CopyFile = {};
try { copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile; } catch { /* no copy yet */ }
const fontsCss = join(root, '.storebound', 'fonts', 'fonts.css');
const jobs = planWeb(cap, { langs, devices, only, dims, framesDir, build, copyText: l => copyText(l, copy[l]),
fonts: existsSync(fontsCss) ? readFileSync(fontsCss, 'utf8') : '' });
const cache = readCache(root);
const { run: todo, skipped } = selectJobs(jobs, cache, a.has('force') ? 'force' : a.has('only-missing') ? 'only-missing' : 'changed');
if (skipped.length) log('shots', `${skipped.length} of ${jobs.length} frames unchanged, skipped (${a.has('only-missing') ? '--only-missing' : 'same inputs as last time'}; --force captures them again)`);
log('shots', `capturing ${todo.length} frames, ${Math.min(concurrency, todo.length) || 0} at a time${cap.session === 'per-language' ? ', one page per language' : ''}`);
if (todo.length) {
const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] }); const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] });
try { let report;
for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) { try { report = await captureWeb(browser, cap, todo, { concurrency, dims }); } finally { await browser.close(); }
const d = dims[device]; report.skipped = skipped.map(j => j.frame);
const q = (cap.query ?? '').replaceAll('{lang}', lang); writeCaptureState(root, report, cache, todo);
const path = (s.path ?? '/').replaceAll('{lang}', lang); for (const l of summaryLines(report)) log('shots', l);
const url = need(cap.baseUrl, 'shots.capture.baseUrl').replace(/\/$/, '') + path + (q ? (path.includes('?') ? '&' : '?') + q : ''); n += report.frames.filter(f => f.ok).length;
const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: lang }); failed += report.frames.filter(f => !f.ok).length;
const page = await c.newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 90000 });
if (s.waitFor) await page.waitForFunction(s.waitFor, null, { timeout: 120000, polling: 50 });
for (const js of s.eval ?? []) await page.evaluate(js);
await page.waitForTimeout(s.delayMs ?? 1000);
await page.screenshot({ path: target(lang, device, name) });
n++;
progress(`${lang}/${device}/${name}.png${errs.length ? ' (page errors: ' + errs.join(' | ').slice(0, 200) + ')' : ''}`);
} catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); }
await c.close();
} }
} finally { await browser.close(); }
} }
if (source === 'ios-sim') { if (source === 'ios-sim') {

View file

@ -28,10 +28,14 @@ export function validateCapture(c: ShotsCapture | undefined): string[] {
if (!c.ios?.device && !c.ios?.devices?.phone) e.push('shots.capture.ios.device: simulator name or UDID, e.g. "iPhone 17 Pro Max"'); if (!c.ios?.device && !c.ios?.devices?.phone) e.push('shots.capture.ios.device: simulator name or UDID, e.g. "iPhone 17 Pro Max"');
} }
if (c.ios?.warmupMs !== undefined && !(Number.isInteger(c.ios.warmupMs) && c.ios.warmupMs >= 0)) e.push('shots.capture.ios.warmupMs: milliseconds (integer >= 0)'); if (c.ios?.warmupMs !== undefined && !(Number.isInteger(c.ios.warmupMs) && c.ios.warmupMs >= 0)) e.push('shots.capture.ios.warmupMs: milliseconds (integer >= 0)');
if (c.concurrency !== undefined && !(Number.isInteger(c.concurrency) && c.concurrency >= 1 && c.concurrency <= 32)) e.push('shots.capture.concurrency: integer 1-32');
if (c.session !== undefined && !['per-shot', 'per-language'].includes(c.session)) e.push('shots.capture.session: per-shot | per-language');
if (c.reuseTimeoutMs !== undefined && !(Number.isInteger(c.reuseTimeoutMs) && c.reuseTimeoutMs > 0)) e.push('shots.capture.reuseTimeoutMs: milliseconds (integer > 0)');
if (src === 'android-emu' && !c.android?.package) e.push('shots.capture.android.package: application id (source android-emu)'); if (src === 'android-emu' && !c.android?.package) e.push('shots.capture.android.package: application id (source android-emu)');
if (src !== 'folder' && (!c.shots || !Object.keys(c.shots).length)) e.push('shots.capture.shots: at least one shot'); if (src !== 'folder' && (!c.shots || !Object.keys(c.shots).length)) e.push('shots.capture.shots: at least one shot');
for (const [name, s] of Object.entries(c.shots ?? {})) { for (const [name, s] of Object.entries(c.shots ?? {})) {
if (!/^[A-Za-z0-9._-]+$/.test(name)) e.push(`shots.capture.shots.${name}: name must be a file name (letters, digits, . _ -)`); if (!/^[A-Za-z0-9._-]+$/.test(name)) e.push(`shots.capture.shots.${name}: name must be a file name (letters, digits, . _ -)`);
if (s.navigate && !['spa', 'reload'].includes(s.navigate)) e.push(`shots.capture.shots.${name}.navigate: spa | reload`);
if (s.device && !['phone', 'tablet', 'both'].includes(s.device)) e.push(`shots.capture.shots.${name}.device: phone | tablet | both`); if (s.device && !['phone', 'tablet', 'both'].includes(s.device)) e.push(`shots.capture.shots.${name}.device: phone | tablet | both`);
if (src === 'web' && s.path === undefined) e.push(`shots.capture.shots.${name}.path: URL path (source web)`); if (src === 'web' && s.path === undefined) e.push(`shots.capture.shots.${name}.path: URL path (source web)`);
if ((src === 'web' || src === 'folder') && (s.args || s.extras)) e.push(`shots.capture.shots.${name}: args / extras only apply to ios-sim / android-emu`); if ((src === 'web' || src === 'folder') && (s.args || s.extras)) e.push(`shots.capture.shots.${name}: args / extras only apply to ios-sim / android-emu`);

View file

@ -1,6 +1,6 @@
// Store screenshots + Play feature graphic at exact pixel sizes, from raw app or game frames and per-language copy. // Store screenshots + Play feature graphic at exact pixel sizes, from raw app or game frames and per-language copy.
// storebound shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--variant b | --variants] // storebound shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--variant b | --variants]
// [--no-sheet] [--port 8792] [--dry] // [--no-sheet] [--port 8792] [--concurrency N] [--dry]
// Out: <shots.out>/<lang>/<size>/NN.png (24-bit RGB: Play rejects alpha / palette PNGs), <lang>/feature/1024x500.png, // Out: <shots.out>/<lang>/<size>/NN.png (24-bit RGB: Play rejects alpha / palette PNGs), <lang>/feature/1024x500.png,
// <lang>/sheet.png (contact sheet of every size packed into a grid, for a quick review) and <shots.out>/report.json (text overflow flags // <lang>/sheet.png (contact sheet of every size packed into a grid, for a quick review) and <shots.out>/report.json (text overflow flags
// per image, read by `shots check` and `shots gallery`). Variants go to <shots.out>/<variant>/<lang>/... // per image, read by `shots check` and `shots gallery`). Variants go to <shots.out>/<variant>/<lang>/...
@ -16,11 +16,11 @@ import { fontCodepoints } from './cmap';
import { readManifest } from './fonts'; import { readManifest } from './fonts';
import { type FontManifest, fontUsage, measureFonts, roleTexts, uncoveredChars } from './glyphs'; import { type FontManifest, fontUsage, measureFonts, roleTexts, uncoveredChars } from './glyphs';
import { join, relative } from 'node:path'; import { join, relative } from 'node:path';
import { spawnSync } from 'node:child_process';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log'; import { done, log, warn } from '../lib/log';
import { launch } from './browser'; import { launch } from './browser';
import { defaultConcurrency, pool, progressLine } from './capture-web';
import { shotsStyle } from '../lib/config'; import { shotsStyle } from '../lib/config';
import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, shotFonts, validateCopy, variantScenes } from './lib'; import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, shotFonts, validateCopy, variantScenes } from './lib';
import { type RenderReport, mergeReport, readReport } from './report'; import { type RenderReport, mergeReport, readReport } from './report';
@ -132,14 +132,24 @@ export async function run(ctx: Ctx): Promise<void> {
}); });
const base = `http://127.0.0.1:${server.port}`; const base = `http://127.0.0.1:${server.port}`;
const browser = await launch(root, { headless: true }); const browser = await launch(root, { headless: true });
const page = await (await browser.newContext({ deviceScaleFactor: 1 })).newPage(); const concurrency = a.num('concurrency', defaultConcurrency('render'));
// one page per worker, each with its own error list
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const pages: { page: any; errs: string[] }[] = [];
const pageFor = async (k: number): Promise<{ page: any; errs: string[] }> => { // eslint-disable-line @typescript-eslint/no-explicit-any
if (pages[k]) return pages[k]!;
const page = await (await browser.newContext({ deviceScaleFactor: 1 })).newPage(); // own context: no background-tab throttling
const errs: string[] = []; const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message)); page.on('pageerror', (e: Error) => errs.push(e.message));
page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); }); page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); });
let warnings = 0; return (pages[k] = { page, errs });
};
let warnings = 0, finished = 0, total = 0;
const started = Date.now();
const report: RenderReport = {}; const report: RenderReport = {};
async function shoot(url: string, w: number, h: number, out: string): Promise<void> { async function shoot(p: { page: any; errs: string[] }, url: string, w: number, h: number, out: string): Promise<void> { // eslint-disable-line @typescript-eslint/no-explicit-any
const { page, errs } = p;
errs.length = 0; errs.length = 0;
mkdirSync(join(out, '..'), { recursive: true }); mkdirSync(join(out, '..'), { recursive: true });
await page.setViewportSize({ width: w, height: h }); await page.setViewportSize({ width: w, height: h });
@ -157,14 +167,18 @@ export async function run(ctx: Ctx): Promise<void> {
} }
if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`); if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`);
await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } }); await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } });
const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]); const ff = Bun.spawn(['ffmpeg', '-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out], { stderr: 'pipe' });
const code = await ff.exited;
rmSync(tmp, { force: true }); rmSync(tmp, { force: true });
if (r.status !== 0) throw new Error('ffmpeg: ' + r.stderr); if (code !== 0) throw new Error('ffmpeg: ' + await new Response(ff.stderr).text());
if (errs.length) warnings++; if (errs.length) warnings++;
log('shots', `${errs.length ? 'WARN ' : ''}${relative(root, out)}${errs.length ? ' ' + errs.join(' | ') : ''}`); finished++;
log('shots', `${progressLine(finished, total, started)} ${errs.length ? 'WARN ' : ''}${relative(root, out)}${errs.length ? ' ' + errs.join(' | ') : ''}`);
} }
try { // every image first (in parallel), then one contact sheet per language from its finished images
const items: { url: string; w: number; h: number; out: string }[] = [];
const sheets: { dir: string; rows: { size: string; files: string[] }[] }[] = [];
for (const [v, job] of jobs) for (const lang of langs) { for (const [v, job] of jobs) for (const lang of langs) {
const sceneIds = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id); const sceneIds = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id);
const vq = v ? `&v=${encodeURIComponent(v)}` : ''; const vq = v ? `&v=${encodeURIComponent(v)}` : '';
@ -174,30 +188,42 @@ export async function run(ctx: Ctx): Promise<void> {
const s = SIZES[size]!; const s = SIZES[size]!;
if (s.feature) { if (s.feature) {
const f = join(dir, 'feature', '1024x500.png'); const f = join(dir, 'feature', '1024x500.png');
await shoot(`${base}/${style === 'app' ? 'feature-app' : 'feature'}.html?lang=${encodeURIComponent(lang)}${vq}`, s.w, s.h, f); items.push({ url: `${base}/${style === 'app' ? 'feature-app' : 'feature'}.html?lang=${encodeURIComponent(lang)}${vq}`, w: s.w, h: s.h, out: f });
rows.push({ size, files: [f] }); rows.push({ size, files: [f] });
continue; continue;
} }
const files: string[] = []; const files: string[] = [];
for (const [i, id] of sceneIds.entries()) { for (const [i, id] of sceneIds.entries()) {
const f = join(dir, size, `${String(i + 1).padStart(2, '0')}.png`); const f = join(dir, size, `${String(i + 1).padStart(2, '0')}.png`);
await shoot(`${base}/${style === 'app' ? 'template-app' : 'template'}.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}${size === 'tab7' || size === 'tab10' ? '&style=android' : ''}${vq}`, s.w, s.h, f); items.push({ url: `${base}/${style === 'app' ? 'template-app' : 'template'}.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}${size === 'tab7' || size === 'tab10' ? '&style=android' : ''}${vq}`, w: s.w, h: s.h, out: f });
files.push(f); files.push(f);
} }
rows.push({ size, files }); rows.push({ size, files });
} }
if (!a.has('no-sheet') && rows.length) { if (!a.has('no-sheet') && rows.length) sheets.push({ dir, rows });
}
total = items.length + sheets.length;
log('shots', `rendering ${items.length} images${sheets.length ? ` + ${sheets.length} contact sheets` : ''}, ${Math.min(concurrency, items.length)} at a time (--concurrency)`);
try {
const slot = new Map<number, number>();
let nextSlot = 0;
const withPage = async (fn: (p: { page: any; errs: string[] }) => Promise<void>): Promise<void> => { // eslint-disable-line @typescript-eslint/no-explicit-any
const free = [...Array(concurrency).keys()].find(k => !slot.has(k)) ?? nextSlot++ % concurrency;
slot.set(free, 1);
try { await fn(await pageFor(free)); } finally { slot.delete(free); }
};
await pool(items, concurrency, it => withPage(p => shoot(p, it.url, it.w, it.h, it.out)));
await pool(sheets, concurrency, async ({ dir, rows }) => {
const lay = sheetLayout(rows); const lay = sheetLayout(rows);
const imgs = lay.tiles.map(t => `<img src="/out/${relative(outDir, t.file)}" style="position:absolute;left:${t.x}px;top:${t.y}px;width:${t.w}px;height:${t.h}px;border-radius:14px">`).join(''); const imgs = lay.tiles.map(t => `<img src="/out/${relative(outDir, t.file)}" style="position:absolute;left:${t.x}px;top:${t.y}px;width:${t.w}px;height:${t.h}px;border-radius:14px">`).join('');
const W = lay.w, y = lay.h;
const sheet = join(dir, '.sheet.html'); const sheet = join(dir, '.sheet.html');
await Bun.write(sheet, `<!doctype html><body style="margin:0;background:#141418;width:${W}px;height:${y}px;position:relative">${imgs} await Bun.write(sheet, `<!doctype html><body style="margin:0;background:#141418;width:${lay.w}px;height:${lay.h}px;position:relative">${imgs}
<script>Promise.all([...document.images].map(i=>i.decode())).then(()=>document.body.dataset.ready='1')</script></body>`); <script>Promise.all([...document.images].map(i=>i.decode())).then(()=>document.body.dataset.ready='1')</script></body>`);
await shoot(`${base}/out/${relative(outDir, sheet)}`, W, y, join(dir, 'sheet.png')); await withPage(p => shoot(p, `${base}/out/${relative(outDir, sheet)}`, lay.w, lay.h, join(dir, 'sheet.png')));
rmSync(sheet, { force: true }); rmSync(sheet, { force: true });
} });
}
} finally { } finally {
for (const p of pages) await p?.page.context().close().catch(() => {});
await browser.close(); await browser.close();
server.stop(true); server.stop(true);
if (Object.keys(report).length) await Bun.write(join(outDir, 'report.json'), JSON.stringify(mergeReport(readReport(outDir), report), null, 1) + '\n'); if (Object.keys(report).length) await Bun.write(join(outDir, 'report.json'), JSON.stringify(mergeReport(readReport(outDir), report), null, 1) + '\n');

View file

@ -2,13 +2,16 @@
These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal). These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review), 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, 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 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 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. 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 2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run (the rows that
for real only after the owner agrees. change, not just a count), then run it for real only after the owner agrees.
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check` 3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it. (offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile** 4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**

View file

@ -12,7 +12,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| API | operations | GET | other | wrapped by a command | owner only | | API | operations | GET | other | wrapped by a command | owner only |
|---|---:|---:|---:|---:|---:| |---|---:|---:|---:|---:|---:|
| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 195 | 166 | | App Store Connect API 4.5.1 | 1303 | 826 | 477 | 196 | 166 |
| Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 32 | 49 | | Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 32 | 49 |
| Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 | | Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 |
@ -236,11 +236,11 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `appInfoLocalizations_getInstance` | GET | `/v1/appInfoLocalizations/{id}` | read | | | `appInfoLocalizations_getInstance` | GET | `/v1/appInfoLocalizations/{id}` | read | |
| `appInfoLocalizations_updateInstance` | PATCH | `/v1/appInfoLocalizations/{id}` | write (dry by default) | | | `appInfoLocalizations_updateInstance` | PATCH | `/v1/appInfoLocalizations/{id}` | write (dry by default) | |
| **appInfos** (20) | | | | | | **appInfos** (20) | | | | |
| `appInfos_ageRatingDeclaration_getToOneRelated` | GET | `/v1/appInfos/{id}/ageRatingDeclaration` | read | validate | | `appInfos_ageRatingDeclaration_getToOneRelated` | GET | `/v1/appInfos/{id}/ageRatingDeclaration` | read | apple/appinfo, validate |
| `appInfos_ageRatingDeclaration_getToOneRelationship` | GET | `/v1/appInfos/{id}/relationships/ageRatingDeclaration` | read | | | `appInfos_ageRatingDeclaration_getToOneRelationship` | GET | `/v1/appInfos/{id}/relationships/ageRatingDeclaration` | read | |
| `appInfos_appInfoLocalizations_getToManyRelated` | GET | `/v1/appInfos/{id}/appInfoLocalizations` | read | apple/listing, validate | | `appInfos_appInfoLocalizations_getToManyRelated` | GET | `/v1/appInfos/{id}/appInfoLocalizations` | read | apple/listing, validate |
| `appInfos_appInfoLocalizations_getToManyRelationship` | GET | `/v1/appInfos/{id}/relationships/appInfoLocalizations` | read | | | `appInfos_appInfoLocalizations_getToManyRelationship` | GET | `/v1/appInfos/{id}/relationships/appInfoLocalizations` | read | |
| `appInfos_getInstance` | GET | `/v1/appInfos/{id}` | read | | | `appInfos_getInstance` | GET | `/v1/appInfos/{id}` | read | apple/appinfo |
| `appInfos_primaryCategory_getToOneRelated` | GET | `/v1/appInfos/{id}/primaryCategory` | read | | | `appInfos_primaryCategory_getToOneRelated` | GET | `/v1/appInfos/{id}/primaryCategory` | read | |
| `appInfos_primaryCategory_getToOneRelationship` | GET | `/v1/appInfos/{id}/relationships/primaryCategory` | read | | | `appInfos_primaryCategory_getToOneRelationship` | GET | `/v1/appInfos/{id}/relationships/primaryCategory` | read | |
| `appInfos_primarySubcategoryOne_getToOneRelated` | GET | `/v1/appInfos/{id}/primarySubcategoryOne` | read | | | `appInfos_primarySubcategoryOne_getToOneRelated` | GET | `/v1/appInfos/{id}/primarySubcategoryOne` | read | |
@ -377,7 +377,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `appStoreVersions_appStoreVersionPhasedRelease_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionPhasedRelease` | read | | | `appStoreVersions_appStoreVersionPhasedRelease_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionPhasedRelease` | read | |
| `appStoreVersions_appStoreVersionSubmission_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionSubmission` | read | | | `appStoreVersions_appStoreVersionSubmission_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionSubmission` | read | |
| `appStoreVersions_appStoreVersionSubmission_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionSubmission` | read | | | `appStoreVersions_appStoreVersionSubmission_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionSubmission` | read | |
| `appStoreVersions_build_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/build` | read | validate | | `appStoreVersions_build_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/build` | read | apple/listing, validate |
| `appStoreVersions_build_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/build` | read | | | `appStoreVersions_build_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/build` | read | |
| `appStoreVersions_build_updateToOneRelationship` | PATCH | `/v1/appStoreVersions/{id}/relationships/build` | write (dry by default) | apple/listing | | `appStoreVersions_build_updateToOneRelationship` | PATCH | `/v1/appStoreVersions/{id}/relationships/build` | write (dry by default) | apple/listing |
| `appStoreVersions_createInstance` | POST | `/v1/appStoreVersions` | write (dry by default) | apple/listing | | `appStoreVersions_createInstance` | POST | `/v1/appStoreVersions` | write (dry by default) | apple/listing |
@ -459,7 +459,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `apps_gameCenterEnabledVersions_getToManyRelated` | GET | `/v1/apps/{id}/gameCenterEnabledVersions` | read | | | `apps_gameCenterEnabledVersions_getToManyRelated` | GET | `/v1/apps/{id}/gameCenterEnabledVersions` | read | |
| `apps_gameCenterEnabledVersions_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/gameCenterEnabledVersions` | read | | | `apps_gameCenterEnabledVersions_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/gameCenterEnabledVersions` | read | |
| `apps_getCollection` | GET | `/v1/apps` | read | apple/asc, apple/bundle, apps, lib/store-apps | | `apps_getCollection` | GET | `/v1/apps` | read | apple/asc, apple/bundle, apps, lib/store-apps |
| `apps_getInstance` | GET | `/v1/apps/{id}` | read | apple/status | | `apps_getInstance` | GET | `/v1/apps/{id}` | read | apple/appinfo, apple/status |
| `apps_inAppPurchasesV2_getToManyRelated` | GET | `/v1/apps/{id}/inAppPurchasesV2` | read | apple/iap, apple/iap-review, apple/iap-submit, apple/offer-codes, apple/promoted, apple/status, catalog, prices, validate | | `apps_inAppPurchasesV2_getToManyRelated` | GET | `/v1/apps/{id}/inAppPurchasesV2` | read | apple/iap, apple/iap-review, apple/iap-submit, apple/offer-codes, apple/promoted, apple/status, catalog, prices, validate |
| `apps_inAppPurchasesV2_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/inAppPurchasesV2` | read | | | `apps_inAppPurchasesV2_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/inAppPurchasesV2` | read | |
| `apps_inAppPurchases_getToManyRelated` | GET | `/v1/apps/{id}/inAppPurchases` | read | | | `apps_inAppPurchases_getToManyRelated` | GET | `/v1/apps/{id}/inAppPurchases` | read | |

27
docs/pitfalls.md Normal file
View file

@ -0,0 +1,27 @@
# Pitfalls: lessons from real use
A changelog of mistakes found while shipping real apps and games with storebound, newest first. Each entry says what
went wrong, why, and what now guards it. The agent-facing short version is `skills/store-pitfalls/SKILL.md`; keep the
two in step.
Rule (CONTRIBUTING.md): every bug found in real use adds an entry here and, where possible, a check or a test that
fails without the fix.
| # | date | lesson | guard |
|---|---|---|---|
| 8 | 2026-10 | Capacitor plugins in a monorepo live in `apps/native/node_modules`, so `scan` missed them. | `scan` / `privacy-manifest` resolve workspace packages (`cli/lib/scan/project.ts`, `cli/lib/node-packages.ts`). |
| 7 | 2026-10 | Console UIs: the App Store Connect sign-in runs in an `idmsa.apple.com` iframe; "User Access" is a plain heading, not a labeled group; Chrome drops session cookies without `--restore-last-session`. | `console` session and fill (`cli/console/`), `tests/console-*.test.ts`. |
| 6 | 2026-10 | Screenshot fonts: only part of the glyphs a language needs were available, so Turkish / Polish / Vietnamese characters fell back to another font silently. | `shots fonts` / `shots check` check every language's characters against the fonts (`tests/glyphs.test.ts`). |
| 5 | 2026-10 | Account features do not imply email collection; Data safety said "email collected" without evidence. | `scan` marks email only with code evidence, else "ask owner" (`cli/lib/scan/declare.ts`). |
| 4 | 2026-10 | The App Store keyword limit (100) counts UTF-8 bytes, not characters. | `check` counts bytes (`cli/lib/copy.ts`). |
| 3 | 2026-10 | App Store app names are unique per storefront: "already being used" although the developer owns no such app. | `apple.name` (App Store name with a suffix the owner picks); `app.name` stays the brand. |
| 2 | 2026-10 | Dry runs that print no plan ("listing: 20 locales") break "show the dry run to the owner". | `cli/lib/dry.ts` `dryPlan(title, rows)`; `tests/pitfalls.test.ts` scans `cli/**` for `--dry` branches that print only a count (allowlist with TODOs for commands being fixed). |
| 1 | 2026-10 | App Store Connect's `/inAppPurchasesV2` list lags right after `apple iap` creates a product; `apple iap-review` then skipped it silently. | `apple iap-review` names config products missing from the store's list and exits 1; `apple iap` and `play products` re-read the list after creating and warn (`cli/lib/store-lag.ts`, `tests/pitfalls.test.ts`). |
## Adding an entry
1. A row above (next number, month, one-sentence lesson, the guard with file or test names).
2. A section in `skills/store-pitfalls/SKILL.md`: symptom → cause → what to do → which command guards it. Then
`bun tools/gen-adapters.ts`.
3. Where the code can know it: a check (`check`, `validate`, `scan`, a warning in the command) and a test with
recorded store answers that fails without the fix.

View file

@ -20,6 +20,11 @@ of a first version is the owner's click. Shared agent rules: `docs/agents-core.m
Key ID and Issuer ID. The same key signs builds (`-allowProvisioningUpdates`). Key ID and Issuer ID. The same key signs builds (`-allowProvisioningUpdates`).
2. **API · Bundle id.** `storebound apple bundle` registers it (Certificates, Identifiers & Profiles). 2. **API · Bundle id.** `storebound apple bundle` registers it (Certificates, Identifiers & Profiles).
3. **UI · App record.** Apps > + > New App: iOS, name, primary language, the bundle id, SKU. **No API for this.** 3. **UI · App record.** Apps > + > New App: iOS, name, primary language, the bundle id, SKU. **No API for this.**
The name is unique on the App Store: when App Store Connect says it is "already being used", ask the owner for a
longer App Store name (30 characters at most, e.g. "STAR DASH: Stone Age to 2100"), set it as `apple.name` and
fill again (`storebound console fill apple-app-record`). `app.name` stays the Play and on-device name; `apple
listing` sends `apple.name` for every locale without its own `### name` block, and `storebound check` flags a name
over 30 characters.
Then `storebound apple status` finds it (put the Apple ID in `apple.appId` to skip the lookup). Then `storebound apple status` finds it (put the Apple ID in `apple.appId` to skip the lookup).
4. **Local · Info.plist.** `ITSAppUsesNonExemptEncryption` with the true answer (`export-compliance` skill; `NO` only 4. **Local · Info.plist.** `ITSAppUsesNonExemptEncryption` with the true answer (`export-compliance` skill; `NO` only
when the app uses nothing beyond OS / HTTPS encryption) so builds arrive answered; when the app uses nothing beyond OS / HTTPS encryption) so builds arrive answered;
@ -41,11 +46,15 @@ of a first version is the owner's click. Shared agent rules: `docs/agents-core.m
Test, Test Information and Beta App Review: the testflight skill. Sandbox testers stay UI: Users and Access > Sandbox. Test, Test Information and Beta App Review: the testflight skill. Sandbox testers stay UI: Users and Access > Sandbox.
7. **API · Version + text.** Fill `store/appstore.md`, then `storebound apple listing --version 1.0.0 --build 3` 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, (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 description / keywords / promo / URLs). Run it with `--dry` first and show the owner the plan: the version decision
(keep, update the editable version's string, create, or refuse with the reason), the build, and per locale create /
update with old -> new per field. Locales still marked `status=draft` / `status=translate` are skipped until
`listing reviewed` (`--include-drafts` only when the owner says so). The real run asks in a terminal and applies
exactly that plan. Then `storebound apple release --phased on`: manual release + phased
release is the default for every version (`release-management`). release is the default for every version (`release-management`).
8. **API · Screenshots.** `store-screenshots` skill, then 8. **API · Screenshots.** `store-screenshots` skill, then
`storebound apple screenshots > .storebound/asc-shots.log 2>&1 &` (6.9" + 6.5" per locale, MD5-idempotent). `storebound apple screenshots > .storebound/asc-shots.log 2>&1 &` (6.9" + 6.5" per locale, MD5-idempotent).
9. **API · App info.** `storebound apple appinfo`: categories, age rating declaration, content rights, Free price, 9. **API · App info.** `storebound apple appinfo` (`--dry` first: old -> new per field): categories, age rating declaration, content rights, Free price,
all territories. The **first** availability record of a new app may be refused by the public API (an error on all territories. The **first** availability record of a new app may be refused by the public API (an error on
POST /v2/appAvailabilities); then set it once in App Store Connect > Pricing and Availability and re-run (later runs only read it). POST /v2/appAvailabilities); then set it once in App Store Connect > Pricing and Availability and re-run (later runs only read it).
10. **API · Review details.** `storebound apple review-details` (contact from `.storebound/credentials.json` 10. **API · Review details.** `storebound apple review-details` (contact from `.storebound/credentials.json`

View file

@ -18,7 +18,7 @@ It is not available over MCP.
| form | where | filled from | | form | where | filled from |
|---|---|---| |---|---|---|
| `apple-app-record` | App Store Connect > Apps > + > New App | app.name, apple.primaryLocale, apple.bundleId, console.appRecord (SKU, user access) | | `apple-app-record` | App Store Connect > Apps > + > New App | apple.name (else app.name), apple.primaryLocale, apple.bundleId, console.appRecord (SKU, user access) |
| `apple-age-rating` | App Information > Age Ratings | guide only: `storebound apple appinfo` sets every question through the API | | `apple-age-rating` | App Information > Age Ratings | guide only: `storebound apple appinfo` sets every question through the API |
| `apple-app-privacy` | the app > App Privacy | dataSafety (types and purposes); linked to identity and tracking are always the owner's | | `apple-app-privacy` | the app > App Privacy | dataSafety (types and purposes); linked to identity and tracking are always the owner's |
| `play-content-rating` | Policy > App content > Content rating | app.contactEmail, app.profile, products, console.contentRating | | `play-content-rating` | Policy > App content > Content rating | app.contactEmail, app.profile, products, console.contentRating |

View file

@ -38,7 +38,9 @@ deleting products. Sending a first release for review is the owner's action in t
`--dry` (asks first; `play release app-release.aab` does the same with more track options). `--dry` (asks first; `play release app-release.aab` does the same with more track options).
Add testers (internal testing list) and **license testers** (Settings > License testing) so test purchases are free. Add testers (internal testing list) and **license testers** (Settings > License testing) so test purchases are free.
6. **API · Listing text.** Fill `store/listing.md` (one section per language), then `storebound play listing`. 6. **API · Listing text.** Fill `store/listing.md` (one section per language), then `storebound play listing`.
It also sets contact email + website (website = the domain serving app-ads.txt). It also sets contact email + website (website = the domain serving app-ads.txt). Run `--dry` first and show the
owner the plan (details and per language old -> new per field; draft languages skipped until `listing reviewed`,
`--include-drafts` only on the owner's word); the real run asks in a terminal and PUTs only what changes.
7. **API · Graphics.** Render (`store-screenshots` skill), `storebound shots jpeg`, then 7. **API · Graphics.** Render (`store-screenshots` skill), `storebound shots jpeg`, then
`storebound play images > .storebound/play-images.log 2>&1 &` and follow the log (it is slow: one edit per language). `storebound play images > .storebound/play-images.log 2>&1 &` and follow the log (it is slow: one edit per language).
8. **API · In-app products.** `store-iap-setup` skill (`storebound play products`). Needs a build with the BILLING 8. **API · In-app products.** `store-iap-setup` skill (`storebound play products`). Needs a build with the BILLING

View file

@ -0,0 +1,72 @@
---
name: store-pitfalls
description: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each - store lists that lag right after a create, dry runs that print a count instead of a plan, App Store names taken on a storefront, keyword limits in bytes, Data safety answers without code evidence, missing font glyphs in screenshots, console sign-in and sessions, Capacitor monorepo plugins. Read it before any store task, and when a store command does something you did not expect.
---
# Store pitfalls
Each entry: **symptom** → cause → what to do → what guards it now. The full changelog of lessons with dates is
`docs/pitfalls.md` in the storebound repository. When you hit a new one, tell the owner and add it there (and here).
## 1. A product you just created is "not there"
- **Symptom:** `apple iap-review` uploads nothing for a product `apple iap` created a minute ago; a list looks short.
- **Cause:** App Store Connect's `/inAppPurchasesV2` list (and Play's product list) can lag for a short while after a
create. A command that walks the list skips what is not in it yet.
- **Do:** wait a minute and re-run. Never assume a product was handled because the command finished.
- **Guard:** `apple iap-review` compares the config's products with the store's list, names the missing ones
("the store's list can lag a minute after creating; re-run") and exits 1. `apple iap` and `play products` read the
list again after creating and warn about any new product that is not in it yet; their dry runs name products that
are not on the store.
## 2. A dry run that only prints a count
- **Symptom:** `--dry` says "listing: 20 locales" or "3 change(s)", but not which fields would change to what.
- **Cause:** the command logged a summary instead of the plan.
- **Do:** never ask the owner to approve a count. Show the rows that change (item, action, old → new). If a command
only prints a count, say so and show the owner the diff from `pull` / `--json` output instead.
- **Guard:** `cli/lib/dry.ts` `dryPlan(title, rows)` prints the standard plan table (`apple iap`, `apple iap-review`,
`play products` use it); `tests/pitfalls.test.ts` scans `cli/**` for `--dry` branches that print nothing but a count.
## 3. "The app name you entered is already being used"
- **Symptom:** creating the App Store record or saving the name fails although you own no app with that name.
- **Cause:** App Store app names are unique per storefront, across all developers.
- **Do:** ask the owner for a variant (a short suffix such as "Example Notes: Lists") and set `apple.name` in the config;
keep `app.name` for Play and the brand. Do not pick the suffix yourself.
- **Guard:** `apple.name` overrides the App Store name.
## 4. Keyword field "too long" at fewer than 100 characters
- **Symptom:** App Store Connect rejects keywords that look short enough, mostly in Turkish, German, CJK.
- **Cause:** the 100 limit counts UTF-8 bytes, not characters ("ş" is 2 bytes, a CJK character 3).
- **Do:** shorten by bytes; drop words, not commas.
- **Guard:** `storebound check` counts bytes for keywords.
## 5. Data safety says "email collected" for an app that never asks for one
- **Symptom:** the proposal marks email (or phone) as collected because the app has accounts.
- **Cause:** account features do not imply email collection (anonymous ids, Game Center, Play Games sign-in).
- **Do:** answer only what the code proves; ask the owner for the rest (rule 5).
- **Guard:** `storebound scan` marks email only with evidence (an email field, an email sign-up call) and otherwise
says "ask owner".
## 6. Boxes or wrong glyphs in localized screenshots
- **Symptom:** Turkish, Polish or Vietnamese captions show fallback glyphs (ş, ğ, ł, ệ) while the English ones are fine.
- **Cause:** the font (or the Google Fonts subset that was downloaded) does not cover those characters, and the
browser silently draws them with another font.
- **Do:** check every language's characters before rendering, pick a font that covers them or let the fallback fill in.
- **Guard:** `storebound shots fonts` / `shots check` check each language's characters against the fonts' glyphs.
## 7. Console automation stops at sign-in or loses the session
- **Symptom:** `console fill` waits on a sign-in page, cannot find fields, or is signed out on the next run.
- **Cause:** the App Store Connect sign-in runs inside an `idmsa.apple.com` iframe; "User Access" is a plain heading,
not a labeled group; Chrome drops session cookies unless the last session is restored.
- **Do:** let the owner sign in in the opened window (never type credentials); re-run after the sign-in.
- **Guard:** the console session handles the iframe and the plain heading and starts Chrome with
`--restore-last-session`; a partial miss fills every field found and leaves only the missing ones to the owner.
## 8. `scan` misses Capacitor plugins in a monorepo
- **Symptom:** SDKs or privacy manifests of Capacitor plugins are not found.
- **Cause:** the plugins live in `apps/native/node_modules` (a workspace package), not in the root `node_modules`.
- **Do:** run `scan` from the project root; check that the stack line lists the plugins.
- **Guard:** `storebound scan` and `privacy-manifest` resolve packages through workspace folders too.
## Adding a lesson
Every bug found in real use gets an entry in `docs/pitfalls.md` and here, and, where possible, a check or a test
that fails without the fix (see CONTRIBUTING.md).

View file

@ -52,6 +52,16 @@ in a plain Android tablet body instead of the iPad one.
`<shots.frames>/<lang>/<phone|tablet>/<shot>.png`, local, not committed. `<shots.frames>/<lang>/<phone|tablet>/<shot>.png`, local, not committed.
- `web` (default): `baseUrl`, `query` with `{lang}`, shots: `path` / `waitFor` / `eval` / `delayMs` / `device`. - `web` (default): `baseUrl`, `query` with `{lang}`, shots: `path` / `waitFor` / `eval` / `delayMs` / `device`.
Phone 440 x 902 @3x and tablet 800 x 1240 @2x by default; the template draws the status bar above. Phone 440 x 902 @3x and tablet 800 x 1240 @2x by default; the template draws the status bar above.
Speed (many languages): frames run in parallel browser contexts (`--concurrency N`, `capture.concurrency`;
default min(3, cores / 4) since game boots are GPU-heavy). `capture.session: 'per-language'` boots the app once
per language and device and switches shots in that page (per shot `navigate: 'spa'` = pushState + popstate to its
path, then `waitFor` / `eval`; `'reload'` = goto in the same page); a shot whose `waitFor` fails there within
`reuseTimeoutMs` (15000) gets a fresh page. Re-runs skip frames whose inputs did not change (shot entry, URL,
frame size, the language's copy, the build: `capture.build` files / folders, else the HTML and scripts at
`baseUrl`, fonts) via `.storebound/capture-cache.json`; `--only-missing` captures only missing files, `--force`
everything. Each progress line shows n/total, ETA and the time per step (goto, wait, eval, delay, shot); the end
lists the slowest frames and steps, and `.storebound/capture-report.json` keeps them. Put the slow step right
(a long `waitFor` = the game reaching the scene: add a URL switch that jumps there).
- `ios-sim` (Unity, Godot, Flutter, native, Capacitor: any Simulator build): `ios.device` (simulator name or UDID, - `ios-sim` (Unity, Godot, Flutter, native, Capacitor: any Simulator build): `ios.device` (simulator name or UDID,
e.g. a 6.9" iPhone), `ios.bundleId`, optional `ios.app` (.app to install), `ios.args`. Per shot: `args` (launch e.g. a 6.9" iPhone), `ios.bundleId`, optional `ios.app` (.app to install), `ios.args`. Per shot: `args` (launch
arguments, read them with UserDefaults / your engine) and / or `url` (deep link). Language goes in as arguments, read them with UserDefaults / your engine) and / or `url` (deep link). Language goes in as
@ -89,7 +99,7 @@ in a plain Android tablet body instead of the iPad one.
`{ bg, glow, ink, shadow }`), frames (one front phone + optional back phones with x / dy / scale / rotate), badge `{ bg, glow, ink, shadow }`), frames (one front phone + optional back phones with x / dy / scale / rotate), badge
slots (y, side, icon, hot, stars). Fonts default to Paytone One + Montserrat (game) or Inter (app): all cover slots (y, side, icon, hot, stars). Fonts default to Paytone One + Montserrat (game) or Inter (app): all cover
Latin Extended and Vietnamese. Latin Extended and Vietnamese.
6. **Render.** `storebound shots render --lang en` first, review `store/renders/en/sheet.png` (contact sheet, sizes 6. **Render.** (`--concurrency N`, default min(4, cores / 2) pages) `storebound shots render --lang en` first, review `store/renders/en/sheet.png` (contact sheet, sizes
packed into a grid), then packed into a grid), then
all languages in the background: `storebound shots render > .storebound/render.log 2>&1 &`. all languages in the background: `storebound shots render > .storebound/render.log 2>&1 &`.
7. **JPEG for Play.** `storebound shots jpeg` (q92, about 4x smaller than PNG; App Store stays PNG). 7. **JPEG for Play.** `storebound shots jpeg` (q92, about 4x smaller than PNG; App Store stays PNG).

View file

@ -2,7 +2,7 @@
Source for `storebound apple listing`. One `## <ASC locale>` section per locale (the first word is the locale code: Source for `storebound apple listing`. One `## <ASC locale>` section per locale (the first word is the locale code:
`en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### <field>`, field names exactly: `en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### <field>`, field names exactly:
`name` (optional, defaults to `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 bytes, comma `name` (optional, defaults to `apple.name`, else `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 bytes, comma
separated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed separated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed
on the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`. on the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`.

View file

@ -2,7 +2,7 @@
Source for `storebound apple listing`. One `## <ASC locale>` section per locale (the first word is the locale code: Source for `storebound apple listing`. One `## <ASC locale>` section per locale (the first word is the locale code:
`en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### <field>`, field names exactly: `en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### <field>`, field names exactly:
`name` (optional, defaults to `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 bytes, comma `name` (optional, defaults to `apple.name`, else `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 bytes, comma
separated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed separated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed
on the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`. on the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`.

View file

@ -51,6 +51,7 @@ const config: ShipConfig = {
apple: { apple: {
bundleId: 'com.example.app', bundleId: 'com.example.app',
// name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there ("already being used"); default app.name
listing: 'store/appstore.md', listing: 'store/appstore.md',
// Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption
// beyond the OS (HTTPS through the system, standard sign-in). // beyond the OS (HTTPS through the system, standard sign-in).

View file

@ -2,7 +2,7 @@
Source for `storebound apple listing`. One `## <ASC locale>` section per locale (the first word is the locale code: Source for `storebound apple listing`. One `## <ASC locale>` section per locale (the first word is the locale code:
`en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### <field>`, field names exactly: `en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### <field>`, field names exactly:
`name` (optional, defaults to `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 bytes, comma `name` (optional, defaults to `apple.name`, else `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 bytes, comma
separated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed separated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed
on the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`. on the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`.

View file

@ -51,6 +51,7 @@ const config: ShipConfig = {
apple: { apple: {
bundleId: 'com.example.app', bundleId: 'com.example.app',
// name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there ("already being used"); default app.name
listing: 'store/appstore.md', listing: 'store/appstore.md',
// Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption
// beyond the OS (HTTPS through the system, standard sign-in). // beyond the OS (HTTPS through the system, standard sign-in).

View file

@ -37,6 +37,7 @@ const config: ShipConfig = {
apple: { apple: {
bundleId: 'com.example.game', bundleId: 'com.example.game',
// name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there ("already being used"); default app.name
// appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out // appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out
listing: 'store/appstore.md', listing: 'store/appstore.md',
reviewShots: 'store/iap-review', reviewShots: 'store/iap-review',

77
tests/apple-name.test.ts Normal file
View file

@ -0,0 +1,77 @@
// apple.name: the App Store name when the plain app.name is taken on the App Store. Fallback order (### name block >
// apple.name > app.name), validation, the console answer, check's length error and same-name hint, listing pull.
import { afterEach, describe, expect, test } from 'bun:test';
import { run as check } from '../cli/check';
import { appleName, type ShipConfig, validateConfig } from '../cli/lib/config';
import { consoleAnswers } from '../cli/lib/console-answers';
import { navPlan } from '../cli/lib/console-forms';
import { appleNameIssues } from '../cli/lib/copy';
import { mergeAppleListing } from '../cli/lib/listing-pull';
import { listingCompleteness } from '../cli/lib/project-files';
import { BASE, capture, jsonOut, project, restore } from './helpers/store-mock';
afterEach(restore);
const NAMED: ShipConfig = { ...BASE, app: { ...BASE.app, name: 'STAR DASH' }, apple: { ...BASE.apple!, name: 'STAR DASH: Stone Age to 2100', primaryLocale: 'en-US' } };
const PLAIN: ShipConfig = { ...BASE, app: { ...BASE.app, name: 'STAR DASH' }, apple: { ...BASE.apple!, primaryLocale: 'en-US' } };
const sec = (loc: string, name?: string) => `## ${loc}\n\n${name ? `### name\n\`\`\`\n${name}\n\`\`\`\n\n` : ''}### subtitle\n\`\`\`\nSub\n\`\`\`\n\n### promotionalText\n\`\`\`\nPromo\n\`\`\`\n\n### keywords\n\`\`\`\nrun,time\n\`\`\`\n\n### description\n\`\`\`\nText.\n\`\`\`\n\n`;
describe('apple.name', () => {
test('fallback order: apple.name, else app.name', () => {
expect(appleName(NAMED)).toBe('STAR DASH: Stone Age to 2100');
expect(appleName(PLAIN)).toBe('STAR DASH');
expect(appleName({ ...PLAIN, apple: { ...PLAIN.apple!, name: ' ' } })).toBe('STAR DASH');
});
test('validated: at most 30 characters, text', () => {
expect(validateConfig(NAMED)).toEqual([]);
expect(validateConfig({ ...NAMED, apple: { ...NAMED.apple!, name: 'STAR DASH: Stone Age to the Year 2100' } }).join('\n')).toContain('apple.name: 37 characters > 30');
expect(validateConfig({ ...NAMED, apple: { ...NAMED.apple!, name: '' } }).join('\n')).toContain('apple.name: the App Store name');
});
test('console fill apple-app-record answers Name from apple.name, else app.name', () => {
const a = new Map(consoleAnswers('apple-app-record', NAMED).map(x => [x.id, x]));
expect(a.get('name')).toMatchObject({ value: 'STAR DASH: Stone Age to 2100', source: 'apple.name', certain: true });
const b = new Map(consoleAnswers('apple-app-record', PLAIN).map(x => [x.id, x]));
expect(b.get('name')).toMatchObject({ value: 'STAR DASH', source: 'app.name' });
expect(b.get('name')!.note).toContain('apple.name');
const pick = navPlan('apple-app-privacy', { ...NAMED, apple: { ...NAMED.apple!, appId: undefined } }).find(s => s.kind === 'pickApp') as { name?: string } | undefined;
expect(pick?.name).toBe('STAR DASH: Stone Age to 2100');
});
test('name issues: length error per locale, same-name hint only without apple.name or own names', () => {
const long = 'A Name That Is Way Too Long For Apple';
expect(appleNameIssues({}, ['en-US'], long, long)).toEqual([expect.objectContaining({ level: 'error', msg: expect.stringContaining('app.name; set apple.name') }), expect.objectContaining({ level: 'info' })]);
expect(appleNameIssues({ 'de-DE': { name: long } }, ['en-US'], 'Short', 'Short').map(i => `${i.level} ${i.msg.slice(0, 31)}`)).toEqual(['error App Store name of de-DE is 37 >']);
const hint = appleNameIssues({ 'en-US': {} , 'de-DE': {} }, ['en-US', 'de-DE'], 'STAR DASH', 'STAR DASH');
expect(hint).toHaveLength(1);
expect(hint[0]!.msg).toContain('already being used');
expect(appleNameIssues({}, ['en-US', 'de-DE'], 'STAR DASH: Stone Age to 2100', 'STAR DASH')).toEqual([]);
expect(appleNameIssues({ 'de-DE': { name: 'STAR DASH: Steinzeit bis 2100' } }, ['en-US', 'de-DE'], 'STAR DASH', 'STAR DASH')).toEqual([]);
});
test('check: hint with the plain name, error when the fallback is too long', async () => {
const files = { 'store/appstore.md': `# App Store\n\n${sec('en-US')}${sec('de-DE')}${sec('tr')}`, '.gitignore': '.storebound/\n' };
let p = project({ ...PLAIN, play: undefined }, files);
let j = jsonOut((await capture(() => check(p.ctx(['--json'], ['json'])))).out);
expect(j.ok).toBe(true);
expect((j.hints as string[]).join('\n')).toContain('already being used');
p = project({ ...NAMED, play: undefined }, files);
j = jsonOut((await capture(() => check(p.ctx(['--json'], ['json'])))).out);
expect(j.hints).toEqual([]);
p = project({ ...PLAIN, app: { ...PLAIN.app, name: 'STAR DASH Stone Age to the Year 2100' }, play: undefined }, files);
const r = await capture(() => check(p.ctx(['--json'], ['json'])));
j = jsonOut(r.out);
expect(j.ok).toBe(false);
expect((j.problems as string[]).filter(x => x.includes('App Store name of'))).toHaveLength(3);
});
test('listing completeness and listing pull use apple.name as the default name', () => {
const p = project({ ...NAMED, play: undefined }, { 'store/appstore.md': `# App Store\n\n${sec('en-US')}${sec('de-DE', 'STAR DASH: Steinzeit bis 2100')}` });
const l = listingCompleteness(p.loaded.config, p.root);
const name = (code: string) => l.locales.find(x => x.apple?.code === code)!.apple!.fields.find(f => f.field === 'name');
expect(name('en-US')).toMatchObject({ length: 28, state: 'ok' });
expect(name('de-DE')).toMatchObject({ length: 29, state: 'ok' });
const md = `# App Store\n\n${sec('en-US')}`;
const r = mergeAppleListing(md, { 'en-US': { name: 'STAR DASH: Stone Age to 2100' }, 'fr-FR': { name: 'STAR DASH: Stone Age to 2100', subtitle: 'Sous-titre' } }, 'STAR DASH: Stone Age to 2100');
expect(r.changes.map(c => `${c.section} ${c.field}`)).toEqual(['fr-FR subtitle']);
expect(r.md).not.toContain('### name');
const own = mergeAppleListing(`# App Store\n\n${sec('en-US', 'Old')}`, { 'en-US': { name: 'STAR DASH: Stone Age to 2100' } }, 'STAR DASH: Stone Age to 2100');
expect(own.changes.map(c => c.field)).toEqual(['name']);
});
});

179
tests/capture-web.test.ts Normal file
View file

@ -0,0 +1,179 @@
// `shots capture` (web) against a local fixture web app: parallel contexts give the same files as serial, the
// per-language session boots the app once per language, the input-hash cache skips unchanged frames and re-runs changed
// ones, and every frame has a timing breakdown. Pure helpers are tested without a browser. Skips the browser part when
// no Chromium can launch. The browser runs run in a `storebound` child process (its own Chromium), like a real run.
import { afterAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { ShipConfig, ShotsCapture } from '../cli/lib/config';
import { type CaptureReport, defaultConcurrency, planWeb, pool, progressLine, selectJobs, timingSummary } from '../cli/shots/capture-web';
import { BASE } from './helpers/store-mock';
const CLI = join(import.meta.dir, '..', 'cli', 'index.ts');
describe('capture helpers', () => {
test('default concurrency: render min(4, cores/2), capture (GPU-heavy) min(3, cores/4), at least 1', () => {
expect(defaultConcurrency('render', 10)).toBe(4);
expect(defaultConcurrency('capture', 10)).toBe(2);
expect(defaultConcurrency('capture', 2)).toBe(1);
expect(defaultConcurrency('render', 1)).toBe(1);
});
test('pool keeps the input order and never runs more than n at once', async () => {
let now = 0, peak = 0;
const out = await pool([5, 1, 3, 2, 4], 2, async x => { now++; peak = Math.max(peak, now); await Bun.sleep(x * 3); now--; return x * 10; });
expect(out).toEqual([50, 10, 30, 20, 40]);
expect(peak).toBe(2);
});
test('progress line with an ETA', () => {
expect(progressLine(5, 20, 0, 10_000)).toBe(' 5/20 ETA 30.0s');
expect(progressLine(20, 20, 0, 10_000)).toBe('20/20');
});
test('cache selection: changed inputs and missing files run; --only-missing; --force', () => {
const cap: ShotsCapture = { source: 'web', baseUrl: 'http://x', shots: { a: { path: '/a' }, b: { path: '/b' } } };
const dims = { phone: { w: 10, h: 20, dpr: 1, bar: 0 }, tablet: { w: 10, h: 20, dpr: 1, bar: 0 } };
const jobs = planWeb(cap, { langs: ['en', 'tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b1' });
expect(jobs.map(j => j.frame)).toEqual(['en/phone/a.png', 'en/phone/b.png', 'tr/phone/a.png', 'tr/phone/b.png']);
const cache = Object.fromEntries(jobs.map(j => [j.frame, j.hash]));
const all = () => true;
expect(selectJobs(jobs, cache, 'changed', all).run).toEqual([]);
const jobs2 = planWeb({ ...cap, shots: { ...cap.shots, b: { path: '/b', delayMs: 5 } } }, { langs: ['en', 'tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b1' });
expect(selectJobs(jobs2, cache, 'changed', all).run.map(j => j.frame)).toEqual(['en/phone/b.png', 'tr/phone/b.png']);
const jobs3 = planWeb(cap, { langs: ['en', 'tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b2' });
expect(selectJobs(jobs3, cache, 'changed', all).run.length).toBe(4);
expect(selectJobs(jobs3, cache, 'only-missing', (f: string) => !f.endsWith('tr/phone/a.png')).run.map(j => j.frame)).toEqual(['tr/phone/a.png']);
expect(selectJobs(jobs, cache, 'force', all).run.length).toBe(4);
});
test('timing summary: slowest frames with their slowest step, time per step', () => {
const t = (goto: number, waitFor: number) => ({ goto, waitFor, eval: 0, delay: 100, screenshot: 50, total: goto + waitFor + 150 });
const s = timingSummary([{ frame: 'en/phone/a.png', timing: t(1000, 200) }, { frame: 'en/phone/b.png', timing: t(100, 5000) }], 1);
expect(s.slowest).toEqual([{ frame: 'en/phone/b.png', total: 5250, step: 'waitFor' }]);
expect(s.steps).toEqual({ goto: 1100, waitFor: 5200, eval: 0, delay: 200, screenshot: 100 });
});
});
// ---- a local fixture web app: /scene/<name>?lang=xx, a SPA (popstate) that counts its boots ----
let boots = 0;
const server = Bun.serve({
port: 0, hostname: '127.0.0.1',
fetch(req) {
const u = new URL(req.url);
if (u.pathname === '/app.js') {
boots++;
return new Response(`
const COLORS = { en: '#1e66f5', de: '#40a02b', tr: '#d20f39' };
function show() {
const name = location.pathname.split('/').pop() || 'home', lang = new URLSearchParams(location.search).get('lang');
document.body.style.cssText = 'margin:0;background:' + (COLORS[lang] || '#000') + ';font:24px sans-serif;color:#fff';
document.body.innerHTML = '<div style="padding:20px">' + lang + ' ' + name + '</div><div style="margin:20px;width:' + (40 * name.length) + 'px;height:60px;background:#fff"></div>';
window.scene = null;
window.shows = (window.shows || 0) + 1;
setTimeout(() => { window.scene = name; }, 30);
}
addEventListener('popstate', show);
show();`, { headers: { 'content-type': 'text/javascript' } });
}
return new Response('<!doctype html><html><head><meta charset="utf-8"><script src="/app.js" defer></script></head><body></body></html>', { headers: { 'content-type': 'text/html' } });
},
});
afterAll(() => server.stop(true));
const canLaunch = spawnSync('bun', ['-e', `const { launch } = await import(${JSON.stringify(join(import.meta.dir, '..', 'cli', 'shots', 'browser.ts'))}); await (await launch(${JSON.stringify(join(import.meta.dir, '..'))}, { headless: true })).close();`], { timeout: 60_000 }).status === 0;
if (!canLaunch) console.warn('capture-web browser tests skipped: no Chromium could launch (bunx playwright install chromium)');
/** A temp project with this config; cli() runs `storebound shots capture <args>` in it. */
function project(cfg: ShipConfig, files: Record<string, string>): { root: string; setConfig: (c: ShipConfig) => void; cli: (args: string[]) => Promise<{ out: string; err: string; code: number }> } {
const root = mkdtempSync(join(tmpdir(), 'sb-cap-'));
for (const [p, t] of Object.entries(files)) { mkdirSync(join(root, p, '..'), { recursive: true }); writeFileSync(join(root, p), t); }
const setConfig = (c: ShipConfig) => writeFileSync(join(root, 'storebound.config.json'), JSON.stringify(c));
setConfig(cfg);
// async: the fixture server lives in this process and must keep answering while the child captures
return { root, setConfig, cli: async args => {
const r = Bun.spawn(['bun', CLI, 'shots', 'capture', ...args], { cwd: root, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1' } });
const [out, err, code] = await Promise.all([new Response(r.stdout).text(), new Response(r.stderr).text(), r.exited]);
return { out, err, code };
} };
}
const shot = (name: string, extra: object = {}) => ({ path: `/scene/${name}`, waitFor: `window.scene === '${name}'`, delayMs: 20, ...extra });
function config(capture: Partial<ShotsCapture> = {}): ShipConfig {
return { ...BASE, shots: { copy: 'store/shots/copy.json', frames: 'store/shots/frames', out: 'store/renders', scenes: [{ id: 'hero', palette: 'fire', frames: [{ src: 'hero.png' }] }], phone: { w: 180, h: 240, dpr: 1 },
capture: { source: 'web', baseUrl: `http://127.0.0.1:${server.port}`, query: 'lang={lang}', build: 'src', shots: { hero: shot('hero'), battle: shot('battle'), king: shot('king') }, ...capture } } };
}
const files = { 'store/shots/copy.json': '{}', 'src/main.js': 'v1' };
const frames = (root: string) => ['en', 'de', 'tr'].flatMap(l => ['hero', 'battle', 'king'].map(n => join(root, 'store/shots/frames', l, 'phone', `${n}.png`)));
describe.skipIf(!canLaunch)('shots capture (web) with a fixture app', () => {
test('concurrency 3 gives the same files as serial', async () => {
const p = project(config(), files);
try {
await p.cli(['--device', 'phone', '--concurrency', '1', '--force']);
const serial = frames(p.root).map(f => readFileSync(f));
const r = await p.cli(['--device', 'phone', '--concurrency', '3', '--force']);
expect(r.out).toContain('capturing 9 frames, 3 at a time');
const parallel = frames(p.root).map(f => readFileSync(f));
expect(parallel.length).toBe(9);
for (const [i, b] of parallel.entries()) expect(Buffer.compare(b, serial[i]!)).toBe(0);
} finally { rmSync(p.root, { recursive: true, force: true }); }
}, 120_000);
test('per-language session boots the app once per language; per-shot once per frame', async () => {
const p = project(config({ session: 'per-language' }), files);
try {
boots = 0;
const r = await p.cli(['--device', 'phone', '--concurrency', '2', '--force']);
expect(boots).toBe(3);
expect(r.out).toContain('(reused page)');
const report = JSON.parse(readFileSync(join(p.root, '.storebound/capture-report.json'), 'utf8')) as CaptureReport;
expect(report.frames.filter(f => f.reused).length).toBe(6);
expect(frames(p.root).every(f => existsSync(f))).toBe(true);
// a shot whose precondition fails in the reused page (it needs a freshly booted page) falls back to a fresh page
const bad = project(config({ session: 'per-language', reuseTimeoutMs: 300, shots: { hero: shot('hero'), fresh: { path: '/scene/fresh', waitFor: "window.scene === 'fresh' && window.shows === 1", delayMs: 20 } } }), files);
try {
boots = 0;
const r2 = await bad.cli(['--device', 'phone', '--lang', 'en', '--force']);
expect(r2.err).toContain('en/phone/fresh: reused page failed');
expect(r2.out).toContain('capture done: 2 frames');
expect(boots).toBe(2);
} finally { rmSync(bad.root, { recursive: true, force: true }); }
boots = 0;
const q = project(config(), files);
await q.cli(['--device', 'phone', '--lang', 'en', '--force']);
rmSync(q.root, { recursive: true, force: true });
expect(boots).toBe(3);
} finally { rmSync(p.root, { recursive: true, force: true }); }
}, 180_000);
test('cache skips unchanged frames, re-runs changed ones; --only-missing; timing breakdown', async () => {
const p = project(config(), files);
try {
let r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('capturing 9 frames');
expect(r.out).toMatch(/tr\/phone\/king\.png goto [\d.]+s wait [\d.]+s eval [\d.]+s delay [\d.]+s shot [\d.]+s = [\d.]+s/);
expect(r.out).toContain('time per step: goto');
expect(r.out).toContain('slowest: ');
const report = JSON.parse(readFileSync(join(p.root, '.storebound/capture-report.json'), 'utf8')) as CaptureReport;
expect(Object.keys(report.frames[0]!.timing).sort()).toEqual(['delay', 'eval', 'goto', 'screenshot', 'total', 'waitFor']);
expect(report.summary.slowest.length).toBe(5);
r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('9 of 9 frames unchanged, skipped');
expect(r.out).toContain('capturing 0 frames');
// a changed shot entry re-runs only that shot (3 languages)
p.setConfig(config({ shots: { hero: shot('hero'), battle: shot('battle', { delayMs: 40 }), king: shot('king') } }));
r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('6 of 9 frames unchanged');
expect(r.out).toContain('capturing 3 frames');
// a build change re-runs everything; --only-missing only the missing file
await Bun.write(join(p.root, 'src/main.js'), 'v2 changed');
rmSync(frames(p.root)[0]!);
r = await p.cli(['--device', 'phone', '--only-missing']);
expect(r.out).toContain('capturing 1 frames');
r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('capturing 8 frames'); // the one just captured already has the new inputs
} finally { rmSync(p.root, { recursive: true, force: true }); }
}, 180_000);
});

View file

@ -1,2 +1,4 @@
// Loaded before every test file (bunfig.toml): no real waiting between the re-checks of cli/lib/upsert.ts. // Loaded before every test file (bunfig.toml): no real waiting between the re-checks of cli/lib/upsert.ts or for
// the store's list to settle after a create (cli/apple/iap.ts).
process.env.STOREBOUND_UPSERT_WAIT_MS = '0'; process.env.STOREBOUND_UPSERT_WAIT_MS = '0';
process.env.STOREBOUND_LIST_SETTLE_MS ??= '0';

157
tests/listing-plan.test.ts Normal file
View file

@ -0,0 +1,157 @@
// Write plans of apple listing, play listing and apple appinfo: the dry run reads only and prints old -> new per field,
// drafts are skipped, the version decision is explicit; the real run applies exactly the plan. Recorded answers only
// (placeholders, no network).
import { afterEach, describe, expect, test } from 'bun:test';
import { run as appInfo } from '../cli/apple/appinfo';
import { run as appleListing } from '../cli/apple/listing';
import { run as playListing } from '../cli/play/listing';
import { planItem, planVersion, short } from '../cli/lib/listing-plan';
import { ascEnv, BASE, capture, jsonOut, mockFetch, playEnv, project, restore, type Call } from './helpers/store-mock';
afterEach(restore);
const page = (data: unknown[]) => ({ data, links: { self: 'x' } });
const v = (id: string, versionString: string, appVersionState: string) => ({ type: 'appStoreVersions', id, attributes: { versionString, appVersionState, platform: 'IOS', copyright: `${new Date().getFullYear()} Example Notes`, releaseType: 'MANUAL' } });
const fence = (t: string) => '```\n' + t + '\n```';
const sec = (loc: string, f: Record<string, string>, mark = '') => `## ${loc}\n${mark}\n` + Object.entries(f).map(([k, t]) => `### ${k}\n${fence(t)}\n`).join('\n') + '\n';
const TEXT = { subtitle: 'Notes that sync', promotionalText: 'Now with lists.', keywords: 'notes,lists', description: 'Write things down.' };
const APPLE_MD = '# App Store\n\n' + sec('en-US', TEXT) + sec('de-DE', { ...TEXT, subtitle: 'Notizen, synchron', description: 'Schreib es auf.' })
+ sec('tr', { ...TEXT, subtitle: 'Senkron notlar' }, '<!-- storebound-translation from=en-US status=draft -->');
const methods = (calls: Call[]) => calls.filter(c => c.method !== 'GET').map(c => `${c.method} ${c.path.split('?')[0]}`);
describe('version decision', () => {
const attrs = { copyright: '2026 Example Notes', releaseType: 'MANUAL' };
test('update the editable version string while PREPARE_FOR_SUBMISSION', () => {
const p = planVersion([v('v-1', '1.0', 'PREPARE_FOR_SUBMISSION')], '1.0.0', attrs);
expect(p).toMatchObject({ action: 'update', id: 'v-1', first: true, reason: 'update the editable version 1.0 (PREPARE_FOR_SUBMISSION) to 1.0.0' });
expect(p.changes.find(c => c.field === 'versionString')).toEqual({ field: 'versionString', from: '1.0', to: '1.0.0' });
});
test('keep, create, refuse', () => {
expect(planVersion([{ ...v('v-1', '1.0.0', 'PREPARE_FOR_SUBMISSION'), attributes: { ...v('v-1', '1.0.0', 'x').attributes, appVersionState: 'PREPARE_FOR_SUBMISSION', copyright: '2026 Example Notes' } }], '1.0.0', attrs).action).toBe('keep');
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION')], '1.1.0', attrs)).toMatchObject({ action: 'create', first: false });
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION')], '1.0.0', attrs).reason).toContain('already exists (READY_FOR_DISTRIBUTION)');
expect(planVersion([v('v-0', '1.2.0', 'READY_FOR_DISTRIBUTION')], '1.1.0', attrs).reason).toContain('not higher than 1.2.0');
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION'), v('v-1', '1.1.0', 'WAITING_FOR_REVIEW')], '1.2.0', attrs).reason).toContain('1.1.0 is WAITING_FOR_REVIEW');
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION'), v('v-1', '1.1', 'REJECTED')], '1.1.0', attrs)).toMatchObject({ action: 'refuse', reason: expect.stringContaining('only while PREPARE_FOR_SUBMISSION') });
expect(planVersion([], '1.0.0', attrs)).toMatchObject({ action: 'create', first: true });
});
test('field diff and long values cut with their length', () => {
expect(planItem('en-US', { attributes: { subtitle: 'A', keywords: null } }, { subtitle: 'B', keywords: '', description: undefined })).toMatchObject({ action: 'update', changes: [{ field: 'subtitle', from: 'A', to: 'B' }], unchanged: ['keywords'] });
expect(short('x'.repeat(100))).toBe(`"${'x'.repeat(60)}…" (100 chars)`);
});
});
function ascRoutes(versions: unknown[], o: { versionLocs?: unknown[]; created?: boolean } = {}) {
return mockFetch([
{ match: /^\/v1\/apps\/6400000101\/appStoreVersions\?filter\[platform\]=IOS/, answer: page(versions) },
{ match: /^\/v1\/apps\/6400000101\/appInfos/, answer: page([{ type: 'appInfos', id: 'ai-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' } }]) },
{ match: /^\/v1\/appInfos\/ai-1\/appInfoLocalizations/, answer: page([{ type: 'appInfoLocalizations', id: 'il-en', attributes: { locale: 'en-US', name: 'Example Notes', subtitle: 'Old subtitle', privacyPolicyUrl: 'https://example.com/privacy' } }]) },
{ match: /^\/v1\/appStoreVersions\/(v-1|v-new)\/appStoreVersionLocalizations/, answer: page(o.versionLocs ?? [{ type: 'appStoreVersionLocalizations', id: 'vl-en', attributes: { locale: 'en-US', ...TEXT, whatsNew: null, supportUrl: 'https://example.com/support', marketingUrl: 'https://example.com' } }]) },
{ method: 'PATCH', match: /^\/v1\/appStoreVersions\/v-1$/, answer: { data: v('v-1', '1.0.0', 'PREPARE_FOR_SUBMISSION') } },
{ method: 'POST', match: /^\/v1\/appStoreVersions$/, answer: { data: v('v-new', '1.1.0', 'PREPARE_FOR_SUBMISSION') } },
{ method: 'POST', match: /^\/v1\/(appInfoLocalizations|appStoreVersionLocalizations)$/, answer: c => ({ data: { id: 'new', attributes: (c.body as { data: { attributes: unknown } }).data.attributes } }) },
{ method: 'PATCH', match: /^\/v1\/(appInfoLocalizations|appStoreVersionLocalizations)\//, answer: { data: {} } },
]);
}
describe('apple listing plan', () => {
test('--dry --json: version update, per-locale create / update with old -> new, draft skipped; GETs only', async () => {
ascEnv();
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
const calls = ascRoutes([v('v-1', '1.0', 'PREPARE_FOR_SUBMISSION')]);
const r = await capture(() => appleListing(p.ctx(['--version', '1.0.0', '--dry', '--json'])));
expect(methods(calls)).toEqual([]);
const j = jsonOut(r.out) as any;
expect(j.versionPlan).toMatchObject({ action: 'update', reason: 'update the editable version 1.0 (PREPARE_FOR_SUBMISSION) to 1.0.0' });
expect(j.versionPlan.existing).toEqual([{ id: 'v-1', versionString: '1.0', state: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }]);
expect(j.appInfo.locales.map((l: any) => `${l.key} ${l.action}`)).toEqual(['en-US update', 'de-DE create']);
expect(j.appInfo.locales[0].changes).toEqual([{ field: 'subtitle', from: 'Old subtitle', to: 'Notes that sync' }]);
expect(j.versionLocales.map((l: any) => `${l.key} ${l.action}`)).toEqual(['en-US same', 'de-DE create']);
expect(j.skipped).toEqual([{ key: 'tr', reason: expect.stringContaining('machine-translated draft') }]);
expect(j.changes).toBe(4);
const t = await capture(() => appleListing(p.ctx(['--version', '1.0.0', '--dry'])));
expect(t.out).toContain('UPDATE: update the editable version 1.0 (PREPARE_FOR_SUBMISSION) to 1.0.0');
expect(t.out).toContain('subtitle: "Old subtitle" -> "Notes that sync"');
expect(t.out).toContain('en-US: unchanged (5 fields)');
expect(t.out).toContain('Skipped tr: machine-translated draft');
});
test('--include-drafts plans the draft locale too', async () => {
ascEnv();
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
ascRoutes([v('v-1', '1.0.0', 'PREPARE_FOR_SUBMISSION')]);
const j = jsonOut((await capture(() => appleListing(p.ctx(['--version', '1.0.0', '--dry', '--json', '--include-drafts'])))).out) as any;
expect(j.skipped).toEqual([]);
expect(j.appInfo.locales.map((l: any) => l.key)).toEqual(['en-US', 'de-DE', 'tr']);
});
test('the real run applies exactly the plan: no write for unchanged locales', async () => {
ascEnv();
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
const calls = ascRoutes([v('v-1', '1.0', 'PREPARE_FOR_SUBMISSION')]);
await capture(() => appleListing(p.ctx(['--version', '1.0.0'])));
expect(methods(calls)).toEqual(['PATCH /v1/appStoreVersions/v-1', 'PATCH /v1/appInfoLocalizations/il-en', 'POST /v1/appInfoLocalizations', 'POST /v1/appStoreVersionLocalizations']);
expect((calls.find(c => c.path === '/v1/appInfoLocalizations/il-en')!.body as any).data.attributes).toEqual({ subtitle: 'Notes that sync' });
expect((calls.find(c => c.path === '/v1/appStoreVersions/v-1')!.body as any).data.attributes).toEqual({ versionString: '1.0.0' });
});
test('a new version is created, then its copied texts are planned again and applied', async () => {
ascEnv();
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
const calls = ascRoutes([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION')]);
const j = jsonOut((await capture(() => appleListing(p.ctx(['--version', '1.1.0', '--dry', '--json'])))).out) as any;
expect(j.versionPlan).toMatchObject({ action: 'create', reason: 'create version 1.1.0 (no editable iOS version)' });
expect(j.versionLocales).toBeNull();
await capture(() => appleListing(p.ctx(['--version', '1.1.0'])));
expect(methods(calls).filter(m => m.includes('appStoreVersion'))).toEqual(['POST /v1/appStoreVersions', 'POST /v1/appStoreVersionLocalizations']);
});
test('a refused version stops the run; the dry run says so and exits 1', async () => {
ascEnv();
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
const calls = ascRoutes([v('v-0', '1.2.0', 'READY_FOR_DISTRIBUTION')]);
const r = await capture(() => appleListing(p.ctx(['--version', '1.1.0', '--dry'])));
expect(r.out).toContain('REFUSE: version 1.1.0 is not higher than 1.2.0');
expect(r.exit).toBe(1);
await expect(appleListing(p.ctx(['--version', '1.1.0']))).rejects.toThrow('not higher than 1.2.0');
expect(methods(calls)).toEqual([]);
});
});
describe('play listing plan', () => {
const PLAY_MD = '# Play\n\n## English\n<!-- play: en-US -->\n\n### title\n```\nExample Notes\n```\n\n### short\n```\nNew short\n```\n\n### full\n```\nFull text.\n```\n\n'
+ '## German\n<!-- play: de-DE -->\n<!-- storebound-translation from=en-US status=draft -->\n\n### short\n```\nKurz\n```\n\n### full\n```\nLang.\n```\n';
const routes = () => mockFetch([
{ method: 'POST', match: /\/edits$/, answer: { id: 'edit-1' } },
{ match: /\/edits\/edit-1\/details$/, answer: { defaultLanguage: 'en-US', contactEmail: 'support@example.com', contactWebsite: 'https://example.com' } },
{ match: /\/edits\/edit-1\/listings$/, answer: { listings: [{ language: 'en-US', title: 'Example Notes', shortDescription: 'Old short', fullDescription: 'Full text.' }] } },
{ method: 'DELETE', match: /\/edits\/edit-1$/, answer: new Response(null, { status: 204 }) },
{ method: 'PUT', match: /\/edits\/edit-1\/listings\/en-US$/, answer: {} },
{ method: 'POST', match: /\/edits\/edit-1:commit$/, answer: {} },
]);
test('--dry --json: old -> new per field, unchanged details, draft language skipped; real run PUTs only the change', async () => {
playEnv();
const p = project({ ...BASE, apple: undefined }, { 'store/listing.md': PLAY_MD });
let calls = routes();
const j = jsonOut((await capture(() => playListing(p.ctx(['--dry', '--json'])))).out) as any;
expect(j.details.action).toBe('same');
expect(j.listings).toEqual([expect.objectContaining({ key: 'en-US', action: 'update', changes: [{ field: 'shortDescription', from: 'Old short', to: 'New short' }] })]);
expect(j.skipped).toEqual([{ key: 'de-DE', reason: expect.stringContaining('draft') }]);
expect(calls.some(c => c.method === 'PUT' || c.path.includes(':commit'))).toBe(false);
calls = routes();
await capture(() => playListing(p.ctx([])));
expect(calls.filter(c => c.method === 'PUT').map(c => c.path.split('/').slice(-2).join('/'))).toEqual(['listings/en-US']);
});
});
describe('apple appinfo plan', () => {
test('--dry --json: categories and age rating old -> new; nothing written', async () => {
ascEnv();
const p = project({ ...BASE, play: undefined, apple: { ...BASE.apple!, info: { categories: { primary: 'PRODUCTIVITY' }, ageRating: { advertising: true }, free: false } } });
const calls = mockFetch([
{ match: /^\/v1\/apps\/6400000101\/appInfos/, answer: page([{ type: 'appInfos', id: 'ai-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' } }]) },
{ match: /^\/v1\/appInfos\/ai-1\?include=/, answer: { data: { id: 'ai-1', relationships: { primaryCategory: { data: { type: 'appCategories', id: 'UTILITIES' } } } } } },
{ match: /^\/v1\/appInfos\/ai-1\/ageRatingDeclaration/, answer: { data: { id: 'ai-1', attributes: { advertising: false, gambling: false, violenceRealistic: 'NONE' } } } },
]);
const j = jsonOut((await capture(() => appInfo(p.ctx(['--dry', '--json'])))).out) as any;
expect(methods(calls)).toEqual([]);
expect(j.items[0]).toMatchObject({ key: 'categories', action: 'update', changes: [{ field: 'primaryCategory', from: 'UTILITIES', to: 'PRODUCTIVITY' }] });
expect(j.items[1].changes).toContainEqual({ field: 'advertising', from: 'false', to: 'true' });
expect(j.items[1].changes.find((c: any) => c.field === 'gambling')).toBeUndefined();
});
});

164
tests/pitfalls.test.ts Normal file
View file

@ -0,0 +1,164 @@
// Guardrails for lessons from real use (docs/pitfalls.md, skills/store-pitfalls): the store's product list lagging
// right after a create, and dry runs that print a count instead of a plan. Recorded App Store Connect / Google Play
// answers; every id is a placeholder.
import { afterEach, describe, expect, test } from 'bun:test';
import { Glob } from 'bun';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { countOnlyDryExits, dryPlan, isPlanLine } from '../cli/lib/dry';
import { LAG_HINT, missingFromStore } from '../cli/lib/store-lag';
import { run as iapReview } from '../cli/apple/iap-review';
import { run as iap } from '../cli/apple/iap';
import { run as playProducts } from '../cli/play/products';
import type { Product } from '../cli/lib/config';
import { ascEnv, BASE, capture, mockFetch, notFound, playEnv, project, restore } from './helpers/store-mock';
const env = { ...process.env };
afterEach(() => { restore(); if (env.STOREBOUND_LIST_SETTLE_MS === undefined) delete process.env.STOREBOUND_LIST_SETTLE_MS; });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const page = (data: unknown[]): any => ({ data, links: { self: 'https://api.appstoreconnect.apple.com/v1/x' }, meta: { paging: { total: data.length, limit: 200 } } });
const product = (id: string): Product => ({ id, type: 'non_consumable', usd: 2.99, listings: { en: { title: 'No Ads', description: 'Removes ads' } } });
// a PNG header of an App Store screenshot size (the size check reads IHDR only)
const png = (w = 1290, h = 2796) => { const b = Buffer.alloc(33); b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0); b.writeUInt32BE(13, 8); b.write('IHDR', 12); b.writeUInt32BE(w, 16); b.writeUInt32BE(h, 20); b[24] = 8; b[25] = 2; return b; };
const PRO = 'com.example.notes.pro', GEMS = 'com.example.notes.gems';
const CONFIG = { ...BASE, products: [product(PRO), { ...product(GEMS), type: 'consumable' as const }] };
describe('store list lag after create', () => {
test('missingFromStore keeps config order and ignores duplicates', () => {
expect(missingFromStore(['a', 'b', 'c', 'b'], ['c'])).toEqual(['a', 'b']);
expect(missingFromStore(['a'], new Set(['a']))).toEqual([]);
});
test('apple iap-review --dry: a product missing from /inAppPurchasesV2 is named with the lag hint and exits 1', async () => {
ascEnv();
const p = project(CONFIG, { [`store/iap-review/${PRO}.png`]: png(), [`store/iap-review/${GEMS}.png`]: png() });
// as answered a few seconds after `apple iap` created both: only the older product is listed
const calls = mockFetch([
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?limit=200/, answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: PRO, state: 'READY_TO_SUBMIT' } }]) },
{ match: /^\/v2\/inAppPurchases\/i-pro\/appStoreReviewScreenshot/, answer: notFound() },
]);
const r = await capture(() => iapReview(p.ctx(['--dry'])));
expect(r.err).toContain(`1 of 2 products not in the store's list: ${GEMS} (${LAG_HINT})`);
expect(r.out).toMatch(new RegExp(`${GEMS.replace(/\./g, '\\.')}\\s+skip\\s+not in the store's list yet`));
expect(r.out).toMatch(new RegExp(`${PRO.replace(/\./g, '\\.')}\\s+upload\\s+store/iap-review/${PRO.replace(/\./g, '\\.')}\\.png \\(none in App Store Connect\\)`));
expect(r.exit).toBe(1);
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
});
test('apple iap-review --dry: every product listed exits 0', async () => {
ascEnv();
const p = project({ ...CONFIG, products: [product(PRO)] }, { [`store/iap-review/${PRO}.png`]: png() });
mockFetch([
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?limit=200/, answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: PRO, state: 'READY_TO_SUBMIT' } }]) },
{ match: /^\/v2\/inAppPurchases\/i-pro\/appStoreReviewScreenshot/, answer: notFound() },
]);
const r = await capture(() => iapReview(p.ctx(['--dry'])));
expect(r.err).not.toContain(LAG_HINT);
expect(r.exit).toBeNull();
});
test('apple iap --dry prints a plan row per product (create with type, locales and prices; update with what is missing)', async () => {
ascEnv();
const p = project({ ...CONFIG, products: [product(PRO), { ...product(GEMS), type: 'consumable', overrides: [{ region: 'TR', currency: 'TRY', price: 49.99 }] }] });
const calls = mockFetch([
{ match: /^\/v1\/territories/, answer: page([{ type: 'territories', id: 'USA' }, { type: 'territories', id: 'TUR' }]) },
{ match: new RegExp(`^/v1/apps/6400000101/inAppPurchasesV2\\?filter\\[productId\\]=${PRO}`), answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: PRO, state: 'MISSING_METADATA' } }]) },
{ match: new RegExp(`^/v1/apps/6400000101/inAppPurchasesV2\\?filter\\[productId\\]=${GEMS}`), answer: page([]) },
{ match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseLocalizations/, answer: page([]) },
{ match: /^\/v2\/inAppPurchases\/i-pro\/iapPriceSchedule/, answer: notFound() },
{ match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseAvailability/, answer: { data: { type: 'inAppPurchaseAvailabilities', id: 'av' } } },
]);
const r = await capture(() => iap(p.ctx(['--dry'])));
expect(r.out).toContain('dry run: apple iap: 2 change(s); nothing written');
expect(r.out).toMatch(/com\.example\.notes\.pro\s+update\s+localizations en-US; prices USA 2\.99 \(state MISSING_METADATA\)/);
expect(r.out).toMatch(/com\.example\.notes\.gems\s+create\s+CONSUMABLE; localizations en-US; prices USA 2\.99, TUR 49\.99; 2 territories/);
expect(r.out).toContain(`not on App Store Connect: ${GEMS}`);
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
});
test('apple iap: a product created this run but missing from the list read after it is named', async () => {
ascEnv();
process.env.STOREBOUND_LIST_SETTLE_MS = '0';
const p = project({ ...CONFIG, products: [product(GEMS)] });
const calls = mockFetch([
{ match: /^\/v1\/territories/, answer: page([{ type: 'territories', id: 'USA' }]) },
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?filter/, answer: page([]) },
{ method: 'POST', match: /^\/v2\/inAppPurchases$/, answer: { data: { type: 'inAppPurchases', id: 'i-gems', attributes: { productId: GEMS } } } },
{ match: /^\/v2\/inAppPurchases\/i-gems\/inAppPurchaseLocalizations/, answer: page([]) },
{ method: 'POST', match: /^\/v1\/inAppPurchaseLocalizations$/, answer: { data: { type: 'inAppPurchaseLocalizations', id: 'l1' } } },
{ match: /^\/v2\/inAppPurchases\/i-gems\/iapPriceSchedule/, answer: notFound() },
{ match: /^\/v2\/inAppPurchases\/i-gems\/pricePoints\?filter\[territory\]=USA/, answer: page([{ type: 'inAppPurchasePricePoints', id: 'pp-usa-299', attributes: { customerPrice: '2.99' } }]) },
{ method: 'POST', match: /^\/v1\/inAppPurchasePriceSchedules$/, answer: { data: { type: 'inAppPurchasePriceSchedules', id: 'ps' } } },
{ match: /^\/v2\/inAppPurchases\/i-gems\/inAppPurchaseAvailability/, answer: notFound() },
{ method: 'POST', match: /^\/v1\/inAppPurchaseAvailabilities$/, answer: { data: { type: 'inAppPurchaseAvailabilities', id: 'av' } } },
// the full list read right after the create does not have it yet
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?limit=200/, answer: page([]) },
]);
const r = await capture(() => iap(p.ctx([])));
expect(calls.filter(c => c.method === 'POST').map(c => c.path)).toEqual(['/v2/inAppPurchases', '/v1/inAppPurchaseLocalizations', '/v1/inAppPurchasePriceSchedules', '/v1/inAppPurchaseAvailabilities']);
expect(r.err).toContain(`1 of 1 new products not in the store's list: ${GEMS} (${LAG_HINT})`);
expect(r.out).toContain('wait a minute before apple iap-review');
expect(r.exit).toBeNull();
});
test('play products: a product created this run but missing from the list read after it is named; --dry shows the plan table', async () => {
playEnv();
const p = project({ ...CONFIG, products: [product(GEMS)] });
const API = '/androidpublisher/v3/applications/com.example.notes';
const conv = { convertedRegionPrices: { US: { regionCode: 'US', price: { currencyCode: 'USD', units: '2', nanos: 990000000 } } },
convertedOtherRegionsPrice: { usdPrice: { currencyCode: 'USD', units: '2', nanos: 990000000 }, eurPrice: { currencyCode: 'EUR', units: '2', nanos: 790000000 } }, regionVersion: { version: '2026/01' } };
const routes = () => mockFetch([
{ match: new RegExp(`^${API}/oneTimeProducts\\?`), answer: { oneTimeProducts: [] } },
{ method: 'POST', match: new RegExp(`^${API}/pricing:convertRegionPrices$`), answer: conv },
{ method: 'PATCH', match: new RegExp(`^${API}/onetimeproducts/`), answer: {} },
{ method: 'POST', match: /purchaseOptions:batchUpdateStates$/, answer: {} },
]);
routes();
let r = await capture(() => playProducts(p.ctx(['--dry'])));
expect(r.out).toMatch(/dry run: play products: 1 change\(s\); nothing written\n.*\n.*\ncom\.example\.notes\.gems\s+create\s+1 regions, 1 listings, USD 2\.99/);
expect(r.out).toContain(`not on Google Play: ${GEMS}`);
const calls = routes();
r = await capture(() => playProducts(p.ctx([])));
expect(calls.filter(c => c.method === 'PATCH')).toHaveLength(1);
expect(r.err).toContain(`1 of 1 new products not in the store's list: ${GEMS} (${LAG_HINT})`);
});
});
describe('dry runs show a plan, not a count', () => {
test('dryPlan: title with counts, kept rows left out of the table', () => {
expect(dryPlan('apple iap', [{ item: 'a', action: 'keep' }])).toBe('dry run: apple iap: nothing to change, 1 unchanged; nothing written');
expect(dryPlan('play products', [{ item: 'com.example.a', action: 'create', detail: '174 regions' }, { item: 'b', action: 'keep' }]).split('\n')).toEqual([
'dry run: play products: 1 change(s), 1 unchanged; nothing written',
'item action detail',
'------------- ------ -----------',
'com.example.a create 174 regions',
]);
});
test('the scanner flags a --dry exit after a count-only line and accepts a plan', () => {
const countOnly = ['export async function run(ctx: Ctx): Promise<void> {', ' const listing = read();',
" log('apple', `listing: ${Object.keys(listing).length} locales (${Object.keys(listing).join(', ')})`);", " if (a.has('dry')) return;", ' await write();', '}'].join('\n');
expect(countOnlyDryExits(countOnly)).toEqual([4]);
const counted = ['export async function run(): Promise<void> {', " if (dry) { done(TAG, `dry run: ${reqs.length} change(s)`); return; }", '}'].join('\n');
expect(countOnlyDryExits(counted)).toEqual([2]);
const planned = ['export async function run(): Promise<void> {', " console.log(dryPlan('apple listing', rows));", " if (dry) return;", '}'].join('\n');
expect(countOnlyDryExits(planned)).toEqual([]);
expect(isPlanLine(" log('apple', `${tag}: would upload ${file}`);")).toBe(true);
expect(isPlanLine(" log(TAG, 'would POST /v1/analyticsReportRequests {accessType=ONGOING} (dry)');")).toBe(true);
expect(isPlanLine(" done(TAG, 'dry run: nothing changed');")).toBe(false);
});
// TODO: remove each entry once its branch lands (the test fails on a stale entry).
const ALLOW: Record<string, string> = {};
test('no write command in cli/** leaves its --dry branch after printing only a count', () => {
const root = join(import.meta.dir, '..');
const flagged: string[] = [];
for (const f of [...new Glob('cli/**/*.ts').scanSync(root)].sort()) {
const lines = countOnlyDryExits(readFileSync(join(root, f), 'utf8'));
if (lines.length) flagged.push(`${f}:${lines.join(',')}`);
}
const files = flagged.map(x => x.split(':')[0]!);
expect(flagged.filter(x => !ALLOW[x.split(':')[0]!])).toEqual([]);
expect(Object.keys(ALLOW).filter(f => !files.includes(f))).toEqual([]);
});
});

View file

@ -80,12 +80,12 @@ describe('listing pull commands', () => {
let r = await capture(() => appleListing(p.ctx(['pull', '--json']))); let r = await capture(() => appleListing(p.ctx(['pull', '--json'])));
const j = jsonOut(r.out); const j = jsonOut(r.out);
expect(j).toMatchObject({ version: '1.1.0', write: false, added: [] }); expect(j).toMatchObject({ version: '1.1.0', write: false, added: [] });
expect((j.changes as { field: string }[]).map(c => c.field)).toEqual(['name', 'description', 'whatsNew']); expect((j.changes as { field: string }[]).map(c => c.field)).toEqual(['description', 'whatsNew']); // the live name equals app.name: not written into the file
expect(j.diff).toContain('-Old text.'); expect(j.diff).toContain('-Old text.');
expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toBe(APPLE_MD); expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toBe(APPLE_MD);
r = await capture(() => appleListing(p.ctx(['pull', '--write']))); r = await capture(() => appleListing(p.ctx(['pull', '--write'])));
expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toContain('### whatsNew\n```\nFaster sync.\n```'); expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toContain('### whatsNew\n```\nFaster sync.\n```');
expect(r.out).toContain('3 change(s) written'); expect(r.out).toContain('2 change(s) written');
}); });
test('play listing pull: one read-only edit, deleted; --write updates the file', async () => { test('play listing pull: one read-only edit, deleted; --write updates the file', async () => {
playEnv(); playEnv();