From e778373fb619eed241050714e093d4e0975735ef Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 11 Oct 2026 16:14:00 +0000 Subject: [PATCH] growth extras: prices ppp, ads apple, web, apple adhoc, play share, revenuecat, console fill (+ desktop button) --- apps/desktop/src-tauri/src/commands.rs | 44 ++- apps/desktop/src-tauri/src/policy.rs | 6 + apps/desktop/src-tauri/tests/d3_writes.rs | 25 +- apps/desktop/src/api.ts | 2 +- apps/desktop/src/dev/fixtures.ts | 30 +- apps/desktop/src/i18n/en.ts | 33 ++ apps/desktop/src/i18n/tr.ts | 33 ++ apps/desktop/src/screens/tabs/AppInfo.tsx | 35 +- apps/desktop/src/styles.css | 7 + apps/desktop/src/ui/ConsoleFill.tsx | 130 +++++++ cli/ads/apple.ts | 202 ++++++++++ cli/ads/client.ts | 71 ++++ cli/apple/adhoc.ts | 200 ++++++++++ cli/console/fill.ts | 282 ++++++++++++++ cli/data/ppp-worldbank.json | 196 ++++++++++ cli/index.ts | 8 +- cli/lib/adhoc.ts | 177 +++++++++ cli/lib/apple-ads.ts | 251 +++++++++++++ cli/lib/config.ts | 133 +++++++ cli/lib/console-answers.ts | 231 ++++++++++++ cli/lib/console-forms.ts | 130 +++++++ cli/lib/credentials.ts | 5 +- cli/lib/desktop-protocol.ts | 12 + cli/lib/play-share.ts | 41 +++ cli/lib/ppp.ts | 342 +++++++++++++++++ cli/lib/revenuecat.ts | 307 ++++++++++++++++ cli/lib/template-files.ts | 6 + cli/lib/web.ts | 294 +++++++++++++++ cli/play/share.ts | 74 ++++ cli/prices-ppp.ts | 174 +++++++++ cli/prices.ts | 6 +- cli/revenuecat.ts | 189 ++++++++++ cli/serve.ts | 24 +- cli/shots/browser.ts | 14 + cli/text-modules.d.ts | 1 + cli/web.ts | 127 +++++++ docs/desktop.md | 23 ++ skills/adhoc-distribution/SKILL.md | 76 ++++ skills/apple-ads/SKILL.md | 66 ++++ skills/console-autofill/SKILL.md | 63 ++++ skills/ppp-pricing/SKILL.md | 69 ++++ skills/revenuecat-sync/SKILL.md | 68 ++++ skills/web-presence/SKILL.md | 86 +++++ templates/credentials.example.json | 6 + templates/web/appstore.svg | 1 + templates/web/googleplay.svg | 1 + templates/web/landing.html | 50 +++ tests/adhoc.test.ts | 347 ++++++++++++++++++ tests/apple-ads.test.ts | 277 ++++++++++++++ tests/console-fill.test.ts | 295 +++++++++++++++ tests/fixtures/console/_common.js | 10 + tests/fixtures/console/apple-app-privacy.html | 35 ++ .../console/apple-app-record-renamed.html | 21 ++ tests/fixtures/console/apple-app-record.html | 23 ++ .../fixtures/console/play-content-rating.html | 32 ++ .../console/play-target-audience.html | 17 + tests/fixtures/console/signin.html | 4 + tests/growth-config.test.ts | 32 ++ tests/no-handmade-svg.test.ts | 15 +- tests/ppp.test.ts | 247 +++++++++++++ tests/revenuecat.test.ts | 331 +++++++++++++++++ tests/serve.test.ts | 29 ++ tests/web.test.ts | 215 +++++++++++ tools/site-icons.ts | 9 +- tools/update-ppp.ts | 44 +++ 65 files changed, 6307 insertions(+), 27 deletions(-) create mode 100644 apps/desktop/src/ui/ConsoleFill.tsx create mode 100644 cli/ads/apple.ts create mode 100644 cli/ads/client.ts create mode 100644 cli/apple/adhoc.ts create mode 100644 cli/console/fill.ts create mode 100644 cli/data/ppp-worldbank.json create mode 100644 cli/lib/adhoc.ts create mode 100644 cli/lib/apple-ads.ts create mode 100644 cli/lib/console-answers.ts create mode 100644 cli/lib/console-forms.ts create mode 100644 cli/lib/play-share.ts create mode 100644 cli/lib/ppp.ts create mode 100644 cli/lib/revenuecat.ts create mode 100644 cli/lib/web.ts create mode 100644 cli/play/share.ts create mode 100644 cli/prices-ppp.ts create mode 100644 cli/revenuecat.ts create mode 100644 cli/web.ts create mode 100644 skills/adhoc-distribution/SKILL.md create mode 100644 skills/apple-ads/SKILL.md create mode 100644 skills/console-autofill/SKILL.md create mode 100644 skills/ppp-pricing/SKILL.md create mode 100644 skills/revenuecat-sync/SKILL.md create mode 100644 skills/web-presence/SKILL.md create mode 100644 templates/web/appstore.svg create mode 100644 templates/web/googleplay.svg create mode 100644 templates/web/landing.html create mode 100644 tests/adhoc.test.ts create mode 100644 tests/apple-ads.test.ts create mode 100644 tests/console-fill.test.ts create mode 100644 tests/fixtures/console/_common.js create mode 100644 tests/fixtures/console/apple-app-privacy.html create mode 100644 tests/fixtures/console/apple-app-record-renamed.html create mode 100644 tests/fixtures/console/apple-app-record.html create mode 100644 tests/fixtures/console/play-content-rating.html create mode 100644 tests/fixtures/console/play-target-audience.html create mode 100644 tests/fixtures/console/signin.html create mode 100644 tests/growth-config.test.ts create mode 100644 tests/ppp.test.ts create mode 100644 tests/revenuecat.test.ts create mode 100644 tests/web.test.ts create mode 100644 tools/update-ppp.ts diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index ba3564d3..c40dc47c 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -257,6 +257,39 @@ pub fn dialog_labels(kind: Kind, title: &str) -> (String, String) { } } +/// Dialog of `console.fill` (title, text, button): the answers of its dry run (`data` of `console fill --dry --json`), +/// the uncertain ones marked for the owner, and the note that the owner reviews and saves in the browser. +pub fn console_fill_dialog(project: &str, data: &Value) -> (String, String, String) { + let title = data["title"].as_str().unwrap_or("Console form"); + let mut s = format!("{title} · {project}\n\nA browser window opens on the console page. Sign in there yourself; storebound fills the fields below and marks the ones you answer.\n\n{}\n", policy::CONSOLE_FILL_NOTE); + let answers = data["answers"].as_array().cloned().unwrap_or_default(); + let mut lines: Vec = answers + .iter() + .map(|a| { + let label = a["label"].as_str().unwrap_or_default(); + if a["certain"].as_bool() == Some(true) { + format!("- {label}: {}", a["value"].as_str().unwrap_or_default()) + } else { + format!("- {label}: you answer this") + } + }) + .collect(); + if lines.is_empty() { + lines.push("- (no answers from the config: every field is yours)".into()); + } + let mut list = String::new(); + for (i, l) in lines.iter().enumerate() { + if list.chars().count() + l.chars().count() > DIALOG_CHARS { + list.push_str(&format!("({} more in the app)\n", lines.len() - i)); + break; + } + list.push_str(l); + list.push('\n'); + } + s.push_str(&format!("\nAnswers ({} for you):\n{list}", data["uncertain"].as_u64().unwrap_or(0))); + (format!("Fill in console: {title}"), s, "Open the browser".to_string()) +} + /// Native Apply / Cancel dialog; true on Apply. async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) -> Res { confirm_dialog_with(window, title, text, "Apply".into()).await @@ -304,10 +337,15 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St if dry["ok"] != Value::Bool(true) { return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry })); } - let summary = if kind == Kind::Owner { owner_summary(&d.title, &d.description, &proj.name) } else { dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive) }; - let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default())); + let (title, text, ok) = if method == policy::CONSOLE_FILL { + console_fill_dialog(&proj.name, &dry["data"]) + } else { + let summary = if kind == Kind::Owner { owner_summary(&d.title, &d.description, &proj.name) } else { dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive) }; + let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default())); + let (title, ok) = dialog_labels(kind, &d.title); + (title, text, ok) + }; let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()); - let (title, ok) = dialog_labels(kind, &d.title); if !confirm_dialog_with(&window, title, tilde(&text, home.as_deref()), ok).await? { return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry })); } diff --git a/apps/desktop/src-tauri/src/policy.rs b/apps/desktop/src-tauri/src/policy.rs index 09b2b22b..44d619d8 100644 --- a/apps/desktop/src-tauri/src/policy.rs +++ b/apps/desktop/src-tauri/src/policy.rs @@ -110,6 +110,12 @@ pub fn sanitize_js_call(method: &str, kind: Option, params: &Value) -> Res /// in its own commands: `project_init`, `project_import_fastlane`); `write_with_confirm` never runs them. pub const NEW_FOLDER_METHODS: &[&str] = &["project.init", "import.fastlane"]; +/// `console.fill`: a write whose real run opens a visible browser on a store console form and lasts until the owner +/// closes it. `write_with_confirm` shows its answers and this note instead of a dry-run log; a cancel (`job_cancel`) +/// stops the command, which closes the browser. +pub const CONSOLE_FILL: &str = "console.fill"; +pub const CONSOLE_FILL_NOTE: &str = "Console pages change. This is AI-assisted: review every field in the browser and press Save yourself. storebound never saves, submits or publishes."; + /// Reads that are never kept in the offline cache (big: one rendered image as a data: URL). pub const NO_CACHE_METHODS: &[&str] = &["project.render"]; diff --git a/apps/desktop/src-tauri/tests/d3_writes.rs b/apps/desktop/src-tauri/tests/d3_writes.rs index b5222213..e22ae7f0 100644 --- a/apps/desktop/src-tauri/tests/d3_writes.rs +++ b/apps/desktop/src-tauri/tests/d3_writes.rs @@ -2,9 +2,9 @@ //! after a dialog that names the action on its button and says users see it at once. Tokens are bound to exactly the //! method and the { project, args } sent (the same vector as the TypeScript side checks). use serde_json::json; -use storebound_desktop::commands::{dialog_labels, dialog_summary, owner_summary}; +use storebound_desktop::commands::{console_fill_dialog, dialog_labels, dialog_summary, owner_summary}; use storebound_desktop::confirm::{canonical, mac, mint}; -use storebound_desktop::policy::{sanitize_js_call, Kind}; +use storebound_desktop::policy::{sanitize_js_call, Kind, CONSOLE_FILL, CONSOLE_FILL_NOTE}; #[test] fn owner_actions_are_dry_runs_from_the_window() { @@ -58,3 +58,24 @@ fn tokens_bind_method_project_and_args_of_each_write() { assert!(canonical(&json!({ "percent": 50 })).is_ok()); assert!(canonical(&json!({ "fraction": 0.5 })).is_err()); } + +#[test] +fn console_fill_is_a_dry_run_from_the_window_and_its_dialog_lists_the_answers() { + let p = sanitize_js_call(CONSOLE_FILL, Some(Kind::Write), &json!({ "args": { "form": "apple-age-rating" } })).unwrap(); + assert_eq!(p["dryRun"], json!(true)); + assert!(sanitize_js_call(CONSOLE_FILL, Some(Kind::Write), &json!({ "dryRun": false })).is_err()); + let data = json!({ "title": "Age rating", "uncertain": 1, "answers": [ + { "id": "violence", "label": "Cartoon violence", "value": "None", "certain": true, "source": "apple.ageRating" }, + { "id": "gambling", "label": "Simulated gambling", "value": "", "certain": false, "source": "" }, + ] }); + let (title, text, ok) = console_fill_dialog("Prism Puddle", &data); + assert_eq!(title, "Fill in console: Age rating"); + assert_eq!(ok, "Open the browser"); + assert!(text.contains("Prism Puddle") && text.contains(CONSOLE_FILL_NOTE)); + assert!(text.contains("- Cartoon violence: None") && text.contains("- Simulated gambling: you answer this")); + let (_, empty, _) = console_fill_dialog("A", &json!(null)); + assert!(empty.contains("every field is yours")); + let many: Vec<_> = (0..400).map(|i| json!({ "label": format!("Question {i}"), "value": "Yes", "certain": true })).collect(); + let (_, long, _) = console_fill_dialog("A", &json!({ "title": "T", "answers": many })); + assert!(long.contains("more in the app") && long.chars().count() < 3_200); +} diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index 4a0e26e1..c6acdea4 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -10,7 +10,7 @@ import type { Overrides } from './lib/identity'; export type { AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult, - AnalyticsCompare, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult, + AnalyticsCompare, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult, } from '../../../cli/lib/desktop-protocol'; export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null } diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 41fc83e3..eb26a725 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -3,7 +3,7 @@ // screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window // shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do // not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER). -import { type Account, type AccountCheck, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult, +import { type Account, type AccountCheck, type ConsoleFillResult, type ConsoleForm, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult, 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 type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model'; @@ -409,6 +409,7 @@ function read(method: string, id: string, args: Record = {}): T case 'project.renders': return ok(method, RENDERS[id]); case 'project.render': return ok(method, { file: String(args.file), dataUrl: renderArt(String(args.file)), bytes: 1_200_000 }); case 'prices.current': return ok(method, PRICES[id]); + case 'console.fill': return { ...ok(method, CONSOLE_FILL[args.form as ConsoleForm]), dryRun: true, command: `storebound console fill ${String(args.form)} --dry --json` }; case 'prices.diff': return ok(method, PRICE_DIFF[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)` }; @@ -417,6 +418,24 @@ function read(method: string, id: string, args: Record = {}): T } } +// ---- console.fill: the answers `console fill
--dry --json` would type (made up, from the demo configs) ---- +const CF = (form: ConsoleForm, title: string, url: string, answers: [string, string, string | null, string][], guidance: string[]): ConsoleFillResult => { + const list = answers.map(([id, label, value, source]) => ({ id, label, value: value ?? '', certain: value !== null, source, ...(value === null ? { note: 'Only you know this: answer it in the console' } : {}) })); + return { form, store: form.startsWith('apple') ? 'apple' : 'play', title, url, answers: list, uncertain: list.filter(a => !a.certain).length, guidance }; +}; +const ASC = 'https://appstoreconnect.apple.com/apps', PLAY = 'https://play.google.com/console'; +const CONSOLE_FILL: Record = { + 'apple-app-record': CF('apple-app-record', 'New App', ASC, [['platform', 'Platforms', 'iOS', 'app.platforms'], ['name', 'Name', 'Prism Puddle', 'app.name'], ['language', 'Primary language', 'English (U.S.)', 'languages[0].apple'], + ['bundleId', 'Bundle ID', 'com.example.prismpuddle', 'apple.bundleId'], ['sku', 'SKU', 'prismpuddle', 'apple.sku'], ['access', 'User access', 'Full access', 'default']], ['After Create, copy the Apple ID into apple.appId.']), + 'apple-age-rating': CF('apple-age-rating', 'Age rating', ASC, [['violenceCartoonOrFantasy', 'Cartoon or fantasy violence', 'Infrequent/Mild', 'apple.ageRating'], ['gamblingSimulated', 'Simulated gambling', 'None', 'apple.ageRating'], + ['messagingAndChat', 'Messaging and chat', null, ''], ['advertising', 'Advertising', 'Yes', 'ads.enabled']], ['The age rating follows from your answers; check it before you save.']), + 'apple-app-privacy': CF('apple-app-privacy', 'App Privacy', ASC, [['collects', 'Do you collect data from this app?', 'Yes', 'play.dataSafety'], ['deviceId', 'Device ID', 'Third-party advertising, Analytics', 'play.dataSafety'], + ['linked', 'Device ID linked to the user', null, ''], ['tracking', 'Device ID used for tracking', null, '']], ['App Privacy has no API: publish the answers in App Store Connect yourself.']), + 'play-content-rating': CF('play-content-rating', 'Content rating', PLAY, [['category', 'Category', 'Game', 'app.profile'], ['violence', 'Violence', 'No', 'play.contentRating'], ['userInteraction', 'Users can interact', 'No', 'play.contentRating'], + ['ads', 'Contains ads', 'Yes', 'ads.enabled'], ['purchases', 'Digital purchases', 'Yes', 'products']], ['Submitting the questionnaire is yours; storebound stops before it.']), + 'play-target-audience': CF('play-target-audience', 'Target audience and content', PLAY, [['ages', 'Target age groups', '13-15, 16-17, 18 and over', 'play.targetAudience'], ['appeal', 'Could appeal to children', null, '']], []), +}; + const CACHED_AGO: Record = { health: 60 * 3, 'reviews.list': 45, 'apple.testflight_status': 60 * 5, 'catalog.diff': 60 * 26, validate: 60 * 2, 'prices.current': 60 * 4, 'apple.ppo_status': 60 * 6 }; const NETWORK = new Set(['health', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'prices.current', 'prices.diff', 'apple.ppo_status']); @@ -497,6 +516,15 @@ async function answer(cmd: string, a: Record): Promise case 'job_cancel': cancelled.add(a.job as string); return true; case 'write_with_confirm': { const method = a.method as string, args = (a.args ?? {}) as Record; + if (method === 'console.fill') { + // the real run lasts until the owner closes the browser: here a few seconds, or until Cancel + const r = CONSOLE_FILL[args.form as ConsoleForm]; + await progressLines(job, ['[console] opening Chromium (profile in ~/.storebound/console-profile/apple)', '[console] waiting for you to sign in', `[console] ${r.title}: filling ${r.answers.length - r.uncertain} fields`, `[console] ${r.uncertain} fields marked for you`]); + for (let i = 0; i < 20 && !(job && cancelled.has(job)); i++) await sleep(250); + if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; + const res: ToolResult = { method, ok: true, exitCode: 0, dryRun: false, command: `storebound console fill ${String(args.form)} --json`, output: '[console] browser closed', data: { ...r, filled: r.answers.length - r.uncertain, highlighted: r.uncertain, fallback: false, stoppedAt: null } }; + return { confirmed: true, stage: 'done', dryRun: { ...res, dryRun: true, data: r }, result: res }; + } await progressLines(job, [`[${method}] dry run`, `[${method}] confirmed in the dialog`, `[${method}] applying`]); if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; const d = DRAFTS[a.projectId as string]?.drafts.find(x => x.file.endsWith(`/${String(args.file)}`)); diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 3c3b80df..5ed02c9a 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1249,4 +1249,37 @@ export const en = { 'folder.locateFailed': 'Could not use that folder', 'folder.remove': 'Remove from list', 'folder.removed': '{name} removed from the list', + + 'cf.button': 'Fill in console', + 'cf.hint': 'Fill in {form} in the console from your config: you review every field and press Save yourself', + 'cf.appleAppRecord': 'App Store app record', + 'cf.appleAgeRating': 'App Store age rating', + 'cf.appleAppPrivacy': 'App Privacy', + 'cf.playContentRating': 'Play content rating', + 'cf.playTargetAudience': 'Play target audience and content', + 'cf.dryFailed': 'Could not prepare {form}', + 'cf.panelTitle': 'Fill in console: {form}', + 'cf.disclaimer': 'Console pages change. This is AI-assisted: review every field in the browser and press Save yourself. storebound never saves, submits or publishes.', + 'cf.notOpened': 'You chose Cancel in the dialog: no browser was opened.', + 'cf.runningText': 'The browser is open. Sign in there yourself; storebound fills the fields and marks the ones you answer. Review every field, press Save yourself, then close the browser.', + 'cf.doneText': 'Browser closed. Filled: {filled}, marked for you: {highlighted}. Check in the console that your answers are saved.', + 'cf.closed': 'Browser closed.', + 'cf.cancelled': 'Stopped: the browser was closed.', + 'cf.failed': 'The browser run stopped', + 'cf.fallback': 'The page did not look as expected, so storebound only marked the fields. Enter the answers yourself.', + 'cf.answers': '{count} answers from your config', + 'cf.answers_one': '1 answer from your config', + 'cf.uncertain': '{count} for you', + 'cf.noAnswers': 'The config has no answers for this form: every field is yours.', + 'cf.youAnswer': 'You answer this', + 'cf.foot': 'A native dialog asks once more before the browser opens.', + 'cf.cancelRun': 'Cancel: close the browser', + 'cf.open': 'Open the browser', + 'cf.waiting': 'Waiting until you close the browser', + 'cf.playTitle': 'Play Console questionnaires', + 'cf.playSub': 'No API: storebound fills them in the console, you save', + 'cf.playContentRatingText': 'The IARC questionnaire that gives the app its age ratings.', + 'cf.playTargetAudienceText': 'Target age groups and whether the app appeals to children.', + 'cf.noRecordTitle': 'No App Store app record yet', + 'cf.noRecordText': 'App Store Connect has no API to create the app record. storebound fills the New App form from your config; you press Create yourself, then put the Apple ID into apple.appId.', } as const; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 1669f588..c0ad56b9 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1251,4 +1251,37 @@ export const tr: Record = { 'folder.locateFailed': 'Bu klasör kullanılamadı', 'folder.remove': 'Listeden kaldır', 'folder.removed': '{name} listeden kaldırıldı', + + 'cf.button': 'Konsolda doldur', + 'cf.hint': '{form} formunu yapılandırmanızdan konsolda doldurur: her alanı siz kontrol eder, Kaydet\'e kendiniz basarsınız', + 'cf.appleAppRecord': 'App Store uygulama kaydı', + 'cf.appleAgeRating': 'App Store yaş derecelendirmesi', + 'cf.appleAppPrivacy': 'Uygulama Gizliliği', + 'cf.playContentRating': 'Play içerik derecelendirmesi', + 'cf.playTargetAudience': 'Play hedef kitle ve içerik', + 'cf.dryFailed': '{form} hazırlanamadı', + 'cf.panelTitle': 'Konsolda doldur: {form}', + 'cf.disclaimer': 'Konsol sayfaları değişebilir. Bu, yapay zekâ destekli bir yardımdır: tarayıcıda her alanı kontrol edin ve Kaydet\'e kendiniz basın. storebound hiçbir zaman kaydetmez, göndermez veya yayınlamaz.', + 'cf.notOpened': 'İletişim kutusunda Vazgeç\'i seçtiniz: tarayıcı açılmadı.', + 'cf.runningText': 'Tarayıcı açık. Orada kendiniz oturum açın; storebound alanları doldurur ve yanıtı size kalanları işaretler. Her alanı kontrol edin, Kaydet\'e kendiniz basın ve ardından tarayıcıyı kapatın.', + 'cf.doneText': 'Tarayıcı kapandı. Doldurulan: {filled}, sizin için işaretlenen: {highlighted}. Yanıtlarınızın kaydedildiğini konsolda kontrol edin.', + 'cf.closed': 'Tarayıcı kapandı.', + 'cf.cancelled': 'Durduruldu: tarayıcı kapatıldı.', + 'cf.failed': 'Tarayıcı çalışması durdu', + 'cf.fallback': 'Sayfa beklendiği gibi görünmedi, bu yüzden storebound yalnızca alanları işaretledi. Yanıtları kendiniz girin.', + 'cf.answers': 'Yapılandırmanızdan {count} yanıt', + 'cf.answers_one': 'Yapılandırmanızdan 1 yanıt', + 'cf.uncertain': '{count} tanesi sizde', + 'cf.noAnswers': 'Yapılandırmada bu form için yanıt yok: tüm alanlar size kalıyor.', + 'cf.youAnswer': 'Bunu siz yanıtlayın', + 'cf.foot': 'Tarayıcı açılmadan önce bir sistem iletişim kutusu bir kez daha sorar.', + 'cf.cancelRun': 'Vazgeç: tarayıcıyı kapat', + 'cf.open': 'Tarayıcıyı aç', + 'cf.waiting': 'Tarayıcıyı kapatmanız bekleniyor', + 'cf.playTitle': 'Play Console anketleri', + 'cf.playSub': 'API yok: storebound bunları konsolda doldurur, siz kaydedersiniz', + 'cf.playContentRatingText': 'Uygulamanın yaş derecelendirmelerini belirleyen IARC anketi.', + 'cf.playTargetAudienceText': 'Hedef yaş grupları ve uygulamanın çocuklara hitap edip etmediği.', + 'cf.noRecordTitle': 'Henüz App Store uygulama kaydı yok', + 'cf.noRecordText': 'App Store Connect\'te uygulama kaydı oluşturmak için bir API yok. storebound Yeni Uygulama formunu yapılandırmanızdan doldurur; Oluştur\'a kendiniz basar, ardından Apple kimliğini apple.appId alanına yazarsınız.', }; diff --git a/apps/desktop/src/screens/tabs/AppInfo.tsx b/apps/desktop/src/screens/tabs/AppInfo.tsx index bd466abf..fb682f00 100644 --- a/apps/desktop/src/screens/tabs/AppInfo.tsx +++ b/apps/desktop/src/screens/tabs/AppInfo.tsx @@ -2,6 +2,8 @@ // question only the owner can answer at the top. Google Play Data safety (upload: dry run, native dialog, real run; // Play cannot read the form back, so the tab compares with the CSV storebound uploaded last), App Store App Privacy // (no API: the answers to enter in App Store Connect), app info, export compliance and the App Review details. +// The forms without an API (App Privacy, age rating, the Play questionnaires, a missing App Store app record) have a +// "Fill in console" button (ui/ConsoleFill.tsx): storebound fills them in a visible browser, the owner saves. import { useState } from 'react'; import { api, type DeclarationsResult, type DeclAsk, type Project } from '../../api'; import { type Key, t } from '../../i18n'; @@ -10,6 +12,7 @@ import { ago, num } from '../../lib/format'; import { useData, useRead, useWrite } from '../../store'; import { useExports, useRunExport } from '../../ui/Exports'; import { Icon, StoreGlyph } from '../../ui/icons'; +import { ConsoleFillButton } from '../../ui/ConsoleFill'; import { Bar, Card, Chip, Empty, ErrorNotice, Notice, Skeleton } from '../../ui/kit'; import { WriteButton } from '../../ui/WriteButton'; import { ascUrl } from '../AppView'; @@ -93,12 +96,15 @@ function DataSafety({ project, d, onDone }: { project: Project; d: DeclarationsR ); } -function AppPrivacy({ d, appId }: { d: DeclarationsResult; appId: string | null | undefined }) { +function AppPrivacy({ project, d, appId }: { project: Project; d: DeclarationsResult; appId: string | null | undefined }) { const ap = d.appPrivacy; if (!ap) return null; return ( {t('ai.apSub')}} pad={false} - actions={}> + actions={<> + + + }>
{t('ai.apNote')}
{!ap.items.length ? {ap.fromDataSafety ? t('ai.apNoneText') : t('ai.apUnknownText')} : ( @@ -138,14 +144,22 @@ export function AppInfoTab({ project }: { project: Project }) { return ( <> + {d.stores.apple && e?.app?.platforms.ios && !e.app.platforms.ios.ascAppId && ( + }> +
{t('cf.noRecordTitle')}{t('cf.noRecordText')}
+
+ )}
{d.stores.play ? : {t('ai.noPlayText')}} - {d.stores.apple ? : {t('ai.noAppleText')}} + {d.stores.apple ? : {t('ai.noAppleText')}}
{d.stores.apple && (
{t('ai.push')}}> + actions={<> + {t('ai.push')} + + }>
{t('ai.category')}
{cat ?? {t('ai.notSet')}}
{t('ai.age')}
{info!.ageRating.length ? {info!.ageRating.map(a => `${a.question} = ${a.value}`).join(', ')} : {t('ai.ageAllNone')}}
@@ -178,6 +192,19 @@ export function AppInfoTab({ project }: { project: Project }) {
)} + {d.stores.play && ( + {t('cf.playSub')}} pad={false}> +
+ {([['play-content-rating', 'cf.playContentRating', 'cf.playContentRatingText'], ['play-target-audience', 'cf.playTargetAudience', 'cf.playTargetAudienceText']] as const).map(([form, title, text]) => ( +
+ +
{t(title)}{t(text)}
+ +
+ ))} +
+
+ )}

{t('ai.foot', { when: ago(r.at) })}

); diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index 66c42d7e..ab629163 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -878,6 +878,13 @@ textarea.input { height: auto; padding: 8px 10px; line-height: 1.45; resize: ver .lb-img .stack { width: 320px; } .lb-foot { display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--line); } .lb-foot .grow { flex: 1; min-width: 0; display: grid; gap: 2px; } +/* "Fill in console" panel (ui/ConsoleFill.tsx): the answers of the dry run, then the run's progress */ +.cf-panel { width: min(680px, 100%); } +.cf-body { min-height: 0; overflow: auto; padding: 20px 22px; gap: 14px; } +.cf-body h2 { font-size: var(--t-section); font-weight: 660; } +.cf-table td:first-child { padding-left: 0; } +.cf-table td:last-child { padding-right: 0; text-align: right; } +.cf-guidance { font-size: var(--t-meta); } /* growth chart */ .lchart { display: grid; gap: 8px; } diff --git a/apps/desktop/src/ui/ConsoleFill.tsx b/apps/desktop/src/ui/ConsoleFill.tsx new file mode 100644 index 00000000..ff45d14e --- /dev/null +++ b/apps/desktop/src/ui/ConsoleFill.tsx @@ -0,0 +1,130 @@ +// "Fill in console": the store forms without an API (App Store app record, age rating, App Privacy; Play content +// rating, target audience). Click -> dry run of `console.fill` (the answers from the config, nothing opens) -> this +// panel lists them, the uncertain ones marked for the owner, with the disclaimer -> "Open the browser" goes through +// write_with_confirm (the host shows the answers again in a native dialog and mints the token only on its button) -> +// a visible browser the owner signs in to; storebound fills the fields and never saves, submits or publishes. The run +// lasts until the owner closes that browser; Cancel here stops the command, which closes it. +import { type KeyboardEvent, useEffect, useRef, useState } from 'react'; +import { api, type ConsoleFillResult, type ConsoleForm, errorText, newJob, onProgress, type Project, type ToolResult } from '../api'; +import { type Key, t } from '../i18n'; +import { useData } from '../store'; +import { Icon, StoreGlyph } from './icons'; +import { Chip, Notice } from './kit'; + +export const CONSOLE_FORM_NAME: Record = { + 'apple-app-record': 'cf.appleAppRecord', 'apple-age-rating': 'cf.appleAgeRating', 'apple-app-privacy': 'cf.appleAppPrivacy', + 'play-content-rating': 'cf.playContentRating', 'play-target-audience': 'cf.playTargetAudience', +}; + +type Stage = + | { s: 'idle' } + | { s: 'dry' } + | { s: 'review'; data: ConsoleFillResult; note?: string } + | { s: 'running'; data: ConsoleFillResult; job: string; lines: string[] } + | { s: 'done'; data: ConsoleFillResult; result: ConsoleFillResult | null; ok: boolean; detail?: string }; + +const tail = (out: string): string => out.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? ''; + +export function ConsoleFillButton({ project, form, small = true, primary }: { project: Project; form: ConsoleForm; small?: boolean; primary?: boolean }) { + const d = useData(); + const [st, setSt] = useState({ s: 'idle' }); + const name = t(CONSOLE_FORM_NAME[form]); + + const start = async () => { + setSt({ s: 'dry' }); + try { + const r = await api.call('console.fill', project.id, { args: { form } }, newJob('console.fill-dry')); + if (!r.ok || !r.data) { setSt({ s: 'idle' }); d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: tail(r.output) || undefined }); return; } + setSt({ s: 'review', data: r.data }); + } catch (e) { + setSt({ s: 'idle' }); + d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: errorText(e) }); + } + }; + + const open = async (data: ConsoleFillResult) => { + const job = newJob('console.fill'); + setSt({ s: 'running', data, job, lines: [] }); + const un = onProgress(p => { + if (p.job !== job || !p.line?.trim()) return; + setSt(x => (x.s === 'running' && x.job === job ? { ...x, lines: [...x.lines, p.line!].slice(-12) } : x)); + }); + try { + const o = await api.writeWithConfirm('console.fill', project.id, { form }, job); + if (o.stage === 'dialog') setSt({ s: 'review', data, note: t('cf.notOpened') }); + else if (o.stage === 'dry-run') setSt({ s: 'done', data, result: null, ok: false, detail: tail(o.dryRun.output) }); + else { + const res = (o.result?.data ?? null) as ConsoleFillResult | null; + setSt({ s: 'done', data, result: res, ok: !!o.result?.ok, detail: o.result?.ok ? undefined : tail(o.result?.output ?? '') }); + } + } catch (e) { + const msg = errorText(e); + setSt({ s: 'done', data, result: null, ok: /cancel/i.test(msg), detail: /cancel/i.test(msg) ? t('cf.cancelled') : msg }); + } finally { un.then(f => f()); } + }; + + const busy = st.s === 'dry'; + return ( + <> + + {(st.s === 'review' || st.s === 'running' || st.s === 'done') && ( + { open(st.data); }} onCancel={() => { if (st.s === 'running') api.cancel(st.job).catch(() => {}); }} onClose={() => setSt({ s: 'idle' })} /> + )} + + ); +} + +function FillPanel({ st, name, onOpen, onCancel, onClose }: { + st: Extract; name: string; onOpen: () => void; onCancel: () => void; onClose: () => void; +}) { + const root = useRef(null); + useEffect(() => { root.current?.focus(); }, []); + const running = st.s === 'running'; + const data = st.data; + const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !running) { e.preventDefault(); onClose(); } }; + return ( +
{ if (e.target === e.currentTarget && !running) onClose(); }}> +
+
+
+

{t('cf.panelTitle', { form: data.title || name })}

+ {data.store === 'apple' ? 'App Store Connect' : 'Google Play Console'} +
+ {t('cf.disclaimer')} + {st.s === 'review' && st.note && {st.note}} + {running && {t('cf.runningText')}} + {st.s === 'done' && (st.ok + ? {st.result ? t('cf.doneText', { filled: st.result.filled ?? 0, highlighted: st.result.highlighted ?? 0 }) : st.detail ?? t('cf.closed')} + : {t('cf.failed')}{st.detail ? `: ${st.detail}` : ''})} + {st.s === 'done' && st.result?.fallback ? {t('cf.fallback')} : null} +
+
{t('cf.answers', { count: data.answers.length })}{data.uncertain > 0 && {t('cf.uncertain', { count: data.uncertain })}}
+ {!data.answers.length ? {t('cf.noAnswers')} : ( +
+ + {data.answers.map(a => ( + + + + + ))} + +
{a.label}
{(a.note || a.source) &&
{a.note ?? a.source}
}
{a.certain ? {a.value} : {t('cf.youAnswer')}}
+ )} + + {data.guidance.length > 0 &&
    {data.guidance.map((g, i) =>
  • {g}
  • )}
} + {running && st.lines.length > 0 &&
{st.lines.join('\n')}
} + +
+
{st.s === 'review' ? t('cf.foot') : null}
+ {running ? : } + {st.s === 'review' && } + {running && {t('cf.waiting')}} +
+ + + ); +} diff --git a/cli/ads/apple.ts b/cli/ads/apple.ts new file mode 100644 index 00000000..c6fcd09a --- /dev/null +++ b/cli/ads/apple.ts @@ -0,0 +1,202 @@ +// Apple Ads (formerly Apple Search Ads) for the app's App Store campaigns. +// storebound ads apple status [--json] token works?, ad accounts and roles (GET /v1/acls), the one used +// storebound ads apple campaigns [--all] [--json] App Store campaigns: status, daily budget, countries, adamId +// storebound ads apple report [--days 7 | --start YYYY-MM-DD --end YYYY-MM-DD] [--by campaign|keyword] [--campaign ] +// [--adgroup ] [--all] [--csv ] [--dry] [--json] +// spend, impressions, taps, installs, TTR, conversion rate, CPA (spend / installs), avg CPT; totals. Read-only. +// storebound ads apple bid --keyword --bid [--campaign ] [--adgroup ] [--dry] [--yes] +// storebound ads apple budget --campaign --daily [--dry] [--yes] +// storebound ads apple pause --campaign [--adgroup ] [--dry] [--yes] +// Writes read the current value first, print "old -> new", and only without --dry ask in the terminal (confirm) before +// the PUT. They are the owner's decisions (money): never offered over MCP, refused under `storebound serve`. +// Report and campaign lists default to the campaigns of config apple.appId (when set); --all shows every app's. +// Credentials and API: cli/ads/client.ts. API: Apple Ads Platform API (https://api.ads.apple.com/v1), which replaces +// the Campaign Management API v5 (sunset January 26, 2027). +// Sources (checked October 2026): the doc URLs in cli/lib/apple-ads.ts, plus +// https://developer.apple.com/documentation/apple-ads-platform-api/post-campaigns-query (pageSize cap 1000) +// https://developer.apple.com/documentation/apple-ads-platform-api/put-campaigns-_id_ (status / dailyBudget examples) +// https://developer.apple.com/documentation/apple-ads-platform-api/put-keywords-_id_ (bid example; bid null is an error) +// https://developer.apple.com/documentation/apple-ads-platform-api/put-adgroups-_id_ (status) +import { writeFileSync } from 'node:fs'; +import { type AclRow, aclRows, campaignQuery, campaignRow, type CampaignRow, canWrite, changeLine, dailyBudgetBody, flattenRows, type J, keywordBidBody, + nextOffset, parseAmount, pauseBody, reportBody, reportCsv, type ReportRow, reportTable, reportWindow, totals } from '../lib/apple-ads'; +import { confirm, type Ctx } from '../lib/ctx'; +import { done, log, printJson, warn } from '../lib/log'; +import { textTable } from '../lib/table'; +import { adsClient, type Ads } from './client'; + +const TAG = 'ads apple'; +const SUBS = ['status', 'campaigns', 'report', 'bid', 'budget', 'pause']; + +const idArg = (ctx: Ctx, name: string, required: boolean): string | undefined => { + const v = ctx.args.get(name); + if (v === undefined || v === 'true') { if (required) throw new Error(`--${name} is required`); return undefined; } + if (!/^\d+$/.test(v)) throw new Error(`--${name}: a numeric id`); + return v; +}; + +async function allCampaigns(ads: Ads): Promise { + const out: J[] = []; + for (let offset: number | null = 0; offset !== null;) { + const page: J = await ads.post('/campaigns/query', campaignQuery(offset)); + out.push(...(page.result ?? [])); + offset = (page.result ?? []).length ? nextOffset(page) : null; + } + return out; +} + +/** The campaigns a report / list covers: one by id, else the app's (config apple.appId) unless --all or none match. */ +async function pickCampaigns(ctx: Ctx, ads: Ads, quiet: boolean): Promise { + const id = idArg(ctx, 'campaign', false); + if (id) return [(await ads.get(`/campaigns/${id}`)).result]; + const all = await allCampaigns(ads); + const appId = ctx.loaded.config.apple?.appId; + if (!appId || ctx.args.has('all')) return all; + const mine = all.filter(c => String(c.promotedObjectId) === String(appId)); + if (!mine.length && all.length && !quiet) warn(TAG, `no campaign promotes apple.appId ${appId}: showing all ${all.length}`); + return mine.length ? mine : all; +} + +async function status(ctx: Ctx, ads: Ads, json: boolean): Promise { + await ads.token(); + const accounts: AclRow[] = aclRows(await ads.get('/acls', false), ads.accountId); + const used = accounts.find(a => a.used) ?? null; + const account = ads.accountId ? (await ads.get(`/ad-accounts/${ads.accountId}`)).result ?? null : null; + const out = { + token: true, accountId: ads.accountId ?? null, accounts, + account: account && { id: String(account.id), name: account.name, currency: account.currency, timezone: account.timezone, systemStatus: account.systemStatus, + systemStatusReasons: account.systemStatusReasons ?? [], productFeatures: account.productFeatures ?? [] }, + canWrite: used ? canWrite(used.roles) : false, + }; + if (json) return printJson(out); + log(TAG, 'token: ok (OAuth client credentials)'); + if (!accounts.length) warn(TAG, 'no ad accounts for this API user (Apple Ads > Account Settings > User Management: give it an API role on an account)'); + else console.log(textTable(['', 'ad account', 'id', 'org', 'roles'], accounts.map(a => [a.used ? '*' : '', a.name, a.accountId, a.orgId, a.roles.join(', ')]))); + if (!ads.accountId) { log(TAG, 'APPLE_ADS_ACCOUNT_ID is not set: put one of the ids above in the env or .storebound/credentials.json'); return; } + if (!used) warn(TAG, `APPLE_ADS_ACCOUNT_ID ${ads.accountId} is not in the list above: this API user has no role on it`); + if (out.account) { + const a = out.account; + log(TAG, `using ${a.name} (${a.id}): ${a.currency}, ${a.timezone}, ${a.systemStatus}${a.systemStatusReasons.length ? ' ' + a.systemStatusReasons.join(', ') : ''}, ${a.productFeatures.join(', ') || 'no product features'}`); + if (!a.productFeatures.includes('APPSTORE_APP_MANUAL')) warn(TAG, 'this ad account is not an App Store account (APPSTORE_APP_MANUAL)'); + } + log(TAG, out.canWrite ? 'role allows bid / budget / pause changes (each one still asks first)' : 'read-only role: reports and lists only'); +} + +async function campaigns(ctx: Ctx, ads: Ads, json: boolean): Promise { + const appId = ctx.loaded.config.apple?.appId; + const rows: CampaignRow[] = (await pickCampaigns(ctx, ads, json)).map(c => campaignRow(c, appId)); + if (json) return printJson({ accountId: ads.accountId, appId: appId ?? null, campaigns: rows }); + if (!rows.length) return log(TAG, 'no App Store campaigns in this ad account'); + console.log(textTable(['', 'id', 'campaign', 'status', 'display', 'daily budget', 'bidding', 'countries', 'adamId'], + rows.map(r => [r.thisApp ? '*' : '', r.id, r.name, r.status, r.displayStatus, r.dailyBudget ? `${r.dailyBudget} ${r.currency}` : '', r.bidStrategy, r.countries.join(' '), r.adamId]))); + if (appId) log(TAG, `* = promotes apple.appId ${appId}`); +} + +async function report(ctx: Ctx, ads: Ads, json: boolean): Promise { + const by = ctx.args.str('by', 'campaign'); + if (by !== 'campaign' && by !== 'keyword') throw new Error('--by campaign | keyword'); + const w = reportWindow({ days: ctx.args.has('days') ? ctx.args.num('days', 7) : undefined, start: ctx.args.get('start'), end: ctx.args.get('end') }); + const adGroupId = idArg(ctx, 'adgroup', false); + const camps = await pickCampaigns(ctx, ads, json); + const names = new Map(camps.map(c => [String(c.id), String(c.name ?? '')] as const)); + const rows: ReportRow[] = []; + for (const c of camps) { + for (let offset: number | null = 0; offset !== null;) { + const res: J = await ads.post(`/reports/apps/${by === 'campaign' ? 'campaigns' : 'keywords'}/query`, reportBody({ ...w, campaignId: String(c.id), adGroupId: by === 'keyword' ? adGroupId : undefined, offset })); + const got = flattenRows(by, res, names); + rows.push(...got); + offset = got.length ? nextOffset(res) : null; + } + } + rows.sort((a, b) => b.spend - a.spend); + const t = totals(rows); + const csv = ctx.args.get('csv'); + if (csv === 'true') throw new Error('--csv '); + if (csv) { + const path = ctx.loaded.resolve(csv); + if (ctx.args.has('dry')) { if (!json) log(TAG, `dry run: would write ${rows.length} row(s) to ${path}`); } + else { writeFileSync(path, reportCsv(rows)); if (!json) log(TAG, `wrote ${rows.length} row(s) to ${path}`); } + } + if (json) return printJson({ accountId: ads.accountId, by, start: w.start, end: w.end, timeZone: 'UTC', campaigns: camps.length, rows, totals: t }); + log(TAG, `${by} report ${w.start} .. ${w.end} (UTC), ${camps.length} campaign(s), ${rows.length} row(s) with activity`); + if (!rows.length) return log(TAG, 'no spend, impressions or taps in this window'); + console.log(reportTable(rows, t)); + if (t.installs === 0 && t.spend > 0) log(TAG, 'CPA n/a: no installs in this window'); +} + +interface Plan { action: 'bid' | 'budget' | 'pause'; target: string; path: string; body: J; old: string | null; new: string; currency: string; applied: boolean } + +async function apply(ctx: Ctx, ads: Ads, json: boolean, p: Plan, unchanged: boolean): Promise { + const say = (m: string) => { if (!json) log(TAG, m); }; + say(`${p.action}: ${p.target}: ${p.action === 'pause' ? `${p.old} -> ${p.new}` : changeLine(p.old, p.new, p.currency)}`); + if (unchanged) { say('already at that value: nothing to change'); return json ? printJson(p) : undefined; } + if (ctx.args.has('dry')) { say(`dry run: would PUT ${p.path} ${JSON.stringify(p.body)}`); return json ? printJson(p) : undefined; } + if (!(await confirm(ctx, `Apply this ${p.action} change in Apple Ads (${p.target})?`))) { say('not changed'); return json ? printJson(p) : undefined; } + await ads.put(p.path, p.body); + p.applied = true; + if (json) return printJson(p); + done(TAG, `${p.action} applied`); +} + +async function bid(ctx: Ctx, ads: Ads, json: boolean): Promise { + const kid = idArg(ctx, 'keyword', true)!; + const amount = parseAmount(ctx.args.get('bid'), '--bid'); + const kw = (await ads.get(`/keywords/${kid}`)).result; + if (!kw || kw.deleted) throw new Error(`keyword ${kid} not found or deleted`); + const camp = idArg(ctx, 'campaign', false), group = idArg(ctx, 'adgroup', false); + if (camp && String(kw.campaignId) !== camp) throw new Error(`keyword ${kid} belongs to campaign ${kw.campaignId}, not ${camp}`); + if (group && String(kw.adGroupId) !== group) throw new Error(`keyword ${kid} belongs to ad group ${kw.adGroupId}, not ${group}`); + const c = (await ads.get(`/campaigns/${kw.campaignId}`)).result; + if (c?.bidStrategy?.bidStrategyType === 'MAX_CONVERSIONS') throw new Error(`campaign ${kw.campaignId} uses Maximize Conversions: keyword bids are not used there`); + const currency = String(kw.bid?.currency ?? c?.dailyBudget?.value?.currency ?? ''); + if (!currency) throw new Error('could not tell the account currency from the keyword or its campaign'); + const old = kw.bid?.amount != null ? String(kw.bid.amount) : null; + await apply(ctx, ads, json, { action: 'bid', target: `keyword "${kw.text}" (${kw.matchType}, ${kid}) in "${c?.name ?? kw.campaignId}"`, path: `/keywords/${kid}`, + body: keywordBidBody(amount, currency), old, new: amount, currency, applied: false }, old !== null && Number(old) === Number(amount)); +} + +async function budget(ctx: Ctx, ads: Ads, json: boolean): Promise { + const id = idArg(ctx, 'campaign', true)!; + const amount = parseAmount(ctx.args.get('daily'), '--daily'); + const c = (await ads.get(`/campaigns/${id}`)).result; + if (!c || c.deleted) throw new Error(`campaign ${id} not found or deleted`); + const currency = String(c.dailyBudget?.value?.currency ?? ''); + if (!currency) throw new Error(`campaign ${id} has no daily budget currency`); + const old = c.dailyBudget?.value?.amount != null ? String(c.dailyBudget.value.amount) : null; + await apply(ctx, ads, json, { action: 'budget', target: `daily budget of "${c.name}" (${id})`, path: `/campaigns/${id}`, body: dailyBudgetBody(amount, currency), + old, new: amount, currency, applied: false }, old !== null && Number(old) === Number(amount)); +} + +async function pause(ctx: Ctx, ads: Ads, json: boolean): Promise { + const id = idArg(ctx, 'campaign', true)!; + const group = idArg(ctx, 'adgroup', false); + const c = (await ads.get(`/campaigns/${id}`)).result; + if (!c || c.deleted) throw new Error(`campaign ${id} not found or deleted`); + let target = `campaign "${c.name}" (${id})`, path = `/campaigns/${id}`, old = String(c.status ?? ''); + if (group) { + const g = (await ads.get(`/adgroups/${group}`)).result; + if (!g || g.deleted) throw new Error(`ad group ${group} not found or deleted`); + if (String(g.campaignId) !== id) throw new Error(`ad group ${group} belongs to campaign ${g.campaignId}, not ${id}`); + target = `ad group "${g.name}" (${group}) in "${c.name}"`; path = `/adgroups/${group}`; old = String(g.status ?? ''); + } + await apply(ctx, ads, json, { action: 'pause', target, path, body: pauseBody(), old, new: 'PAUSED', currency: '', applied: false }, old === 'PAUSED'); +} + +export async function run(ctx: Ctx): Promise { + const sub = ctx.args._[0]; + const json = ctx.args.has('json'); + if (!sub || ctx.args.has('help') || !SUBS.includes(sub)) { + console.log(`usage: storebound ads apple ${SUBS.join(' | ')} (see the apple-ads skill)`); + if (sub && !SUBS.includes(sub) && !ctx.args.has('help')) process.exitCode = 2; + return; + } + const ads = adsClient(ctx.loaded.root); + switch (sub) { + case 'status': return status(ctx, ads, json); + case 'campaigns': return campaigns(ctx, ads, json); + case 'report': return report(ctx, ads, json); + case 'bid': return bid(ctx, ads, json); + case 'budget': return budget(ctx, ads, json); + case 'pause': return pause(ctx, ads, json); + } +} diff --git a/cli/ads/client.ts b/cli/ads/client.ts new file mode 100644 index 00000000..65561fb1 --- /dev/null +++ b/cli/ads/client.ts @@ -0,0 +1,71 @@ +// Apple Ads Platform API client: OAuth client credentials (an ES256 client secret signed with the key uploaded in +// Apple Ads > Account Settings > API), Bearer calls with X-AP-Context: adAccountId=, retries on 429 / 5xx. +// The access token lives in memory for this process only (never written to disk, never printed). +// Credentials (env, else .storebound/credentials.json): APPLE_ADS_CLIENT_ID, APPLE_ADS_TEAM_ID, APPLE_ADS_KEY_ID, +// APPLE_ADS_PRIVATE_KEY (path to the PEM, or the PEM itself), APPLE_ADS_ACCOUNT_ID (optional for `status`). +// Sources (checked October 2026): see cli/lib/apple-ads.ts; retries per +// https://developer.apple.com/documentation/apple-ads-platform-api/rate-limits (Retry-After on 429). +import { createPrivateKey, type KeyObject } from 'node:crypto'; +import { credentialValue, inline } from '../lib/credentials'; +import { ADS_API, adsHeaders, type AdsCreds, clientSecret, type J, TOKEN_URL, tokenForm } from '../lib/apple-ads'; +import { errorBody } from '../lib/http'; + +export const CRED_NAMES = ['APPLE_ADS_CLIENT_ID', 'APPLE_ADS_TEAM_ID', 'APPLE_ADS_KEY_ID', 'APPLE_ADS_PRIVATE_KEY'] as const; + +export function adsCreds(root: string): AdsCreds { + // the template's placeholders (templates/credentials.example.json, copied by `storebound init`) count as not set + const v = (n: string) => { const x = credentialValue(root, n); return x && !/00000000-0000-0000|\/absolute\/path\/to\//.test(x) ? x : undefined; }; + const missing = CRED_NAMES.filter(n => !v(n)); + if (missing.length) throw new Error(`${missing.join(', ')} not set (env, or .storebound/credentials.json); see the apple-ads skill`); + let pem: string; + try { pem = inline(v('APPLE_ADS_PRIVATE_KEY')!, /BEGIN (EC )?PRIVATE KEY/); } catch { throw new Error('APPLE_ADS_PRIVATE_KEY: the private key file could not be read (set a path to the PEM, or the PEM itself)'); } + return { clientId: v('APPLE_ADS_CLIENT_ID')!, teamId: v('APPLE_ADS_TEAM_ID')!, keyId: v('APPLE_ADS_KEY_ID')!, pem, accountId: v('APPLE_ADS_ACCOUNT_ID') }; +} + +/** Seconds to wait before retry `attempt` (1-based): Retry-After when the server sends it, else 2, 4, 8, 16. */ +export const retryWait = (retryAfter: string | null, attempt: number): number => { + const s = Number(retryAfter); + return Number.isFinite(s) && s >= 0 && retryAfter !== null && retryAfter !== '' ? Math.min(s, 60) : Math.min(2 ** attempt, 16); +}; + +export type Ads = ReturnType; + +export function adsClient(root: string, o: { sleep?: (ms: number) => Promise } = {}) { + const c = adsCreds(root); + let key: KeyObject; + try { key = createPrivateKey(c.pem); } catch { throw new Error('APPLE_ADS_PRIVATE_KEY is not a valid EC private key (PEM)'); } + const sleep = o.sleep ?? ((ms: number) => Bun.sleep(ms)); + let cached = { token: '', until: 0 }; + + async function token(): Promise { + if (cached.token && Date.now() < cached.until) return cached.token; + const r = await fetch(TOKEN_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: tokenForm(c.clientId, clientSecret(c, key)).toString() }); + const t = await r.text(); + // the answer may echo the request; only the status and Apple's error code are shown + if (!r.ok) { let code = ''; try { code = String(JSON.parse(t).error ?? ''); } catch { /* not JSON */ } throw new Error(`Apple Ads token request -> ${r.status}${code ? ' ' + code : ''} (check APPLE_ADS_CLIENT_ID / TEAM_ID / KEY_ID and that the uploaded public key matches APPLE_ADS_PRIVATE_KEY)`); } + const j = JSON.parse(t) as { access_token?: string; expires_in?: number }; + if (!j.access_token) throw new Error('Apple Ads token request: no access_token in the answer'); + cached = { token: j.access_token, until: Date.now() + Math.max(60, (j.expires_in ?? 3600) - 120) * 1000 }; + return cached.token; + } + + async function call(method: string, path: string, body?: unknown, scoped = true): Promise { + if (scoped && !c.accountId) throw new Error('APPLE_ADS_ACCOUNT_ID is not set: run `storebound ads apple status` to list your ad accounts'); + for (let attempt = 1; ; attempt++) { + const r = await fetch(ADS_API + path, { method, headers: adsHeaders(await token(), scoped ? c.accountId : undefined), body: body === undefined ? undefined : JSON.stringify(body) }); + const t = await r.text(); + if ((r.status === 429 || r.status >= 500) && attempt < 5) { await sleep(retryWait(r.headers.get('Retry-After'), attempt) * 1000); continue; } + if (r.status === 401 && attempt === 1) { cached = { token: '', until: 0 }; continue; } + if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t, 800)}`); + return t ? JSON.parse(t) : {}; + } + } + + return { + accountId: c.accountId, + token, + get: (path: string, scoped = true) => call('GET', path, undefined, scoped), + post: (path: string, body: unknown) => call('POST', path, body), + put: (path: string, body: unknown) => call('PUT', path, body), + }; +} diff --git a/cli/apple/adhoc.ts b/cli/apple/adhoc.ts new file mode 100644 index 00000000..7129d7ac --- /dev/null +++ b/cli/apple/adhoc.ts @@ -0,0 +1,200 @@ +// Ad-hoc / release-testing distribution: register test devices, an ad-hoc provisioning profile, ExportOptions.plist +// and the IPA export. +// storebound apple adhoc devices [--platform IOS|MAC_OS] [--json] registered devices, UDIDs masked +// storebound apple adhoc register [--csv .storebound/devices.csv] [--name n --udid u --platform IOS] [--dry] [--yes] +// storebound apple adhoc profile [--name ""] [--dry] [--yes] IOS_APP_ADHOC profile with every enabled iOS device +// storebound apple adhoc options [--method release-testing|ad-hoc] [--out build/ExportOptions.plist] [--dry] +// storebound apple adhoc export --archive [--plist build/ExportOptions.plist] [--out build/adhoc] [--dry] +// The devices CSV (name, udid, platform) is personal data: keep it in .storebound/ (gitignored). Full UDIDs are never +// printed, also not in --json or in API errors. register only adds devices: it never disables, enables or deletes one +// (that is the owner's call, on the Apple Developer website). Each registration uses one of the 100 yearly slots of +// its product family, and disabling a device does not give the slot back, so register asks first. +// --json of devices: { devices: [{ id, name, platform, deviceClass, model, status, udid (masked) }], usage: [{ deviceClass, registered, limit }] }. +// Sources (checked October 2026): +// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-devices (filter[platform] IOS|MAC_OS|UNIVERSAL, limit <= 200) +// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-devices (name, platform, udid) +// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-profiles (profileType IOS_APP_ADHOC) +// .../get-v1-bundleids (filter[identifier]), .../get-v1-certificates (filter[certificateType] DISTRIBUTION | IOS_DISTRIBUTION), +// .../get-v1-bundleids-_id_-profiles, .../get-v1-profiles-_id_-devices +// https://developer.apple.com/help/account/devices/devices-overview (100 per product family per membership year) +// `xcodebuild -help` (Xcode 27) for the ExportOptions keys and -exportArchive / -allowProvisioningUpdates. +// Not verified from a document: the UDID shapes (see cli/lib/adhoc.ts) and whether App Store Connect accepts a second +// profile with the same name; `profile` therefore gives a changed profile a new, dated name. +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative } from 'node:path'; +import { + deviceCreateReq, deviceFromApi, type DevicePlatform, exportArgv, type ExportMethod, exportOptionsPlist, maskedDevice, maskUdid, + parseDevicesCsv, parsePlatform, planRegister, profileCreateReq, profileCurrent, profileDevices, type RegisteredDevice, scrubUdids, + shellLine, slotUsage, usableCertificates, validUdid, type WantedDevice, YEARLY_LIMIT, +} from '../lib/adhoc'; +import type { Ctx } from '../lib/ctx'; +import { confirm, need } from '../lib/ctx'; +import { done, log, printJson, warn } from '../lib/log'; +import { textTable } from '../lib/table'; +import { type Asc, ascClient, type J } from './asc'; + +const TAG = 'adhoc'; +const USAGE = 'usage: storebound apple adhoc devices | register [--csv f | --name n --udid u] | profile | options | export --archive '; +const METHODS: ExportMethod[] = ['release-testing', 'ad-hoc']; + +async function registered(c: Asc, platform?: DevicePlatform): Promise { + return (await c.all(`/v1/devices?limit=200${platform ? `&filter[platform]=${platform}` : ''}`)).map(deviceFromApi); +} + +function usageLines(devs: RegisteredDevice[]): void { + for (const u of slotUsage(devs)) log(TAG, `${u.deviceClass}: ${u.registered} registered of ${u.limit} per membership year`); +} + +function wantedDevices(ctx: Ctx): WantedDevice[] { + const a = ctx.args; + const udid = a.get('udid'); + if (udid !== undefined) { + const name = a.get('name'); + const platform = parsePlatform(a.get('platform')); + if (!name || name === 'true') throw new Error('--udid needs --name ""'); + if (!platform) throw new Error('--platform: IOS or MAC_OS'); + if (!validUdid(udid, platform)) throw new Error(`--udid ${maskUdid(udid)}: not a device UDID (40 hex digits, or 8 hex - 16 hex)`); + return [{ name, udid: udid.trim(), platform }]; + } + const rel = a.get('csv') ?? ctx.loaded.config.apple?.adhoc?.devices ?? '.storebound/devices.csv'; + const file = ctx.loaded.resolve(rel); + if (!existsSync(file)) throw new Error(`${rel}: no devices file. Create it with the header line "name,udid,platform" and one device per line (platform IOS or MAC_OS); see skills/adhoc-distribution`); + if (!relative(ctx.loaded.root, file).startsWith('.storebound')) warn(TAG, `${rel} is outside .storebound/: device UDIDs are personal data, keep the file gitignored`); + const { devices, errors } = parseDevicesCsv(readFileSync(file, 'utf8')); + if (errors.length) throw new Error(`${rel}:\n ${errors.join('\n ')}`); + if (!devices.length) throw new Error(`${rel}: no devices`); + return devices; +} + +async function register(ctx: Ctx, c: () => Promise): Promise { + const wanted = wantedDevices(ctx); + const api = await c(); + const all = await registered(api); + const plan = planRegister(wanted, all); + log(TAG, `${wanted.length} in the list: ${plan.add.length} new, ${plan.present.length} already registered, ${plan.disabled.length} disabled`); + for (const d of plan.disabled) warn(TAG, `${d.name} (${maskUdid(d.udid)}) is registered but disabled; enable it on the Apple Developer website if it should test (storebound does not)`); + usageLines(all); + if (!plan.add.length) { done(TAG, 'nothing to register'); return; } + console.log(textTable(['name', 'platform', 'udid'], plan.add.map(d => [d.name, d.platform, maskUdid(d.udid)]))); + if (ctx.args.has('dry')) { log(TAG, `dry run: would register ${plan.add.length} device(s); nothing sent`); return; } + if (!(await confirm(ctx, `Register ${plan.add.length} device(s)? Each uses one of the ${YEARLY_LIMIT} yearly slots of its product family, also if it is disabled later.`))) { + log(TAG, 'not confirmed, nothing registered'); + return; + } + const udids = plan.add.map(d => d.udid); + let failed = 0; + for (const d of plan.add) { + try { + await api.asc('POST', '/v1/devices', deviceCreateReq(d)); + log(TAG, `registered ${d.name} (${maskUdid(d.udid)})`); + } catch (e) { + failed++; + warn(TAG, `${d.name} (${maskUdid(d.udid)}) not registered: ${scrubUdids((e as Error).message, udids)}`); + } + } + if (failed) throw new Error(`${failed} of ${plan.add.length} device(s) not registered`); + done(TAG, `${plan.add.length} device(s) registered; run \`storebound apple adhoc profile\` (or export with automatic signing) so the builds include them`); +} + +async function profile(ctx: Ctx, c: () => Promise): Promise { + const { config, resolve } = ctx.loaded; + const bundleId = need(config.apple?.bundleId, 'apple.bundleId'); + const name = ctx.args.get('name') ?? config.apple?.adhoc?.profile ?? `${bundleId} AdHoc`; + const api = await c(); + const bids = await api.asc('GET', `/v1/bundleIds?filter[identifier]=${encodeURIComponent(bundleId)}&limit=200`); + const bid = (bids.data as J[]).find(b => b.attributes?.identifier === bundleId && ['IOS', 'UNIVERSAL'].includes(b.attributes?.platform)); + if (!bid) throw new Error(`no iOS bundle id ${bundleId} on the Apple Developer account (Certificates, Identifiers & Profiles > Identifiers)`); + const certs = usableCertificates(await api.all('/v1/certificates?filter[certificateType]=DISTRIBUTION,IOS_DISTRIBUTION&limit=200')); + if (!certs.length) throw new Error('no valid Apple Distribution certificate: create one in Xcode (Settings > Accounts > Manage Certificates) or on the developer website'); + const devices = profileDevices(await registered(api, 'IOS')); + if (!devices.length) throw new Error('no enabled iOS devices: register them first (storebound apple adhoc register)'); + const want = devices.map(d => d.id); + const existing = (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).filter((p: J) => p.attributes?.profileType === 'IOS_APP_ADHOC' && p.attributes?.name === name); + let newName = name; + for (const p of existing) { + const has = (await api.all(`/v1/profiles/${p.id}/devices?limit=200`)).map((d: J) => d.id as string); + const st = profileCurrent(p.attributes.profileState, has, want); + if (st.current) { done(TAG, `profile "${name}" is current (${has.length} devices, expires ${String(p.attributes.expirationDate ?? '').slice(0, 10)})`); return; } + log(TAG, `profile "${name}" is ${p.attributes.profileState === 'ACTIVE' ? `missing ${st.missing} device(s)` : 'invalid'}; profiles cannot be changed, so a new one is created`); + newName = `${name} ${new Date().toISOString().slice(0, 10)}`; + } + const classes = new Map(); + for (const d of devices) classes.set(d.deviceClass ?? 'UNKNOWN', (classes.get(d.deviceClass ?? 'UNKNOWN') ?? 0) + 1); + log(TAG, `plan: create IOS_APP_ADHOC "${newName}" for ${bundleId}: ${devices.length} devices (${[...classes].map(([k, v]) => `${v} ${k}`).join(', ')}), ${certs.length} distribution certificate(s)`); + if (ctx.args.has('dry')) { log(TAG, 'dry run: nothing created'); return; } + if (!(await confirm(ctx, `Create the ad-hoc provisioning profile "${newName}"?`))) { log(TAG, 'not confirmed, nothing created'); return; } + const res = (await api.asc('POST', '/v1/profiles', profileCreateReq(newName, bid.id, certs, want))).data; + const content = res?.attributes?.profileContent as string | undefined; + if (content) { + const out = resolve(`build/adhoc/${newName.replace(/[^\w.-]+/g, '_')}.mobileprovision`); + mkdirSync(dirname(out), { recursive: true }); + writeFileSync(out, Buffer.from(content, 'base64')); + log(TAG, `saved ${relative(ctx.loaded.root, out)} (double-click to install it for manual signing)`); + } + if (newName !== name) warn(TAG, `the new profile is "${newName}": set apple.adhoc.profile to it for manual signing; the old one can be deleted on the Apple Developer website (owner)`); + done(TAG, `profile "${newName}" created (uuid ${res?.attributes?.uuid ?? '?'})`); +} + +function plistFor(ctx: Ctx): string { + const { config } = ctx.loaded; + const method = (ctx.args.get('method') ?? config.apple?.adhoc?.method ?? 'release-testing') as ExportMethod; + if (!METHODS.includes(method)) throw new Error(`--method: ${METHODS.join(' | ')} (ad-hoc is the name before Xcode 15.3)`); + return exportOptionsPlist({ method, teamId: need(config.apple?.teamId, 'apple.teamId'), bundleId: config.apple?.bundleId, profile: config.apple?.adhoc?.profile }); +} + +function options(ctx: Ctx): void { + const rel = ctx.args.str('out', 'build/ExportOptions.plist'); + const xml = plistFor(ctx); + if (ctx.args.has('dry')) { log(TAG, `dry run: would write ${rel}`); console.log(xml); return; } + const out = ctx.loaded.resolve(rel); + mkdirSync(dirname(out), { recursive: true }); + writeFileSync(out, xml); + done(TAG, `wrote ${rel}`); +} + +function exportIpa(ctx: Ctx): void { + const a = ctx.args; + const archive = a.get('archive'); + if (!archive || archive === 'true') throw new Error('usage: storebound apple adhoc export --archive [--out build/adhoc] [--dry]'); + if (!existsSync(archive)) throw new Error(`${archive}: no such archive (Xcode: Product > Archive, or xcodebuild archive)`); + const plistRel = a.str('plist', 'build/ExportOptions.plist'); + const plist = ctx.loaded.resolve(plistRel); + const out = ctx.loaded.resolve(a.str('out', 'build/adhoc')); + const dry = a.has('dry'); + if (!existsSync(plist)) { + const xml = plistFor(ctx); + if (dry) { log(TAG, `dry run: would write ${plistRel}`); console.log(xml); } + else { mkdirSync(dirname(plist), { recursive: true }); writeFileSync(plist, xml); log(TAG, `wrote ${plistRel}`); } + } + const argv = exportArgv(archive, plist, out); + if (dry) { log(TAG, 'dry run: would run'); console.log(shellLine(argv)); return; } + log(TAG, 'running xcodebuild -exportArchive; -allowProvisioningUpdates lets Xcode contact Apple to create or update signing assets'); + const r = spawnSync(argv[0]!, argv.slice(1), { stdio: 'inherit' }); + if (r.error) throw new Error(`xcodebuild: ${r.error.message} (Xcode installed? xcode-select -p)`); + if (r.status !== 0) throw new Error(`xcodebuild -exportArchive failed (exit ${r.status})`); + const ipas = existsSync(out) ? readdirSync(out).filter(f => f.endsWith('.ipa')) : []; + done(TAG, ipas.length ? `exported ${ipas.map(f => join(relative(ctx.loaded.root, out), f)).join(', ')}` : `export finished in ${relative(ctx.loaded.root, out)}`); +} + +export async function run(ctx: Ctx): Promise { + const a = ctx.args; + const sub = a._[0]; + let client: Asc | null = null; + const c = async (): Promise => (client ??= await ascClient(ctx.loaded.root, ctx.loaded.config.apple?.bundleId ?? '', ctx.loaded.config.apple?.appId)); + if (sub === 'devices') { + const p = a.get('platform'); + const platform = p ? parsePlatform(p) : undefined; + if (p && !platform) throw new Error('--platform: IOS or MAC_OS'); + const devs = await registered(await c(), platform ?? undefined); + if (a.has('json')) { printJson({ devices: devs.map(maskedDevice), usage: slotUsage(devs) }); return; } + console.log(textTable(['name', 'platform', 'class', 'model', 'status', 'udid'], devs.map(maskedDevice).map(d => [d.name, d.platform, d.deviceClass ?? '', d.model ?? '', d.status, d.udid]))); + usageLines(devs); + return; + } + if (sub === 'register') return register(ctx, c); + if (sub === 'profile') return profile(ctx, c); + if (sub === 'options') return options(ctx); + if (sub === 'export') return exportIpa(ctx); + throw new Error(USAGE); +} diff --git a/cli/console/fill.ts b/cli/console/fill.ts new file mode 100644 index 00000000..51c8b1d9 --- /dev/null +++ b/cli/console/fill.ts @@ -0,0 +1,282 @@ +// AI-assisted autofill of console forms that have no API, in a visible Chromium the owner signs in to: +// storebound console fill lists the forms +// storebound console fill --dry [--json] the answers and the step-by-step guidance; opens no browser +// storebound console fill [--store apple|play] [--json] [--profile ] +// Forms: apple-app-record, apple-age-rating (guide only: `storebound apple appinfo` sets it), apple-app-privacy, +// play-content-rating, play-target-audience. Answers come from the config only (cli/lib/console-answers.ts); anything +// it does not prove stays EMPTY and highlighted (AGENTS.md rule 5). +// Safety: storebound never types passwords, never touches sign-in pages (it waits while the owner signs in), never reads +// cookies or storage, and never clicks Save / Submit / Publish / Create / Next: every click goes through safeClick and +// its gate. The owner reviews each page, clicks Next, and presses the final button; the command ends when the window +// is closed. Locators are accessible names only (cli/lib/console-forms.ts); a missing or ambiguous field means the UI +// changed: filling stops and the guidance is printed instead. Not exposed over MCP. +// Profile: ~/.storebound/console-profile/ (or --profile / STOREBOUND_CONSOLE_PROFILE), so the sign-in is kept. +// Sources (checked October 2026): see cli/lib/console-answers.ts; Playwright launchPersistentContext, getByRole, +// getByLabel: https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context , +// https://playwright.dev/docs/locators +import { mkdirSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import type { Ctx } from '../lib/ctx'; +import { type Answer, type ConsoleResult, consoleResult, DISCLAIMER, FORM_IDS, fillValue, formMeta, isForm, valueText } from '../lib/console-answers'; +import { consoleReached, type FieldDef, type FormDef, formDef, forbiddenControl, isSignInUrl, type Name } from '../lib/console-forms'; +import { log, printJson, warn } from '../lib/log'; +import { launchPersistent } from '../shots/browser'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +type Page = any; +type Locator = any; + +const TAG = 'console'; +const CHECK = 'storebound: check this'; + +/** Locators with only the visible matches (hidden earlier pages stay in many consoles' DOM). */ +const vis = (l: Locator): Locator => { try { return l.filter({ visible: true }); } catch { return l; } }; +const nameOpts = (n: Name) => (typeof n === 'string' ? { name: n, exact: true } : { name: n }); + +type Found = { state: 'ok'; loc: Locator } | { state: 'none' | 'ambiguous' }; + +async function first(tries: Locator[]): Promise { + for (const t of tries) { + const l = vis(t); + const n = await l.count(); + if (n === 1) return { state: 'ok', loc: l }; + if (n > 1) return { state: 'ambiguous' }; + } + return { state: 'none' }; +} + +async function find(root: Locator, role: string, names: Name[], label = false): Promise { + for (const n of names) { + const tries = [root.getByRole(role, nameOpts(n))]; + if (label) tries.push(root.getByLabel(n, typeof n === 'string' ? { exact: true } : {})); + const f = await first(tries); + if (f.state !== 'none') return f; + } + return { state: 'none' }; +} + +interface Resolved { field: FieldDef; ok: boolean; seen: boolean; loc?: Locator; options?: Record } + +async function resolve(root: Locator, f: FieldDef): Promise { + if (f.kind !== 'radio') { + const role = f.kind === 'text' ? 'textbox' : f.kind === 'select' ? 'combobox' : 'checkbox'; + const r = await find(root, role, f.names ?? [], f.kind !== 'checkbox'); + return { field: f, ok: r.state === 'ok', seen: r.state !== 'none', ...(r.state === 'ok' ? { loc: r.loc } : {}) }; + } + let scope = root, seen = false; + if (f.names?.length) { + let g = await find(root, 'radiogroup', f.names); + if (g.state === 'none') g = await find(root, 'group', f.names); + if (g.state !== 'ok') return { field: f, ok: false, seen: g.state !== 'none' }; + scope = g.loc; seen = true; + } + const options: Record = {}; + let ok = true; + for (const [v, names] of Object.entries(f.options ?? {})) { + const r = await find(scope, 'radio', names); + if (r.state === 'ok') { options[v] = r.loc; seen = true; } else { ok = false; if (r.state === 'ambiguous') seen = true; } + } + return { field: f, ok, seen, ...(f.names?.length ? { loc: scope } : {}), options }; +} + +/** The accessible name of a control as the page labels it (what the click gate checks). */ +async function accName(loc: Locator): Promise { + return (await loc.evaluate((el: any) => { + const by = el.getAttribute('aria-labelledby'); + const ref = by ? by.split(/\s+/).map((id: string) => el.ownerDocument.getElementById(id)?.textContent ?? '').join(' ') : ''; + const labels = el.labels ? [...el.labels].map((l: any) => l.textContent).join(' ') : ''; + return el.getAttribute('aria-label') || ref || labels || el.textContent || ''; + })).trim().replace(/\s+/g, ' '); +} + +/** + * The single click gate: refuses any control whose name says save, submit, publish, create, next ... (English and + * Turkish). Every click storebound makes, checkboxes and radio buttons included, goes through here. + */ +export async function safeClick(loc: Locator, name: string, action: 'click' | 'check' | 'uncheck' = 'click'): Promise { + if (forbiddenControl(name)) { warn(TAG, `not clicking "${name}": storebound never presses save, submit, publish, next or similar`); return false; } + if (action === 'click') await loc.click(); + else await loc.setChecked(action === 'check'); + return true; +} + +/** Outline + a small "storebound: check this" label next to the element (no SVG). */ +export async function highlight(loc: Locator, text = CHECK): Promise { + await loc.evaluate((el: any, t: string) => { + const box = (el.tagName === 'INPUT' && el.closest('label')) || el; + if (box.getAttribute('data-storebound-check')) return; + box.setAttribute('data-storebound-check', '1'); + box.style.outline = '3px solid #d93025'; + box.style.outlineOffset = '2px'; + const s = el.ownerDocument.createElement('span'); + s.textContent = t; + s.setAttribute('data-storebound-label', '1'); + s.style.cssText = 'display:inline-block;margin:2px 6px;padding:1px 6px;border-radius:4px;background:#d93025;color:#fff;font:600 12px/18px system-ui,sans-serif'; + box.insertAdjacentElement('afterend', s); + }, text); +} + +async function setField(r: Resolved, v: string | boolean): Promise { + const f = r.field; + if (f.kind === 'text') { await r.loc.fill(String(v)); return true; } + if (f.kind === 'checkbox') return safeClick(r.loc, await accName(r.loc), v ? 'check' : 'uncheck'); + if (f.kind === 'radio') { + const o = r.options?.[String(v)]; + return o ? safeClick(o, await accName(o), 'check') : false; + } + // select: only a native Yes, we collect data from this app + + + + + + + diff --git a/tests/fixtures/console/apple-app-record-renamed.html b/tests/fixtures/console/apple-app-record-renamed.html new file mode 100644 index 00000000..5dc72673 --- /dev/null +++ b/tests/fixtures/console/apple-app-record-renamed.html @@ -0,0 +1,21 @@ + + +Apps - App Store Connect + +

Apps

+
+

New App

+
Platforms + +
+

+

+

+

+
User Access + +
+ +
+ diff --git a/tests/fixtures/console/apple-app-record.html b/tests/fixtures/console/apple-app-record.html new file mode 100644 index 00000000..9c010745 --- /dev/null +++ b/tests/fixtures/console/apple-app-record.html @@ -0,0 +1,23 @@ + + +Apps - App Store Connect + +

Apps

+
+

New App

+
Platforms + + +
+

+

+

+

+
User Access + +
+ +
+ diff --git a/tests/fixtures/console/play-content-rating.html b/tests/fixtures/console/play-content-rating.html new file mode 100644 index 00000000..7c8ce7cd --- /dev/null +++ b/tests/fixtures/console/play-content-rating.html @@ -0,0 +1,32 @@ + + +Content rating - Play Console + +

Content rating

+
+

+
Category + + + +
+ +
+ + + diff --git a/tests/fixtures/console/play-target-audience.html b/tests/fixtures/console/play-target-audience.html new file mode 100644 index 00000000..8192e29f --- /dev/null +++ b/tests/fixtures/console/play-target-audience.html @@ -0,0 +1,17 @@ + + +Target audience and content - Play Console + +

Target audience and content

+
Target age + + +
+ + + diff --git a/tests/fixtures/console/signin.html b/tests/fixtures/console/signin.html new file mode 100644 index 00000000..4c7c369d --- /dev/null +++ b/tests/fixtures/console/signin.html @@ -0,0 +1,4 @@ + + +Sign in + diff --git a/tests/growth-config.test.ts b/tests/growth-config.test.ts new file mode 100644 index 00000000..cdadb04e --- /dev/null +++ b/tests/growth-config.test.ts @@ -0,0 +1,32 @@ +// Config validation of the growth extras: web, revenuecat, prices.ppp, apple.teamId / adhoc. +import { describe, expect, test } from 'bun:test'; +import { type ShipConfig, validateConfig, validateExtras } from '../cli/lib/config'; + +const base: ShipConfig = { + app: { name: 'Example', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'hi@example.com' }, + languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], + apple: { bundleId: 'com.example.app' }, + play: { packageName: 'com.example.app' }, +}; +const fp = Array.from({ length: 32 }, (_, i) => (i * 7 % 256).toString(16).toUpperCase().padStart(2, '0')).join(':'); + +describe('growth extras config', () => { + test('a full, valid set passes', () => { + const c: ShipConfig = { ...base, apple: { ...base.apple!, teamId: 'ABCDEFGHIJ', adhoc: { method: 'ad-hoc' } }, + prices: { ppp: { source: 'worldbank', floor: 0.25, ceiling: 1 } }, + web: { domain: 'links.example.com', paths: ['/invite/*'], exclude: ['/admin/*'], androidSha256: [fp], landing: true }, + revenuecat: { projectId: 'proj0example', entitlements: { pro: ['com.example.app.pro'] }, offering: 'default' } }; + expect(validateExtras(c)).toEqual([]); + expect(validateConfig(c)).toEqual([]); + }); + test('each mistake is named', () => { + const c = { ...base, apple: { ...base.apple!, teamId: 'abc', adhoc: { method: 'enterprise' } }, + prices: { ppp: { source: 'file', floor: 2, ceiling: 1 } }, + web: { domain: 'https://example.com/x', paths: ['invite'], androidSha256: ['ab:cd'] }, + revenuecat: { projectId: '', entitlements: { pro: [] }, offering: 'a b' } } as unknown as ShipConfig; + const e = validateExtras(c).join('\n'); + for (const s of ['apple.teamId', 'apple.adhoc.method', 'prices.ppp.file', 'floor is above ceiling', 'web.domain', 'must start with /', 'web.androidSha256', 'revenuecat.projectId', 'revenuecat.entitlements.pro', 'revenuecat.offering']) + expect(e).toContain(s); + }); + test('no extras, no problems', () => expect(validateExtras(base)).toEqual([])); +}); diff --git a/tests/no-handmade-svg.test.ts b/tests/no-handmade-svg.test.ts index c33317c7..1467fbb1 100644 --- a/tests/no-handmade-svg.test.ts +++ b/tests/no-handmade-svg.test.ts @@ -3,13 +3,13 @@ // the desktop webview, the site and the teaser video (media/teaser), and on any SVG file that is not a known asset. // The brand mark is a PNG (tools/brand-assets.py from brand/master/logo-mark.png): no inline brand SVG anywhere. // Allowed: the root a visx chart renders into (files that import @visx/*), the vendored icon -// files (site/img/icons: Phosphor and simple-icons; apps/desktop/src/ui/store-marks: simple-icons; media/teaser/icons: -// Phosphor), each byte-equal to +// files (site/img/icons: Phosphor and simple-icons; apps/desktop/src/ui/store-marks and templates/web: simple-icons; +// media/teaser/icons: Phosphor), each byte-equal to // its package (tools/site-icons.ts), and the Mermaid output (docs/img, site/img journey*.svg). import { describe, expect, test } from 'bun:test'; import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join, relative } from 'node:path'; -import { checkSiteIcons, ICON_DIR, MARK_DIR, SITE_ICONS, STORE_MARKS, TEASER_DIR, TEASER_ICONS } from '../tools/site-icons'; +import { checkSiteIcons, ICON_DIR, MARK_DIR, SITE_ICONS, STORE_MARKS, TEASER_DIR, TEASER_ICONS, WEB_DIR } from '../tools/site-icons'; const ROOT = join(import.meta.dir, '..'); const walk = (dir: string, keep: (f: string) => boolean): string[] => readdirSync(join(ROOT, dir)).flatMap(n => { @@ -73,11 +73,18 @@ describe('no hand-written SVG', () => { for (const n of used) expect(vendored, n).toContain(n ?? ''); }); + test('templates (the web init landing page): store marks are the vendored simple-icons files, no inline SVG', () => { + const files = walk('templates', n => /\.(html|css|js)$/.test(n)); + expect(files).toContain('templates/web/landing.html'); + expect(files.flatMap(f => svgHits(f, read(f)))).toEqual([]); + }); + test('SVG files: vendored Phosphor / simple-icons files and Mermaid diagrams only', () => { - const svgs = ['site', 'docs', 'apps/desktop/src', 'media'].flatMap(d => walk(d, n => n.endsWith('.svg'))).map(f => relative(ROOT, join(ROOT, f))); + const svgs = ['site', 'docs', 'apps/desktop/src', 'media', 'templates'].flatMap(d => walk(d, n => n.endsWith('.svg'))).map(f => relative(ROOT, join(ROOT, f))); const vendored = new Set([ ...[...SITE_ICONS, ...STORE_MARKS].map(n => relative(ROOT, join(ICON_DIR, `${n}.svg`))), ...STORE_MARKS.map(n => relative(ROOT, join(MARK_DIR, `${n}.svg`))), + ...STORE_MARKS.map(n => relative(ROOT, join(WEB_DIR, `${n}.svg`))), ...TEASER_ICONS.map(([w, n]) => relative(ROOT, join(TEASER_DIR, `${n}-${w}.svg`))), ]); // byte equality with the packages is checked by checkSiteIcons (above); here: no other SVG file sneaks in diff --git a/tests/ppp.test.ts b/tests/ppp.test.ts new file mode 100644 index 00000000..60d86428 --- /dev/null +++ b/tests/ppp.test.ts @@ -0,0 +1,247 @@ +import { describe, expect, test } from 'bun:test'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve as pathResolve } from 'node:path'; +import bundledJson from '../cli/data/ppp-worldbank.json'; +import { parseArgs } from '../cli/lib/args'; +import { ALPHA3 } from '../cli/lib/money'; +import { + appleCurrencyHint, bigMacDataset, CURRENCY, datasetJson, datasetProblems, fxOf, parseFactorCsv, planRows, type PppDataset, pppCsv, propose, snapApple, + snapEnding, worldBankDataset, +} from '../cli/lib/ppp'; +import { parsePriceCsv } from '../cli/lib/prices'; +import { applePoints, run } from '../cli/prices-ppp'; + +const P = 'com.example.game.remove_ads'; +const ds: PppDataset = { + name: 'worldbank', source: 'test', url: 'https://example.com', license: 'CC BY 4.0', retrieved: '2026-10-11', eur: { fx: 0.9 }, + countries: { + US: { ppp: 1, fx: 1, year: 2025, currency: 'USD' }, + DE: { ppp: 0.72, fx: 0.9, year: 2025, currency: 'EUR' }, + TR: { ppp: 16, fx: 40, year: 2025, currency: 'TRY' }, + IN: { ppp: 20, fx: 87, year: 2025, currency: 'INR' }, + CH: { ppp: 1.2, fx: 0.8, year: 2025, currency: 'CHF' }, + JP: { ppp: 97, fx: 150, year: 2025, currency: 'JPY' }, + BA: { ppp: 0.7, fx: 1.75, year: 2025, currency: 'BAM' }, + AF: { ppp: 13, year: 2024, currency: 'AFN' }, + }, +}; + +describe('ppp math', () => { + test('usd = base x factor / fx, clamped to floor..ceiling', () => { + expect(propose(10, 0.72, 0.9, 0.3, 1.2)).toMatchObject({ clamped: null }); + expect(propose(10, 0.72, 0.9, 0.3, 1.2).usd).toBeCloseTo(8, 9); + const lo = propose(10, 20, 87, 0.3, 1.2); + expect(lo.clamped).toBe('floor'); + expect(lo.usd).toBe(3); + expect(lo.usdRaw).toBeCloseTo(2.299, 3); + expect(propose(10, 1.2, 0.8, 0.3, 1.2)).toMatchObject({ usd: 12, clamped: 'ceiling' }); + expect(() => propose(10, 0, 1, 0.3, 1.2)).toThrow(); + }); + test('fxOf: USD 1, EUR the euro rate, else a country with that currency', () => { + expect(fxOf(ds, 'USD')).toBe(1); + expect(fxOf(ds, 'EUR')).toBe(0.9); + expect(fxOf(ds, 'TRY')).toBe(40); + expect(fxOf(ds, 'XYZ')).toBeNull(); + }); +}); + +describe('snapping', () => { + test('two-decimal currencies: x.x9 under 1, x.99 under 100, ...9 under 1000', () => { + expect(snapEnding(2.4, 'USD')).toBe(1.99); + expect(snapEnding(2.6, 'USD')).toBe(2.99); + expect(snapEnding(0.3, 'GBP')).toBe(0.29); + expect(snapEnding(0.02, 'GBP')).toBe(0.09); + expect(snapEnding(1.2, 'EUR')).toBe(0.99); + expect(snapEnding(49.6, 'TRY')).toBe(49.99); + expect(snapEnding(129.4, 'TRY')).toBe(129); + expect(snapEnding(135, 'INR')).toBe(139); + }); + test('zero-decimal and large-unit currencies: round numbers', () => { + expect(snapEnding(478, 'JPY')).toBe(480); + expect(snapEnding(80.4, 'JPY')).toBe(80); + expect(snapEnding(3456, 'KRW')).toBe(3500); + expect(snapEnding(45678, 'IDR')).toBe(46000); + expect(snapEnding(56789, 'VND')).toBe(57000); + expect(snapEnding(2345, 'CLP')).toBe(2300); + expect(snapEnding(923, 'HUF')).toBe(920); + expect(snapEnding(1234.5, 'PKR')).toBe(1200); + }); + test('Apple: nearest real price point', () => { + expect(snapApple([49.99, 59.99, 64.99, 69.99], 62)).toBe(59.99); + expect(snapApple([], 62)).toBeNull(); + }); +}); + +describe('planRows', () => { + test('offline Play: local currency, US row is the base, clamp flags, skipped regions', () => { + const { rows, skipped } = planRows({ product: P, base: 4.99, store: 'play', dataset: ds, floor: 0.3, ceiling: 1.2 }); + const by = new Map(rows.map(r => [r.region, r] as const)); + expect(by.get('US')).toMatchObject({ currency: 'USD', price: 4.99, snap: 'base' }); + expect(by.get('DE')).toMatchObject({ currency: 'EUR', price: 3.99, clamped: null, snap: 'ending' }); + expect(by.get('IN')).toMatchObject({ currency: 'INR', clamped: 'floor', price: 129 }); + expect(by.get('CH')).toMatchObject({ clamped: 'ceiling', price: 4.99 }); + expect(by.get('JP')).toMatchObject({ currency: 'JPY', price: 480 }); + expect(by.get('BA')!.currency).toBe('BAM'); + expect(skipped.find(s => s.region === 'AF')!.why).toBe('no exchange rate'); + expect(skipped.find(s => s.region === 'FR')!.why).toMatch(/no PPP factor/); + expect(rows.every(r => r.territory === undefined)).toBe(true); + }); + test('offline Apple: the currency hint (Euro-Zone group EUR, USD groups USD), alpha-3 territory', () => { + const { rows } = planRows({ product: P, base: 4.99, store: 'apple', dataset: ds, floor: 0.3, ceiling: 1.2 }); + const ba = rows.find(r => r.region === 'BA')!; + expect(ba).toMatchObject({ currency: 'EUR', territory: 'BIH' }); + expect(ba.snappedFrom).toBeCloseTo((4.99 * 0.7 / 1.75) * 0.9, 2); + expect(appleCurrencyHint('TR')).toBe('TRY'); + expect(appleCurrencyHint('AF')).toBe('USD'); + expect(appleCurrencyHint('RS')).toBe('EUR'); + }); + test('online Apple: snaps to the mocked price points and takes the store currency', () => { + const regions = new Map([ + ['US', { currency: 'USD', points: [3.99, 4.99, 5.99] }], + ['TR', { currency: 'TRY', points: [49.99, 59.99, 64.99, 69.99, 79.99] }], + ['AF', { currency: 'USD', points: [0.99, 1.99] }], + ['JP', { currency: 'JPY', points: [] as number[] }], + ]); + const { rows, skipped } = planRows({ product: P, base: 4.99, store: 'apple', dataset: ds, floor: 0.3, ceiling: 1.2, regions }); + expect(rows.map(r => `${r.region} ${r.currency} ${r.price} ${r.snap}`)).toEqual(['TR TRY 79.99 apple-point', 'US USD 4.99 apple-point']); + expect(rows[0]!.snappedFrom).toBeCloseTo(4.99 * 0.4 * 40, 1); + expect(skipped.map(s => `${s.region}: ${s.why}`)).toEqual(['AF: no exchange rate', 'JP: no Apple price points']); + }); + test('CSV round trip through parsePriceCsv (the prices import parser)', () => { + const rows = [...planRows({ product: P, base: 4.99, store: 'apple', dataset: ds, floor: 0.3, ceiling: 1.2 }).rows, + ...planRows({ product: P, base: 4.99, store: 'play', dataset: ds, floor: 0.3, ceiling: 1.2 }).rows]; + const back = parsePriceCsv(pppCsv(rows), { products: [P], today: '2026-10-11' }); + const k = (r: { store: string; region: string; currency: string; price: number }) => `${r.store} ${r.region} ${r.currency} ${r.price}`; + expect(back.map(k).sort()).toEqual(rows.map(k).sort()); + expect(back.find(r => r.store === 'apple' && r.region === 'DE')!.territory).toBe('DEU'); + expect(pppCsv(rows).split('\n')[0]).toBe('product,store,region,currency,price,start_date,kind'); + }); +}); + +describe('datasets', () => { + const bundled = bundledJson as unknown as PppDataset; + test('bundled World Bank file: shape, citation, licence, euro rate', () => { + expect(datasetProblems(bundled)).toEqual([]); + expect(bundled.name).toBe('worldbank'); + expect(bundled.license).toBe('CC BY 4.0'); + expect(bundled.attribution).toMatch(/World Bank/); + expect(bundled.source).toMatch(/PA\.NUS\.PPP/); + expect(bundled.source).toMatch(/PA\.NUS\.FCRF/); + expect(bundled.retrieved).toMatch(/^\d{4}-\d{2}-\d{2}$/); + expect(bundled.urls!.some(u => u.startsWith('https://api.worldbank.org/'))).toBe(true); + expect(bundled.year).toBeGreaterThanOrEqual(2023); + expect(Object.keys(bundled.countries).length).toBeGreaterThan(120); + for (const [r, e] of Object.entries(bundled.countries)) { + expect(ALPHA3[r]).toBeDefined(); + expect(e.currency).toBe(CURRENCY[r]!); + if (e.currency === 'EUR') expect(e.fx).toBe(bundled.eur!.fx); + } + expect(bundled.countries.US).toMatchObject({ ppp: 1, fx: 1 }); + expect(JSON.parse(datasetJson(bundled))).toEqual(bundled); + }); + test('CURRENCY covers every App Store territory', () => { + expect(Object.keys(ALPHA3).filter(k => !CURRENCY[k])).toEqual([]); + }); + test('worldBankDataset: latest year, aggregates out, euro rate, unit mismatch dropped', () => { + const obs = (id: string, date: string, value: number | null) => ({ country: { id }, countryiso3code: '', date, value }); + const ppp: [unknown, ReturnType[]] = [{}, [obs('ZH', '2025', 5), obs('DE', '2024', 0.7), obs('DE', '2025', 0.71), obs('TR', '2025', null), obs('TR', '2024', 15), obs('LR', '2025', 0.4), obs('US', '2025', 1)]]; + const fx: [unknown, ReturnType[]] = [{}, [obs('XC', '2025', 0.88), obs('TR', '2025', 39), obs('LR', '2025', 190), obs('US', '2025', 1)]]; + const countries: [unknown, { id: string; iso2Code: string; region?: { value?: string } }[]] = [{}, [ + { id: 'AFE', iso2Code: 'ZH', region: { value: 'Aggregates' } }, { id: 'DEU', iso2Code: 'DE', region: { value: 'Europe & Central Asia' } }, + { id: 'TUR', iso2Code: 'TR' }, { id: 'LBR', iso2Code: 'LR' }, { id: 'USA', iso2Code: 'US' }]]; + const d = worldBankDataset(ppp, fx, countries, '2026-10-11'); + expect(Object.keys(d.countries)).toEqual(['DE', 'TR', 'US']); + expect(d.countries.DE).toEqual({ ppp: 0.71, fx: 0.88, year: 2025, currency: 'EUR' }); + expect(d.countries.TR).toEqual({ ppp: 15, fx: 39, year: 2024, fxYear: 2025, currency: 'TRY' }); + expect(d.eur).toEqual({ fx: 0.88, year: 2025 }); + expect(d.notes!.join(' ')).toMatch(/LR/); + expect(datasetProblems(d)).toEqual([]); + }); + test('bigMacDataset: implied PPP = local / US price, latest date, euro area row for EUR members', () => { + const csv = `date,iso_a3,currency_code,name,local_price,dollar_ex,dollar_price +2025-07-01,USA,USD,United States,5.5,1,5.5 +2026-07-01,USA,USD,United States,6,1,6 +2026-07-01,TUR,TRY,Turkey,240,40,6 +2026-07-01,EUZ,EUR,Euro area,5.4,0.9,6 +`; + const d = bigMacDataset(csv, '2026-10-11'); + expect(d.countries.TR).toEqual({ ppp: 40, fx: 40, year: 2026, currency: 'TRY' }); + expect(d.countries.DE).toEqual({ ppp: 0.9, fx: 0.9, year: 2026, currency: 'EUR' }); + expect(d.countries.US!.ppp).toBe(1); + expect(d.eur!.fx).toBe(0.9); + expect(d.license).toMatch(/CC BY 4\.0/); + }); + test('factor CSV: fx falls back to the bundled rate when the currency matches; errors at once', () => { + const fb: PppDataset = { ...ds }; + const d = parseFactorCsv('region,factor,currency,fx\nTR,15,TRY,\nDE,0.7,EUR,0.92\nUS,1,USD,\nAF,13,AFN,\n', fb, 'f.csv'); + expect(d.countries.TR).toEqual({ ppp: 15, fx: 40, currency: 'TRY' }); + expect(d.countries.DE!.fx).toBe(0.92); + expect(d.countries.US!.fx).toBe(1); + expect(d.countries.AF!.fx).toBeUndefined(); + expect(() => parseFactorCsv('region,factor,currency\nTUR,0,tr\n')).toThrow(/region "TUR"/); + expect(() => parseFactorCsv('region,factor,currency\nTR,0,tr\n')).toThrow(/currency.*factor/); + }); +}); + +describe('command', () => { + test('applePoints: batched GET with include=territory -> region, currency, points', async () => { + const urls: string[] = []; + const fake = { asc: async (_m: string, url: string) => { + urls.push(url); + return { data: [ + { id: 'pp1', attributes: { customerPrice: '59.99' }, relationships: { territory: { data: { type: 'territories', id: 'TUR' } } } }, + { id: 'pp2', attributes: { customerPrice: '64.99' }, relationships: { territory: { data: { type: 'territories', id: 'TUR' } } } }, + { id: 'pp3', attributes: { customerPrice: '4.99' }, relationships: { territory: { data: { type: 'territories', id: 'USA' } } } }], + included: [{ type: 'territories', id: 'TUR', attributes: { currency: 'TRY' } }, { type: 'territories', id: 'USA', attributes: { currency: 'USD' } }] }; + } }; + const m = await applePoints(fake as never, 'iap-1', ['TUR', 'USA']); + expect(urls).toEqual(['/v2/inAppPurchases/iap-1/pricePoints?filter[territory]=TUR,USA&include=territory&fields[territories]=currency&limit=8000']); + expect(m.get('TR')).toEqual({ currency: 'TRY', points: [59.99, 64.99] }); + expect(m.get('US')).toEqual({ currency: 'USD', points: [4.99] }); + }); + + async function runIn(argv: string[]): Promise<{ out: string; dir: string }> { + const dir = mkdtempSync(join(tmpdir(), 'ppp-')); + const config = { app: { name: 'Example' }, apple: { bundleId: 'com.example.game' }, play: { packageName: 'com.example.game' }, + products: [{ id: P, type: 'non_consumable', usd: 2.99, listings: {} }] }; + const lines: string[] = []; + const orig = console.log; + const fetchOrig = globalThis.fetch; + console.log = (...x: unknown[]) => { lines.push(x.join(' ')); }; + globalThis.fetch = (() => { throw new Error('no network in tests'); }) as never; + try { + await run({ loaded: { config, root: dir, path: join(dir, 'storebound.config.ts'), resolve: (p: string) => pathResolve(dir, p) }, args: parseArgs(argv) } as never); + } finally { console.log = orig; globalThis.fetch = fetchOrig; } + return { out: lines.join('\n'), dir }; + } + + test('offline --dry --json: the documented shape, nothing written', async () => { + const { out, dir } = await runIn(['--offline', '--dry', '--json', '--base', '4.99']); + const j = JSON.parse(out.slice(out.indexOf('{'))); + expect(Object.keys(j)).toEqual(['source', 'base', 'floor', 'ceiling', 'online', 'rows', 'skipped', 'diff', 'out', 'written']); + expect(j.source).toMatchObject({ name: 'worldbank', license: 'CC BY 4.0' }); + expect(j.base).toEqual({ [P]: 4.99 }); + expect(j.written).toBe(false); + expect(j.rows.find((r: { store: string; region: string }) => r.store === 'play' && r.region === 'US')).toMatchObject({ price: 4.99, factor: 1, usdEquivalent: 4.99 }); + expect(j.diff.every((d: { change: string }) => d.change === 'new')).toBe(true); + expect(() => readFileSync(join(dir, 'store/prices-ppp.csv'))).toThrow(); + }); + test('offline write: the sheet parses back with the import parser', async () => { + const { out, dir } = await runIn(['--offline', '--store', 'play', '--floor', '0.4']); + const csv = readFileSync(join(dir, 'store/prices-ppp.csv'), 'utf8'); + const rows = parsePriceCsv(csv, { products: [P] }); + expect(rows.length).toBeGreaterThan(100); + expect(rows.every(r => r.store === 'play')).toBe(true); + expect(out).toMatch(/storebound prices import --csv store\/prices-ppp\.csv --dry/); + }); + test('source file and bad bounds', async () => { + const dir = mkdtempSync(join(tmpdir(), 'ppp-f-')); + writeFileSync(join(dir, 'f.csv'), 'region,factor,currency,fx\nTR,16,TRY,40\n'); + await expect(runIn(['--offline', '--floor', '2', '--ceiling', '1'])).rejects.toThrow(/floor/); + await expect(runIn(['--offline', '--source', 'bigmac'])).rejects.toThrow(/--update-bigmac/); + const { out } = await runIn(['--offline', '--dry', '--json', '--source', 'file', '--file', join(dir, 'f.csv'), '--store', 'play']); + const j = JSON.parse(out.slice(out.indexOf('{'))); + expect(j.rows.map((r: { region: string }) => r.region)).toEqual(['TR', 'US']); + }); +}); diff --git a/tests/revenuecat.test.ts b/tests/revenuecat.test.ts new file mode 100644 index 00000000..717de9b6 --- /dev/null +++ b/tests/revenuecat.test.ts @@ -0,0 +1,331 @@ +// RevenueCat adapter: config -> wanted RevenueCat state, package identifiers, diff, sync plan order, and the command +// against a mocked fetch (paginated reads, --dry and no-TTY send no POST, the key never shows up). Response shapes are +// written by hand from https://www.revenuecat.com/docs/api-v2 (placeholder ids, no real project). +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { parseArgs } from '../cli/lib/args'; +import type { Loaded, ShipConfig } from '../cli/lib/config'; +import { outOfSync, RC_PACKAGE, rcDiff, rcPlan, type RcState, resolveApps, wantedRevenueCat } from '../cli/lib/revenuecat'; +import { rcClient, run } from '../cli/revenuecat'; + +const KEY = 'sk_test_placeholder_secret_value'; +const PROJECT = 'proj_example1'; +const APPS = { apple: 'app_apple1', play: 'app_play1' }; + +const listing = (title: string) => ({ en: { title, description: 'd' } }); +function config(over: Partial = {}): ShipConfig { + return { + app: { name: 'Example', privacyPolicyUrl: 'https://example.com/privacy' }, + languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }], + apple: { bundleId: 'com.example.app' }, + play: { packageName: 'com.example.app' }, + products: [ + { id: 'com.example.app.lifetime', type: 'non_consumable', usd: 29.99, listings: listing('Lifetime') }, + { id: 'com.example.app.coins_100', type: 'consumable', usd: 0.99, listings: listing('100 coins') }, + { id: 'com.example.app.pass_30d', type: 'non_renewing', usd: 4.99, listings: listing('30-day pass'), platforms: ['ios'] }, + ], + subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [ + { id: 'com.example.app.pro_monthly', period: 'P1M', level: 2, usd: 4.99, listings: listing('Pro monthly') }, + { id: 'com.example.app.pro_yearly', period: 'P1Y', level: 1, usd: 39.99, listings: listing('Pro yearly'), basePlanId: 'annual' }, + { id: 'com.example.app.pro_monthly_b', period: 'P1M', level: 3, usd: 5.99, listings: listing('Pro monthly B'), platforms: ['android'] }, + ] }], + revenuecat: { projectId: PROJECT, apps: APPS }, + ...over, + } as unknown as ShipConfig; +} + +describe('wantedRevenueCat', () => { + const w = wantedRevenueCat(config()); + test('one product per store item; Play subscriptions are productId:basePlanId', () => { + expect(w.products.map(p => `${p.key} ${p.type}`)).toEqual([ + 'apple:com.example.app.lifetime non_consumable', 'play:com.example.app.lifetime non_consumable', + 'apple:com.example.app.coins_100 consumable', 'play:com.example.app.coins_100 consumable', + 'apple:com.example.app.pass_30d non_renewing_subscription', + 'apple:com.example.app.pro_monthly subscription', 'play:com.example.app.pro_monthly:monthly subscription', + 'apple:com.example.app.pro_yearly subscription', 'play:com.example.app.pro_yearly:annual subscription', + 'play:com.example.app.pro_monthly_b:monthly subscription', + ]); + expect(w.problems).toEqual([]); + }); + test('default entitlement "pro" = every non-consumable, non-renewing and subscription; no consumables', () => { + expect(w.entitlements).toHaveLength(1); + expect(w.entitlements[0]!.lookupKey).toBe('pro'); + expect(w.entitlements[0]!.products.some(k => k.includes('coins'))).toBe(false); + expect(w.entitlements[0]!.products).toContain('apple:com.example.app.pass_30d'); + expect(w.entitlements[0]!.products).toHaveLength(8); + }); + test('package identifiers: reserved by period, first wins; lifetime; the rest custom', () => { + expect(w.offering.lookupKey).toBe('default'); + expect(w.offering.packages.map(p => [p.lookupKey, p.position])).toEqual([ + ['$rc_monthly', 1], ['$rc_annual', 2], ['com.example.app.pro_monthly_b', 3], + ['$rc_lifetime', 4], ['com.example.app.coins_100', 5], ['com.example.app.pass_30d', 6], + ]); + expect(w.offering.packages[0]!.products).toEqual(['apple:com.example.app.pro_monthly', 'play:com.example.app.pro_monthly:monthly']); + expect(RC_PACKAGE).toEqual({ P1W: '$rc_weekly', P1M: '$rc_monthly', P2M: '$rc_two_month', P3M: '$rc_three_month', P6M: '$rc_six_month', P1Y: '$rc_annual' }); + }); + test('platforms: an android-only app has only Play products; non_renewing is a Play consumable', () => { + const c = config({ app: { name: 'E', privacyPolicyUrl: 'https://example.com/p', platforms: ['android'] } as ShipConfig['app'] }); + const x = wantedRevenueCat(c); + expect(x.products.every(p => p.store === 'play')).toBe(true); + expect(x.offering.packages.find(p => p.configId === 'com.example.app.pass_30d')).toBeUndefined(); + const y = wantedRevenueCat(config({ products: [{ id: 'com.example.app.pass', type: 'non_renewing', usd: 1, listings: listing('Pass') }], subscriptions: [] } as Partial)); + expect(y.products.map(p => p.type)).toEqual(['non_renewing_subscription', 'consumable']); + }); + test('configured entitlements; unknown ids and consumables are problems; offering key', () => { + const c = config(); + c.revenuecat = { projectId: PROJECT, apps: APPS, offering: 'main', entitlements: { premium: ['com.example.app.pro_yearly', 'com.example.app.coins_100', 'com.example.app.nope'] } }; + const x = wantedRevenueCat(c); + expect(x.entitlements.map(e => [e.lookupKey, e.products])).toEqual([['premium', ['apple:com.example.app.pro_yearly', 'play:com.example.app.pro_yearly:annual']]]); + expect(x.problems).toHaveLength(2); + expect(x.offering.lookupKey).toBe('main'); + // the lifetime product is in no entitlement: a custom package, not $rc_lifetime + expect(x.offering.packages.map(p => p.lookupKey)).not.toContain('$rc_lifetime'); + }); +}); + +test('resolveApps: config ids, else match by bundle id / package name', () => { + const c = config(); + c.revenuecat = { projectId: PROJECT }; + const apps = [ + { id: 'app_a', type: 'app_store', app_store: { bundle_id: 'com.example.app' } }, + { id: 'app_p', type: 'play_store', play_store: { package_name: 'com.example.other' } }, + ]; + const r = resolveApps(c, apps); + expect(r.ids).toEqual({ apple: 'app_a' }); + expect(r.problems[0]).toContain('no Play Store app for com.example.app'); +}); + +// Full RevenueCat state for config(): everything in place. +function synced(): RcState { + const w = wantedRevenueCat(config()); + const products = w.products.map((p, i) => ({ id: `prod_${i}`, store_identifier: p.storeIdentifier, type: p.type, app_id: APPS[p.store], state: 'active' })); + const id = (k: string) => products[w.products.findIndex(p => p.key === k)]!.id; + return { + products, + entitlements: [{ id: 'entl_1', lookup_key: 'pro', state: 'active', productIds: w.entitlements[0]!.products.map(id) }], + offerings: [{ id: 'ofrng_1', lookup_key: 'default', is_current: true, state: 'active', + packages: w.offering.packages.map((p, i) => ({ id: `pkge_${i}`, lookup_key: p.lookupKey, position: p.position, products: p.products.map(k => ({ product_id: id(k), eligibility_criteria: 'all' })) })) }], + }; +} + +describe('rcDiff', () => { + const w = wantedRevenueCat(config()); + test('in sync', () => { + const rows = rcDiff(w, synced(), APPS); + expect(outOfSync(rows)).toBe(0); + expect(rows.every(r => r.status === 'ok')).toBe(true); + }); + test('missing, extra and mismatched', () => { + const s = synced(); + s.products = s.products.filter(p => p.store_identifier !== 'com.example.app.pro_yearly'); + s.products.push({ id: 'prod_x', store_identifier: 'com.example.app.old', type: 'consumable', app_id: APPS.apple, state: 'active' }); + s.products.push({ id: 'prod_web', store_identifier: 'prod_stripe', type: 'subscription', app_id: 'app_web', state: 'active' }); + s.products.find(p => p.store_identifier === 'com.example.app.lifetime' && p.app_id === APPS.play)!.type = 'subscription'; + s.entitlements.push({ id: 'entl_2', lookup_key: 'legacy', productIds: [] }); + s.offerings[0]!.packages = s.offerings[0]!.packages.filter(p => p.lookup_key !== '$rc_annual'); + s.offerings[0]!.packages.push({ id: 'pkge_x', lookup_key: 'promo', products: [] }); + s.offerings[0]!.is_current = false; + const rows = rcDiff(w, s, APPS); + const find = (status: string, key: string) => rows.find(r => r.status === status && r.key === key); + expect(find('missing', 'apple:com.example.app.pro_yearly')).toBeTruthy(); + expect(find('missing', 'pro <- apple:com.example.app.pro_yearly')).toBeTruthy(); + expect(find('missing', '$rc_annual')).toBeTruthy(); + expect(find('mismatch', 'play:com.example.app.lifetime')?.msg).toContain('type subscription'); + expect(find('extra', 'apple:com.example.app.old')).toBeTruthy(); + expect(find('extra', 'legacy')).toBeTruthy(); + expect(find('extra', 'promo')).toBeTruthy(); + expect(find('info', 'default')).toBeTruthy(); + expect(rows.some(r => r.key.includes('prod_stripe'))).toBe(false); // other apps are ignored + expect(outOfSync(rows)).toBe(4); + expect(rows[0]!.status).toBe('mismatch'); + }); + test('a package holding another product for the same app is a mismatch, not an attach', () => { + const s = synced(); + s.products.push({ id: 'prod_other', store_identifier: 'com.example.app.other_monthly', type: 'subscription', app_id: APPS.apple, state: 'active' }); + const pk = s.offerings[0]!.packages.find(p => p.lookup_key === '$rc_monthly')!; + pk.products = pk.products.filter(x => s.products.find(p => p.id === x.product_id)!.app_id !== APPS.apple).concat({ product_id: 'prod_other' }); + const rows = rcDiff(w, s, APPS); + expect(rows.find(r => r.key === '$rc_monthly <- apple:com.example.app.pro_monthly')?.status).toBe('mismatch'); + expect(rcPlan(w, s, APPS).filter(x => x.op === 'attach-package')).toEqual([]); + }); +}); + +describe('rcPlan', () => { + const w = wantedRevenueCat(config()); + test('empty project: creates in dependency order, attaches with chunks, no set-current by default', () => { + const plan = rcPlan(w, { products: [], entitlements: [], offerings: [] }, APPS); + const ops = plan.map(s => s.op); + const first = (op: string) => ops.indexOf(op as never), last = (op: string) => ops.lastIndexOf(op as never); + expect(last('create-product')).toBeLessThan(first('create-entitlement')); + expect(first('create-entitlement')).toBeLessThan(first('attach-entitlement')); + expect(last('attach-entitlement')).toBeLessThan(first('create-offering')); + expect(first('create-offering')).toBeLessThan(first('create-package')); + expect(last('create-package')).toBeLessThan(first('attach-package')); + expect(ops.filter(o => o === 'create-product')).toHaveLength(10); + expect(ops).not.toContain('set-current'); + expect(rcPlan(w, { products: [], entitlements: [], offerings: [] }, APPS, { current: true }).at(-1)!.op).toBe('set-current'); + }); + test('in sync: empty plan (idempotent); never deletes or detaches', () => { + expect(rcPlan(w, synced(), APPS)).toEqual([]); + const s = synced(); + s.products.push({ id: 'prod_x', store_identifier: 'com.example.app.old', type: 'consumable', app_id: APPS.apple }); + expect(rcPlan(w, s, APPS)).toEqual([]); + }); + test('a store without a resolved app is skipped', () => { + const plan = rcPlan(w, { products: [], entitlements: [], offerings: [] }, { apple: APPS.apple }); + expect(plan.some(s => JSON.stringify(s).includes('play:'))).toBe(false); + }); + test('new package positions avoid taken ones', () => { + const s = synced(); + s.offerings[0]!.packages = [{ id: 'pkge_x', lookup_key: 'promo', position: 1, products: [] }]; + const pos = rcPlan(w, s, APPS).filter(x => x.op === 'create-package').map(x => (x as { body: { position: number } }).body.position); + expect(new Set(pos).size).toBe(pos.length); + expect(pos).not.toContain(1); + }); +}); + +// ---- the command against a mocked fetch ---- + +interface Call { method: string; url: string; auth: string | null; body?: string } +const realFetch = globalThis.fetch; +const savedKey = process.env.REVENUECAT_SECRET_KEY; +let out: string[] = []; +const saved = { log: console.log, warn: console.warn, error: console.error }; +const tty = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY'); +beforeEach(() => { + out = []; + console.log = (...a: unknown[]) => { out.push(a.join(' ')); }; + console.warn = console.log; console.error = console.log; + process.env.REVENUECAT_SECRET_KEY = KEY; +}); +afterEach(() => { + globalThis.fetch = realFetch; + Object.assign(console, saved); + if (savedKey === undefined) delete process.env.REVENUECAT_SECRET_KEY; else process.env.REVENUECAT_SECRET_KEY = savedKey; + if (tty) Object.defineProperty(process.stdin, 'isTTY', tty); else delete (process.stdin as { isTTY?: boolean }).isTTY; + process.exitCode = 0; +}); +const json = (o: unknown, status = 200, headers: Record = {}) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json', ...headers } }); +const list = (items: unknown[], next: string | null = null) => ({ object: 'list', items, next_page: next, url: '/v2/x' }); + +function fake(route: (c: Call) => Response): Call[] { + const calls: Call[] = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const c: Call = { method: init?.method ?? 'GET', url: String(input), auth: new Headers(init?.headers).get('authorization'), body: init?.body as string | undefined }; + calls.push(c); + return route(c); + }) as typeof fetch; + return calls; +} +const ctx = (argv: string[], cfg = config()) => { + const root = mkdtempSync(join(tmpdir(), 'sb-rc-')); + return { loaded: { config: cfg, root, path: join(root, 'storebound.config.ts'), resolve: (p: string) => join(root, p) } as Loaded, args: parseArgs(argv) }; +}; + +/** A RevenueCat project as GET answers it, products split over two pages. */ +function project(s: RcState): (c: Call) => Response { + const P = `https://api.revenuecat.com/v2/projects/${PROJECT}`; + return c => { + if (c.method !== 'GET') return json({ id: `new_${c.url.split('/').at(-1)}` }, 201); + const u = new URL(c.url); + const path = u.origin + u.pathname; + if (path === `${P}/products`) { + const half = Math.ceil(s.products.length / 2); + return u.searchParams.get('starting_after') ? json(list(s.products.slice(half))) : json(list(s.products.slice(0, half), `/v2/projects/${PROJECT}/products?limit=100&starting_after=${s.products[half - 1]?.id}`)); + } + if (path === `${P}/entitlements`) return json(list(s.entitlements.map(e => ({ object: 'entitlement', id: e.id, lookup_key: e.lookup_key, display_name: e.lookup_key, state: 'active' })))); + const ent = path.match(/entitlements\/([^/]+)\/products$/); + if (ent) return json(list(s.entitlements.find(e => e.id === ent[1])!.productIds.map(id => s.products.find(p => p.id === id)))); + if (path === `${P}/offerings`) return json(list(s.offerings.map(o => ({ object: 'offering', id: o.id, lookup_key: o.lookup_key, is_current: o.is_current, state: 'active' })))); + const pk = path.match(/offerings\/([^/]+)\/packages$/); + if (pk) return json(list(s.offerings.find(o => o.id === pk[1])!.packages.map(p => ({ object: 'package', id: p.id, lookup_key: p.lookup_key, position: p.position })))); + const pp = path.match(/packages\/([^/]+)\/products$/); + if (pp) return json(list(s.offerings.flatMap(o => o.packages).find(p => p.id === pp[1])!.products.map(x => ({ product: s.products.find(p => p.id === x.product_id), eligibility_criteria: 'all' })))); + return json({ type: 'resource_missing', message: 'not found' }, 404); + }; +} + +describe('revenuecat command (mocked fetch)', () => { + test('diff reads every page, sends the Bearer key, in sync -> exit 0 and the scope footer', async () => { + const calls = fake(project(synced())); + await run(ctx(['diff'])); + expect(calls.filter(c => c.url.includes('/products?')).length).toBeGreaterThanOrEqual(2); + expect(calls.some(c => c.url.includes('starting_after=prod_4'))).toBe(true); + expect(calls.every(c => c.auth === `Bearer ${KEY}` && c.url.startsWith('https://api.revenuecat.com/v2/'))).toBe(true); + expect(calls.every(c => c.method === 'GET')).toBe(true); + expect(process.exitCode).toBe(0); + expect(out.join('\n')).toContain('receipt / purchase token validation'); + expect(out.join('\n')).not.toContain(KEY); + }); + test('diff --json: stable shape; out of sync -> exit 1', async () => { + fake(project({ products: [], entitlements: [], offerings: [] })); + await run(ctx(['diff', '--json'])); + const j = JSON.parse(out.find(l => l.startsWith('{'))!); + expect(Object.keys(j)).toEqual(['projectId', 'apps', 'outOfSync', 'rows', 'scope']); + expect(j.outOfSync).toBeGreaterThan(0); + expect(process.exitCode).toBe(1); + }); + test('apps are looked up by bundle id / package name when not configured', async () => { + const cfg = config(); cfg.revenuecat = { projectId: PROJECT }; + const base = project(synced()); + const calls = fake(c => c.url.includes('/apps?') ? json(list([ + { object: 'app', id: APPS.apple, type: 'app_store', app_store: { bundle_id: 'com.example.app' } }, + { object: 'app', id: APPS.play, type: 'play_store', play_store: { package_name: 'com.example.app' } }, + ])) : base(c)); + await run(ctx(['diff'], cfg)); + expect(calls[0]!.url).toContain(`/projects/${PROJECT}/apps`); + expect(process.exitCode).toBe(0); + }); + test('sync --dry sends no POST', async () => { + const calls = fake(project({ products: [], entitlements: [], offerings: [] })); + await run(ctx(['sync', '--dry'])); + expect(calls.some(c => c.method !== 'GET')).toBe(false); + expect(out.join('\n')).toContain('create product apple:com.example.app.lifetime'); + expect(out.join('\n')).toContain('dry run'); + }); + test('sync without a terminal and without --yes sends no POST', async () => { + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + const calls = fake(project({ products: [], entitlements: [], offerings: [] })); + await run(ctx(['sync'])); + expect(calls.some(c => c.method !== 'GET')).toBe(false); + expect(out.join('\n')).toContain('re-run with --yes'); + }); + test('sync --yes: POSTs in order with resolved ids and the documented bodies', async () => { + const calls = fake(project({ products: [], entitlements: [], offerings: [] })); + await run(ctx(['sync', '--yes'])); + const posts = calls.filter(c => c.method === 'POST').map(c => new URL(c.url).pathname.replace(`/v2/projects/${PROJECT}`, '')); + expect(posts.slice(0, 10).every(p => p === '/products')).toBe(true); + expect(posts).toContain('/entitlements'); + expect(posts).toContain('/entitlements/new_entitlements/actions/attach_products'); + expect(posts).toContain('/offerings/new_offerings/packages'); + expect(posts).toContain('/packages/new_packages/actions/attach_products'); + const attach = calls.find(c => c.url.endsWith('/packages/new_packages/actions/attach_products'))!; + expect(JSON.parse(attach.body!).products[0]).toEqual({ product_id: 'new_products', eligibility_criteria: 'all' }); + const prod = JSON.parse(calls.find(c => c.method === 'POST')!.body!); + expect(prod).toEqual({ store_identifier: 'com.example.app.lifetime', app_id: APPS.apple, type: 'non_consumable', display_name: 'Lifetime' }); + }); + test('a 401 names the key variable but never contains the key', async () => { + fake(() => json({ object: 'error', type: 'authentication_error', message: `Invalid API key ${KEY}`, retryable: false }, 401)); + const err = await run(ctx(['diff'])).then(() => null, (e: Error) => e); + expect(err?.message).toContain('401'); + expect(err?.message).toContain('REVENUECAT_SECRET_KEY'); + expect(err?.message).not.toContain(KEY); + expect(out.join('\n')).not.toContain(KEY); + }); + test('429 waits for Retry-After and retries; next_page off api.revenuecat.com is refused', async () => { + let n = 0; + fake(() => (n++ === 0 ? json({ object: 'error', type: 'rate_limit_error', backoff_ms: 0 }, 429, { 'retry-after': '0' }) : json(list([{ id: 'a' }])))); + expect(await rcClient(KEY).all('/projects/p/apps')).toEqual([{ id: 'a' }]); + expect(n).toBe(2); + fake(() => json(list([{ id: 'a' }], 'https://elsewhere.example.com/v2/x'))); + await expect(rcClient(KEY).all('/projects/p/apps')).rejects.toThrow('refusing'); + }); + test('missing key: a clear error, no request', async () => { + delete process.env.REVENUECAT_SECRET_KEY; + const calls = fake(() => json({})); + await expect(run(ctx(['diff']))).rejects.toThrow('REVENUECAT_SECRET_KEY is not set'); + expect(calls).toHaveLength(0); + }); +}); diff --git a/tests/serve.test.ts b/tests/serve.test.ts index 31f94cdd..5ab8b782 100644 --- a/tests/serve.test.ts +++ b/tests/serve.test.ts @@ -202,6 +202,35 @@ describe('serve --stdio: session', () => { await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } }); expect(errOf(await pending).code).toBe(ERR.cancelled); }); + test('console.fill: desktop only (never MCP), answers as data in the dry run, browser only with a host token, cancel kills it', async () => { + expect(describeMethods().find(m => m.method === 'console.fill')).toMatchObject({ kind: 'write', json: true, network: true, destructive: false }); + expect(DESKTOP_ONLY.some(t => t.name === 'console_fill')).toBe(true); + expect(TOOLS.some(t => t.name.startsWith('console') || t.command[0] === 'console')).toBe(false); + expect('console.fill').not.toMatch(FORBIDDEN_METHOD_WORDS); + let now = 9_000_000; + const answers = { form: 'apple-age-rating', store: 'apple', title: 'Age rating', url: 'https://appstoreconnect.apple.com/', answers: [{ id: 'violence', label: 'Cartoon violence', value: 'None', certain: true, source: 'apple.ageRating' }], uncertain: 0, guidance: [] }; + const { s, call, calls, nextId } = await session(argv => (argv.includes('--dry') ? { data: answers } : { wait: new Promise(() => {}) }), () => now); + const p = { project: DEMO, args: { form: 'apple-age-rating' } }; + expect(resOf(await call('console.fill', p))).toMatchObject({ dryRun: true, data: { answers: [{ id: 'violence' }] } }); + expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'apple-age-rating', '--dry', '--json']); + expect(calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBeUndefined(); + await call('console.fill', { project: DEMO, args: { form: 'play-content-rating', store: 'play' } }); + expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'play-content-rating', '--store', 'play', '--dry', '--json']); + for (const args of [{ form: 'apple-submit' }, { form: 'apple-age-rating', store: 'web' }, {}, { form: '--yes' }]) + expect(errOf(await call('console.fill', { project: DEMO, args })).code).toBe(ERR.invalidParams); + expect(errOf(await call('console.fill', { ...p, dryRun: false })).code).toBe(ERR.confirmRequired); + const n = calls.length; + // real run: waits for the owner (no timeout), the token answers the command's own question, a cancel stops it + const id = nextId(); + const pending = call('console.fill', { ...p, dryRun: false, confirmToken: mint(SECRET, 'console.fill', p, { now }) }); + await Bun.sleep(5); + expect(calls.length).toBe(n + 1); + expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'apple-age-rating', '--json']); + expect(calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBe('1'); + now += 600_000; + await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } }); + expect(errOf(await pending).code).toBe(ERR.cancelled); + }); test('portfolio.status: apps across platforms, release trains, catalog parity, per-app errors, progress n/total', async () => { const summary = { dir: DEMO, name: 'Demo', apple: { bundleId: 'com.example.demo', appId: null }, play: { packageName: 'com.example.demo' }, platforms: ['ios', 'android'], products: 2, productIds: ['coins', 'no_ads'], subscriptions: 0, subscriptionIds: [], catalog: { ios: ['coins', 'no_ads'], android: ['coins', 'no_ads'] } }; const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: summary } diff --git a/tests/web.test.ts b/tests/web.test.ts new file mode 100644 index 00000000..d495d21b --- /dev/null +++ b/tests/web.test.ts @@ -0,0 +1,215 @@ +// web init / web check: builders (exact JSON), validators, live checks against a local server, init into a temp dir. +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ShipConfig } from '../cli/lib/config'; +import { TEMPLATE_TEXT } from '../cli/lib/template-files'; +import { + aasaFor, assetLinksFor, checkLanding, fillLanding, HANDLE_ALL_URLS, normalizeFingerprint, planWeb, smartBannerTag, + validateAasa, validateAssetLinks, webIdsOf, +} from '../cli/lib/web'; +import { checkSite } from '../cli/web'; + +const ROOT = join(import.meta.dir, '..'); +const fp = Array.from({ length: 32 }, (_, i) => (i * 7 % 256).toString(16).toUpperCase().padStart(2, '0')).join(':'); +const fp2 = Array.from({ length: 32 }, (_, i) => (255 - i).toString(16).toUpperCase().padStart(2, '0')).join(':'); +const cfg: ShipConfig = { + app: { name: 'Example & Co', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', termsUrl: 'https://example.com/terms', website: 'https://example.com', contactEmail: 'hi@example.com' }, + languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], + apple: { bundleId: 'com.example.app', teamId: 'ABCDEFGHIJ', appId: '123456789' }, + play: { packageName: 'com.example.app' }, + web: { domain: 'links.example.com', paths: ['/invite/*'], exclude: ['/admin/*'], androidSha256: [fp], webcredentials: true }, +}; +const ids = webIdsOf(cfg); +const problems = (f: { level: string; message: string }[]) => f.filter(x => x.level === 'problem').map(x => x.message); + +describe('builders', () => { + test('apple-app-site-association: exact JSON, excludes first', () => { + expect(aasaFor(cfg)).toEqual({ + applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/admin/*', exclude: true, comment: 'stays in the browser' }, { '/': '/invite/*' }] }] }, + webcredentials: { apps: ['ABCDEFGHIJ.com.example.app'] }, + }); + expect(aasaFor({ ...cfg, web: undefined })).toEqual({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/*' }] }] } }); + expect(aasaFor({ ...cfg, apple: { bundleId: 'com.example.app' } })).toBeNull(); + }); + test('assetlinks.json: exact JSON, dynamic rules only with excludes', () => { + expect(assetLinksFor({ ...cfg, web: { domain: 'links.example.com', androidSha256: [fp] } })).toEqual([ + { relation: [HANDLE_ALL_URLS], target: { namespace: 'android_app', package_name: 'com.example.app', sha256_cert_fingerprints: [fp] } }, + ]); + expect(assetLinksFor(cfg)![0]!.relation_extensions).toEqual({ [HANDLE_ALL_URLS]: { dynamic_app_link_components: [{ '/': '/admin/*', exclude: true }, { '/': '/invite/*' }] } }); + expect(assetLinksFor({ ...cfg, web: { domain: 'links.example.com' } })).toBeNull(); + }); + test('Smart App Banner tag and landing page', () => { + expect(smartBannerTag(cfg)).toBe(''); + expect(smartBannerTag(cfg, 'https://links.example.com/invite/1')).toBe(''); + expect(smartBannerTag({ ...cfg, apple: { bundleId: 'com.example.app' } })).toBeNull(); + const html = fillLanding(TEMPLATE_TEXT['web/landing.html']!, cfg); + expect(html).toContain(''); + expect(html).toContain('Example & Co'); + expect(html).toContain('href="https://apps.apple.com/app/id123456789"'); + expect(html).toContain('href="https://play.google.com/store/apps/details?id=com.example.app"'); + expect(html).toContain('href="https://example.com/terms"'); + expect(html).toContain('App Store is a trademark of Apple Inc.; Google Play is a trademark of Google LLC.'); + expect(html).not.toMatch(/\{\{|/); + expect(html).not.toMatch(/https?:\/\/(?!apps\.apple\.com|play\.google\.com|example\.com)/); + const playOnly = fillLanding(TEMPLATE_TEXT['web/landing.html']!, { ...cfg, apple: undefined, app: { ...cfg.app, termsUrl: undefined } }); + expect(playOnly).not.toContain('apple-itunes-app'); + expect(playOnly).not.toContain('apps.apple.com'); + expect(playOnly).not.toContain('Terms of Use'); + expect(playOnly).toContain('Google Play'); + }); + test('fingerprints from the Play API: hex, colon hex, base64, base64url', () => { + const hex = fp.replace(/:/g, ''); + const b64 = Buffer.from(hex, 'hex').toString('base64'); + expect(normalizeFingerprint(hex.toLowerCase())).toBe(fp); + expect(normalizeFingerprint(fp.toLowerCase())).toBe(fp); + expect(normalizeFingerprint(b64)).toBe(fp); + expect(normalizeFingerprint(b64.replace(/=$/, '').replace(/\+/g, '-').replace(/\//g, '_'))).toBe(fp); + expect(normalizeFingerprint('abcd')).toBeNull(); + }); + test('plan: missing inputs are skipped with the fix, not errors', () => { + const p = planWeb({ ...cfg, apple: { bundleId: 'com.example.app' }, web: { domain: 'links.example.com' } }, { landing: false }); + expect(p.files).toEqual([]); + expect(p.skipped.join('\n')).toContain('apple.teamId'); + expect(p.skipped.join('\n')).toContain('Play app signing'); + expect(p.skipped.join('\n')).toContain('apple.appId'); + const full = planWeb(cfg, { landing: true, template: TEMPLATE_TEXT['web/landing.html'], marks: { appstore: 'a', googleplay: 'g' } }); + expect(full.files.map(f => f.path)).toEqual(['.well-known/apple-app-site-association', '.well-known/assetlinks.json', 'smart-app-banner.html', 'index.html', 'appstore.svg', 'googleplay.svg']); + expect(full.skipped).toEqual([]); + }); +}); + +describe('validators', () => { + const aasa = aasaFor(cfg)!; + const links = assetLinksFor(cfg)!; + test('good files pass', () => { + expect(problems(validateAasa(aasa, ids))).toEqual([]); + expect(problems(validateAssetLinks(links, ids))).toEqual([]); + }); + test('AASA: wrong team id, empty components, legacy format, missing webcredentials', () => { + const wrong = aasaFor({ ...cfg, apple: { ...cfg.apple!, teamId: 'ZYXWVUTSRQ' } }); + expect(problems(validateAasa(wrong, ids)).join()).toContain('does not list ABCDEFGHIJ.com.example.app'); + expect(problems(validateAasa({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [] }] } }, ids)).join()).toContain('no URL opens the app'); + expect(problems(validateAasa({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/*', exclude: true }] }] } }, ids)).join()).toContain('every component is excluded'); + const legacy = validateAasa({ applinks: { apps: [], details: [{ appID: 'ABCDEFGHIJ.com.example.app', paths: ['*'] }] } }, { teamId: 'ABCDEFGHIJ', bundleId: 'com.example.app' }); + expect(problems(legacy)).toEqual([]); + expect(legacy.some(x => x.level === 'info' && /legacy/.test(x.message))).toBe(true); + expect(problems(validateAasa({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/*' }] }] } }, ids)).join()).toContain('no "webcredentials" section'); + expect(problems(validateAasa([], ids))).toEqual(['not a JSON object']); + }); + test('assetlinks: missing fingerprint, extra fingerprint, wrong relation, wrong package, object instead of list', () => { + const extra = validateAssetLinks(assetLinksFor(cfg, [fp, fp2]), ids); + expect(problems(extra)).toEqual([]); + expect(extra.some(x => x.level === 'info' && /extra fingerprint/.test(x.message))).toBe(true); + expect(problems(validateAssetLinks(assetLinksFor(cfg, [fp2]), ids)).join()).toContain('is missing'); + const rel = [{ relation: ['delegate_permission/common.get_login_creds'], target: { namespace: 'android_app', package_name: 'com.example.app', sha256_cert_fingerprints: [fp] } }]; + expect(problems(validateAssetLinks(rel, ids)).join()).toContain(`not ${HANDLE_ALL_URLS}`); + expect(problems(validateAssetLinks(assetLinksFor({ ...cfg, play: { packageName: 'com.example.other' } }), ids)).join()).toContain('no android_app statement for com.example.app'); + expect(problems(validateAssetLinks(links[0], ids)).join()).toContain('not a list of statements'); + const lower = [{ relation: [HANDLE_ALL_URLS], target: { namespace: 'android_app', package_name: 'com.example.app', sha256_cert_fingerprints: [fp.toLowerCase()] } }]; + expect(problems(validateAssetLinks(lower, ids)).join()).toContain('AB:CD'); + }); + test('landing: Smart App Banner app-id', () => { + const page = (body: string) => ({ url: 'https://links.example.com/', status: 200, contentType: 'text/html', body, bytes: body.length }); + expect(checkLanding(page(''), ids)[0]!.level).toBe('ok'); + expect(checkLanding(page(''), ids)[0]!.level).toBe('problem'); + expect(checkLanding(page(''), ids)[0]!.level).toBe('problem'); + }); +}); + +describe('web check against a local server', () => { + type Route = { status?: number; type?: string; body?: string; location?: string }; + let routes: Record = {}; + let server: ReturnType; + let base = ''; + beforeAll(() => { + server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch(req) { + const r = routes[new URL(req.url).pathname]; + if (!r) return new Response('not found', { status: 404, headers: { 'content-type': 'text/html' } }); + return new Response(r.body ?? '', { status: r.status ?? 200, headers: { ...(r.type ? { 'content-type': r.type } : {}), ...(r.location ? { location: r.location } : {}) } }); + } }); + base = `http://127.0.0.1:${server.port}`; + }); + afterAll(() => server.stop(true)); + const good = (): Record => ({ + '/.well-known/apple-app-site-association': { type: 'application/json', body: JSON.stringify(aasaFor(cfg)) }, + '/.well-known/assetlinks.json': { type: 'application/json', body: JSON.stringify(assetLinksFor(cfg)) }, + '/': { type: 'text/html', body: fillLanding(TEMPLATE_TEXT['web/landing.html']!, cfg) }, + }); + + test('good site: no problems, legacy path is informational', async () => { + routes = good(); + const c = await checkSite(base, ids, { landing: true }); + expect(c.filter(x => !x.ok)).toEqual([]); + expect(c.find(x => x.id === 'aasa-legacy')!.level).toBe('info'); + expect(c.find(x => x.id === 'landing')!.level).toBe('ok'); + expect(c.every(x => typeof x.url === 'string' && typeof x.message === 'string')).toBe(true); + }); + test('redirect is a problem and is not followed', async () => { + routes = { ...good(), '/.well-known/apple-app-site-association': { status: 301, location: 'https://www.links.example.com/.well-known/apple-app-site-association' } }; + const c = await checkSite(base, ids); + const bad = c.filter(x => x.id === 'aasa' && !x.ok); + expect(bad).toHaveLength(1); + expect(bad[0]!.message).toContain('HTTP 301 redirect to https://www.links.example.com'); + }); + test('text/plain content type and an HTML fallback page are problems', async () => { + routes = { ...good(), '/.well-known/assetlinks.json': { type: 'text/plain', body: JSON.stringify(assetLinksFor(cfg)) }, '/.well-known/apple-app-site-association': { type: 'application/json', body: '' } }; + const c = await checkSite(base, ids); + expect(c.filter(x => !x.ok).map(x => `${x.id}: ${x.message}`)).toEqual([ + 'aasa: the body is an HTML page, not JSON (a single-page-app fallback or a custom 404 page?)', + 'assetlinks: content-type is "text/plain", not application/json', + ]); + }); + test('missing files and wrong ids', async () => { + routes = { '/.well-known/apple-app-site-association': { type: 'application/json', body: JSON.stringify(aasaFor({ ...cfg, apple: { ...cfg.apple!, teamId: 'ZYXWVUTSRQ' } })) } }; + const c = await checkSite(base, ids); + expect(c.filter(x => !x.ok).map(x => x.id)).toEqual(['aasa', 'aasa', 'assetlinks']); // appIDs and webcredentials.apps + expect(c.find(x => x.id === 'assetlinks')!.message).toBe('HTTP 404'); + }); +}); + +describe('web init (CLI)', () => { + const project = () => { + const d = mkdtempSync(join(tmpdir(), 'sb-web-')); + const c = { ...cfg, web: { ...cfg.web!, landing: true } }; + writeFileSync(join(d, 'storebound.config.json'), JSON.stringify(c)); + return d; + }; + const cli = (d: string, ...args: string[]) => Bun.spawnSync(['bun', join(ROOT, 'cli/index.ts'), 'web', 'init', ...args], { cwd: d, env: { ...process.env, NO_COLOR: '1' } }); + + test('--dry prints the files and writes nothing', () => { + const d = project(); + try { + const r = cli(d, '--dry'); + expect(r.exitCode).toBe(0); + const out = r.stdout.toString(); + expect(out).toContain('would write web/.well-known/apple-app-site-association'); + expect(out).toContain('"ABCDEFGHIJ.com.example.app"'); + expect(out).toContain(''); + expect(readdirSync(d)).toEqual(['storebound.config.json']); + } finally { rmSync(d, { recursive: true, force: true }); } + }, 30_000); + + test('writes the files, then reports unchanged / updated', () => { + const d = project(); + try { + const first = cli(d, '--json'); + expect(first.exitCode).toBe(0); + const j = JSON.parse(first.stdout.toString()); + expect(j.files.map((f: { path: string; status: string }) => `${f.status} ${f.path}`)).toEqual([ + 'new web/.well-known/apple-app-site-association', 'new web/.well-known/assetlinks.json', 'new web/smart-app-banner.html', + 'new web/index.html', 'new web/appstore.svg', 'new web/googleplay.svg', + ]); + expect(j.skipped).toEqual([]); + expect(JSON.parse(readFileSync(join(d, 'web/.well-known/assetlinks.json'), 'utf8'))).toEqual(assetLinksFor(cfg)); + expect(readFileSync(join(d, 'web/appstore.svg'), 'utf8')).toBe(readFileSync(join(ROOT, 'templates/web/appstore.svg'), 'utf8')); + writeFileSync(join(d, 'web/smart-app-banner.html'), 'old'); + const second = JSON.parse(cli(d, '--json').stdout.toString()); + expect(second.files.filter((f: { status: string }) => f.status !== 'unchanged').map((f: { path: string; status: string }) => `${f.status} ${f.path}`)).toEqual(['updated web/smart-app-banner.html']); + mkdirSync(join(d, 'site')); + expect(cli(d, '--out', 'site', '--json').exitCode).toBe(0); + expect(existsSync(join(d, 'site/.well-known/apple-app-site-association'))).toBe(true); + } finally { rmSync(d, { recursive: true, force: true }); } + }, 30_000); +}); diff --git a/tools/site-icons.ts b/tools/site-icons.ts index b4943399..0cddf02f 100644 --- a/tools/site-icons.ts +++ b/tools/site-icons.ts @@ -5,6 +5,7 @@ // apps/desktop/src/ui/store-marks the same two store marks for the desktop app (the other desktop icons come from // @phosphor-icons/react) // media/teaser/icons Phosphor icons for the teaser video (the mouse cursor, the blocker-list icons) +// templates/web the two store marks for the landing page `storebound web init --landing` writes // Both show them as CSS masks (site/style.css .ic-*, desktop styles.css .store-mark), so they take the text colour in // both themes and nothing is loaded from outside. The store marks only name the store next to its name; they are // trademarks of Apple Inc. and Google LLC (docs/desktop.md, the site footer). @@ -24,6 +25,7 @@ const simple = join(root, 'node_modules/simple-icons'); export const ICON_DIR = join(root, 'site/img/icons'); export const MARK_DIR = join(root, 'apps/desktop/src/ui/store-marks'); export const TEASER_DIR = join(root, 'media/teaser/icons'); +export const WEB_DIR = join(root, 'templates/web'); /** [vendored dir, file name, package file] for every vendored icon. */ function plan(): [string, string, string][] { @@ -32,6 +34,7 @@ function plan(): [string, string, string][] { ...SITE_ICONS.map(n => [ICON_DIR, `${n}.svg`, join(phosphor, 'assets/regular', `${n}.svg`)] as [string, string, string]), ...marks.map(([f, src]) => [ICON_DIR, f, src] as [string, string, string]), ...marks.map(([f, src]) => [MARK_DIR, f, src] as [string, string, string]), + ...marks.map(([f, src]) => [WEB_DIR, f, src] as [string, string, string]), ...TEASER_ICONS.map(([w, n]) => [TEASER_DIR, `${n}-${w}.svg`, join(phosphor, 'assets', w, `${n}-${w}.svg`)] as [string, string, string]), ]; } @@ -47,7 +50,7 @@ export function checkSiteIcons(): string[] { if (!existsSync(at)) out.push(`${rel(at)} missing (bun tools/site-icons.ts)`); else if (readFileSync(at, 'utf8') !== readFileSync(src, 'utf8')) out.push(`${rel(at)} is not ${rel(src).replace('node_modules/', '')}`); } - for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR]) { + for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR, WEB_DIR]) { if (!existsSync(dir)) continue; for (const f of readdirSync(dir)) if (f.endsWith('.svg') && !p.some(([d, n]) => d === dir && n === f)) out.push(`${rel(join(dir, f))} is not a vendored icon`); } @@ -64,10 +67,10 @@ if (import.meta.main) { for (const b of bad) console.error(`site-icons: ${b}`); process.exit(bad.length ? 1 : 0); } - for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR]) mkdirSync(dir, { recursive: true }); + for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR, WEB_DIR]) mkdirSync(dir, { recursive: true }); for (const [dir, f, src] of plan()) writeFileSync(join(dir, f), readFileSync(src)); writeFileSync(join(ICON_DIR, 'LICENSE.txt'), `Icons in this folder, copied unchanged by tools/site-icons.ts:\n\nPhosphor ${version(phosphor)} (https://phosphoricons.com), regular weight, from the @phosphor-icons/core\npackage.\n\n${readFileSync(join(phosphor, 'LICENSE'), 'utf8')}\n\n${simpleNote()}`); writeFileSync(join(TEASER_DIR, 'LICENSE.txt'), `Icons in this folder, copied unchanged by tools/site-icons.ts:\n\nPhosphor ${version(phosphor)} (https://phosphoricons.com), from the @phosphor-icons/core package.\n\n${readFileSync(join(phosphor, 'LICENSE'), 'utf8')}`); writeFileSync(join(MARK_DIR, 'LICENSE.txt'), `Store marks in this folder, copied unchanged by tools/site-icons.ts.\n\n${simpleNote()}`); - console.log(`site-icons: ${SITE_ICONS.length} Phosphor icons ${version(phosphor)} and ${STORE_MARKS.length} simple-icons ${version(simple)} store marks and ${TEASER_ICONS.length} teaser icons -> site/img/icons/, apps/desktop/src/ui/store-marks/, media/teaser/icons/`); + console.log(`site-icons: ${SITE_ICONS.length} Phosphor icons ${version(phosphor)} and ${STORE_MARKS.length} simple-icons ${version(simple)} store marks and ${TEASER_ICONS.length} teaser icons -> site/img/icons/, apps/desktop/src/ui/store-marks/, media/teaser/icons/, templates/web/`); } diff --git a/tools/update-ppp.ts b/tools/update-ppp.ts new file mode 100644 index 00000000..9eb11329 --- /dev/null +++ b/tools/update-ppp.ts @@ -0,0 +1,44 @@ +#!/usr/bin/env bun +// Refreshes the bundled PPP dataset of `storebound prices ppp` from the World Bank API (read-only public API, no key). +// bun tools/update-ppp.ts fetch PA.NUS.PPP + PA.NUS.FCRF, rewrite cli/data/ppp-worldbank.json (retrieved = today) +// bun tools/update-ppp.ts --check print the bundled file's age and data year, write nothing +// bun tools/update-ppp.ts --bigmac [--project ] [--dry] +// download The Economist Big Mac index into /.storebound/ppp-bigmac.json +// (not bundled: the repo's licence leaves third-party data out; same as +// `storebound prices ppp --update-bigmac`) +// Not run in CI (network). Sources: https://data.worldbank.org/indicator/PA.NUS.PPP, +// https://data.worldbank.org/indicator/PA.NUS.FCRF, https://github.com/TheEconomist/big-mac-data +import { readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { parseArgs } from '../cli/lib/args'; +import { datasetJson, datasetProblems, type PppDataset, WB, worldBankDataset } from '../cli/lib/ppp'; +import { updateBigMac } from '../cli/prices-ppp'; + +const FILE = join(import.meta.dir, '..', 'cli', 'data', 'ppp-worldbank.json'); +const a = parseArgs(process.argv.slice(2), ['check', 'bigmac']); +const today = new Date().toISOString().slice(0, 10); + +async function json(url: string): Promise { + const r = await fetch(url); + if (!r.ok) throw new Error(`${url} -> ${r.status}`); + return (await r.json()) as never; +} + +if (a.has('check')) { + const ds = JSON.parse(readFileSync(FILE, 'utf8')) as PppDataset; + const days = Math.round((Date.parse(today) - Date.parse(ds.retrieved)) / 86_400_000); + console.log(`ppp-worldbank.json: retrieved ${ds.retrieved} (${days} days ago), data up to ${ds.year}, ${Object.keys(ds.countries).length} countries${days > 365 ? ' - older than a year: run bun tools/update-ppp.ts' : ''}`); + const p = datasetProblems(ds); + if (p.length) { console.error(p.join('\n')); process.exit(1); } +} else if (a.has('bigmac')) { + await updateBigMac(resolve(a.str('project', process.cwd())), a.has('dry')); +} else { + const to = new Date().getFullYear(); + const [ppp, fx, countries] = await Promise.all([json(WB.api(WB.ppp, 2018, to)), json(WB.api(WB.fx, 2018, to)), json(WB.countries)]); + const ds = worldBankDataset(ppp, fx, countries, today); + const p = datasetProblems(ds); + if (p.length) throw new Error(p.join('; ')); + writeFileSync(FILE, datasetJson(ds)); + console.log(`wrote ${FILE}: ${Object.keys(ds.countries).length} countries, data up to ${ds.year}, retrieved ${today}`); + for (const n of ds.notes ?? []) console.log(` note: ${n}`); +}