Merge remote-tracking branch 'origin/main' into play-app-record
# Conflicts: # CHANGELOG.md # docs/pitfalls.md # skills/store-pitfalls/SKILL.md # tests/console-fill.test.ts
This commit is contained in:
commit
04fb0089b5
70 changed files with 3729 additions and 290 deletions
|
|
@ -1,5 +1,7 @@
|
||||||
# bun run ci on every push to main and every pull request into main: adapters, desktop version, tests, typecheck,
|
# bun run ci on every push to main and every pull request into main: adapters, desktop version, tests, typecheck,
|
||||||
# desktop i18n / typecheck / build, desktop boot check (headless Chromium), desktop Rust tests and clippy, scrub. Runs on the VDS runner (docs/desktop-release.md).
|
# desktop i18n / typecheck / build, desktop boot check (headless Chromium), desktop Rust tests and clippy, scrub. Runs on the VDS runner (docs/desktop-release.md).
|
||||||
|
# tools/ci.ts runs the steps as a task graph and the tests as parallel shards (CPU cores - 1, max 8) on the one
|
||||||
|
# self-hosted runner, so a job matrix would only queue; CI=full makes it run the Rust steps on every push.
|
||||||
# Publishes nothing: site/ is still published by Jenkins.
|
# Publishes nothing: site/ is still published by Jenkins.
|
||||||
name: ci
|
name: ci
|
||||||
|
|
||||||
|
|
@ -14,6 +16,7 @@ env:
|
||||||
BUN_VERSION: '1.4.0'
|
BUN_VERSION: '1.4.0'
|
||||||
CARGO_TERM_COLOR: never
|
CARGO_TERM_COLOR: never
|
||||||
CARGO_INCREMENTAL: '0'
|
CARGO_INCREMENTAL: '0'
|
||||||
|
CI: full
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
ci:
|
ci:
|
||||||
|
|
@ -40,6 +43,12 @@ jobs:
|
||||||
apps/desktop/src-tauri/target
|
apps/desktop/src-tauri/target
|
||||||
key: ci-${{ runner.os }}-${{ hashFiles('bun.lock', 'apps/desktop/src-tauri/Cargo.lock') }}
|
key: ci-${{ runner.os }}-${{ hashFiles('bun.lock', 'apps/desktop/src-tauri/Cargo.lock') }}
|
||||||
restore-keys: ci-${{ runner.os }}-
|
restore-keys: ci-${{ runner.os }}-
|
||||||
|
# recorded test durations (shard balance) and tsc's incremental build info
|
||||||
|
- uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: node_modules/.cache/storebound-ci
|
||||||
|
key: ci-timings-${{ runner.os }}-${{ github.sha }}
|
||||||
|
restore-keys: ci-timings-${{ runner.os }}-
|
||||||
- name: Bun and Rust
|
- name: Bun and Rust
|
||||||
run: |
|
run: |
|
||||||
P="${FORGEJO_PATH:-$GITHUB_PATH}"
|
P="${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||||
|
|
|
||||||
|
|
@ -86,5 +86,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
||||||
## Working on storebound itself
|
## Working on storebound itself
|
||||||
|
|
||||||
- Bun + TypeScript strict, zero runtime dependencies. `bun run ci` must pass (adapters fresh, tests, typecheck, scrub).
|
- Bun + TypeScript strict, zero runtime dependencies. `bun run ci` must pass (adapters fresh, tests, typecheck, scrub).
|
||||||
|
- Inner loop: `bun run ci:quick` (typecheck, the tests related to your change against origin/main, scrub; seconds).
|
||||||
|
Before every push: the full `bun run ci` (every check and test, in parallel shards), and check its exit code.
|
||||||
- Skills are the single source: edit `skills/*/SKILL.md` or `docs/agents-core.md`, then `bun tools/gen-adapters.ts`.
|
- Skills are the single source: edit `skills/*/SKILL.md` or `docs/agents-core.md`, then `bun tools/gen-adapters.ts`.
|
||||||
- Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com.
|
- Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com.
|
||||||
|
|
|
||||||
49
CHANGELOG.md
49
CHANGELOG.md
|
|
@ -38,6 +38,43 @@
|
||||||
`agreement` field is outlined whatever its answer). The log and guidance say the package name is set by the first
|
`agreement` field is outlined whatever its answer). The log and guidance say the package name is set by the first
|
||||||
AAB upload (`play upload --track internal` / `flow run release`).
|
AAB upload (`play upload --track internal` / `flow run release`).
|
||||||
- In `--dry`, the `console fill` list, the MCP / desktop form list and the desktop App info "Play Console forms" card.
|
- In `--dry`, the `console fill` list, the MCP / desktop form list and the desktop App info "Play Console forms" card.
|
||||||
|
- Faster CI: `bun run ci` runs as a task graph (independent steps at once, `[step]`-prefixed output, fail fast, time
|
||||||
|
per step) with the tests split into parallel shards (CPU cores - 1, max 8) balanced by recorded durations, browser
|
||||||
|
suites in shards of their own. New `bun run ci:quick` for the inner loop: typecheck plus the tests related to the
|
||||||
|
change against origin/main (through imports) plus scrub. The desktop Rust host runs only when `src-tauri` or the
|
||||||
|
sidecar build changed (`CI=full` always; Forgejo CI sets it). Fixed sleeps in tests became event waits.
|
||||||
|
- ASO from official and public data only (no scraping, no third-party ASO services):
|
||||||
|
- `aso competitors [--term <kw>] [--storefront us,tr] [--top 10]`: per keyword of the locale's keyword field (and
|
||||||
|
`--term`) the top apps in the iTunes Search API (name, developer, rating count, first release, last update, genre
|
||||||
|
localized to the storefront), the words in their names that the name / subtitle / keywords do not cover (only
|
||||||
|
words of two or more developers: a one-developer word is likely a brand) and the apps new in a term's top N since
|
||||||
|
the last snapshot (`.storebound/aso/competitors/<date>.json`). Same pace as `aso rank` (one call every 3.5 s, stop
|
||||||
|
on 403 / 429). Competitor subtitles are not in any public API and are not shown.
|
||||||
|
- `aso suggest [--locale] [--fresh] [--offline] [--write]`: keyword candidates from the own name / subtitle /
|
||||||
|
description (words and two-word phrases), competitor names, the localized category names (from the Search API's
|
||||||
|
`genres`) and, with Apple Ads credentials, the Apple Ads Platform API keyword suggestions
|
||||||
|
(`POST /v1/suggestions/keywords/query`, relative popularity 0-100). Each candidate shows relevance (own text,
|
||||||
|
competitor names), competition (top apps with the word in their name) and popularity (Apple Ads only, else
|
||||||
|
"unknown"). Proposes a keyword field per locale that fits 100 bytes with the existing rules (no spaces, no
|
||||||
|
duplicates, plural-insensitive, no name / subtitle words, no filler or category words; current terms kept first
|
||||||
|
unless `--fresh`) as old -> new; `--write` puts it into `store/appstore.md` with a draft line that `check --aso` and
|
||||||
|
`aso audit` report until the owner deletes it.
|
||||||
|
- `aso audit`: one offline report: `check --aso` findings, the cross-locale free keyword room, rank trend arrows from
|
||||||
|
the `aso rank` snapshots, competitor coverage gaps, Play short description use and keyword density, App Store
|
||||||
|
conversion from the analytics snapshots, Product Page Optimization / Play listing experiment ideas (suggestions
|
||||||
|
only: PPO cannot test the subtitle; Play experiments stay in Play Console) and the next 3 actions.
|
||||||
|
- MCP: read-only `aso_competitors` (saves no snapshot), `aso_suggest` (never writes), `aso_audit` (offline).
|
||||||
|
- Desktop: an ASO card on the Growth tab (`aso.audit`): keyword field state, keywords ranked, coverage gaps, the
|
||||||
|
rank trend of the best three keywords (visx, rank 1 at the top), the rank table and the next 3 actions.
|
||||||
|
- `examples/demo-app` has listing files (`store/appstore.md`, `store/listing.md`) to try the ASO commands on.
|
||||||
|
- Local font files in `shots.fonts`: `title`, `body` and `fallback[]` take, besides a Google Fonts family, a path
|
||||||
|
(relative to the config) or `{ family, file, weight?, style?, license? }` (TTF / OTF / WOFF / WOFF2, validated by
|
||||||
|
extension and signature; the family comes from the name table when not given). `shots fonts` checks the file's cmap
|
||||||
|
per language, tries the listed fallbacks in order before the automatic Noto ones (`pl title: ę ł ą Ł not in ER
|
||||||
|
Display -> Noto Sans Display`), errors when nothing covers a character, and records the file in fonts.json with its
|
||||||
|
path, sha256 and license. Render and `shots video` serve it in place at `/fonts/local/...` (never copied); the hash
|
||||||
|
in fonts.css invalidates the capture cache, and render refuses a font file changed since `shots fonts`. `shots check`
|
||||||
|
treats the local font and listed fallbacks as configured and warns when a local font has no license note.
|
||||||
- Idempotency: every store write is an upsert; running a command twice, or again after a crash or a lost answer,
|
- Idempotency: every store write is an upsert; running a command twice, or again after a crash or a lost answer,
|
||||||
leaves exactly one of each thing (table of every write path: `docs/idempotency.md`).
|
leaves exactly one of each thing (table of every write path: `docs/idempotency.md`).
|
||||||
- New `cli/lib/upsert.ts`: `findOrCreate` looks again with a fresh GET right before a create and asks a journal of
|
- New `cli/lib/upsert.ts`: `findOrCreate` looks again with a fresh GET right before a create and asks a journal of
|
||||||
|
|
@ -70,6 +107,18 @@
|
||||||
with zero writes on the second run, a crash in the middle of a screenshot set, IAP and subscription creates whose
|
with zero writes on the second run, a crash in the middle of a screenshot set, IAP and subscription creates whose
|
||||||
answer is lost, 409 duplicates, the list lag after a crash, Play edit error paths and an unclear commit, the lock.
|
answer is lost, 409 duplicates, the list lag after a crash, Play edit error paths and an unclear commit, the lock.
|
||||||
Pitfall 9 in `docs/pitfalls.md` and the store-pitfalls skill.
|
Pitfall 9 in `docs/pitfalls.md` and the store-pitfalls skill.
|
||||||
|
- The last open rows are closed (`docs/idempotency.md` has none left):
|
||||||
|
- `apple listing`: the App Store version is created through `findOrCreate` (a fresh look right before the create,
|
||||||
|
the journal for the list lag, a lost answer looks first); localizations through `createOnce` (409 = found, then
|
||||||
|
only the differing fields are PATCHed); unchanged localizations and an attached build are left alone.
|
||||||
|
- `play listing`: compares again inside the write edit and PUTs only differing details and languages; nothing left
|
||||||
|
to change = the edit is deleted, not committed.
|
||||||
|
- `apple appinfo`: categories, age rating, content rights compared with the live values, only differences PATCHed.
|
||||||
|
- `play data-safety`: Play cannot read the form back, so the sha256 of the last uploaded CSV is kept in
|
||||||
|
`.storebound/data-safety.sha256`; the same CSV is not sent again unless `--force` (MCP `force`).
|
||||||
|
- Twice-run tests for `apple listing` (plus a lost version create and a 409 localization), `play listing` (plus a
|
||||||
|
store that became current before the edit), `apple appinfo`, `play data-safety`, `apple promoted`,
|
||||||
|
`apple win-back`, `apple preorder`, `apple testflight testers`, `play upload` and `prices import` (Play).
|
||||||
|
|
||||||
- Faster `shots capture` (web) and `shots render` (a 22-language game took about 50 min to capture, serially, with a
|
- 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):
|
new context and a full game boot per frame):
|
||||||
|
|
|
||||||
|
|
@ -7,9 +7,25 @@ but fixes, store rule updates and new engines / AI tools are very welcome.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
bun install # Bun 1.1+; playwright is a dev dependency (renders, web capture)
|
bun install # Bun 1.1+; playwright is a dev dependency (renders, web capture)
|
||||||
bun run ci # adapters fresh, tests, typecheck, secrets / personal data scrub
|
bun run ci:quick # inner loop: typecheck + the tests your change touches + scrub (seconds)
|
||||||
|
bun run ci # full gate before pushing: every check and test (adapters, API tables, typecheck,
|
||||||
|
# desktop build and boot check, Rust host when it changed, scrub)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Which one when.** Run `bun run ci:quick` while you work: it diffs against `origin/main` (committed, staged,
|
||||||
|
unstaged and new files), maps the changed files to the tests that import them (directly, through other modules, or
|
||||||
|
by naming a fixture or page) and runs those, plus `tsc` (incremental) and the scrub. A change to `package.json`,
|
||||||
|
`bun.lock`, `bunfig.toml`, `tsconfig.json` or the test preload runs every test. Run the full `bun run ci` before every
|
||||||
|
push and check its exit code: it is the gate, `ci:quick` is not.
|
||||||
|
|
||||||
|
`tools/ci.ts` runs the steps as a task graph (independent steps at the same time, output prefixed with the step
|
||||||
|
name, the first failure stops the rest, a time-per-step summary at the end). The tests run as parallel shards
|
||||||
|
(CPU cores - 1, at most 8; `STOREBOUND_CI_SHARDS=n` overrides) balanced by the durations of the last run, kept in
|
||||||
|
`node_modules/.cache/storebound-ci/`; the browser suites get a shard each. So tests must be shard-safe: temp folders
|
||||||
|
from `mkdtempSync`, servers on port 0, no fixed sleeps (wait for the event), no state shared through files in the
|
||||||
|
checkout. The desktop Rust host (`cargo test`, `clippy`) runs only when `apps/desktop/src-tauri/` or
|
||||||
|
`tools/build-sidecars.ts` changed against `origin/main`; `CI=full bun run ci` always runs it (Forgejo CI does).
|
||||||
|
|
||||||
Try the screenshot and video pipeline on the demo game without any store account: see
|
Try the screenshot and video pipeline on the demo game without any store account: see
|
||||||
[examples/demo-game/README.md](examples/demo-game/README.md).
|
[examples/demo-game/README.md](examples/demo-game/README.md).
|
||||||
|
|
||||||
|
|
|
||||||
26
README.md
26
README.md
|
|
@ -422,6 +422,9 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
||||||
| `reports apple-sales \| apple-finance \| play-earnings \| play-sales` | API, read-only + local | sales / finance reports into `.storebound/reports/`, summary per product and currency, CSV export |
|
| `reports apple-sales \| apple-finance \| play-earnings \| play-sales` | API, read-only + local | sales / finance reports into `.storebound/reports/`, summary per product and currency, CSV export |
|
||||||
| `triage [--days 14]` | API, read-only | TestFlight crash and screenshot feedback, Play error reports: grouped by signature with devices, OS versions, builds |
|
| `triage [--days 14]` | API, read-only | TestFlight crash and screenshot feedback, Play error reports: grouped by signature with devices, OS versions, builds |
|
||||||
| `aso rank [--storefronts us,de]` | network + local | App Store rank per keyword and storefront plus competitors from the public iTunes Search API (rate limited) -> `.storebound/aso/` |
|
| `aso rank [--storefronts us,de]` | network + local | App Store rank per keyword and storefront plus competitors from the public iTunes Search API (rate limited) -> `.storebound/aso/` |
|
||||||
|
| `aso competitors [--term <kw>] [--storefront us,tr] [--top 10]` | network + local | top apps per keyword (name, developer, rating count, first release, last update, localized genre; no subtitles: not in any public API) and the words in their names you do not cover, same rate limit -> `.storebound/aso/competitors/` |
|
||||||
|
| `aso suggest [--locale en-US] [--write]` | local (+ Apple Ads API with credentials) | keyword candidates (own text, competitor names, localized category names, Apple Ads keyword suggestions with their relative 0-100 popularity) scored by relevance and competition, and a 100-byte keyword field per locale as a diff; `--write` puts it into `store/appstore.md` as a draft for review. Popularity is never estimated |
|
||||||
|
| `aso audit` | local | one report: `check --aso`, free keyword room, rank trend arrows, competitor gaps, Play short description and density, App Store conversion from the analytics snapshots, PPO / Play experiment ideas and the next 3 actions |
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|
@ -431,7 +434,7 @@ 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] [--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 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 ...), your own local font files, and the glyph coverage check per language |
|
||||||
| `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 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 |
|
||||||
|
|
@ -735,6 +738,23 @@ languages, every store size, a review gallery and an app preview video. No store
|
||||||
Some display fonts lack Latin Extended: Lilita One has no ş ğ İ ą ę ń ś ź ż ć ă ș ț č ř ě ů ő ű or Vietnamese,
|
Some display fonts lack Latin Extended: Lilita One has no ş ğ İ ą ę ń ś ź ż ć ă ș ț č ř ě ů ő ű or Vietnamese,
|
||||||
so Turkish, Polish, Czech, Romanian, Hungarian or Vietnamese titles need another title font (Paytone One, Baloo 2,
|
so Turkish, Polish, Czech, Romanian, Hungarian or Vietnamese titles need another title font (Paytone One, Baloo 2,
|
||||||
Rowdies) or `fonts: { ..., fallback: ['Noto Sans Display'] }` to accept the mixed glyphs.
|
Rowdies) or `fonts: { ..., fallback: ['Noto Sans Display'] }` to accept the mixed glyphs.
|
||||||
|
|
||||||
|
**Your own brand font.** `shots.fonts.title` / `body` / `fallback[]` also take a local file (relative to the
|
||||||
|
config; TTF, OTF, WOFF or WOFF2, checked by extension and signature) or `{ family, file, weight?, style?, license? }`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
fonts: {
|
||||||
|
title: { family: 'ER Display', file: 'apps/game/public/assets/fonts/er-display.woff2', license: 'OFL-1.1' },
|
||||||
|
body: 'Montserrat',
|
||||||
|
fallback: ['Noto Sans Display'], // tried in order, before the automatic Noto fallbacks
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
`shots fonts` runs the same cmap check on the file (`pl title: ę ł ą Ł not in ER Display -> Noto Sans Display`),
|
||||||
|
prints its size, glyph count, sha256 and license, and records it in `fonts.json`. The file is never copied: render
|
||||||
|
(and `shots video` captions) serve it from where it is, and a changed file changes `fonts.css` (the capture cache
|
||||||
|
misses) and makes `shots render` ask for `shots fonts` again. `shots check` counts the local font and listed
|
||||||
|
fallbacks as configured, not as fallbacks, and warns when a local font has no `license` note.
|
||||||
3. **Render.** Every store size at exact pixels: iPhone 6.9" and 6.5", 13" iPad (if your app runs on iPad), Play
|
3. **Render.** Every store size at exact pixels: iPhone 6.9" and 6.5", 13" iPad (if your app runs on iPad), Play
|
||||||
phone, 7" and 10" tablets, the 1024 x 500 feature graphic. 24-bit RGB, no alpha (both stores reject it).
|
phone, 7" and 10" tablets, the 1024 x 500 feature graphic. 24-bit RGB, no alpha (both stores reject it).
|
||||||
4. **Check and review.** `shots check` applies the store rules locally (sources cited in `cli/shots/spec.ts`);
|
4. **Check and review.** `shots check` applies the store rules locally (sources cited in `cli/shots/spec.ts`);
|
||||||
|
|
@ -766,7 +786,7 @@ navigation.
|
||||||
| `store-subscriptions` | subscription groups, levels, base plans, prices, intro and promotional offers, offer codes, disclosure and Terms (3.1.2), first submission |
|
| `store-subscriptions` | subscription groups, levels, base plans, prices, intro and promotional offers, offer codes, disclosure and Terms (3.1.2), first submission |
|
||||||
| `review-access` | demo account for reviewers (App Review fields, Play App access), never committed |
|
| `review-access` | demo account for reviewers (App Review fields, Play App access), never committed |
|
||||||
| `account-deletion` | Apple 5.1.1(v) in-app deletion, Play delete-account web page and Data safety |
|
| `account-deletion` | Apple 5.1.1(v) in-app deletion, Play delete-account web page and Data safety |
|
||||||
| `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing, keyword ranks via the iTunes Search API |
|
| `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing, keyword ranks, competitors, keyword field proposals and the ASO audit (iTunes Search API, Apple Ads popularity with credentials) |
|
||||||
| `app-store-promotion` | IAP offer codes, win-back offers, promoted IAPs, pre-orders (Play pre-registration: console guide), custom product pages, in-app events |
|
| `app-store-promotion` | IAP offer codes, win-back offers, promoted IAPs, pre-orders (Play pre-registration: console guide), custom product pages, in-app events |
|
||||||
| `store-declarations` | every questionnaire: Play Data safety (API) and App content (IARC, target audience, ads, advertising ID, app access, government / financial / health), Apple App Privacy labels and age rating |
|
| `store-declarations` | every questionnaire: Play Data safety (API) and App content (IARC, target audience, ads, advertising ID, app access, government / financial / health), Apple App Privacy labels and age rating |
|
||||||
| `export-compliance` | encryption answer, Info.plist key, declarations; never exempt by default |
|
| `export-compliance` | encryption answer, Info.plist key, declarations; never exempt by default |
|
||||||
|
|
@ -797,7 +817,7 @@ per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same proc
|
||||||
`initialize` (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). It runs each tool as a CLI call in the project directory
|
`initialize` (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). It runs each tool as a CLI call in the project directory
|
||||||
(the server's working directory, or `STOREBOUND_PROJECT`) and returns the output.
|
(the server's working directory, or `STOREBOUND_PROJECT`) and returns the output.
|
||||||
|
|
||||||
- One tool per command. Read-only: `scan`, `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`,
|
- One tool per command. Read-only: `scan`, `check`, `check_aso`, `aso_competitors` (no snapshot saved), `aso_suggest` (never writes), `aso_audit`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`,
|
||||||
`analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`,
|
`analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`,
|
||||||
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `workspace_list`, `workspace_status`,
|
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `workspace_list`, `workspace_status`,
|
||||||
`release_status`, `release_plan`, `flow_list`, `flow_run` (dry mode only), `listing_check`. Local writes: `import_fastlane`, `whats_new`, `listing_translate`, `icons`,
|
`release_status`, `release_plan`, `flow_list`, `flow_run` (dry mode only), `listing_check`. Local writes: `import_fastlane`, `whats_new`, `listing_translate`, `icons`,
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import type { Overrides } from './lib/identity';
|
||||||
export type {
|
export type {
|
||||||
AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult,
|
AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult,
|
||||||
ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult,
|
ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult,
|
||||||
AnalyticsCompare, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult,
|
AnalyticsCompare, AsoAuditView, AsoTrendRow, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult,
|
||||||
} from '../../../cli/lib/desktop-protocol';
|
} from '../../../cli/lib/desktop-protocol';
|
||||||
|
|
||||||
export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null }
|
export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null }
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
// DEV-ONLY FIXTURE DATA for the screens that cover the rest of the CLI (prices, store art, growth, app info). Made-up
|
// DEV-ONLY FIXTURE DATA for the screens that cover the rest of the CLI (prices, store art, growth, app info). Made-up
|
||||||
// numbers around the two demo apps; drawn SVG stand-ins for the rendered screenshots. Only src/dev/fixtures.ts imports
|
// numbers around the two demo apps; drawn SVG stand-ins for the rendered screenshots. Only src/dev/fixtures.ts imports
|
||||||
// this module, and only fixture mode (dev builds) loads that.
|
// this module, and only fixture mode (dev builds) loads that.
|
||||||
import type { AnalyticsCompare, DeclarationsResult, ListingText, PpoStatus, PriceRowData, PricesCurrent, PricesDiff, RendersResult, RenderTile } from '../api';
|
import type { AnalyticsCompare, AsoAuditView, DeclarationsResult, ListingText, PpoStatus, PriceRowData, PricesCurrent, PricesDiff, RendersResult, RenderTile } from '../api';
|
||||||
|
|
||||||
const HOME = '/home/you';
|
const HOME = '/home/you';
|
||||||
const NOW = Date.now();
|
const NOW = Date.now();
|
||||||
|
|
@ -200,3 +200,38 @@ function analytics(days: number, seed: number): AnalyticsCompare {
|
||||||
return { snapshots: Math.ceil(days / 28) + 1, since: day(days), series: { apple, play }, effects };
|
return { snapshots: Math.ceil(days / 28) + 1, since: day(days), series: { apple, play }, effects };
|
||||||
}
|
}
|
||||||
export const ANALYTICS: Record<string, AnalyticsCompare | null> = { 'p-prism': analytics(56, 1), 'p-tidy': null };
|
export const ANALYTICS: Record<string, AnalyticsCompare | null> = { 'p-prism': analytics(56, 1), 'p-tidy': null };
|
||||||
|
|
||||||
|
// ---- aso.audit: `aso audit --json` of the demo apps (made up: four rank snapshots two weeks apart) ----
|
||||||
|
function asoAudit(withRanks: boolean): AsoAuditView {
|
||||||
|
const dates = [day(42), day(28), day(14), day(0)];
|
||||||
|
const series = [
|
||||||
|
{ storefront: 'us', keyword: 'match', ranks: [48, 39, 31, 24] },
|
||||||
|
{ storefront: 'us', keyword: 'puzzle', ranks: [88, 92, 71, 66] },
|
||||||
|
{ storefront: 'us', keyword: 'tiles', ranks: [null, 140, 118, 121] },
|
||||||
|
{ storefront: 'us', keyword: 'offline', ranks: [null, null, null, null] },
|
||||||
|
];
|
||||||
|
const rows = series.map(x => {
|
||||||
|
const rank = x.ranks.at(-1) ?? null, previous = x.ranks.at(-2) ?? null;
|
||||||
|
const known = x.ranks.filter((v): v is number => v !== null);
|
||||||
|
return { storefront: x.storefront, keyword: x.keyword, rank, previous, change: rank !== null && previous !== null ? previous - rank : null,
|
||||||
|
arrow: rank === null ? '·' as const : previous === null ? 'new' as const : rank < previous ? '↑' as const : rank > previous ? '↓' as const : '→' as const,
|
||||||
|
best: known.length ? Math.min(...known) : null, snapshots: x.ranks.length };
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
generated: day(0),
|
||||||
|
keywordField: { errors: 0, warnings: 1, hints: 2, findings: [{ level: 'warn', where: 'apple en-US', msg: 'keywords: 71/100 bytes used; fill at least 90 (29 bytes free)' }] },
|
||||||
|
drafts: [],
|
||||||
|
ranks: withRanks ? { snapshots: 4, latest: day(0), rows, dates, series } : { snapshots: 0, latest: null, rows: [], dates: [], series: [] },
|
||||||
|
competitors: withRanks ? { date: day(3), gaps: [{ storefront: 'us', locale: 'en-US', gaps: [{ word: 'blast', apps: 4, developers: 3 }, { word: 'block', apps: 3, developers: 3 }] }] } : { date: null, gaps: [] },
|
||||||
|
experiments: [{ store: 'apple', what: 'first screenshot caption', why: 'the first screenshot is what search results show', how: 'storebound apple ppo create --variant b --dry' }],
|
||||||
|
next: withRanks ? [
|
||||||
|
{ what: 'fill the keyword field of en-US (71/100 bytes used)', why: 'unused bytes are unused search reach', command: 'storebound aso suggest --locale en-US' },
|
||||||
|
{ what: 'consider "blast", "block" for en-US (in the names of 3 developers\' top apps)', why: 'words the top apps lead with; only if they describe your app', command: 'storebound aso suggest --locale en-US' },
|
||||||
|
{ what: 'look at the keywords that dropped: us "tiles" 118 -> 121', why: 'a drop after a listing change is the signal to revert or adjust it' },
|
||||||
|
] : [
|
||||||
|
{ what: 'take a first rank snapshot', why: 'trends need a baseline before the next listing change', command: 'storebound aso rank --dry, then storebound aso rank' },
|
||||||
|
{ what: 'read the competitors for your keywords', why: 'coverage gaps and suggest need the top apps per term', command: 'storebound aso competitors --dry, then storebound aso competitors' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export const ASO: Record<string, AsoAuditView> = { 'p-prism': asoAudit(true), 'p-tidy': asoAudit(false) };
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import { type Account, type AccountCheck, type ConsoleFillResult, type ConsoleFo
|
||||||
type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api';
|
type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api';
|
||||||
import { buildApps, type Overrides } from '../lib/identity';
|
import { buildApps, type Overrides } from '../lib/identity';
|
||||||
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model';
|
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model';
|
||||||
import { ANALYTICS, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more';
|
import { ANALYTICS, ASO, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more';
|
||||||
|
|
||||||
export const FIXTURE_MARKER = 'storebound-dev-fixtures';
|
export const FIXTURE_MARKER = 'storebound-dev-fixtures';
|
||||||
|
|
||||||
|
|
@ -438,6 +438,7 @@ function read(method: string, id: string, args: Record<string, unknown> = {}): T
|
||||||
case 'prices.diff': return ok(method, PRICE_DIFF[id]);
|
case 'prices.diff': return ok(method, PRICE_DIFF[id]);
|
||||||
case 'apple.ppo_status': return ok(method, PPO[id]);
|
case 'apple.ppo_status': return ok(method, PPO[id]);
|
||||||
case 'analytics.compare': return ANALYTICS[id] ? ok(method, ANALYTICS[id]) : { method, ok: false, exitCode: 1, dryRun: false, command: 'storebound analytics compare --json', output: `error: no snapshots in ${HOME}/apps/tidy-lists/.storebound/analytics (storebound analytics snapshot)` };
|
case 'analytics.compare': return ANALYTICS[id] ? ok(method, ANALYTICS[id]) : { method, ok: false, exitCode: 1, dryRun: false, command: 'storebound analytics compare --json', output: `error: no snapshots in ${HOME}/apps/tidy-lists/.storebound/analytics (storebound analytics snapshot)` };
|
||||||
|
case 'aso.audit': return ASO[id] ? ok(method, ASO[id]) : { method, ok: false, exitCode: 1, dryRun: false, command: 'storebound aso audit --json', output: 'fixture: no data for aso.audit' };
|
||||||
case 'check': return { method, ok: true, exitCode: 0, dryRun: false, command: 'storebound check', output: '12:00:01 [check] config ok: storebound.config.ts\n12:00:01 [check] listing: 4 languages\n12:00:01 [check] 0 problems, 2 warnings' };
|
case 'check': return { method, ok: true, exitCode: 0, dryRun: false, command: 'storebound check', output: '12:00:01 [check] config ok: storebound.config.ts\n12:00:01 [check] listing: 4 languages\n12:00:01 [check] 0 problems, 2 warnings' };
|
||||||
default: return { method, ok: false, exitCode: 1, dryRun: false, command: `storebound ${method}`, output: `fixture: no data for ${method}` };
|
default: return { method, ok: false, exitCode: 1, dryRun: false, command: `storebound ${method}`, output: `fixture: no data for ${method}` };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1068,6 +1068,29 @@ export const en = {
|
||||||
'gr.before': 'Before',
|
'gr.before': 'Before',
|
||||||
'gr.after': 'After',
|
'gr.after': 'After',
|
||||||
'gr.reading': 'A change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too.',
|
'gr.reading': 'A change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too.',
|
||||||
|
'gr.aso': 'ASO',
|
||||||
|
'gr.asoSub': 'aso audit, offline, {date}',
|
||||||
|
'gr.asoSubNone': 'Keyword field, rank trend and next steps from the app folder (aso audit, offline)',
|
||||||
|
'gr.asoField': 'Keyword field',
|
||||||
|
'gr.asoFieldSub': 'check --aso over store/appstore.md',
|
||||||
|
'gr.asoErrors': '{count} errors',
|
||||||
|
'gr.asoErrors_one': '1 error',
|
||||||
|
'gr.asoWarnings': '{count} warnings',
|
||||||
|
'gr.asoWarnings_one': '1 warning',
|
||||||
|
'gr.asoDrafts': 'Draft keywords to review: {locales}',
|
||||||
|
'gr.asoRanked': 'Keywords ranked',
|
||||||
|
'gr.asoLatest': 'In the first 200 results · {date}',
|
||||||
|
'gr.asoNoRanks': 'No rank snapshot yet: storebound aso rank',
|
||||||
|
'gr.asoGaps': 'Coverage gaps',
|
||||||
|
'gr.asoGapsSub': 'Words in top apps\' names you do not cover · {date}',
|
||||||
|
'gr.asoNoCompetitors': 'No competitor snapshot yet: storebound aso competitors',
|
||||||
|
'gr.asoChartAria': 'Keyword ranks over the rank snapshots, rank 1 at the top',
|
||||||
|
'gr.asoNotRanked': 'not ranked',
|
||||||
|
'gr.asoKeyword': 'Keyword',
|
||||||
|
'gr.asoRank': 'Rank',
|
||||||
|
'gr.asoBest': 'Best',
|
||||||
|
'gr.asoNext': 'Next 3 actions',
|
||||||
|
'gr.asoReading': 'Ranks follow the public iTunes Search API order, which is close to, not equal to, App Store search: read them as a trend. Popularity comes only from Apple Ads (aso suggest with an Apple Ads API key), never estimated.',
|
||||||
'gr.ppo': 'Product Page Optimization',
|
'gr.ppo': 'Product Page Optimization',
|
||||||
'gr.ppoSub': 'App Store A/B tests of the screenshots',
|
'gr.ppoSub': 'App Store A/B tests of the screenshots',
|
||||||
'gr.ppoRead': 'Read tests',
|
'gr.ppoRead': 'Read tests',
|
||||||
|
|
|
||||||
|
|
@ -1070,6 +1070,29 @@ export const tr: Record<keyof typeof en, string> = {
|
||||||
'gr.before': 'Önce',
|
'gr.before': 'Önce',
|
||||||
'gr.after': 'Sonra',
|
'gr.after': 'Sonra',
|
||||||
'gr.reading': 'Bir değişiklik iki tarafta da birkaç gün ve yeterli trafik ister; mevsim, öne çıkarılma ve reklamlar da bu sayıları oynatır.',
|
'gr.reading': 'Bir değişiklik iki tarafta da birkaç gün ve yeterli trafik ister; mevsim, öne çıkarılma ve reklamlar da bu sayıları oynatır.',
|
||||||
|
'gr.aso': 'ASO',
|
||||||
|
'gr.asoSub': 'aso audit, çevrimdışı, {date}',
|
||||||
|
'gr.asoSubNone': 'Uygulama klasöründen anahtar kelime alanı, sıralama eğilimi ve sonraki adımlar (aso audit, çevrimdışı)',
|
||||||
|
'gr.asoField': 'Anahtar kelime alanı',
|
||||||
|
'gr.asoFieldSub': 'store/appstore.md üzerinde check --aso',
|
||||||
|
'gr.asoErrors': '{count} hata',
|
||||||
|
'gr.asoErrors_one': '1 hata',
|
||||||
|
'gr.asoWarnings': '{count} uyarı',
|
||||||
|
'gr.asoWarnings_one': '1 uyarı',
|
||||||
|
'gr.asoDrafts': 'Gözden geçirilecek taslak kelimeler: {locales}',
|
||||||
|
'gr.asoRanked': 'Sıralanan kelimeler',
|
||||||
|
'gr.asoLatest': 'İlk 200 sonuçta · {date}',
|
||||||
|
'gr.asoNoRanks': 'Henüz sıralama anlık görüntüsü yok: storebound aso rank',
|
||||||
|
'gr.asoGaps': 'Kapsama boşlukları',
|
||||||
|
'gr.asoGapsSub': 'Üst sıradaki uygulamaların adlarında olup sende olmayan kelimeler · {date}',
|
||||||
|
'gr.asoNoCompetitors': 'Henüz rakip anlık görüntüsü yok: storebound aso competitors',
|
||||||
|
'gr.asoChartAria': 'Sıralama anlık görüntülerine göre anahtar kelime sıraları, 1. sıra en üstte',
|
||||||
|
'gr.asoNotRanked': 'sırada değil',
|
||||||
|
'gr.asoKeyword': 'Anahtar kelime',
|
||||||
|
'gr.asoRank': 'Sıra',
|
||||||
|
'gr.asoBest': 'En iyi',
|
||||||
|
'gr.asoNext': 'Sonraki 3 adım',
|
||||||
|
'gr.asoReading': 'Sıralar herkese açık iTunes Search API sırasını izler; bu App Store aramasına yakındır ama aynı değildir: eğilim olarak oku. Popülerlik yalnızca Apple Ads\'ten gelir (Apple Ads API anahtarıyla aso suggest), asla tahmin edilmez.',
|
||||||
'gr.ppo': 'Ürün Sayfası Optimizasyonu',
|
'gr.ppo': 'Ürün Sayfası Optimizasyonu',
|
||||||
'gr.ppoSub': 'Ekran görüntülerinin App Store A/B testleri',
|
'gr.ppoSub': 'Ekran görüntülerinin App Store A/B testleri',
|
||||||
'gr.ppoRead': 'Testleri oku',
|
'gr.ppoRead': 'Testleri oku',
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
// Growth: store analytics snapshots against the listing changes from git (`analytics compare --json`, offline; a new
|
// Growth: store analytics snapshots against the listing changes from git (`analytics compare --json`, offline; a new
|
||||||
// snapshot and the App Store report request are confirm-gated writes), App Store Product Page Optimization tests
|
// snapshot and the App Store report request are confirm-gated writes), App Store Product Page Optimization tests
|
||||||
// (status read; create and upload treatments: dry run, dialog, real run; start / stop are owner actions with their
|
// (status read; create and upload treatments: dry run, dialog, real run; start / stop are owner actions with their
|
||||||
// own dialog, never MCP tools), and Google Play store listing experiments (no API: Play Console).
|
// own dialog, never MCP tools), Google Play store listing experiments (no API: Play Console), and the ASO card
|
||||||
|
// (`aso audit --json`, offline: keyword field findings, rank trend from the `aso rank` snapshots, the next 3 actions).
|
||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { type AnalyticsCompare, api, type PpoStatus, type PpoTest } from '../../api';
|
import { type AnalyticsCompare, api, type AsoAuditView, type AsoTrendRow, type PpoStatus, type PpoTest } from '../../api';
|
||||||
import { t } from '../../i18n';
|
import { t } from '../../i18n';
|
||||||
import type { UnifiedApp } from '../../lib/identity';
|
import type { UnifiedApp } from '../../lib/identity';
|
||||||
import { analyticsCsv, exportName } from '../../lib/exports';
|
import { analyticsCsv, exportName } from '../../lib/exports';
|
||||||
|
|
@ -15,6 +16,7 @@ import { useExports } from '../../ui/Exports';
|
||||||
import { Icon, StoreGlyph } from '../../ui/icons';
|
import { Icon, StoreGlyph } from '../../ui/icons';
|
||||||
import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, Seg, Skeleton } from '../../ui/kit';
|
import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, Seg, Skeleton } from '../../ui/kit';
|
||||||
import { LineChart } from '../../ui/LineChart';
|
import { LineChart } from '../../ui/LineChart';
|
||||||
|
import { RankChart } from '../../ui/RankChart';
|
||||||
import { WriteButton } from '../../ui/WriteButton';
|
import { WriteButton } from '../../ui/WriteButton';
|
||||||
import { ascUrl, PLAY_CONSOLE } from '../AppView';
|
import { ascUrl, PLAY_CONSOLE } from '../AppView';
|
||||||
|
|
||||||
|
|
@ -91,6 +93,62 @@ function Analytics({ projectId, hasApple, hasPlay, name, playReports }: { projec
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const arrowTone = (a: AsoTrendRow['arrow']): 'ok' | 'warn' | 'bad' | 'info' | 'neutral' => (a === '↑' || a === 'new' ? 'ok' : a === '↓' ? 'warn' : a === 'lost' ? 'bad' : 'neutral');
|
||||||
|
|
||||||
|
function Aso({ projectId }: { projectId: string }) {
|
||||||
|
const r = useRead<AsoAuditView>(projectId, 'aso.audit', { network: false });
|
||||||
|
const a = r.data;
|
||||||
|
const ranked = a ? a.ranks.rows.filter(x => x.rank !== null) : [];
|
||||||
|
const gaps = a ? a.competitors.gaps.reduce((n, g) => n + g.gaps.length, 0) : 0;
|
||||||
|
// the three best-ranked keywords of the latest snapshot, as lines (rank 1 at the top)
|
||||||
|
const lines = a ? ranked.slice().sort((x, y) => (x.rank ?? 999) - (y.rank ?? 999)).slice(0, 3).map((row, i) => ({
|
||||||
|
label: `${row.keyword} (${row.storefront})`, cls: (['l1', 'l2', 'l3'] as const)[i]!,
|
||||||
|
ranks: a.ranks.series.find(s => s.storefront === row.storefront && s.keyword === row.keyword)?.ranks ?? [],
|
||||||
|
})) : [];
|
||||||
|
return (
|
||||||
|
<Card title={t('gr.aso')} icon="search" sub={a ? t('gr.asoSub', { date: date(a.generated) }) : t('gr.asoSubNone')} pad={false}
|
||||||
|
actions={<button className="btn btn-sm" onClick={r.refresh} disabled={r.loading}><Icon name="refresh" className={r.loading ? 'spin' : undefined} />{t('action.refresh')}</button>}>
|
||||||
|
{r.error ? <div className="card-body"><ErrorNotice error={r.error} /></div> : !a ? <div className="card-body"><Skeleton lines={4} block /></div> : (
|
||||||
|
<div className="card-body stack" style={{ gap: 16 }}>
|
||||||
|
<div className="kpis" style={{ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))' }}>
|
||||||
|
<Kpi icon="text" label={t('gr.asoField')} value={a.keywordField.errors ? t('gr.asoErrors', { count: a.keywordField.errors }) : t('gr.asoWarnings', { count: a.keywordField.warnings })}
|
||||||
|
tone={a.keywordField.errors ? 'bad' : a.keywordField.warnings ? 'warn' : 'ok'} sub={a.drafts.length ? t('gr.asoDrafts', { locales: a.drafts.join(', ') }) : t('gr.asoFieldSub')} />
|
||||||
|
<Kpi icon="activity" label={t('gr.asoRanked')} value={a.ranks.snapshots ? `${num(ranked.length)} / ${num(a.ranks.rows.length)}` : '–'}
|
||||||
|
sub={a.ranks.latest ? t('gr.asoLatest', { date: date(a.ranks.latest) }) : t('gr.asoNoRanks')} />
|
||||||
|
<Kpi icon="search" label={t('gr.asoGaps')} value={a.competitors.date ? num(gaps) : '–'} sub={a.competitors.date ? t('gr.asoGapsSub', { date: date(a.competitors.date) }) : t('gr.asoNoCompetitors')} />
|
||||||
|
</div>
|
||||||
|
{a.ranks.dates.length > 1 && lines.length > 0 && <RankChart dates={a.ranks.dates} lines={lines} label={t('gr.asoChartAria')} noRank={t('gr.asoNotRanked')} />}
|
||||||
|
{a.ranks.rows.length > 0 && (
|
||||||
|
<table className="table">
|
||||||
|
<thead><tr><th>{t('gr.asoKeyword')}</th><th>{t('col.store')}</th><th className="right">{t('gr.asoRank')}</th><th className="right">{t('col.diff')}</th><th className="right">{t('gr.asoBest')}</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{a.ranks.rows.slice(0, 8).map(x => (
|
||||||
|
<tr key={`${x.storefront}|${x.keyword}`}>
|
||||||
|
<td className="strong">{x.keyword}</td>
|
||||||
|
<td className="mono-id">{x.storefront}</td>
|
||||||
|
<td className="right num">{x.rank === null ? '–' : `#${x.rank}`}</td>
|
||||||
|
<td className="right"><Chip tone={arrowTone(x.arrow)} dot={false}>{x.change === null ? x.arrow : `${x.arrow} ${x.change > 0 ? '+' : ''}${x.change}`}</Chip></td>
|
||||||
|
<td className="right num">{x.best === null ? '–' : `#${x.best}`}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
{a.next.length > 0 && (
|
||||||
|
<div className="stack" style={{ gap: 6 }}>
|
||||||
|
<div className="act-head"><Icon name="check" />{t('gr.asoNext')}</div>
|
||||||
|
<ol className="small" style={{ margin: 0, paddingLeft: 18 }}>
|
||||||
|
{a.next.map((x, i) => <li key={i}><span className="strong">{x.what}</span><div className="muted">{x.why}{x.command ? <> · <code className="mono">{x.command}</code></> : null}</div></li>)}
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<p className="small muted">{t('gr.asoReading')}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function Experiments({ app }: { app: UnifiedApp }) {
|
function Experiments({ app }: { app: UnifiedApp }) {
|
||||||
const d = useData();
|
const d = useData();
|
||||||
const target = app.project?.id ?? app.target;
|
const target = app.project?.id ?? app.target;
|
||||||
|
|
@ -183,6 +241,7 @@ export function GrowthTab({ app }: { app: UnifiedApp }) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{app.project && <Analytics projectId={app.project.id} hasApple={hasApple} hasPlay={hasPlay} name={s?.name ?? app.name} playReports={!!s?.playReports} />}
|
{app.project && <Analytics projectId={app.project.id} hasApple={hasApple} hasPlay={hasPlay} name={s?.name ?? app.name} playReports={!!s?.playReports} />}
|
||||||
|
{app.project && (hasApple || hasPlay) && <Aso projectId={app.project.id} />}
|
||||||
<div className={`grid ${hasApple && hasPlay ? 'g-main-side' : ''}`} style={{ alignItems: 'start' }}>
|
<div className={`grid ${hasApple && hasPlay ? 'g-main-side' : ''}`} style={{ alignItems: 'start' }}>
|
||||||
{hasApple && <Experiments app={app} />}
|
{hasApple && <Experiments app={app} />}
|
||||||
{hasPlay && <PlayExperiments app={app} />}
|
{hasPlay && <PlayExperiments app={app} />}
|
||||||
|
|
|
||||||
73
apps/desktop/src/ui/RankChart.tsx
Normal file
73
apps/desktop/src/ui/RankChart.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
// Keyword ranks over the `aso rank` snapshots, drawn with visx (scales, axes, shapes, tooltip, responsive width).
|
||||||
|
// Rank 1 is the top of the chart (the y axis runs from the worst rank shown down to 1); a keyword the app was not in
|
||||||
|
// the first results for has no point that day. Reuses the line chart's styles (.lchart) and crosshair tooltip.
|
||||||
|
import { AxisBottom, AxisLeft } from '@visx/axis';
|
||||||
|
import { curveMonotoneX } from '@visx/curve';
|
||||||
|
import { Group } from '@visx/group';
|
||||||
|
import { useParentSize } from '@visx/responsive';
|
||||||
|
import { scaleLinear } from '@visx/scale';
|
||||||
|
import { Bar, Circle, Line, LinePath } from '@visx/shape';
|
||||||
|
import { date } from '../lib/format';
|
||||||
|
import { ChartTip, useIndexHover } from './charts';
|
||||||
|
import { dateTicks } from './LineChart';
|
||||||
|
|
||||||
|
export interface RankLine { label: string; ranks: (number | null)[]; cls: 'l1' | 'l2' | 'l3' }
|
||||||
|
|
||||||
|
const M = { top: 12, right: 18, bottom: 26, left: 40 };
|
||||||
|
|
||||||
|
/** The y domain: rank 1 at the top, a round worst rank at the bottom (at least 10) and up to 5 ticks. */
|
||||||
|
export function rankAxis(lines: (number | null)[][]): { worst: number; ticks: number[] } {
|
||||||
|
const hi = Math.max(10, ...lines.flat().filter((v): v is number => v !== null));
|
||||||
|
const step = hi <= 10 ? 3 : hi <= 50 ? 10 : hi <= 100 ? 25 : 50;
|
||||||
|
const worst = hi <= 10 ? 10 : Math.ceil(hi / step) * step;
|
||||||
|
const ticks = [1, ...Array.from({ length: Math.floor(worst / step) }, (_, i) => (i + 1) * step)].filter((v, i, a) => a.indexOf(v) === i && v <= worst);
|
||||||
|
return { worst, ticks };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RankChart({ dates, lines, label, noRank }: { dates: string[]; lines: RankLine[]; label: string; noRank: string }) {
|
||||||
|
const { parentRef, width } = useParentSize({ debounceTime: 50 });
|
||||||
|
const n = dates.length;
|
||||||
|
const h = useIndexHover(n, width, M.left, M.right);
|
||||||
|
if (n < 2 || !lines.length) return null;
|
||||||
|
const height = Math.round(Math.max(170, Math.min(230, width * 0.28)));
|
||||||
|
const { worst, ticks } = rankAxis(lines.map(l => l.ranks));
|
||||||
|
const x = scaleLinear({ domain: [0, n - 1], range: [M.left, Math.max(M.left + 1, width - M.right)] });
|
||||||
|
const y = scaleLinear({ domain: [1, worst], range: [M.top, height - M.bottom] });
|
||||||
|
const pts = (vs: (number | null)[]) => vs.map((v, i) => [i, v] as const);
|
||||||
|
const defined = (d: readonly [number, number | null]) => d[1] !== null;
|
||||||
|
const xs = dateTicks(n, Math.max(2, Math.floor(width / 110)));
|
||||||
|
const hv = h.hover;
|
||||||
|
return (
|
||||||
|
<div className="lchart">
|
||||||
|
<div ref={parentRef} className="lchart-plot" style={{ height }}>
|
||||||
|
{width > 0 && (
|
||||||
|
<svg width={width} height={height} role="img" aria-label={label} tabIndex={0} {...h.handlers}>
|
||||||
|
<Group className="grid-l">
|
||||||
|
{ticks.map(v => <Line key={v} from={{ x: M.left, y: y(v) }} to={{ x: width - M.right, y: y(v) }} />)}
|
||||||
|
</Group>
|
||||||
|
<AxisLeft scale={y} left={M.left} tickValues={ticks} tickFormat={v => `#${Number(v)}`} hideAxisLine hideTicks tickClassName="ax" tickLabelProps={{ className: 'ax', textAnchor: 'end', dx: -4, dy: 4 }} />
|
||||||
|
<AxisBottom scale={x} top={height - M.bottom} tickValues={xs} tickFormat={v => date(dates[Number(v)])} hideAxisLine hideTicks
|
||||||
|
tickLabelProps={(_, i) => ({ className: 'ax', textAnchor: i === 0 ? 'start' : i === xs.length - 1 ? 'end' : 'middle', dy: 4 })} />
|
||||||
|
{lines.map(l => <LinePath key={l.label} className={`ln ${l.cls}`} data={pts(l.ranks)} defined={defined} x={d => x(d[0])} y={d => y(d[1] ?? worst)} curve={curveMonotoneX} />)}
|
||||||
|
{lines.map(l => l.ranks.map((v, i) => (v === null ? null : <Circle key={`${l.label}${i}`} className={l.cls} cx={x(i)} cy={y(v)} r={2.5} />)))}
|
||||||
|
{hv !== null && (
|
||||||
|
<Group className="hov">
|
||||||
|
<Line from={{ x: x(hv), y: M.top }} to={{ x: x(hv), y: height - M.bottom }} />
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
<Bar x={M.left} y={M.top} width={Math.max(0, width - M.left - M.right)} height={height - M.top - M.bottom} fill="transparent" />
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
{hv !== null && width > 0 && (
|
||||||
|
<ChartTip left={x(hv)} top={h.tooltipTop ?? M.top}>
|
||||||
|
<b>{date(dates[hv])}</b>
|
||||||
|
{lines.map(l => <span key={l.label} className="vx-row"><i className={`sw ${l.cls}`} />{l.label}<b className="num">{l.ranks[hv] == null ? noRank : `#${l.ranks[hv]}`}</b></span>)}
|
||||||
|
</ChartTip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="lchart-legend" aria-live="polite">
|
||||||
|
{lines.map(l => <span key={l.label} className="lg"><span className={`sw ${l.cls}`} />{l.label}</span>)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -48,7 +48,8 @@ describe('webview rules', () => {
|
||||||
});
|
});
|
||||||
test('built bundle (when present) has no fixture mode and no dev switches', () => {
|
test('built bundle (when present) has no fixture mode and no dev switches', () => {
|
||||||
const dist = join(ROOT, 'dist', 'assets');
|
const dist = join(ROOT, 'dist', 'assets');
|
||||||
if (!existsSync(dist)) return;
|
// tools/ci.ts runs this file again as "desktop bundle check" after the build; its test shards skip it here
|
||||||
|
if (!existsSync(dist) || process.env.STOREBOUND_SKIP_DIST_CHECK === '1') return;
|
||||||
for (const n of readdirSync(dist)) {
|
for (const n of readdirSync(dist)) {
|
||||||
const s = readFileSync(join(dist, n), 'utf8');
|
const s = readFileSync(join(dist, n), 'utf8');
|
||||||
expect(s, n).not.toContain('storebound-dev-fixtures');
|
expect(s, n).not.toContain('storebound-dev-fixtures');
|
||||||
|
|
|
||||||
|
|
@ -60,6 +60,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
||||||
'appStoreVersions_build_getToOneRelated': 'apple/listing 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_getInstance': 'apple/listing',
|
||||||
'appStoreVersions_updateInstance': 'apple/listing',
|
'appStoreVersions_updateInstance': 'apple/listing',
|
||||||
'apps_analyticsReportRequests_getToManyRelated': 'analytics',
|
'apps_analyticsReportRequests_getToManyRelated': 'analytics',
|
||||||
'apps_appAvailabilityV2_getToOneRelated': 'apple/appinfo apple/preorder validate',
|
'apps_appAvailabilityV2_getToOneRelated': 'apple/appinfo apple/preorder validate',
|
||||||
|
|
|
||||||
|
|
@ -16,12 +16,13 @@ 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 { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
|
||||||
|
import { createOnce, findOrCreate, getById } from '../lib/upsert';
|
||||||
import { appleName } from '../lib/config';
|
import { appleName } 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 { done, log, printJson, warn } from '../lib/log';
|
import { done, log, printJson, warn } from '../lib/log';
|
||||||
import { ascClient, type J } from './asc';
|
import { ascClient, EDITABLE, type J } from './asc';
|
||||||
|
|
||||||
export function readAppleCopy(ctx: Ctx) {
|
export function readAppleCopy(ctx: Ctx) {
|
||||||
const { config, resolve } = ctx.loaded;
|
const { config, resolve } = ctx.loaded;
|
||||||
|
|
@ -156,15 +157,21 @@ export function listingPlanLines(p: AppleListingPlan): string[] {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, plan: ItemPlan[]): Promise<void> {
|
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, listPath: string, plan: ItemPlan[]): Promise<void> {
|
||||||
|
const patch = async (key: string, id: string, changes: ItemPlan['changes']) => {
|
||||||
|
await c.asc('PATCH', `/v1/${type}/${id}`, { data: { type, id, attributes: Object.fromEntries(changes.map(ch => [ch.field, ch.to ?? ''])) } });
|
||||||
|
log('apple', `${type} ${key}: updated ${changes.map(ch => ch.field).join(', ')}`);
|
||||||
|
};
|
||||||
for (const l of plan) {
|
for (const l of plan) {
|
||||||
if (l.action === 'create') {
|
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 } } } } });
|
// a locale is unique per parent: a 409 (or a lost answer) finds the existing one, which is then updated, never created twice
|
||||||
log('apple', `${type} ${l.key}: created`);
|
const made = await createOnce<J>({ what: `${type} ${l.key}`, tag: 'apple', unique: true,
|
||||||
} else if (l.action === 'update') {
|
find: async () => (await c.all(`${listPath}?limit=200`)).find((x: J) => x.attributes.locale === l.key) ?? null,
|
||||||
await c.asc('PATCH', `/v1/${type}/${l.id}`, { data: { type, id: l.id, attributes: Object.fromEntries(l.changes.map(ch => [ch.field, ch.to ?? ''])) } });
|
create: async () => (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } })).data });
|
||||||
log('apple', `${type} ${l.key}: updated ${l.changes.map(ch => ch.field).join(', ')}`);
|
if (made.created) { log('apple', `${type} ${l.key}: created`); continue; }
|
||||||
}
|
const again = planItem(l.key, { id: made.value.id, attributes: made.value.attributes ?? {} }, l.attributes);
|
||||||
|
if (again.action === 'update') await patch(l.key, made.value.id, again.changes);
|
||||||
|
} else if (l.action === 'update') await patch(l.key, l.id!, l.changes);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -189,9 +196,21 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const vp = p.versionPlan;
|
const vp = p.versionPlan;
|
||||||
let versionId = vp.id;
|
let versionId = vp.id;
|
||||||
if (vp.action === 'create') {
|
if (vp.action === 'create') {
|
||||||
versionId = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
|
// look again right before the create (another run, or a lost answer), then the journal for the list lag
|
||||||
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
|
const made = await findOrCreate<J>({ what: `App Store version ${version}`, tag: 'apple', unique: true,
|
||||||
log('apple', `version ${version} created`);
|
find: async () => (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`))
|
||||||
|
.find((x: J) => x.attributes.versionString === version && EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState)) ?? null,
|
||||||
|
journal: { root, key: `apple:${appId}:version:IOS:${version}`, byId: id => getById(c.asc, `/v1/appStoreVersions/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||||
|
create: async () => (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
|
||||||
|
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data });
|
||||||
|
versionId = made.value.id;
|
||||||
|
if (made.created) log('apple', `version ${version} created`);
|
||||||
|
else {
|
||||||
|
const { platform: _p, ...want } = vp.attributes;
|
||||||
|
const again = planItem(version, { id: versionId!, attributes: made.value.attributes ?? {} }, want);
|
||||||
|
if (again.action === 'update') await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(again.changes.map(ch => [ch.field, ch.to])) } });
|
||||||
|
log('apple', `version ${version} exists already (an earlier run made it): using it${again.action === 'update' ? `, updated ${again.changes.map(ch => ch.field).join(', ')}` : ''}`);
|
||||||
|
}
|
||||||
} else if (vp.action === 'update') {
|
} else if (vp.action === 'update') {
|
||||||
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(vp.changes.map(ch => [ch.field, ch.to])) } });
|
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: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`);
|
log('apple', `version: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`);
|
||||||
|
|
@ -200,8 +219,9 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } });
|
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } });
|
||||||
log('apple', `build ${version} (${p.build.number}) attached`);
|
log('apple', `build ${version} (${p.build.number}) attached`);
|
||||||
}
|
}
|
||||||
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, p.appInfo.locales);
|
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, `/v1/appInfos/${p.appInfo.id}/appInfoLocalizations`, p.appInfo.locales);
|
||||||
const vl = p.versionLocales ?? planLocales(await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=200`), p.wanted);
|
const vlPath = `/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations`;
|
||||||
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vl);
|
const vl = p.versionLocales ?? planLocales(await c.all(`${vlPath}?limit=200`), p.wanted);
|
||||||
|
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vlPath, vl);
|
||||||
done('apple', 'listing done');
|
done('apple', 'listing done');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
234
cli/aso.ts
234
cli/aso.ts
|
|
@ -1,32 +1,86 @@
|
||||||
// App Store keyword rank check through Apple's public iTunes Search API (no account, no scraping).
|
// App Store keyword work from official / public data only (no scraping, no third-party ASO services).
|
||||||
// storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--only-keywords] [--competitors 3] [--limit 200]
|
// storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--only-keywords] [--competitors 3] [--limit 200]
|
||||||
// [--delay 3500] [--dry] [--json]
|
// [--delay 3500] [--dry] [--json]
|
||||||
// Keywords: the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless
|
// storebound aso competitors [--term <kw>]... [--storefront us,tr] [--only-terms] [--top 10] [--delay 3500] [--no-save] [--dry] [--json]
|
||||||
|
// storebound aso suggest [--locale en-US,tr] [--fresh] [--offline] [--write] [--json]
|
||||||
|
// storebound aso audit [--storefront US] [--json]
|
||||||
|
// rank: keywords = the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless
|
||||||
// "us=en-GB"), plus --keywords (--only-keywords: just those). One request per keyword and storefront, at most one
|
// "us=en-GB"), plus --keywords (--only-keywords: just those). One request per keyword and storefront, at most one
|
||||||
// every 3.5 s (Apple allows about 20 a minute); a 403 / 429 stops the run with what was read. Rank = position of the
|
// every 3.5 s (Apple allows about 20 a minute); a 403 / 429 stops the run with what was read. Rank = position of the
|
||||||
// app (apple.appId, else the bundle id) in the first --limit results, "-" when not there; plus the first competitors
|
// app (apple.appId, else the bundle id) in the first --limit results, "-" when not there; plus the first competitors
|
||||||
// (title, developer, rating). Subtitles are not in the public API and are not shown. Writes
|
// (title, developer, rating). Writes .storebound/aso/<date>.json (and compares with the previous one) unless --dry.
|
||||||
// .storebound/aso/<date>.json (and compares with the previous one) unless --dry. Pure parts: cli/lib/aso-rank.ts.
|
// competitors: the same queries and rate limit; per term the top N other apps (name, developer, rating count, first
|
||||||
|
// release, last update, genre) and the words in their names that our name / subtitle / keywords do not cover. Saves
|
||||||
|
// .storebound/aso/competitors/<date>.json unless --dry / --no-save; names the apps new in a term's top N since the
|
||||||
|
// previous snapshot. Competitor subtitles are not in any public API and are not shown.
|
||||||
|
// suggest: keyword candidates per App Store locale from our own name / subtitle / description, the latest competitor
|
||||||
|
// snapshot, the localized category names (from the Search API's genres) and, when Apple Ads credentials exist (and
|
||||||
|
// not --offline), Apple Ads keyword suggestions with their relative popularity (0-100). Prints the ranked candidates
|
||||||
|
// and a 100-byte keyword field per locale as a diff against store/appstore.md; --write puts it there with a draft
|
||||||
|
// line above it (review, then delete the line). Never invents a popularity.
|
||||||
|
// audit: one offline report (cli/lib/aso-audit.ts) with experiment ideas and the next 3 actions. Never writes.
|
||||||
|
// Pure parts: cli/lib/aso-rank.ts, cli/lib/aso-intel.ts, cli/lib/aso-audit.ts.
|
||||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
import { adsClient } from './ads/client';
|
||||||
|
import type { Snapshot } from './lib/analytics';
|
||||||
|
import { mergeSeries } from './lib/analytics';
|
||||||
|
import { auditAso } from './lib/aso';
|
||||||
|
import { auditText, buildAudit, type RankSnap } from './lib/aso-audit';
|
||||||
|
import {
|
||||||
|
ADS_KEYWORD_SUGGESTIONS, type AdsSuggestion, candidates, categoryNames, competitorRow, type CompetitorRow, type CompetitorSnapshot, coverageGaps, draftLocales,
|
||||||
|
draftMark, fitKeywordField, keywordSuggestionBody, newEntrants, parseKeywordSuggestions, setKeywords, storefrontOf, tokens,
|
||||||
|
} from './lib/aso-intel';
|
||||||
|
import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank';
|
||||||
|
import { appleName } from './lib/config';
|
||||||
|
import { parseAppStoreListing, parsePlayListing } from './lib/copy';
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import { done, log, printJson, warn } from './lib/log';
|
import { done, log, printJson, warn } from './lib/log';
|
||||||
import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank';
|
|
||||||
import { appleSections } from './lib/project-files';
|
import { appleSections } from './lib/project-files';
|
||||||
import { textTable } from './lib/table';
|
import { textTable } from './lib/table';
|
||||||
|
|
||||||
const TAG = 'aso';
|
const TAG = 'aso';
|
||||||
|
const SUBS = ['rank', 'competitors', 'suggest', 'audit'];
|
||||||
|
const SNAP_RE = /^\d{4}-\d{2}-\d{2}\.json$/;
|
||||||
|
const today = () => new Date().toISOString().slice(0, 10);
|
||||||
|
|
||||||
export async function run(ctx: Ctx): Promise<void> {
|
function listingOf(ctx: Ctx): { file: string; md: string; sections: Map<string, Record<string, string | undefined>> } {
|
||||||
|
const { config, resolve } = ctx.loaded;
|
||||||
|
const file = resolve(config.apple?.listing ?? 'store/appstore.md');
|
||||||
|
const md = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
||||||
|
return { file, md, sections: appleSections(md) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const primaryLocale = (ctx: Ctx): string => ctx.loaded.config.apple?.primaryLocale ?? ctx.loaded.config.languages.find(l => l.apple)?.apple ?? 'en-US';
|
||||||
|
|
||||||
|
function snapshots<T>(dir: string): { file: string; data: T }[] {
|
||||||
|
if (!existsSync(dir)) return [];
|
||||||
|
return readdirSync(dir).filter(f => SNAP_RE.test(f)).sort().map(f => {
|
||||||
|
try { return { file: f, data: JSON.parse(readFileSync(join(dir, f), 'utf8')) as T }; } catch { return null; }
|
||||||
|
}).filter((x): x is { file: string; data: T } => x !== null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One Search API call per item, one every `delay` ms; stops on 403 / 429 with what was read. */
|
||||||
|
async function searchAll<P extends { storefront: string; keyword: string }>(plan: P[], limit: number, delay: number, each: (p: P, results: SearchApp[], i: number) => void): Promise<number> {
|
||||||
|
let read = 0;
|
||||||
|
for (const [i, p] of plan.entries()) {
|
||||||
|
if (i) await Bun.sleep(delay);
|
||||||
|
const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } });
|
||||||
|
if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${read} of ${plan.length}; try later or with a larger --delay`); break; }
|
||||||
|
if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; }
|
||||||
|
each(p, ((await r.json()) as { results?: SearchApp[] }).results ?? [], i);
|
||||||
|
read++;
|
||||||
|
}
|
||||||
|
return read;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rank(ctx: Ctx): Promise<void> {
|
||||||
const { config, resolve } = ctx.loaded;
|
const { config, resolve } = ctx.loaded;
|
||||||
const a = ctx.args;
|
const a = ctx.args;
|
||||||
if (a._[0] !== 'rank') throw new Error('usage: storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--dry] [--json]');
|
|
||||||
if (!config.apple) throw new Error('aso rank checks App Store search: the config has no apple section');
|
if (!config.apple) throw new Error('aso rank checks App Store search: the config has no apple section');
|
||||||
const primary = config.apple.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US';
|
const { file: listingFile, sections: listing } = listingOf(ctx);
|
||||||
const listingFile = resolve(config.apple.listing ?? 'store/appstore.md');
|
|
||||||
const listing = existsSync(listingFile) ? appleSections(readFileSync(listingFile, 'utf8')) : new Map<string, Record<string, string | undefined>>();
|
|
||||||
const extra = a.list('keywords');
|
const extra = a.list('keywords');
|
||||||
const fronts = parseStorefronts(a.list('storefronts'), primary);
|
const fronts = parseStorefronts(a.list('storefronts'), primaryLocale(ctx));
|
||||||
const n = a.num('competitors', 3);
|
const n = a.num('competitors', 3);
|
||||||
const limit = a.num('limit', 200);
|
const limit = a.num('limit', 200);
|
||||||
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
|
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
|
||||||
|
|
@ -40,21 +94,16 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const rows: RankRow[] = [];
|
const rows: RankRow[] = [];
|
||||||
for (const [i, p] of plan.entries()) {
|
await searchAll(plan, limit, delay, (p, results, i) => {
|
||||||
if (i) await Bun.sleep(delay);
|
|
||||||
const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } });
|
|
||||||
if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${rows.length} of ${plan.length}; try later or with a larger --delay`); break; }
|
|
||||||
if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; }
|
|
||||||
const results = ((await r.json()) as { results?: SearchApp[] }).results ?? [];
|
|
||||||
const row: RankRow = { storefront: p.storefront, locale: p.locale, keyword: p.keyword, rank: rankOf(results, app), results: results.length, competitors: competitors(results, app, n) };
|
const row: RankRow = { storefront: p.storefront, locale: p.locale, keyword: p.keyword, rank: rankOf(results, app), results: results.length, competitors: competitors(results, app, n) };
|
||||||
rows.push(row);
|
rows.push(row);
|
||||||
log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${row.rank ?? `not in the first ${results.length}`}`);
|
log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${row.rank ?? `not in the first ${results.length}`}`);
|
||||||
}
|
});
|
||||||
const dir = resolve('.storebound/aso');
|
const dir = resolve('.storebound/aso');
|
||||||
const prevFile = existsSync(dir) ? readdirSync(dir).filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).sort().at(-1) : undefined;
|
const prevFile = snapshots<unknown>(dir).at(-1)?.file;
|
||||||
const prev = prevFile ? (JSON.parse(readFileSync(join(dir, prevFile), 'utf8')) as { rows?: RankRow[] }).rows : undefined;
|
const prev = prevFile ? (JSON.parse(readFileSync(join(dir, prevFile), 'utf8')) as { rows?: RankRow[] }).rows : undefined;
|
||||||
const delta = rankDelta(rows, prev);
|
const delta = rankDelta(rows, prev);
|
||||||
const date = new Date().toISOString().slice(0, 10);
|
const date = today();
|
||||||
if (a.has('json')) printJson({ date, previous: prevFile ?? null, rows: rows.map(r => ({ ...r, change: delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`) ?? null })) });
|
if (a.has('json')) printJson({ date, previous: prevFile ?? null, rows: rows.map(r => ({ ...r, change: delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`) ?? null })) });
|
||||||
else console.log(textTable(['store', 'keyword', 'rank', 'change', 'top competitors'], rows.map(r => {
|
else console.log(textTable(['store', 'keyword', 'rank', 'change', 'top competitors'], rows.map(r => {
|
||||||
const d = delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`);
|
const d = delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`);
|
||||||
|
|
@ -64,3 +113,148 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
writeFileSync(join(dir, `${date}.json`), JSON.stringify({ date, app: { appId: app.appId ?? null, bundleId: app.bundleId }, rows }, null, 2) + '\n');
|
writeFileSync(join(dir, `${date}.json`), JSON.stringify({ date, app: { appId: app.appId ?? null, bundleId: app.bundleId }, rows }, null, 2) + '\n');
|
||||||
done(TAG, `${rows.length} rank(s) saved to ${join(dir, `${date}.json`)}${prevFile ? ` (change vs ${prevFile})` : ''}; Search API order is close to App Store search, read it as a trend`);
|
done(TAG, `${rows.length} rank(s) saved to ${join(dir, `${date}.json`)}${prevFile ? ` (change vs ${prevFile})` : ''}; Search API order is close to App Store search, read it as a trend`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function competitorsCmd(ctx: Ctx): Promise<void> {
|
||||||
|
const { config, resolve } = ctx.loaded;
|
||||||
|
const a = ctx.args;
|
||||||
|
if (!config.apple) throw new Error('aso competitors reads App Store search: the config has no apple section');
|
||||||
|
const { file, sections } = listingOf(ctx);
|
||||||
|
const terms = a.many('term').flatMap(t => t.split(',')).map(t => t.trim()).filter(Boolean);
|
||||||
|
const fronts = parseStorefronts([...a.list('storefront'), ...a.list('storefronts')], primaryLocale(ctx));
|
||||||
|
const top = Math.max(1, Math.min(50, a.num('top', 10)));
|
||||||
|
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
|
||||||
|
const app = { appId: config.apple.appId, bundleId: config.apple.bundleId };
|
||||||
|
const plan = fronts.flatMap(f => keywordList(a.has('only-terms') ? '' : sections.get(f.locale)?.keywords, terms).map(k => ({ ...f, keyword: k })));
|
||||||
|
if (!plan.length) throw new Error(`no terms: ${file} has no keywords for ${fronts.map(f => f.locale).join(', ')}; pass --term <keyword>`);
|
||||||
|
const limit = top + 1;
|
||||||
|
const save = !a.has('dry') && !a.has('no-save');
|
||||||
|
if (!a.has('json')) log(TAG, `${plan.length} quer${plan.length === 1 ? 'y' : 'ies'} (${fronts.map(f => f.storefront).join(', ')}), top ${top} each, one every ${delay / 1000}s: about ${Math.ceil(plan.length * delay / 60_000)} min`);
|
||||||
|
if (a.has('dry')) {
|
||||||
|
if (a.has('json')) printJson({ dryRun: true, top, queries: plan.map(p => ({ storefront: p.storefront, locale: p.locale, term: p.keyword, url: searchUrl(p.keyword, p.storefront, limit) })) });
|
||||||
|
else for (const p of plan) log(TAG, `would GET ${searchUrl(p.keyword, p.storefront, limit)}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rows: CompetitorRow[] = [];
|
||||||
|
await searchAll(plan, limit, delay, (p, results, i) => {
|
||||||
|
rows.push(competitorRow(results, app, { storefront: p.storefront, locale: p.locale, term: p.keyword }, top));
|
||||||
|
if (!a.has('json')) log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${results.length} result(s)`);
|
||||||
|
});
|
||||||
|
const dir = resolve('.storebound/aso/competitors');
|
||||||
|
const prev = snapshots<CompetitorSnapshot>(dir).filter(s => s.file !== `${today()}.json`).at(-1);
|
||||||
|
const fresh = newEntrants(rows, prev?.data.rows);
|
||||||
|
const gaps = fronts.map(f => {
|
||||||
|
const s = sections.get(f.locale) ?? {};
|
||||||
|
const covered = [...tokens(s.name ?? appleName(config), f.locale), ...tokens(s.subtitle ?? '', f.locale), ...(s.keywords ?? '').split(',').flatMap(t => tokens(t, f.locale))];
|
||||||
|
return { storefront: f.storefront, locale: f.locale, gaps: coverageGaps(rows.filter(r => r.storefront === f.storefront && r.locale === f.locale), covered, f.locale) };
|
||||||
|
});
|
||||||
|
const snap: CompetitorSnapshot = { date: today(), app: { appId: app.appId ?? null, bundleId: app.bundleId }, top, rows };
|
||||||
|
if (a.has('json')) printJson({ ...snap, previous: prev?.file ?? null, newEntrants: Object.fromEntries(fresh), gaps, saved: save,
|
||||||
|
notes: ['Search API order is close to, not equal to, App Store search', 'competitor subtitles are not in any public API'] });
|
||||||
|
else {
|
||||||
|
for (const r of rows) {
|
||||||
|
console.log(`\n${r.storefront} "${r.term}"${r.ourRank ? ` (you: #${r.ourRank})` : ''}`);
|
||||||
|
console.log(textTable(['#', 'app', 'developer', 'ratings', 'released', 'updated', 'genre'],
|
||||||
|
r.apps.map(x => [x.rank, x.name.slice(0, 40), x.developer.slice(0, 24), x.ratings, x.released ?? '-', x.updated ?? '-', x.genres[0]?.name || x.genre])));
|
||||||
|
const n = fresh.get(`${r.storefront}|${r.term.toLowerCase()}`);
|
||||||
|
if (n?.length) log(TAG, `new in the top ${top} since ${prev!.data.date}: ${n.join(', ')}`);
|
||||||
|
}
|
||||||
|
for (const g of gaps) console.log(`\n${g.storefront} ${g.locale}: words in competitors' names you do not cover: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} developers)`).join(', ') : 'none'}`);
|
||||||
|
log(TAG, 'subtitles are not in any public API, so they are not shown; words one developer uses are left out (likely a brand); never put other apps\' names into your keywords');
|
||||||
|
}
|
||||||
|
if (save) {
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
writeFileSync(join(dir, `${snap.date}.json`), JSON.stringify(snap, null, 2) + '\n');
|
||||||
|
if (!a.has('json')) done(TAG, `${rows.length} term(s) saved to ${join(dir, `${snap.date}.json`)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function suggest(ctx: Ctx): Promise<void> {
|
||||||
|
const { config, resolve, root } = ctx.loaded;
|
||||||
|
const a = ctx.args;
|
||||||
|
const json = a.has('json');
|
||||||
|
if (!config.apple) throw new Error('aso suggest proposes App Store keyword fields: the config has no apple section');
|
||||||
|
const { file, md } = listingOf(ctx);
|
||||||
|
if (!md) throw new Error(`${file} not found`);
|
||||||
|
const listing = parseAppStoreListing(md);
|
||||||
|
const locales = a.list('locale').length ? a.list('locale') : Object.keys(listing);
|
||||||
|
for (const l of locales) if (!listing[l]) throw new Error(`--locale ${l}: no "## ${l}" section in ${file}`);
|
||||||
|
const comp = snapshots<CompetitorSnapshot>(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null;
|
||||||
|
const cats = Object.values(config.apple.info?.categories ?? {}).filter((x): x is string => typeof x === 'string');
|
||||||
|
// Apple Ads keyword suggestions: only with the owner's credentials and an Apple ID; never estimated without them
|
||||||
|
let ads: ReturnType<typeof adsClient> | null = null;
|
||||||
|
let adsNote = '';
|
||||||
|
if (a.has('offline')) adsNote = '--offline: Apple Ads not asked; popularity unknown';
|
||||||
|
else if (!config.apple.appId) adsNote = 'no apple.appId in the config: Apple Ads suggestions need the app\'s Apple ID; popularity unknown';
|
||||||
|
else {
|
||||||
|
try { ads = adsClient(root); if (!ads.accountId) { ads = null; adsNote = 'APPLE_ADS_ACCOUNT_ID is not set: popularity unknown'; } } catch (e) { adsNote = `no Apple Ads credentials (${(e as Error).message.split(';')[0]}): popularity unknown`; }
|
||||||
|
}
|
||||||
|
const results: { locale: string; storefront: string; ads: string; competitors: string | null; candidates: ReturnType<typeof candidates>; proposal: ReturnType<typeof fitKeywordField> }[] = [];
|
||||||
|
for (const locale of locales) {
|
||||||
|
const c = listing[locale]!;
|
||||||
|
const sf = storefrontOf(locale);
|
||||||
|
const rows = (comp?.rows ?? []).filter(r => r.locale === locale);
|
||||||
|
const name = c.name ?? appleName(config);
|
||||||
|
let sugg: AdsSuggestion[] = [];
|
||||||
|
let adsState = adsNote;
|
||||||
|
if (ads) {
|
||||||
|
const seeds = [...new Set([...tokens(name, locale), ...tokens(c.subtitle ?? '', locale), ...(c.keywords ?? '').split(',').map(t => t.trim()).filter(Boolean)])].slice(0, 20);
|
||||||
|
try {
|
||||||
|
sugg = parseKeywordSuggestions(await ads.post(ADS_KEYWORD_SUGGESTIONS, keywordSuggestionBody(config.apple.appId!, seeds, [sf])));
|
||||||
|
adsState = `Apple Ads keyword suggestions (${sf.toUpperCase()}): ${sugg.length}; popularity is Apple's relative 0-100 score, not a search volume`;
|
||||||
|
} catch (e) { adsState = `Apple Ads keyword suggestions failed (${(e as Error).message.slice(0, 160)}): popularity unknown`; }
|
||||||
|
}
|
||||||
|
const cands = candidates({ locale, name, subtitle: c.subtitle ?? '', keywords: c.keywords ?? '', description: c.description ?? '', competitors: rows, categories: categoryNames(rows, cats), ads: sugg });
|
||||||
|
const proposal = fitKeywordField({ locale, current: c.keywords ?? '', name, subtitle: c.subtitle ?? '', ranked: cands, fresh: a.has('fresh') });
|
||||||
|
results.push({ locale, storefront: sf, ads: adsState, competitors: rows.length ? `${comp!.date}: ${rows.length} term(s)` : null, candidates: cands, proposal });
|
||||||
|
}
|
||||||
|
const write = a.has('write') && !a.has('dry');
|
||||||
|
const changed = results.filter(r => r.proposal.after !== r.proposal.before);
|
||||||
|
if (json) printJson({ file, written: write && changed.length > 0, results: results.map(r => ({ ...r, candidates: r.candidates.slice(0, 60) })) });
|
||||||
|
else {
|
||||||
|
for (const r of results) {
|
||||||
|
console.log(`\n== ${r.locale} (storefront ${r.storefront}) · competitors: ${r.competitors ?? 'no snapshot (storebound aso competitors)'} · ${r.ads}`);
|
||||||
|
const shown = r.candidates.filter(c => c.status === 'candidate').slice(0, 25);
|
||||||
|
console.log(textTable(['candidate', 'from', 'relevance', 'in names', 'popularity'], shown.map(c => [c.term, c.sources.join('+'), `${c.relevance}/2`, `${c.inNames}/${c.ofApps}`,
|
||||||
|
c.popularity === null ? 'unknown' : `${c.popularity}${c.popularityFrom === 'phrase' ? ' (phrase)' : ''}`])));
|
||||||
|
const skipped = r.candidates.filter(c => c.status !== 'candidate' && c.kind === 'word').slice(0, 12);
|
||||||
|
if (skipped.length) log(TAG, `left out: ${skipped.map(c => `${c.term} (${c.why})`).join(', ')}`);
|
||||||
|
const p = r.proposal;
|
||||||
|
if (p.after === p.before) { log(TAG, `${r.locale}: keyword field unchanged (${p.bytes}/100 bytes)`); continue; }
|
||||||
|
console.log(`--- ${r.locale} keywords (store/appstore.md)\n- ${p.before || '(empty)'}\n+ ${p.after}\n ${p.bytes}/100 bytes · kept ${p.kept.length} · added ${p.added.join(', ') || 'none'}${p.dropped.length ? ` · dropped ${p.dropped.map(d => `${d.term} (${d.why})`).join(', ')}` : ''}`);
|
||||||
|
}
|
||||||
|
log(TAG, 'relevance: in your own text (+1) and in competitors\' names (+1); "in names": top apps that already have the word in their name; popularity only from Apple Ads, never estimated');
|
||||||
|
}
|
||||||
|
if (!changed.length) return;
|
||||||
|
if (!write) { if (!json) log(TAG, `dry run: nothing written; --write puts the ${changed.length} proposal(s) into ${file} as drafts for review`); return; }
|
||||||
|
let next = md;
|
||||||
|
for (const r of changed) next = setKeywords(next, r.locale, r.proposal.after, draftMark(today()));
|
||||||
|
writeFileSync(file, next);
|
||||||
|
if (!json) done(TAG, `wrote ${changed.length} draft keyword field(s) to ${file}: review them, delete the draft lines, then storebound check --aso`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function audit(ctx: Ctx): void {
|
||||||
|
const { config, resolve } = ctx.loaded;
|
||||||
|
const a = ctx.args;
|
||||||
|
const storefront = (a.get('storefront') ?? 'US').toUpperCase();
|
||||||
|
const { file, md } = listingOf(ctx);
|
||||||
|
const apple = config.apple && md ? parseAppStoreListing(md) : undefined;
|
||||||
|
const playFile = resolve(config.play?.listing ?? 'store/listing.md');
|
||||||
|
const play = config.play && existsSync(playFile) ? parsePlayListing(readFileSync(playFile, 'utf8'), config.app.name) : undefined;
|
||||||
|
const findings = auditAso({ apple, play, appName: appleName(config), storefront });
|
||||||
|
const ranks = snapshots<RankSnap>(resolve('.storebound/aso')).map(s => ({ date: s.data.date, rows: s.data.rows ?? [] }));
|
||||||
|
const comp = snapshots<CompetitorSnapshot>(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null;
|
||||||
|
const analytics = mergeSeries(snapshots<Snapshot>(resolve('.storebound/analytics')).map(s => s.data)).apple;
|
||||||
|
const r = buildAudit({ today: today(), storefront, findings, drafts: md ? draftLocales(md) : [], apple, appName: appleName(config), play, ranks, competitors: comp, analytics,
|
||||||
|
variants: Object.keys(config.shots?.variants ?? {}) });
|
||||||
|
if (a.has('json')) return printJson({ ...r, files: { appstore: apple ? file : null, play: play ? playFile : null } });
|
||||||
|
console.log(auditText(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
|
const sub = ctx.args._[0];
|
||||||
|
if (!sub || !SUBS.includes(sub)) throw new Error('usage: storebound aso rank | competitors | suggest | audit (see the aso-basics skill)');
|
||||||
|
if (sub === 'rank') return rank(ctx);
|
||||||
|
if (sub === 'competitors') return competitorsCmd(ctx);
|
||||||
|
if (sub === 'suggest') return suggest(ctx);
|
||||||
|
return audit(ctx);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { relative } from 'node:path';
|
import { relative } from 'node:path';
|
||||||
import { appPrivacyMismatches } from './lib/app-privacy';
|
import { appPrivacyMismatches } from './lib/app-privacy';
|
||||||
import { type AsoFinding, auditAso } from './lib/aso';
|
import { type AsoFinding, auditAso } from './lib/aso';
|
||||||
|
import { draftLocales } from './lib/aso-intel';
|
||||||
import { appleName, playCodes } from './lib/config';
|
import { appleName, playCodes } from './lib/config';
|
||||||
import { APPLE_IAP_LIMITS, appleNameIssues, 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';
|
||||||
|
|
@ -22,9 +23,11 @@ import { type CopyFile, validateCopy } from './shots/lib';
|
||||||
|
|
||||||
function aso(ctx: Ctx): void {
|
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 appleMd = config.apple ? readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8') : '';
|
||||||
|
const apple = config.apple ? parseAppStoreListing(appleMd) : 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: appleName(config), storefront: ctx.args.get('storefront') ?? 'US' });
|
const f: AsoFinding[] = auditAso({ apple, play, appName: appleName(config), storefront: ctx.args.get('storefront') ?? 'US' });
|
||||||
|
for (const l of draftLocales(appleMd)) f.push({ level: 'warn', where: `apple ${l}`, msg: 'keywords: draft from `aso suggest`, not reviewed yet (review, then delete the storebound-aso draft line)' });
|
||||||
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}`);
|
||||||
|
|
|
||||||
|
|
@ -168,6 +168,8 @@ export interface OpenOpts {
|
||||||
hosts?: string[];
|
hosts?: string[];
|
||||||
headless?: boolean;
|
headless?: boolean;
|
||||||
platform?: string;
|
platform?: string;
|
||||||
|
/** Tests: Playwright's launch timeout for modes (b) and (c) (default: Playwright's 30 s). */
|
||||||
|
launchTimeoutMs?: number;
|
||||||
say: (m: string) => void;
|
say: (m: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -233,7 +235,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
|
||||||
copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) });
|
copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) });
|
||||||
const c = await chromiumFor(root);
|
const c = await chromiumFor(root);
|
||||||
const context = await c.launchPersistentContext(copy.dir, {
|
const context = await c.launchPersistentContext(copy.dir, {
|
||||||
channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS,
|
channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}),
|
||||||
// Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read
|
// Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read
|
||||||
ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'],
|
ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'],
|
||||||
});
|
});
|
||||||
|
|
@ -251,7 +253,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
|
||||||
}
|
}
|
||||||
// (c) storebound's persistent profile, the owner signs in there
|
// (c) storebound's persistent profile, the owner signs in there
|
||||||
mkdirSync(o.profileDir, { recursive: true });
|
mkdirSync(o.profileDir, { recursive: true });
|
||||||
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS });
|
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}) });
|
||||||
o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`);
|
o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`);
|
||||||
const page = await ownTab(context);
|
const page = await ownTab(context);
|
||||||
return wrapContext('profile', context, page, () => { /* kept on purpose */ });
|
return wrapContext('profile', context, page, () => { /* kept on purpose */ });
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
||||||
'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches | pull [--write]: store texts of IAPs + subscriptions as a config proposal'],
|
'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches | pull [--write]: store texts of IAPs + subscriptions as a config proposal'],
|
||||||
'reports': [() => import('./reports'), 'apple-sales | apple-finance --month | play-earnings --month | play-sales --month: download to .storebound/reports/, summary table + CSV; read-only'],
|
'reports': [() => import('./reports'), 'apple-sales | apple-finance --month | play-earnings --month | play-sales --month: download to .storebound/reports/, summary table + CSV; read-only'],
|
||||||
'triage': [() => import('./triage'), 'TestFlight crash / screenshot feedback and Play error reports grouped by signature, device, OS version, build; read-only, --json'],
|
'triage': [() => import('./triage'), 'TestFlight crash / screenshot feedback and Play error reports grouped by signature, device, OS version, build; read-only, --json'],
|
||||||
'aso': [() => import('./aso'), 'rank [--storefronts us,de] [--keywords a,b]: App Store rank per keyword and storefront + competitors from the public iTunes Search API (rate limited) -> .storebound/aso/'],
|
'aso': [() => import('./aso'), 'rank | competitors | suggest | audit: App Store ranks, top apps per keyword, keyword field proposals (Apple Ads popularity with credentials) and one ASO report, from the public iTunes Search API -> .storebound/aso/'],
|
||||||
'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes) | ppp --base <USD> (purchasing power price sheet, snapped to store price points)'],
|
'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes) | ppp --base <USD> (purchasing power price sheet, snapped to store price points)'],
|
||||||
'ads apple': [() => import('./ads/apple'), 'Apple Ads (Search Ads): status | campaigns | report (spend, taps, installs, CPA per campaign / keyword, --csv); bid | budget | pause (dry run, asks first; never via MCP)'],
|
'ads apple': [() => import('./ads/apple'), 'Apple Ads (Search Ads): status | campaigns | report (spend, taps, installs, CPA per campaign / keyword, --csv); bid | budget | pause (dry run, asks first; never via MCP)'],
|
||||||
'web': [() => import('./web'), 'init (apple-app-site-association, assetlinks.json, Smart App Banner tag, optional landing page) | check <domain> (live files: content type, no redirects, ids match)'],
|
'web': [() => import('./web'), 'init (apple-app-site-association, assetlinks.json, Smart App Banner tag, optional landing page) | check <domain> (live files: content type, no redirects, ids match)'],
|
||||||
|
|
@ -49,7 +49,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
||||||
'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'],
|
'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'],
|
||||||
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language; pull [--write]: live listings back into the listing file (diff first)'],
|
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language; pull [--write]: live listings back into the listing file (diff first)'],
|
||||||
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'],
|
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'],
|
||||||
'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'],
|
'play data-safety': [() => import('./play/data-safety'), '[--force] Data safety form (CSV import through the API; skipped when unchanged since the last upload)'],
|
||||||
'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'],
|
'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'],
|
||||||
'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'],
|
'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'],
|
||||||
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],
|
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],
|
||||||
|
|
|
||||||
221
cli/lib/aso-audit.ts
Normal file
221
cli/lib/aso-audit.ts
Normal file
|
|
@ -0,0 +1,221 @@
|
||||||
|
// `aso audit`: one offline report over everything storebound already keeps, as pure parts. Inputs: the `check --aso`
|
||||||
|
// findings and the cross-locale free-keyword-room hint (cli/lib/aso.ts), the rank snapshots of `aso rank`
|
||||||
|
// (.storebound/aso/<date>.json, trend arrows), the latest competitor snapshot of `aso competitors`
|
||||||
|
// (.storebound/aso/competitors/<date>.json, coverage gaps), the Play listing (keyword density, short description use),
|
||||||
|
// the App Store analytics snapshots (.storebound/analytics, impressions / downloads / conversion) and the screenshot
|
||||||
|
// variants of the config. Output: the report, experiment ideas (suggestions only: nothing is started) and the next 3
|
||||||
|
// concrete actions. No network, no writes.
|
||||||
|
import type { AppleDay } from './analytics';
|
||||||
|
import type { AsoFinding } from './aso';
|
||||||
|
import { words } from './aso';
|
||||||
|
import { type CompetitorSnapshot, coverageGaps, type Gap, isStop, tokens } from './aso-intel';
|
||||||
|
import type { RankRow } from './aso-rank';
|
||||||
|
import type { AppleCopy, PlayCopy } from './copy';
|
||||||
|
import { len } from './copy';
|
||||||
|
import { textTable } from './table';
|
||||||
|
|
||||||
|
export interface RankSnap { date: string; rows: RankRow[] }
|
||||||
|
export type Arrow = '↑' | '↓' | '→' | 'new' | 'lost' | '·';
|
||||||
|
export interface TrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: Arrow; best: number | null; snapshots: number }
|
||||||
|
|
||||||
|
const k = (r: { storefront: string; keyword: string }) => `${r.storefront}|${r.keyword.toLowerCase()}`;
|
||||||
|
|
||||||
|
/** Latest rank per storefront + keyword against the snapshot before it (positive change = moved up). Pure. */
|
||||||
|
export function rankTrend(snaps: RankSnap[]): { rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] } {
|
||||||
|
const sorted = [...snaps].sort((a, b) => a.date.localeCompare(b.date));
|
||||||
|
const dates = sorted.map(s => s.date);
|
||||||
|
const hist = new Map<string, { storefront: string; keyword: string; ranks: (number | null | undefined)[] }>();
|
||||||
|
sorted.forEach((s, i) => {
|
||||||
|
for (const r of s.rows) {
|
||||||
|
const h = hist.get(k(r)) ?? { storefront: r.storefront, keyword: r.keyword, ranks: Array(sorted.length).fill(undefined) };
|
||||||
|
h.ranks[i] = r.rank;
|
||||||
|
hist.set(k(r), h);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const rows: TrendRow[] = [];
|
||||||
|
for (const h of hist.values()) {
|
||||||
|
const seen = h.ranks.map((v, i) => ({ v, i })).filter(x => x.v !== undefined) as { v: number | null; i: number }[];
|
||||||
|
const last = seen.at(-1)!, prev = seen.at(-2);
|
||||||
|
const rank = last.v, previous = prev ? prev.v : null;
|
||||||
|
const arrow: Arrow = !prev ? (rank === null ? '·' : 'new') : rank === null ? (previous === null ? '·' : 'lost') : previous === null ? 'new'
|
||||||
|
: rank < previous ? '↑' : rank > previous ? '↓' : '→';
|
||||||
|
const known = seen.map(x => x.v).filter((v): v is number => v !== null);
|
||||||
|
rows.push({ storefront: h.storefront, keyword: h.keyword, rank, previous, change: rank !== null && previous !== null ? previous - rank : null, arrow,
|
||||||
|
best: known.length ? Math.min(...known) : null, snapshots: seen.length });
|
||||||
|
}
|
||||||
|
rows.sort((a, b) => a.storefront.localeCompare(b.storefront) || (a.rank ?? 999) - (b.rank ?? 999) || a.keyword.localeCompare(b.keyword));
|
||||||
|
const series = [...hist.values()].map(h => ({ storefront: h.storefront, keyword: h.keyword, ranks: h.ranks.map(v => v ?? null) }));
|
||||||
|
return { rows, dates, series };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlayUse { lang: string; title: string; shortChars: number; shortRoom: number; titleWordsInShort: boolean; shortWordsInOpening: boolean; top: { word: string; count: number; density: number }[]; stuffed: string[] }
|
||||||
|
|
||||||
|
/** Play: how the short description is used and which words the full description leans on (density). Pure. */
|
||||||
|
export function playUse(c: PlayCopy): PlayUse {
|
||||||
|
const L = c.lang;
|
||||||
|
const full = words(c.full, L);
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
for (const w of full) if (w.length > 3 && !isStop(w, L)) counts.set(w, (counts.get(w) ?? 0) + 1);
|
||||||
|
const top = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 5)
|
||||||
|
.map(([word, count]) => ({ word, count, density: full.length ? count / full.length : 0 }));
|
||||||
|
const titleWords = tokens(c.title, L).filter(w => w.length > 2);
|
||||||
|
const shortWords = new Set(tokens(c.short, L));
|
||||||
|
const opening = new Set(words(c.full.split('\n').slice(0, 3).join(' '), L));
|
||||||
|
return {
|
||||||
|
lang: L, title: c.title, shortChars: len(c.short), shortRoom: 80 - len(c.short),
|
||||||
|
titleWordsInShort: titleWords.some(w => shortWords.has(w)),
|
||||||
|
shortWordsInOpening: [...shortWords].some(w => w.length > 3 && opening.has(w)),
|
||||||
|
top, stuffed: top.filter(t => full.length >= 80 && t.count >= 6 && t.density > 0.03).map(t => t.word),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Experiment { store: 'apple' | 'play'; what: string; why: string; how: string }
|
||||||
|
export interface Action { what: string; why: string; command?: string }
|
||||||
|
|
||||||
|
export interface AuditInput {
|
||||||
|
today: string;
|
||||||
|
storefront: string;
|
||||||
|
findings: AsoFinding[];
|
||||||
|
drafts: string[];
|
||||||
|
apple?: Record<string, AppleCopy>;
|
||||||
|
appName: string;
|
||||||
|
play?: PlayCopy[];
|
||||||
|
ranks: RankSnap[];
|
||||||
|
competitors: CompetitorSnapshot | null;
|
||||||
|
analytics: AppleDay[];
|
||||||
|
variants: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AsoAudit {
|
||||||
|
generated: string; storefront: string;
|
||||||
|
keywordField: { errors: number; warnings: number; hints: number; findings: AsoFinding[] };
|
||||||
|
crossLocale: string | null;
|
||||||
|
drafts: string[];
|
||||||
|
ranks: { snapshots: number; latest: string | null; rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] };
|
||||||
|
competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: Gap[] }[] };
|
||||||
|
play: PlayUse[];
|
||||||
|
/** check --aso findings of the Play listing (stuffing, claims, caps, emoji, short description room). */
|
||||||
|
playFindings: AsoFinding[];
|
||||||
|
analytics: { days: number; start: string; end: string; impressions: number; pageViews: number; downloads: number; conversion: number | null } | null;
|
||||||
|
experiments: Experiment[];
|
||||||
|
next: Action[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const daysBetween = (a: string, b: string) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
|
||||||
|
|
||||||
|
/** The whole audit. Pure. */
|
||||||
|
export function buildAudit(i: AuditInput): AsoAudit {
|
||||||
|
const kwFindings = i.findings.filter(f => f.where.startsWith('apple ') && !/storefront$/.test(f.where));
|
||||||
|
const playFindings = i.findings.filter(f => f.where.startsWith('play '));
|
||||||
|
const cross = i.findings.find(f => /storefront$/.test(f.where))?.msg ?? null;
|
||||||
|
const trend = rankTrend(i.ranks);
|
||||||
|
const gaps: AsoAudit['competitors']['gaps'] = [];
|
||||||
|
if (i.competitors) {
|
||||||
|
const groups = new Map<string, CompetitorSnapshot['rows']>();
|
||||||
|
for (const r of i.competitors.rows) groups.set(`${r.storefront}|${r.locale}`, [...(groups.get(`${r.storefront}|${r.locale}`) ?? []), r]);
|
||||||
|
for (const [g, rows] of groups) {
|
||||||
|
const [storefront, locale] = g.split('|') as [string, string];
|
||||||
|
const c = i.apple?.[locale];
|
||||||
|
const covered = [...words(c?.name ?? i.appName, locale), ...words(c?.subtitle ?? '', locale), ...(c?.keywords ?? '').split(',').flatMap(t => words(t, locale))];
|
||||||
|
gaps.push({ storefront, locale, gaps: coverageGaps(rows, covered, locale, 8) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const play = (i.play ?? []).map(playUse);
|
||||||
|
const last = i.analytics.slice(-28);
|
||||||
|
const sum = (f: (d: AppleDay) => number) => last.reduce((n, d) => n + f(d), 0);
|
||||||
|
const analytics = last.length ? { days: last.length, start: last[0]!.date, end: last.at(-1)!.date, impressions: sum(d => d.uniqueImpressions || d.impressions),
|
||||||
|
pageViews: sum(d => d.uniquePageViews || d.pageViews), downloads: sum(d => d.firstTimeDownloads || d.downloads), conversion: null as number | null } : null;
|
||||||
|
if (analytics) analytics.conversion = analytics.impressions ? analytics.downloads / analytics.impressions : null;
|
||||||
|
const a: AsoAudit = {
|
||||||
|
generated: i.today, storefront: i.storefront,
|
||||||
|
keywordField: { errors: kwFindings.filter(f => f.level === 'error').length, warnings: kwFindings.filter(f => f.level === 'warn').length, hints: kwFindings.filter(f => f.level === 'info').length, findings: kwFindings },
|
||||||
|
crossLocale: cross, drafts: i.drafts,
|
||||||
|
ranks: { snapshots: i.ranks.length, latest: trend.dates.at(-1) ?? null, rows: trend.rows, dates: trend.dates, series: trend.series },
|
||||||
|
competitors: { date: i.competitors?.date ?? null, gaps },
|
||||||
|
play, playFindings, analytics, experiments: [], next: [],
|
||||||
|
};
|
||||||
|
a.experiments = experimentIdeas(a, i);
|
||||||
|
a.next = nextActions(a, i);
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Product Page Optimization (Apple) and store listing experiment (Play) ideas from the audit. Suggestions only. Pure. */
|
||||||
|
export function experimentIdeas(a: AsoAudit, i: AuditInput): Experiment[] {
|
||||||
|
const out: Experiment[] = [];
|
||||||
|
if (i.apple) {
|
||||||
|
const v = i.variants[0];
|
||||||
|
out.push({ store: 'apple', what: 'first screenshot caption: lead with the search phrase people use for the app\'s main job',
|
||||||
|
why: a.analytics?.conversion !== null && a.analytics ? `App Store conversion (first-time downloads / unique impressions, last ${a.analytics.days} days) is ${(a.analytics.conversion! * 100).toFixed(1)}%: the first screenshot is what search results show` : 'the first screenshot is what search results show; PPO measures it against the original',
|
||||||
|
how: v ? `variant "${v}" exists: storebound shots render --variant ${v}, then storebound apple ppo create --variant ${v} --dry and apple ppo upload --variant ${v} --dry (starting the test is the owner's step: apple ppo start)`
|
||||||
|
: 'add a shots.variants entry with the new caption, storebound shots render --variant b, then storebound apple ppo create --variant b --dry (starting the test is the owner\'s step: apple ppo start)' });
|
||||||
|
out.push({ store: 'apple', what: 'subtitle variant',
|
||||||
|
why: 'PPO tests only icons, screenshots and app previews: the subtitle cannot be A/B tested on the App Store',
|
||||||
|
how: 'change it with the next version and compare before / after with storebound analytics compare (one change at a time)' });
|
||||||
|
}
|
||||||
|
for (const p of a.play.slice(0, 1)) {
|
||||||
|
out.push({ store: 'play', what: `short description variant (${p.lang})`,
|
||||||
|
why: p.shortRoom > 30 ? `the short description uses ${p.shortChars}/80 characters` : !p.titleWordsInShort ? 'the short description shares no word with the title' : 'the short description is the first text on the listing',
|
||||||
|
how: 'Play Console > Grow users > Store listing experiments (no API: storebound only prepares the text; the store-screenshots skill has the steps)' });
|
||||||
|
if (i.variants.length) out.push({ store: 'play', what: `screenshot variant "${i.variants[0]}"`, why: 'graphics experiments need no new version',
|
||||||
|
how: `storebound shots render --variant ${i.variants[0]} --size play, then upload it as the experiment's variant in Play Console` });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The next 3 concrete actions, most important first. Pure. */
|
||||||
|
export function nextActions(a: AsoAudit, i: AuditInput): Action[] {
|
||||||
|
const out: Action[] = [];
|
||||||
|
const f = a.keywordField.findings;
|
||||||
|
const err = f.find(x => x.level === 'error');
|
||||||
|
if (err) out.push({ what: `fix ${err.where}: ${err.msg}`, why: 'App Store Connect refuses the keyword field as it is', command: 'storebound check --aso' });
|
||||||
|
if (a.drafts.length) out.push({ what: `review the draft keywords of ${a.drafts.join(', ')} in store/appstore.md and delete the draft line`, why: 'they were proposed by aso suggest, not reviewed yet' });
|
||||||
|
const room = f.find(x => /bytes used; fill/.test(x.msg));
|
||||||
|
if (room) out.push({ what: `fill the keyword field of ${room.where.replace('apple ', '')} (${room.msg.replace(/^keywords: /, '')})`, why: 'unused bytes are unused search reach', command: `storebound aso suggest --locale ${room.where.replace('apple ', '')}` });
|
||||||
|
const rep = f.find(x => /repeat words from the name/.test(x.msg));
|
||||||
|
if (rep) out.push({ what: `${rep.where}: replace the words the name / subtitle already index (${rep.msg.split(': ').at(-1)})`, why: 'they take bytes without adding reach', command: `storebound aso suggest --locale ${rep.where.replace('apple ', '')}` });
|
||||||
|
const gap = a.competitors.gaps.find(g => g.gaps.length);
|
||||||
|
if (gap) out.push({ what: `consider "${gap.gaps.slice(0, 3).map(g => g.word).join('", "')}" for ${gap.locale} (in the names of ${gap.gaps[0]!.developers} developers' top apps, not in your name / subtitle / keywords)`, why: 'words the top apps lead with; only if they describe your app', command: `storebound aso suggest --locale ${gap.locale}` });
|
||||||
|
const lost = a.ranks.rows.filter(r => r.arrow === '↓' || r.arrow === 'lost');
|
||||||
|
if (lost.length) out.push({ what: `look at the keywords that dropped: ${lost.slice(0, 3).map(r => `${r.storefront} "${r.keyword}" ${r.previous ?? '-'} -> ${r.rank ?? '-'}`).join(', ')}`, why: 'a drop after a listing change is the signal to revert or adjust it' });
|
||||||
|
if (!a.ranks.latest) out.push({ what: 'take a first rank snapshot', why: 'trends need a baseline before the next listing change', command: 'storebound aso rank --dry, then storebound aso rank' });
|
||||||
|
else if (daysBetween(a.ranks.latest, i.today) > 14) out.push({ what: `take a new rank snapshot (the last is from ${a.ranks.latest})`, why: 'trend arrows compare the last two snapshots', command: 'storebound aso rank' });
|
||||||
|
if (!a.competitors.date) out.push({ what: 'read the competitors for your keywords', why: 'coverage gaps and suggest need the top apps per term', command: 'storebound aso competitors --dry, then storebound aso competitors' });
|
||||||
|
for (const p of a.play) {
|
||||||
|
if (p.stuffed.length) out.push({ what: `Play ${p.lang}: use "${p.stuffed.join('", "')}" less often in the full description`, why: 'reads as keyword stuffing (Play metadata policy)' });
|
||||||
|
else if (p.shortRoom > 30) out.push({ what: `Play ${p.lang}: put the core phrase into the short description (${p.shortChars}/80 used)`, why: 'Play indexes the short description' });
|
||||||
|
}
|
||||||
|
if (!a.analytics) out.push({ what: 'start App Store analytics snapshots', why: 'conversion before / after each listing change is the real measure', command: 'storebound analytics setup --dry, then storebound analytics snapshot' });
|
||||||
|
return out.slice(0, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
const signed = (n: number | null) => (n === null ? '' : n > 0 ? `+${n}` : String(n));
|
||||||
|
|
||||||
|
/** The report as text. Pure. */
|
||||||
|
export function auditText(a: AsoAudit): string {
|
||||||
|
const o: string[] = [];
|
||||||
|
const kf = a.keywordField;
|
||||||
|
o.push(`ASO audit ${a.generated} (offline: listing files, .storebound/aso snapshots, .storebound/analytics)`, '');
|
||||||
|
o.push(`1. Keyword field (check --aso): ${kf.errors} errors, ${kf.warnings} warnings, ${kf.hints} hints`);
|
||||||
|
for (const f of kf.findings.filter(x => x.level !== 'info').slice(0, 8)) o.push(` ${f.level === 'error' ? 'ERROR' : 'warn '} [${f.where}] ${f.msg}`);
|
||||||
|
if (a.drafts.length) o.push(` draft keywords (from aso suggest, not reviewed): ${a.drafts.join(', ')}`);
|
||||||
|
if (a.crossLocale) o.push(` ${a.storefront} storefront: ${a.crossLocale}`);
|
||||||
|
o.push('', `2. Ranks (aso rank, iTunes Search API order; a trend, not App Store search itself): ${a.ranks.snapshots} snapshot(s)${a.ranks.latest ? `, latest ${a.ranks.latest}` : ''}`);
|
||||||
|
if (a.ranks.rows.length) o.push(indent(textTable(['store', 'keyword', 'rank', '', 'change', 'best'], a.ranks.rows.map(r => [r.storefront, r.keyword, r.rank ?? '-', r.arrow, signed(r.change), r.best ?? '-']))));
|
||||||
|
else o.push(' none yet: storebound aso rank');
|
||||||
|
o.push('', `3. Competitor coverage (aso competitors${a.competitors.date ? `, ${a.competitors.date}` : ''}): words in the top apps' names you do not cover`);
|
||||||
|
if (!a.competitors.date) o.push(' no snapshot yet: storebound aso competitors');
|
||||||
|
for (const g of a.competitors.gaps) o.push(` ${g.storefront} ${g.locale}: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} devs)`).join(', ') : 'none'}`);
|
||||||
|
o.push('', '4. Google Play listing');
|
||||||
|
if (!a.play.length) o.push(' no Play listing');
|
||||||
|
for (const f of a.playFindings.filter(x => x.level !== 'info')) o.push(` warn [${f.where}] ${f.msg}`);
|
||||||
|
for (const p of a.play) o.push(` ${p.lang}: short ${p.shortChars}/80${p.titleWordsInShort ? '' : ', no title word in it'}${p.shortWordsInOpening ? '' : ', opening lines share no word with it'}; top words ${p.top.map(t => `${t.word} ${t.count}x (${(t.density * 100).toFixed(1)}%)`).join(', ') || '-'}${p.stuffed.length ? `; STUFFING: ${p.stuffed.join(', ')}` : ''}`);
|
||||||
|
o.push('', '5. App Store analytics (analytics snapshot)');
|
||||||
|
o.push(a.analytics ? ` ${a.analytics.start} .. ${a.analytics.end} (${a.analytics.days} days): ${a.analytics.impressions} unique impressions, ${a.analytics.pageViews} product page views, ${a.analytics.downloads} first-time downloads, conversion ${a.analytics.conversion === null ? 'n/a' : `${(a.analytics.conversion * 100).toFixed(2)}%`}` : ' no snapshots: storebound analytics snapshot');
|
||||||
|
o.push('', '6. Experiment ideas (suggestions only; nothing is started)');
|
||||||
|
for (const e of a.experiments) o.push(` [${e.store === 'apple' ? 'App Store PPO' : 'Play experiment'}] ${e.what}`, ` why: ${e.why}`, ` how: ${e.how}`);
|
||||||
|
o.push('', 'Next 3 actions');
|
||||||
|
a.next.forEach((x, n) => o.push(` ${n + 1}. ${x.what}`, ` why: ${x.why}${x.command ? `; run: ${x.command}` : ''}`));
|
||||||
|
return o.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
const indent = (s: string) => s.split('\n').map(l => ` ${l}`).join('\n');
|
||||||
366
cli/lib/aso-intel.ts
Normal file
366
cli/lib/aso-intel.ts
Normal file
|
|
@ -0,0 +1,366 @@
|
||||||
|
// ASO keyword research from official and public data only, as pure parts. The commands are in cli/aso.ts
|
||||||
|
// (`aso competitors`, `aso suggest`); the audit report is cli/lib/aso-audit.ts.
|
||||||
|
//
|
||||||
|
// Data sources and what each number is (and is not):
|
||||||
|
// - iTunes Search API (public, no account; https://performance-partners.apple.com/search-api): the top N apps for a
|
||||||
|
// term in one storefront, with name (trackName), developer, rating count, first release date, last update, genre
|
||||||
|
// and the genre names localized to that storefront ("genres": "Produktivität" for country=de). Its order is close
|
||||||
|
// to, not equal to, App Store search. It has no subtitle field, so competitor subtitles are never shown.
|
||||||
|
// - Apple Ads Platform API, POST /v1/suggestions/keywords/query (only with the owner's Apple Ads credentials):
|
||||||
|
// keyword suggestions for the app (promotedObjectId = Apple ID, promotedObjectType APPSTORE_APP), seeded with
|
||||||
|
// `terms` and scoped with `countriesOrRegions`; each KeywordSuggestion is { text, popularity } where popularity is
|
||||||
|
// "a relative popularity score (not an absolute volume)" on a 0-100 scale. That is the only popularity signal
|
||||||
|
// storebound shows; without credentials popularity stays "unknown" (never estimated).
|
||||||
|
// https://developer.apple.com/documentation/apple-ads-platform-api/query-keyword-suggestions
|
||||||
|
// https://developer.apple.com/documentation/apple-ads-platform-api/keywordsuggestion
|
||||||
|
// https://developer.apple.com/documentation/apple-ads-platform-api/recommendationqueryrequest (pageSize 1..1000)
|
||||||
|
// (The Recommendations endpoints are budget / target CPA only; Insights has search term popularity 1-5 by genre,
|
||||||
|
// not used here.)
|
||||||
|
// - The app's own listing (store/appstore.md): name, subtitle, keyword field and description.
|
||||||
|
// Nothing here scrapes a store web page or calls a third-party ASO service.
|
||||||
|
import { FILLER, words } from './aso';
|
||||||
|
import type { SearchApp } from './aso-rank';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Words
|
||||||
|
|
||||||
|
/** Function words that never make a keyword (a few languages; extend as needed). FILLER (app, game, free ...) too. */
|
||||||
|
const STOP: Record<string, string[]> = {
|
||||||
|
en: ['to', 'in', 'on', 'at', 'by', 'or', 'is', 'it', 'its', 'you', 'your', 'our', 'we', 'my', 'me', 'all', 'one', 'new', 'more', 'from', 'that', 'this', 'are', 'be', 'can', 'get', 'up', 'out', 'as', 'so', 'no', 'not', 'any', 'every', 'each', 'just', 'into', 'than', 'then', 'also', 'will', 'has', 'have', 'only', 'when', 'what', 'who', 'how', 'way', 'like', 'use', 'make', 'keep', 'see'],
|
||||||
|
de: ['der', 'die', 'das', 'und', 'mit', 'für', 'von', 'zu', 'ein', 'eine', 'ist', 'im', 'in', 'auf', 'den', 'dem', 'des', 'sie', 'du', 'dein', 'deine', 'alle', 'oder', 'auch'],
|
||||||
|
fr: ['le', 'la', 'les', 'et', 'de', 'des', 'du', 'un', 'une', 'pour', 'avec', 'en', 'au', 'aux', 'vos', 'votre', 'est', 'dans', 'sur', 'ou', 'tout', 'tous'],
|
||||||
|
es: ['el', 'la', 'los', 'las', 'y', 'de', 'del', 'un', 'una', 'para', 'con', 'en', 'tu', 'tus', 'es', 'por', 'o', 'que', 'todo', 'todos'],
|
||||||
|
pt: ['o', 'a', 'os', 'as', 'e', 'de', 'do', 'da', 'um', 'uma', 'para', 'com', 'em', 'seu', 'sua', 'no', 'na', 'ou', 'que', 'todo', 'todos'],
|
||||||
|
it: ['il', 'lo', 'la', 'le', 'gli', 'e', 'di', 'del', 'un', 'una', 'per', 'con', 'in', 'tuo', 'tua', 'che', 'tutti'],
|
||||||
|
tr: ['ve', 'ile', 'için', 'göre', 'kadar', 'sonra', 'önce', 'olan', 'olarak', 'bir', 'bu', 'şu', 'da', 'de', 'mi', 'en', 'çok', 'her', 'tüm', 'gibi', 'daha', 'sen', 'senin'],
|
||||||
|
};
|
||||||
|
/** Words of listing boilerplate (account, settings, privacy ...): they describe the store page, not the app's job. */
|
||||||
|
const BOILER = new Set(['account', 'accounts', 'settings', 'sign', 'signin', 'login', 'delete', 'privacy', 'policy', 'terms', 'support', 'contact', 'feature', 'features',
|
||||||
|
'update', 'updates', 'version', 'subscription', 'purchase', 'purchases', 'time', 'any', 'back', 'between', 'off', 'next', 'keeps', 'keep', 'item', 'items',
|
||||||
|
'change', 'changes', 'show', 'shows', 'work', 'works', 'people', 'phone', 'phones', 'here', 'there', 'about', 'want', 'need', 'help', 'day', 'days', 'even', 'much', 'many']);
|
||||||
|
const lang = (locale: string): string => locale.split('-')[0]!.toLowerCase();
|
||||||
|
export const isStop = (w: string, locale: string): boolean => FILLER.has(w) || BOILER.has(w) || (STOP[lang(locale)] ?? []).includes(w) || STOP.en!.includes(w) || /^\d+$/.test(w);
|
||||||
|
/** "Ayarlar'dan" -> "Ayarlar", "it's" -> "it": the suffix after an apostrophe is not a word of its own. */
|
||||||
|
const unApostrophe = (s: string): string => s.replace(/['’]\p{L}+/gu, '');
|
||||||
|
|
||||||
|
/** Content words of a text (lowercased for the locale, function words, boilerplate and numbers left out). Pure. */
|
||||||
|
export const tokens = (s: string, locale: string): string[] => words(unApostrophe(s), locale).filter(w => !isStop(w, locale));
|
||||||
|
|
||||||
|
/** Two-word phrases of content words that stand next to each other in the text. Pure. */
|
||||||
|
export function bigrams(s: string, locale: string): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const seg of unApostrophe(s).split(/[.!?\n:;,()"“”«»•·|/–—-]+/)) {
|
||||||
|
const ws = words(seg, locale);
|
||||||
|
for (let i = 0; i + 1 < ws.length; i++) if (!isStop(ws[i]!, locale) && !isStop(ws[i + 1]!, locale)) out.push(`${ws[i]} ${ws[i + 1]}`);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plural-insensitive key: languages whose plural is mostly "-s" fold "lists" and "list" together. Pure. */
|
||||||
|
export function stem(w: string, locale: string): string {
|
||||||
|
const l = lang(locale);
|
||||||
|
if (l === 'en' && w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y'; // groceries -> grocery
|
||||||
|
return ['en', 'fr', 'es', 'pt'].includes(l) && w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Languages that add suffixes to a word ("listeler", "listelerini"): one word starts with the other. */
|
||||||
|
const SUFFIXING = new Set(['tr', 'fi', 'hu', 'et', 'az', 'kk', 'uz']);
|
||||||
|
/** The same keyword for search: plural-insensitive, and in suffixing languages a word that only adds a short suffix
|
||||||
|
* (up to 5 letters) to a word of at least 4. A heuristic: it errs on the side of not repeating a word. Pure. */
|
||||||
|
export function sameWord(a: string, b: string, locale: string): boolean {
|
||||||
|
const x = stem(a, locale), y = stem(b, locale);
|
||||||
|
if (x === y) return true;
|
||||||
|
if (!SUFFIXING.has(lang(locale))) return false;
|
||||||
|
const [s, l] = x.length <= y.length ? [x, y] : [y, x];
|
||||||
|
return s.length >= 4 && l.startsWith(s) && l.length - s.length <= 5;
|
||||||
|
}
|
||||||
|
const coveredBy = (w: string, set: Iterable<string>, locale: string): boolean => { for (const s of set) if (sameWord(w, s, locale)) return true; return false; };
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Competitors (iTunes Search API)
|
||||||
|
|
||||||
|
/** App Store Connect category id -> iTunes genre id (the "genreIds" of Search API results). Apple's genre ids. */
|
||||||
|
export const GENRE_IDS: Record<string, string> = {
|
||||||
|
BOOKS: '6018', BUSINESS: '6000', DEVELOPER_TOOLS: '6026', EDUCATION: '6017', ENTERTAINMENT: '6016', FINANCE: '6015', FOOD_AND_DRINK: '6023', GAMES: '6014',
|
||||||
|
GRAPHICS_AND_DESIGN: '6027', HEALTH_AND_FITNESS: '6013', LIFESTYLE: '6012', MAGAZINES_AND_NEWSPAPERS: '6021', MEDICAL: '6020', MUSIC: '6011', NAVIGATION: '6010',
|
||||||
|
NEWS: '6009', PHOTO_AND_VIDEO: '6008', PRODUCTIVITY: '6007', REFERENCE: '6006', SHOPPING: '6024', SOCIAL_NETWORKING: '6005', SPORTS: '6004', STICKERS: '6025',
|
||||||
|
TRAVEL: '6003', UTILITIES: '6002', WEATHER: '6001',
|
||||||
|
GAMES_ACTION: '7001', GAMES_ADVENTURE: '7002', GAMES_CASUAL: '7003', GAMES_BOARD: '7004', GAMES_CARD: '7005', GAMES_CASINO: '7006', GAMES_FAMILY: '7009',
|
||||||
|
GAMES_MUSIC: '7011', GAMES_PUZZLE: '7012', GAMES_RACING: '7013', GAMES_ROLE_PLAYING: '7014', GAMES_SIMULATION: '7015', GAMES_SPORTS: '7016',
|
||||||
|
GAMES_STRATEGY: '7017', GAMES_TRIVIA: '7018', GAMES_WORD: '7019',
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface CompetitorApp {
|
||||||
|
rank: number; id: string; name: string; developer: string; ratings: number; rating: number | null;
|
||||||
|
/** First release (releaseDate) and the current version's release (currentVersionReleaseDate), YYYY-MM-DD. */
|
||||||
|
released: string | null; updated: string | null;
|
||||||
|
genre: string;
|
||||||
|
/** Genre ids with their names localized to the storefront. */
|
||||||
|
genres: { id: string; name: string }[];
|
||||||
|
}
|
||||||
|
export interface CompetitorRow { storefront: string; locale: string; term: string; results: number; ourRank: number | null; apps: CompetitorApp[] }
|
||||||
|
export interface CompetitorSnapshot { date: string; app: { appId: string | null; bundleId: string }; top: number; rows: CompetitorRow[] }
|
||||||
|
|
||||||
|
const isUs = (r: SearchApp, app: { appId?: string; bundleId?: string }) => !!((app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId));
|
||||||
|
|
||||||
|
/** One term's Search API results -> the top n other apps (and our own position among the results read). Pure. */
|
||||||
|
export function competitorRow(results: SearchApp[], app: { appId?: string; bundleId?: string }, q: { storefront: string; locale: string; term: string }, n: number): CompetitorRow {
|
||||||
|
const i = results.findIndex(r => isUs(r, app));
|
||||||
|
const apps = results.map((r, k) => ({ r, k })).filter(({ r }) => !isUs(r, app)).slice(0, n).map(({ r, k }): CompetitorApp => ({
|
||||||
|
rank: k + 1, id: String(r.trackId), name: r.trackName, developer: r.sellerName ?? '', ratings: r.userRatingCount ?? 0, rating: r.averageUserRating ?? null,
|
||||||
|
released: r.releaseDate?.slice(0, 10) ?? null, updated: r.currentVersionReleaseDate?.slice(0, 10) ?? null, genre: r.primaryGenreName ?? '',
|
||||||
|
genres: (r.genreIds ?? []).map((id, j) => ({ id: String(id), name: r.genres?.[j] ?? '' })).filter(g => g.name),
|
||||||
|
}));
|
||||||
|
return { ...q, results: results.length, ourRank: i >= 0 ? i + 1 : null, apps };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Distinct apps of the rows (one storefront / locale), first seen first. Pure. */
|
||||||
|
export function distinctApps(rows: CompetitorRow[]): CompetitorApp[] {
|
||||||
|
const seen = new Map<string, CompetitorApp>();
|
||||||
|
for (const r of rows) for (const a of r.apps) if (!seen.has(a.id)) seen.set(a.id, a);
|
||||||
|
return [...seen.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Gap { word: string; apps: number; developers: number; terms: string[]; examples: string[] }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Words in competitors' names that our name, subtitle and keyword field do not cover. A word only counts when apps of at
|
||||||
|
* least two different developers use it: a word one developer uses is most likely a brand (and other apps' names and
|
||||||
|
* trademarks must never go into a keyword field). Pure.
|
||||||
|
*/
|
||||||
|
export function coverageGaps(rows: CompetitorRow[], covered: Iterable<string>, locale: string, max = 15): Gap[] {
|
||||||
|
const have = [...covered];
|
||||||
|
const by = new Map<string, { apps: Set<string>; devs: Set<string>; terms: Set<string>; examples: string[] }>();
|
||||||
|
for (const r of rows) for (const a of r.apps) for (const w of new Set(tokens(a.name, locale))) {
|
||||||
|
if (w.length < 3 || coveredBy(w, have, locale)) continue;
|
||||||
|
const k = stem(w, locale);
|
||||||
|
const g = by.get(k) ?? { apps: new Set(), devs: new Set(), terms: new Set(), examples: [] };
|
||||||
|
if (!g.apps.has(a.id) && g.examples.length < 3) g.examples.push(a.name);
|
||||||
|
g.apps.add(a.id); g.devs.add(a.developer.toLowerCase()); g.terms.add(r.term);
|
||||||
|
by.set(k, g);
|
||||||
|
}
|
||||||
|
return [...by.entries()].filter(([, g]) => g.devs.size >= 2)
|
||||||
|
.map(([word, g]) => ({ word, apps: g.apps.size, developers: g.devs.size, terms: [...g.terms], examples: g.examples }))
|
||||||
|
.sort((a, b) => b.developers - a.developers || b.apps - a.apps || a.word.localeCompare(b.word)).slice(0, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Apps in the top N now that were not there in the previous snapshot, per storefront + term. Pure. */
|
||||||
|
export function newEntrants(now: CompetitorRow[], before: CompetitorRow[] | undefined): Map<string, string[]> {
|
||||||
|
const out = new Map<string, string[]>();
|
||||||
|
if (!before) return out;
|
||||||
|
const prev = new Map(before.map(r => [`${r.storefront}|${r.term.toLowerCase()}`, new Set(r.apps.map(a => a.id))] as const));
|
||||||
|
for (const r of now) {
|
||||||
|
const p = prev.get(`${r.storefront}|${r.term.toLowerCase()}`);
|
||||||
|
if (p) out.set(`${r.storefront}|${r.term.toLowerCase()}`, r.apps.filter(a => !p.has(a.id)).map(a => a.name));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The category names of the app in one storefront's language, read from the Search API results' localized genres. Pure. */
|
||||||
|
export function categoryNames(rows: CompetitorRow[], categoryIds: string[]): string[] {
|
||||||
|
const ids = new Set(categoryIds.map(c => GENRE_IDS[c]).filter(Boolean));
|
||||||
|
const names = new Set<string>();
|
||||||
|
for (const a of distinctApps(rows)) for (const g of a.genres) if (ids.has(g.id)) names.add(g.name);
|
||||||
|
return [...names];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Apple Ads keyword suggestions
|
||||||
|
|
||||||
|
export const ADS_KEYWORD_SUGGESTIONS = '/suggestions/keywords/query';
|
||||||
|
|
||||||
|
/** RecommendationQueryRequest for keyword suggestions: the two required filters, seed terms, countries. Pure. */
|
||||||
|
export function keywordSuggestionBody(adamId: string, terms: string[], countries: string[], pageSize = 200): Record<string, unknown> {
|
||||||
|
const filters: Record<string, unknown>[] = [
|
||||||
|
{ field: 'promotedObjectId', operator: 'EQUALS', value: [adamId] },
|
||||||
|
{ field: 'promotedObjectType', operator: 'EQUALS', value: ['APPSTORE_APP'] },
|
||||||
|
];
|
||||||
|
if (terms.length) filters.push({ field: 'terms', operator: 'IN', value: terms });
|
||||||
|
if (countries.length) filters.push({ field: 'countriesOrRegions', operator: 'IN', value: countries.map(c => c.toUpperCase()) });
|
||||||
|
return { filters, sorting: [{ field: 'popularity', order: 'DESC' }], pagination: { offset: 0, pageSize: Math.min(1000, Math.max(1, pageSize)) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdsSuggestion { text: string; popularity: number }
|
||||||
|
/** `result` of the keyword suggestions answer -> { text, popularity } (0-100), invalid rows left out. Pure. */
|
||||||
|
export function parseKeywordSuggestions(res: unknown): AdsSuggestion[] {
|
||||||
|
const rows = (res as { result?: unknown })?.result;
|
||||||
|
if (!Array.isArray(rows)) return [];
|
||||||
|
return rows.filter((r): r is { text: string; popularity: number } => typeof r?.text === 'string' && typeof r?.popularity === 'number')
|
||||||
|
.map(r => ({ text: r.text.trim(), popularity: Math.max(0, Math.min(100, Math.round(r.popularity))) })).filter(r => r.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Candidates and scoring
|
||||||
|
|
||||||
|
export type CandSource = 'name' | 'subtitle' | 'keywords' | 'description' | 'competitors' | 'category' | 'apple-ads';
|
||||||
|
export type CandStatus = 'candidate' | 'indexed' | 'category' | 'filler';
|
||||||
|
export interface Candidate {
|
||||||
|
term: string;
|
||||||
|
kind: 'word' | 'phrase';
|
||||||
|
sources: CandSource[];
|
||||||
|
/** Times in our own name / subtitle / description. */
|
||||||
|
ours: number;
|
||||||
|
/** relevance 0-2: +1 in our own text (name, subtitle, description, keywords), +1 in competitor names (the top apps). */
|
||||||
|
relevance: number;
|
||||||
|
/** Competition: how many of the distinct top apps already have it in their name, of how many read. */
|
||||||
|
inNames: number; ofApps: number;
|
||||||
|
/** Apple Ads relative popularity 0-100, null = unknown (no credentials, or Apple returned nothing for it). */
|
||||||
|
popularity: number | null;
|
||||||
|
/** exact: Apple Ads suggested this exact word; phrase: the highest score of a suggested phrase that contains it. */
|
||||||
|
popularityFrom: 'exact' | 'phrase' | null;
|
||||||
|
status: CandStatus;
|
||||||
|
why?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CandidateInput {
|
||||||
|
locale: string;
|
||||||
|
name: string; subtitle: string; keywords: string; description: string;
|
||||||
|
/** The competitor rows of this locale's storefront (latest `aso competitors` snapshot), may be empty. */
|
||||||
|
competitors: CompetitorRow[];
|
||||||
|
/** Category names in this language (categoryNames); matched by Apple anyway, so never put into the field. */
|
||||||
|
categories: string[];
|
||||||
|
ads: AdsSuggestion[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every keyword candidate of one locale with its signals. Sorted: candidates first, by relevance, popularity (known
|
||||||
|
* first), lower competition, then how often our own text uses it. Pure. */
|
||||||
|
export function candidates(i: CandidateInput): Candidate[] {
|
||||||
|
const L = i.locale;
|
||||||
|
const m = new Map<string, Candidate>();
|
||||||
|
const key = (t: string) => t.split(' ').map(w => stem(w, L)).join(' ');
|
||||||
|
const add = (term: string, kind: Candidate['kind'], src: CandSource, n = 1) => {
|
||||||
|
const k = key(term);
|
||||||
|
const c = m.get(k) ?? { term, kind, sources: [], ours: 0, relevance: 0, inNames: 0, ofApps: 0, popularity: null, popularityFrom: null, status: 'candidate' as CandStatus };
|
||||||
|
if (!c.sources.includes(src)) c.sources.push(src);
|
||||||
|
if (src === 'name' || src === 'subtitle' || src === 'description') c.ours += n;
|
||||||
|
m.set(k, c);
|
||||||
|
};
|
||||||
|
for (const [src, text] of [['name', i.name], ['subtitle', i.subtitle], ['description', i.description]] as const) for (const w of tokens(text, L)) if (w.length > 2) add(w, 'word', src);
|
||||||
|
for (const w of i.keywords.split(',').flatMap(t => tokens(t, L))) if (w.length > 1) add(w, 'word', 'keywords');
|
||||||
|
// phrases: only the ones our own text uses at least twice, or that stand in the name / subtitle
|
||||||
|
const phraseCount = new Map<string, number>();
|
||||||
|
for (const b of [...bigrams(i.name, L), ...bigrams(i.subtitle, L), ...bigrams(i.subtitle, L), ...bigrams(i.description, L)]) phraseCount.set(b, (phraseCount.get(b) ?? 0) + 1);
|
||||||
|
for (const [b, n] of phraseCount) if (n >= 2) add(b, 'phrase', 'description', n);
|
||||||
|
const apps = distinctApps(i.competitors);
|
||||||
|
const nameWords = apps.map(a => new Set(tokens(a.name, L).map(w => stem(w, L))));
|
||||||
|
for (const g of coverageGaps(i.competitors, [], L, 200)) add(g.word, 'word', 'competitors');
|
||||||
|
const catWords = [...new Set(i.categories.flatMap(c => words(c, L)))];
|
||||||
|
const cats = new Set(catWords.map(w => stem(w, L)));
|
||||||
|
for (const c of catWords) add(c, 'word', 'category');
|
||||||
|
for (const s of i.ads) {
|
||||||
|
const ws = tokens(s.text, L);
|
||||||
|
if (ws.length === 1) add(ws[0]!, 'word', 'apple-ads');
|
||||||
|
}
|
||||||
|
const indexed = [...tokens(i.name, L), ...tokens(i.subtitle, L)];
|
||||||
|
for (const c of m.values()) {
|
||||||
|
const ws = c.term.split(' ').map(w => stem(w, L));
|
||||||
|
const inOurs = c.ours > 0 || c.sources.includes('keywords');
|
||||||
|
c.inNames = nameWords.filter(n => ws.every(w => n.has(w))).length;
|
||||||
|
c.ofApps = apps.length;
|
||||||
|
c.relevance = (inOurs ? 1 : 0) + (c.inNames > 0 ? 1 : 0);
|
||||||
|
const exact = i.ads.find(s => key(s.text.toLocaleLowerCase(L)) === key(c.term));
|
||||||
|
const phrases = i.ads.filter(s => ws.every(w => tokens(s.text, L).map(x => stem(x, L)).includes(w)));
|
||||||
|
if (exact) { c.popularity = exact.popularity; c.popularityFrom = 'exact'; }
|
||||||
|
else if (phrases.length) { c.popularity = Math.max(...phrases.map(s => s.popularity)); c.popularityFrom = 'phrase'; }
|
||||||
|
if (ws.some(w => cats.has(w)) && ws.length === 1) { c.status = 'category'; c.why = 'category name: matched by Apple anyway'; }
|
||||||
|
else if (ws.every(w => coveredBy(w, indexed, L))) { c.status = 'indexed'; c.why = 'already in the name / subtitle (indexed)'; }
|
||||||
|
else if (ws.some(w => FILLER.has(w))) { c.status = 'filler'; c.why = 'filler word'; }
|
||||||
|
}
|
||||||
|
const order = (c: Candidate) => (c.status === 'candidate' ? 0 : 1);
|
||||||
|
// a word only the description uses once is noise, unless competitors or Apple Ads bring it up too
|
||||||
|
const weak = (c: Candidate) => c.sources.length === 1 && c.sources[0] === 'description' && c.ours < 2;
|
||||||
|
return [...m.values()].filter(c => !weak(c)).sort((a, b) => order(a) - order(b) || b.relevance - a.relevance || (b.popularity ?? -1) - (a.popularity ?? -1)
|
||||||
|
|| a.inNames - b.inNames || b.ours - a.ours || a.term.localeCompare(b.term));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// The 100-byte keyword field
|
||||||
|
|
||||||
|
export interface FieldProposal { locale: string; before: string; after: string; bytes: number; kept: string[]; added: string[]; dropped: { term: string; why: string }[] }
|
||||||
|
|
||||||
|
const bytes = (s: string) => Buffer.byteLength(s, 'utf8');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A keyword field for one locale that fits 100 bytes (UTF-8) with the existing rules: commas without spaces, no
|
||||||
|
* duplicates (plural-insensitive), no words of the name / subtitle, no filler or category words, single words. Current
|
||||||
|
* terms that are still valid are kept first (change a few terms per release, not all), unless `fresh`; then the best
|
||||||
|
* candidates fill the room. Pure.
|
||||||
|
*/
|
||||||
|
export function fitKeywordField(o: { locale: string; current: string; name: string; subtitle: string; ranked: Candidate[]; fresh?: boolean; limit?: number }): FieldProposal {
|
||||||
|
const L = o.locale, limit = o.limit ?? 100;
|
||||||
|
const indexed = [...tokens(o.name, L), ...tokens(o.subtitle, L)];
|
||||||
|
const blocked = new Map(o.ranked.filter(c => c.status !== 'candidate' && c.kind === 'word').map(c => [stem(c.term, L), c.why ?? c.status] as const));
|
||||||
|
const out: string[] = [], kept: string[] = [], added: string[] = [], dropped: { term: string; why: string }[] = [];
|
||||||
|
const seen: string[] = [];
|
||||||
|
const fits = (t: string) => bytes([...out, t].join(',')) <= limit;
|
||||||
|
const tryAdd = (t: string, into: string[]): string | null => {
|
||||||
|
const ws = words(t, L);
|
||||||
|
if (!ws.length) return 'empty';
|
||||||
|
if (ws.every(w => coveredBy(w, indexed, L))) return 'already in the name / subtitle (indexed)';
|
||||||
|
if (ws.some(w => FILLER.has(w))) return 'filler word';
|
||||||
|
if (ws.length === 1 ? coveredBy(ws[0]!, seen, L) : seen.includes(ws.join(' '))) return 'duplicate';
|
||||||
|
const b = ws.length === 1 ? blocked.get(stem(ws[0]!, L)) : undefined;
|
||||||
|
if (b) return b;
|
||||||
|
if (!fits(t)) return 'no room in 100 bytes';
|
||||||
|
seen.push(ws.length === 1 ? ws[0]! : ws.join(' ')); out.push(t); into.push(t);
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
if (!o.fresh) for (const t of o.current.split(',').map(s => s.trim().toLocaleLowerCase(L)).filter(Boolean)) {
|
||||||
|
// keep a current phrase as the words it is made of: single words combine on their own and save bytes
|
||||||
|
const parts = /\s/.test(t) ? tokens(t, L) : [t];
|
||||||
|
for (const p of parts) { const why = tryAdd(p, kept); if (why && why !== 'duplicate') dropped.push({ term: p, why }); }
|
||||||
|
}
|
||||||
|
for (const c of o.ranked) {
|
||||||
|
if (c.status !== 'candidate' || c.kind !== 'word') continue;
|
||||||
|
tryAdd(c.term, added);
|
||||||
|
}
|
||||||
|
const after = out.join(',');
|
||||||
|
return { locale: L, before: o.current, after, bytes: bytes(after), kept, added, dropped };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Writing the proposal into store/appstore.md (only with --write; marked as a draft for review)
|
||||||
|
|
||||||
|
export const DRAFT_RE = /^<!--\s*storebound-aso:\s*draft\b[^>]*-->\s*$/m;
|
||||||
|
export const draftMark = (date: string): string => `<!-- storebound-aso: draft keywords from \`aso suggest\` ${date}; review them, then delete this line -->`;
|
||||||
|
|
||||||
|
/** Locales of store/appstore.md whose keywords carry the draft line. Pure. */
|
||||||
|
export function draftLocales(md: string): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const sec of md.split(/^(?=## )/m)) {
|
||||||
|
if (!sec.startsWith('## ')) continue;
|
||||||
|
const kw = sec.split(/^(?=### )/m).find(p => /^### keywords\s*$/m.test(p.split('\n')[0]!));
|
||||||
|
if (kw && DRAFT_RE.test(kw)) out.push(sec.slice(3).split(/[\s·]/)[0]!.trim());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** store/appstore.md with the keywords block of `locale` set to `value` and the draft line above it. Pure. */
|
||||||
|
export function setKeywords(md: string, locale: string, value: string, mark: string): string {
|
||||||
|
const secs = md.split(/^(?=## )/m);
|
||||||
|
const i = secs.findIndex(s => s.startsWith('## ') && s.slice(3).split(/[\s·]/)[0]!.trim() === locale);
|
||||||
|
if (i < 0) throw new Error(`no "## ${locale}" section in the App Store listing`);
|
||||||
|
const parts = secs[i]!.split(/^(?=### )/m);
|
||||||
|
const block = `### keywords\n${mark}\n\`\`\`\n${value}\n\`\`\`\n`;
|
||||||
|
const k = parts.findIndex(p => /^### keywords\s*$/.test(p.split('\n')[0]!));
|
||||||
|
if (k >= 0) {
|
||||||
|
const old = parts[k]!;
|
||||||
|
const fence = /^```[^\n]*\n[\s\S]*?\n```[^\n]*\n?/m.exec(old);
|
||||||
|
const tail = fence ? old.slice(fence.index + fence[0].length) : old.split('\n').slice(1).join('\n');
|
||||||
|
parts[k] = block + tail.replace(DRAFT_RE, '').replace(/^\n+/, '\n');
|
||||||
|
if (!/\n$/.test(parts[k]!)) parts[k] += '\n';
|
||||||
|
} else {
|
||||||
|
const last = parts.length - 1;
|
||||||
|
parts[last] = parts[last]!.replace(/\n*$/, '\n\n') + block + (i < secs.length - 1 ? '\n' : '');
|
||||||
|
}
|
||||||
|
secs[i] = parts.join('');
|
||||||
|
return secs.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "us" for en-US, "tr" for tr, "jp" for ja ... : the storefront a locale is most likely meant for. Pure. */
|
||||||
|
export function storefrontOf(locale: string): string {
|
||||||
|
const [l, r] = locale.split('-');
|
||||||
|
if (r && /^[A-Za-z]{2}$/.test(r)) return r.toLowerCase();
|
||||||
|
const map: Record<string, string> = { ja: 'jp', ko: 'kr', zh: locale === 'zh-Hant' ? 'tw' : 'cn', el: 'gr', he: 'il', hi: 'in', uk: 'ua', vi: 'vn', cs: 'cz', da: 'dk', sv: 'se', nb: 'no', ms: 'my', ca: 'es', en: 'us', ar: 'sa' };
|
||||||
|
return map[l!.toLowerCase()] ?? l!.toLowerCase();
|
||||||
|
}
|
||||||
|
|
@ -8,14 +8,18 @@
|
||||||
// title (trackName), developer (sellerName), bundleId, rating and description, but no subtitle: competitor subtitles
|
// title (trackName), developer (sellerName), bundleId, rating and description, but no subtitle: competitor subtitles
|
||||||
// are not available through a public API, so they are not shown (storebound scrapes nothing).
|
// are not available through a public API, so they are not shown (storebound scrapes nothing).
|
||||||
// Result fields used (as the API returns them; Apple's table lists only the general ones): trackId, trackName,
|
// Result fields used (as the API returns them; Apple's table lists only the general ones): trackId, trackName,
|
||||||
// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName.
|
// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName; `aso competitors` also releaseDate,
|
||||||
|
// currentVersionReleaseDate, genres (localized to the storefront, e.g. "Produktivität" for country=de) and genreIds.
|
||||||
|
|
||||||
export const SEARCH_API = 'https://itunes.apple.com/search';
|
export const SEARCH_API = 'https://itunes.apple.com/search';
|
||||||
/** Apple: about 20 calls per minute. One call every 3.5 s stays below it with room for retries. */
|
/** Apple: about 20 calls per minute. One call every 3.5 s stays below it with room for retries. */
|
||||||
export const MIN_DELAY_MS = 3_500;
|
export const MIN_DELAY_MS = 3_500;
|
||||||
export const MAX_RESULTS = 200;
|
export const MAX_RESULTS = 200;
|
||||||
|
|
||||||
export interface SearchApp { trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string }
|
export interface SearchApp {
|
||||||
|
trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string;
|
||||||
|
releaseDate?: string; currentVersionReleaseDate?: string; genres?: string[]; genreIds?: string[]; primaryGenreId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
export function searchUrl(term: string, country: string, limit = MAX_RESULTS): string {
|
export function searchUrl(term: string, country: string, limit = MAX_RESULTS): string {
|
||||||
if (!/^[a-z]{2}$/i.test(country)) throw new Error(`storefront "${country}": a two-letter country code (us, de, tr)`);
|
if (!/^[a-z]{2}$/i.test(country)) throw new Error(`storefront "${country}": a two-letter country code (us, de, tr)`);
|
||||||
|
|
|
||||||
|
|
@ -16,9 +16,9 @@ export const CROSS_LOCALES: Record<string, string[]> = {
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Words that add nothing in the keyword field (Apple: the category name and "app" are matched anyway). */
|
/** Words that add nothing in the keyword field (Apple: the category name and "app" are matched anyway). */
|
||||||
const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']);
|
export const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']);
|
||||||
|
|
||||||
const words = (s: string, locale: string): string[] =>
|
export const words = (s: string, locale: string): string[] =>
|
||||||
s.toLocaleLowerCase(locale).split(/[^\p{L}\p{N}]+/u).filter(w => w.length > 1);
|
s.toLocaleLowerCase(locale).split(/[^\p{L}\p{N}]+/u).filter(w => w.length > 1);
|
||||||
|
|
||||||
/** One locale of the App Store listing: keyword field rules. */
|
/** One locale of the App Store listing: keyword field rules. */
|
||||||
|
|
|
||||||
|
|
@ -101,6 +101,12 @@ export interface ShotFrame { src: string; x?: number; dy?: number; scale?: numbe
|
||||||
export interface Palette { bg: [string, string, string]; glow: string; ink: string; shadow: string }
|
export interface Palette { bg: [string, string, string]; glow: string; ink: string; shadow: string }
|
||||||
export interface ShotScene { id: string; palette: string | Palette; hero?: boolean; frames: ShotFrame[]; badges?: ShotBadgeSlot[]; over?: number }
|
export interface ShotScene { id: string; palette: string | Palette; hero?: boolean; frames: ShotFrame[]; badges?: ShotBadgeSlot[]; over?: number }
|
||||||
|
|
||||||
|
/** A local font file for shots.fonts. license: 'OFL-1.1', 'proprietary' or a short note (shown by `shots fonts`;
|
||||||
|
* `shots check` warns without one). weight / style: the @font-face descriptors (default: all weights, normal). */
|
||||||
|
export interface LocalFontSpec { family?: string; file: string; weight?: number | string; style?: 'normal' | 'italic'; license?: string }
|
||||||
|
/** A Google Fonts family name, a local font path (relative to the config) or a LocalFontSpec. */
|
||||||
|
export type FontSpec = string | LocalFontSpec;
|
||||||
|
|
||||||
export interface ShotsConfig {
|
export interface ShotsConfig {
|
||||||
/** Look of the rendered screenshots: game (sunburst, sparkles, badges, bold outlined titles) or app (calm gradient,
|
/** Look of the rendered screenshots: game (sunburst, sparkles, badges, bold outlined titles) or app (calm gradient,
|
||||||
* device frame, headline + subline, no sparkles or badges). Default: app for the app / subscription-app profiles,
|
* device frame, headline + subline, no sparkles or badges). Default: app for the app / subscription-app profiles,
|
||||||
|
|
@ -114,11 +120,12 @@ export interface ShotsConfig {
|
||||||
out: string;
|
out: string;
|
||||||
/** Optional logo image for the hero scene and the feature graphic. */
|
/** Optional logo image for the hero scene and the feature graphic. */
|
||||||
logo?: string;
|
logo?: string;
|
||||||
/** Google Fonts families for titles / body text (downloaded and subset by `shots fonts`). Default: game Paytone One +
|
/** Fonts for titles / body text: a Google Fonts family (downloaded and subset by `shots fonts`), or your own font file
|
||||||
* Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: Noto families you accept for
|
* (a path relative to the config, TTF / OTF / WOFF / WOFF2, or { family, file, weight?, style?, license? }).
|
||||||
* characters the title / body font lacks (e.g. ['Noto Sans Display']); without it a render that needs an automatic
|
* Default: game Paytone One + Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: fonts you
|
||||||
* fallback is an ERROR in `shots check`. */
|
* accept for characters the title / body font lacks, tried in order before the automatic Noto fallbacks (e.g.
|
||||||
fonts?: { title?: string; body?: string; fallback?: string[] };
|
* ['Noto Sans Display'] or a local file); a render that needs an automatic fallback is an ERROR in `shots check`. */
|
||||||
|
fonts?: { title?: FontSpec; body?: FontSpec; fallback?: FontSpec[] };
|
||||||
scenes: ShotScene[];
|
scenes: ShotScene[];
|
||||||
feature?: { frame: string; palette?: string | Palette };
|
feature?: { frame: string; palette?: string | Palette };
|
||||||
/** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar).
|
/** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar).
|
||||||
|
|
@ -866,6 +873,19 @@ export function validateConfig(c: unknown): string[] {
|
||||||
for (const k of ['copy', 'frames', 'out'] as const) if (!s[k]) e.push(`shots.${k}: missing`);
|
for (const k of ['copy', 'frames', 'out'] as const) if (!s[k]) e.push(`shots.${k}: missing`);
|
||||||
if (s.style !== undefined && s.style !== 'game' && s.style !== 'app') e.push('shots.style: game | app');
|
if (s.style !== undefined && s.style !== 'game' && s.style !== 'app') e.push('shots.style: game | app');
|
||||||
if (!s.scenes?.length) e.push('shots.scenes: at least one scene');
|
if (!s.scenes?.length) e.push('shots.scenes: at least one scene');
|
||||||
|
const fontKeys: [string, unknown][] = [['title', s.fonts?.title], ['body', s.fonts?.body], ...(Array.isArray(s.fonts?.fallback) ? s.fonts!.fallback! : s.fonts?.fallback !== undefined ? [s.fonts.fallback] : []).map((f, i) => [`fallback[${i}]`, f] as [string, unknown])];
|
||||||
|
if (s.fonts?.fallback !== undefined && !Array.isArray(s.fonts.fallback)) e.push('shots.fonts.fallback: a list');
|
||||||
|
for (const [k, f] of fontKeys) {
|
||||||
|
if (f === undefined) continue;
|
||||||
|
if (typeof f === 'string') { if (!f.trim()) e.push(`shots.fonts.${k}: empty`); else if (/[\\/]|\.[a-z0-9]{2,5}$/i.test(f) && !/\.(ttf|otf|woff2?)$/i.test(f)) e.push(`shots.fonts.${k}: ${f}: a font file must be TTF, OTF, WOFF or WOFF2`); continue; }
|
||||||
|
const o = f as Partial<LocalFontSpec>;
|
||||||
|
if (!o || typeof o !== 'object' || typeof o.file !== 'string') { e.push(`shots.fonts.${k}: a Google Fonts family, a font file path or { family, file, weight?, style?, license? }`); continue; }
|
||||||
|
if (!/\.(ttf|otf|woff2?)$/i.test(o.file)) e.push(`shots.fonts.${k}.file: ${o.file}: TTF, OTF, WOFF or WOFF2`);
|
||||||
|
if (o.family !== undefined && (typeof o.family !== 'string' || !o.family.trim())) e.push(`shots.fonts.${k}.family: a name`);
|
||||||
|
if (o.style !== undefined && o.style !== 'normal' && o.style !== 'italic') e.push(`shots.fonts.${k}.style: normal | italic`);
|
||||||
|
if (o.weight !== undefined && !/^\d{3}( \d{3})?$/.test(String(o.weight))) e.push(`shots.fonts.${k}.weight: e.g. 400, 800 or "100 900"`);
|
||||||
|
if (o.license !== undefined && typeof o.license !== 'string') e.push(`shots.fonts.${k}.license: text ('OFL-1.1', 'proprietary', ...)`);
|
||||||
|
}
|
||||||
for (const sc of s.scenes ?? []) if (!sc.frames?.length) e.push(`shots.scenes[${sc.id}].frames: at least one frame`);
|
for (const sc of s.scenes ?? []) if (!sc.frames?.length) e.push(`shots.scenes[${sc.id}].frames: at least one frame`);
|
||||||
e.push(...validateCapture(s.capture));
|
e.push(...validateCapture(s.capture));
|
||||||
const sceneIds = new Set((s.scenes ?? []).map(x => x.id));
|
const sceneIds = new Set((s.scenes ?? []).map(x => x.id));
|
||||||
|
|
|
||||||
|
|
@ -322,6 +322,17 @@ export interface AnalyticsCompare {
|
||||||
/** Per store with no days in any snapshot: why the newest snapshot has none (no report request yet, no bucket). */
|
/** Per store with no days in any snapshot: why the newest snapshot has none (no report request yet, no bucket). */
|
||||||
errors?: { apple?: string; play?: string };
|
errors?: { apple?: string; play?: string };
|
||||||
}
|
}
|
||||||
|
/** aso.audit (`aso audit --json`, offline, cli/lib/aso-audit.ts AsoAudit): the parts the Growth tab's ASO card shows. */
|
||||||
|
export interface AsoTrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: '↑' | '↓' | '→' | 'new' | 'lost' | '·'; best: number | null; snapshots: number }
|
||||||
|
export interface AsoAuditView {
|
||||||
|
generated: string;
|
||||||
|
keywordField: { errors: number; warnings: number; hints: number; findings: { level: 'error' | 'warn' | 'info'; where: string; msg: string }[] };
|
||||||
|
drafts: string[];
|
||||||
|
ranks: { snapshots: number; latest: string | null; rows: AsoTrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] };
|
||||||
|
competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: { word: string; apps: number; developers: number }[] }[] };
|
||||||
|
experiments: { store: 'apple' | 'play'; what: string; why: string; how: string }[];
|
||||||
|
next: { what: string; why: string; command?: string }[];
|
||||||
|
}
|
||||||
/** console.fill (`console fill <form> --json`, cli/console/fill.ts): the answers it types into one console form. The
|
/** console.fill (`console fill <form> --json`, cli/console/fill.ts): the answers it types into one console form. The
|
||||||
* dry run has the answers only; the real run (it ends when the owner closes the browser) adds what happened. */
|
* dry run has the answers only; the real run (it ends when the owner closes the browser) adds what happened. */
|
||||||
export type ConsoleForm = 'apple-app-record' | 'apple-age-rating' | 'apple-app-privacy' | 'play-app-record' | 'play-content-rating' | 'play-target-audience';
|
export type ConsoleForm = 'apple-app-record' | 'apple-age-rating' | 'apple-app-privacy' | 'play-app-record' | 'play-content-rating' | 'play-target-audience';
|
||||||
|
|
|
||||||
|
|
@ -129,7 +129,9 @@ export function normalizeKeywords(text: string, o: { name?: string; subtitle?: s
|
||||||
return { text: kept.join(','), dropped };
|
return { text: kept.join(','), dropped };
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; limit: number; problems: string[] }
|
/** `chars` is what the store counts: characters, except App Store keywords, which App Store Connect limits in UTF-8 bytes
|
||||||
|
* (`unit` says which). */
|
||||||
|
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; unit: 'chars' | 'bytes'; limit: number; problems: string[] }
|
||||||
|
|
||||||
/** Limits and rules of one translated section. `source` = the source language's fields (identical text is flagged). */
|
/** Limits and rules of one translated section. `source` = the source language's fields (identical text is flagged). */
|
||||||
export function checkFields(store: 'apple' | 'play', f: Record<string, string | undefined>, source: Record<string, string | undefined> = {}, status?: TStatus): FieldCheck[] {
|
export function checkFields(store: 'apple' | 'play', f: Record<string, string | undefined>, source: Record<string, string | undefined> = {}, status?: TStatus): FieldCheck[] {
|
||||||
|
|
@ -139,10 +141,11 @@ export function checkFields(store: 'apple' | 'play', f: Record<string, string |
|
||||||
const v = f[k];
|
const v = f[k];
|
||||||
if (v === undefined) continue;
|
if (v === undefined) continue;
|
||||||
const limit = (FIELD_LIMITS[store] as Record<string, number>)[k]!;
|
const limit = (FIELD_LIMITS[store] as Record<string, number>)[k]!;
|
||||||
const c: FieldCheck = { store, field: k, chars: len(v), limit, problems: [] };
|
const bytes = store === 'apple' && k === 'keywords';
|
||||||
if (len(v) > limit) c.problems.push(`${len(v)} > ${limit} characters`);
|
const n = bytes ? Buffer.byteLength(v, 'utf8') : len(v);
|
||||||
if (store === 'apple' && k === 'keywords') {
|
const c: FieldCheck = { store, field: k, chars: n, unit: bytes ? 'bytes' : 'chars', limit, problems: [] };
|
||||||
if (Buffer.byteLength(v) > limit) c.problems.push(`${Buffer.byteLength(v)} bytes > ${limit}`);
|
if (n > limit) c.problems.push(`${n} > ${limit} ${bytes ? 'bytes' : 'characters'}`);
|
||||||
|
if (bytes) {
|
||||||
if (/,\s|\s,/.test(v)) c.problems.push('spaces around commas');
|
if (/,\s|\s,/.test(v)) c.problems.push('spaces around commas');
|
||||||
const words = v.split(',').map(w => w.trim().toLocaleLowerCase()).filter(Boolean);
|
const words = v.split(',').map(w => w.trim().toLocaleLowerCase()).filter(Boolean);
|
||||||
const dup = words.filter((w, i) => words.indexOf(w) !== i);
|
const dup = words.filter((w, i) => words.indexOf(w) !== i);
|
||||||
|
|
|
||||||
|
|
@ -116,7 +116,10 @@ const COMPETITORS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat',
|
||||||
'amazon', 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run',
|
'amazon', 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run',
|
||||||
'angry birds', 'tetris', 'wordle', 'duolingo', 'zoom', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'notion', 'evernote', 'photoshop', 'canva', 'capcut', 'iphone', 'ipad', 'apple'];
|
'angry birds', 'tetris', 'wordle', 'duolingo', 'zoom', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'notion', 'evernote', 'photoshop', 'canva', 'capcut', 'iphone', 'ipad', 'apple'];
|
||||||
const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/;
|
const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/;
|
||||||
const PLACEHOLDER = /lorem ipsum|\bTODO\b|\bTBD\b|\bFIXME\b|\bplaceholder\b|\bXXX\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
|
// Developer markers count only in capitals ("TODO:", "FIXME"): "todo" is a real word and keyword (a to-do app).
|
||||||
|
const PLACEHOLDER_MARKERS = /\bTODO\b|\bTBD\b|\bFIXME\b|\bXXX\b/;
|
||||||
|
const PLACEHOLDER_TEXT = /lorem ipsum|\bplaceholder\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
|
||||||
|
const PLACEHOLDER = { test: (l: string) => PLACEHOLDER_MARKERS.test(l) || PLACEHOLDER_TEXT.test(l) } as RegExp;
|
||||||
const FGS_PERMISSION: Record<string, string> = {
|
const FGS_PERMISSION: Record<string, string> = {
|
||||||
camera: 'CAMERA', connectedDevice: 'CONNECTED_DEVICE', dataSync: 'DATA_SYNC', health: 'HEALTH', location: 'LOCATION', mediaPlayback: 'MEDIA_PLAYBACK',
|
camera: 'CAMERA', connectedDevice: 'CONNECTED_DEVICE', dataSync: 'DATA_SYNC', health: 'HEALTH', location: 'LOCATION', mediaPlayback: 'MEDIA_PLAYBACK',
|
||||||
mediaProjection: 'MEDIA_PROJECTION', microphone: 'MICROPHONE', phoneCall: 'PHONE_CALL', remoteMessaging: 'REMOTE_MESSAGING', specialUse: 'SPECIAL_USE',
|
mediaProjection: 'MEDIA_PROJECTION', microphone: 'MICROPHONE', phoneCall: 'PHONE_CALL', remoteMessaging: 'REMOTE_MESSAGING', specialUse: 'SPECIAL_USE',
|
||||||
|
|
|
||||||
|
|
@ -127,7 +127,7 @@ async function translate(ctx: Ctx): Promise<void> {
|
||||||
if (a.has('json')) printJson({ source: src.id, dryRun: dry, hook: !!hook, files: { apple: files.apple?.path ?? null, play: files.play?.path ?? null }, results: rows.map(r => ({ ...r, problems: problemsOf(r) })) });
|
if (a.has('json')) printJson({ source: src.id, dryRun: dry, hook: !!hook, files: { apple: files.apple?.path ?? null, play: files.play?.path ?? null }, results: rows.map(r => ({ ...r, problems: problemsOf(r) })) });
|
||||||
else {
|
else {
|
||||||
console.log(textTable(['language', 'store', 'section', 'fields', 'problems'], rows.map(r => [r.lang, r.store === 'apple' ? 'App Store' : 'Google Play', r.action,
|
console.log(textTable(['language', 'store', 'section', 'fields', 'problems'], rows.map(r => [r.lang, r.store === 'apple' ? 'App Store' : 'Google Play', r.action,
|
||||||
r.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '), problemsOf(r).join('; ')])));
|
r.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '), problemsOf(r).join('; ')])));
|
||||||
}
|
}
|
||||||
const json = a.has('json');
|
const json = a.has('json');
|
||||||
if (dry) { if (!json) done(TAG, 'dry run: listing files not written'); return; }
|
if (dry) { if (!json) done(TAG, 'dry run: listing files not written'); return; }
|
||||||
|
|
@ -167,7 +167,7 @@ function check(ctx: Ctx): void {
|
||||||
if (ctx.args.has('json')) printJson({ sections: r, ok: !bad.length, drafts: drafts.map(d => `${d.store}:${d.lang}`) });
|
if (ctx.args.has('json')) printJson({ sections: r, ok: !bad.length, drafts: drafts.map(d => `${d.store}:${d.lang}`) });
|
||||||
else {
|
else {
|
||||||
console.log(textTable(['store', 'language', 'status', 'fields', 'problems'], r.map(x => [x.store === 'apple' ? 'App Store' : 'Google Play', x.lang,
|
console.log(textTable(['store', 'language', 'status', 'fields', 'problems'], r.map(x => [x.store === 'apple' ? 'App Store' : 'Google Play', x.lang,
|
||||||
x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '),
|
x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '),
|
||||||
x.checks.flatMap(c => c.problems.map(p => `${c.field}: ${p}`)).join('; ')])));
|
x.checks.flatMap(c => c.problems.map(p => `${c.field}: ${p}`)).join('; ')])));
|
||||||
if (drafts.length) warn(TAG, `${drafts.length} machine-translated draft(s) not reviewed yet: ${drafts.map(d => `${d.store}:${d.lang}`).join(', ')} (storebound listing reviewed --lang <ids> after reading them)`);
|
if (drafts.length) warn(TAG, `${drafts.length} machine-translated draft(s) not reviewed yet: ${drafts.map(d => `${d.store}:${d.lang}`).join(', ')} (storebound listing reviewed --lang <ids> after reading them)`);
|
||||||
done(TAG, bad.length ? `${bad.length} section(s) with problems` : `${r.length} section(s) within the store limits`);
|
done(TAG, bad.length ? `${bad.length} section(s) with problems` : `${r.length} section(s) within the store limits`);
|
||||||
|
|
|
||||||
|
|
@ -163,7 +163,8 @@ export const TOOLS: ToolDef[] = [
|
||||||
props: { only, csv: { type: 'string', description: 'Prices CSV with rows for subscription ids' } },
|
props: { only, csv: { type: 'string', description: 'Prices CSV with rows for subscription ids' } },
|
||||||
args: i => [...opt('only', i.only), ...opt('csv', i.csv)] },
|
args: i => [...opt('only', i.only), ...opt('csv', i.csv)] },
|
||||||
{ name: 'play_data_safety', title: 'Push Play Data safety', command: ['play', 'data-safety'], write: true, destructive: true, network: true, idempotent: true,
|
{ name: 'play_data_safety', title: 'Push Play Data safety', command: ['play', 'data-safety'], write: true, destructive: true, network: true, idempotent: true,
|
||||||
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). dry_run prints the CSV.' },
|
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). Skipped when the CSV equals the last upload of this project (hash in .storebound/; force: true sends it anyway). dry_run prints the CSV.',
|
||||||
|
props: { force: { type: 'boolean', default: false, description: 'Upload even when the CSV equals the last upload (after a manual change in Play Console)' } }, args: i => flag('force', i.force) },
|
||||||
{ name: 'play_release_testing', title: 'Release to a Play testing track', command: ['play', 'release'], write: true, network: true,
|
{ name: 'play_release_testing', title: 'Release to a Play testing track', command: ['play', 'release'], write: true, network: true,
|
||||||
description: 'Upload an AAB (or reuse a versionCode) to a TESTING track (internal, alpha, beta) with release notes. Production is not available here.',
|
description: 'Upload an AAB (or reuse a versionCode) to a TESTING track (internal, alpha, beta) with release notes. Production is not available here.',
|
||||||
props: { aab: { type: 'string', description: 'Path to the .aab' }, version_code: { type: 'integer', minimum: 1 },
|
props: { aab: { type: 'string', description: 'Path to the .aab' }, version_code: { type: 'integer', minimum: 1 },
|
||||||
|
|
@ -356,6 +357,20 @@ export const TOOLS: ToolDef[] = [
|
||||||
props: { storefronts: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,de=de-DE (default us)' }, keywords: { type: 'string', description: 'Extra keywords, comma-separated' },
|
props: { storefronts: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,de=de-DE (default us)' }, keywords: { type: 'string', description: 'Extra keywords, comma-separated' },
|
||||||
competitors: { type: 'integer', minimum: 0, maximum: 10, default: 3 } },
|
competitors: { type: 'integer', minimum: 0, maximum: 10, default: 3 } },
|
||||||
args: i => [...opt('storefronts', i.storefronts), ...opt('keywords', i.keywords), ...opt('competitors', i.competitors), '--json'] },
|
args: i => [...opt('storefronts', i.storefronts), ...opt('keywords', i.keywords), ...opt('competitors', i.competitors), '--json'] },
|
||||||
|
{ name: 'aso_competitors', title: 'App Store competitors per keyword', command: ['aso', 'competitors'], write: false, network: true,
|
||||||
|
description: 'Read-only: for each keyword of the locale\'s keyword field (plus terms) and storefront, the top apps in Apple\'s public iTunes Search API (name, developer, rating count, first release, last update, localized genre) and the words in their names that your name / subtitle / keywords do not cover (only words of at least two developers: a one-developer word is likely a brand). One request every 3.5 s. Saves no snapshot (the terminal run `storebound aso competitors` does). Search API order is close to, not equal to, App Store search; competitor subtitles are not in any public API.',
|
||||||
|
props: { storefront: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,tr (default us)' },
|
||||||
|
terms: { type: 'string', description: 'Extra terms, comma-separated' }, top: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
|
||||||
|
args: i => [...opt('storefront', i.storefront), ...opt('term', i.terms), ...opt('top', i.top), '--no-save', '--json'] },
|
||||||
|
{ name: 'aso_suggest', title: 'Keyword field proposal', command: ['aso', 'suggest'], write: false, network: true,
|
||||||
|
description: 'Read-only proposal: keyword candidates per App Store locale from your own name / subtitle / description, the latest `aso competitors` snapshot, the localized category names and, when Apple Ads credentials exist, Apple Ads keyword suggestions (relative popularity 0-100; without credentials popularity is "unknown", never estimated). Scores relevance (own text, competitor names) and competition (top apps with the word in their name) and returns a 100-byte keyword field per locale as old -> new. Never writes: the owner runs `storebound aso suggest --write` in a terminal, which marks the result as a draft for review.',
|
||||||
|
props: { locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale of store/appstore.md)' },
|
||||||
|
fresh: { type: 'boolean', default: false, description: 'Do not keep the current keywords first' }, offline: { type: 'boolean', default: false, description: 'Skip Apple Ads' } },
|
||||||
|
args: i => [...opt('locale', i.locale), ...flag('fresh', i.fresh), ...flag('offline', i.offline), '--json'] },
|
||||||
|
{ name: 'aso_audit', title: 'ASO audit', command: ['aso', 'audit'], write: false, network: false,
|
||||||
|
description: 'Offline ASO report: keyword field findings (check --aso), cross-locale free keyword room, rank trend from the `aso rank` snapshots, competitor coverage gaps, Play short description use and keyword density, App Store analytics conversion from the snapshots, Product Page Optimization / Play experiment ideas (suggestions only) and the next 3 actions.',
|
||||||
|
props: { storefront: { type: 'string', description: 'App Store storefront for the cross-locale hint', default: 'US' } },
|
||||||
|
args: i => [...opt('storefront', i.storefront), '--json'] },
|
||||||
{ name: 'ads_scan', title: 'AdAttributionKit scan', command: ['ads', 'scan'], write: false, network: false,
|
{ name: 'ads_scan', title: 'AdAttributionKit scan', command: ['ads', 'scan'], write: false, network: false,
|
||||||
description: 'Local scan of an iOS project for AdAttributionKit and SKAdNetwork: ad network ids (SKAdNetworkItems, AdNetworkIdentifiers, lowercase), postback copy endpoints (AttributionCopyEndpoint, re-engagement copies, NSAdvertisingAttributionReportEndpoint), attribution windows and cooldown, conversion value updates in code, ad SDKs without ids.',
|
description: 'Local scan of an iOS project for AdAttributionKit and SKAdNetwork: ad network ids (SKAdNetworkItems, AdNetworkIdentifiers, lowercase), postback copy endpoints (AttributionCopyEndpoint, re-engagement copies, NSAdvertisingAttributionReportEndpoint), attribution windows and cooldown, conversion value updates in code, ad SDKs without ids.',
|
||||||
props: { ios: { type: 'string', description: 'Path of the iOS project folder, e.g. ios/App' } }, required: ['ios'], args: i => [...opt('ios', i.ios), '--json'] },
|
props: { ios: { type: 'string', description: 'Path of the iOS project folder, e.g. ios/App' } }, required: ['ios'], args: i => [...opt('ios', i.ios), '--json'] },
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,10 @@
|
||||||
// Play Data safety form through applications.dataSafety (CSV import; replaces every earlier answer).
|
// Play Data safety form through applications.dataSafety (CSV import; replaces every earlier answer).
|
||||||
// storebound play data-safety [--csv out.csv] [--dry]
|
// storebound play data-safety [--csv out.csv] [--dry] [--force]
|
||||||
// Answers come from `dataSafety` in storebound.config.ts. --dry only writes / prints the CSV.
|
// Answers come from `dataSafety` in storebound.config.ts. --dry only writes / prints the CSV.
|
||||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
// Play cannot read the form back, so a run compares with what this project uploaded last: the sha256 of that CSV
|
||||||
|
// (per package) is kept in .storebound/data-safety.sha256 (gitignored). The same CSV is not sent again; --force sends it
|
||||||
|
// anyway (e.g. after the form was changed in Play Console by hand).
|
||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { need } from '../lib/ctx';
|
import { need } from '../lib/ctx';
|
||||||
|
|
@ -10,6 +13,27 @@ import { DATA_SAFETY_UPLOADED } from '../lib/declarations';
|
||||||
import { done, log } from '../lib/log';
|
import { done, log } from '../lib/log';
|
||||||
import { playClient } from './client';
|
import { playClient } from './client';
|
||||||
|
|
||||||
|
export const DATA_SAFETY_HASH = '.storebound/data-safety.sha256';
|
||||||
|
|
||||||
|
/** sha256 of the CSV for one package. Pure. */
|
||||||
|
export const dataSafetyHash = (pkg: string, csv: string): string => new Bun.CryptoHasher('sha256').update(`${pkg}\n${csv}`).digest('hex');
|
||||||
|
|
||||||
|
/** The hash of the last upload of this package, null when none is recorded. */
|
||||||
|
export function lastUpload(root: string, pkg: string): { sha256: string; at: string } | null {
|
||||||
|
const f = join(root, DATA_SAFETY_HASH);
|
||||||
|
if (!existsSync(f)) return null;
|
||||||
|
try { return (JSON.parse(readFileSync(f, 'utf8')) as Record<string, { sha256: string; at: string }>)[pkg] ?? null; } catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function rememberUpload(root: string, pkg: string, sha256: string): void {
|
||||||
|
const f = join(root, DATA_SAFETY_HASH);
|
||||||
|
let all: Record<string, { sha256: string; at: string }> = {};
|
||||||
|
try { if (existsSync(f)) all = JSON.parse(readFileSync(f, 'utf8')); } catch { all = {}; }
|
||||||
|
all[pkg] = { sha256, at: new Date().toISOString() };
|
||||||
|
mkdirSync(join(root, '.storebound'), { recursive: true });
|
||||||
|
writeFileSync(f, JSON.stringify(all, null, 2) + '\n');
|
||||||
|
}
|
||||||
|
|
||||||
export async function run(ctx: Ctx): Promise<void> {
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
const { config, root, resolve } = ctx.loaded;
|
const { config, root, resolve } = ctx.loaded;
|
||||||
const csv = dataSafetyCsv(need(config.dataSafety, 'dataSafety'));
|
const csv = dataSafetyCsv(need(config.dataSafety, 'dataSafety'));
|
||||||
|
|
@ -17,10 +41,25 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
if (out) { writeFileSync(resolve(out), csv); log('play', `wrote ${out}`); }
|
if (out) { writeFileSync(resolve(out), csv); log('play', `wrote ${out}`); }
|
||||||
const types = Object.keys(config.dataSafety!.data);
|
const types = Object.keys(config.dataSafety!.data);
|
||||||
log('play', `data safety: ${types.length} data types declared (${types.join(', ') || 'none'})`);
|
log('play', `data safety: ${types.length} data types declared (${types.join(', ') || 'none'})`);
|
||||||
if (ctx.args.has('dry')) { if (!out) process.stdout.write(csv); return; }
|
const pkg = need(config.play?.packageName, 'play.packageName');
|
||||||
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
|
const hash = dataSafetyHash(pkg, csv);
|
||||||
|
const last = lastUpload(root, pkg);
|
||||||
|
const same = last?.sha256 === hash;
|
||||||
|
if (ctx.args.has('dry')) {
|
||||||
|
if (!out) process.stdout.write(csv);
|
||||||
|
log('play', same ? `the same CSV was uploaded ${last!.at.slice(0, 16).replace('T', ' ')} UTC: a real run sends nothing (--force sends it again)` : 'a real run uploads it (it differs from the last upload, or none is recorded)');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (same && !ctx.args.has('force')) {
|
||||||
|
done('play', `data safety unchanged since the upload of ${last!.at.slice(0, 16).replace('T', ' ')} UTC: nothing sent (--force sends it again, e.g. after a change in Play Console)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const play = await playClient(root, pkg);
|
||||||
await play.call('POST', `${play.API}/dataSafety`, { safetyLabels: csv });
|
await play.call('POST', `${play.API}/dataSafety`, { safetyLabels: csv });
|
||||||
// Play cannot read the form back: keep what went up, so the desktop app can show what changed since (gitignored).
|
// keep what went up: the hash skips the next identical upload, the CSV lets the desktop app show what changed since
|
||||||
try { mkdirSync(join(root, '.storebound'), { recursive: true }); writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv); } catch { /* the upload itself worked */ }
|
try {
|
||||||
|
rememberUpload(root, pkg, hash);
|
||||||
|
writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv);
|
||||||
|
} catch { /* the upload itself worked */ }
|
||||||
done('play', `data safety updated (${csv.split('\n').length - 2} rows)`);
|
done('play', `data safety updated (${csv.split('\n').length - 2} rows)`);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -140,16 +140,24 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
if (dry) { done('play', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
|
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 (!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; }
|
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)!);
|
// The edit compares again with what it holds (a Console save or another run since the plan): only differing details
|
||||||
await play.edit(async id => {
|
// and languages are PUT; nothing left to change = the edit is deleted, not committed. Commit only after every PUT worked.
|
||||||
if (p.details.action !== 'same') {
|
let sent = 0;
|
||||||
|
await play.edit(async (id, ctl) => {
|
||||||
|
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 ?? [];
|
||||||
|
const q = playPlan(cur, details, now, bodies, { only: a.has('only') });
|
||||||
|
const todo = q.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
|
||||||
|
sent = q.changes;
|
||||||
|
if (!q.changes) { ctl.unchanged(); return; }
|
||||||
|
if (q.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: ${p.details.changes.map(ch => ch.field).join(', ')}`);
|
log('play', `details: ${q.details.changes.map(ch => ch.field).join(', ')}`);
|
||||||
}
|
}
|
||||||
for (const [i, b] of todo.entries()) {
|
for (const [i, b] of todo.entries()) {
|
||||||
await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b);
|
await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b);
|
||||||
log('play', step(i + 1, todo.length, b.language!));
|
log('play', step(i + 1, todo.length, b.language!));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
done('play', 'listing done');
|
done('play', sent ? 'listing done' : 'listing already up to date (the edit was deleted, nothing committed)');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,7 @@ export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_r
|
||||||
export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i;
|
export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i;
|
||||||
|
|
||||||
/** Read tools whose command prints a structured result with --json. */
|
/** Read tools whose command prints a structured result with --json. */
|
||||||
export const JSON_TOOLS = new Set(['check', 'check_aso', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
export const JSON_TOOLS = new Set(['check', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
||||||
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff',
|
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff',
|
||||||
'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']);
|
'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,8 @@
|
||||||
// Per set: Play 2-8 phone screenshots, Apple 1-10 per display type, 13" iPad set when apple.ipad, feature graphic.
|
// Per set: Play 2-8 phone screenshots, Apple 1-10 per display type, 13" iPad set when apple.ipad, feature graphic.
|
||||||
// Per app preview: 886x1920 / 1200x1600, H.264, <= 30 fps, 15-30 s, stereo AAC track, <= 500 MB, <= 3 per set.
|
// Per app preview: 886x1920 / 1200x1600, H.264, <= 30 fps, 15-30 s, stereo AAC track, <= 500 MB, <= 3 per set.
|
||||||
// Text overflow flags come from the last `shots render` (report.json). Frames: with capture.source "folder" every frame
|
// Text overflow flags come from the last `shots render` (report.json). Frames: with capture.source "folder" every frame
|
||||||
// the scenes use must exist with the right aspect. Exit 1 on any error (warnings do not fail).
|
// the scenes use must exist with the right aspect. Local font files (shots.fonts paths) without a license note: warn.
|
||||||
|
// Exit 1 on any error (warnings do not fail).
|
||||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import type { ShipConfig } from '../lib/config';
|
import type { ShipConfig } from '../lib/config';
|
||||||
|
|
@ -17,6 +18,8 @@ import { defaultSizes, frameDims, SIZES } from './lib';
|
||||||
import type { LocalIssue, RendersCheck } from '../lib/validate-rules';
|
import type { LocalIssue, RendersCheck } from '../lib/validate-rules';
|
||||||
import { allIssues, requiredSets, type RendersScan, scanRenders, storeOf } from './report';
|
import { allIssues, requiredSets, type RendersScan, scanRenders, storeOf } from './report';
|
||||||
import { imageInfo } from './spec';
|
import { imageInfo } from './spec';
|
||||||
|
import { fontsDirOf, readManifest } from './fonts';
|
||||||
|
import { localFontIssues } from './local-fonts';
|
||||||
|
|
||||||
/** Frame files the scenes (and the feature graphic) use, per language and device class. */
|
/** Frame files the scenes (and the feature graphic) use, per language and device class. */
|
||||||
export function framesNeeded(config: ShipConfig, langs: string[]): { lang: string; device: 'phone' | 'tablet'; name: string }[] {
|
export function framesNeeded(config: ShipConfig, langs: string[]): { lang: string; device: 'phone' | 'tablet'; name: string }[] {
|
||||||
|
|
@ -58,9 +61,9 @@ export function rendersCheck(config: ShipConfig, dir: string): Record<'apple' |
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function run(ctx: Ctx): Promise<void> {
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
const { config, resolve } = ctx.loaded;
|
const { config, resolve, root } = ctx.loaded;
|
||||||
const scan = scanProject(ctx);
|
const scan = scanProject(ctx);
|
||||||
const issues = allIssues(scan);
|
const issues = [...allIssues(scan), ...localFontIssues(readManifest(fontsDirOf(root))).map(issue => ({ where: '.storebound/fonts/fonts.json', issue }))];
|
||||||
const cap = config.shots?.capture;
|
const cap = config.shots?.capture;
|
||||||
const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : [];
|
const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : [];
|
||||||
if (ctx.args.has('json')) {
|
if (ctx.args.has('json')) {
|
||||||
|
|
|
||||||
|
|
@ -8,20 +8,25 @@ const tag = (d: DataView, o: number): string => String.fromCharCode(d.getUint8(o
|
||||||
const view = (b: Uint8Array): DataView => new DataView(b.buffer, b.byteOffset, b.byteLength);
|
const view = (b: Uint8Array): DataView => new DataView(b.buffer, b.byteOffset, b.byteLength);
|
||||||
|
|
||||||
/** The raw cmap table of a font file (any of the formats above). Throws on anything else. */
|
/** The raw cmap table of a font file (any of the formats above). Throws on anything else. */
|
||||||
export function cmapTable(file: Uint8Array): Uint8Array {
|
export const cmapTable = (file: Uint8Array): Uint8Array => fontTable(file, 'cmap');
|
||||||
|
|
||||||
|
/** One raw (untransformed) table of a font file, e.g. 'cmap' or 'name'. Throws when the file is not a font or the
|
||||||
|
* table is missing. */
|
||||||
|
export function fontTable(file: Uint8Array, want: string): Uint8Array {
|
||||||
const d = view(file);
|
const d = view(file);
|
||||||
|
if (file.byteLength < 12) throw new Error('not a font file (too short)');
|
||||||
const sig = tag(d, 0);
|
const sig = tag(d, 0);
|
||||||
if (sig === 'wOF2') return woff2Cmap(file);
|
if (sig === 'wOF2') return woff2Table(file, want);
|
||||||
if (sig === 'wOFF') {
|
if (sig === 'wOFF') {
|
||||||
const n = d.getUint16(12);
|
const n = d.getUint16(12);
|
||||||
for (let i = 0; i < n; i++) {
|
for (let i = 0; i < n; i++) {
|
||||||
const o = 44 + i * 20;
|
const o = 44 + i * 20;
|
||||||
if (tag(d, o) !== 'cmap') continue;
|
if (tag(d, o) !== want) continue;
|
||||||
const off = d.getUint32(o + 4), comp = d.getUint32(o + 8), orig = d.getUint32(o + 12);
|
const off = d.getUint32(o + 4), comp = d.getUint32(o + 8), orig = d.getUint32(o + 12);
|
||||||
const raw = file.subarray(off, off + comp);
|
const raw = file.subarray(off, off + comp);
|
||||||
return comp < orig ? new Uint8Array(inflateSync(raw)) : raw;
|
return comp < orig ? new Uint8Array(inflateSync(raw)) : raw;
|
||||||
}
|
}
|
||||||
throw new Error('woff: no cmap table');
|
throw new Error(`woff: no ${want} table`);
|
||||||
}
|
}
|
||||||
let base = 0;
|
let base = 0;
|
||||||
if (sig === 'ttcf') base = d.getUint32(12);
|
if (sig === 'ttcf') base = d.getUint32(12);
|
||||||
|
|
@ -29,9 +34,9 @@ export function cmapTable(file: Uint8Array): Uint8Array {
|
||||||
const n = d.getUint16(base + 4);
|
const n = d.getUint16(base + 4);
|
||||||
for (let i = 0; i < n; i++) {
|
for (let i = 0; i < n; i++) {
|
||||||
const o = base + 12 + i * 16;
|
const o = base + 12 + i * 16;
|
||||||
if (tag(d, o) === 'cmap') { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); }
|
if (tag(d, o) === want) { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); }
|
||||||
}
|
}
|
||||||
throw new Error('sfnt: no cmap table');
|
throw new Error(`sfnt: no ${want} table`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG',
|
const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG',
|
||||||
|
|
@ -39,7 +44,7 @@ const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'pos
|
||||||
'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar',
|
'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar',
|
||||||
'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill'];
|
'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill'];
|
||||||
|
|
||||||
function woff2Cmap(file: Uint8Array): Uint8Array {
|
function woff2Table(file: Uint8Array, want: string): Uint8Array {
|
||||||
const d = view(file);
|
const d = view(file);
|
||||||
const n = d.getUint16(12), compLen = d.getUint32(20);
|
const n = d.getUint16(12), compLen = d.getUint32(20);
|
||||||
let p = 48;
|
let p = 48;
|
||||||
|
|
@ -56,10 +61,10 @@ function woff2Cmap(file: Uint8Array): Uint8Array {
|
||||||
const version = (flags >> 6) & 3;
|
const version = (flags >> 6) & 3;
|
||||||
const transformed = t === 'glyf' || t === 'loca' ? version === 0 : version !== 0;
|
const transformed = t === 'glyf' || t === 'loca' ? version === 0 : version !== 0;
|
||||||
const len = transformed ? base128() : orig;
|
const len = transformed ? base128() : orig;
|
||||||
if (t === 'cmap') found = [off, orig];
|
if (t === want) found = [off, orig];
|
||||||
off += len;
|
off += len;
|
||||||
}
|
}
|
||||||
if (!found) throw new Error('woff2: no cmap table');
|
if (!found) throw new Error(`woff2: no ${want} table`);
|
||||||
if (tag(d, 4) === 'ttcf') { // collection directory: skip it (version, numFonts 255UInt16, per font numTables + indices)
|
if (tag(d, 4) === 'ttcf') { // collection directory: skip it (version, numFonts 255UInt16, per font numTables + indices)
|
||||||
p += 4;
|
p += 4;
|
||||||
const u16 = (): number => { const c = d.getUint8(p++); return c === 253 ? (p += 2, d.getUint16(p - 2)) : c === 255 ? 253 + d.getUint8(p++) : c === 254 ? 506 + d.getUint8(p++) : c; };
|
const u16 = (): number => { const c = d.getUint8(p++); return c === 253 ? (p += 2, d.getUint16(p - 2)) : c === 255 ? 253 + d.getUint8(p++) : c === 254 ? 506 + d.getUint8(p++) : c; };
|
||||||
|
|
@ -110,6 +115,28 @@ function readSub(d: DataView, o: number, out: Set<number>): void {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Family name from the name table (typographic family 16, else family 1; Windows Unicode, else Mac Roman), or null. */
|
||||||
|
export function fontFamilyName(file: Uint8Array): string | null {
|
||||||
|
let t: Uint8Array;
|
||||||
|
try { t = fontTable(file, 'name'); } catch { return null; }
|
||||||
|
const d = view(t);
|
||||||
|
const count = d.getUint16(2), strings = d.getUint16(4);
|
||||||
|
const recs: { pid: number; lang: number; id: number; text: string }[] = [];
|
||||||
|
for (let i = 0; i < count && 6 + i * 12 + 12 <= t.byteLength; i++) {
|
||||||
|
const o = 6 + i * 12;
|
||||||
|
const pid = d.getUint16(o), lang = d.getUint16(o + 4), id = d.getUint16(o + 6), len = d.getUint16(o + 8), off = strings + d.getUint16(o + 10);
|
||||||
|
if ((id !== 1 && id !== 16) || off + len > t.byteLength) continue;
|
||||||
|
const raw = t.subarray(off, off + len);
|
||||||
|
let text = '';
|
||||||
|
if (pid === 3 || pid === 0) for (let k = 0; k + 1 < raw.length; k += 2) text += String.fromCharCode((raw[k]! << 8) | raw[k + 1]!);
|
||||||
|
else if (pid === 1) text = String.fromCharCode(...raw);
|
||||||
|
else continue;
|
||||||
|
recs.push({ pid, lang, id, text: text.trim() });
|
||||||
|
}
|
||||||
|
const score = (r: { pid: number; lang: number; id: number }): number => (r.id === 16 ? 10 : 0) + (r.pid === 3 ? 4 : r.pid === 0 ? 3 : 1) + (r.lang === 0x409 || r.lang === 0 ? 1 : 0);
|
||||||
|
return recs.filter(r => r.text).sort((a, b) => score(b) - score(a))[0]?.text ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Code points a font file covers. */
|
/** Code points a font file covers. */
|
||||||
export const fontCodepoints = (file: Uint8Array): Set<number> => cmapCodepoints(cmapTable(file));
|
export const fontCodepoints = (file: Uint8Array): Set<number> => cmapCodepoints(cmapTable(file));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,14 +8,16 @@
|
||||||
// character no fallback covers fails with the language and the characters.
|
// character no fallback covers fails with the language and the characters.
|
||||||
// storebound shots fonts [--json] (re-run after editing the copy or the fonts)
|
// storebound shots fonts [--json] (re-run after editing the copy or the fonts)
|
||||||
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css + fonts.json (faces and the per-language stacks, read by render).
|
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css + fonts.json (faces and the per-language stacks, read by render).
|
||||||
// All of these fonts are SIL Open Font License 1.1.
|
// The Google fonts are SIL Open Font License 1.1. A local font file in shots.fonts (local-fonts.ts) gets the same cmap
|
||||||
|
// check, is read in place (never copied) and recorded with its path, sha256 and license note.
|
||||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
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, printJson, warn } from '../lib/log';
|
import { done, log, printJson, warn } from '../lib/log';
|
||||||
import { shotsStyle } from '../lib/config';
|
import { shotsStyle } from '../lib/config';
|
||||||
import { type CopyFile, shotFonts } from './lib';
|
import type { CopyFile } from './lib';
|
||||||
|
import { localByFamily, resolveShotFonts } from './local-fonts';
|
||||||
import { fontCodepoints } from './cmap';
|
import { fontCodepoints } from './cmap';
|
||||||
import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs';
|
import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs';
|
||||||
|
|
||||||
|
|
@ -54,14 +56,24 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const dir = fontsDirOf(root);
|
const dir = fontsDirOf(root);
|
||||||
mkdirSync(dir, { recursive: true });
|
mkdirSync(dir, { recursive: true });
|
||||||
const style = shotsStyle(config);
|
const style = shotsStyle(config);
|
||||||
const { title, body, titleVariable } = shotFonts(shots, style);
|
const sf = resolveShotFonts(shots, style, resolve, root);
|
||||||
|
const { titleVariable } = sf;
|
||||||
|
const title = sf.title.family, body = sf.body.family;
|
||||||
|
const local = localByFamily([sf.title, sf.body, ...sf.fallback]);
|
||||||
const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name);
|
const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name);
|
||||||
|
|
||||||
const sizes: string[] = [];
|
const sizes: string[] = [];
|
||||||
const manifest = await planFonts({
|
const manifest = await planFonts({
|
||||||
langs: texts, title, body, titleAxis: titleVariable ? 'wght@100..900' : null, bodyAxis: 'wght@100..900',
|
langs: texts, title, body, titleAxis: titleVariable ? 'wght@100..900' : null, bodyAxis: 'wght@100..900',
|
||||||
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: shots.fonts?.fallback, base: ASCII,
|
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: sf.fallback.map(f => f.family), base: ASCII, local,
|
||||||
}, async (job: FaceJob) => {
|
}, async (job: FaceJob) => {
|
||||||
|
if (job.local) { // read in place: the whole file's cmap
|
||||||
|
const bin = new Uint8Array(readFileSync(join(root, job.local.path)));
|
||||||
|
const cps = fontCodepoints(bin);
|
||||||
|
const line = `${job.local.path} ${job.family}, ${(bin.byteLength / 1024).toFixed(1)} KB, ${cps.size} in the cmap, sha256 ${job.local.hash}, license: ${job.local.license ?? 'none noted (add license to the shots.fonts entry)'}`;
|
||||||
|
if (!sizes.includes(line)) sizes.push(line);
|
||||||
|
return cps;
|
||||||
|
}
|
||||||
let bin: Uint8Array;
|
let bin: Uint8Array;
|
||||||
try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) {
|
try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) {
|
||||||
if (job.kind !== 'fallback') throw e;
|
if (job.kind !== 'fallback') throw e;
|
||||||
|
|
@ -77,12 +89,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
writeFileSync(join(dir, 'fonts.json'), JSON.stringify(manifest, null, 1) + '\n');
|
writeFileSync(join(dir, 'fonts.json'), JSON.stringify(manifest, null, 1) + '\n');
|
||||||
if (ctx.args.has('json')) return printJson(manifest);
|
if (ctx.args.has('json')) return printJson(manifest);
|
||||||
for (const s of sizes) log('shots', s);
|
for (const s of sizes) log('shots', s);
|
||||||
|
for (const f of Object.values(local)) if (!f.license) warn('shots', `local font ${f.path} has no license note: add license ('OFL-1.1', 'proprietary', ...) to its shots.fonts entry`);
|
||||||
let auto = 0;
|
let auto = 0;
|
||||||
for (const [lang, l] of Object.entries(manifest.langs)) for (const f of l.fallbacks) {
|
for (const [lang, l] of Object.entries(manifest.langs)) for (const f of l.fallbacks) {
|
||||||
const ok = manifest.faces[f.face]?.chosen;
|
const ok = manifest.faces[f.face]?.chosen;
|
||||||
if (!ok) auto++;
|
if (!ok) auto++;
|
||||||
const base = f.role === 'title' ? title : body;
|
const base = f.role === 'title' ? title : body;
|
||||||
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}`);
|
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}${manifest.faces[f.face]?.local ? ' (local file)' : ''}`);
|
||||||
}
|
}
|
||||||
if (auto) warn('shots', `${auto} automatic fallbacks: renders that use them fail \`shots check\`. Pick title / body fonts that cover them${style === 'game' ? ' (titles: e.g. Paytone One, Baloo 2, Rowdies)' : ''} or accept the fallback with shots.fonts.fallback: ['<family>']`);
|
if (auto) warn('shots', `${auto} automatic fallbacks: renders that use them fail \`shots check\`. Pick title / body fonts that cover them${style === 'game' ? ' (titles: e.g. Paytone One, Baloo 2, Rowdies)' : ''} or accept the fallback with shots.fonts.fallback: ['<family>']`);
|
||||||
done('shots', 'fonts done');
|
done('shots', 'fonts done');
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@
|
||||||
import type { SceneCopy } from './lib';
|
import type { SceneCopy } from './lib';
|
||||||
import { scriptFont } from './lib';
|
import { scriptFont } from './lib';
|
||||||
import { needsGlyph } from './cmap';
|
import { needsGlyph } from './cmap';
|
||||||
|
import { type LocalFontInfo, localFile, slug } from './local-fonts';
|
||||||
|
|
||||||
export type Role = 'title' | 'body';
|
export type Role = 'title' | 'body';
|
||||||
export interface RoleTexts { title: string; body: string }
|
export interface RoleTexts { title: string; body: string }
|
||||||
|
|
@ -61,16 +62,16 @@ export function fallbackFamilies(ch: string, lang: string, role: Role): string[]
|
||||||
export const FALLBACK_ORDER = ['Noto Sans Display', 'Noto Sans', 'Noto Sans KR', 'Noto Sans JP', 'Noto Sans SC', 'Noto Sans TC',
|
export const FALLBACK_ORDER = ['Noto Sans Display', 'Noto Sans', 'Noto Sans KR', 'Noto Sans JP', 'Noto Sans SC', 'Noto Sans TC',
|
||||||
...NOTO_SCRIPTS.map(s => `Noto Sans ${s}`), ...SYMBOLS];
|
...NOTO_SCRIPTS.map(s => `Noto Sans ${s}`), ...SYMBOLS];
|
||||||
|
|
||||||
const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
|
||||||
|
|
||||||
export type FaceKind = 'title' | 'body' | 'script' | 'fallback';
|
export type FaceKind = 'title' | 'body' | 'script' | 'fallback';
|
||||||
/** One downloaded face: `face` is the @font-face family name the templates use. axis: css2 axis spec ("wght@800",
|
/** One downloaded face: `face` is the @font-face family name the templates use. axis: css2 axis spec ("wght@800",
|
||||||
* "wght@100..900") or null for the font's default instance. */
|
* "wght@100..900") or null for the font's default instance. */
|
||||||
export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string }
|
export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string; local?: LocalFontInfo }
|
||||||
export interface LangFonts { title: string[]; body: string[]; fallbacks: { role: Role; face: string; family: string; chars: string }[] }
|
export interface LangFonts { title: string[]; body: string[]; fallbacks: { role: Role; face: string; family: string; chars: string }[] }
|
||||||
export interface FontManifest {
|
export interface FontManifest {
|
||||||
v: 1;
|
v: 1;
|
||||||
faces: Record<string, { family: string; file: string; kind: FaceKind; role?: Role; chosen: boolean }>;
|
/** local: a local font file (shots.fonts entry with a path), read in place, never copied; file = its served path. */
|
||||||
|
faces: Record<string, { family: string; file: string; kind: FaceKind; role?: Role; chosen: boolean; local?: LocalFontInfo }>;
|
||||||
langs: Record<string, LangFonts>;
|
langs: Record<string, LangFonts>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -81,8 +82,11 @@ export interface PlanInput {
|
||||||
titleAxis: string | null; bodyAxis: string | null;
|
titleAxis: string | null; bodyAxis: string | null;
|
||||||
/** Weight axis for automatic title fallbacks (game titles are heavy display faces: "wght@800"). */
|
/** Weight axis for automatic title fallbacks (game titles are heavy display faces: "wght@800"). */
|
||||||
fallbackTitleAxis: string | null;
|
fallbackTitleAxis: string | null;
|
||||||
/** shots.fonts.fallback: families the owner accepts as fallbacks. */
|
/** shots.fonts.fallback: families the owner accepts as fallbacks, in order. Families that are not one of the automatic
|
||||||
|
* Noto fallbacks (another Google family, a local file) are tried first, for every character the stack lacks. */
|
||||||
chosen?: string[];
|
chosen?: string[];
|
||||||
|
/** Local font files by family (title, body or fallback). */
|
||||||
|
local?: Record<string, LocalFontInfo>;
|
||||||
/** Extra characters for the title / body downloads (ASCII, so later copy edits rarely need a new download). */
|
/** Extra characters for the title / body downloads (ASCII, so later copy edits rarely need a new download). */
|
||||||
base?: string;
|
base?: string;
|
||||||
}
|
}
|
||||||
|
|
@ -100,6 +104,11 @@ export class GlyphError extends Error {
|
||||||
* and returns the code points its cmap covers. Throws GlyphError when no fallback covers a character. */
|
* and returns the code points its cmap covers. Throws GlyphError when no fallback covers a character. */
|
||||||
export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise<Set<number>>): Promise<FontManifest> {
|
export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise<Set<number>>): Promise<FontManifest> {
|
||||||
const chosen = new Set((input.chosen ?? []).map(s => s.toLowerCase()));
|
const chosen = new Set((input.chosen ?? []).map(s => s.toLowerCase()));
|
||||||
|
const local = input.local ?? {};
|
||||||
|
const extra = [...new Set(input.chosen ?? [])].filter(f => !FALLBACK_ORDER.some(n => n.toLowerCase() === f.toLowerCase()));
|
||||||
|
const order = [...extra, ...FALLBACK_ORDER];
|
||||||
|
const fileOf = (family: string, google: string): string => local[family] ? localFile(family, local[family]!) : google;
|
||||||
|
const loc = (family: string): { local?: LocalFontInfo } => (local[family] ? { local: local[family] } : {});
|
||||||
const base = input.base ?? '';
|
const base = input.base ?? '';
|
||||||
const scripts = new Map<string, { family: string; chars: Set<string> }>();
|
const scripts = new Map<string, { family: string; chars: Set<string> }>();
|
||||||
const langScript = new Map<string, string | null>();
|
const langScript = new Map<string, string | null>();
|
||||||
|
|
@ -121,13 +130,13 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
|
||||||
const add = async (job: FaceJob, isChosen: boolean): Promise<void> => {
|
const add = async (job: FaceJob, isChosen: boolean): Promise<void> => {
|
||||||
cps.set(job.face, await get(job));
|
cps.set(job.face, await get(job));
|
||||||
if (job.kind === 'fallback' && ![...job.chars].some(ch => cps.get(job.face)!.has(ch.codePointAt(0)!))) return; // covers none: not a face
|
if (job.kind === 'fallback' && ![...job.chars].some(ch => cps.get(job.face)!.has(ch.codePointAt(0)!))) return; // covers none: not a face
|
||||||
faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen };
|
faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen, ...(job.local ? { local: job.local } : {}) };
|
||||||
};
|
};
|
||||||
await add({ face: input.title, family: input.title, file: 'title.woff2', kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title) }, true);
|
await add({ face: input.title, family: input.title, file: fileOf(input.title, 'title.woff2'), kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title), ...loc(input.title) }, true);
|
||||||
if (input.body !== input.title) await add({ face: input.body, family: input.body, file: 'body.woff2', kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body) }, true);
|
if (input.body !== input.title) await add({ face: input.body, family: input.body, file: fileOf(input.body, 'body.woff2'), kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body), ...loc(input.body) }, true);
|
||||||
else { // same family: one download (title axis) with both roles' characters
|
else { // same family: one download (title axis) with both roles' characters
|
||||||
const t = faces[input.title]!;
|
const t = faces[input.title]!;
|
||||||
cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]) }));
|
cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]), ...loc(input.title) }));
|
||||||
}
|
}
|
||||||
for (const [s, v] of scripts) await add({ face: `Store ${s}`, family: v.family, file: `${s}.woff2`, kind: 'script', axis: 'wght@100..900', chars: sorted(v.chars) }, true);
|
for (const [s, v] of scripts) await add({ face: `Store ${s}`, family: v.family, file: `${s}.woff2`, kind: 'script', axis: 'wght@100..900', chars: sorted(v.chars) }, true);
|
||||||
|
|
||||||
|
|
@ -139,17 +148,17 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
|
||||||
langs[lang] = { title: [...(x ? [x] : []), input.title], body: [...(x ? [x] : []), input.body], fallbacks: [] };
|
langs[lang] = { title: [...(x ? [x] : []), input.title], body: [...(x ? [x] : []), input.body], fallbacks: [] };
|
||||||
for (const role of ['title', 'body'] as const) {
|
for (const role of ['title', 'body'] as const) {
|
||||||
const stack = langs[lang]![role].map(f => cps.get(f)!);
|
const stack = langs[lang]![role].map(f => cps.get(f)!);
|
||||||
for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: fallbackFamilies(ch, lang, role) });
|
for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: [...extra, ...fallbackFamilies(ch, lang, role)] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const gaps = new Map<string, { lang: string; role: Role; chars: string[]; tried: string[] }>();
|
const gaps = new Map<string, { lang: string; role: Role; chars: string[]; tried: string[] }>();
|
||||||
const hits = new Map<string, Map<string, Set<string>>>(); // lang|role -> face -> chars
|
const hits = new Map<string, Map<string, Set<string>>>(); // lang|role -> face -> chars
|
||||||
for (const role of ['title', 'body'] as const) for (const family of FALLBACK_ORDER) {
|
for (const role of ['title', 'body'] as const) for (const family of order) {
|
||||||
const want = pending.filter(p => p.role === role && p.tries.includes(family));
|
const want = pending.filter(p => p.role === role && p.tries.includes(family));
|
||||||
if (!want.length) continue;
|
if (!want.length) continue;
|
||||||
const face = `Store fb ${slug(family)} ${role}`;
|
const face = `Store fb ${slug(family)} ${role}`;
|
||||||
const axis = family === 'Noto Color Emoji' ? null : role === 'title' ? input.fallbackTitleAxis : 'wght@100..900';
|
const axis = family === 'Noto Color Emoji' ? null : role === 'title' ? input.fallbackTitleAxis : 'wght@100..900';
|
||||||
await add({ face, family, file: `fb-${slug(family)}-${role}.woff2`, kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)) }, chosen.has(family.toLowerCase()));
|
await add({ face, family, file: fileOf(family, `fb-${slug(family)}-${role}.woff2`), kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)), ...loc(family) }, chosen.has(family.toLowerCase()));
|
||||||
const got = cps.get(face)!;
|
const got = cps.get(face)!;
|
||||||
for (const p of want) {
|
for (const p of want) {
|
||||||
p.tries = p.tries.filter(f => f !== family);
|
p.tries = p.tries.filter(f => f !== family);
|
||||||
|
|
@ -165,14 +174,14 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
|
||||||
for (const p of pending) {
|
for (const p of pending) {
|
||||||
if ((p as { done?: boolean }).done) continue;
|
if ((p as { done?: boolean }).done) continue;
|
||||||
const k = `${p.lang}|${p.role}`;
|
const k = `${p.lang}|${p.role}`;
|
||||||
const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...fallbackFamilies(p.ch, p.lang, p.role)] };
|
const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...extra, ...fallbackFamilies(p.ch, p.lang, p.role)] };
|
||||||
g.chars.push(p.ch);
|
g.chars.push(p.ch);
|
||||||
gaps.set(k, g);
|
gaps.set(k, g);
|
||||||
}
|
}
|
||||||
if (gaps.size) throw new GlyphError([...gaps.values()]);
|
if (gaps.size) throw new GlyphError([...gaps.values()]);
|
||||||
for (const [k, m] of hits) {
|
for (const [k, m] of hits) {
|
||||||
const [lang, role] = k.split('|') as [string, Role];
|
const [lang, role] = k.split('|') as [string, Role];
|
||||||
for (const face of [...m.keys()].sort((a, b) => FALLBACK_ORDER.indexOf(faces[a]!.family) - FALLBACK_ORDER.indexOf(faces[b]!.family))) {
|
for (const face of [...m.keys()].sort((a, b) => order.indexOf(faces[a]!.family) - order.indexOf(faces[b]!.family))) {
|
||||||
langs[lang]![role].push(face);
|
langs[lang]![role].push(face);
|
||||||
langs[lang]!.fallbacks.push({ role, face, family: faces[face]!.family, chars: [...m.get(face)!].join('') });
|
langs[lang]!.fallbacks.push({ role, face, family: faces[face]!.family, chars: [...m.get(face)!].join('') });
|
||||||
}
|
}
|
||||||
|
|
@ -187,6 +196,12 @@ export function fontsCss(m: FontManifest): string {
|
||||||
for (const [face, f] of Object.entries(m.faces)) {
|
for (const [face, f] of Object.entries(m.faces)) {
|
||||||
if (seen.has(face)) continue;
|
if (seen.has(face)) continue;
|
||||||
seen.add(face);
|
seen.add(face);
|
||||||
|
if (f.local) { // the project's own font file, served in place; ?v= changes with its content
|
||||||
|
const l = f.local;
|
||||||
|
css += `/* ${f.family}: local file ${l.path} (${l.license ? 'license: ' + l.license.replace(/\*\//g, '') : 'no license note'}) */\n`;
|
||||||
|
css += `@font-face { font-family: '${face}'; font-weight: ${l.weight ?? '100 900'}; font-style: ${l.style ?? 'normal'}; font-synthesis: none; src: url(${f.file}?v=${l.hash}) format('${l.format}'); }\n`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
css += `@font-face { font-family: '${face}'; font-weight: 100 900; font-synthesis: none; src: url(${f.file}) format('woff2'); }\n`;
|
css += `@font-face { font-family: '${face}'; font-weight: 100 900; font-synthesis: none; src: url(${f.file}) format('woff2'); }\n`;
|
||||||
}
|
}
|
||||||
return css;
|
return css;
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
// Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data.
|
// Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data.
|
||||||
|
import { specFamily } from './local-fonts';
|
||||||
import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config';
|
import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config';
|
||||||
|
|
||||||
/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), iphone-medium = 6.3" iPhone with
|
/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), iphone-medium = 6.3" iPhone with
|
||||||
|
|
@ -54,7 +55,8 @@ export const palette = (p: string | Palette | undefined, style: 'game' | 'app' =
|
||||||
* Cyrillic. The app title is a variable font (bold headline weights). Per-script stack: glyphs.ts. */
|
* Cyrillic. The app title is a variable font (bold headline weights). Per-script stack: glyphs.ts. */
|
||||||
export function shotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app'): { title: string; body: string; titleVariable: boolean } {
|
export function shotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app'): { title: string; body: string; titleVariable: boolean } {
|
||||||
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
|
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
|
||||||
return { title: shots?.fonts?.title ?? d.title, body: shots?.fonts?.body ?? d.body, titleVariable: style === 'app' };
|
// local files: the family given in the config, else the file name (resolveShotFonts reads the real name table)
|
||||||
|
return { title: specFamily(shots?.fonts?.title ?? d.title), body: specFamily(shots?.fonts?.body ?? d.body), titleVariable: style === 'app' };
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SceneCopy { eyebrow?: string; title: [string, string]; sub?: string; badges?: [string, string?][] }
|
export interface SceneCopy { eyebrow?: string; title: [string, string]; sub?: string; badges?: [string, string?][] }
|
||||||
|
|
|
||||||
130
cli/shots/local-fonts.ts
Normal file
130
cli/shots/local-fonts.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
||||||
|
// A game's or app's own brand font as a local file, next to the Google Fonts families:
|
||||||
|
// shots.fonts.title / body / fallback[] = 'Paytone One' (Google Fonts family)
|
||||||
|
// | 'assets/fonts/er-display.woff2' (local file, family from its name table)
|
||||||
|
// | { family, file, weight?, style?, license? }
|
||||||
|
// Paths are relative to the config. TTF / OTF / WOFF / WOFF2 (checked by extension and signature). The file is never
|
||||||
|
// copied: `shots fonts` reads its cmap and records it in fonts.json (path relative to the project, sha256, license),
|
||||||
|
// fonts.css points at /fonts/local/<slug>.<ext>?v=<hash> and the render / video servers serve that route from the
|
||||||
|
// original file. A changed file changes fonts.css (capture cache) and fails render until `shots fonts` runs again.
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||||
|
import { basename, join, relative } from 'node:path';
|
||||||
|
import { fontFamilyName } from './cmap';
|
||||||
|
import type { FontManifest } from './glyphs';
|
||||||
|
|
||||||
|
import type { FontSpec, LocalFontSpec, ShotsConfig } from '../lib/config';
|
||||||
|
export type { FontSpec, LocalFontSpec };
|
||||||
|
export type FontFormat = 'truetype' | 'opentype' | 'woff' | 'woff2';
|
||||||
|
|
||||||
|
/** A local font as fonts.json records it. path: relative to the project root. */
|
||||||
|
export interface LocalFontInfo { path: string; format: FontFormat; hash: string; bytes: number; weight?: string; style?: string; license?: string }
|
||||||
|
/** A resolved font of shots.fonts: the family name the templates use, plus the file for a local font. */
|
||||||
|
export interface FontRef { family: string; local?: LocalFontInfo & { abs: string } }
|
||||||
|
|
||||||
|
const EXT: Record<string, FontFormat> = { ttf: 'truetype', otf: 'opentype', woff: 'woff', woff2: 'woff2' };
|
||||||
|
|
||||||
|
/** A string spec is a local file when it ends in a font extension or contains a path separator. */
|
||||||
|
export const isLocalSpec = (s: FontSpec): boolean => typeof s !== 'string' || /\.(ttf|otf|woff2?)$/i.test(s) || /[\\/]/.test(s);
|
||||||
|
|
||||||
|
/** Format from the file signature (null = not a font file storebound reads). */
|
||||||
|
export function sniffFormat(bin: Uint8Array): FontFormat | null {
|
||||||
|
if (bin.byteLength < 12) return null;
|
||||||
|
const sig = String.fromCharCode(bin[0]!, bin[1]!, bin[2]!, bin[3]!);
|
||||||
|
if (sig === 'wOF2') return 'woff2';
|
||||||
|
if (sig === 'wOFF') return 'woff';
|
||||||
|
if (sig === 'OTTO') return 'opentype';
|
||||||
|
if (sig === 'true' || (bin[0] === 0 && bin[1] === 1 && bin[2] === 0 && bin[3] === 0)) return 'truetype';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const fileHash = (bin: Uint8Array): string => createHash('sha256').update(bin).digest('hex').slice(0, 16);
|
||||||
|
|
||||||
|
/** Resolves and validates one local font spec (file exists, TTF / OTF / WOFF / WOFF2). Throws with the config key. */
|
||||||
|
export function loadLocalFont(spec: FontSpec, key: string, resolve: (p: string) => string, root: string): FontRef {
|
||||||
|
const o: LocalFontSpec = typeof spec === 'string' ? { file: spec } : spec;
|
||||||
|
if (!o.file || typeof o.file !== 'string') throw new Error(`${key}: { family, file } needs a file path (relative to the config)`);
|
||||||
|
const ext = o.file.split('.').pop()!.toLowerCase();
|
||||||
|
if (!EXT[ext]) throw new Error(`${key}: ${o.file}: not a font file (TTF, OTF, WOFF or WOFF2)`);
|
||||||
|
const abs = resolve(o.file);
|
||||||
|
if (!existsSync(abs) || !statSync(abs).isFile()) throw new Error(`${key}: ${o.file} not found (paths are relative to the config: ${abs})`);
|
||||||
|
const bin = new Uint8Array(readFileSync(abs));
|
||||||
|
const format = sniffFormat(bin);
|
||||||
|
if (!format) throw new Error(`${key}: ${o.file} is not a TTF / OTF / WOFF / WOFF2 font (unknown signature)`);
|
||||||
|
const sfnt = (f: FontFormat): boolean => f === 'truetype' || f === 'opentype';
|
||||||
|
if (format !== EXT[ext] && !(sfnt(format) && sfnt(EXT[ext]!))) throw new Error(`${key}: ${o.file} is ${format.toUpperCase()} inside, but named .${ext}: rename it`);
|
||||||
|
const family = (o.family ?? fontFamilyName(bin) ?? basename(o.file).replace(/\.[^.]+$/, '')).trim();
|
||||||
|
if (!family) throw new Error(`${key}: ${o.file}: no family name (give { family, file })`);
|
||||||
|
return { family, local: { abs, path: relative(root, abs), format, hash: fileHash(bin), bytes: bin.byteLength,
|
||||||
|
...(o.weight !== undefined ? { weight: String(o.weight) } : {}), ...(o.style ? { style: o.style } : {}), ...(o.license ? { license: o.license } : {}) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** shots.fonts resolved: Google families as names, local files loaded and validated (throws on a bad file). */
|
||||||
|
export function resolveShotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app', resolve: (p: string) => string, root: string): { title: FontRef; body: FontRef; fallback: FontRef[]; titleVariable: boolean } {
|
||||||
|
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
|
||||||
|
const ref = (s: FontSpec, key: string): FontRef => isLocalSpec(s) ? loadLocalFont(s, key, resolve, root) : { family: s as string };
|
||||||
|
const fallback = (shots?.fonts?.fallback ?? []).map((f, i) => ref(f, `shots.fonts.fallback[${i}]`));
|
||||||
|
return { title: ref(shots?.fonts?.title ?? d.title, 'shots.fonts.title'), body: ref(shots?.fonts?.body ?? d.body, 'shots.fonts.body'), fallback, titleVariable: style === 'app' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Local files by family for planFonts (one family, one file). */
|
||||||
|
export function localByFamily(refs: FontRef[]): Record<string, LocalFontInfo> {
|
||||||
|
const out: Record<string, LocalFontInfo> = {};
|
||||||
|
for (const r of refs) if (r.local) {
|
||||||
|
const { abs: _abs, ...info } = r.local;
|
||||||
|
if (out[r.family] && out[r.family]!.hash !== info.hash) throw new Error(`shots.fonts: two different files for the family "${r.family}" (give each a distinct family)`);
|
||||||
|
out[r.family] = info;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Family name of a spec without reading files (Google family, { family }, else the file name). For callers that only
|
||||||
|
* need a name and never a local file's name table. */
|
||||||
|
export const specFamily = (s: FontSpec): string => typeof s !== 'string' ? s.family ?? basename(s.file).replace(/\.[^.]+$/, '')
|
||||||
|
: isLocalSpec(s) ? basename(s).replace(/\.[^.]+$/, '') : s;
|
||||||
|
|
||||||
|
export const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||||
|
|
||||||
|
/** fonts.json file name of a local face: served at /fonts/local/<slug>.<ext>. */
|
||||||
|
export const localFile = (family: string, l: Pick<LocalFontInfo, 'format'>): string =>
|
||||||
|
`local/${slug(family)}.${l.format === 'truetype' ? 'ttf' : l.format === 'opentype' ? 'otf' : l.format}`;
|
||||||
|
|
||||||
|
/** Absolute file of a face: the downloaded subset in .storebound/fonts, or the local font file itself. */
|
||||||
|
export function faceFilePath(fontsDir: string, root: string, f: FontManifest['faces'][string]): string {
|
||||||
|
return f.local ? join(root, f.local.path) : join(fontsDir, f.file);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** File for a /fonts/<rel> request of the render / video page (null = not ours). */
|
||||||
|
export function fontsRoute(rel: string, fontsDir: string, root: string, m: FontManifest | null): string | null {
|
||||||
|
rel = rel.split('?')[0]!;
|
||||||
|
if (rel.includes('..')) return null;
|
||||||
|
if (rel.startsWith('local/')) {
|
||||||
|
const f = Object.values(m?.faces ?? {}).find(x => x.local && x.file === rel);
|
||||||
|
return f ? faceFilePath(fontsDir, root, f) : null;
|
||||||
|
}
|
||||||
|
return join(fontsDir, rel);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FONT_TYPES: Record<string, string> = { woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css' };
|
||||||
|
|
||||||
|
/** Local faces whose file changed (or vanished) since `shots fonts`. */
|
||||||
|
export function staleLocalFonts(m: FontManifest, root: string): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const f of new Map(Object.values(m.faces).filter(x => x.local).map(x => [x.local!.path, x] as const)).values()) {
|
||||||
|
const abs = join(root, f.local!.path);
|
||||||
|
if (!existsSync(abs)) out.push(`${f.family}: ${f.local!.path} is gone`);
|
||||||
|
else if (fileHash(new Uint8Array(readFileSync(abs))) !== f.local!.hash) out.push(`${f.family}: ${f.local!.path} changed`);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `shots check` warnings for local fonts without a license note. */
|
||||||
|
export function localFontIssues(m: FontManifest | null): { level: 'warn'; code: 'font-license'; msg: string }[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const out: { level: 'warn'; code: 'font-license'; msg: string }[] = [];
|
||||||
|
for (const f of Object.values(m?.faces ?? {})) {
|
||||||
|
if (!f.local || f.local.license || seen.has(f.local.path)) continue;
|
||||||
|
seen.add(f.local.path);
|
||||||
|
out.push({ level: 'warn', code: 'font-license', msg: `local font ${f.family} (${f.local.path}) has no license note: add license ('OFL-1.1', 'proprietary', or a short note) to its shots.fonts entry, and make sure you may embed it in store graphics` });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
@ -8,7 +8,8 @@
|
||||||
// Fonts: the per-language stacks from .storebound/fonts/fonts.json (`shots fonts`). Before rendering, every character
|
// Fonts: the per-language stacks from .storebound/fonts/fonts.json (`shots fonts`). Before rendering, every character
|
||||||
// of the copy is checked against the cmaps of the downloaded faces (stale fonts fail with the language and the
|
// of the copy is checked against the cmaps of the downloaded faces (stale fonts fail with the language and the
|
||||||
// characters); while rendering, the page measures which face drew every character, and report.json records it per
|
// characters); while rendering, the page measures which face drew every character, and report.json records it per
|
||||||
// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`.
|
// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`. Local font files (shots.fonts
|
||||||
|
// paths) are served from where they are at /fonts/local/... (local-fonts.ts); a file changed since `shots fonts` fails.
|
||||||
// Style: shotsStyle() = shots.style, else app for the app / subscription-app profiles (template-app.html,
|
// Style: shotsStyle() = shots.style, else app for the app / subscription-app profiles (template-app.html,
|
||||||
// feature-app.html: calm gradient, device frame, headline + subline), else game (template.html, feature.html).
|
// feature-app.html: calm gradient, device frame, headline + subline), else game (template.html, feature.html).
|
||||||
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
||||||
|
|
@ -22,11 +23,12 @@ import { done, log, warn } from '../lib/log';
|
||||||
import { launch } from './browser';
|
import { launch } from './browser';
|
||||||
import { defaultConcurrency, pool, progressLine } from './capture-web';
|
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, validateCopy, variantScenes } from './lib';
|
||||||
|
import { faceFilePath, fontsRoute, resolveShotFonts, staleLocalFonts } from './local-fonts';
|
||||||
import { type RenderReport, mergeReport, readReport } from './report';
|
import { type RenderReport, mergeReport, readReport } from './report';
|
||||||
|
|
||||||
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
|
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
|
||||||
webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' };
|
webp: 'image/webp', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css', svg: 'image/svg+xml' };
|
||||||
|
|
||||||
export async function run(ctx: Ctx): Promise<void> {
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
const { config, root, resolve } = ctx.loaded;
|
const { config, root, resolve } = ctx.loaded;
|
||||||
|
|
@ -62,7 +64,8 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const { phone, tablet } = frameDims(config);
|
const { phone, tablet } = frameDims(config);
|
||||||
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
|
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
|
||||||
const style = shotsStyle(config);
|
const style = shotsStyle(config);
|
||||||
const sf = shotFonts(shots, style);
|
const rf = resolveShotFonts(shots, style, resolve, root);
|
||||||
|
const sf = { title: rf.title.family, body: rf.body.family };
|
||||||
const fonts = { title: sf.title, body: sf.body };
|
const fonts = { title: sf.title, body: sf.body };
|
||||||
const manifest = existsSync(join(fontsDir, 'fonts.css')) ? readManifest(fontsDir) : null;
|
const manifest = existsSync(join(fontsDir, 'fonts.css')) ? readManifest(fontsDir) : null;
|
||||||
if (existsSync(join(fontsDir, 'fonts.css')) && !manifest) warn('shots', 'fonts from an older storebound (no fonts.json): run `storebound shots fonts` again for the glyph coverage check');
|
if (existsSync(join(fontsDir, 'fonts.css')) && !manifest) warn('shots', 'fonts from an older storebound (no fonts.json): run `storebound shots fonts` again for the glyph coverage check');
|
||||||
|
|
@ -79,10 +82,14 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const x = stacks(lang, job.copy).script;
|
const x = stacks(lang, job.copy).script;
|
||||||
if (x) faces[x] = { family: x, file: '', kind: 'script', chosen: true };
|
if (x) faces[x] = { family: x, file: '', kind: 'script', chosen: true };
|
||||||
}
|
}
|
||||||
|
if (manifest) {
|
||||||
|
const stale = staleLocalFonts(manifest, root);
|
||||||
|
if (stale.length) throw new Error(`shots render: local font files changed since \`shots fonts\`: run \`storebound shots fonts\`\n ${stale.join('\n ')}`);
|
||||||
|
}
|
||||||
if (manifest) { // glyph coverage of the local font files, before rendering anything
|
if (manifest) { // glyph coverage of the local font files, before rendering anything
|
||||||
const cmaps = new Map<string, Set<number>>();
|
const cmaps = new Map<string, Set<number>>();
|
||||||
const cps = (face: string): Set<number> => {
|
const cps = (face: string): Set<number> => {
|
||||||
if (!cmaps.has(face)) { const f = manifest.faces[face]; cmaps.set(face, f && existsSync(join(fontsDir, f.file)) ? fontCodepoints(readFileSync(join(fontsDir, f.file))) : new Set()); }
|
if (!cmaps.has(face)) { const f = manifest.faces[face]; const file = f && faceFilePath(fontsDir, root, f); cmaps.set(face, file && existsSync(file) ? fontCodepoints(readFileSync(file)) : new Set()); }
|
||||||
return cmaps.get(face)!;
|
return cmaps.get(face)!;
|
||||||
};
|
};
|
||||||
const gaps: string[] = [];
|
const gaps: string[] = [];
|
||||||
|
|
@ -121,7 +128,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
let file = '';
|
let file = '';
|
||||||
if (p === '/logo' && shots.logo) file = resolve(shots.logo);
|
if (p === '/logo' && shots.logo) file = resolve(shots.logo);
|
||||||
else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8));
|
else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8));
|
||||||
else if (p.startsWith('/fonts/')) file = join(fontsDir, p.slice(7));
|
else if (p.startsWith('/fonts/')) file = fontsRoute(p.slice(7), fontsDir, root, manifest) ?? '';
|
||||||
else if (p.startsWith('/out/')) file = join(outDir, p.slice(5));
|
else if (p.startsWith('/out/')) file = join(outDir, p.slice(5));
|
||||||
else if (/^\/(template|feature)(-app)?\.html$/.test(p)) file = join(tpl, p.slice(1));
|
else if (/^\/(template|feature)(-app)?\.html$/.test(p)) file = join(tpl, p.slice(1));
|
||||||
if (!file || file.includes('..')) return new Response('no', { status: 404 });
|
if (!file || file.includes('..')) return new Response('no', { status: 404 });
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,8 @@ import { done, log, warn } from '../lib/log';
|
||||||
import { launch } from './browser';
|
import { launch } from './browser';
|
||||||
import { shotsStyle } from '../lib/config';
|
import { shotsStyle } from '../lib/config';
|
||||||
import { readManifest } from './fonts';
|
import { readManifest } from './fonts';
|
||||||
import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont, shotFonts } from './lib';
|
import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont } from './lib';
|
||||||
|
import { FONT_TYPES, fontsRoute, resolveShotFonts } from './local-fonts';
|
||||||
import { ffprobe } from './report';
|
import { ffprobe } from './report';
|
||||||
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec';
|
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec';
|
||||||
|
|
||||||
|
|
@ -159,12 +160,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const style = shotsStyle(ctx.loaded.config);
|
const style = shotsStyle(ctx.loaded.config);
|
||||||
const pal = palette(shots.scenes[0]?.palette, style);
|
const pal = palette(shots.scenes[0]?.palette, style);
|
||||||
return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: style === 'app' ? '#111827' : pal.ink, rtl: rtl.get(lang),
|
return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: style === 'app' ? '#111827' : pal.ink, rtl: rtl.get(lang),
|
||||||
fonts: { title: shotFonts(shots, style).title, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } });
|
fonts: { title: resolveShotFonts(shots, style, ctx.loaded.resolve, root).title.family, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } });
|
||||||
}
|
}
|
||||||
if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
||||||
if (url.pathname.startsWith('/fonts/') && !url.pathname.includes('..')) {
|
if (url.pathname.startsWith('/fonts/')) {
|
||||||
const f = Bun.file(join(fontsDir, url.pathname.slice(7)));
|
const file = fontsRoute(decodeURIComponent(url.pathname.slice(7)), fontsDir, root, readManifest(fontsDir));
|
||||||
if (await f.exists()) return new Response(f, { headers: { 'content-type': url.pathname.endsWith('.css') ? 'text/css' : 'font/woff2' } });
|
const f = file ? Bun.file(file) : null;
|
||||||
|
if (f && await f.exists()) return new Response(f, { headers: { 'content-type': FONT_TYPES[file!.split('.').pop()!.toLowerCase()] ?? 'font/woff2' } });
|
||||||
}
|
}
|
||||||
return new Response('no', { status: 404 });
|
return new Response('no', { status: 404 });
|
||||||
} });
|
} });
|
||||||
|
|
|
||||||
|
|
@ -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 | 196 | 166 |
|
| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 197 | 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 |
|
||||||
|
|
||||||
|
|
@ -386,7 +386,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
|
||||||
| `appStoreVersions_deleteInstance` | DELETE | `/v1/appStoreVersions/{id}` | owner only (typed confirm) | |
|
| `appStoreVersions_deleteInstance` | DELETE | `/v1/appStoreVersions/{id}` | owner only (typed confirm) | |
|
||||||
| `appStoreVersions_gameCenterAppVersion_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/gameCenterAppVersion` | read | |
|
| `appStoreVersions_gameCenterAppVersion_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/gameCenterAppVersion` | read | |
|
||||||
| `appStoreVersions_gameCenterAppVersion_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/gameCenterAppVersion` | read | |
|
| `appStoreVersions_gameCenterAppVersion_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/gameCenterAppVersion` | read | |
|
||||||
| `appStoreVersions_getInstance` | GET | `/v1/appStoreVersions/{id}` | read | |
|
| `appStoreVersions_getInstance` | GET | `/v1/appStoreVersions/{id}` | read | apple/listing |
|
||||||
| `appStoreVersions_routingAppCoverage_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/routingAppCoverage` | read | |
|
| `appStoreVersions_routingAppCoverage_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/routingAppCoverage` | read | |
|
||||||
| `appStoreVersions_routingAppCoverage_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/routingAppCoverage` | read | |
|
| `appStoreVersions_routingAppCoverage_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/routingAppCoverage` | read | |
|
||||||
| `appStoreVersions_updateInstance` | PATCH | `/v1/appStoreVersions/{id}` | write (dry by default) | apple/listing |
|
| `appStoreVersions_updateInstance` | PATCH | `/v1/appStoreVersions/{id}` | write (dry by default) | apple/listing |
|
||||||
|
|
|
||||||
|
|
@ -38,8 +38,9 @@ Tests: `tests/idempotency.test.ts` runs the write commands twice against statefu
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
Status: **ok** = converges, second run writes nothing (tested where marked T). **writes** = converges but sends the
|
Status: **ok** = converges, second run writes nothing (tested twice where marked T; the rows without T are covered
|
||||||
same values again (no duplicate; noted below). **owner** = a public or irreversible step that asks first.
|
by the shared helpers, see "Not run twice in the tests" below). **owner** = a public or irreversible step that asks
|
||||||
|
first. No write path sends the same values again on a second run.
|
||||||
|
|
||||||
| command | key | on re-run | status |
|
| command | key | on re-run | status |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
|
|
@ -48,9 +49,9 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi
|
||||||
| `apple iap-review` | one review screenshot per product (MD5 + not FAILED) | kept when the bytes match, else deleted and uploaded | ok |
|
| `apple iap-review` | one review screenshot per product (MD5 + not FAILED) | kept when the bytes match, else deleted and uploaded | ok |
|
||||||
| `apple subscriptions` | group reference name; product id; locale; promo offer code; campaign name; custom code | groups and subscriptions: findOrCreate + journal; localizations / offers / codes: createOnce; prices compared per territory, only differences sent; a subscription found late is read live (prices, intro) | ok T (twice, lost answer) |
|
| `apple subscriptions` | group reference name; product id; locale; promo offer code; campaign name; custom code | groups and subscriptions: findOrCreate + journal; localizations / offers / codes: createOnce; prices compared per territory, only differences sent; a subscription found late is read live (prices, intro) | ok T (twice, lost answer) |
|
||||||
| `apple offer-codes` | campaign name per product; custom code; one-time batches by count | campaign: findOrCreate + journal (names not known unique: no blind retry); codes: 409 = exists | ok T |
|
| `apple offer-codes` | campaign name per product; custom code; one-time batches by count | campaign: findOrCreate + journal (names not known unique: no blind retry); codes: 409 = exists | ok T |
|
||||||
| `apple win-back` | offer id per subscription | only missing offers; 409 = exists | ok (owner: asks) |
|
| `apple win-back` | offer id per subscription | only missing offers; 409 = exists | ok T (owner: asks) |
|
||||||
| `apple promoted` | product per promoted purchase | plan from the store; order PATCH only when it differs | ok |
|
| `apple promoted` | product per promoted purchase | plan from the store; order PATCH only when it differs | ok T |
|
||||||
| `apple preorder` | territory | plan from the store | ok (owner) |
|
| `apple preorder` | territory | plan from the store; a territory already on pre-order with that date is left | ok T (owner) |
|
||||||
| `apple cpp create` | page name; locale | page: findOrCreate + journal; locales from a fresh read, 409 = exists | ok T |
|
| `apple cpp create` | page name; locale | page: findOrCreate + journal; locales from a fresh read, 409 = exists | ok T |
|
||||||
| `apple cpp upload` / `apple ppo upload` / `apple screenshots` | display type; position + MD5 | set: findOrCreate (unique, 409 = found); screenshots: matching prefix kept, rest replaced in order | ok T (twice, crash on the 3rd file) |
|
| `apple cpp upload` / `apple ppo upload` / `apple screenshots` | display type; position + MD5 | set: findOrCreate (unique, 409 = found); screenshots: matching prefix kept, rest replaced in order | ok T (twice, crash on the 3rd file) |
|
||||||
| `apple cpp submit` / `apple events submit` / `apple iap-submit` | the app's draft submission; version id per item | draft reused or created once (journal); an item in the draft is not added again | ok T (iap-submit) (owner: submit asks) |
|
| `apple cpp submit` / `apple events submit` / `apple iap-submit` | the app's draft submission; version id per item | draft reused or created once (journal); an item in the draft is not added again | ok T (iap-submit) (owner: submit asks) |
|
||||||
|
|
@ -59,7 +60,7 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi
|
||||||
| `apple ppo create` | test name (open tests only); treatment name; locale | findOrCreate + journal for test and treatments | ok T |
|
| `apple ppo create` | test name (open tests only); treatment name; locale | findOrCreate + journal for test and treatments | ok T |
|
||||||
| `apple previews` | preview type; position + MD5; poster time code | like screenshots; poster PATCH only where it differs | ok |
|
| `apple previews` | preview type; position + MD5; poster time code | like screenshots; poster PATCH only where it differs | ok |
|
||||||
| `apple testflight groups` | group name | findOrCreate + journal, 409 = found | ok T |
|
| `apple testflight groups` | group name | findOrCreate + journal, 409 = found | ok T |
|
||||||
| `apple testflight testers` | email (masked) per group | only missing testers / memberships; 409 = exists | ok (owner: asks) |
|
| `apple testflight testers` | email (masked) per group | only missing testers / memberships; 409 = exists | ok T (owner: asks) |
|
||||||
| `apple testflight what-to-test` / `info` | locale; fields | POST missing locales, PATCH changed fields only | ok |
|
| `apple testflight what-to-test` / `info` | locale; fields | POST missing locales, PATCH changed fields only | ok |
|
||||||
| `apple testflight distribute` | group per build | relationship adds (same when sent twice); beta review once per build (409 = exists) | ok (owner) |
|
| `apple testflight distribute` | group per build | relationship adds (same when sent twice); beta review once per build (409 = exists) | ok (owner) |
|
||||||
| `apple testflight expire` | build | only unexpired builds planned | ok (owner) |
|
| `apple testflight expire` | build | only unexpired builds planned | ok (owner) |
|
||||||
|
|
@ -70,20 +71,20 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi
|
||||||
| `apple adhoc profile` | profile name (+ dated names of earlier runs) | a current profile (also a dated one) ends the run; a new name never collides | ok |
|
| `apple adhoc profile` | profile name (+ dated names of earlier runs) | a current profile (also a dated one) ends the run; a new name never collides | ok |
|
||||||
| `apple signing ensure` | certificate with a local key (SPKI); profile with that certificate | a lost certificate answer keeps the pending key and finds the certificate by its public key (now or on the next run); profiles: createOnce, re-read | ok |
|
| `apple signing ensure` | certificate with a local key (SPKI); profile with that certificate | a lost certificate answer keeps the pending key and finds the certificate by its public key (now or on the next run); profiles: createOnce, re-read | ok |
|
||||||
| `apple upload` | build upload per version + build number | a COMPLETE upload is not sent again (only the wait); an unfinished one is resumed; reservations createOnce | ok |
|
| `apple upload` | build upload per version + build number | a COMPLETE upload is not sent again (only the wait); an unfinished one is resumed; reservations createOnce | ok |
|
||||||
| `apple listing` | version (editable); locale | see "open points" | writes |
|
| `apple listing` | version string (editable, iOS); locale; build per version | plan from the store; version: findOrCreate (fresh GET right before the create, journal, unique: a lost answer looks first); localizations: createOnce (409 / lost answer = found, then only differing fields PATCHed); unchanged localizations skipped; the build is not re-attached when it is attached | ok T (twice, changed field, lost answer, 409) |
|
||||||
| `apple appinfo` | categories, age rating, rights, price, availability | PATCHes every run (same values); price / availability only when missing | writes |
|
| `apple appinfo` | categories, age rating, rights, price, availability | each compared with the live value, only what differs is PATCHed; price schedule and availability only when missing (an existing price is never changed here: `prices import`) | ok T (twice, one changed answer) |
|
||||||
| `analytics setup` | the ONGOING request | exists = done; createOnce | ok |
|
| `analytics setup` | the ONGOING request | exists = done; createOnce | ok |
|
||||||
| `reviews send` | review id (local `sent:` mark) | Apple 409 (already answered) = noted as sent; Play `:reply` replaces | ok (owner) |
|
| `reviews send` | review id (local `sent:` mark) | Apple 409 (already answered) = noted as sent; Play `:reply` replaces | ok (owner) |
|
||||||
| `play products` | product id | PATCH `allowMissing` (create or update) only when it differs; activation only when not ACTIVE | ok T |
|
| `play products` | product id | PATCH `allowMissing` (create or update) only when it differs; activation only when not ACTIVE | ok T |
|
||||||
| `play subscriptions` | product id; base plan id; offer id | create: 409 = found (createOnce); PATCH only differences; activation only when needed | ok T (twice, lost answer) |
|
| `play subscriptions` | product id; base plan id; offer id | create: 409 = found (createOnce); PATCH only differences; activation only when needed | ok T (twice, lost answer) |
|
||||||
| `play images` | language + image type, sha256 in order | one read edit compares; only changed types are cleared and uploaded, in one edit per language | ok T |
|
| `play images` | language + image type, sha256 in order | one read edit compares; only changed types are cleared and uploaded, in one edit per language | ok T |
|
||||||
| `play listing` | language | see "open points" | writes |
|
| `play listing` | language; details | compared like the dry run (`playPlan`), again inside the write edit: only differing details / languages PUT; nothing differs = the edit is deleted, not committed; commit only after every PUT worked | ok T (twice, store current by the time the edit opens) |
|
||||||
| `play release` | versionCode; track release | a versionCode Play has is reused, not uploaded; an identical track release is not PUT; nothing changed = edit deleted | ok T |
|
| `play release` | versionCode; track release | a versionCode Play has is reused, not uploaded; an identical track release is not PUT; nothing changed = edit deleted | ok T |
|
||||||
| `play upload` | versionCode + track | already on that track with that status = done | ok |
|
| `play upload` | versionCode + track | already on that track with that status = done | ok T |
|
||||||
| `play rollout` | track releases | the same releases = edit deleted, not committed | ok T |
|
| `play rollout` | track releases | the same releases = edit deleted, not committed | ok T |
|
||||||
| `play data-safety` | the form | Play has no read API for it: the same CSV is sent again (a set, no duplicates) | writes |
|
| `play data-safety` | sha256 of package + CSV (`.storebound/data-safety.sha256`) | Play cannot read the form back: the hash of the last upload is kept locally, the same CSV is not sent again; `--force` sends it anyway (after a hand edit in Play Console) | ok T |
|
||||||
| `play share` | none (a new link each time) | a new internal sharing artifact per run (asks first; links expire in 60 days) | owner |
|
| `play share` | none (a new link each time) | a new internal sharing artifact per run (asks first; links expire in 60 days) | owner |
|
||||||
| `prices import` | product x store x region | diff first; only changed product / store pairs written (`--reconvert` always rewrites Play regions) | ok |
|
| `prices import` | product x store x region | diff first; only changed product / store pairs written (`--reconvert` always rewrites Play regions) | ok T (Play) |
|
||||||
| `revenuecat sync` | store identifier + app; lookup keys | plan from a fresh read; creates through createOnce (409 = found by key); attaches are the same twice | ok |
|
| `revenuecat sync` | store identifier + app; lookup keys | plan from a fresh read; creates through createOnce (409 = found by key); attaches are the same twice | ok |
|
||||||
| `ads apple bid / budget / pause` | campaign / keyword | PUT of a value | ok (owner) |
|
| `ads apple bid / budget / pause` | campaign / keyword | PUT of a value | ok (owner) |
|
||||||
| `web init` | file content | unchanged files are not written | ok |
|
| `web init` | file content | unchanged files are not written | ok |
|
||||||
|
|
@ -91,13 +92,19 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi
|
||||||
| `console fill` | none | fills fields in a visible browser, never presses Save / Submit / Next | ok (never saves) |
|
| `console fill` | none | fills fields in a visible browser, never presses Save / Submit / Next | ok (never saves) |
|
||||||
| `storebound api <write>` | none (one raw request) | a POST without a clear answer is not retried; check with a GET first | raw |
|
| `storebound api <write>` | none (one raw request) | a POST without a clear answer is not retried; check with a GET first | raw |
|
||||||
|
|
||||||
## Open points (owned by another change)
|
## Not run twice in the tests
|
||||||
|
|
||||||
- `apple listing`: the version is matched by "the editable version", not by its version string, and a new one is
|
No row is open. These write paths are not run twice against the store doubles; they converge through the shared,
|
||||||
created without findOrCreate; localizations are POSTed without `createOnce` (a 409 stops the run), and the build is
|
tested helpers instead:
|
||||||
re-attached (PATCH) every run. Should use findOrCreate for the version and localizations, and skip the build PATCH
|
|
||||||
when it is attached already.
|
- `apple previews`: the asset-set logic of `apple screenshots` (`keptPrefix`, `syncAssets`), tested with a crash on
|
||||||
- `play listing`: every run opens an edit, PUTs details and every listing and commits, also when nothing changed. Should
|
the 3rd file. `apple iap-review` and `apple events upload` compare MD5 / size with what is delivered before sending.
|
||||||
compare like its dry run (`listingChanges`, `detailsChanges`) and call `ctl.unchanged()` when nothing differs.
|
- `apple signing ensure`, `apple upload`: reservations and certificates through `createOnce` and lookups by key
|
||||||
- `apple appinfo`: categories, age rating and content rights are PATCHed every run. Should compare with the current
|
(tested in `helpers`); `apple adhoc profile` stops at a current profile. The doubles have no certificate, profile
|
||||||
values first.
|
or build upload pipeline.
|
||||||
|
- `revenuecat sync`: `createOnce` with RevenueCat's 409 (`isConflict` tested); there is no RevenueCat double.
|
||||||
|
- `apple testflight what-to-test` / `info` / `distribute` / `expire`, `apple cpp upload` / `ppo upload` (the
|
||||||
|
screenshot path), `analytics setup`, `reviews send`, `ads apple`, `web init`, `flow run`: plan from the store (or
|
||||||
|
the file) first, the same helpers.
|
||||||
|
- `prices import` on the App Store side: the doubles have no manual price list per schedule; the Play side is tested,
|
||||||
|
and both share `diffPrices` / `sameSchedule`.
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,10 @@ fails without the fix.
|
||||||
|
|
||||||
| # | date | lesson | guard |
|
| # | date | lesson | guard |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| 11 | 2026-10 | App Privacy purposes were over-mapped: Play "advertising" became both Third-Party Advertising and Developer's Advertising or Marketing (Device ID, Coarse Location, Product Interaction, Performance Data). | `applePurpose` maps one Play purpose to one Apple purpose (advertising: third-party only); Developer's Advertising only from `appPrivacy.types`; `check` compares `appPrivacy.types` with Info.plist / PrivacyInfo.xcprivacy (`tests/app-privacy.test.ts`). |
|
| 13 | 2026-10 | App Privacy purposes were over-mapped: Play "advertising" became both Third-Party Advertising and Developer's Advertising or Marketing (Device ID, Coarse Location, Product Interaction, Performance Data). | `applePurpose` maps one Play purpose to one Apple purpose (advertising: third-party only); Developer's Advertising only from `appPrivacy.types`; `check` compares `appPrivacy.types` with Info.plist / PrivacyInfo.xcprivacy (`tests/app-privacy.test.ts`). |
|
||||||
| 10 | 2026-10 | A new Play app has no API: Play Console's "Create app" is the only way, its page-level button carries the same words as the form's final submit, and Free cannot become Paid later. | `console fill play-app-record`: `createAppAllowed` lets the opener through only on the app list, never in a form or dialog (EN + TR); declarations never ticked; Free / Paid outlined as an owner check (`tests/console-fill.test.ts`). |
|
| 12 | 2026-10 | A new Play app has no API: Play Console's "Create app" is the only way, its page-level button carries the same words as the form's final submit, and Free cannot become Paid later. | `console fill play-app-record`: `createAppAllowed` lets the opener through only on the app list, never in a form or dialog (EN + TR); declarations never ticked; Free / Paid outlined as an owner check (`tests/console-fill.test.ts`). |
|
||||||
|
| 11 | 2026-10 | Google Play has no public search API, so there is no Play keyword rank or Play competitor list to read without scraping. | `aso` reads App Store search only (iTunes Search API); `aso audit` covers Play through the listing text (short description, density); the aso-basics skill says so. |
|
||||||
|
| 10 | 2026-10 | The iTunes Search API order is close to, not equal to, App Store search (no personalisation, no search ads, no in-app event rows) and it has no subtitle field. | `aso rank` / `aso competitors` / `aso audit` label ranks as a trend and show no competitor subtitles; popularity only from Apple Ads, never estimated (`cli/lib/aso-intel.ts`). |
|
||||||
| 9 | 2026-10 | A retried or repeated write can duplicate on a live store: a POST create retried after a timeout or 5xx, a re-run during the list lag right after a create, two runs at once, a Play edit redone after an unclear commit, a crash in the middle of a screenshot set. | Every write is an upsert (`cli/lib/upsert.ts`: findOrCreate with a fresh re-check and a journal of recent creates, createOnce treating 409 as found, no blind retry of a create); API clients retry only requests that are safe twice; Play edits are all or nothing; asset sets keep the matching prefix; one lock per app and store (`cli/lib/lock.ts`, `--force-unlock`). Table: `docs/idempotency.md`; `tests/idempotency.test.ts` runs every write twice and asserts zero writes on the second run. |
|
| 9 | 2026-10 | A retried or repeated write can duplicate on a live store: a POST create retried after a timeout or 5xx, a re-run during the list lag right after a create, two runs at once, a Play edit redone after an unclear commit, a crash in the middle of a screenshot set. | Every write is an upsert (`cli/lib/upsert.ts`: findOrCreate with a fresh re-check and a journal of recent creates, createOnce treating 409 as found, no blind retry of a create); API clients retry only requests that are safe twice; Play edits are all or nothing; asset sets keep the matching prefix; one lock per app and store (`cli/lib/lock.ts`, `--force-unlock`). Table: `docs/idempotency.md`; `tests/idempotency.test.ts` runs every write twice and asserts zero writes on the second run. |
|
||||||
| 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`). |
|
| 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`. |
|
| 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`. |
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,8 @@ bun ../../cli/index.ts shots render --size ios69,play,feature
|
||||||
bun ../../cli/index.ts shots gallery # store/renders/index.html
|
bun ../../cli/index.ts shots gallery # store/renders/index.html
|
||||||
bun ../../cli/index.ts check # profile checks: delete-account URL, demo account, terms URL
|
bun ../../cli/index.ts check # profile checks: delete-account URL, demo account, terms URL
|
||||||
bun ../../cli/index.ts play data-safety --dry # the Data safety CSV Play imports, from dataSafety in the config
|
bun ../../cli/index.ts play data-safety --dry # the Data safety CSV Play imports, from dataSafety in the config
|
||||||
|
bun ../../cli/index.ts aso audit # offline ASO report over store/appstore.md + store/listing.md
|
||||||
|
bun ../../cli/index.ts aso suggest --offline # keyword field proposals as a diff (nothing written)
|
||||||
```
|
```
|
||||||
|
|
||||||
`bun ../../cli/index.ts scan` (offline rejection-risk scan) finds four things that are true for a fictional app and
|
`bun ../../cli/index.ts scan` (offline rejection-risk scan) finds four things that are true for a fictional app and
|
||||||
|
|
|
||||||
72
examples/demo-app/store/appstore.md
Normal file
72
examples/demo-app/store/appstore.md
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
# Tidy Lists · App Store listing copy (demo)
|
||||||
|
|
||||||
|
Source for `storebound apple listing` and the ASO commands (`check --aso`, `aso suggest`, `aso audit`). Fictional app:
|
||||||
|
the text shows the format, it is never uploaded.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## en-US · English (U.S.)
|
||||||
|
|
||||||
|
### subtitle
|
||||||
|
```
|
||||||
|
Shared lists for groceries
|
||||||
|
```
|
||||||
|
|
||||||
|
### promotionalText
|
||||||
|
```
|
||||||
|
Share a list with the people you live with and see every change as it happens.
|
||||||
|
```
|
||||||
|
|
||||||
|
### keywords
|
||||||
|
```
|
||||||
|
tasks,checklist,shopping,family,planner,list
|
||||||
|
```
|
||||||
|
|
||||||
|
### description
|
||||||
|
```
|
||||||
|
Tidy Lists keeps grocery lists, packing lists and to-do lists in one calm place.
|
||||||
|
|
||||||
|
Share a list with family or roommates and every change shows up on their phone. Check items off in the store, sort
|
||||||
|
them by aisle, and reuse a packing list for the next trip.
|
||||||
|
|
||||||
|
FEATURES
|
||||||
|
• Shared lists that sync between phones
|
||||||
|
• Grocery lists sorted by aisle
|
||||||
|
• Packing lists and checklists you can reuse
|
||||||
|
• Works offline; changes sync when you are back online
|
||||||
|
|
||||||
|
Sign in with an account to share lists. Delete your account any time in Settings.
|
||||||
|
```
|
||||||
|
|
||||||
|
## tr · Türkçe
|
||||||
|
|
||||||
|
### subtitle
|
||||||
|
```
|
||||||
|
Market için ortak listeler
|
||||||
|
```
|
||||||
|
|
||||||
|
### promotionalText
|
||||||
|
```
|
||||||
|
Bir listeyi evdekilerle paylaş ve her değişikliği anında gör.
|
||||||
|
```
|
||||||
|
|
||||||
|
### keywords
|
||||||
|
```
|
||||||
|
yapılacaklar,alışveriş,aile,planlayıcı,kontrol
|
||||||
|
```
|
||||||
|
|
||||||
|
### description
|
||||||
|
```
|
||||||
|
Tidy Lists market listelerini, valiz listelerini ve yapılacaklar listelerini tek bir sakin yerde tutar.
|
||||||
|
|
||||||
|
Bir listeyi ailenle ya da ev arkadaşlarınla paylaş; her değişiklik onların telefonunda da görünür. Markette
|
||||||
|
ürünleri işaretle, reyona göre sırala ve valiz listesini bir sonraki yolculukta yeniden kullan.
|
||||||
|
|
||||||
|
ÖZELLİKLER
|
||||||
|
• Telefonlar arasında eşitlenen ortak listeler
|
||||||
|
• Reyona göre sıralı market listeleri
|
||||||
|
• Yeniden kullanılabilen valiz ve kontrol listeleri
|
||||||
|
• Çevrimdışı çalışır; değişiklikler bağlantı gelince eşitlenir
|
||||||
|
|
||||||
|
Liste paylaşmak için bir hesapla giriş yap. Hesabını istediğin zaman Ayarlar'dan silebilirsin.
|
||||||
|
```
|
||||||
60
examples/demo-app/store/listing.md
Normal file
60
examples/demo-app/store/listing.md
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
# Tidy Lists · Google Play listing copy (demo)
|
||||||
|
|
||||||
|
Source for `storebound play listing` and the ASO commands. Fictional app: the text shows the format, it is never
|
||||||
|
uploaded.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English (en-US)
|
||||||
|
<!-- play: en-US -->
|
||||||
|
|
||||||
|
### Play title (max 30)
|
||||||
|
```
|
||||||
|
Tidy Lists: Shared Groceries
|
||||||
|
```
|
||||||
|
|
||||||
|
### Play short description (max 80)
|
||||||
|
```
|
||||||
|
Shared grocery lists
|
||||||
|
```
|
||||||
|
|
||||||
|
### Play full description (max 4000)
|
||||||
|
```
|
||||||
|
Tidy Lists keeps groceries, packing and to-dos in one calm place.
|
||||||
|
|
||||||
|
Share a grocery list with family or roommates and every change shows up on their phone. Check items off in the
|
||||||
|
store, sort them by aisle, and reuse your packing checklist for the next trip.
|
||||||
|
|
||||||
|
FEATURES
|
||||||
|
• Shared lists that sync between phones
|
||||||
|
• Groceries sorted by aisle
|
||||||
|
• Packing checklists you can reuse
|
||||||
|
• Works offline; changes sync when you are back online
|
||||||
|
|
||||||
|
Sign in with an account to share lists. Delete your account any time in Settings.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Türkçe (tr-TR)
|
||||||
|
<!-- play: tr-TR -->
|
||||||
|
|
||||||
|
### Play title (max 30)
|
||||||
|
```
|
||||||
|
Tidy Lists: Ortak Market
|
||||||
|
```
|
||||||
|
|
||||||
|
### Play short description (max 80)
|
||||||
|
```
|
||||||
|
Ailenle ortak market ve yapılacaklar listeleri, her telefonda anında eşitlenir
|
||||||
|
```
|
||||||
|
|
||||||
|
### Play full description (max 4000)
|
||||||
|
```
|
||||||
|
Tidy Lists market listelerini, valiz listelerini ve yapılacaklar listelerini tek bir sakin yerde tutar.
|
||||||
|
|
||||||
|
Bir listeyi ailenle ya da ev arkadaşlarınla paylaş; her değişiklik onların telefonunda da görünür.
|
||||||
|
|
||||||
|
ÖZELLİKLER
|
||||||
|
• Telefonlar arasında eşitlenen ortak listeler
|
||||||
|
• Reyona göre sıralı market listeleri
|
||||||
|
• Çevrimdışı çalışır
|
||||||
|
```
|
||||||
|
|
@ -59,6 +59,7 @@
|
||||||
"adapters": "bun tools/gen-adapters.ts",
|
"adapters": "bun tools/gen-adapters.ts",
|
||||||
"scrub": "bun tools/scrub.ts",
|
"scrub": "bun tools/scrub.ts",
|
||||||
"ci": "bun tools/ci.ts",
|
"ci": "bun tools/ci.ts",
|
||||||
|
"ci:quick": "bun tools/ci.ts --quick",
|
||||||
"check": "bun run typecheck && bun test"
|
"check": "bun run typecheck && bun test"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
---
|
---
|
||||||
name: aso-basics
|
name: aso-basics
|
||||||
description: App store optimization basics for a mobile app's or game's text - App Store keyword field rules (100 characters, commas without spaces, no repeats of name / subtitle words, fill 90%+), subtitle and name, cross-localization keyword room per storefront, screenshot captions with real keywords, Google Play title / short / full description keyword placement without stuffing. Keyword rank checks per storefront through the public iTunes Search API. Use when the user writes or improves store listing text, keywords, asks why the app or game is not found in store search, or wants keyword ranks and competitors.
|
description: App store optimization basics for a mobile app's or game's text - App Store keyword field rules (100 characters, commas without spaces, no repeats of name / subtitle words, fill 90%+), subtitle and name, cross-localization keyword room per storefront, screenshot captions with real keywords, Google Play title / short / full description keyword placement without stuffing. Keyword ranks, competitors per keyword, keyword field proposals and one ASO audit from official / public data (iTunes Search API, Apple Ads popularity with the owner's credentials, App Store analytics snapshots). Use when the user writes or improves store listing text, keywords, asks why the app or game is not found in store search, or wants keyword ranks, competitors, keyword ideas or an ASO review.
|
||||||
---
|
---
|
||||||
|
|
||||||
# ASO basics
|
# ASO basics
|
||||||
|
|
@ -48,6 +48,44 @@ true; never use competitor or other apps' or games' names, "best / #1", or unrel
|
||||||
429 stops the run with what was read). The table shows the app's position in the first 200 results, the change
|
429 stops the run with what was read). The table shows the app's position in the first 200 results, the change
|
||||||
since the last snapshot (`.storebound/aso/<date>.json`) and the first competitors (title, developer, rating).
|
since the last snapshot (`.storebound/aso/<date>.json`) and the first competitors (title, developer, rating).
|
||||||
|
|
||||||
|
6. Competitors: `storebound aso competitors --dry`, then without `--dry` (MCP: `aso_competitors`, read-only, saves no
|
||||||
|
snapshot). Per keyword (plus `--term`) and storefront the top N apps: name, developer, rating count, first release,
|
||||||
|
last update, genre in the storefront's language. Then the words in their names your name / subtitle / keywords do
|
||||||
|
not cover; a word only counts when two or more developers use it (one developer's word is most likely a brand).
|
||||||
|
Snapshots go to `.storebound/aso/competitors/` and the next run names the apps new in a term's top N.
|
||||||
|
7. Keyword ideas: `storebound aso suggest --locale en-US` (MCP: `aso_suggest`, never writes). Candidates come from the
|
||||||
|
own name / subtitle / description, the latest competitor snapshot, the category names in that language and, when
|
||||||
|
`APPLE_ADS_*` credentials are set (`ads apple status` works), Apple Ads keyword suggestions. For each: relevance
|
||||||
|
(in your own text +1, in competitor names +1), competition (top apps with the word in their name, "3/16"),
|
||||||
|
popularity (Apple Ads' relative 0-100 score; "unknown" otherwise). Show the owner the proposed field (old -> new,
|
||||||
|
bytes) and the left-out words with the reason. Only after a yes: `storebound aso suggest --locale en-US --write`
|
||||||
|
(terminal); it writes the field with a draft line above it. The owner reviews, deletes the line, runs
|
||||||
|
`check --aso`. Never put words in that do not describe the app, other apps' names or brands.
|
||||||
|
8. Review: `storebound aso audit` (MCP: `aso_audit`, offline) puts it together: keyword field findings, free keyword
|
||||||
|
room in other localizations, rank trend arrows (↑ ↓ → new lost), coverage gaps, Play short description use and word
|
||||||
|
density, App Store conversion from `analytics snapshot`, experiment ideas and the next 3 actions. Start there.
|
||||||
|
|
||||||
|
## Experiments (suggestions only; nothing starts on its own)
|
||||||
|
- App Store Product Page Optimization tests the icon, screenshots and app previews only, not the name or subtitle.
|
||||||
|
To test a first-screenshot caption: a `shots.variants` entry, `shots render --variant b`, `apple ppo create --variant
|
||||||
|
b --dry`, `apple ppo upload --variant b --dry` (store-screenshots skill). Starting a test (`apple ppo start`) is the
|
||||||
|
owner's step.
|
||||||
|
- A subtitle change ships with a version: change one thing, then compare with `analytics compare`.
|
||||||
|
- Google Play store listing experiments (short / full description, icon, feature graphic, screenshots) have no API:
|
||||||
|
storebound prepares the text and renders; the owner sets the experiment up in Play Console.
|
||||||
|
|
||||||
|
## Where the numbers come from (say it to the owner)
|
||||||
|
| number | source | is | is not |
|
||||||
|
|---|---|---|---|
|
||||||
|
| rank | iTunes Search API, first 200 results | the app's position in that API's order today | the App Store search position (no personalisation, ads, in-app events) |
|
||||||
|
| competitors, rating count, release dates, genre | iTunes Search API | what the top apps of that term show publicly | their subtitles (no public API has them), downloads or revenue |
|
||||||
|
| relevance, competition | own listing + competitor names | how close a word is to your text and how many top apps lead with it | search volume |
|
||||||
|
| popularity 0-100 | Apple Ads Platform API keyword suggestions (owner's credentials) | Apple's relative score across the chosen countries | an absolute number of searches; never estimated without Apple Ads |
|
||||||
|
| impressions, downloads, conversion | App Store Connect analytics snapshots | real store numbers for the window read | instant feedback: a change needs days on both sides |
|
||||||
|
|
||||||
|
Google Play has no public search API: there are no Play keyword ranks or Play competitor lists here (that would need
|
||||||
|
scraping). Use the Play Console acquisition report (search terms) and `analytics snapshot` for Play.
|
||||||
|
|
||||||
## Rank check limits (say them to the owner)
|
## Rank check limits (say them to the owner)
|
||||||
- The Search API order is close to, not the same as, App Store search (no personalisation, no Search Ads, no in-app
|
- The Search API order is close to, not the same as, App Store search (no personalisation, no Search Ads, no in-app
|
||||||
event rows). Read ranks as a trend over weeks, not as a promise.
|
event rows). Read ranks as a trend over weeks, not as a promise.
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,8 @@ CLI: `storebound` (or `bunx storebound` in a project that has it, or `bun <toolc
|
||||||
2. **Play Data safety (API).** Fill `dataSafety` (types not listed = not collected; `shared` = third party that is not
|
2. **Play Data safety (API).** Fill `dataSafety` (types not listed = not collected; `shared` = third party that is not
|
||||||
your service provider, e.g. ad networks; analytics vendors acting as processors are "collected" only).
|
your service provider, e.g. ad networks; analytics vendors acting as processors are "collected" only).
|
||||||
`storebound play data-safety --dry --csv store/data-safety.csv` to review, then `storebound play data-safety`.
|
`storebound play data-safety --dry --csv store/data-safety.csv` to review, then `storebound play data-safety`.
|
||||||
|
Play cannot read the form back: storebound keeps the hash of the last upload in `.storebound/data-safety.sha256`
|
||||||
|
and skips an unchanged CSV. After a hand edit in Play Console, `--force` sends the config's answers again.
|
||||||
Then check the summary in Play Console > Policy and programs > App content > Data safety.
|
Then check the summary in Play Console > Policy and programs > App content > Data safety.
|
||||||
3. **Play App content (UI).** Policy and programs > App content, each card with `store/declarations.md`:
|
3. **Play App content (UI).** Policy and programs > App content, each card with `store/declarations.md`:
|
||||||
privacy policy, app access, ads, content rating (IARC questionnaire), target audience and content, news, COVID-19,
|
privacy policy, app access, ads, content rating (IARC questionnaire), target audience and content, news, COVID-19,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
---
|
---
|
||||||
name: store-pitfalls
|
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, duplicates from retries, re-runs and parallel runs., Play's Create app form (no API, opener and submit share a name, Free is final), App Privacy purposes over-mapped (Play advertising is Third-Party Advertising only). Read it before any store task, and when a store command does something you did not expect.
|
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, duplicates from retries, re-runs and parallel runs, App Store search ranks that are only a trend, Play without a search API, Play's Create app form (no API, opener and submit share a name, Free is final), App Privacy purposes over-mapped (Play advertising is Third-Party Advertising only). Read it before any store task, and when a store command does something you did not expect.
|
||||||
---
|
---
|
||||||
|
|
||||||
# Store pitfalls
|
# Store pitfalls
|
||||||
|
|
@ -83,7 +83,23 @@ Each entry: **symptom** → cause → what to do → what guards it now. The ful
|
||||||
Play edits deleted on every error and never redone after an unclear commit, screenshot / preview sets keep the
|
Play edits deleted on every error and never redone after an unclear commit, screenshot / preview sets keep the
|
||||||
matching prefix in order, `.storebound/locks/` per app and store. `tests/idempotency.test.ts`.
|
matching prefix in order, `.storebound/locks/` per app and store. `tests/idempotency.test.ts`.
|
||||||
|
|
||||||
## 10. A new Play app: "Create app" is both the opener and the submit
|
## 10. "We rank #4 for this keyword" (from the Search API)
|
||||||
|
- **Symptom:** `aso rank` says #4, the owner's phone shows the app lower (or higher) in App Store search.
|
||||||
|
- **Cause:** the iTunes Search API order is close to, not equal to, App Store search: no personalisation, no search
|
||||||
|
ads, no in-app event rows. It has no subtitle field either.
|
||||||
|
- **Do:** read ranks as a trend over weeks (`aso audit` arrows), never as a promise; never claim a competitor's
|
||||||
|
subtitle (no public API has it); a popularity number exists only from Apple Ads, never estimate one.
|
||||||
|
- **Guard:** `aso rank`, `aso competitors` and `aso audit` say it in their output; `aso suggest` shows popularity
|
||||||
|
"unknown" without Apple Ads credentials.
|
||||||
|
|
||||||
|
## 11. "Check our Google Play keyword ranks"
|
||||||
|
- **Symptom:** the owner asks for Play ranks or Play competitors per keyword.
|
||||||
|
- **Cause:** Google Play has no public search API; reading Play search pages would be scraping.
|
||||||
|
- **Do:** say so. Measure Play through the Play Console acquisition reports (search terms) and `analytics snapshot`
|
||||||
|
(store listing visitors, acquisitions); improve the listing text with `aso audit` (short description, density).
|
||||||
|
- **Guard:** `aso` covers App Store search only; the aso-basics skill states the limit.
|
||||||
|
|
||||||
|
## 12. A new Play app: "Create app" is both the opener and the submit
|
||||||
- **Symptom:** an agent cannot create the Play app through the API, or clicks "Create app" without knowing whether it
|
- **Symptom:** an agent cannot create the Play app through the API, or clicks "Create app" without knowing whether it
|
||||||
opens the form or submits it; or an app goes out as Free and the owner later wants it paid.
|
opens the form or submits it; or an app goes out as Free and the owner later wants it paid.
|
||||||
- **Cause:** the Play Developer API cannot create apps. Play Console's Home has a "Create app" button that opens the
|
- **Cause:** the Play Developer API cannot create apps. Play Console's Home has a "Create app" button that opens the
|
||||||
|
|
@ -95,7 +111,7 @@ Each entry: **symptom** → cause → what to do → what guards it now. The ful
|
||||||
- **Guard:** `createAppAllowed` lets the opener through only on the app list, never inside a form or dialog (English
|
- **Guard:** `createAppAllowed` lets the opener through only on the app list, never inside a form or dialog (English
|
||||||
and Turkish); agreement checkboxes are never ticked; Free or paid is outlined as an owner check.
|
and Turkish); agreement checkboxes are never ticked; Free or paid is outlined as an owner check.
|
||||||
|
|
||||||
## 11. App Privacy purposes over-mapped
|
## 13. App Privacy purposes over-mapped
|
||||||
- **Symptom:** App Privacy says Developer's Advertising or Marketing for Device ID, Coarse Location, Product Interaction
|
- **Symptom:** App Privacy says Developer's Advertising or Marketing for Device ID, Coarse Location, Product Interaction
|
||||||
or Performance Data, although the app only shows an ad SDK's ads.
|
or Performance Data, although the app only shows an ad SDK's ads.
|
||||||
- **Cause:** a Play purpose was turned into two Apple purposes ("advertising" -> Third-Party Advertising AND
|
- **Cause:** a Play purpose was turned into two Apple purposes ("advertising" -> Third-Party Advertising AND
|
||||||
|
|
|
||||||
|
|
@ -92,6 +92,11 @@ in a plain Android tablet body instead of the iPad one.
|
||||||
titles; Montserrat, Inter, Nunito for body), or, if the owner accepts mixed glyphs, `shots.fonts.fallback:
|
titles; Montserrat, Inter, Nunito for body), or, if the owner accepts mixed glyphs, `shots.fonts.fallback:
|
||||||
['Noto Sans Display']`. Lilita One lacks most of Latin Extended (Turkish ş ğ İ, Polish, Czech, Romanian) and
|
['Noto Sans Display']`. Lilita One lacks most of Latin Extended (Turkish ş ğ İ, Polish, Czech, Romanian) and
|
||||||
Vietnamese. Re-run after copy or font edits (render refuses fonts that no longer cover the copy).
|
Vietnamese. Re-run after copy or font edits (render refuses fonts that no longer cover the copy).
|
||||||
|
A game's own brand font: put the file path (relative to the config; TTF / OTF / WOFF / WOFF2) or
|
||||||
|
`{ family, file, license }` into `shots.fonts.title` / `body` / `fallback`. The same coverage check runs on it, listed
|
||||||
|
fallbacks are tried before Noto (`pl title: ę ł ą Ł not in ER Display -> Noto Sans Display`), the file is served in
|
||||||
|
place (never copied) and its hash is in fonts.json, so edits to the font need `shots fonts` again. Ask the owner for
|
||||||
|
the license ('OFL-1.1', 'proprietary', ...) and put it in `license`; `shots check` warns without one.
|
||||||
5. **Style and scenes.** `shots.style`: `game` (sunburst, sparkles, outlined titles, badges) or `app` (calm gradient,
|
5. **Style and scenes.** `shots.style`: `game` (sunburst, sparkles, outlined titles, badges) or `app` (calm gradient,
|
||||||
one clean device frame, headline + subline, no sparkles; badges only as quiet chips when the copy has them).
|
one clean device frame, headline + subline, no sparkles; badges only as quiet chips when the copy has them).
|
||||||
Default: `app` for the app / subscription-app profiles, `game` otherwise. `shots.scenes`: palette (game: fire,
|
Default: `app` for the app / subscription-app profiles, `game` otherwise. `shots.scenes`: palette (game: fire,
|
||||||
|
|
|
||||||
322
tests/aso-plus.test.ts
Normal file
322
tests/aso-plus.test.ts
Normal file
|
|
@ -0,0 +1,322 @@
|
||||||
|
// aso competitors / suggest / audit: pure parts and the commands against recorded iTunes Search API answers
|
||||||
|
// (tests/fixtures/aso, real response shape, placeholder apps) and mocked Apple Ads keyword suggestions.
|
||||||
|
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
||||||
|
import { generateKeyPairSync } from 'node:crypto';
|
||||||
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { run as aso } from '../cli/aso';
|
||||||
|
import { run as check } from '../cli/check';
|
||||||
|
import { auditText, buildAudit, nextActions, playUse, rankTrend } from '../cli/lib/aso-audit';
|
||||||
|
import {
|
||||||
|
bigrams, candidates, categoryNames, competitorRow, coverageGaps, DRAFT_RE, draftLocales, draftMark, fitKeywordField, keywordSuggestionBody, newEntrants,
|
||||||
|
parseKeywordSuggestions, sameWord, setKeywords, stem, storefrontOf, tokens,
|
||||||
|
} from '../cli/lib/aso-intel';
|
||||||
|
import type { SearchApp } from '../cli/lib/aso-rank';
|
||||||
|
import { FORBIDDEN_ARGS, TOOLS, toArgv } from '../cli/mcp-tools';
|
||||||
|
import { JSON_TOOLS, methodName } from '../cli/serve';
|
||||||
|
import { BASE, capture, jsonOut, mockFetch, project, restore } from './helpers/store-mock';
|
||||||
|
|
||||||
|
const FIX = join(import.meta.dir, 'fixtures/aso');
|
||||||
|
const US = JSON.parse(readFileSync(join(FIX, 'search-grocery-list-us.json'), 'utf8')) as { results: SearchApp[] };
|
||||||
|
const DE = JSON.parse(readFileSync(join(FIX, 'search-einkaufsliste-de.json'), 'utf8')) as { results: SearchApp[] };
|
||||||
|
const ADS = JSON.parse(readFileSync(join(FIX, 'ads-keyword-suggestions.json'), 'utf8'));
|
||||||
|
const APP = { appId: '6400000101', bundleId: 'com.example.notes' };
|
||||||
|
const ADS_KEYS = ['APPLE_ADS_CLIENT_ID', 'APPLE_ADS_TEAM_ID', 'APPLE_ADS_KEY_ID', 'APPLE_ADS_PRIVATE_KEY', 'APPLE_ADS_ACCOUNT_ID'];
|
||||||
|
const saved: Record<string, string | undefined> = {};
|
||||||
|
|
||||||
|
beforeEach(() => { for (const k of ADS_KEYS) { saved[k] = process.env[k]; delete process.env[k]; } });
|
||||||
|
afterEach(() => { restore(); for (const k of ADS_KEYS) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
|
||||||
|
|
||||||
|
const LISTING = `# App Store
|
||||||
|
|
||||||
|
## en-US · English
|
||||||
|
|
||||||
|
### subtitle
|
||||||
|
\`\`\`
|
||||||
|
Shared grocery lists
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### promotionalText
|
||||||
|
\`\`\`
|
||||||
|
Promo.
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### keywords
|
||||||
|
\`\`\`
|
||||||
|
todo,checklist,list,family
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### description
|
||||||
|
\`\`\`
|
||||||
|
Example Notes keeps grocery lists and packing lists in one place. Share a packing list with family.
|
||||||
|
|
||||||
|
Sort groceries by aisle and reuse a packing checklist.
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
## de-DE · Deutsch
|
||||||
|
|
||||||
|
### subtitle
|
||||||
|
\`\`\`
|
||||||
|
Gemeinsame Listen
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### promotionalText
|
||||||
|
\`\`\`
|
||||||
|
Promo.
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### keywords
|
||||||
|
\`\`\`
|
||||||
|
einkauf,familie
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### description
|
||||||
|
\`\`\`
|
||||||
|
Einkaufslisten für die ganze Familie.
|
||||||
|
\`\`\`
|
||||||
|
`;
|
||||||
|
const PLAY = '# Play\n\n## English\n<!-- play: en-US -->\n\n### title\n```\nExample Notes: Groceries\n```\n\n### short\n```\nShared lists\n```\n\n### full\n```\nGrocery lists for the family.\n```\n';
|
||||||
|
|
||||||
|
describe('words', () => {
|
||||||
|
test('tokens, bigrams, plural-insensitive and suffix-aware sameness', () => {
|
||||||
|
expect(tokens('The best Grocery Lists for your family app', 'en-US')).toEqual(['best', 'grocery', 'lists', 'family']);
|
||||||
|
expect(tokens("Ayarlar'dan sil", 'tr')).toEqual(['ayarlar', 'sil']);
|
||||||
|
expect(bigrams('Grocery lists. Packing lists and more', 'en-US')).toEqual(['grocery lists', 'packing lists']);
|
||||||
|
expect(stem('groceries', 'en-US')).toBe('grocery');
|
||||||
|
expect(stem('lists', 'en-US')).toBe('list');
|
||||||
|
expect(stem('lists', 'de-DE')).toBe('lists');
|
||||||
|
expect(sameWord('listeler', 'listelerini', 'tr')).toBe(true);
|
||||||
|
expect(sameWord('list', 'listing', 'en-US')).toBe(false);
|
||||||
|
expect(storefrontOf('en-US')).toBe('us');
|
||||||
|
expect(storefrontOf('tr')).toBe('tr');
|
||||||
|
expect(storefrontOf('ja')).toBe('jp');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('competitors (recorded Search API answers)', () => {
|
||||||
|
const row = competitorRow(US.results, APP, { storefront: 'us', locale: 'en-US', term: 'grocery list' }, 4);
|
||||||
|
test('top N other apps with release dates and localized genres; our own position', () => {
|
||||||
|
expect(row.ourRank).toBe(3);
|
||||||
|
expect(row.apps.map(a => a.rank)).toEqual([1, 2, 4, 5]);
|
||||||
|
expect(row.apps[0]).toMatchObject({ name: 'Basket: Grocery Shopping List', developer: 'Example Studio A', ratings: 80000, released: '2012-05-11', updated: '2026-09-11', genre: 'Productivity' });
|
||||||
|
expect(row.apps[0]!.genres).toEqual([{ id: '6007', name: 'Productivity' }, { id: '6024', name: 'Shopping' }]);
|
||||||
|
});
|
||||||
|
test('coverage gaps: words of two or more developers that we do not cover; one-developer words (brands) left out', () => {
|
||||||
|
const all = competitorRow(US.results, APP, { storefront: 'us', locale: 'en-US', term: 'grocery list' }, 10);
|
||||||
|
const gaps = coverageGaps([all], ['list', 'todo'], 'en-US');
|
||||||
|
expect(gaps.map(g => g.word)).toEqual(['grocery', 'shopping']);
|
||||||
|
expect(gaps[0]).toMatchObject({ apps: 3, developers: 3 });
|
||||||
|
expect(gaps.some(g => g.word === 'cartful')).toBe(false); // one developer, two apps: a brand
|
||||||
|
expect(coverageGaps([all], ['groceries', 'lists', 'shopping'], 'en-US')).toEqual([]);
|
||||||
|
});
|
||||||
|
test('new entrants and localized category names', () => {
|
||||||
|
const before = { ...row, apps: row.apps.slice(1) };
|
||||||
|
expect(newEntrants([row], [before]).get('us|grocery list')).toEqual(['Basket: Grocery Shopping List']);
|
||||||
|
expect(newEntrants([row], undefined).size).toBe(0);
|
||||||
|
const de = competitorRow(DE.results, APP, { storefront: 'de', locale: 'de-DE', term: 'einkaufsliste' }, 10);
|
||||||
|
expect(categoryNames([de], ['PRODUCTIVITY'])).toEqual(['Produktivität']);
|
||||||
|
expect(categoryNames([de], ['FOOD_AND_DRINK'])).toEqual(['Essen und Trinken']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Apple Ads keyword suggestions', () => {
|
||||||
|
test('request body: required filters, terms, countries, popularity order', () => {
|
||||||
|
const b = keywordSuggestionBody('6400000101', ['grocery'], ['us']) as { filters: { field: string; value: string[] }[]; sorting: unknown; pagination: unknown };
|
||||||
|
expect(b.filters.map(f => f.field)).toEqual(['promotedObjectId', 'promotedObjectType', 'terms', 'countriesOrRegions']);
|
||||||
|
expect(b.filters[1]!.value).toEqual(['APPSTORE_APP']);
|
||||||
|
expect(b.filters[3]!.value).toEqual(['US']);
|
||||||
|
expect(b.sorting).toEqual([{ field: 'popularity', order: 'DESC' }]);
|
||||||
|
expect(b.pagination).toEqual({ offset: 0, pageSize: 200 });
|
||||||
|
});
|
||||||
|
test('parse: text + popularity 0-100, junk left out', () => {
|
||||||
|
expect(parseKeywordSuggestions(ADS)).toHaveLength(4);
|
||||||
|
expect(parseKeywordSuggestions({ result: [{ text: 'x', popularity: 140 }, { text: 'y' }, null] })).toEqual([{ text: 'x', popularity: 100 }]);
|
||||||
|
expect(parseKeywordSuggestions({})).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('candidates and the 100-byte field', () => {
|
||||||
|
const comp = [competitorRow(US.results, APP, { storefront: 'us', locale: 'en-US', term: 'grocery list' }, 10)];
|
||||||
|
const base = { locale: 'en-US', name: 'Example Notes', subtitle: 'Shared grocery lists', keywords: 'todo,checklist,list,family', description: 'Grocery lists and packing lists. Share a packing list with family. Sort by aisle, reuse a packing checklist. Aisle sorting.', competitors: comp, categories: ['Productivity'] };
|
||||||
|
test('no popularity without Apple Ads; relevance and competition from own text and competitor names', () => {
|
||||||
|
const c = candidates({ ...base, ads: [] });
|
||||||
|
expect(c.every(x => x.popularity === null)).toBe(true);
|
||||||
|
const packing = c.find(x => x.term === 'packing')!;
|
||||||
|
expect(packing).toMatchObject({ status: 'candidate', relevance: 2, inNames: 1, ofApps: 5 });
|
||||||
|
expect(c.find(x => x.term === 'grocery')!.status).toBe('indexed');
|
||||||
|
expect(c.find(x => x.term === 'productivity')!.status).toBe('category');
|
||||||
|
expect(c.find(x => x.term === 'cartful')).toBeUndefined();
|
||||||
|
});
|
||||||
|
test('Apple Ads popularity: exact word, or the best phrase that contains it', () => {
|
||||||
|
const c = candidates({ ...base, ads: parseKeywordSuggestions(ADS) });
|
||||||
|
expect(c.find(x => x.term === 'packing')).toMatchObject({ popularity: 41, popularityFrom: 'exact' });
|
||||||
|
expect(c.find(x => x.term === 'shopping')).toMatchObject({ popularity: 64, popularityFrom: 'exact', sources: ['competitors', 'apple-ads'] });
|
||||||
|
expect(c.find(x => x.term === 'aisle')!.popularity).toBeNull();
|
||||||
|
});
|
||||||
|
test('fit: <= 100 bytes, current terms kept, indexed and duplicate words dropped', () => {
|
||||||
|
const ranked = candidates({ ...base, ads: [] });
|
||||||
|
const p = fitKeywordField({ locale: 'en-US', current: base.keywords, name: base.name, subtitle: base.subtitle, ranked });
|
||||||
|
expect(p.kept).toEqual(['todo', 'checklist', 'family']);
|
||||||
|
expect(p.dropped).toEqual([{ term: 'list', why: 'already in the name / subtitle (indexed)' }]);
|
||||||
|
expect(p.added).toContain('packing');
|
||||||
|
expect(p.after).not.toMatch(/,\s|\s,/);
|
||||||
|
expect(p.bytes).toBeLessThanOrEqual(100);
|
||||||
|
expect(new Set(p.after.split(',')).size).toBe(p.after.split(',').length);
|
||||||
|
// bytes, not characters: Turkish letters take two
|
||||||
|
const many = Array.from({ length: 30 }, (_, i) => ({ term: `şğü${i}`, kind: 'word' as const, sources: ['description' as const], ours: 2, relevance: 1, inNames: 0, ofApps: 0, popularity: null, popularityFrom: null, status: 'candidate' as const }));
|
||||||
|
const t = fitKeywordField({ locale: 'tr', current: '', name: 'X', subtitle: '', ranked: many });
|
||||||
|
expect(t.bytes).toBeLessThanOrEqual(100);
|
||||||
|
expect(Buffer.byteLength(t.after)).toBe(t.bytes);
|
||||||
|
expect(fitKeywordField({ locale: 'en-US', current: 'todo', name: 'X', subtitle: '', ranked, fresh: true }).kept).toEqual([]);
|
||||||
|
});
|
||||||
|
test('write: keywords block replaced, draft line above it, found again, then removable', () => {
|
||||||
|
const md = setKeywords(LISTING, 'en-US', 'todo,packing', draftMark('2026-10-12'));
|
||||||
|
expect(md).toContain('### keywords\n<!-- storebound-aso: draft keywords from `aso suggest` 2026-10-12; review them, then delete this line -->\n```\ntodo,packing\n```\n');
|
||||||
|
expect(md).toContain('### description\n```\nExample Notes keeps');
|
||||||
|
expect(draftLocales(md)).toEqual(['en-US']);
|
||||||
|
expect(setKeywords(md, 'en-US', 'a,b', draftMark('2026-10-13')).match(/storebound-aso/g)).toHaveLength(1);
|
||||||
|
expect(draftLocales(md.replace(DRAFT_RE, ''))).toEqual([]);
|
||||||
|
expect(() => setKeywords(LISTING, 'fr-FR', 'x', 'm')).toThrow('no "## fr-FR"');
|
||||||
|
const noKw = '## ja · 日本語\n\n### subtitle\n```\nx\n```\n';
|
||||||
|
expect(setKeywords(noKw, 'ja', 'リスト', draftMark('2026-10-12'))).toContain('### subtitle\n```\nx\n```\n\n### keywords\n<!-- storebound-aso');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('audit parts', () => {
|
||||||
|
const r = (date: string, rows: [string, number | null][]) => ({ date, rows: rows.map(([keyword, rank]) => ({ storefront: 'us', locale: 'en-US', keyword, rank, results: 200, competitors: [] })) });
|
||||||
|
test('rank trend arrows', () => {
|
||||||
|
const t = rankTrend([r('2026-09-01', [['todo', 12], ['list', 40], ['plan', null]]), r('2026-09-15', [['todo', 8], ['list', 55], ['plan', 30], ['new', null]]), r('2026-08-01', [['todo', 20], ['gone', 9]])]);
|
||||||
|
const by = Object.fromEntries(t.rows.map(x => [x.keyword, x]));
|
||||||
|
expect(t.dates).toEqual(['2026-08-01', '2026-09-01', '2026-09-15']);
|
||||||
|
expect(by.todo).toMatchObject({ rank: 8, previous: 12, change: 4, arrow: '↑', best: 8, snapshots: 3 });
|
||||||
|
expect(by.list).toMatchObject({ arrow: '↓', change: -15 });
|
||||||
|
expect(by.plan!.arrow).toBe('new');
|
||||||
|
expect(by.new!.arrow).toBe('·');
|
||||||
|
expect(by.gone).toMatchObject({ rank: 9, arrow: 'new', snapshots: 1 });
|
||||||
|
expect(t.series.find(s => s.keyword === 'todo')!.ranks).toEqual([20, 12, 8]);
|
||||||
|
});
|
||||||
|
test('play use: short description room, title words, density', () => {
|
||||||
|
const full = Array.from({ length: 12 }, () => 'grocery lists for the family to share and plan').join('. ');
|
||||||
|
const u = playUse({ lang: 'en-US', title: 'Example: Groceries', short: 'Shared lists', full, whatsNew: '' });
|
||||||
|
expect(u).toMatchObject({ shortChars: 12, shortRoom: 68, titleWordsInShort: false });
|
||||||
|
expect(u.stuffed).toContain('grocery');
|
||||||
|
});
|
||||||
|
test('audit: next 3 actions, PPO cannot test the subtitle, Play experiments are a guide', () => {
|
||||||
|
const a = buildAudit({ today: '2026-10-12', storefront: 'US', findings: [{ level: 'warn', where: 'apple en-US', msg: 'keywords: 40/100 bytes used; fill at least 90 (60 bytes free)' }],
|
||||||
|
drafts: [], appName: 'Example Notes', ranks: [], competitors: null, analytics: [], variants: ['b'],
|
||||||
|
apple: { 'en-US': { subtitle: 'x', keywords: 'a' } }, play: [{ lang: 'en-US', title: 'T', short: 'Short', full: 'Full text.', whatsNew: '' }] });
|
||||||
|
expect(a.next).toHaveLength(3);
|
||||||
|
expect(a.next[0]!.command).toBe('storebound aso suggest --locale en-US');
|
||||||
|
expect(a.next[1]!.what).toBe('take a first rank snapshot');
|
||||||
|
expect(a.experiments.find(e => e.what === 'subtitle variant')!.why).toContain('cannot be A/B tested');
|
||||||
|
expect(a.experiments.find(e => e.store === 'apple')!.how).toContain('apple ppo create --variant b --dry');
|
||||||
|
expect(a.experiments.find(e => e.store === 'play')!.how).toContain('no API');
|
||||||
|
expect(auditText(a)).toContain('Next 3 actions');
|
||||||
|
expect(nextActions({ ...a, keywordField: { ...a.keywordField, findings: [] } }, { today: '2026-10-12', variants: [] } as never).length).toBeLessThanOrEqual(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('commands', () => {
|
||||||
|
const files = { 'store/appstore.md': LISTING, 'store/listing.md': PLAY };
|
||||||
|
test('competitors: --dry lists the queries, a run saves a snapshot and the gaps', async () => {
|
||||||
|
const p = project(BASE, files);
|
||||||
|
const calls = mockFetch([{ match: /^\/search\?term=grocery\+list&country=us/, answer: US }]);
|
||||||
|
let r = await capture(() => aso(p.ctx(['competitors', '--term', 'grocery list', '--only-terms', '--dry', '--json'])));
|
||||||
|
expect(jsonOut(r.out).queries).toEqual([{ storefront: 'us', locale: 'en-US', term: 'grocery list', url: 'https://itunes.apple.com/search?term=grocery+list&country=us&media=software&entity=software&limit=11' }]);
|
||||||
|
expect(calls).toHaveLength(0);
|
||||||
|
r = await capture(() => aso(p.ctx(['competitors', '--term', 'grocery list', '--only-terms', '--top', '3', '--json'])));
|
||||||
|
const j = jsonOut(r.out) as { rows: { ourRank: number; apps: unknown[] }[]; gaps: { gaps: { word: string }[] }[]; saved: boolean };
|
||||||
|
expect(j.rows[0]!.ourRank).toBe(3);
|
||||||
|
expect(j.rows[0]!.apps).toHaveLength(3);
|
||||||
|
expect(j.saved).toBe(true);
|
||||||
|
const snap = join(p.root, '.storebound/aso/competitors', `${new Date().toISOString().slice(0, 10)}.json`);
|
||||||
|
expect(JSON.parse(readFileSync(snap, 'utf8')).top).toBe(3);
|
||||||
|
// MCP form: read-only, nothing saved
|
||||||
|
const q = project(BASE, files);
|
||||||
|
mockFetch([{ match: /^\/search\?term=grocery\+list/, answer: US }]);
|
||||||
|
r = await capture(() => aso(q.ctx(['competitors', '--term', 'grocery list', '--only-terms', '--no-save', '--json'])));
|
||||||
|
expect(jsonOut(r.out).saved).toBe(false);
|
||||||
|
expect(existsSync(join(q.root, '.storebound/aso/competitors'))).toBe(false);
|
||||||
|
});
|
||||||
|
test('suggest: offline proposal is a dry diff; --write marks a draft that check --aso reports', async () => {
|
||||||
|
const p = project(BASE, files);
|
||||||
|
mockFetch([]);
|
||||||
|
let r = await capture(() => aso(p.ctx(['suggest', '--locale', 'en-US', '--json'])));
|
||||||
|
const j = jsonOut(r.out) as { written: boolean; results: { ads: string; proposal: { before: string; after: string; bytes: number }; candidates: { popularity: number | null }[] }[] };
|
||||||
|
expect(j.written).toBe(false);
|
||||||
|
expect(j.results[0]!.ads).toMatch(/no Apple Ads credentials.*popularity unknown/);
|
||||||
|
expect(j.results[0]!.candidates.every(c => c.popularity === null)).toBe(true);
|
||||||
|
expect(j.results[0]!.proposal.before).toBe('todo,checklist,list,family');
|
||||||
|
expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toBe(LISTING);
|
||||||
|
r = await capture(() => aso(p.ctx(['suggest', '--locale', 'en-US', '--write'])));
|
||||||
|
const md = readFileSync(join(p.root, 'store/appstore.md'), 'utf8');
|
||||||
|
expect(draftLocales(md)).toEqual(['en-US']);
|
||||||
|
expect(md).toContain(j.results[0]!.proposal.after);
|
||||||
|
r = await capture(() => check(p.ctx(['--aso'])));
|
||||||
|
expect(r.out).toContain('draft from `aso suggest`, not reviewed yet');
|
||||||
|
});
|
||||||
|
test('suggest with Apple Ads credentials: popularity from the keyword suggestions endpoint', async () => {
|
||||||
|
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||||
|
Object.assign(process.env, { APPLE_ADS_CLIENT_ID: 'SEARCHADS.client-placeholder', APPLE_ADS_TEAM_ID: 'SEARCHADS.team-placeholder', APPLE_ADS_KEY_ID: 'key-placeholder',
|
||||||
|
APPLE_ADS_PRIVATE_KEY: privateKey.export({ type: 'sec1', format: 'pem' }).toString(), APPLE_ADS_ACCOUNT_ID: '123456789' });
|
||||||
|
const p = project(BASE, files);
|
||||||
|
const calls = mockFetch([
|
||||||
|
{ method: 'POST', match: /^\/auth\/oauth2\/token$/, answer: { access_token: 'token-placeholder', token_type: 'Bearer', expires_in: 3600 } },
|
||||||
|
{ method: 'POST', match: /^\/v1\/suggestions\/keywords\/query$/, answer: ADS },
|
||||||
|
]);
|
||||||
|
const r = await capture(() => aso(p.ctx(['suggest', '--locale', 'en-US', '--json'])));
|
||||||
|
const j = jsonOut(r.out) as { results: { ads: string; candidates: { term: string; popularity: number | null }[] }[] };
|
||||||
|
expect(j.results[0]!.ads).toContain('Apple Ads keyword suggestions (US): 4');
|
||||||
|
expect(j.results[0]!.candidates.find(c => c.term === 'packing')!.popularity).toBe(41);
|
||||||
|
const q = calls.find(c => c.path === '/v1/suggestions/keywords/query')!;
|
||||||
|
expect((q.body as { filters: unknown[] }).filters[0]).toEqual({ field: 'promotedObjectId', operator: 'EQUALS', value: ['6400000101'] });
|
||||||
|
expect(calls.some(c => c.method !== 'POST')).toBe(false);
|
||||||
|
});
|
||||||
|
test('audit: offline report from the listing files and snapshots', async () => {
|
||||||
|
const p = project(BASE, { ...files,
|
||||||
|
'.storebound/aso/2026-09-01.json': JSON.stringify({ date: '2026-09-01', rows: [{ storefront: 'us', locale: 'en-US', keyword: 'todo', rank: 30, results: 200, competitors: [] }] }),
|
||||||
|
'.storebound/aso/2026-09-15.json': JSON.stringify({ date: '2026-09-15', rows: [{ storefront: 'us', locale: 'en-US', keyword: 'todo', rank: 21, results: 200, competitors: [] }] }),
|
||||||
|
'.storebound/aso/competitors/2026-09-15.json': JSON.stringify({ date: '2026-09-15', app: APP, top: 10, rows: [competitorRow(US.results, APP, { storefront: 'us', locale: 'en-US', term: 'grocery list' }, 10)] }),
|
||||||
|
});
|
||||||
|
const calls = mockFetch([]);
|
||||||
|
let r = await capture(() => aso(p.ctx(['audit', '--json'])));
|
||||||
|
const j = jsonOut(r.out) as { ranks: { rows: { arrow: string; change: number }[] }; competitors: { gaps: { gaps: { word: string }[] }[] }; next: unknown[]; play: unknown[] };
|
||||||
|
expect(j.ranks.rows[0]).toMatchObject({ arrow: '↑', change: 9 });
|
||||||
|
expect(j.competitors.gaps[0]!.gaps.map(g => g.word)).toContain('shopping');
|
||||||
|
expect(j.next.length).toBeLessThanOrEqual(3);
|
||||||
|
expect(j.play).toHaveLength(1);
|
||||||
|
expect(calls).toHaveLength(0);
|
||||||
|
r = await capture(() => aso(p.ctx(['audit'])));
|
||||||
|
expect(r.out).toContain('2. Ranks');
|
||||||
|
expect(r.out).toMatch(/us\s+todo\s+21\s+↑\s+\+9/);
|
||||||
|
});
|
||||||
|
test('unknown subcommand', async () => {
|
||||||
|
const p = project(BASE, files);
|
||||||
|
await expect(aso(p.ctx(['nope']))).rejects.toThrow('rank | competitors | suggest | audit');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MCP and desktop', () => {
|
||||||
|
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||||
|
test('read-only tools: competitors saves nothing, suggest never writes, audit is offline', () => {
|
||||||
|
expect(t('aso_competitors')).toMatchObject({ write: false, network: true });
|
||||||
|
expect(toArgv(t('aso_competitors'), { storefront: 'us,tr', terms: 'grocery list', top: 5 }).argv).toEqual(['aso', 'competitors', '--storefront', 'us,tr', '--term', 'grocery list', '--top', '5', '--no-save', '--json']);
|
||||||
|
expect(t('aso_suggest')).toMatchObject({ write: false, network: true });
|
||||||
|
expect(toArgv(t('aso_suggest'), { locale: 'en-US', offline: true }).argv).toEqual(['aso', 'suggest', '--locale', 'en-US', '--offline', '--json']);
|
||||||
|
expect(t('aso_audit')).toMatchObject({ write: false, network: false });
|
||||||
|
expect(toArgv(t('aso_audit'), {}).argv).toEqual(['aso', 'audit', '--json']);
|
||||||
|
for (const n of ['aso_competitors', 'aso_suggest', 'aso_audit']) {
|
||||||
|
for (const a of FORBIDDEN_ARGS) expect(toArgv(t(n), { locale: 'x' }).argv).not.toContain(a);
|
||||||
|
expect(JSON_TOOLS.has(n)).toBe(true);
|
||||||
|
}
|
||||||
|
expect(methodName('aso_audit')).toBe('aso.audit');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// keep the fixture honest: placeholder apps only, the real Search API field set
|
||||||
|
test('fixtures are placeholders with the Search API fields used', () => {
|
||||||
|
for (const r of [...US.results, ...DE.results]) {
|
||||||
|
expect(r.bundleId).toMatch(/^com\.example\./);
|
||||||
|
for (const k of ['trackId', 'trackName', 'sellerName', 'userRatingCount', 'releaseDate', 'currentVersionReleaseDate', 'genres', 'genreIds', 'primaryGenreName']) expect(r).toHaveProperty(k);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
@ -79,7 +79,9 @@ const server = Bun.serve({
|
||||||
});
|
});
|
||||||
afterAll(() => server.stop(true));
|
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;
|
// launch only: exiting closes the browser's pipe and it quits on its own (a graceful close of Google Chrome, the
|
||||||
|
// fallback without playwright's Chromium, can take 30 s)
|
||||||
|
const canLaunch = spawnSync('bun', ['-e', `const { launch } = await import(${JSON.stringify(join(import.meta.dir, '..', 'cli', 'shots', 'browser.ts'))}); await launch(${JSON.stringify(join(import.meta.dir, '..'))}, { headless: true }); process.exit(0);`], { timeout: 60_000 }).status === 0;
|
||||||
if (!canLaunch) console.warn('capture-web browser tests skipped: no Chromium could launch (bunx playwright install chromium)');
|
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. */
|
/** A temp project with this config; cli() runs `storebound shots capture <args>` in it. */
|
||||||
|
|
|
||||||
68
tests/ci-plan.test.ts
Normal file
68
tests/ci-plan.test.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { balance, depsOf, GLOBAL, HEAVY, junitTimes, listTests, relatedTests, rustNeeded, shardCount } from '../tools/ci-plan';
|
||||||
|
|
||||||
|
describe('tools/ci-plan: test shards', () => {
|
||||||
|
test('shard count: cores - 1, between 1 and 8, env override', () => {
|
||||||
|
expect(shardCount({}, 10)).toBe(8);
|
||||||
|
expect(shardCount({}, 4)).toBe(3);
|
||||||
|
expect(shardCount({}, 1)).toBe(1);
|
||||||
|
expect(shardCount({ STOREBOUND_CI_SHARDS: '3' }, 10)).toBe(3);
|
||||||
|
expect(shardCount({ STOREBOUND_CI_SHARDS: 'x' }, 10)).toBe(8);
|
||||||
|
});
|
||||||
|
test('balance: every file once, longest first, heavy suites never share a shard', () => {
|
||||||
|
const cost: Record<string, number> = { h1: 10, h2: 9, a: 5, b: 4, c: 3, d: 2, e: 1 };
|
||||||
|
const shards = balance(Object.keys(cost), 3, f => cost[f]!, ['h1', 'h2']);
|
||||||
|
expect(shards.flat().sort()).toEqual(Object.keys(cost).sort());
|
||||||
|
for (const s of shards) expect(s.filter(f => f.startsWith('h')).length).toBeLessThanOrEqual(1);
|
||||||
|
const loads = shards.map(s => s.reduce((n, f) => n + cost[f]!, 0));
|
||||||
|
expect(Math.max(...loads) - Math.min(...loads)).toBeLessThanOrEqual(cost.a!);
|
||||||
|
});
|
||||||
|
test('balance: more heavy suites than shards still places each once; empty shards dropped', () => {
|
||||||
|
expect(balance(['h1', 'h2', 'h3'], 2, () => 1, ['h1', 'h2', 'h3']).flat().sort()).toEqual(['h1', 'h2', 'h3']);
|
||||||
|
expect(balance(['a'], 8, () => 1)).toEqual([['a']]);
|
||||||
|
});
|
||||||
|
test('JUnit report: per-file seconds from the top-level suites only', () => {
|
||||||
|
const xml = `<testsuites><testsuite name="tests/a.test.ts" file="tests/a.test.ts" tests="2" time="1.5" hostname="h">
|
||||||
|
<testsuite name="group" file="tests/a.test.ts" time="0.2"></testsuite></testsuite>
|
||||||
|
<testsuite name="tests/b.test.ts" file="tests/b.test.ts" time="0.25"></testsuite></testsuites>`;
|
||||||
|
expect(junitTimes(xml)).toEqual({ 'tests/a.test.ts': 1.5, 'tests/b.test.ts': 0.25 });
|
||||||
|
});
|
||||||
|
test('every heavy suite exists and every test file is found', () => {
|
||||||
|
const all = listTests();
|
||||||
|
for (const h of HEAVY) expect(all).toContain(h);
|
||||||
|
expect(all).toContain('tests/ci-plan.test.ts');
|
||||||
|
expect(all).toContain('apps/desktop/tests/webview.test.ts');
|
||||||
|
expect(all.some(f => f.includes('node_modules') || f.includes('/fixtures/'))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('tools/ci-plan: related tests (ci:quick)', () => {
|
||||||
|
const all = listTests();
|
||||||
|
test('imports, transitive imports and spawned CLI paths', () => {
|
||||||
|
expect(depsOf('tests/ci-plan.test.ts')).toEqual(['tools/ci-plan.ts']);
|
||||||
|
expect(relatedTests(['tools/ci-plan.ts'], all)).toEqual(['tests/ci-plan.test.ts']);
|
||||||
|
// a CLI library change reaches the tests that import it directly and through other modules
|
||||||
|
const upsert = relatedTests(['cli/lib/upsert.ts'], all);
|
||||||
|
expect(upsert).toContain('tests/idempotency.test.ts');
|
||||||
|
expect(upsert.length).toBeGreaterThan(3);
|
||||||
|
});
|
||||||
|
test('a changed test runs itself; a global file runs everything; docs run nothing', () => {
|
||||||
|
expect(relatedTests(['tests/pure.test.ts'], all)).toEqual(['tests/pure.test.ts']);
|
||||||
|
expect(relatedTests(['package.json'], all)).toEqual(all);
|
||||||
|
expect(GLOBAL.test('bunfig.toml')).toBe(true);
|
||||||
|
expect(relatedTests([['docs/nobody', 'reads.md'].join('-')], all)).toEqual([]);
|
||||||
|
});
|
||||||
|
test('a browser suite runs for its own module and its near imports, not for every shared core module', () => {
|
||||||
|
expect(relatedTests(['cli/lib/upsert.ts'], all, undefined, HEAVY)).not.toContain('tests/console-fill.test.ts');
|
||||||
|
expect(relatedTests(['cli/lib/upsert.ts'], all)).toContain('tests/console-fill.test.ts');
|
||||||
|
expect(relatedTests(['cli/console/fill.ts'], all, undefined, HEAVY)).toContain('tests/console-fill.test.ts');
|
||||||
|
expect(relatedTests(['tests/capture-web.test.ts'], all, undefined, HEAVY)).toEqual(['tests/capture-web.test.ts']);
|
||||||
|
});
|
||||||
|
test('Rust steps only for the Tauri crate or the sidecar build, or with CI=full / unknown diff', () => {
|
||||||
|
expect(rustNeeded(['cli/index.ts'], {})).toBe(false);
|
||||||
|
expect(rustNeeded(['apps/desktop/src-tauri/src/main.rs'], {})).toBe(true);
|
||||||
|
expect(rustNeeded(['tools/build-sidecars.ts'], {})).toBe(true);
|
||||||
|
expect(rustNeeded([], { CI: 'full' })).toBe(true);
|
||||||
|
expect(rustNeeded(null, {})).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,7 +1,11 @@
|
||||||
// storebound console fill: pure answer building (rule 5: only what the config proves is certain), the click gate, the
|
// storebound console fill: pure answer building (rule 5: only what the config proves is certain), the click gate, the
|
||||||
// sign-in detector, and the engine run headless against MODELED console pages (tests/fixtures/console, written from
|
// sign-in detector, and the engine run headless against MODELED console pages (tests/fixtures/console, written from
|
||||||
// the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium launches.
|
// the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium is
|
||||||
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
|
// installed (a launch that times out fails instead). Load-proofing (tests/helpers/browser.ts): one launch with a long
|
||||||
|
// launch timeout, every context closed right after its test, event-driven waits for log lines, explicit test timeouts.
|
||||||
|
// Slow on purpose (marked SLOW): the sign-in / watching tests and the account tests wait out real "not here" timeouts
|
||||||
|
// of the engine (navTimeoutMs / navMs, scaled down through the options) and the profile tests relaunch Chromium.
|
||||||
|
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
|
@ -12,6 +16,7 @@ import { parseArgs } from '../cli/lib/args';
|
||||||
import { type ShipConfig, validateExtras } from '../cli/lib/config';
|
import { type ShipConfig, validateExtras } from '../cli/lib/config';
|
||||||
import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId, formMeta } from '../cli/lib/console-answers';
|
import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId, formMeta } from '../cli/lib/console-answers';
|
||||||
import { consoleReached, CREATE_APP_OPENERS, createAppAllowed, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInText, isSignInUrl, navAllowed, navPlan, playDeveloperId, switchAllowed } from '../cli/lib/console-forms';
|
import { consoleReached, CREATE_APP_OPENERS, createAppAllowed, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInText, isSignInUrl, navAllowed, navPlan, playDeveloperId, switchAllowed } from '../cli/lib/console-forms';
|
||||||
|
import { AFTER_ALL_MS, AFTER_EACH_MS, capped, CLOSE_TIMEOUT_MS, LAUNCH_TIMEOUT_MS, launchTestBrowser, logLines, testScope } from './helpers/browser';
|
||||||
|
|
||||||
const config: ShipConfig = {
|
const config: ShipConfig = {
|
||||||
app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' },
|
app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' },
|
||||||
|
|
@ -160,14 +165,18 @@ describe('--dry --json', () => {
|
||||||
|
|
||||||
// ---- the engine against the modeled pages ----
|
// ---- the engine against the modeled pages ----
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// launched once for the whole file (module level: bun's hook timeouts do not apply, LAUNCH_TIMEOUT_MS does)
|
||||||
let browser: any = null;
|
const shared = await launchTestBrowser('playwright');
|
||||||
let skipWhy = '';
|
const { browser, skipWhy } = shared;
|
||||||
try {
|
if (!browser) console.warn(`console-fill browser tests skipped: no Chromium installed (${skipWhy}). Run \`bunx playwright install chromium\`.`);
|
||||||
const { chromium } = await import('playwright');
|
/** The contexts and engine runs of the current test, closed / awaited right after it (afterEach below). */
|
||||||
try { browser = await chromium.launch({ headless: true }); } catch { browser = await chromium.launch({ headless: true, channel: 'chrome' }); }
|
const scope = testScope(() => browser);
|
||||||
} catch (e) { skipWhy = (e as Error).message.split('\n')[0]!; }
|
/** Browser tests: a few seconds each on an idle machine; the timeout leaves room for a loaded one. */
|
||||||
if (!browser) console.warn(`console-fill browser tests skipped: no Chromium could launch (${skipWhy}). Run \`bunx playwright install chromium\`.`);
|
const BROWSER_TEST_MS = 30_000;
|
||||||
|
/** SLOW tests (engine "not here" timeouts, Chromium relaunches): ~5-10 s idle. */
|
||||||
|
const SLOW_TEST_MS = 90_000;
|
||||||
|
/** Engine waits that are expected to SUCCEED: they return as soon as the element is there, so a long cap costs nothing. */
|
||||||
|
const FOUND_MS = 15_000;
|
||||||
|
|
||||||
const FIX = join(import.meta.dir, 'fixtures', 'console');
|
const FIX = join(import.meta.dir, 'fixtures', 'console');
|
||||||
/** Console URLs of the navigation plans -> modeled pages (bases: asc = <base>asc, play = <base>play). */
|
/** Console URLs of the navigation plans -> modeled pages (bases: asc = <base>asc, play = <base>play). */
|
||||||
|
|
@ -195,10 +204,12 @@ beforeAll(() => {
|
||||||
} });
|
} });
|
||||||
base = `http://127.0.0.1:${server.port}/`;
|
base = `http://127.0.0.1:${server.port}/`;
|
||||||
});
|
});
|
||||||
afterAll(async () => { server?.stop(true); await browser?.close(); }, 30_000); // closing every context of the run can take a few seconds
|
// bounded: every context is closed per test (afterEach) and each close is capped (tests/helpers/browser.ts)
|
||||||
|
afterEach(() => scope.settle(), AFTER_EACH_MS);
|
||||||
|
afterAll(async () => { await shared.close(); server?.stop(true); }, AFTER_ALL_MS);
|
||||||
|
|
||||||
async function open(file: string) {
|
async function open(file: string) {
|
||||||
const page = await browser.newPage();
|
const page = await scope.newPage();
|
||||||
await page.goto(base + file);
|
await page.goto(base + file);
|
||||||
return page;
|
return page;
|
||||||
}
|
}
|
||||||
|
|
@ -227,7 +238,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
// the next poll finds nothing left to do
|
// the next poll finds nothing left to do
|
||||||
expect((await fillPage(page, def, pageAnswers('apple-app-record'), new Set([0]))).section).toBeNull();
|
expect((await fillPage(page, def, pageAnswers('apple-app-record'), new Set([0]))).section).toBeNull();
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('User Access under a plain heading (real App Store Connect): the radios are found in the dialog', async () => {
|
test('User Access under a plain heading (real App Store Connect): the radios are found in the dialog', async () => {
|
||||||
const page = await open('apple-app-record-heading.html');
|
const page = await open('apple-app-record-heading.html');
|
||||||
|
|
@ -237,7 +248,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
expect(s.filled).toContain('name');
|
expect(s.filled).toContain('name');
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('a lasting partial miss fills every field that was found and leaves only the missing one', async () => {
|
test('a lasting partial miss fills every field that was found and leaves only the missing one', async () => {
|
||||||
const page = await open('apple-app-record-renamed.html');
|
const page = await open('apple-app-record-renamed.html');
|
||||||
|
|
@ -250,7 +261,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
expect(await checked(page, 'iOS')).toBe(true);
|
expect(await checked(page, 'iOS')).toBe(true);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('a renamed label stops filling and falls back to guidance', async () => {
|
test('a renamed label stops filling and falls back to guidance', async () => {
|
||||||
const page = await open('apple-app-record-renamed.html');
|
const page = await open('apple-app-record-renamed.html');
|
||||||
|
|
@ -262,7 +273,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
expect(consoleResult('apple-app-record', config).guidance).toContain('Name: Example Game');
|
expect(consoleResult('apple-app-record', config).guidance).toContain('Name: Example Game');
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('app privacy: section by section as the owner moves on; Next / Save / Publish never clicked', async () => {
|
test('app privacy: section by section as the owner moves on; Next / Save / Publish never clicked', async () => {
|
||||||
const page = await open('apple-app-privacy.html');
|
const page = await open('apple-app-privacy.html');
|
||||||
|
|
@ -295,7 +306,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
expect(done.size).toBe(def.sections.length);
|
expect(done.size).toBe(def.sections.length);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('content rating: full email in the page, Game, purchases yes, the rest empty + highlighted', async () => {
|
test('content rating: full email in the page, Game, purchases yes, the rest empty + highlighted', async () => {
|
||||||
const page = await open('play-content-rating.html');
|
const page = await open('play-content-rating.html');
|
||||||
|
|
@ -316,7 +327,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
expect(await page.getByRole('radiogroup', { name: /loot boxes/ }).getByRole('radio').evaluateAll((els: HTMLInputElement[]) => els.some(e => e.checked))).toBe(false);
|
expect(await page.getByRole('radiogroup', { name: /loot boxes/ }).getByRole('radio').evaluateAll((els: HTMLInputElement[]) => els.some(e => e.checked))).toBe(false);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('target audience: ages, appeal highlighted, ads yes', async () => {
|
test('target audience: ages, appeal highlighted, ads yes', async () => {
|
||||||
const page = await open('play-target-audience.html');
|
const page = await open('play-target-audience.html');
|
||||||
|
|
@ -333,7 +344,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
expect(await checked(page, /^Yes, my app contains ads/, 'radio')).toBe(true);
|
expect(await checked(page, /^Yes, my app contains ads/, 'radio')).toBe(true);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('sign-in detector and safeClick', async () => {
|
test('sign-in detector and safeClick', async () => {
|
||||||
const signin = await open('signin.html');
|
const signin = await open('signin.html');
|
||||||
|
|
@ -348,7 +359,7 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
|
||||||
expect(await safeClick(page.getByRole('button', { name: 'Cancel' }), 'Cancel')).toBe(true);
|
expect(await safeClick(page.getByRole('button', { name: 'Cancel' }), 'Cancel')).toBe(true);
|
||||||
expect(await clicks(page)).toEqual(['Cancel']);
|
expect(await clicks(page)).toEqual(['Cancel']);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---- navigation to the form after sign-in ----
|
// ---- navigation to the form after sign-in ----
|
||||||
|
|
@ -400,10 +411,10 @@ describe('navigation plan (pure)', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
const quiet = { timeoutMs: 1500, say: () => {} };
|
const quiet = { timeoutMs: FOUND_MS, say: () => {} }; // every navigation with `quiet` is expected to succeed
|
||||||
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
|
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
|
||||||
const noneDenied = (names: string[]) => { for (const n of names) expect(navAllowed(n, 'link')).toBe(true); };
|
const noneDenied = (names: string[]) => { for (const n of names) expect(navAllowed(n, 'link')).toBe(true); };
|
||||||
const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
|
const fresh = async () => { const p = await scope.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
|
||||||
|
|
||||||
test('App Store Connect (EN): + > New App opens the dialog and it is filled; Create and Submit for Review never clicked', async () => {
|
test('App Store Connect (EN): + > New App opens the dialog and it is filled; Create and Submit for Review never clicked', async () => {
|
||||||
const page = await fresh();
|
const page = await fresh();
|
||||||
|
|
@ -415,7 +426,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
expect(s.filled).toContain('name');
|
expect(s.filled).toContain('name');
|
||||||
expect(await clicks(page)).toEqual(['+']); // the + button only, never Create / Submit for Review
|
expect(await clicks(page)).toEqual(['+']); // the + button only, never Create / Submit for Review
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('App Store Connect (TR): Uygulama Ekle > Yeni Uygulama; Oluştur and İncelemeye Gönder never clicked', async () => {
|
test('App Store Connect (TR): Uygulama Ekle > Yeni Uygulama; Oluştur and İncelemeye Gönder never clicked', async () => {
|
||||||
const page = await fresh();
|
const page = await fresh();
|
||||||
|
|
@ -424,7 +435,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
expect(await navClicks(page)).toEqual(['Uygulama Ekle', 'Yeni Uygulama']);
|
expect(await navClicks(page)).toEqual(['Uygulama Ekle', 'Yeni Uygulama']);
|
||||||
expect(await clicks(page)).toEqual(['+']);
|
expect(await clicks(page)).toEqual(['+']);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('a missing step stops navigation, names the step and clicks nothing', async () => {
|
test('a missing step stops navigation, names the step and clicks nothing', async () => {
|
||||||
const page = await fresh();
|
const page = await fresh();
|
||||||
|
|
@ -435,7 +446,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
expect(await navClicks(page)).toEqual([]);
|
expect(await navClicks(page)).toEqual([]);
|
||||||
expect(formMeta('apple-app-record', config).open[0]).toContain('New App');
|
expect(formMeta('apple-app-record', config).open[0]).toContain('New App');
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('App Privacy: appId deep link, or app list > the app > App Privacy; two apps of one name -> stop and list', async () => {
|
test('App Privacy: appId deep link, or app list > the app > App Privacy; two apps of one name -> stop and list', async () => {
|
||||||
let page = await fresh();
|
let page = await fresh();
|
||||||
|
|
@ -453,7 +464,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
expect(r).toMatchObject({ ok: false, failed: 'the app in the list', candidates: ['Example Game', 'Example Game'] });
|
expect(r).toMatchObject({ ok: false, failed: 'the app in the list', candidates: ['Example Game', 'Example Game'] });
|
||||||
expect(await navClicks(page)).toEqual([]);
|
expect(await navClicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('Play: the app by package name > Policy and programs > App content > Start / Manage; nothing deny-listed clicked', async () => {
|
test('Play: the app by package name > Policy and programs > App content > Start / Manage; nothing deny-listed clicked', async () => {
|
||||||
for (const [form, link, heading] of [['play-content-rating', 'Start', 'Content rating'], ['play-target-audience', 'Manage', 'Target audience and content']] as const) {
|
for (const [form, link, heading] of [['play-content-rating', 'Start', 'Content rating'], ['play-target-audience', 'Manage', 'Target audience and content']] as const) {
|
||||||
|
|
@ -466,7 +477,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
expect(await page.getByRole('heading', { level: 1 }).textContent()).toBe(heading);
|
expect(await page.getByRole('heading', { level: 1 }).textContent()).toBe(heading);
|
||||||
await page.close();
|
await page.close();
|
||||||
}
|
}
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('navClick refuses a Start button, Start rollout, Save and Publish even when pointed at them', async () => {
|
test('navClick refuses a Start button, Start rollout, Save and Publish even when pointed at them', async () => {
|
||||||
const page = await open('play-app-content.html');
|
const page = await open('play-app-content.html');
|
||||||
|
|
@ -478,7 +489,7 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
expect((await navClick(page.getByRole('button', { name: 'Publish' }))).clicked).toBe(false);
|
expect((await navClick(page.getByRole('button', { name: 'Publish' }))).clicked).toBe(false);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('already on the form: nothing is clicked', async () => {
|
test('already on the form: nothing is clicked', async () => {
|
||||||
const page = await open('play-content-rating.html');
|
const page = await open('play-content-rating.html');
|
||||||
|
|
@ -486,14 +497,14 @@ describe.skipIf(!browser)('navigation (headless, modeled pages)', () => {
|
||||||
expect(r).toMatchObject({ ok: true, steps: ['already open'] });
|
expect(r).toMatchObject({ ok: true, steps: ['already open'] });
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---- sign-in during navigation, watching after the fallback, the session kept across relaunches ----
|
// ---- sign-in during navigation, watching after the fallback, the session kept across relaunches ----
|
||||||
|
|
||||||
/** A browser context whose console hosts (appstoreconnect / idmsa / play.google.com) are served from the fixtures. */
|
/** A browser context whose console hosts (appstoreconnect / idmsa / play.google.com) are served from the fixtures. */
|
||||||
async function consoleBrowser(map: (u: URL, cookie: string) => string | null): Promise<ConsoleBrowser> {
|
async function consoleBrowser(map: (u: URL, cookie: string) => string | null): Promise<ConsoleBrowser> {
|
||||||
const ctx = await browser.newContext();
|
const ctx = scope.track(await browser.newContext());
|
||||||
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, async (route: any) => {
|
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, async (route: any) => {
|
||||||
const u = new URL(route.request().url());
|
const u = new URL(route.request().url());
|
||||||
const cookie: string = (await route.request().headerValue('cookie')) ?? '';
|
const cookie: string = (await route.request().headerValue('cookie')) ?? '';
|
||||||
|
|
@ -506,22 +517,25 @@ async function consoleBrowser(map: (u: URL, cookie: string) => string | null): P
|
||||||
const done = new Promise<void>(r => ctx.on('close', () => { closed = true; r(); }));
|
const done = new Promise<void>(r => ctx.on('close', () => { closed = true; r(); }));
|
||||||
return { mode: 'profile', context: ctx, page, pages: () => ctx.pages(), closed: done, isClosed: () => closed, close: () => ctx.close(), cleanup: () => {} };
|
return { mode: 'profile', context: ctx, page, pages: () => ctx.pages(), closed: done, isClosed: () => closed, close: () => ctx.close(), cleanup: () => {} };
|
||||||
}
|
}
|
||||||
const until = async (what: string, fn: () => boolean | Promise<boolean>, ms = 20_000, said?: string[]) => {
|
const tmpDirs: string[] = [];
|
||||||
const end = Date.now() + ms;
|
afterAll(() => { for (const d of tmpDirs) rmSync(d, { recursive: true, force: true }); });
|
||||||
while (Date.now() < end) { if (await fn()) return; await Bun.sleep(50); }
|
const tmpAccounts = () => { const d = mkdtempSync(join(tmpdir(), 'storebound-accounts-')); tmpDirs.push(d); return join(d, 'console-accounts.json'); };
|
||||||
throw new Error(`timed out waiting for: ${what}${said ? `\n${said.join("\n")}` : ""}`);
|
/**
|
||||||
};
|
* The engine's timings scaled down for tests (production: tick 1 s, 20 s per navigation step, 10 min for a sign-in).
|
||||||
const tmpAccounts = () => join(mkdtempSync(join(tmpdir(), 'storebound-accounts-')), 'console-accounts.json');
|
* navTimeoutMs is both how long a step that IS there may take to show up (headroom for a loaded machine) and what a
|
||||||
const fast = (said: string[]) => ({ say: (m: string) => { said.push(m); }, tickMs: 100, navTimeoutMs: 1500, signInWaitMs: 30_000, accountsFile: tmpAccounts(), env: {} });
|
* step that is NOT there costs (the watching tests wait that out once), so it stays a few seconds, not FOUND_MS.
|
||||||
|
*/
|
||||||
|
const fast = (log: ReturnType<typeof logLines>) => ({ say: log.say, tickMs: 100, navTimeoutMs: 5000, signInWaitMs: 30_000, accountsFile: tmpAccounts(), env: {} });
|
||||||
|
const FILLED = (lines: string[]) => lines.some(m => /^New App: filled \d+/.test(m));
|
||||||
|
|
||||||
describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the real console hosts, routed locally)', () => {
|
describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the real console hosts, routed locally)', () => {
|
||||||
test('ASC /login with an idmsa frame and no password field: detected mid-navigation, never touched; after sign-in navigation restarts at step 1', async () => {
|
test('ASC /login with an idmsa frame and no password field: detected mid-navigation, never touched; after sign-in navigation restarts at step 1', async () => {
|
||||||
const b = await consoleBrowser((u, cookie) => u.hostname === 'idmsa.apple.com' ? 'idmsa-signin.html'
|
const b = await consoleBrowser((u, cookie) => u.hostname === 'idmsa.apple.com' ? 'idmsa-signin.html'
|
||||||
: u.hostname !== 'appstoreconnect.apple.com' ? null
|
: u.hostname !== 'appstoreconnect.apple.com' ? null
|
||||||
: u.pathname === '/login' ? 'asc-login.html' : u.pathname === '/apps' ? (cookie.includes('myacinfo=') ? 'asc-apps.html' : 'asc-shell.html') : null);
|
: u.pathname === '/login' ? 'asc-login.html' : u.pathname === '/apps' ? (cookie.includes('myacinfo=') ? 'asc-apps.html' : 'asc-shell.html') : null);
|
||||||
const said: string[] = [];
|
const log = logLines(), said = log.lines;
|
||||||
const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) });
|
const run = scope.run(fillSession(b, { form: 'apple-app-record', config, ...fast(log) }));
|
||||||
await until('the sign-in hint', () => said.some(m => m.startsWith('sign in in the browser window')));
|
await log.wait('the sign-in hint', l => l.some(m => m.startsWith('sign in in the browser window')));
|
||||||
expect(said.some(m => /^a sign-in page appeared at step/.test(m))).toBe(true); // the shell looked signed in, then /login
|
expect(said.some(m => /^a sign-in page appeared at step/.test(m))).toBe(true); // the shell looked signed in, then /login
|
||||||
expect(said.some(m => m.includes('Keep me signed in'))).toBe(true);
|
expect(said.some(m => m.includes('Keep me signed in'))).toBe(true);
|
||||||
expect(new URL(b.page.url()).pathname).toBe('/login');
|
expect(new URL(b.page.url()).pathname).toBe('/login');
|
||||||
|
|
@ -530,40 +544,40 @@ describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the
|
||||||
expect(await frame.evaluate(() => (window as any).__clicks)).toEqual([]); // nothing clicked on the sign-in form
|
expect(await frame.evaluate(() => (window as any).__clicks)).toEqual([]); // nothing clicked on the sign-in form
|
||||||
expect(await frame.locator('#acc').inputValue()).toBe(''); // nothing typed
|
expect(await frame.locator('#acc').inputValue()).toBe(''); // nothing typed
|
||||||
await b.page.evaluate(() => (window as any).__signIn()); // the owner signs in
|
await b.page.evaluate(() => (window as any).__signIn()); // the owner signs in
|
||||||
await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said);
|
await log.wait('the New App dialog filled', FILLED);
|
||||||
expect(said).toContain('signed in: opening the form again from step 1');
|
expect(said).toContain('signed in: opening the form again from step 1');
|
||||||
expect(await b.page.getByRole('textbox', { name: 'Name', exact: true }).inputValue()).toBe('Example Game');
|
expect(await b.page.getByRole('textbox', { name: 'Name', exact: true }).inputValue()).toBe('Example Game');
|
||||||
expect(await clicks(b.page)).toEqual(['+']); // never Create / Submit for Review
|
expect(await clicks(b.page)).toEqual(['+']); // never Create / Submit for Review
|
||||||
await b.context.close();
|
await b.context.close();
|
||||||
expect((await run).filled).toBeGreaterThan(0);
|
expect((await run).filled).toBeGreaterThan(0);
|
||||||
}, 40_000);
|
}, SLOW_TEST_MS);
|
||||||
|
|
||||||
test('after the printed steps storebound keeps watching: the owner opens Apps by hand, navigation resumes at step 2 and fills', async () => {
|
test('after the printed steps storebound keeps watching: the owner opens Apps by hand, navigation resumes at step 2 and fills', async () => {
|
||||||
const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('owner') ? 'asc-apps.html' : 'asc-apps-noplus.html') : null);
|
const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('owner') ? 'asc-apps.html' : 'asc-apps-noplus.html') : null);
|
||||||
const said: string[] = [];
|
const log = logLines(), said = log.lines;
|
||||||
const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) });
|
const run = scope.run(fillSession(b, { form: 'apple-app-record', config, ...fast(log) }));
|
||||||
await until('the printed steps', () => said.some(m => m.startsWith('open the form: Apps')));
|
await log.wait('the printed steps', l => l.some(m => m.startsWith('open the form: Apps')));
|
||||||
expect(await clicks(b.page)).toEqual([]);
|
expect(await clicks(b.page)).toEqual([]);
|
||||||
await b.page.evaluate(() => { location.href = '/apps?owner=1'; }); // the owner navigates
|
await b.page.evaluate(() => { location.href = '/apps?owner=1'; }); // the owner navigates
|
||||||
await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said);
|
await log.wait('the New App dialog filled', FILLED);
|
||||||
expect(said).toContain('the page changed: storebound opens the form from step 2/4');
|
expect(said).toContain('the page changed: storebound opens the form from step 2/4');
|
||||||
expect(await b.page.evaluate(() => (window as any).__navClicks())).toEqual(['Add Apps', 'New App']);
|
expect(await b.page.evaluate(() => (window as any).__navClicks())).toEqual(['Add Apps', 'New App']);
|
||||||
expect(await clicks(b.page)).toEqual(['+']);
|
expect(await clicks(b.page)).toEqual(['+']);
|
||||||
await b.context.close();
|
await b.context.close();
|
||||||
await run;
|
await run;
|
||||||
}, 40_000);
|
}, SLOW_TEST_MS);
|
||||||
|
|
||||||
test('after the printed steps: the owner opens the dialog by hand, storebound sees it and fills it', async () => {
|
test('after the printed steps: the owner opens the dialog by hand, storebound sees it and fills it', async () => {
|
||||||
const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('dialog') ? 'apple-app-record.html' : 'asc-apps-noplus.html') : null);
|
const b = await consoleBrowser(u => u.hostname === 'appstoreconnect.apple.com' && u.pathname === '/apps' ? (u.search.includes('dialog') ? 'apple-app-record.html' : 'asc-apps-noplus.html') : null);
|
||||||
const said: string[] = [];
|
const log = logLines();
|
||||||
const run = fillSession(b, { form: 'apple-app-record', config, ...fast(said) });
|
const run = scope.run(fillSession(b, { form: 'apple-app-record', config, ...fast(log) }));
|
||||||
await until('the printed steps', () => said.some(m => m.startsWith('open the form: Apps')));
|
await log.wait('the printed steps', l => l.some(m => m.startsWith('open the form: Apps')));
|
||||||
await b.page.evaluate(() => { location.href = '/apps?dialog=1'; });
|
await b.page.evaluate(() => { location.href = '/apps?dialog=1'; });
|
||||||
await until('the New App dialog filled', () => said.some(m => /^New App: filled \d+/.test(m)), 20_000, said);
|
await log.wait('the New App dialog filled', FILLED);
|
||||||
expect(await clicks(b.page)).toEqual([]); // not even + : the dialog was open
|
expect(await clicks(b.page)).toEqual([]); // not even + : the dialog was open
|
||||||
await b.context.close();
|
await b.context.close();
|
||||||
await run;
|
await run;
|
||||||
}, 40_000);
|
}, SLOW_TEST_MS);
|
||||||
|
|
||||||
test('resumeAt: the furthest step visible now, never the initial page load', async () => {
|
test('resumeAt: the furthest step visible now, never the initial page load', async () => {
|
||||||
const page = await open('asc-apps.html');
|
const page = await open('asc-apps.html');
|
||||||
|
|
@ -574,15 +588,17 @@ describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the
|
||||||
await page.goto(base + 'asc-apps-noplus.html');
|
await page.goto(base + 'asc-apps-noplus.html');
|
||||||
expect(await resumeAt(page, plan)).toBeNull();
|
expect(await resumeAt(page, plan)).toBeNull();
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
for (const store of ['apple', 'play'] as const) {
|
for (const store of ['apple', 'play'] as const) {
|
||||||
test(`${store}: a session cookie survives closing and relaunching storebound's own profile`, async () => {
|
test(`${store}: a session cookie survives closing and relaunching storebound's own profile`, async () => {
|
||||||
const dir = mkdtempSync(join(tmpdir(), `storebound-profile-${store}-`));
|
const dir = mkdtempSync(join(tmpdir(), `storebound-profile-${store}-`));
|
||||||
const root = join(import.meta.dir, '..');
|
const root = join(import.meta.dir, '..');
|
||||||
|
// its own Chromium (a persistent profile), launched twice: SLOW, and the launch timeout is raised like the shared one
|
||||||
|
const opts = { store, profileDir: dir, fresh: true, headless: true, say: () => {}, launchTimeoutMs: LAUNCH_TIMEOUT_MS };
|
||||||
|
let b: ConsoleBrowser | null = null;
|
||||||
try {
|
try {
|
||||||
const opts = { store, profileDir: dir, fresh: true, headless: true, say: () => {} };
|
b = await openConsoleBrowser(root, opts);
|
||||||
let b = await openConsoleBrowser(root, opts);
|
|
||||||
await b.page.goto(base + 'session-set');
|
await b.page.goto(base + 'session-set');
|
||||||
await b.close(); // graceful: Chromium writes its cookie store
|
await b.close(); // graceful: Chromium writes its cookie store
|
||||||
await b.closed;
|
await b.closed;
|
||||||
|
|
@ -592,8 +608,12 @@ describe.skipIf(!browser)('sign-in and watching (headless, modeled pages on the
|
||||||
expect(await b.page.textContent('#c')).toBe('kept');
|
expect(await b.page.textContent('#c')).toBe('kept');
|
||||||
await b.close();
|
await b.close();
|
||||||
await b.closed;
|
await b.closed;
|
||||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
} finally {
|
||||||
}, 60_000);
|
// a failed assertion must not leave this Chromium running into the next test
|
||||||
|
if (b && !b.isClosed()) await capped(b.context.close(), CLOSE_TIMEOUT_MS);
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}, 2 * LAUNCH_TIMEOUT_MS + SLOW_TEST_MS); // two Chromium launches (each capped) plus the test itself
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -633,7 +653,7 @@ describe('accounts (pure)', () => {
|
||||||
|
|
||||||
describe.skipIf(!browser)('accounts (headless, modeled pages)', () => {
|
describe.skipIf(!browser)('accounts (headless, modeled pages)', () => {
|
||||||
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
|
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
|
||||||
const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
|
const fresh = async () => { const p = await scope.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
|
||||||
const DENIED = ['Sign Out', 'Edit Profile', 'Create', 'Submit for Review', 'Create app', 'Create developer account', 'Save', 'Publish'];
|
const DENIED = ['Sign Out', 'Edit Profile', 'Create', 'Submit for Review', 'Create app', 'Create developer account', 'Save', 'Publish'];
|
||||||
|
|
||||||
test('App Store Connect, 3 teams, the bundle id in the 2nd: switched through the account menu, remembered, then picked first', async () => {
|
test('App Store Connect, 3 teams, the bundle id in the 2nd: switched through the account menu, remembered, then picked first', async () => {
|
||||||
|
|
@ -661,7 +681,7 @@ describe.skipIf(!browser)('accounts (headless, modeled pages)', () => {
|
||||||
expect(said2).toContain('team 1/3: Example Games Ltd');
|
expect(said2).toContain('team 1/3: Example Games Ltd');
|
||||||
for (const n of DENIED) expect(await navClicks(page)).not.toContain(n);
|
for (const n of DENIED) expect(await navClicks(page)).not.toContain(n);
|
||||||
await page.close();
|
await page.close();
|
||||||
}, 60_000);
|
}, SLOW_TEST_MS);
|
||||||
|
|
||||||
test('Play, one login in 5 developer accounts, the app in the 4th: found by package name, remembered, then opened directly', async () => {
|
test('Play, one login in 5 developer accounts, the app in the 4th: found by package name, remembered, then opened directly', async () => {
|
||||||
const file = tmpAccounts(), said: string[] = [];
|
const file = tmpAccounts(), said: string[] = [];
|
||||||
|
|
@ -688,7 +708,7 @@ describe.skipIf(!browser)('accounts (headless, modeled pages)', () => {
|
||||||
expect((await openAcross(page, { form: 'play-target-audience', config, say: m => { said3.push(m); }, bases: pb, navMs: 1500, file: tmpAccounts(), env: { STOREBOUND_PLAY_DEVELOPER_ID: '4444' } })).nav.ok).toBe(true);
|
expect((await openAcross(page, { form: 'play-target-audience', config, say: m => { said3.push(m); }, bases: pb, navMs: 1500, file: tmpAccounts(), env: { STOREBOUND_PLAY_DEVELOPER_ID: '4444' } })).nav.ok).toBe(true);
|
||||||
expect(said3.some(m => m.includes('developer accounts'))).toBe(false);
|
expect(said3.some(m => m.includes('developer accounts'))).toBe(false);
|
||||||
await page.close();
|
await page.close();
|
||||||
}, 60_000);
|
}, SLOW_TEST_MS);
|
||||||
|
|
||||||
test('Play: a package in none of the developer accounts is said plainly; nothing deny-listed clicked', async () => {
|
test('Play: a package in none of the developer accounts is said plainly; nothing deny-listed clicked', async () => {
|
||||||
const page = await fresh();
|
const page = await fresh();
|
||||||
|
|
@ -699,7 +719,7 @@ describe.skipIf(!browser)('accounts (headless, modeled pages)', () => {
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
for (const n of DENIED) expect(await navClicks(page)).not.toContain(n);
|
for (const n of DENIED) expect(await navClicks(page)).not.toContain(n);
|
||||||
await page.close();
|
await page.close();
|
||||||
}, 60_000);
|
}, SLOW_TEST_MS);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---- play-app-record: Play Console's Create app form (no API can create a Play app) ----
|
// ---- play-app-record: Play Console's Create app form (no API can create a Play app) ----
|
||||||
|
|
@ -768,9 +788,9 @@ describe('play-app-record (pure)', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe.skipIf(!browser)('play-app-record (headless, modeled pages)', () => {
|
describe.skipIf(!browser)('play-app-record (headless, modeled pages)', () => {
|
||||||
const quiet = { timeoutMs: 1500, say: () => {} };
|
const quiet = { timeoutMs: FOUND_MS, say: () => {} }; // every navigation here is expected to succeed
|
||||||
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
|
const navClicks = (page: any): Promise<string[]> => page.evaluate(() => (window as any).__navClicks());
|
||||||
const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
|
const fresh = async () => { const p = await scope.newPage(); await p.goto(base + 'blank.html'); await p.evaluate(() => sessionStorage.clear()); return p; };
|
||||||
const pb = (play: string) => ({ asc: base + 'asc', play: base + play });
|
const pb = (play: string) => ({ asc: base + 'asc', play: base + play });
|
||||||
const ans = () => pageAnswers('play-app-record');
|
const ans = () => pageAnswers('play-app-record');
|
||||||
const def = () => formDef('play-app-record', ans());
|
const def = () => formDef('play-app-record', ans());
|
||||||
|
|
@ -801,7 +821,7 @@ describe.skipIf(!browser)('play-app-record (headless, modeled pages)', () => {
|
||||||
expect(await safeClick(submit, opener)).toBe(false);
|
expect(await safeClick(submit, opener)).toBe(false);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
test('an agreement answer that says yes is still never ticked', async () => {
|
test('an agreement answer that says yes is still never ticked', async () => {
|
||||||
|
|
@ -812,7 +832,7 @@ describe.skipIf(!browser)('play-app-record (headless, modeled pages)', () => {
|
||||||
expect(await agreed(page)).toBe(0);
|
expect(await agreed(page)).toBe(0);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('a renamed field: partial fill, the missing one left to the owner; nothing ticked or submitted', async () => {
|
test('a renamed field: partial fill, the missing one left to the owner; nothing ticked or submitted', async () => {
|
||||||
const page = await open('play-create-app-renamed.html');
|
const page = await open('play-create-app-renamed.html');
|
||||||
|
|
@ -825,7 +845,7 @@ describe.skipIf(!browser)('play-app-record (headless, modeled pages)', () => {
|
||||||
expect(await agreed(page)).toBe(0);
|
expect(await agreed(page)).toBe(0);
|
||||||
expect(await clicks(page)).toEqual([]);
|
expect(await clicks(page)).toEqual([]);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('the opener inside a dialog, or on a page that is not the app list, is refused', async () => {
|
test('the opener inside a dialog, or on a page that is not the app list, is refused', async () => {
|
||||||
const page = await open('blank.html');
|
const page = await open('blank.html');
|
||||||
|
|
@ -836,12 +856,12 @@ describe.skipIf(!browser)('play-app-record (headless, modeled pages)', () => {
|
||||||
await page.setContent('<h1>All apps</h1><button type="button">Create app</button>');
|
await page.setContent('<h1>All apps</h1><button type="button">Create app</button>');
|
||||||
expect(await createAppHere(page.getByRole('button', { name: 'Create app' }), 'Create app', 'button')).toBe(true);
|
expect(await createAppHere(page.getByRole('button', { name: 'Create app' }), 'Create app', 'button')).toBe(true);
|
||||||
await page.close();
|
await page.close();
|
||||||
});
|
}, BROWSER_TEST_MS);
|
||||||
|
|
||||||
test('accounts: several and none picked -> stop and list; by play.developerAccount -> that one, remembered; by play.developerId -> directly', async () => {
|
test('accounts: several and none picked -> stop and list; by play.developerAccount -> that one, remembered; by play.developerId -> directly', async () => {
|
||||||
const go = async (c: ShipConfig, file: string, said: string[], env: Record<string, string> = {}) => {
|
const go = async (c: ShipConfig, file: string, said: string[], env: Record<string, string> = {}) => {
|
||||||
const page = await fresh();
|
const page = await fresh();
|
||||||
const r = await openAcross(page, { form: 'play-app-record', config: c, say: m => { said.push(m); }, bases: pb('playn'), navMs: 1500, file, env });
|
const r = await openAcross(page, { form: 'play-app-record', config: c, say: m => { said.push(m); }, bases: pb('playn'), navMs: FOUND_MS, file, env });
|
||||||
return { r, page };
|
return { r, page };
|
||||||
};
|
};
|
||||||
const file = tmpAccounts();
|
const file = tmpAccounts();
|
||||||
|
|
@ -878,19 +898,19 @@ describe.skipIf(!browser)('play-app-record (headless, modeled pages)', () => {
|
||||||
expect(said).toContain('creating the app in developer account 2222 (play.developerId)');
|
expect(said).toContain('creating the app in developer account 2222 (play.developerId)');
|
||||||
expect(said).toContain('opening the form, step 1/3: open the app list of the developer account');
|
expect(said).toContain('opening the form, step 1/3: open the app list of the developer account');
|
||||||
await page.close();
|
await page.close();
|
||||||
}, 60_000);
|
}, SLOW_TEST_MS);
|
||||||
|
|
||||||
test('fillSession: notes logged, form filled, the run ends without any submit', async () => {
|
test('fillSession: notes logged, form filled, the run ends without any submit', async () => {
|
||||||
const b = await consoleBrowser(u => (u.hostname !== 'play.google.com' ? null : u.pathname === '/console' || u.pathname.endsWith('/app-list') ? 'play-home.html' : u.pathname === '/play-create-app.html' ? 'play-create-app.html' : null));
|
const b = await consoleBrowser(u => (u.hostname !== 'play.google.com' ? null : u.pathname === '/console' || u.pathname.endsWith('/app-list') ? 'play-home.html' : u.pathname === '/play-create-app.html' ? 'play-create-app.html' : null));
|
||||||
const said: string[] = [];
|
const log = logLines(), said = log.lines;
|
||||||
const c = { ...config, play: { ...config.play!, developerId: '4444' } } as ShipConfig;
|
const c = { ...config, play: { ...config.play!, developerId: '4444' } } as ShipConfig;
|
||||||
const done = fillSession(b, { form: 'play-app-record', config: c, ...fast(said) });
|
const done = scope.run(fillSession(b, { form: 'play-app-record', config: c, ...fast(log) }));
|
||||||
await until('the Create app form filled', () => said.some(m => /^Create app: filled 4, check 2/.test(m)), 20_000, said);
|
await log.wait('the Create app form filled', l => l.some(m => /^Create app: filled 4, check 2/.test(m)));
|
||||||
expect(said.some(m => m.includes('first AAB upload'))).toBe(true);
|
expect(said.some(m => m.includes('first AAB upload'))).toBe(true);
|
||||||
expect(said.some(m => m.includes('never become paid'))).toBe(true);
|
expect(said.some(m => m.includes('never become paid'))).toBe(true);
|
||||||
await until('the final line', () => said.some(m => m.includes('press Create app yourself')), 5_000, said);
|
await log.wait('the final line', l => l.some(m => m.includes('press Create app yourself')));
|
||||||
expect(await clicks(b.page)).toEqual([]);
|
expect(await clicks(b.page)).toEqual([]);
|
||||||
await b.context.close();
|
await b.context.close();
|
||||||
expect((await done).filled).toBe(4);
|
expect((await done).filled).toBe(4);
|
||||||
}, 40_000);
|
}, SLOW_TEST_MS);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { chromeDataDir, CONSOLE_HOSTS, cookieApplies, copySession, devToolsEndpoint, filterCookies, NEVER_COPY, openConsoleBrowser, pickProfile, sessionFiles } from '../cli/console/session';
|
import { chromeDataDir, CONSOLE_HOSTS, cookieApplies, copySession, devToolsEndpoint, filterCookies, NEVER_COPY, openConsoleBrowser, pickProfile, sessionFiles } from '../cli/console/session';
|
||||||
|
import { capped, CLOSE_TIMEOUT_MS, LAUNCH_TIMEOUT_MS } from './helpers/browser';
|
||||||
|
|
||||||
const scratch = mkdtempSync(join(tmpdir(), 'sb-session-test-'));
|
const scratch = mkdtempSync(join(tmpdir(), 'sb-session-test-'));
|
||||||
afterAll(() => rmSync(scratch, { recursive: true, force: true }));
|
afterAll(() => rmSync(scratch, { recursive: true, force: true }));
|
||||||
|
|
@ -138,15 +139,19 @@ describe.skipIf(!hasChrome)('copy mode with real Chrome (throwaway profile, loca
|
||||||
} });
|
} });
|
||||||
const site = `http://127.0.0.1:${server.port}`, other = `http://localhost:${server.port}`;
|
const site = `http://127.0.0.1:${server.port}`, other = `http://localhost:${server.port}`;
|
||||||
const src = tmp('chrome-real');
|
const src = tmp('chrome-real');
|
||||||
|
// two real Chrome launches: SLOW; launch timeouts raised like the shared browser's (tests/helpers/browser.ts), and
|
||||||
|
// whatever is still open is closed in `finally`, so a failed assertion leaves no Chrome running
|
||||||
|
let seed: any = null, b: any = null;
|
||||||
try {
|
try {
|
||||||
const opts = { channel: 'chrome', headless: true, ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'] };
|
const opts = { channel: 'chrome', headless: true, timeout: LAUNCH_TIMEOUT_MS, ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'] };
|
||||||
const seed = await chromium.launchPersistentContext(src, opts);
|
seed = await chromium.launchPersistentContext(src, opts);
|
||||||
const p0 = seed.pages()[0] ?? await seed.newPage();
|
const p0 = seed.pages()[0] ?? await seed.newPage();
|
||||||
await p0.goto(`${site}/set`); await p0.goto(`${other}/set`);
|
await p0.goto(`${site}/set`); await p0.goto(`${other}/set`);
|
||||||
await seed.close();
|
await seed.close();
|
||||||
|
seed = null;
|
||||||
const said: string[] = [];
|
const said: string[] = [];
|
||||||
const b = await openConsoleBrowser(join(import.meta.dir, '..'), {
|
b = await openConsoleBrowser(join(import.meta.dir, '..'), {
|
||||||
store: 'apple', profileDir: tmp('own-profile'), say: m => said.push(m), chromeDir: src, hosts: ['127.0.0.1'], headless: true, platform: 'darwin',
|
store: 'apple', profileDir: tmp('own-profile'), say: m => said.push(m), chromeDir: src, hosts: ['127.0.0.1'], headless: true, platform: 'darwin', launchTimeoutMs: LAUNCH_TIMEOUT_MS,
|
||||||
});
|
});
|
||||||
expect(b.mode).toBe('copy');
|
expect(b.mode).toBe('copy');
|
||||||
expect(said.join('\n')).toContain('your Chrome sign-in');
|
expect(said.join('\n')).toContain('your Chrome sign-in');
|
||||||
|
|
@ -159,6 +164,10 @@ describe.skipIf(!hasChrome)('copy mode with real Chrome (throwaway profile, loca
|
||||||
await b.context.close();
|
await b.context.close();
|
||||||
await b.closed;
|
await b.closed;
|
||||||
expect(existsSync(b.tempDir!)).toBe(false);
|
expect(existsSync(b.tempDir!)).toBe(false);
|
||||||
} finally { server.stop(true); }
|
} finally {
|
||||||
}, 60_000);
|
if (seed) await capped(seed.close(), CLOSE_TIMEOUT_MS);
|
||||||
|
if (b && !b.isClosed()) { await capped(b.context.close(), CLOSE_TIMEOUT_MS); b.cleanup(); }
|
||||||
|
server.stop(true);
|
||||||
|
}
|
||||||
|
}, 2 * LAUNCH_TIMEOUT_MS); // bounded by the two launches; ~3 s on an idle machine
|
||||||
});
|
});
|
||||||
|
|
|
||||||
25
tests/fixtures/aso/ads-keyword-suggestions.json
vendored
Normal file
25
tests/fixtures/aso/ads-keyword-suggestions.json
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
{
|
||||||
|
"result": [
|
||||||
|
{
|
||||||
|
"text": "grocery list",
|
||||||
|
"popularity": 78
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "packing",
|
||||||
|
"popularity": 41
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "shopping",
|
||||||
|
"popularity": 64
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "meal planner",
|
||||||
|
"popularity": 55
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": {
|
||||||
|
"offset": 0,
|
||||||
|
"pageSize": 200,
|
||||||
|
"totalCount": 4
|
||||||
|
}
|
||||||
|
}
|
||||||
119
tests/fixtures/aso/search-einkaufsliste-de.json
vendored
Normal file
119
tests/fixtures/aso/search-einkaufsliste-de.json
vendored
Normal file
|
|
@ -0,0 +1,119 @@
|
||||||
|
{
|
||||||
|
"resultCount": 2,
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000007?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Einkaufsliste Plus",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000906?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 3000,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000906,
|
||||||
|
"trackName": "Einkaufsliste Plus",
|
||||||
|
"genreIds": [
|
||||||
|
"6007"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Produktivität"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Productivity",
|
||||||
|
"primaryGenreId": 6007,
|
||||||
|
"releaseDate": "2014-01-01T07:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-07-01T07:00:00Z",
|
||||||
|
"sellerName": "Example Studio E",
|
||||||
|
"bundleId": "com.example.einkauf",
|
||||||
|
"artistId": 1000000007,
|
||||||
|
"artistName": "Example Studio E",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 3000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000008?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Einkaufsliste & Rezepte",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000907?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 800,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000907,
|
||||||
|
"trackName": "Einkaufsliste & Rezepte",
|
||||||
|
"genreIds": [
|
||||||
|
"6007",
|
||||||
|
"6023"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Produktivität",
|
||||||
|
"Essen und Trinken"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Productivity",
|
||||||
|
"primaryGenreId": 6007,
|
||||||
|
"releaseDate": "2019-01-01T07:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-06-01T07:00:00Z",
|
||||||
|
"sellerName": "Example Studio F",
|
||||||
|
"bundleId": "com.example.rezepte",
|
||||||
|
"artistId": 1000000008,
|
||||||
|
"artistName": "Example Studio F",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 800
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
343
tests/fixtures/aso/search-grocery-list-us.json
vendored
Normal file
343
tests/fixtures/aso/search-grocery-list-us.json
vendored
Normal file
|
|
@ -0,0 +1,343 @@
|
||||||
|
{
|
||||||
|
"resultCount": 6,
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000001?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Basket: Grocery Shopping List",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000901?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 80000,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000901,
|
||||||
|
"trackName": "Basket: Grocery Shopping List",
|
||||||
|
"genreIds": [
|
||||||
|
"6007",
|
||||||
|
"6024"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Productivity",
|
||||||
|
"Shopping"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Productivity",
|
||||||
|
"primaryGenreId": 6007,
|
||||||
|
"releaseDate": "2012-05-11T07:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-09-11T16:20:00Z",
|
||||||
|
"sellerName": "Example Studio A",
|
||||||
|
"bundleId": "com.example.basket",
|
||||||
|
"artistId": 1000000001,
|
||||||
|
"artistName": "Example Studio A",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 80000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000002?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Pantry Grocery Shopping List",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000902?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 52000,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000902,
|
||||||
|
"trackName": "Pantry Grocery Shopping List",
|
||||||
|
"genreIds": [
|
||||||
|
"6024"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Shopping"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Shopping",
|
||||||
|
"primaryGenreId": 6024,
|
||||||
|
"releaseDate": "2009-08-14T07:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-09-15T10:00:00Z",
|
||||||
|
"sellerName": "Example Studio B",
|
||||||
|
"bundleId": "com.example.pantry",
|
||||||
|
"artistId": 1000000002,
|
||||||
|
"artistName": "Example Studio B",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 52000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000003?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Example Notes",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000101?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 50,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000101,
|
||||||
|
"trackName": "Example Notes",
|
||||||
|
"genreIds": [
|
||||||
|
"6007"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Productivity"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Productivity",
|
||||||
|
"primaryGenreId": 6007,
|
||||||
|
"releaseDate": "2025-01-02T08:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-10-01T08:00:00Z",
|
||||||
|
"sellerName": "Example",
|
||||||
|
"bundleId": "com.example.notes",
|
||||||
|
"artistId": 1000000003,
|
||||||
|
"artistName": "Example",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 50
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000004?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Cartful: Shared Grocery List",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000903?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 21000,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000903,
|
||||||
|
"trackName": "Cartful: Shared Grocery List",
|
||||||
|
"genreIds": [
|
||||||
|
"6007"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Productivity"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Productivity",
|
||||||
|
"primaryGenreId": 6007,
|
||||||
|
"releaseDate": "2012-07-21T07:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-05-28T07:00:00Z",
|
||||||
|
"sellerName": "Example Studio C",
|
||||||
|
"bundleId": "com.example.cartful",
|
||||||
|
"artistId": 1000000004,
|
||||||
|
"artistName": "Example Studio C",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 21000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000005?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Cartful Recipes",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000904?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 900,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000904,
|
||||||
|
"trackName": "Cartful Recipes",
|
||||||
|
"genreIds": [
|
||||||
|
"6023"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Food & Drink"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Food & Drink",
|
||||||
|
"primaryGenreId": 6023,
|
||||||
|
"releaseDate": "2018-03-03T07:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-02-01T07:00:00Z",
|
||||||
|
"sellerName": "Example Studio C",
|
||||||
|
"bundleId": "com.example.cartful.recipes",
|
||||||
|
"artistId": 1000000005,
|
||||||
|
"artistName": "Example Studio C",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 900
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"isGameCenterEnabled": false,
|
||||||
|
"features": [
|
||||||
|
"iosUniversal"
|
||||||
|
],
|
||||||
|
"advisories": [],
|
||||||
|
"supportedDevices": [
|
||||||
|
"iPhone15-iPhone15"
|
||||||
|
],
|
||||||
|
"kind": "software",
|
||||||
|
"artistViewUrl": "https://apps.apple.com/us/developer/id1000000006?uo=4",
|
||||||
|
"artworkUrl60": "https://example.com/art60.png",
|
||||||
|
"artworkUrl100": "https://example.com/art100.png",
|
||||||
|
"artworkUrl512": "https://example.com/art512.png",
|
||||||
|
"screenshotUrls": [],
|
||||||
|
"ipadScreenshotUrls": [],
|
||||||
|
"appletvScreenshotUrls": [],
|
||||||
|
"trackCensoredName": "Packing Planner: Travel Lists",
|
||||||
|
"trackViewUrl": "https://apps.apple.com/us/app/id6400000905?uo=4",
|
||||||
|
"trackContentRating": "4+",
|
||||||
|
"contentAdvisoryRating": "4+",
|
||||||
|
"averageUserRating": 4.6,
|
||||||
|
"averageUserRatingForCurrentVersion": 4.6,
|
||||||
|
"userRatingCountForCurrentVersion": 1200,
|
||||||
|
"languageCodesISO2A": [
|
||||||
|
"EN"
|
||||||
|
],
|
||||||
|
"fileSizeBytes": "52428800",
|
||||||
|
"sellerUrl": "https://example.com",
|
||||||
|
"formattedPrice": "Free",
|
||||||
|
"trackId": 6400000905,
|
||||||
|
"trackName": "Packing Planner: Travel Lists",
|
||||||
|
"genreIds": [
|
||||||
|
"6003"
|
||||||
|
],
|
||||||
|
"genres": [
|
||||||
|
"Travel"
|
||||||
|
],
|
||||||
|
"primaryGenreName": "Travel",
|
||||||
|
"primaryGenreId": 6003,
|
||||||
|
"releaseDate": "2016-06-09T07:00:00Z",
|
||||||
|
"currentVersionReleaseDate": "2026-08-29T07:00:00Z",
|
||||||
|
"sellerName": "Example Studio D",
|
||||||
|
"bundleId": "com.example.packing",
|
||||||
|
"artistId": 1000000006,
|
||||||
|
"artistName": "Example Studio D",
|
||||||
|
"isVppDeviceBasedLicensingEnabled": true,
|
||||||
|
"currency": "USD",
|
||||||
|
"description": "Placeholder description.",
|
||||||
|
"price": 0.0,
|
||||||
|
"releaseNotes": "Bug fixes.",
|
||||||
|
"minimumOsVersion": "16.0",
|
||||||
|
"version": "3.2.1",
|
||||||
|
"wrapperType": "software",
|
||||||
|
"userRatingCount": 1200
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
120
tests/helpers/browser.ts
Normal file
120
tests/helpers/browser.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
// Shared plumbing of the headless browser tests (tests/console-fill.test.ts, tests/site-overflow.test.ts,
|
||||||
|
// tests/console-session.test.ts). They used to time out now and then, mostly when the machine was busy:
|
||||||
|
// - the afterAll browser close (30 s, "(unnamed)" hook timeout). Cause: Google Chrome (the fallback when
|
||||||
|
// playwright's own Chromium is not downloaded) often hangs in its own shutdown after loading http pages and only
|
||||||
|
// exits when its 10 s teardown watchdog fires ("Teardown watchdog expired" in DEBUG=pw:browser); under load that
|
||||||
|
// passed 30 s. Measured on an idle machine: 10-30 s per close. The shared browser is a throwaway profile with nothing
|
||||||
|
// to flush, so it is launched as a browser server and KILLED at the end (milliseconds), not closed gracefully
|
||||||
|
// - Chromium's 30 s default launch timeout: one launch per file now, with an explicit, generous launch timeout; a
|
||||||
|
// launch that times out fails the file instead of quietly skipping it (a skip under load would hide lost
|
||||||
|
// coverage); only a browser that is not installed skips
|
||||||
|
// - every context of the run left open until afterAll, and a failed test's contexts and engine loops running into
|
||||||
|
// the next test: every context a test opens is tracked and closed right after it (afterEach)
|
||||||
|
// - polling sleeps in the waits for log lines: event-driven now (resolved on each new line)
|
||||||
|
// Hook timeouts are bounded by the numbers below (each close is capped), never open-ended.
|
||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
|
|
||||||
|
/** Launching Chromium: well above a cold start on a loaded machine (seconds), far below "hung". */
|
||||||
|
export const LAUNCH_TIMEOUT_MS = 60_000;
|
||||||
|
/** One context close, or an engine run ending after its window closed; longer is abandoned (and the browser killed). */
|
||||||
|
export const CLOSE_TIMEOUT_MS = 15_000;
|
||||||
|
/**
|
||||||
|
* Hook timeouts. afterEach: a test's contexts close in parallel, each capped at CLOSE_TIMEOUT_MS, then the engine runs
|
||||||
|
* it started, each capped at CLOSE_TIMEOUT_MS. afterAll: disconnect (capped) and kill the browser server.
|
||||||
|
*/
|
||||||
|
export const AFTER_EACH_MS = 2 * CLOSE_TIMEOUT_MS + 5_000;
|
||||||
|
export const AFTER_ALL_MS = CLOSE_TIMEOUT_MS + 5_000;
|
||||||
|
|
||||||
|
/** Waits for `p` (its error ignored) or `ms`, whichever is first: true when `p` settled in time. Never rejects. */
|
||||||
|
export async function capped(p: Promise<unknown>, ms: number): Promise<boolean> {
|
||||||
|
let t: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
const ok = await Promise.race([p.then(() => true, () => true), new Promise<boolean>(r => { t = setTimeout(() => r(false), ms); })]);
|
||||||
|
clearTimeout(t);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TestBrowser {
|
||||||
|
/** A connected Playwright Browser, or null when no Chromium is installed (then the browser tests skip). */
|
||||||
|
browser: any;
|
||||||
|
skipWhy: string;
|
||||||
|
/** afterAll: disconnects and kills the browser process (a throwaway profile: nothing to flush). Fast and bounded. */
|
||||||
|
close: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Launches headless Chromium once, as a browser server the tests connect to: playwright's own build, else Google Chrome
|
||||||
|
* (channel "chrome"). `browser` is null only when neither is installed; a launch that times out or crashes throws.
|
||||||
|
*/
|
||||||
|
export async function launchTestBrowser(pkg: 'playwright' | 'playwright-core'): Promise<TestBrowser> {
|
||||||
|
const none = (e: unknown): TestBrowser => ({ browser: null, skipWhy: firstLine(e), close: async () => {} });
|
||||||
|
let chromium: any;
|
||||||
|
try { chromium = (await import(pkg)).chromium; } catch (e) { return none(e); }
|
||||||
|
const opts = { headless: true, timeout: LAUNCH_TIMEOUT_MS };
|
||||||
|
let server: any;
|
||||||
|
try { server = await chromium.launchServer(opts); } catch (e) {
|
||||||
|
if (!notInstalled(e)) throw e;
|
||||||
|
try { server = await chromium.launchServer({ ...opts, channel: 'chrome' }); } catch (e2) {
|
||||||
|
if (!notInstalled(e2)) throw e2;
|
||||||
|
return none(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let browser: any;
|
||||||
|
try { browser = await chromium.connect(server.wsEndpoint(), { timeout: LAUNCH_TIMEOUT_MS }); } catch (e) { await server.kill(); throw e; }
|
||||||
|
return {
|
||||||
|
browser, skipWhy: '',
|
||||||
|
close: async () => {
|
||||||
|
await capped(browser.close(), CLOSE_TIMEOUT_MS); // a connected browser: closes its contexts and disconnects
|
||||||
|
await server.kill(); // SIGKILL, then playwright removes the temporary profile
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const firstLine = (e: unknown) => (e as Error).message.split('\n')[0]!;
|
||||||
|
/** Playwright's "no such browser" errors (bundled build not downloaded, Chrome channel not installed). */
|
||||||
|
const notInstalled = (e: unknown) => /Executable doesn't exist|distribution '[^']+' is not found|Failed to launch .* because executable/i.test((e as Error).message);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The contexts and engine runs of the current test. `newPage` opens a page in a fresh context (as browser.newPage
|
||||||
|
* does) and tracks it; `track` adds one opened elsewhere; `settle` (afterEach) closes them all and waits for the runs.
|
||||||
|
*/
|
||||||
|
export function testScope(browser: () => any) {
|
||||||
|
const contexts = new Set<any>();
|
||||||
|
const runs = new Set<Promise<unknown>>();
|
||||||
|
return {
|
||||||
|
async newPage(opts?: Record<string, unknown>): Promise<any> {
|
||||||
|
const ctx = await browser().newContext(opts);
|
||||||
|
contexts.add(ctx);
|
||||||
|
return ctx.newPage();
|
||||||
|
},
|
||||||
|
track<T>(ctx: T): T { contexts.add(ctx); return ctx; },
|
||||||
|
/** An engine run (fillSession ...) that ends when its context closes. */
|
||||||
|
run<T>(p: Promise<T>): Promise<T> { runs.add(p); return p; },
|
||||||
|
async settle(): Promise<void> {
|
||||||
|
const cs = [...contexts], rs = [...runs];
|
||||||
|
contexts.clear(); runs.clear();
|
||||||
|
await Promise.all(cs.map(c => capped(c.close(), CLOSE_TIMEOUT_MS)));
|
||||||
|
await Promise.all(rs.map(r => capped(r, CLOSE_TIMEOUT_MS)));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The log lines of an engine run (`say`), with event-driven waits: `wait` resolves on the line that makes `pred`
|
||||||
|
* true (checked on every new line, no polling) and fails after `ms` with every line seen so far.
|
||||||
|
*/
|
||||||
|
export function logLines() {
|
||||||
|
const lines: string[] = [];
|
||||||
|
const waiters = new Set<() => void>();
|
||||||
|
return {
|
||||||
|
lines,
|
||||||
|
say: (m: string) => { lines.push(m); for (const w of [...waiters]) w(); },
|
||||||
|
wait(what: string, pred: (lines: string[]) => boolean, ms = 30_000): Promise<void> {
|
||||||
|
if (pred(lines)) return Promise.resolve();
|
||||||
|
return new Promise<void>((resolve, reject) => {
|
||||||
|
const check = () => { if (pred(lines)) { done(); resolve(); } };
|
||||||
|
const t = setTimeout(() => { done(); reject(new Error(`timed out after ${ms} ms waiting for: ${what}\n${lines.join('\n')}`)); }, ms);
|
||||||
|
const done = () => { clearTimeout(t); waiters.delete(check); };
|
||||||
|
waiters.add(check);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -57,6 +57,17 @@ const LISTS: Record<string, { type: string; one?: boolean }> = {
|
||||||
'inAppPurchases/versions': { type: 'inAppPurchaseVersions' },
|
'inAppPurchases/versions': { type: 'inAppPurchaseVersions' },
|
||||||
'subscriptions/versions': { type: 'subscriptionVersions' },
|
'subscriptions/versions': { type: 'subscriptionVersions' },
|
||||||
'subscriptionGroups/versions': { type: 'subscriptionGroupVersions' },
|
'subscriptionGroups/versions': { type: 'subscriptionGroupVersions' },
|
||||||
|
'appStoreVersions/build': { type: 'builds', one: true },
|
||||||
|
'apps/appInfos': { type: 'appInfos' },
|
||||||
|
'appInfos/appInfoLocalizations': { type: 'appInfoLocalizations' },
|
||||||
|
'appInfos/ageRatingDeclaration': { type: 'ageRatingDeclarations', one: true },
|
||||||
|
'apps/appPriceSchedule': { type: 'appPriceSchedules', one: true },
|
||||||
|
'apps/appPricePoints': { type: 'appPricePoints' },
|
||||||
|
'apps/appAvailabilityV2': { type: 'appAvailabilities', one: true },
|
||||||
|
'appAvailabilities/territoryAvailabilities': { type: 'territoryAvailabilities' },
|
||||||
|
'apps/promotedPurchases': { type: 'promotedPurchases' },
|
||||||
|
'subscriptions/winBackOffers': { type: 'winBackOffers' },
|
||||||
|
'betaGroups/betaTesters': { type: 'betaTesters' },
|
||||||
};
|
};
|
||||||
/** Stores refuse a second resource with the same key (409 ENTITY_ERROR ... already exists). */
|
/** Stores refuse a second resource with the same key (409 ENTITY_ERROR ... already exists). */
|
||||||
const UNIQUE: Record<string, (r: R) => string> = {
|
const UNIQUE: Record<string, (r: R) => string> = {
|
||||||
|
|
@ -76,6 +87,12 @@ const UNIQUE: Record<string, (r: R) => string> = {
|
||||||
reviewSubmissions: r => `${r.rels.app}|${r.attributes.state}`,
|
reviewSubmissions: r => `${r.rels.app}|${r.attributes.state}`,
|
||||||
appStoreVersionPhasedReleases: r => String(r.rels.appStoreVersion),
|
appStoreVersionPhasedReleases: r => String(r.rels.appStoreVersion),
|
||||||
bundleIds: r => String(r.attributes.identifier),
|
bundleIds: r => String(r.attributes.identifier),
|
||||||
|
appStoreVersions: r => `${r.rels.app}|${r.attributes.platform}|${r.attributes.versionString}`,
|
||||||
|
appInfoLocalizations: r => `${r.rels.appInfo}|${r.attributes.locale}`,
|
||||||
|
appStoreVersionLocalizations: r => `${r.rels.appStoreVersion}|${r.attributes.locale}`,
|
||||||
|
promotedPurchases: r => String(r.rels.inAppPurchaseV2 ?? r.rels.subscription),
|
||||||
|
winBackOffers: r => `${r.rels.subscription}|${r.attributes.offerId}`,
|
||||||
|
betaTesters: r => String(r.attributes.email).toLowerCase(),
|
||||||
};
|
};
|
||||||
const ASSETS = /Screenshots$|^appPreviews$|^appScreenshots$/;
|
const ASSETS = /Screenshots$|^appPreviews$|^appScreenshots$/;
|
||||||
/** Attributes a new resource of a type starts with. */
|
/** Attributes a new resource of a type starts with. */
|
||||||
|
|
@ -83,6 +100,7 @@ const DEFAULTS: Record<string, Record<string, unknown>> = {
|
||||||
inAppPurchases: { state: 'MISSING_METADATA' }, subscriptions: { state: 'MISSING_METADATA' }, reviewSubmissions: { state: 'READY_FOR_REVIEW' },
|
inAppPurchases: { state: 'MISSING_METADATA' }, subscriptions: { state: 'MISSING_METADATA' }, reviewSubmissions: { state: 'READY_FOR_REVIEW' },
|
||||||
appCustomProductPageVersions: { state: 'PREPARE_FOR_SUBMISSION' }, devices: { status: 'ENABLED', deviceClass: 'IPHONE' },
|
appCustomProductPageVersions: { state: 'PREPARE_FOR_SUBMISSION' }, devices: { status: 'ENABLED', deviceClass: 'IPHONE' },
|
||||||
appStoreVersionPhasedReleases: { phasedReleaseState: 'INACTIVE' }, appEvents: { eventState: 'DRAFT' }, appStoreVersionExperiments: { state: 'PREPARE_FOR_SUBMISSION' },
|
appStoreVersionPhasedReleases: { phasedReleaseState: 'INACTIVE' }, appEvents: { eventState: 'DRAFT' }, appStoreVersionExperiments: { state: 'PREPARE_FOR_SUBMISSION' },
|
||||||
|
appStoreVersions: { appVersionState: 'PREPARE_FOR_SUBMISSION' }, betaTesters: { state: 'NOT_INVITED' },
|
||||||
};
|
};
|
||||||
|
|
||||||
const singular = (t: string): string => t.replace(/s$/, '');
|
const singular = (t: string): string => t.replace(/s$/, '');
|
||||||
|
|
@ -144,6 +162,8 @@ export class FakeAsc {
|
||||||
main.attributes.uploadOperations = [{ method: 'PUT', url: `${UPLOAD_HOST}${main.id}`, offset: 0, length: Number(d.attributes.fileSize ?? 0), requestHeaders: [{ name: 'Content-Type', value: 'image/png' }] }];
|
main.attributes.uploadOperations = [{ method: 'PUT', url: `${UPLOAD_HOST}${main.id}`, offset: 0, length: Number(d.attributes.fileSize ?? 0), requestHeaders: [{ name: 'Content-Type', value: 'image/png' }] }];
|
||||||
main.attributes.assetDeliveryState = { state: 'AWAITING_UPLOAD' };
|
main.attributes.assetDeliveryState = { state: 'AWAITING_UPLOAD' };
|
||||||
}
|
}
|
||||||
|
// a tester belongs to the app of its groups (GET /v1/betaTesters?filter[apps]=)
|
||||||
|
if (d.type === 'betaTesters') { const g = [main.rels.betaGroups].flat()[0]; const app = g ? this.res.get(String(g))?.rels.app : undefined; if (app) main.rels.app = app; }
|
||||||
const r = this.put(main);
|
const r = this.put(main);
|
||||||
if (this.lag[d.type]) r.hiddenReads = this.lag[d.type];
|
if (this.lag[d.type]) r.hiddenReads = this.lag[d.type];
|
||||||
for (const inc of body.included ?? []) {
|
for (const inc of body.included ?? []) {
|
||||||
|
|
@ -202,15 +222,28 @@ export class FakeAsc {
|
||||||
}
|
}
|
||||||
if (method === 'PATCH') {
|
if (method === 'PATCH') {
|
||||||
if (rel === 'relationships' && type && id) {
|
if (rel === 'relationships' && type && id) {
|
||||||
|
const data = (body as { data: { id: string } | { id: string }[] | null }).data;
|
||||||
|
if (data && !Array.isArray(data)) {
|
||||||
|
// a to-one relationship (the build of a version): the target points back at the patched resource
|
||||||
|
for (const r of this.children(id, this.res.get(data.id)?.type ?? '')) delete r.rels[singular(type)];
|
||||||
|
const t = this.res.get(data.id);
|
||||||
|
if (t) t.rels[singular(type)] = id;
|
||||||
|
return new Response(null, { status: 204 });
|
||||||
|
}
|
||||||
// order of a screenshot / preview set
|
// order of a screenshot / preview set
|
||||||
const ids = ((body as { data: { id: string }[] }).data ?? []).map(d => d.id);
|
const ids = ((data ?? []) as { id: string }[]).map(d => d.id);
|
||||||
const base = Math.min(...ids.map(i => this.res.get(i)?.order ?? 0));
|
const base = Math.min(...ids.map(i => this.res.get(i)?.order ?? 0));
|
||||||
ids.forEach((i, k) => { const r = this.res.get(i); if (r) r.order = base + k; });
|
ids.forEach((i, k) => { const r = this.res.get(i); if (r) r.order = base + k; });
|
||||||
return new Response(null, { status: 204 });
|
return new Response(null, { status: 204 });
|
||||||
}
|
}
|
||||||
const self = id ? this.res.get(id) : undefined;
|
let self = id ? this.res.get(id) : undefined;
|
||||||
|
// the age rating declaration is addressed by its app info's id
|
||||||
|
if (self && type && self.type !== type) self = this.children(self.id, type)[0];
|
||||||
if (!self) return json({ errors: [{ status: '404' }] }, 404);
|
if (!self) return json({ errors: [{ status: '404' }] }, 404);
|
||||||
const attrs = (body as { data: { attributes?: Record<string, unknown> } }).data.attributes ?? {};
|
const attrs = (body as { data: { attributes?: Record<string, unknown> } }).data.attributes ?? {};
|
||||||
|
for (const [k, v] of Object.entries((body as { data: { relationships?: Record<string, { data: { id: string } | null }> } }).data.relationships ?? {})) {
|
||||||
|
if (v.data) self.rels[k] = v.data.id; else delete self.rels[k];
|
||||||
|
}
|
||||||
// inline creates (subscription prices, introductory offers) become children of the patched resource
|
// inline creates (subscription prices, introductory offers) become children of the patched resource
|
||||||
for (const inc of (body as { included?: { type: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data: { id: string } }> }[] }).included ?? [])
|
for (const inc of (body as { included?: { type: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data: { id: string } }> }[] }).included ?? [])
|
||||||
this.put({ type: inc.type, id: `${inc.type.slice(0, 8)}-${this.next}`, attributes: { ...(inc.attributes ?? {}) },
|
this.put({ type: inc.type, id: `${inc.type.slice(0, 8)}-${this.next}`, attributes: { ...(inc.attributes ?? {}) },
|
||||||
|
|
@ -244,6 +277,8 @@ export class FakePlay {
|
||||||
subs = new Map<string, Record<string, unknown>>();
|
subs = new Map<string, Record<string, unknown>>();
|
||||||
offers = new Map<string, Record<string, unknown>>();
|
offers = new Map<string, Record<string, unknown>>();
|
||||||
next = 1;
|
next = 1;
|
||||||
|
/** every Data safety CSV that was posted */
|
||||||
|
dataSafety: string[] = [];
|
||||||
/** versionCode the next bundle upload reports */
|
/** versionCode the next bundle upload reports */
|
||||||
bundleCode = 42;
|
bundleCode = 42;
|
||||||
|
|
||||||
|
|
@ -352,7 +387,7 @@ export class FakePlay {
|
||||||
if (m[4]) o.state = 'ACTIVE';
|
if (m[4]) o.state = 'ACTIVE';
|
||||||
return json(o);
|
return json(o);
|
||||||
}
|
}
|
||||||
if (method === 'POST' && p === '/dataSafety') return json({});
|
if (method === 'POST' && p === '/dataSafety') { this.dataSafety.push(String((body as { safetyLabels?: string }).safetyLabels ?? '')); return json({}); }
|
||||||
return err(599, 'UNKNOWN', `fake play: ${method} ${p}`);
|
return err(599, 'UNKNOWN', `fake play: ${method} ${p}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,16 @@ import { run as playSubscriptions } from '../cli/play/subscriptions';
|
||||||
import { run as playImages } from '../cli/play/images';
|
import { run as playImages } from '../cli/play/images';
|
||||||
import { run as playRollout } from '../cli/play/rollout';
|
import { run as playRollout } from '../cli/play/rollout';
|
||||||
import { run as playRelease } from '../cli/play/release';
|
import { run as playRelease } from '../cli/play/release';
|
||||||
|
import { run as appleListing } from '../cli/apple/listing';
|
||||||
|
import { run as appleAppinfo } from '../cli/apple/appinfo';
|
||||||
|
import { run as applePromoted } from '../cli/apple/promoted';
|
||||||
|
import { run as appleWinBack } from '../cli/apple/win-back';
|
||||||
|
import { run as applePreorder } from '../cli/apple/preorder';
|
||||||
|
import { run as playListing } from '../cli/play/listing';
|
||||||
|
import { run as playDataSafety } from '../cli/play/data-safety';
|
||||||
|
import { run as playUpload } from '../cli/play/upload';
|
||||||
|
import { run as prices } from '../cli/prices';
|
||||||
|
import { makeAab } from './build-fixtures';
|
||||||
import { ascEnv, BASE, capture, playEnv, project, restore } from './helpers/store-mock';
|
import { ascEnv, BASE, capture, playEnv, project, restore } from './helpers/store-mock';
|
||||||
import { installStores, type Stores, uninstallStores, writes } from './helpers/fake-stores';
|
import { installStores, type Stores, uninstallStores, writes } from './helpers/fake-stores';
|
||||||
|
|
||||||
|
|
@ -219,6 +229,185 @@ describe('Google Play: a second run writes nothing', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const APPLE_MD = '# App Store\n\n## en-US · English\n\n### subtitle\n```\nNotes that sync\n```\n\n### keywords\n```\nnotes,lists\n```\n\n### description\n```\nNotes for everyone.\n```\n\n### promotionalText\n```\nNow with lists.\n```\n\n### whatsNew\n```\nFaster sync.\n```\n';
|
||||||
|
|
||||||
|
/** An app with a released 1.0.0, an editable app info and a processed build 9 of 1.1.0. */
|
||||||
|
function appleListingStore(): void {
|
||||||
|
s.asc.put({ type: 'appStoreVersions', id: 'ver-old', attributes: { versionString: '1.0.0', appVersionState: 'READY_FOR_SALE', platform: 'IOS' }, rels: { app: APP } });
|
||||||
|
s.asc.put({ type: 'appInfos', id: 'info-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' }, rels: { app: APP } });
|
||||||
|
s.asc.put({ type: 'builds', id: 'b-9', attributes: { version: '9', processingState: 'VALID' }, rels: { app: APP } });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('listing, appinfo, data safety and the owner commands: a second run writes nothing', () => {
|
||||||
|
test('apple listing: version created (re-checked first), build attached, localizations created once; then nothing', async () => {
|
||||||
|
appleListingStore();
|
||||||
|
const p = project(CONFIG, { 'store/appstore.md': APPLE_MD });
|
||||||
|
const r = await twice(() => appleListing(p.ctx(['--version', '1.1.0', '--build', '9'])));
|
||||||
|
expect(r.first).toEqual(['POST /v1/appStoreVersions', expect.stringMatching(/^PATCH \/v1\/appStoreVersions\/.+\/relationships\/build$/), 'POST /v1/appInfoLocalizations', 'POST /v1/appStoreVersionLocalizations']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect([count('appStoreVersions'), count('appInfoLocalizations'), count('appStoreVersionLocalizations')]).toEqual([2, 1, 1]);
|
||||||
|
// a changed text: only that field of that localization is PATCHed, the build is not attached again
|
||||||
|
const q = project(CONFIG, { 'store/appstore.md': APPLE_MD.replace('Notes for everyone.', 'Notes for all.') });
|
||||||
|
const before = s.calls.length;
|
||||||
|
await capture(() => appleListing(q.ctx(['--version', '1.1.0', '--build', '9'])));
|
||||||
|
const w = writes(s.calls.slice(before));
|
||||||
|
expect(w.map(c => `${c.method} ${c.path.replace(/\/[^/]+$/, '/:id')}`)).toEqual(['PATCH /v1/appStoreVersionLocalizations/:id']);
|
||||||
|
expect(Object.keys((w[0]!.body as { data: { attributes: object } }).data.attributes)).toEqual(['description']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('apple listing: a lost answer on the version create is found by the re-check, not created twice', async () => {
|
||||||
|
appleListingStore();
|
||||||
|
const p = project(CONFIG, { 'store/appstore.md': APPLE_MD });
|
||||||
|
s.faults.push({ method: 'POST', match: /^\/v1\/appStoreVersions$/, when: 'after', status: 502 });
|
||||||
|
const r = await capture(() => appleListing(p.ctx(['--version', '1.1.0'])));
|
||||||
|
expect(r.exit).toBe(null);
|
||||||
|
expect(r.err).toContain('no clear answer');
|
||||||
|
expect(count('appStoreVersions')).toBe(2);
|
||||||
|
expect(s.calls.filter(c => c.method === 'POST' && c.path === '/v1/appStoreVersions')).toHaveLength(1);
|
||||||
|
expect(count('appStoreVersionLocalizations')).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('apple listing: a localization the list does not show yet answers 409; it is used and updated, not created twice', async () => {
|
||||||
|
appleListingStore();
|
||||||
|
s.asc.put({ type: 'appStoreVersions', id: 'ver-2', attributes: { versionString: '1.1.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS', copyright: `${new Date().getFullYear()} Example Notes`, releaseType: 'MANUAL' }, rels: { app: APP } });
|
||||||
|
s.asc.put({ type: 'appStoreVersionLocalizations', id: 'vloc-en', attributes: { locale: 'en-US', description: 'Old.' }, rels: { appStoreVersion: 'ver-2' }, hiddenReads: 1 } as never);
|
||||||
|
const p = project(CONFIG, { 'store/appstore.md': APPLE_MD });
|
||||||
|
const r = await capture(() => appleListing(p.ctx(['--version', '1.1.0'])));
|
||||||
|
expect(r.exit).toBe(null);
|
||||||
|
expect(r.out).toContain('already exists, using it');
|
||||||
|
expect(count('appStoreVersionLocalizations')).toBe(1);
|
||||||
|
expect(s.asc.res.get('vloc-en')!.attributes.description).toBe('Notes for everyone.');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('play listing: one committed edit with only what differs; the second run opens no write edit and commits nothing', async () => {
|
||||||
|
s.play.live.listings['de-DE'] = { language: 'de-DE', title: 'Notizen' };
|
||||||
|
const p = project(CONFIG, { 'store/listing.md': LISTING });
|
||||||
|
const r = await twice(() => playListing(p.ctx([])));
|
||||||
|
expect(r.first).toEqual(['PUT /androidpublisher/v3/applications/com.example.notes/edits/edit-2/details', 'PUT /androidpublisher/v3/applications/com.example.notes/edits/edit-2/listings/en-US',
|
||||||
|
'POST /androidpublisher/v3/applications/com.example.notes/edits/edit-2:commit']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect(s.play.committed).toHaveLength(1);
|
||||||
|
expect(s.play.edits.size).toBe(0);
|
||||||
|
expect(s.play.live.listings['de-DE']).toEqual({ language: 'de-DE', title: 'Notizen' }); // a language not in the file is left alone
|
||||||
|
});
|
||||||
|
|
||||||
|
test('play listing: the store reached the wanted state between plan and edit: the edit is deleted, not committed', async () => {
|
||||||
|
const p = project(CONFIG, { 'store/listing.md': LISTING });
|
||||||
|
// the plan sees an empty listing; right after it (before the write edit opens) another run makes it current
|
||||||
|
const orig = s.play.handle.bind(s.play);
|
||||||
|
let planned = false;
|
||||||
|
s.play.handle = (method, url, body) => {
|
||||||
|
if (method === 'DELETE' && /\/edits\/edit-1$/.test(url) && !planned) {
|
||||||
|
planned = true;
|
||||||
|
s.play.live.details = { defaultLanguage: 'en-US', contactEmail: 'support@example.com', contactWebsite: 'https://example.com' };
|
||||||
|
s.play.live.listings['en-US'] = { language: 'en-US', title: 'Example Notes', shortDescription: 'Notes.', fullDescription: 'Notes for everyone.' };
|
||||||
|
}
|
||||||
|
return orig(method, url, body);
|
||||||
|
};
|
||||||
|
const r = await capture(() => playListing(p.ctx([])));
|
||||||
|
expect(r.out).toContain('nothing committed');
|
||||||
|
expect(s.play.committed).toEqual([]);
|
||||||
|
expect(writes(s.calls)).toEqual([]);
|
||||||
|
expect(s.play.edits.size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('apple appinfo: categories, age rating, content rights, price and availability set once, then compared and left', async () => {
|
||||||
|
s.asc.put({ type: 'appInfos', id: 'info-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' }, rels: { app: APP } });
|
||||||
|
s.asc.put({ type: 'ageRatingDeclarations', id: 'age-1', attributes: {}, rels: { appInfo: 'info-1' } });
|
||||||
|
s.asc.put({ type: 'appPricePoints', id: 'app-pp-free', attributes: { customerPrice: '0.0' }, rels: { app: APP, territory: 'USA' } });
|
||||||
|
const cfg: ShipConfig = { ...CONFIG, apple: { ...CONFIG.apple!, info: { categories: { primary: 'PRODUCTIVITY' }, contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT', ageRating: { advertising: true } } as never } };
|
||||||
|
const p = project(cfg);
|
||||||
|
const r = await twice(() => appleAppinfo(p.ctx([])));
|
||||||
|
expect(r.first).toEqual(['PATCH /v1/appInfos/info-1', 'PATCH /v1/ageRatingDeclarations/info-1', `PATCH /v1/apps/${APP}`, 'POST /v1/appPriceSchedules', 'POST /v2/appAvailabilities']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect(s.asc.res.get('age-1')!.attributes.advertising).toBe(true);
|
||||||
|
// one answer changed in the config: only the age rating is PATCHed
|
||||||
|
const q = project({ ...cfg, apple: { ...cfg.apple!, info: { ...cfg.apple!.info!, ageRating: { advertising: true, contests: 'INFREQUENT_OR_MILD' } } as never } });
|
||||||
|
const before = s.calls.length;
|
||||||
|
await capture(() => appleAppinfo(q.ctx([])));
|
||||||
|
expect(writes(s.calls.slice(before)).map(c => `${c.method} ${c.path}`)).toEqual(['PATCH /v1/ageRatingDeclarations/info-1']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('play data-safety: the same CSV is not sent again (hash in .storebound/); a changed one or --force is', async () => {
|
||||||
|
const ds = { collectsData: true, encryptedInTransit: true, deletionRequest: false, data: { PSL_DEVICE_ID: { shared: false, collect: ['analytics'] } } };
|
||||||
|
const p = project({ ...CONFIG, dataSafety: ds as never });
|
||||||
|
const r = await twice(() => playDataSafety(p.ctx([])));
|
||||||
|
expect(r.first).toEqual(['POST /androidpublisher/v3/applications/com.example.notes/dataSafety']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect(existsSync(join(p.root, '.storebound', 'data-safety.sha256'))).toBe(true);
|
||||||
|
let before = s.calls.length;
|
||||||
|
await capture(() => playDataSafety(p.ctx(['--force'])));
|
||||||
|
expect(writes(s.calls.slice(before))).toHaveLength(1);
|
||||||
|
const q = project({ ...CONFIG, dataSafety: { ...ds, data: { ...ds.data, PSL_EMAIL: { shared: false, collect: ['functionality'] } } } as never });
|
||||||
|
mkdirSync(join(q.root, '.storebound'), { recursive: true });
|
||||||
|
writeFileSync(join(q.root, '.storebound', 'data-safety.sha256'), readFileSync(join(p.root, '.storebound', 'data-safety.sha256')));
|
||||||
|
before = s.calls.length;
|
||||||
|
await capture(() => playDataSafety(q.ctx([])));
|
||||||
|
expect(writes(s.calls.slice(before))).toHaveLength(1);
|
||||||
|
expect(s.play.dataSafety).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('apple promoted: created and ordered once', async () => {
|
||||||
|
s.asc.put({ type: 'inAppPurchases', id: 'iap-pro', attributes: { productId: 'com.example.notes.pro', state: 'APPROVED' }, rels: { app: APP } });
|
||||||
|
s.asc.put({ type: 'inAppPurchases', id: 'iap-tip', attributes: { productId: 'com.example.notes.tip', state: 'APPROVED' }, rels: { app: APP } });
|
||||||
|
const p = project({ ...CONFIG, apple: { ...CONFIG.apple!, promoted: { products: ['com.example.notes.tip', 'com.example.notes.pro'] } } });
|
||||||
|
const r = await twice(() => applePromoted(p.ctx(['--yes'])));
|
||||||
|
expect(r.first.filter(x => x === 'POST /v1/promotedPurchases')).toHaveLength(2);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect(count('promotedPurchases')).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('apple win-back: the missing offer is created once', async () => {
|
||||||
|
const g = s.asc.put({ type: 'subscriptionGroups', id: 'grp-1', attributes: { referenceName: 'Pro' }, rels: { app: APP } });
|
||||||
|
s.asc.put({ type: 'subscriptions', id: 'sub-1', attributes: { productId: 'com.example.notes.monthly', state: 'APPROVED' }, rels: { subscriptionGroup: g.id } });
|
||||||
|
const cfg: ShipConfig = { ...CONFIG, subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [
|
||||||
|
{ id: 'com.example.notes.monthly', period: 'P1M', level: 1, usd: 4.99, listings: { en: { title: 'Monthly', description: 'Pro every month.' } },
|
||||||
|
winBack: [{ id: 'come-back', type: 'free', duration: 'P1M', paidMonths: 1, lapsedMonths: { min: 1, max: 6 }, start: '2099-01-01' }] },
|
||||||
|
] } as never] };
|
||||||
|
const p = project(cfg);
|
||||||
|
const r = await twice(() => appleWinBack(p.ctx(['--yes'])));
|
||||||
|
expect(r.first).toEqual(['POST /v1/winBackOffers']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect(count('winBackOffers')).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('apple preorder enable: territories set once; the same date again changes nothing', async () => {
|
||||||
|
const av = s.asc.put({ type: 'appAvailabilities', id: 'avail-1', attributes: { availableInNewTerritories: true }, rels: { app: APP } });
|
||||||
|
for (const t of ['USA', 'DEU']) s.asc.put({ type: 'territoryAvailabilities', id: `ta-${t}`, attributes: { available: true, contentStatuses: ['CANNOT_SELL'] }, rels: { appAvailability: av.id, territory: t } });
|
||||||
|
const p = project(CONFIG);
|
||||||
|
const date = new Date(Date.now() + 30 * 86400_000).toISOString().slice(0, 10);
|
||||||
|
const r = await twice(() => applePreorder(p.ctx(['enable', '--release-date', date, '--yes'])));
|
||||||
|
expect(r.first).toEqual(['PATCH /v1/territoryAvailabilities/ta-USA', 'PATCH /v1/territoryAvailabilities/ta-DEU']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('apple testflight testers: created in their groups once', async () => {
|
||||||
|
s.asc.put({ type: 'betaGroups', id: 'grp-friends', attributes: { name: 'Friends', isInternalGroup: false }, rels: { app: APP } });
|
||||||
|
const p = project(CONFIG, { '.storebound/testers.csv': 'email,first_name,groups\ntester1@example.com,Ex,Friends\ntester2@example.com,Am,Friends\n' });
|
||||||
|
const r = await twice(() => appleTestflight(p.ctx(['testers', '--yes'])));
|
||||||
|
expect(r.first).toEqual(['POST /v1/betaTesters', 'POST /v1/betaTesters']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect(count('betaTesters')).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('play upload: uploaded once; the same versionCode on the same track is not sent again', async () => {
|
||||||
|
const p = project(CONFIG, { 'store/listing.md': LISTING, 'build/android/app.aab': makeAab('com.example.notes', 42) });
|
||||||
|
const r = await twice(() => playUpload(p.ctx(['--yes'])));
|
||||||
|
expect(r.first).toEqual(['POST /upload/androidpublisher/v3/applications/com.example.notes/edits/edit-2/bundles', 'PUT /androidpublisher/v3/applications/com.example.notes/edits/edit-2/tracks/internal',
|
||||||
|
'POST /androidpublisher/v3/applications/com.example.notes/edits/edit-2:commit']);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
expect(s.play.committed).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('prices import (Play): changed regions written once, then the diff is empty', async () => {
|
||||||
|
const p = project({ ...CONFIG, products: [CONFIG.products![0]!] }, { 'store/prices.csv': 'product,store,region,currency,price\ncom.example.notes.pro,play,DE,EUR,3.49\n' });
|
||||||
|
await capture(() => playProducts(p.ctx([])));
|
||||||
|
const r = await twice(() => prices(p.ctx(['import', '--store', 'play', '--yes'])));
|
||||||
|
expect(r.first.some(x => x.startsWith('PATCH /androidpublisher/v3/applications/com.example.notes/onetimeproducts/'))).toBe(true);
|
||||||
|
expect(r.second).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('crash midway and unclear answers', () => {
|
describe('crash midway and unclear answers', () => {
|
||||||
test('screenshot set: an upload that dies on the 3rd file leaves a prefix; the re-run finishes it without duplicates, in order', async () => {
|
test('screenshot set: an upload that dies on the 3rd file leaves a prefix; the re-run finishes it without duplicates, in order', async () => {
|
||||||
const files: Record<string, Uint8Array> = {};
|
const files: Record<string, Uint8Array> = {};
|
||||||
|
|
|
||||||
|
|
@ -97,3 +97,12 @@ describe('listing commands', () => {
|
||||||
expect(sb(dir, 'listing', 'translate', '--to', 'xx').stderr.toString()).toContain('not a language of the config');
|
expect(sb(dir, 'listing', 'translate', '--to', 'xx').stderr.toString()).toContain('not a language of the config');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('listing check counts App Store keywords in UTF-8 bytes, the other fields in characters', () => {
|
||||||
|
const ru = 'игра,бег,прыжки,монеты,уровни,рекорд,аркада,быстро'; // 50 characters, 93 bytes
|
||||||
|
const kw = checkFields('apple', { keywords: ru, subtitle: 'Быстрая аркада' }).find(c => c.field === 'keywords')!;
|
||||||
|
expect(kw).toMatchObject({ chars: 93, unit: 'bytes', problems: [] });
|
||||||
|
expect(checkFields('apple', { keywords: ru + ',звук' }).find(c => c.field === 'keywords')!.problems).toContain('102 > 100 bytes');
|
||||||
|
expect(checkFields('apple', { subtitle: 'Быстрая аркада' })[0]).toMatchObject({ chars: 14, unit: 'chars' });
|
||||||
|
});
|
||||||
|
|
||||||
|
|
|
||||||
216
tests/local-fonts.test.ts
Normal file
216
tests/local-fonts.test.ts
Normal file
|
|
@ -0,0 +1,216 @@
|
||||||
|
// A game's own brand font as a local file in shots.fonts: validation, cmap coverage with listed + Noto fallbacks,
|
||||||
|
// @font-face served in place, `shots check` (local + listed fallback pass, license warning) and the content hash that
|
||||||
|
// invalidates the capture cache and stale renders. Fonts are tiny hand-made sfnt / WOFF2 files (cmap + name only).
|
||||||
|
import { afterAll, describe, expect, test } from 'bun:test';
|
||||||
|
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { brotliCompressSync } from 'node:zlib';
|
||||||
|
import { fontCodepoints, fontFamilyName } from '../cli/shots/cmap';
|
||||||
|
import { type FaceJob, fontIssues, fontsCss, fontUsage, type FontManifest, GlyphError, planFonts } from '../cli/shots/glyphs';
|
||||||
|
import { langTexts } from '../cli/shots/fonts';
|
||||||
|
import { faceFilePath, fontsRoute, loadLocalFont, localByFamily, localFontIssues, resolveShotFonts, staleLocalFonts } from '../cli/shots/local-fonts';
|
||||||
|
import { planWeb } from '../cli/shots/capture-web';
|
||||||
|
import { validateConfig } from '../cli/lib/config';
|
||||||
|
|
||||||
|
// ---- minimal font writer: an sfnt (or WOFF2) with a format 12 cmap and a name table ----
|
||||||
|
function cmapBytes(cps: number[]): Uint8Array {
|
||||||
|
const sorted = [...new Set(cps)].sort((a, b) => a - b);
|
||||||
|
const len = 16 + sorted.length * 12;
|
||||||
|
const b = new DataView(new ArrayBuffer(12 + len));
|
||||||
|
b.setUint16(2, 1); b.setUint16(4, 3); b.setUint16(6, 10); b.setUint32(8, 12);
|
||||||
|
b.setUint16(12, 12); b.setUint32(16, len); b.setUint32(24, sorted.length);
|
||||||
|
sorted.forEach((c, i) => { b.setUint32(28 + i * 12, c); b.setUint32(32 + i * 12, c); b.setUint32(36 + i * 12, i + 1); });
|
||||||
|
return new Uint8Array(b.buffer);
|
||||||
|
}
|
||||||
|
function nameBytes(family: string): Uint8Array {
|
||||||
|
const str = new Uint8Array(family.length * 2);
|
||||||
|
[...family].forEach((c, i) => { str[i * 2] = 0; str[i * 2 + 1] = c.charCodeAt(0); });
|
||||||
|
const b = new DataView(new ArrayBuffer(6 + 12 + str.length));
|
||||||
|
b.setUint16(2, 1); b.setUint16(4, 18);
|
||||||
|
b.setUint16(6, 3); b.setUint16(8, 1); b.setUint16(10, 0x409); b.setUint16(12, 1); b.setUint16(14, str.length); b.setUint16(16, 0);
|
||||||
|
new Uint8Array(b.buffer).set(str, 18);
|
||||||
|
return new Uint8Array(b.buffer);
|
||||||
|
}
|
||||||
|
function sfnt(cps: number[], family: string, sig = 0x00010000): Uint8Array {
|
||||||
|
const tables: [string, Uint8Array][] = [['cmap', cmapBytes(cps)], ['name', nameBytes(family)]];
|
||||||
|
let off = 12 + tables.length * 16;
|
||||||
|
const out = new Uint8Array(off + tables.reduce((n, [, t]) => n + t.length, 0));
|
||||||
|
const d = new DataView(out.buffer);
|
||||||
|
d.setUint32(0, sig); d.setUint16(4, tables.length);
|
||||||
|
tables.forEach(([tag, t], i) => {
|
||||||
|
out.set([...tag].map(c => c.charCodeAt(0)), 12 + i * 16);
|
||||||
|
d.setUint32(12 + i * 16 + 8, off); d.setUint32(12 + i * 16 + 12, t.length);
|
||||||
|
out.set(t, off); off += t.length;
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
function woff2(cps: number[], family: string): Uint8Array {
|
||||||
|
const cmap = cmapBytes(cps), name = nameBytes(family);
|
||||||
|
const stream = new Uint8Array(brotliCompressSync(Buffer.concat([cmap, name])));
|
||||||
|
const b128 = (n: number): number[] => { const b = [n & 0x7f]; n = Math.floor(n / 128); while (n) { b.unshift(0x80 | (n & 0x7f)); n = Math.floor(n / 128); } return b; };
|
||||||
|
const dir = [0, ...b128(cmap.length), 5, ...b128(name.length)]; // known-table indices: 0 = cmap, 5 = name
|
||||||
|
const out = new Uint8Array(48 + dir.length + stream.length);
|
||||||
|
const d = new DataView(out.buffer);
|
||||||
|
out.set([...'wOF2'].map(c => c.charCodeAt(0)), 0); d.setUint32(4, 0x00010000); d.setUint32(8, out.length);
|
||||||
|
d.setUint16(12, 2); d.setUint32(20, stream.length);
|
||||||
|
out.set(dir, 48); out.set(stream, 48 + dir.length);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const range = (a: number, b: number): number[] => Array.from({ length: b - a + 1 }, (_, i) => a + i);
|
||||||
|
const cpsOf = (s: string): number[] => [...s].map(c => c.codePointAt(0)!);
|
||||||
|
// "ER Display": ASCII, Latin-1 and Latin Extended-A without ą ę Ł ł; no Vietnamese (ơ ư, U+1EA0..)
|
||||||
|
const ER = [...range(0x20, 0x7e), ...range(0xa0, 0xff), ...range(0x100, 0x17f).filter(c => ![0x105, 0x119, 0x141, 0x142].includes(c))];
|
||||||
|
|
||||||
|
const root = mkdtempSync(join(tmpdir(), 'sb-localfonts-'));
|
||||||
|
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
||||||
|
const fontsDir = join(root, '.storebound', 'fonts');
|
||||||
|
mkdirSync(join(root, 'assets', 'fonts'), { recursive: true });
|
||||||
|
mkdirSync(fontsDir, { recursive: true });
|
||||||
|
writeFileSync(join(root, 'assets/fonts/er-display.woff2'), woff2(ER, 'ER Display'));
|
||||||
|
writeFileSync(join(root, 'assets/fonts/er-pl.ttf'), sfnt([0x105, 0x119, 0x141, 0x142], 'ER Polish'));
|
||||||
|
const resolve = (p: string): string => join(root, p);
|
||||||
|
|
||||||
|
describe('local font files: config and validation', () => {
|
||||||
|
test('a path reads the family from the name table (WOFF2 and TTF); the object form sets family, weight, license', () => {
|
||||||
|
expect(fontFamilyName(woff2(ER, 'ER Display'))).toBe('ER Display');
|
||||||
|
const a = loadLocalFont('assets/fonts/er-display.woff2', 'shots.fonts.title', resolve, root);
|
||||||
|
expect(a.family).toBe('ER Display');
|
||||||
|
expect(a.local).toMatchObject({ path: 'assets/fonts/er-display.woff2', format: 'woff2' });
|
||||||
|
expect(a.local!.hash).toMatch(/^[0-9a-f]{16}$/);
|
||||||
|
const b = loadLocalFont({ family: 'ER Pl', file: 'assets/fonts/er-pl.ttf', weight: 800, license: 'OFL-1.1' }, 'k', resolve, root);
|
||||||
|
expect(b).toMatchObject({ family: 'ER Pl', local: { format: 'truetype', weight: '800', license: 'OFL-1.1' } });
|
||||||
|
expect(fontCodepoints(readFileSync(join(root, 'assets/fonts/er-display.woff2'))).size).toBe(ER.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing file, wrong extension, not a font, mismatched format', () => {
|
||||||
|
writeFileSync(join(root, 'assets/fonts/bad.ttf'), new Uint8Array(64));
|
||||||
|
writeFileSync(join(root, 'assets/fonts/fake.ttf'), woff2(ER, 'X'));
|
||||||
|
expect(() => loadLocalFont('assets/fonts/nope.ttf', 'shots.fonts.title', resolve, root)).toThrow('shots.fonts.title: assets/fonts/nope.ttf not found');
|
||||||
|
expect(() => loadLocalFont({ file: 'assets/fonts/er.svg' }, 'k', resolve, root)).toThrow('not a font file (TTF, OTF, WOFF or WOFF2)');
|
||||||
|
expect(() => loadLocalFont('assets/fonts/bad.ttf', 'k', resolve, root)).toThrow('unknown signature');
|
||||||
|
expect(() => loadLocalFont('assets/fonts/fake.ttf', 'k', resolve, root)).toThrow('is WOFF2 inside, but named .ttf');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validateConfig: font entry shapes', () => {
|
||||||
|
const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en' }] };
|
||||||
|
const shots = (fonts: unknown) => ({ ...base, shots: { copy: 'c.json', frames: 'f', out: 'o', scenes: [{ id: 'a', palette: 'fire', frames: [{ src: 'a' }] }], fonts } });
|
||||||
|
expect(validateConfig(shots({ title: 'assets/er.woff2', body: 'Montserrat', fallback: [{ family: 'ER Pl', file: 'a/er-pl.ttf', license: 'OFL-1.1' }, 'Noto Sans Display'] }))).toEqual([]);
|
||||||
|
const errs = validateConfig(shots({ title: 'assets/er.svg', body: { family: 'B' }, fallback: [{ file: 'x.otf', style: 'oblique', weight: 'bold' }] }));
|
||||||
|
expect(errs).toEqual([
|
||||||
|
'shots.fonts.title: assets/er.svg: a font file must be TTF, OTF, WOFF or WOFF2',
|
||||||
|
'shots.fonts.body: a Google Fonts family, a font file path or { family, file, weight?, style?, license? }',
|
||||||
|
'shots.fonts.fallback[0].style: normal | italic',
|
||||||
|
'shots.fonts.fallback[0].weight: e.g. 400, 800 or "100 900"',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Copy: ER Display covers tr / de / fr titles; Polish needs ą ę Ł ł, Vietnamese needs ơ ư ạ ...
|
||||||
|
const COPY = {
|
||||||
|
tr: { s1: { title: ["Taş Devri'nden", 'İleri!'] as [string, string], sub: 'Kasabaları yağmala' } },
|
||||||
|
de: { s1: { title: ['Größer', 'schöner'] as [string, string] } },
|
||||||
|
pl: { s1: { title: ['Gęsi łąka', 'Łódź'] as [string, string], sub: 'Szybka gra' } },
|
||||||
|
vi: { s1: { title: ['Chiến đấu', 'Thế giới'] as [string, string], sub: 'Trận nhanh' } },
|
||||||
|
};
|
||||||
|
const NOTO: Record<string, (cp: number) => boolean> = {
|
||||||
|
Montserrat: () => true, // body: covers everything here
|
||||||
|
'Noto Sans Display': cp => cp < 0x250 || (cp >= 0x1ea0 && cp <= 0x1ef9),
|
||||||
|
};
|
||||||
|
/** Getter like `shots fonts`: local files read in place, Google families faked. */
|
||||||
|
function getter(asked: FaceJob[]): (job: FaceJob) => Promise<Set<number>> {
|
||||||
|
return async job => {
|
||||||
|
asked.push(job);
|
||||||
|
if (job.local) return fontCodepoints(readFileSync(join(root, job.local.path)));
|
||||||
|
const f = NOTO[job.family] ?? (() => false);
|
||||||
|
return new Set(cpsOf(job.chars).filter(f));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
async function plan(fallback: (string | { family?: string; file: string; license?: string })[] = [], asked: FaceJob[] = []): Promise<FontManifest> {
|
||||||
|
const sf = resolveShotFonts({ fonts: { title: 'assets/fonts/er-display.woff2', body: 'Montserrat', fallback } }, 'game', resolve, root);
|
||||||
|
return planFonts({ langs: langTexts(COPY, [], 'STAR DASH'), title: sf.title.family, body: sf.body.family, titleAxis: null, bodyAxis: 'wght@100..900',
|
||||||
|
fallbackTitleAxis: 'wght@800', chosen: sf.fallback.map(f => f.family), local: localByFamily([sf.title, sf.body, ...sf.fallback]) }, getter(asked));
|
||||||
|
}
|
||||||
|
const fb = (m: FontManifest, lang: string) => m.langs[lang]!.fallbacks.filter(f => f.role === 'title').map(f => `${f.family}:${[...f.chars].join(' ')}`);
|
||||||
|
|
||||||
|
describe('coverage of a local title font', () => {
|
||||||
|
test('pl / vi titles: the characters ER Display lacks go to Noto Sans Display (automatic); tr / de need nothing', async () => {
|
||||||
|
const asked: FaceJob[] = [];
|
||||||
|
const m = await plan([], asked);
|
||||||
|
expect(fb(m, 'pl')).toEqual(['Noto Sans Display:ę ł ą Ł']);
|
||||||
|
expect(fb(m, 'vi')).toEqual(['Noto Sans Display:ế ấ ớ']);
|
||||||
|
for (const l of ['tr', 'de']) expect(m.langs[l]!.fallbacks).toEqual([]);
|
||||||
|
expect(m.faces['ER Display']).toMatchObject({ family: 'ER Display', kind: 'title', chosen: true, file: 'local/er-display.woff2', local: { path: 'assets/fonts/er-display.woff2', format: 'woff2' } });
|
||||||
|
expect(m.faces['Store fb noto-sans-display title']!.chosen).toBe(false);
|
||||||
|
expect(asked.find(j => j.family === 'ER Display')!.local).toBeDefined(); // read in place, not downloaded
|
||||||
|
});
|
||||||
|
|
||||||
|
test('listed fallbacks first (a local file), then Noto; chosen, so check passes', async () => {
|
||||||
|
const m = await plan([{ file: 'assets/fonts/er-pl.ttf', license: 'OFL-1.1' }, 'Noto Sans Display']);
|
||||||
|
expect(fb(m, 'pl')).toEqual(['ER Polish:ę ł ą Ł']);
|
||||||
|
expect(fb(m, 'vi')).toEqual(['Noto Sans Display:ế ấ ớ']);
|
||||||
|
expect(m.langs.pl!.title).toEqual(['ER Display', 'Store fb er-polish title']);
|
||||||
|
expect(m.faces['Store fb er-polish title']).toMatchObject({ kind: 'fallback', chosen: true, file: 'local/er-polish.ttf', local: { license: 'OFL-1.1' } });
|
||||||
|
expect(m.faces['Store fb noto-sans-display title']!.chosen).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nothing covers it: GlyphError names the local font and the fallbacks tried', async () => {
|
||||||
|
const err = await planFonts({ langs: langTexts({ pl: { s1: { title: ['ą', 'x'] } } }, [], ''), title: 'ER Display', body: 'Montserrat', titleAxis: null, bodyAxis: null,
|
||||||
|
fallbackTitleAxis: null, local: localByFamily([loadLocalFont('assets/fonts/er-display.woff2', 'k', resolve, root)]) },
|
||||||
|
async job => job.local ? fontCodepoints(readFileSync(join(root, job.local.path))) : new Set()).catch(e => e);
|
||||||
|
expect(err).toBeInstanceOf(GlyphError);
|
||||||
|
expect(err.message).toContain('pl (title): "ą" U+0105; tried ER Display, Noto Sans Display, Noto Sans');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('render and check with a local font', () => {
|
||||||
|
test('fonts.css: @font-face for the local file, served in place at /fonts/local/... with its hash', async () => {
|
||||||
|
const m = await plan([{ file: 'assets/fonts/er-pl.ttf', license: 'OFL-1.1' }]);
|
||||||
|
const css = fontsCss(m);
|
||||||
|
const h = m.faces['ER Display']!.local!.hash;
|
||||||
|
expect(css).toContain(`@font-face { font-family: 'ER Display'; font-weight: 100 900; font-style: normal; font-synthesis: none; src: url(local/er-display.woff2?v=${h}) format('woff2'); }`);
|
||||||
|
expect(css).toContain("src: url(local/er-polish.ttf?v=");
|
||||||
|
expect(css).toContain("format('truetype')");
|
||||||
|
expect(css).toContain('/* ER Polish: local file assets/fonts/er-pl.ttf (license: OFL-1.1) */');
|
||||||
|
expect(fontsRoute(`local/er-display.woff2?v=${h}`, fontsDir, root, m)).toBe(join(root, 'assets/fonts/er-display.woff2'));
|
||||||
|
expect(fontsRoute('local/other.ttf', fontsDir, root, m)).toBeNull();
|
||||||
|
expect(fontsRoute('local/../../x.ttf', fontsDir, root, m)).toBeNull();
|
||||||
|
expect(fontsRoute('fb-noto-sans-display-title.woff2', fontsDir, root, m)).toBe(join(fontsDir, 'fb-noto-sans-display-title.woff2'));
|
||||||
|
expect(faceFilePath(fontsDir, root, m.faces['ER Display']!)).toBe(join(root, 'assets/fonts/er-display.woff2'));
|
||||||
|
// nothing is copied into .storebound/fonts
|
||||||
|
expect(Object.values(m.faces).filter(f => f.local).every(f => f.file.startsWith('local/'))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('check: the local font and the listed fallback are not fallbacks the config did not choose; an automatic Noto is', async () => {
|
||||||
|
const m = await plan([{ file: 'assets/fonts/er-pl.ttf' }]);
|
||||||
|
const ok = fontUsage([
|
||||||
|
{ el: 'h1 span:1', text: 'Gęsi łąka', faces: { 'ER Display': 'Gsika', 'Store fb er-polish title': 'ęłą' } },
|
||||||
|
{ el: 'p.sub', text: 'Szybka gra', faces: { Montserrat: 'Szybkagr' } },
|
||||||
|
], m.faces);
|
||||||
|
expect(ok.used).toEqual({ 'ER Display': 5, 'ER Polish': 3, Montserrat: 8 });
|
||||||
|
expect(fontIssues(ok)).toEqual([]);
|
||||||
|
const bad = fontUsage([{ el: 'h1 span:1', text: 'Chiến', faces: { 'ER Display': 'Chin', 'Store fb noto-sans-display title': 'ế' } }], m.faces);
|
||||||
|
expect(fontIssues(bad).map(i => i.code)).toEqual(['font-fallback']);
|
||||||
|
// license note: warn for the local file without one
|
||||||
|
expect(localFontIssues(m).map(i => i.msg.split(' has')[0])).toEqual(['local font ER Display (assets/fonts/er-display.woff2)', 'local font ER Polish (assets/fonts/er-pl.ttf)']);
|
||||||
|
const licensed = await plan([{ file: 'assets/fonts/er-pl.ttf', license: 'proprietary' }]);
|
||||||
|
expect(localFontIssues(licensed).length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a changed font file changes the content hash: capture cache misses, render refuses the stale fonts.json', async () => {
|
||||||
|
const m1 = await plan();
|
||||||
|
const cap = { source: 'web' as const, baseUrl: 'http://x', shots: { a: { path: '/a' } } };
|
||||||
|
const dims = { phone: { w: 10, h: 20, dpr: 1, bar: 0 }, tablet: { w: 10, h: 20, dpr: 1, bar: 0 } };
|
||||||
|
const job = (m: FontManifest) => planWeb(cap, { langs: ['tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b', fonts: fontsCss(m) })[0]!.hash;
|
||||||
|
expect(staleLocalFonts(m1, root)).toEqual([]);
|
||||||
|
writeFileSync(join(root, 'assets/fonts/er-display.woff2'), woff2([...ER, 0x105], 'ER Display'));
|
||||||
|
try {
|
||||||
|
expect(staleLocalFonts(m1, root)).toEqual(['ER Display: assets/fonts/er-display.woff2 changed']);
|
||||||
|
const m2 = await plan();
|
||||||
|
expect(m2.faces['ER Display']!.local!.hash).not.toBe(m1.faces['ER Display']!.local!.hash);
|
||||||
|
expect(job(m2)).not.toBe(job(m1));
|
||||||
|
expect(fb(m2, 'pl')).toEqual(['Noto Sans Display:ę ł Ł']); // ą now in the font
|
||||||
|
} finally { writeFileSync(join(root, 'assets/fonts/er-display.woff2'), woff2(ER, 'ER Display')); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -470,3 +470,10 @@ describe('integration', () => {
|
||||||
expect(JSON_TOOLS.has('scan')).toBe(true);
|
expect(JSON_TOOLS.has('scan')).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('placeholder text: "todo" as a word or keyword is fine, TODO / FIXME markers and lorem ipsum are not', async () => {
|
||||||
|
const r = await scanVariant('clean', { 'store/appstore.md': s => s.replace(/(### keywords\n+```\n)/, '$1todo,tasks,') });
|
||||||
|
expect(r.findings.filter(f => f.rule === 'placeholder-text')).toEqual([]);
|
||||||
|
const bad = await scanVariant('clean', { 'store/appstore.md': s => s.replace(/(### keywords\n+```\n)/, '$1TODO,') });
|
||||||
|
expect(bad.findings.some(f => f.rule === 'placeholder-text')).toBe(true);
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,12 @@ function fakeRunner(reply: (argv: string[]) => { code?: number; out?: string; da
|
||||||
return { calls, run };
|
return { calls, run };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resolves once `cond` holds (the child was started), instead of a fixed sleep. */
|
||||||
|
async function until(cond: () => boolean, ms = 5000) {
|
||||||
|
const end = Date.now() + ms;
|
||||||
|
while (!cond()) { if (Date.now() > end) throw new Error('until: timed out'); await new Promise(r => setImmediate(r)); }
|
||||||
|
}
|
||||||
|
|
||||||
async function session(reply?: Parameters<typeof fakeRunner>[0], clock: () => number = Date.now) {
|
async function session(reply?: Parameters<typeof fakeRunner>[0], clock: () => number = Date.now) {
|
||||||
const sent: J[] = [];
|
const sent: J[] = [];
|
||||||
const f = fakeRunner(reply);
|
const f = fakeRunner(reply);
|
||||||
|
|
@ -195,10 +201,10 @@ describe('serve --stdio: session', () => {
|
||||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
test('cancellation answers -32800 and kills the child', async () => {
|
test('cancellation answers -32800 and kills the child', async () => {
|
||||||
const { s, call, nextId } = await session(() => ({ wait: new Promise(() => {}) }));
|
const { s, call, calls, nextId } = await session(() => ({ wait: new Promise(() => {}) }));
|
||||||
const id = nextId();
|
const id = nextId();
|
||||||
const pending = call('validate', { project: DEMO });
|
const pending = call('validate', { project: DEMO });
|
||||||
await Bun.sleep(5);
|
await until(() => calls.length > 0);
|
||||||
await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } });
|
await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } });
|
||||||
expect(errOf(await pending).code).toBe(ERR.cancelled);
|
expect(errOf(await pending).code).toBe(ERR.cancelled);
|
||||||
});
|
});
|
||||||
|
|
@ -223,7 +229,7 @@ describe('serve --stdio: session', () => {
|
||||||
// real run: waits for the owner (no timeout), the token answers the command's own question, a cancel stops it
|
// real run: waits for the owner (no timeout), the token answers the command's own question, a cancel stops it
|
||||||
const id = nextId();
|
const id = nextId();
|
||||||
const pending = call('console.fill', { ...p, dryRun: false, confirmToken: mint(SECRET, 'console.fill', p, { now }) });
|
const pending = call('console.fill', { ...p, dryRun: false, confirmToken: mint(SECRET, 'console.fill', p, { now }) });
|
||||||
await Bun.sleep(5);
|
await until(() => calls.length > n);
|
||||||
expect(calls.length).toBe(n + 1);
|
expect(calls.length).toBe(n + 1);
|
||||||
expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'apple-age-rating', '--json']);
|
expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'apple-age-rating', '--json']);
|
||||||
expect(calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBe('1');
|
expect(calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBe('1');
|
||||||
|
|
|
||||||
|
|
@ -1,28 +1,28 @@
|
||||||
// The site (site/index.html) never scrolls sideways: at every viewport width from 320 to 1440 px (10 px steps), in the
|
// The site (site/index.html) never scrolls sideways: at every viewport width from 320 to 1440 px (10 px steps), in the
|
||||||
// light and the dark theme, document.documentElement.scrollWidth stays within innerWidth. On a failure it names the
|
// light and the dark theme, document.documentElement.scrollWidth stays within innerWidth. On a failure it names the
|
||||||
// elements whose right edge passes the viewport outside any scroll container (pseudo-elements show as their owner).
|
// elements whose right edge passes the viewport outside any scroll container (pseudo-elements show as their owner).
|
||||||
// Uses the bundled playwright-core with its Chromium (or Google Chrome); skips when neither can launch.
|
// Uses the bundled playwright-core with its Chromium (or Google Chrome); skips when neither is installed (a launch that
|
||||||
import { afterAll, describe, expect, test } from 'bun:test';
|
// times out on a busy machine fails instead). One launch, the context closed right after each test, capped closes
|
||||||
|
// (tests/helpers/browser.ts). SLOW on purpose: 113 widths x 2 themes, each a resize and a layout read.
|
||||||
|
import { afterAll, afterEach, describe, expect, test } from 'bun:test';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
import { AFTER_ALL_MS, AFTER_EACH_MS, launchTestBrowser, testScope } from './helpers/browser';
|
||||||
|
|
||||||
const page = 'file://' + join(import.meta.dir, '..', 'site', 'index.html');
|
const page = 'file://' + join(import.meta.dir, '..', 'site', 'index.html');
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
const shared = await launchTestBrowser('playwright-core');
|
||||||
let browser: any = null;
|
const { browser, skipWhy } = shared;
|
||||||
let skipWhy = '';
|
if (!browser) console.warn(`site overflow test skipped: no Chromium installed (${skipWhy}). Run \`bunx playwright install chromium\`.`);
|
||||||
try {
|
const scope = testScope(() => browser);
|
||||||
const { chromium } = await import('playwright-core');
|
|
||||||
try { browser = await chromium.launch({ headless: true }); } catch { browser = await chromium.launch({ headless: true, channel: 'chrome' }); }
|
|
||||||
} catch (e) { skipWhy = (e as Error).message.split('\n')[0]!; }
|
|
||||||
if (!browser) console.warn(`site overflow test skipped: no Chromium could launch (${skipWhy}). Run \`bunx playwright install chromium\`.`);
|
|
||||||
|
|
||||||
afterAll(async () => { await browser?.close(); });
|
// bounded: one context per test, each close capped (bun's 5 s default hook timeout was too tight for Chrome's slow shutdown)
|
||||||
|
afterEach(() => scope.settle(), AFTER_EACH_MS);
|
||||||
|
afterAll(() => shared.close(), AFTER_ALL_MS);
|
||||||
|
|
||||||
describe.skipIf(!browser)('site: no horizontal overflow', () => {
|
describe.skipIf(!browser)('site: no horizontal overflow', () => {
|
||||||
for (const scheme of ['light', 'dark'] as const) {
|
for (const scheme of ['light', 'dark'] as const) {
|
||||||
test(`320-1440 px, ${scheme}`, async () => {
|
test(`320-1440 px, ${scheme}`, async () => {
|
||||||
const ctx = await browser.newContext({ colorScheme: scheme, viewport: { width: 1440, height: 900 } });
|
const p = await scope.newPage({ colorScheme: scheme, viewport: { width: 1440, height: 900 } });
|
||||||
const p = await ctx.newPage();
|
|
||||||
await p.goto(page, { waitUntil: 'load' });
|
await p.goto(page, { waitUntil: 'load' });
|
||||||
const bad: string[] = [];
|
const bad: string[] = [];
|
||||||
for (let w = 320; w <= 1440; w += 10) {
|
for (let w = 320; w <= 1440; w += 10) {
|
||||||
|
|
@ -44,7 +44,6 @@ describe.skipIf(!browser)('site: no horizontal overflow', () => {
|
||||||
});
|
});
|
||||||
if (r) bad.push(r);
|
if (r) bad.push(r);
|
||||||
}
|
}
|
||||||
await ctx.close();
|
|
||||||
expect(bad).toEqual([]);
|
expect(bad).toEqual([]);
|
||||||
}, 120_000);
|
}, 120_000);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
194
tools/ci-plan.ts
Normal file
194
tools/ci-plan.ts
Normal file
|
|
@ -0,0 +1,194 @@
|
||||||
|
// The planning half of tools/ci.ts: which test files exist, how they are split into shards, which tests a change
|
||||||
|
// touches (ci:quick) and whether the desktop Rust host needs to run. Pure functions plus small file / git reads;
|
||||||
|
// tests/ci-plan.test.ts covers them.
|
||||||
|
import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||||
|
import { cpus } from 'node:os';
|
||||||
|
import { dirname, join, normalize, relative } from 'node:path';
|
||||||
|
|
||||||
|
export const ROOT = join(import.meta.dir, '..');
|
||||||
|
/** Recorded per-file test durations (seconds), written after every run. Gitignored (node_modules/). */
|
||||||
|
export const TIMINGS = join(ROOT, 'node_modules/.cache/storebound-ci/test-timings.json');
|
||||||
|
|
||||||
|
/** Suites that drive a real Chromium (or a heavy child process): each gets a shard of its own, never another heavy
|
||||||
|
* suite next to it, so they don't fight for CPU and time out. */
|
||||||
|
export const HEAVY = [
|
||||||
|
'tests/console-fill.test.ts', 'tests/site-overflow.test.ts', 'tests/local-fonts.test.ts', 'tests/glyphs.test.ts',
|
||||||
|
'tests/capture-web.test.ts', 'tests/console-session.test.ts',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Changes that can affect every test: run the whole suite. */
|
||||||
|
export const GLOBAL = /^(package\.json|bun\.lock|bunfig\.toml|tsconfig\.json|tests\/helpers\/preload\.ts)$/;
|
||||||
|
|
||||||
|
const SKIP_DIRS = new Set(['node_modules', '.git', '.scratch', 'dist', 'target', 'fixtures', '.claude']);
|
||||||
|
|
||||||
|
/** Every *.test.ts / *.test.tsx `bun test` would pick up, relative to the root, sorted. */
|
||||||
|
export function listTests(root = ROOT): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
const walk = (dir: string) => {
|
||||||
|
for (const e of readdirSync(join(root, dir), { withFileTypes: true })) {
|
||||||
|
const p = dir ? `${dir}/${e.name}` : e.name;
|
||||||
|
if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) walk(p); }
|
||||||
|
else if (/\.test\.tsx?$/.test(e.name)) out.push(p);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk('');
|
||||||
|
return out.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shard count: CPU cores - 1, at least 1, at most 8 (STOREBOUND_CI_SHARDS overrides). */
|
||||||
|
export function shardCount(env = process.env, cores = cpus().length): number {
|
||||||
|
const n = Number(env.STOREBOUND_CI_SHARDS);
|
||||||
|
if (Number.isInteger(n) && n > 0) return n;
|
||||||
|
return Math.max(1, Math.min(8, cores - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readTimings(file = TIMINGS): Record<string, number> {
|
||||||
|
try { return JSON.parse(readFileSync(file, 'utf8')) as Record<string, number>; } catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeTimings(t: Record<string, number>, file = TIMINGS): void {
|
||||||
|
try { mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, `${JSON.stringify(t, null, 1)}\n`); } catch { /* cache only */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per-file seconds from bun's JUnit report (the top-level <testsuite> of each file). */
|
||||||
|
export function junitTimes(xml: string): Record<string, number> {
|
||||||
|
const out: Record<string, number> = {};
|
||||||
|
for (const m of xml.matchAll(/<testsuite name="([^"]+)" file="([^"]+)"[^>]*?time="([\d.]+)"/g)) {
|
||||||
|
if (m[1] === m[2]) out[m[2]!] = Number(m[3]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Estimated cost of a file: its recorded time, else its size (about 1 s per 40 KB, 0.2 s minimum). */
|
||||||
|
export function cost(file: string, timings: Record<string, number>, size: (f: string) => number): number {
|
||||||
|
return timings[file] ?? Math.max(0.2, size(file) / 40_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Longest-processing-time-first split into at most n shards. Heavy files each open a shard of their own and never
|
||||||
|
* share it with another heavy file; light files fill the least loaded shard. Empty shards are dropped.
|
||||||
|
*/
|
||||||
|
export function balance(files: string[], n: number, costOf: (f: string) => number, heavy: string[] = HEAVY): string[][] {
|
||||||
|
const shards = Array.from({ length: Math.max(1, n) }, () => ({ files: [] as string[], load: 0, heavy: false }));
|
||||||
|
const sorted = [...files].sort((a, b) => costOf(b) - costOf(a) || a.localeCompare(b));
|
||||||
|
const isHeavy = (f: string) => heavy.includes(f);
|
||||||
|
for (const f of sorted.filter(isHeavy)) {
|
||||||
|
const free = shards.filter(s => !s.heavy);
|
||||||
|
const s = (free.length ? free : shards).reduce((a, b) => (b.load < a.load ? b : a));
|
||||||
|
s.files.push(f); s.load += costOf(f); s.heavy = true;
|
||||||
|
}
|
||||||
|
for (const f of sorted.filter(f => !isHeavy(f))) {
|
||||||
|
const s = shards.reduce((a, b) => (b.load < a.load ? b : a));
|
||||||
|
s.files.push(f); s.load += costOf(f);
|
||||||
|
}
|
||||||
|
return shards.filter(s => s.files.length).map(s => s.files);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function planShards(files: string[], n = shardCount(), root = ROOT): string[][] {
|
||||||
|
const t = readTimings();
|
||||||
|
return balance(files, n, f => cost(f, t, p => { try { return statSync(join(root, p)).size; } catch { return 0; } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- which tests a change touches ----
|
||||||
|
|
||||||
|
const IMPORT_RE = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)['"](\.{1,2}\/[^'"]+)['"]/gm;
|
||||||
|
const JOIN_RE = /join\(\s*(?:import\.meta\.dir|__dirname|ROOT|root|REPO)\s*,((?:\s*'[^']*'\s*,?)+)\)/g;
|
||||||
|
|
||||||
|
function resolveFile(p: string): string | null {
|
||||||
|
for (const c of [p, `${p}.ts`, `${p}.tsx`, join(p, 'index.ts'), join(p, 'index.tsx')]) {
|
||||||
|
try { if (statSync(c).isFile()) return c; } catch { /* next */ }
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Repo files a source file depends on: relative imports, plus `join(import.meta.dir, '..', 'cli', 'index.ts')`
|
||||||
|
* style paths (a test that spawns the CLI depends on it). */
|
||||||
|
export function depsOf(file: string, root = ROOT, src = readFileSync(join(root, file), 'utf8')): string[] {
|
||||||
|
const dir = dirname(join(root, file));
|
||||||
|
const out = new Set<string>();
|
||||||
|
for (const m of src.matchAll(IMPORT_RE)) {
|
||||||
|
const r = resolveFile(normalize(join(dir, m[1]!)));
|
||||||
|
if (r) out.add(relative(root, r));
|
||||||
|
}
|
||||||
|
for (const m of src.matchAll(JOIN_RE)) {
|
||||||
|
const parts = [...m[1]!.matchAll(/'([^']*)'/g)].map(x => x[1]!);
|
||||||
|
for (const base of [dir, root]) {
|
||||||
|
const r = resolveFile(normalize(join(base, ...parts)));
|
||||||
|
if (r && r.startsWith(root)) { out.add(relative(root, r)); break; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...out];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests related to the changed files: a changed test itself, every test that imports a changed file (transitively),
|
||||||
|
* and every test that names a changed non-code file (fixture, page, skill) by its file name or its fixture folder.
|
||||||
|
* A change to a GLOBAL file returns every test. Files in `near` (the browser suites, by default none) count as
|
||||||
|
* related only through imports at most NEAR_DEPTH steps away: nearly every module reaches cli/lib/config.ts and the
|
||||||
|
* store clients, and ci:quick should not start a browser for every change there (the full ci runs them).
|
||||||
|
*/
|
||||||
|
export const NEAR_DEPTH = 2;
|
||||||
|
export function relatedTests(changed: string[], tests: string[], root = ROOT, near: string[] = []): string[] {
|
||||||
|
if (changed.some(f => GLOBAL.test(f))) return tests;
|
||||||
|
const changedSet = new Set(changed);
|
||||||
|
const direct = new Map<string, string[]>();
|
||||||
|
const depsCached = (f: string) => {
|
||||||
|
let d = direct.get(f);
|
||||||
|
if (!d) { try { d = depsOf(f, root); } catch { d = []; } direct.set(f, d); }
|
||||||
|
return d;
|
||||||
|
};
|
||||||
|
/** Every file a test reaches, with its import distance. */
|
||||||
|
const closure = (f: string): Map<string, number> => {
|
||||||
|
const depth = new Map<string, number>([[f, 0]]);
|
||||||
|
const queue = [f];
|
||||||
|
while (queue.length) {
|
||||||
|
const cur = queue.shift()!;
|
||||||
|
if (!/\.(ts|tsx)$/.test(cur)) continue;
|
||||||
|
for (const d of depsCached(cur)) if (!depth.has(d)) { depth.set(d, depth.get(cur)! + 1); queue.push(d); }
|
||||||
|
}
|
||||||
|
return depth;
|
||||||
|
};
|
||||||
|
const names = changed.filter(f => !/\.(ts|tsx)$/.test(f) || f.includes('/fixtures/')).flatMap(f => {
|
||||||
|
const base = f.split('/').pop()!;
|
||||||
|
const fx = /(?:^|\/)fixtures\/([^/]+)/.exec(f)?.[1];
|
||||||
|
return [base, ...(fx ? [`fixtures/${fx}`, `'${fx}'`] : [])].filter(s => s.length > 3);
|
||||||
|
});
|
||||||
|
return tests.filter(t => {
|
||||||
|
if (changedSet.has(t)) return true;
|
||||||
|
const all = closure(t);
|
||||||
|
const max = near.includes(t) ? NEAR_DEPTH : Infinity;
|
||||||
|
if (changed.some(c => all.has(c) && all.get(c)! <= max)) return true;
|
||||||
|
if (!names.length) return false;
|
||||||
|
const srcs = [...all.keys()].filter(d => d.startsWith('tests/') || d.startsWith('apps/desktop/tests/')).map(d => {
|
||||||
|
try { return readFileSync(join(root, d), 'utf8'); } catch { return ''; }
|
||||||
|
}).join('\n');
|
||||||
|
return names.some(n => srcs.includes(n));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- git ----
|
||||||
|
|
||||||
|
function git(args: string[], root = ROOT): string | null {
|
||||||
|
const r = Bun.spawnSync(['git', ...args], { cwd: root, stdout: 'pipe', stderr: 'ignore' });
|
||||||
|
return r.exitCode === 0 ? r.stdout.toString() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Files changed against origin/main (committed since the merge base, staged, unstaged and untracked), or null
|
||||||
|
* when that cannot be told (no git, no origin/main). */
|
||||||
|
export function changedFiles(base = process.env.STOREBOUND_CI_BASE ?? 'origin/main', root = ROOT): string[] | null {
|
||||||
|
const mb = git(['merge-base', base, 'HEAD'], root)?.trim();
|
||||||
|
if (!mb) return null;
|
||||||
|
const lists = [git(['diff', '--name-only', mb], root), git(['ls-files', '--others', '--exclude-standard'], root)];
|
||||||
|
if (lists.some(l => l === null)) return null;
|
||||||
|
return [...new Set(lists.join('\n').split('\n').map(s => s.trim()).filter(Boolean))].sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Desktop Rust host inputs: the crate, and the sidecar build its build script needs (cargo test / clippy never run
|
||||||
|
* the sidecar itself, so a CLI change does not need them; tools/ci.ts rebuilds the sidecar on CLI changes). */
|
||||||
|
export const RUST_INPUTS = /^(apps\/desktop\/src-tauri\/|tools\/build-sidecars\.ts$)/;
|
||||||
|
|
||||||
|
/** Run cargo test / clippy? Always with CI=full or when the change set is unknown; else only when a Rust input changed. */
|
||||||
|
export function rustNeeded(changed: string[] | null, env = process.env): boolean {
|
||||||
|
if (env.CI === 'full' || changed === null) return true;
|
||||||
|
return changed.some(f => RUST_INPUTS.test(f));
|
||||||
|
}
|
||||||
205
tools/ci.ts
205
tools/ci.ts
|
|
@ -1,46 +1,175 @@
|
||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
// Everything CI runs, in order; stops at the first failure. bun run ci
|
// Everything CI runs, as a small task graph: independent steps run at the same time, output is streamed with a
|
||||||
// `bun test` covers the CLI and the desktop webview (apps/desktop/tests: model, i18n, theme contrast, webview rules),
|
// [step] prefix, the first failure stops everything, and a summary prints the time per step.
|
||||||
// the desktop boot check (tools/desktop-boot-check.ts: the built window in headless Chromium, needs playwright's
|
// bun run ci full gate before pushing (every check, every test)
|
||||||
// browser or Google Chrome), the site overflow check (tests/site-overflow.test.ts: no sideways scroll at 320-1440 px,
|
// bun run ci:quick inner loop: typecheck + the tests related to the change (git diff against origin/main,
|
||||||
// light and dark; skips without Chromium), and the no-hand-written-SVG guard (tests/no-handmade-svg.test.ts: visx charts, Phosphor icons, simple-icons store marks, Mermaid diagrams).
|
// mapped through imports) + scrub
|
||||||
// The desktop Rust host (cargo test, clippy
|
// The tests run as shards: N = CPU cores - 1 (max 8; STOREBOUND_CI_SHARDS=n overrides) parallel `bun test <files>`
|
||||||
// with warnings as errors) runs when cargo is installed; set STOREBOUND_CI_RUST=0 to skip it on a machine without Rust.
|
// processes, balanced by the durations recorded after the last run (node_modules/.cache/storebound-ci/, falling back
|
||||||
|
// to file size). Browser suites (tools/ci-plan.ts HEAVY) each get a shard of their own.
|
||||||
|
// `bun test` covers the CLI and the desktop webview (apps/desktop/tests), the site overflow check and the
|
||||||
|
// no-hand-written-SVG guard; the desktop boot check (tools/desktop-boot-check.ts: the built window in headless
|
||||||
|
// Chromium, needs playwright's browser or Google Chrome) runs after the desktop build.
|
||||||
|
// The desktop Rust host (cargo test, clippy with warnings as errors) runs when cargo is installed and
|
||||||
|
// apps/desktop/src-tauri or the sidecar build changed against origin/main, or always with CI=full;
|
||||||
|
// STOREBOUND_CI_RUST=0 skips it on a machine without Rust.
|
||||||
|
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||||
|
import { homedir, tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
import { hostTarget, OUT_DIR, outName } from './build-sidecars';
|
||||||
|
import { changedFiles, HEAVY, junitTimes, listTests, planShards, readTimings, relatedTests, ROOT, rustNeeded, writeTimings } from './ci-plan';
|
||||||
|
|
||||||
const root = new URL('..', import.meta.url).pathname;
|
interface Task { name: string; cmd: string[]; cwd?: string; env?: Record<string, string>; after?: string[]; junit?: string }
|
||||||
const tauri = join(root, 'apps/desktop/src-tauri');
|
|
||||||
const cargo = process.env.STOREBOUND_CI_RUST === '0' ? null : Bun.which('cargo');
|
const quick = process.argv.includes('--quick');
|
||||||
const steps: [string, string[], string?][] = [
|
const tauri = join(ROOT, 'apps/desktop/src-tauri');
|
||||||
['adapters', ['bun', 'tools/gen-adapters.ts', '--check']],
|
const cache = join(ROOT, 'node_modules/.cache/storebound-ci');
|
||||||
|
const changed = changedFiles();
|
||||||
|
const tests = listTests();
|
||||||
|
const touches = (re: RegExp) => changed === null || changed.some(f => re.test(f));
|
||||||
|
const tasks: Task[] = [];
|
||||||
|
const add = (t: Task) => tasks.push(t);
|
||||||
|
const tsc = (name: string, project: string) => add({ name, cmd: ['bunx', 'tsc', '--noEmit', '--incremental', '-p', project,
|
||||||
|
'--tsBuildInfoFile', join(cache, `${name.replace(/\W+/g, '-')}.tsbuildinfo`)] });
|
||||||
|
const junitDir = mkdtempSync(join(tmpdir(), 'sb-ci-'));
|
||||||
|
|
||||||
|
function addTests(files: string[]) {
|
||||||
|
planShards(files).forEach((shard, i, all) => {
|
||||||
|
const junit = join(junitDir, `shard-${i + 1}.xml`);
|
||||||
|
// the built-bundle check in apps/desktop/tests/webview.test.ts runs as "desktop bundle check" once the build is
|
||||||
|
// done; here it would read dist/ while vite rewrites it
|
||||||
|
// browser suites share the machine with the other steps: a browser start or close can pass bun's 5 s default
|
||||||
|
const timeout = shard.some(f => HEAVY.includes(f)) ? ['--timeout=30000'] : [];
|
||||||
|
add({ name: `tests ${i + 1}/${all.length}`, cmd: ['bun', 'test', ...timeout, '--reporter=junit', `--reporter-outfile=${junit}`, ...shard.map(f => `./${f}`)],
|
||||||
|
env: { STOREBOUND_SKIP_DIST_CHECK: '1' }, junit });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (quick) {
|
||||||
|
const related = changed === null ? tests : relatedTests(changed, tests, ROOT, HEAVY);
|
||||||
|
const far = changed === null ? [] : relatedTests(changed, tests).filter(t => !related.includes(t));
|
||||||
|
console.log(`ci:quick: ${changed === null ? 'no origin/main to diff against: every test' : `${changed.length} changed file(s), ${related.length} related test file(s)`}`);
|
||||||
|
if (far.length) console.log(`ci:quick: left out ${far.length} browser suite(s) reached only through shared modules (bun run ci runs them): ${far.join(' ')}`);
|
||||||
|
add({ name: 'adapters', cmd: ['bun', 'tools/gen-adapters.ts', '--check'] });
|
||||||
|
tsc('typecheck', '.');
|
||||||
|
if (touches(/^apps\/desktop\//)) tsc('desktop typecheck', 'apps/desktop');
|
||||||
|
if (related.length) addTests(related);
|
||||||
|
add({ name: 'scrub', cmd: ['bun', 'tools/scrub.ts'] });
|
||||||
|
} else {
|
||||||
|
const cargo = process.env.STOREBOUND_CI_RUST === '0' ? null : Bun.which('cargo');
|
||||||
|
const rust = cargo && rustNeeded(changed);
|
||||||
|
if (!cargo) console.log('ci: cargo not found (or STOREBOUND_CI_RUST=0): desktop Rust tests and clippy skipped');
|
||||||
|
else if (!rust) console.log('ci: apps/desktop/src-tauri and the sidecar build unchanged against origin/main: desktop Rust tests and clippy skipped (CI=full runs them)');
|
||||||
|
add({ name: 'adapters', cmd: ['bun', 'tools/gen-adapters.ts', '--check'] });
|
||||||
// the App Store Connect / Google Play operation tables, the wrapped-by scan and docs/api-coverage.md match specs/ and cli/
|
// the App Store Connect / Google Play operation tables, the wrapped-by scan and docs/api-coverage.md match specs/ and cli/
|
||||||
['api tables', ['bun', 'tools/gen-api.ts', '--check']],
|
add({ name: 'api tables', cmd: ['bun', 'tools/gen-api.ts', '--check'] });
|
||||||
// one desktop version: package.json desktopVersion = apps/desktop/package.json = tauri.conf.json = Cargo.toml / .lock
|
// one desktop version: package.json desktopVersion = apps/desktop/package.json = tauri.conf.json = Cargo.toml / .lock
|
||||||
['desktop version', ['bun', 'tools/desktop-version.ts']],
|
add({ name: 'desktop version', cmd: ['bun', 'tools/desktop-version.ts'] });
|
||||||
['tests', ['bun', 'test']],
|
add({ name: 'desktop i18n', cmd: ['bun', 'tools/i18n-check.ts'] });
|
||||||
['typecheck', ['bunx', 'tsc', '--noEmit']],
|
tsc('typecheck', '.');
|
||||||
['desktop i18n', ['bun', 'tools/i18n-check.ts']],
|
tsc('desktop typecheck', 'apps/desktop');
|
||||||
['desktop typecheck', ['bunx', 'tsc', '--noEmit', '-p', 'apps/desktop']],
|
add({ name: 'scrub', cmd: ['bun', 'tools/scrub.ts'] });
|
||||||
['desktop build', ['bun', 'run', '--cwd', 'apps/desktop', 'build']],
|
addTests(tests);
|
||||||
// the release bundle must not carry the dev fixture mode (apps/desktop/tests/webview.test.ts checks dist/ when present)
|
// `vite build` only: the desktop package's own build script runs tsc first, which "desktop typecheck" already does
|
||||||
['desktop bundle check', ['bun', 'test', 'apps/desktop/tests/webview.test.ts']],
|
add({ name: 'desktop build', cmd: ['bunx', 'vite', 'build', '--logLevel', 'warn'], cwd: join(ROOT, 'apps/desktop') });
|
||||||
|
// the release bundle must not carry the dev fixture mode
|
||||||
|
add({ name: 'desktop bundle check', cmd: ['bun', 'test', './apps/desktop/tests/webview.test.ts'], after: ['desktop build'] });
|
||||||
// the built window boots (release CSP, Tauri's frozen Object.prototype, mocked host + real sidecar) on an empty, a
|
// the built window boots (release CSP, Tauri's frozen Object.prototype, mocked host + real sidecar) on an empty, a
|
||||||
// D1 (folders gone) and a full D3 saved state, through every screen: no uncaught error, never an empty window
|
// D1 (folders gone) and a full D3 saved state, through every screen: no uncaught error, never an empty window
|
||||||
['desktop boot check', ['bun', 'tools/desktop-boot-check.ts']],
|
add({ name: 'desktop boot check', cmd: ['bun', 'tools/desktop-boot-check.ts'], after: ['desktop build'] });
|
||||||
...(cargo ? [
|
// the CLI compiled into the desktop sidecar (bun build --compile, scanned for this machine's paths): rebuilt when
|
||||||
// tauri's build script needs the host sidecar binary (gitignored), so a clean checkout builds it first
|
// its inputs changed, with CI=full, or when missing; tauri's build script needs it for cargo test / clippy
|
||||||
['desktop sidecar (host)', ['bun', 'tools/build-sidecars.ts', '--host']],
|
const hostBin = join(OUT_DIR, outName(hostTarget()));
|
||||||
['desktop rust tests', [cargo, 'test', '--quiet'], tauri],
|
const sidecarBuild = process.env.CI === 'full' || !existsSync(hostBin) || touches(/^(cli\/|tools\/build-sidecars\.ts$|package\.json$|bun\.lock$)/);
|
||||||
['desktop clippy', [cargo, 'clippy', '--all-targets', '--quiet', '--', '-D', 'warnings'], tauri],
|
if (sidecarBuild) add({ name: 'desktop sidecar (host)', cmd: ['bun', 'tools/build-sidecars.ts', '--host'] });
|
||||||
] as [string, string[], string][] : []),
|
if (cargo && rust) {
|
||||||
['scrub', ['bun', 'tools/scrub.ts']],
|
const after = sidecarBuild ? ['desktop sidecar (host)'] : [];
|
||||||
];
|
// cargo locks the target dir, so test and clippy run one after the other
|
||||||
if (!cargo) console.log('ci: cargo not found (or STOREBOUND_CI_RUST=0): desktop Rust tests and clippy skipped');
|
add({ name: 'desktop rust tests', cmd: [cargo, 'test', '--quiet'], cwd: tauri, after });
|
||||||
for (const [name, cmd, cwd] of steps) {
|
add({ name: 'desktop clippy', cmd: [cargo, 'clippy', '--all-targets', '--quiet', '--', '-D', 'warnings'], cwd: tauri, after: ['desktop rust tests'] });
|
||||||
const t = Date.now();
|
}
|
||||||
console.log(`\n== ${name}: ${cmd.join(' ')}`);
|
|
||||||
const r = Bun.spawnSync(cmd, { cwd: cwd ?? root, stdout: 'inherit', stderr: 'inherit' });
|
|
||||||
if (r.exitCode !== 0) { console.error(`\nci: ${name} failed (exit ${r.exitCode})`); process.exit(1); }
|
|
||||||
console.log(`== ${name} ok (${((Date.now() - t) / 1000).toFixed(1)}s)`);
|
|
||||||
}
|
}
|
||||||
console.log('\nci: all green');
|
|
||||||
|
// The browser suites fall back to Google Chrome without playwright's own headless Chromium; Chrome's shutdown takes
|
||||||
|
// seconds to half a minute per browser, which makes those shards several times slower.
|
||||||
|
if (tasks.some(t => t.name === 'desktop boot check' || t.cmd.some(a => HEAVY.some(h => a.endsWith(h))))) try {
|
||||||
|
const { registry } = await import('playwright-core/lib/server/registry/index' as string);
|
||||||
|
const exe = registry.findExecutable('chromium-headless-shell')?.executablePath('javascript') as string | undefined;
|
||||||
|
if (exe && !existsSync(exe)) console.log(`ci: playwright's headless Chromium is not installed (${exe.replace(homedir(), '~')}): the browser tests use Google Chrome, which is much slower to close. Install it once: bunx playwright install chromium-headless-shell`);
|
||||||
|
} catch { /* playwright internals moved: no hint */ }
|
||||||
|
|
||||||
|
// ---- runner ----
|
||||||
|
|
||||||
|
interface Run { task: Task; start: number; end?: number; code?: number; proc?: ReturnType<typeof Bun.spawn> }
|
||||||
|
const runs = new Map<string, Run>();
|
||||||
|
const t0 = Date.now();
|
||||||
|
const width = Math.max(...tasks.map(t => t.name.length));
|
||||||
|
const tag = (n: string) => `[${n.padEnd(width)}]`;
|
||||||
|
let failed: string | null = null;
|
||||||
|
|
||||||
|
async function pump(stream: ReadableStream<Uint8Array>, name: string, out: NodeJS.WriteStream) {
|
||||||
|
const dec = new TextDecoder();
|
||||||
|
let buf = '';
|
||||||
|
const reader = stream.getReader();
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
if (failed && failed !== name) continue; // a stopped step's last words are noise
|
||||||
|
buf += dec.decode(value, { stream: true });
|
||||||
|
const lines = buf.split('\n');
|
||||||
|
buf = lines.pop()!;
|
||||||
|
if (lines.length) out.write(lines.map(l => `${tag(name)} ${l}\n`).join(''));
|
||||||
|
}
|
||||||
|
if (buf && !(failed && failed !== name)) out.write(`${tag(name)} ${buf}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start(task: Task): Promise<void> {
|
||||||
|
const run: Run = { task, start: Date.now() };
|
||||||
|
runs.set(task.name, run);
|
||||||
|
console.log(`${tag(task.name)} $ ${task.cmd.join(' ').replace(junitDir, '$TMP')}`);
|
||||||
|
const proc = Bun.spawn(task.cmd, { cwd: task.cwd ?? ROOT, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, FORCE_COLOR: '0', ...task.env } });
|
||||||
|
run.proc = proc;
|
||||||
|
await Promise.all([pump(proc.stdout, task.name, process.stdout), pump(proc.stderr, task.name, process.stderr), proc.exited]);
|
||||||
|
run.code = proc.exitCode ?? 1;
|
||||||
|
run.end = Date.now();
|
||||||
|
if (failed) return;
|
||||||
|
console.log(`${tag(task.name)} ${run.code === 0 ? 'ok' : `FAILED (exit ${run.code})`} in ${((run.end - run.start) / 1000).toFixed(1)}s`);
|
||||||
|
if (run.code !== 0) {
|
||||||
|
failed = task.name;
|
||||||
|
for (const r of runs.values()) if (r.end === undefined) r.proc?.kill('SIGKILL'); // bun test ignores SIGTERM until its files finish
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = new Set(tasks);
|
||||||
|
const active = new Set<Promise<void>>();
|
||||||
|
while ((pending.size || active.size) && !failed) {
|
||||||
|
for (const t of [...pending]) {
|
||||||
|
if ((t.after ?? []).every(a => runs.get(a)?.code === 0)) {
|
||||||
|
pending.delete(t);
|
||||||
|
const p = start(t).finally(() => active.delete(p));
|
||||||
|
active.add(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!active.size) { failed = 'scheduler (unmet dependency)'; break; }
|
||||||
|
await Promise.race(active);
|
||||||
|
}
|
||||||
|
if (failed) await Promise.allSettled([...active]);
|
||||||
|
|
||||||
|
// record per-file durations for the next split (only from shards that finished)
|
||||||
|
const timings = readTimings();
|
||||||
|
for (const r of runs.values()) {
|
||||||
|
if (!r.task.junit || r.end === undefined) continue;
|
||||||
|
try { Object.assign(timings, junitTimes(readFileSync(r.task.junit, 'utf8'))); } catch { /* no report */ }
|
||||||
|
}
|
||||||
|
writeTimings(timings);
|
||||||
|
rmSync(junitDir, { recursive: true, force: true });
|
||||||
|
|
||||||
|
console.log(`\n${quick ? 'ci:quick' : 'ci'} summary (wall ${((Date.now() - t0) / 1000).toFixed(1)}s)`);
|
||||||
|
for (const r of [...runs.values()].sort((a, b) => a.start - b.start)) {
|
||||||
|
const s = r.end === undefined ? 'killed' : r.code === 0 ? 'ok' : r.task.name === failed ? 'FAILED' : 'stopped';
|
||||||
|
const secs = (((r.end ?? Date.now()) - r.start) / 1000).toFixed(1).padStart(6);
|
||||||
|
console.log(` ${r.task.name.padEnd(width)} ${secs}s @${((r.start - t0) / 1000).toFixed(1).padStart(5)}s ${s}`);
|
||||||
|
}
|
||||||
|
for (const t of pending) console.log(` ${t.name.padEnd(width)} - not started`);
|
||||||
|
if (failed) { console.error(`\nci: ${failed} failed`); process.exit(1); }
|
||||||
|
console.log(`\n${quick ? 'ci:quick' : 'ci'}: all green`);
|
||||||
|
|
|
||||||
|
|
@ -84,6 +84,8 @@ export function generate(root: string): Map<string, string> {
|
||||||
'file below and follow it step by step.', '', coreBody.replace(/^/, ''), '', cli, '', '## Skills', '', indexPaths, '',
|
'file below and follow it step by step.', '', coreBody.replace(/^/, ''), '', cli, '', '## Skills', '', indexPaths, '',
|
||||||
'## Working on storebound itself', '',
|
'## Working on storebound itself', '',
|
||||||
'- Bun + TypeScript strict, zero runtime dependencies. `bun run ci` must pass (adapters fresh, tests, typecheck, scrub).',
|
'- Bun + TypeScript strict, zero runtime dependencies. `bun run ci` must pass (adapters fresh, tests, typecheck, scrub).',
|
||||||
|
'- Inner loop: `bun run ci:quick` (typecheck, the tests related to your change against origin/main, scrub; seconds).',
|
||||||
|
' Before every push: the full `bun run ci` (every check and test, in parallel shards), and check its exit code.',
|
||||||
'- Skills are the single source: edit `skills/*/SKILL.md` or `docs/agents-core.md`, then `bun tools/gen-adapters.ts`.',
|
'- Skills are the single source: edit `skills/*/SKILL.md` or `docs/agents-core.md`, then `bun tools/gen-adapters.ts`.',
|
||||||
'- Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com.',
|
'- Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com.',
|
||||||
''].join('\n'));
|
''].join('\n'));
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue