@sprid/release 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,21 @@
3
3
  @sprid/release follows semver: a breaking change to a command's arguments, its
4
4
  output shape or its exit codes is a major release.
5
5
 
6
+ ## 1.4.0 - 2026-10-30
7
+
8
+ - `pages` (`asc-pages`) creates and updates App Store custom product pages from
9
+ `ascCustomProductPages`: screenshots per device profile, promotional text, deep
10
+ link, search keywords and visibility. It prints each page's URL; `--submit`
11
+ sends the page versions to App Review.
12
+ - `page-test` (`asc-page-test`) creates a product page optimization test from
13
+ `ascProductPageTest` with up to three treatments; `--start` starts it and sends
14
+ it to App Review when needed, `--stop` ends it. `--result <text> --annotate`
15
+ records the result Apple shows, since Apple's API has none.
16
+ - `page-results` (`asc-page-results`) reads page views and first-time downloads
17
+ per page from Apple's Detailed analytics reports, each date counted once.
18
+ `--annotate` records the comparison in Sprid.
19
+ - Neither command submits a draft review submission that holds other items.
20
+
6
21
  ## 1.3.0 - 2026-10-30
7
22
 
8
23
  - `creative` (`asc-creative`) pushes the App Store's product page header, search
package/README.md CHANGED
@@ -80,6 +80,61 @@ version; a standalone submission happens in App Store Connect.
80
80
  A Play preview video is listing copy: set `playVideo` (a YouTube URL) on a
81
81
  locale's `storeCopy` and push it with `metadata`. An empty string removes it.
82
82
 
83
+ ### Custom product pages and product page tests
84
+
85
+ Two different experiments, measured differently:
86
+
87
+ - A **custom product page** is a second App Store page with its own screenshots,
88
+ promotional text, deep link and search keywords. It only shows to traffic you
89
+ send to its URL (`…?ppid=<page id>`) or to searches for its keywords, so the
90
+ URL is the tag: put it behind an ad, a link in bio or a landing page button.
91
+ - A **product page test** splits the default page's own visitors between the
92
+ original and up to three treatments (icon, screenshots). Apple assigns
93
+ visitors and measures it; there is nothing to tag.
94
+
95
+ ```ts
96
+ ascCustomProductPages: [{
97
+ name: 'Focus', // analytics reports identify the page by this name
98
+ screenshots: { dir: './shots', glob: '{lang}/focus_*.png' }, // or an array, one per device profile
99
+ promotionalText: { en: 'Deep work, timed' },
100
+ deepLink: 'https://example.com/focus',
101
+ keywords: { en: ['focus timer'] }, // must already be keywords of the live version
102
+ }],
103
+ ascProductPageTest: {
104
+ name: 'Outcome-first screenshots', // a finished test cannot restart; the next one needs a new name
105
+ trafficProportion: 50, // percent of visitors in treatments, split evenly
106
+ treatments: [{ name: 'Outcome', screenshots: { dir: './shots', glob: '{lang}/outcome_*.png' } }],
107
+ },
108
+ ```
109
+
110
+ ```sh
111
+ sprid release pages # dry run: checks files, text and keywords locally
112
+ sprid release pages --execute --submit # create or update, upload, send to App Review; prints each URL
113
+ sprid release page-test --execute # create the test and its treatments, not started
114
+ sprid release page-test --execute --start # start it, and send it to App Review when its treatments need it
115
+ sprid release page-test --execute --stop # end it early; it cannot restart
116
+ sprid release page-results --days 28 # views and first-time downloads per page
117
+ ```
118
+
119
+ Screenshots go through Asset Library and replace only the configured device
120
+ profiles; every file is uploaded and processed before an existing one is
121
+ removed. An approved page changes through a new version with the same URL.
122
+ Neither command submits a draft review submission that already holds other
123
+ items (an app version being prepared): the items are added and go to review
124
+ with that submission.
125
+
126
+ `page-results` reads Apple's Detailed analytics reports, where custom product
127
+ pages appear by name: page views, first-time downloads and downloads per view
128
+ for each page against the default page. Apple lags two to three days, drops rows
129
+ under five users and adds noise. It needs an ongoing report request; the first
130
+ run with `--request-reports --execute` creates one (the key needs the Admin
131
+ role) and data arrives one to two days later.
132
+
133
+ Apple's API returns no product page test results. `page-results` shows the
134
+ test's state and dates; the result itself is in App Store Connect → Analytics →
135
+ Acquisition → Product Page Optimization. Record it with
136
+ `sprid release page-test --result "Outcome +14%, 92% confidence" --annotate`.
137
+
83
138
  Play shows each tablet slot only on tablets of that size, so one tablet capture goes to both
84
139
  slots by default. Every screenshot file is resolved before any slot is emptied.
85
140
 
@@ -131,6 +186,12 @@ Add `--annotate` alongside `--execute` to record the change in Sprid using your
131
186
  existing login or `SPRID_PAT`. Without `--annotate`, releases do not contact Sprid.
132
187
  Annotations are best effort. Store publishing works independently of Sprid.
133
188
 
189
+ Experiments land the same way, next to the store numbers they should move: a
190
+ page update or a test start records the page URLs or the test's treatments and
191
+ traffic share; `page-results --annotate` records each page's downloads per view
192
+ against the default page; `page-test --result "<text>" --annotate` records the
193
+ test result as Apple shows it, with the test's dates.
194
+
134
195
  ## Library use
135
196
 
136
197
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprid/release",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Build, sign and release mobile apps locally. Store copy, screenshots, binary uploads and review submissions from one app-owned configuration. Dry run by default.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
package/src/annotate.ts CHANGED
@@ -29,8 +29,10 @@ function loadCreds(): Creds | null {
29
29
  }
30
30
 
31
31
  export async function annotate(input: {
32
- kind: 'listing' | 'screenshots' | 'submission' | 'release';
32
+ kind: 'listing' | 'screenshots' | 'submission' | 'release' | 'note';
33
33
  label: string;
34
+ /** Insight areas the change explains, e.g. `['store']`. A `note` explains none unless given. */
35
+ areas?: string[];
34
36
  /** App Profile slug; the CLI's `.sprid/app.json` carries it. */
35
37
  app?: string;
36
38
  meta?: Record<string, unknown>;
@@ -47,6 +49,7 @@ export async function annotate(input: {
47
49
  kind: input.kind,
48
50
  label: input.label,
49
51
  meta: input.meta ?? {},
52
+ ...(input.areas ? { areas: input.areas } : {}),
50
53
  source: 'cli',
51
54
  }),
52
55
  });
package/src/asc/client.ts CHANGED
@@ -8,7 +8,19 @@ import { readFile } from 'node:fs/promises';
8
8
  import type { AppReleaseConfig } from '../config.ts';
9
9
  import { ascIssuer, ascKeyId, resolveAscKeyPath } from '../config.ts';
10
10
 
11
- export const ASC_BASE = 'https://api.appstoreconnect.apple.com/v1';
11
+ export const ASC_ORIGIN = 'https://api.appstoreconnect.apple.com';
12
+ export const ASC_BASE = `${ASC_ORIGIN}/v1`;
13
+
14
+ /** `/x` is a v1 path; `/v2/x` and Apple's absolute `links.next` URLs are used as given. */
15
+ function ascUrl(path: string): string {
16
+ if (path.startsWith('/v2/')) return `${ASC_ORIGIN}${path}`;
17
+ if (/^https?:/.test(path)) {
18
+ const url = new URL(path);
19
+ if (url.origin !== ASC_ORIGIN || url.username || url.password) throw new Error(`Refusing a non-App Store Connect URL: ${url.origin}`);
20
+ return url.href;
21
+ }
22
+ return `${ASC_BASE}${path}`;
23
+ }
12
24
 
13
25
  export interface AscClient {
14
26
  /** The app id this client targets (its bundle id). */
@@ -49,7 +61,7 @@ export function createAscClient(config: AppReleaseConfig): AscClient {
49
61
  // resource creation or review submission automatically after an ambiguous 5xx.
50
62
  const repeatable = method === 'GET' || (method === 'PATCH' && /^\/(appScreenshots|appAssetLibraryImages|appAssetLibraryVideos)\/[^/]+$/.test(path));
51
63
  for (let attempt = 0; ; attempt++) {
52
- const res = await fetch(`${ASC_BASE}${path}`, {
64
+ const res = await fetch(ascUrl(path), {
53
65
  ...init,
54
66
  redirect: 'error',
55
67
  signal: init.signal ?? AbortSignal.timeout(30000),
package/src/asc/index.ts CHANGED
@@ -8,3 +8,9 @@ export { pushAscScreenshots } from './screenshots.ts';
8
8
  export type { PushAscScreenshotsOptions } from './screenshots.ts';
9
9
  export { pushAscCreative, creativeProblems, imageInfo, uploadLibraryAsset } from './creative.ts';
10
10
  export type { PushAscCreativeOptions } from './creative.ts';
11
+ export { addToReview } from './submissions.ts';
12
+ export type { ReviewItem } from './submissions.ts';
13
+ export { pushCustomProductPages, pushProductPageTest, readProductPageTest, planPages, planTest, DEFAULT_SCREENSHOT_PROFILE } from './product-pages.ts';
14
+ export type { PushPagesOptions, PushTestOptions, PushedPage, TestStatus, PagePlan, TestPlan } from './product-pages.ts';
15
+ export { readPageResults, printPageResults, resultsLabel, downloadsPerView, foldPages } from './page-results.ts';
16
+ export type { PageResults, PageResultsOptions, PageRow } from './page-results.ts';
@@ -0,0 +1,218 @@
1
+ /**
2
+ * How each App Store page performs, from Apple's Analytics Reports.
3
+ *
4
+ * Custom product pages are only split out in the *Detailed* reports, where a row
5
+ * names its page in `Page Title` (the page's name in App Store Connect, never its
6
+ * ppid). Views come from "App Store Discovery and Engagement Detailed", downloads
7
+ * from "App Downloads Detailed", joined by page name.
8
+ *
9
+ * Product page optimization results are not in Apple's API at all, so for a test
10
+ * this reads its state and dates and says where Apple shows the result.
11
+ *
12
+ * Daily report instances overlap: each re-delivers the last two or three dates,
13
+ * and the latest processing date replaces a date's whole batch. Each date is
14
+ * taken from exactly one instance, or every day would count two or three times.
15
+ * https://developer.apple.com/documentation/analytics-reports/data-completeness-corrections
16
+ */
17
+
18
+ import { gunzipSync } from 'node:zlib';
19
+ import type { AppReleaseConfig } from '../config.ts';
20
+ import { createAscClient, type AscClient } from './client.ts';
21
+ import { findTest, listAll, testStatus, type TestStatus } from './product-pages.ts';
22
+
23
+ export interface PageRow {
24
+ title: string;
25
+ type: string;
26
+ impressions: number;
27
+ pageViews: number;
28
+ firstTimeDownloads: number;
29
+ redownloads: number;
30
+ }
31
+
32
+ export interface PageResults {
33
+ status: 'ok' | 'unconfigured' | 'pending';
34
+ note?: string;
35
+ window: { start: string; end: string; days: number };
36
+ /** Distinct dates with data in each report; Apple lags two to three days. */
37
+ coverage: { views: number; downloads: number };
38
+ rows: PageRow[];
39
+ /** The app's custom product pages, so a row can be matched to its URL. */
40
+ pages: { id: string; name: string; url?: string }[];
41
+ test?: TestStatus;
42
+ }
43
+
44
+ type Row = Record<string, string>;
45
+
46
+ export function parseTsv(text: string): Row[] {
47
+ const lines = text.split('\n').filter(l => l.length);
48
+ if (!lines.length) return [];
49
+ const header = lines[0].split('\t').map(h => h.trim());
50
+ return lines.slice(1).map(line => {
51
+ const cells = line.split('\t');
52
+ return Object.fromEntries(header.map((h, i) => [h, (cells[i] ?? '').trim()]));
53
+ });
54
+ }
55
+
56
+ /** The first column matching any pattern, most specific first ("Event" before "Engagement Type"). */
57
+ function col(row: Row, ...patterns: RegExp[]): string | undefined {
58
+ const keys = Object.keys(row);
59
+ for (const re of patterns) { const k = keys.find(x => re.test(x)); if (k) return k; }
60
+ return undefined;
61
+ }
62
+ const count = (row: Row) => Number((row[col(row, /^Counts?$/i) ?? ''] ?? '0').replace(/,/g, '')) || 0;
63
+ const pageOf = (row: Row) => ({
64
+ title: row[col(row, /^Page Title$/i) ?? ''] || '(none)',
65
+ type: row[col(row, /^Page Type$/i) ?? ''] || '(none)',
66
+ });
67
+
68
+ /** Rows of one report dated in [start, end), each date from the latest instance that carries it. */
69
+ export async function readReport(client: AscClient, reportId: string, start: string, end: string,
70
+ download: (url: string) => Promise<Buffer> = defaultDownload): Promise<{ rows: Row[]; dates: string[] }> {
71
+ const instances = await listAll(client, `/analyticsReports/${reportId}/instances?filter[granularity]=DAILY&limit=200`);
72
+ // processingDate is delivery time: a batch delivered after `end` can still hold dates inside the window.
73
+ const relevant = instances.filter((i: any) => (i.attributes?.processingDate ?? '') >= start);
74
+ const byDate = new Map<string, { revision: string; id: string; rows: Row[] }>();
75
+ for (const inst of relevant) {
76
+ const own = new Map<string, Row[]>();
77
+ for (const seg of await listAll(client, `/analyticsReportInstances/${inst.id}/segments`)) {
78
+ if (!seg.attributes?.url) continue;
79
+ for (const row of parseTsv(gunzipSync(await download(seg.attributes.url), { maxOutputLength: 64 * 1024 * 1024 }).toString('utf8'))) {
80
+ const date = row[col(row, /^Date$/i) ?? ''];
81
+ if (!date || date < start || date >= end) continue;
82
+ if (!own.has(date)) own.set(date, []);
83
+ own.get(date)!.push(row);
84
+ }
85
+ }
86
+ const revision = String(inst.attributes?.processingDate ?? '');
87
+ for (const [date, rows] of own) {
88
+ const held = byDate.get(date);
89
+ if (held && (revision < held.revision || (revision === held.revision && String(inst.id) < held.id))) continue;
90
+ byDate.set(date, { revision, id: String(inst.id), rows });
91
+ }
92
+ }
93
+ const dates = [...byDate.keys()].sort();
94
+ return { rows: dates.flatMap(d => byDate.get(d)!.rows), dates };
95
+ }
96
+
97
+ async function defaultDownload(url: string): Promise<Buffer> {
98
+ const res = await fetch(url, { signal: AbortSignal.timeout(60_000) });
99
+ if (!res.ok) throw new Error(`Report segment download: HTTP ${res.status}`);
100
+ return Buffer.from(await res.arrayBuffer());
101
+ }
102
+
103
+ /** Fold Discovery and Downloads rows into one row per page. */
104
+ export function foldPages(views: Row[], downloads: Row[]): PageRow[] {
105
+ const pages = new Map<string, PageRow>();
106
+ const get = (row: Row) => {
107
+ const { title, type } = pageOf(row);
108
+ const key = `${type}\u0000${title}`;
109
+ if (!pages.has(key)) pages.set(key, { title, type, impressions: 0, pageViews: 0, firstTimeDownloads: 0, redownloads: 0 });
110
+ return pages.get(key)!;
111
+ };
112
+ for (const row of views) {
113
+ const event = (row[col(row, /^Event$/i) ?? ''] ?? '').toLowerCase();
114
+ if (/impression/.test(event)) get(row).impressions += count(row);
115
+ else if (/page view/.test(event)) get(row).pageViews += count(row);
116
+ }
117
+ for (const row of downloads) {
118
+ const type = (row[col(row, /Download Type/i) ?? ''] ?? '').toLowerCase();
119
+ if (/first.time/.test(type)) get(row).firstTimeDownloads += count(row);
120
+ else if (/re.?download/.test(type)) get(row).redownloads += count(row);
121
+ }
122
+ return [...pages.values()].filter(p => p.pageViews || p.firstTimeDownloads || p.impressions)
123
+ .sort((a, b) => b.pageViews - a.pageViews || b.firstTimeDownloads - a.firstTimeDownloads);
124
+ }
125
+
126
+ /** First-time downloads per page view, the number a page changes. Null below 1 view. */
127
+ export const downloadsPerView = (p: PageRow): number | null => (p.pageViews ? p.firstTimeDownloads / p.pageViews : null);
128
+ const pct = (v: number | null) => (v === null ? '-' : `${(v * 100).toFixed(1)}%`);
129
+ export const isDefaultPage = (p: PageRow) => /default/i.test(p.title);
130
+
131
+ /** One line for a Sprid annotation: each custom page against the default page. At most 200 characters. */
132
+ export function resultsLabel(results: PageResults): string {
133
+ const names = new Set(results.pages.map(p => p.name));
134
+ const custom = results.rows.filter(r => names.has(r.title));
135
+ const base = results.rows.find(isDefaultPage);
136
+ const parts = custom.map(r => `"${r.title}" ${pct(downloadsPerView(r))} of ${r.pageViews} views`);
137
+ if (base) parts.push(`default ${pct(downloadsPerView(base))}`);
138
+ const label = `Product pages, ${results.window.days} days: ${parts.join('; ') || 'no custom page traffic yet'}`;
139
+ return label.length > 200 ? `${label.slice(0, 199)}…` : label;
140
+ }
141
+
142
+ export interface PageResultsOptions {
143
+ config: AppReleaseConfig;
144
+ /** Days back from today. Default 28. */
145
+ days?: number;
146
+ /** Create the ONGOING report request when there is none (needs the Admin role). Only with execute. */
147
+ requestReports?: boolean;
148
+ execute?: boolean;
149
+ /** Injected for tests. */
150
+ download?: (url: string) => Promise<Buffer>;
151
+ today?: Date;
152
+ }
153
+
154
+ export async function readPageResults({ config, days = 28, requestReports = false, execute = false, download, today = new Date() }: PageResultsOptions): Promise<PageResults> {
155
+ if (!Number.isInteger(days) || days < 1 || days > 365) throw new Error('--days takes a whole number from 1 to 365.');
156
+ const end = today.toISOString().slice(0, 10);
157
+ const start = new Date(Date.parse(end) - days * 86_400_000).toISOString().slice(0, 10);
158
+ const client = createAscClient(config);
159
+ const app = await client.findApp();
160
+ const pages = (await listAll(client, `/apps/${app.id}/appCustomProductPages?limit=200`))
161
+ .map((p: any) => ({ id: p.id, name: p.attributes?.name, url: p.attributes?.url }));
162
+ let test: TestStatus | undefined;
163
+ const testName = config.ascProductPageTest?.name;
164
+ if (testName) {
165
+ const found = await findTest(client, app.id, testName);
166
+ if (found) test = await testStatus(client, found);
167
+ }
168
+ const base: PageResults = { status: 'ok', window: { start, end, days }, coverage: { views: 0, downloads: 0 }, rows: [], pages, test };
169
+
170
+ const requests = await listAll(client, `/apps/${app.id}/analyticsReportRequests`);
171
+ let request = requests.find((r: any) => r.attributes?.accessType === 'ONGOING' && !r.attributes?.stoppedDueToInactivity);
172
+ if (!request) {
173
+ if (!(requestReports && execute)) {
174
+ return { ...base, status: 'unconfigured', note: 'Apple generates no analytics reports for this app yet. Run once with --request-reports --execute (the key needs the Admin role); the first data arrives one to two days later.' };
175
+ }
176
+ const created = await client.api('/analyticsReportRequests', { method: 'POST', body: JSON.stringify({ data: {
177
+ type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, relationships: { app: { data: { type: 'apps', id: app.id } } },
178
+ } }) });
179
+ request = created.data;
180
+ return { ...base, status: 'pending', note: 'Report request created. Apple delivers the first reports in one to two days; run page-results again then.' };
181
+ }
182
+ const reports = await listAll(client, `/analyticsReportRequests/${request.id}/reports?limit=200`);
183
+ const named = (re: RegExp) => reports.find((r: any) => re.test(r.attributes?.name ?? ''));
184
+ const viewsReport = named(/^App Store Discovery and Engagement Detailed$/);
185
+ const downloadsReport = named(/^App (Store )?Downloads Detailed$/);
186
+ if (!viewsReport || !downloadsReport) {
187
+ return { ...base, status: 'pending', note: 'The Detailed reports are not listed yet; Apple adds them one to two days after the request.' };
188
+ }
189
+ const views = await readReport(client, viewsReport.id, start, end, download);
190
+ const downloads = await readReport(client, downloadsReport.id, start, end, download);
191
+ return { ...base, coverage: { views: views.dates.length, downloads: downloads.dates.length }, rows: foldPages(views.rows, downloads.rows) };
192
+ }
193
+
194
+ export function printPageResults(results: PageResults): void {
195
+ const { start, end } = results.window;
196
+ console.log(`App Store pages, ${start} to ${end} (exclusive)`);
197
+ if (results.note) console.log(`\n${results.note}`);
198
+ if (results.status === 'ok') {
199
+ console.log(`Data on ${results.coverage.views} days (views) and ${results.coverage.downloads} days (downloads); Apple lags two to three days.\n`);
200
+ const names = new Set(results.pages.map(p => p.name));
201
+ const shown = results.rows.filter(r => names.has(r.title) || isDefaultPage(r)).concat(results.rows.filter(r => !names.has(r.title) && !isDefaultPage(r)).slice(0, 5));
202
+ const w = Math.max(12, ...shown.map(r => r.title.length));
203
+ console.log(`${'Page'.padEnd(w)} ${'Views'.padStart(8)} ${'Downloads'.padStart(9)} ${'Per view'.padStart(8)}`);
204
+ for (const r of shown) {
205
+ console.log(`${r.title.padEnd(w)} ${String(r.pageViews).padStart(8)} ${String(r.firstTimeDownloads).padStart(9)} ${pct(downloadsPerView(r)).padStart(8)}${names.has(r.title) ? ' custom' : ''}`);
206
+ }
207
+ if (!shown.length) console.log('No page views in the window.');
208
+ console.log('\nDownloads are first-time downloads. Apple drops rows under five users and adds noise, so small pages read low or not at all.');
209
+ }
210
+ for (const p of results.pages) console.log(` ${p.name}: ${p.url ?? '(no URL yet)'}`);
211
+ if (results.test) {
212
+ const t = results.test;
213
+ console.log(`\nProduct page test "${t.name}": ${t.state}${t.startDate ? `, started ${t.startDate}` : ''}${t.endDate ? `, ended ${t.endDate}` : ''}`);
214
+ console.log(` ${t.trafficProportion ?? '?'}% of visitors in treatments: ${t.treatments.map(x => x.name).join(', ') || 'none'}`);
215
+ console.log(" Apple's API has no test results. Read them in App Store Connect → Analytics → Acquisition → Product Page Optimization,");
216
+ console.log(' then record them with: page-test --result "<what Apple shows>" --annotate');
217
+ }
218
+ }
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Custom product pages and product page optimization tests (iOS).
3
+ *
4
+ * A custom product page is a second App Store page with its own screenshots,
5
+ * promotional text, deep link and search keywords, reached at its own URL
6
+ * (`?ppid=<page id>`). Traffic you send there (an ad, a link, a keyword) sees
7
+ * that page; Apple's analytics reports then split views and downloads by its name.
8
+ *
9
+ * A product page optimization test is Apple splitting the default page's own
10
+ * visitors between the original and up to three treatments (icon, screenshots).
11
+ * Apple measures it; its API returns no results, only the test's state and dates.
12
+ *
13
+ * pages: POST /appCustomProductPages (+ inline version and localizations)
14
+ * → promotional text, deep link, keywords, visibility
15
+ * → screenshots through Asset Library placements on each localization
16
+ * → `--submit` adds the page versions to a review submission
17
+ * page-test: POST /v2/appStoreVersionExperiments → treatments → localizations
18
+ * → screenshots on each treatment localization
19
+ * → `--start` sets started and adds the test to a review submission
20
+ *
21
+ * Screenshots go through Asset Library: the screenshot-set endpoints were
22
+ * deprecated at App Store Connect API 4.5. Every file is uploaded and processed
23
+ * before any existing placement is deleted.
24
+ */
25
+
26
+ import { readdirSync, readFileSync } from 'node:fs';
27
+ import { basename, dirname, extname, resolve } from 'node:path';
28
+ import { listingLocaleMap, releasePath, type AppReleaseConfig, type AscCustomProductPage, type AscPageScreenshots, type AscProductPageTest } from '../config.ts';
29
+ import { LIMITS } from '../copy.ts';
30
+ import { createAscClient, type AscClient } from './client.ts';
31
+ import { imageInfo, uploadLibraryAsset } from './creative.ts';
32
+ import { addToReview, type ReviewItem } from './submissions.ts';
33
+
34
+ export const DEFAULT_SCREENSHOT_PROFILE = 'IPHONE_DYNAMIC_ISLAND_LARGE_PROFILE';
35
+ const MAX_PAGES = 70;
36
+ const MAX_SCREENSHOTS = 10;
37
+ const MAX_TREATMENTS = 3;
38
+ /** Page versions that take edits. A version in review is locked until it is withdrawn. */
39
+ const EDITABLE_PAGE_STATES = new Set(['PREPARE_FOR_SUBMISSION', 'REJECTED']);
40
+ const EDITABLE_TEST_STATES = new Set(['PREPARE_FOR_SUBMISSION', 'REJECTED']);
41
+ const FINISHED_TEST_STATES = new Set(['COMPLETED', 'STOPPED']);
42
+
43
+ export interface ScreenshotSet { profile: string; files: string[] }
44
+
45
+ /** `<dir>/<glob>` with `{lang}` filled in, where the last segment holds the only `*`. */
46
+ function filesFor(config: AppReleaseConfig, set: AscPageScreenshots, lang: string): string[] {
47
+ const full = resolve(releasePath(config, set.dir), set.glob.replaceAll('{lang}', lang));
48
+ const rx = new RegExp('^' + basename(full).replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
49
+ try {
50
+ return readdirSync(dirname(full)).filter(n => rx.test(n)).sort().map(n => resolve(dirname(full), n));
51
+ } catch {
52
+ return [];
53
+ }
54
+ }
55
+
56
+ const asList = <T>(value: T | T[] | undefined): T[] => (value === undefined ? [] : Array.isArray(value) ? value : [value]);
57
+
58
+ /** Resolve one owner's screenshot sets for one locale and collect what is wrong with them. */
59
+ function resolveSets(config: AppReleaseConfig, sets: AscPageScreenshots[], lang: string, where: string, problems: string[]): ScreenshotSet[] {
60
+ const out: ScreenshotSet[] = [];
61
+ const profiles = new Set<string>();
62
+ for (const set of sets) {
63
+ const profile = set.profile ?? DEFAULT_SCREENSHOT_PROFILE;
64
+ if (profiles.has(profile)) problems.push(`${where}: two screenshot sets for ${profile}`);
65
+ profiles.add(profile);
66
+ const files = filesFor(config, set, lang);
67
+ if (!files.length) { problems.push(`${where}: no screenshots match ${set.glob.replaceAll('{lang}', lang)}`); continue; }
68
+ if (files.length > MAX_SCREENSHOTS) problems.push(`${where}: ${files.length} screenshots for ${profile}; the store takes ${MAX_SCREENSHOTS}`);
69
+ for (const file of files) {
70
+ if (!['.png', '.jpg', '.jpeg'].includes(extname(file).toLowerCase())) { problems.push(`${basename(file)}: screenshots are PNG or JPEG`); continue; }
71
+ try {
72
+ if (imageInfo(readFileSync(file)).alpha) problems.push(`${basename(file)}: has an alpha channel; App Store Connect refuses transparency`);
73
+ } catch (e) {
74
+ problems.push(`${basename(file)}: ${(e as Error).message}`);
75
+ }
76
+ }
77
+ out.push({ profile, files });
78
+ }
79
+ return out;
80
+ }
81
+
82
+ export interface PagePlan {
83
+ name: string;
84
+ deepLink?: string;
85
+ visible: boolean;
86
+ /** Keywords are managed only for a page that declares them; others keep what App Store Connect holds. */
87
+ manageKeywords: boolean;
88
+ locales: { locale: string; promotionalText?: string; keywords: string[]; screenshots: ScreenshotSet[] }[];
89
+ }
90
+
91
+ /** Check every page locally and resolve its files. Throws with every problem at once. */
92
+ export function planPages(config: AppReleaseConfig, localeMap: Record<string, string>): PagePlan[] {
93
+ const pages = config.ascCustomProductPages;
94
+ if (!pages?.length) throw new Error('release.config.ts needs `ascCustomProductPages` for the pages command.');
95
+ const problems: string[] = [];
96
+ if (pages.length > MAX_PAGES) problems.push(`${pages.length} pages; App Store Connect allows ${MAX_PAGES}`);
97
+ const names = new Set<string>();
98
+ const plans = pages.map((page: AscCustomProductPage) => {
99
+ const name = page.name?.trim();
100
+ if (!name) problems.push('every custom product page needs a name');
101
+ else if (names.has(name)) problems.push(`two pages are named "${name}"; analytics reports tell pages apart by name`);
102
+ names.add(name);
103
+ if (page.deepLink) {
104
+ try { new URL(page.deepLink); } catch { problems.push(`${name}: deepLink ${page.deepLink} is not a URL`); }
105
+ }
106
+ const sets = asList(page.screenshots);
107
+ if (!sets.length) problems.push(`${name}: a custom product page needs screenshots`);
108
+ const locales = Object.entries(localeMap).map(([locale, lang]) => {
109
+ const promotionalText = page.promotionalText?.[lang] ?? config.storeCopy?.[lang]?.promotionalText;
110
+ if (promotionalText && promotionalText.length > LIMITS.promotionalText) {
111
+ problems.push(`${name} [${locale}]: promotional text is ${promotionalText.length}/${LIMITS.promotionalText} characters`);
112
+ }
113
+ const keywords = (page.keywords?.[lang] ?? []).map(k => k.trim()).filter(Boolean);
114
+ const own = config.storeCopy?.[lang]?.keywords;
115
+ if (own !== undefined) {
116
+ const listed = new Set(own.split(',').map(k => k.trim().toLowerCase()));
117
+ for (const k of keywords) if (!listed.has(k.toLowerCase())) problems.push(`${name} [${locale}]: keyword "${k}" is not in storeCopy.${lang}.keywords; a page can only take the app's own keywords`);
118
+ }
119
+ return { locale, promotionalText, keywords, screenshots: resolveSets(config, sets, lang, `${name} [${locale}]`, problems) };
120
+ });
121
+ return { name, deepLink: page.deepLink, visible: page.visible ?? true, manageKeywords: page.keywords !== undefined, locales };
122
+ });
123
+ if (problems.length) throw new Error(`Custom product pages are not ready:\n ${problems.join('\n ')}`);
124
+ return plans;
125
+ }
126
+
127
+ export interface TestPlan {
128
+ name: string;
129
+ trafficProportion: number;
130
+ treatments: { name: string; appIconName?: string; locales: { locale: string; screenshots: ScreenshotSet[] }[] }[];
131
+ }
132
+
133
+ export function planTest(config: AppReleaseConfig, localeMap: Record<string, string>): TestPlan {
134
+ const test: AscProductPageTest | undefined = config.ascProductPageTest;
135
+ if (!test) throw new Error('release.config.ts needs `ascProductPageTest` for the page-test command.');
136
+ const problems: string[] = [];
137
+ if (!test.name?.trim()) problems.push('the test needs a name');
138
+ if (!Number.isInteger(test.trafficProportion) || test.trafficProportion < 1 || test.trafficProportion > 100) {
139
+ problems.push(`trafficProportion ${test.trafficProportion}: a whole percent from 1 to 100`);
140
+ }
141
+ if (!test.treatments?.length || test.treatments.length > MAX_TREATMENTS) problems.push(`${test.treatments?.length ?? 0} treatments; a test takes 1 to ${MAX_TREATMENTS}`);
142
+ const names = new Set<string>();
143
+ const treatments = (test.treatments ?? []).map(t => {
144
+ if (!t.name?.trim()) problems.push('every treatment needs a name');
145
+ else if (names.has(t.name)) problems.push(`two treatments are named "${t.name}"`);
146
+ names.add(t.name);
147
+ const sets = asList(t.screenshots);
148
+ if (!sets.length && !t.appIconName) problems.push(`${t.name}: a treatment needs screenshots or an appIconName, or it shows the original`);
149
+ const locales = sets.length
150
+ ? Object.entries(localeMap).map(([locale, lang]) => ({ locale, screenshots: resolveSets(config, sets, lang, `${t.name} [${locale}]`, problems) }))
151
+ : [];
152
+ return { name: t.name, appIconName: t.appIconName, locales };
153
+ });
154
+ if (problems.length) throw new Error(`The product page test is not ready:\n ${problems.join('\n ')}`);
155
+ return { name: test.name.trim(), trafficProportion: test.trafficProportion, treatments };
156
+ }
157
+
158
+ /** Every page of a list endpoint. Apple's `links.next` is absolute; the client accepts it. */
159
+ export async function listAll(client: AscClient, path: string): Promise<any[]> {
160
+ const out: any[] = [];
161
+ for (let next: string | undefined = path, pages = 0; next; pages++) {
162
+ if (pages >= 20) throw new Error(`${path}: more than 20 pages of results`);
163
+ const res = await client.api(next);
164
+ out.push(...(res?.data ?? []));
165
+ next = res?.links?.next;
166
+ }
167
+ return out;
168
+ }
169
+
170
+ interface Owner { rel: 'appCustomProductPageLocalization' | 'appStoreVersionExperimentTreatmentLocalization'; type: string; id: string; label: string }
171
+ const ownerPath = (o: Owner) => `/${o.type}/${o.id}`;
172
+
173
+ /** Upload every distinct file once, before anything on the store is replaced. */
174
+ async function uploadAll(client: AscClient, appId: string, files: string[]): Promise<Map<string, { type: string; id: string }>> {
175
+ const uploaded = new Map<string, { type: string; id: string }>();
176
+ if (!files.length) return uploaded;
177
+ const { data: library } = await client.api(`/apps/${appId}/assetLibrary`);
178
+ for (const file of new Set(files)) {
179
+ uploaded.set(file, await uploadLibraryAsset(client, library.id, file, { category: 'APP_SCREENSHOTS_AND_PREVIEWS' }));
180
+ console.log(` uploaded ${basename(file)}`);
181
+ }
182
+ return uploaded;
183
+ }
184
+
185
+ /** Replace the owner's screenshots in each given profile with the uploaded files, in order. */
186
+ async function placeScreenshots(client: AscClient, owner: Owner, sets: ScreenshotSet[], uploaded: Map<string, { type: string; id: string }>): Promise<void> {
187
+ if (!sets.length) return;
188
+ const profiles = new Set(sets.map(s => s.profile));
189
+ const existing = await listAll(client, `${ownerPath(owner)}/placements?limit=200`);
190
+ for (const p of existing) {
191
+ if (p.attributes?.placementType === 'APP_SCREENSHOT' && profiles.has(p.attributes.placementGroup)) {
192
+ await client.api(`/appAssetLibraryPlacements/${p.id}`, { method: 'DELETE' });
193
+ }
194
+ }
195
+ const link = { [owner.rel]: { data: { type: owner.type, id: owner.id } } };
196
+ for (const set of sets) {
197
+ const ids: string[] = [];
198
+ for (const file of set.files) {
199
+ const { data } = await client.api('/appAssetLibraryPlacements', { method: 'POST', body: JSON.stringify({ data: {
200
+ type: 'appAssetLibraryPlacements',
201
+ attributes: { placementType: 'APP_SCREENSHOT', placementGroup: set.profile },
202
+ relationships: { image: { data: uploaded.get(file)! }, ...link },
203
+ } }) });
204
+ ids.push(data.id);
205
+ }
206
+ if (ids.length > 1) {
207
+ await client.api('/appAssetLibraryPlacementOrderingRequests', { method: 'POST', body: JSON.stringify({ data: {
208
+ type: 'appAssetLibraryPlacementOrderingRequests',
209
+ attributes: { placementGroup: set.profile },
210
+ relationships: { orderedPlacements: { data: ids.map(id => ({ type: 'appAssetLibraryPlacements', id })) }, ...link },
211
+ } }) });
212
+ }
213
+ console.log(` [${owner.label}] ${set.profile} ← ${set.files.length} screenshot${set.files.length === 1 ? '' : 's'}`);
214
+ }
215
+ }
216
+
217
+ export interface PushedPage { id: string; name: string; url?: string; versionId: string; state: string }
218
+
219
+ export interface PushPagesOptions {
220
+ config: AppReleaseConfig;
221
+ localeMap?: Record<string, string>;
222
+ execute?: boolean;
223
+ /** Add every edited page version to a review submission and submit it. */
224
+ submit?: boolean;
225
+ }
226
+
227
+ export async function pushCustomProductPages({ config, localeMap, execute = false, submit = false }: PushPagesOptions): Promise<PushedPage[]> {
228
+ console.log(`App Store custom product pages ${execute ? '(EXECUTE)' : '(DRY RUN)'}`);
229
+ const plans = planPages(config, listingLocaleMap(config, 'apple', localeMap));
230
+ console.log(JSON.stringify(plans.map(p => ({ name: p.name, deepLink: p.deepLink, visible: p.visible,
231
+ locales: p.locales.map(l => ({ locale: l.locale, promotionalText: l.promotionalText, keywords: l.keywords.length ? l.keywords : undefined,
232
+ screenshots: l.screenshots.map(s => ({ profile: s.profile, files: s.files })) })) })), null, 2));
233
+ if (!execute) return [];
234
+
235
+ const client = createAscClient(config);
236
+ const app = await client.findApp();
237
+ const existing = await listAll(client, `/apps/${app.id}/appCustomProductPages?limit=200`);
238
+
239
+ // Keywords are checked against the app's live keywords before the first write.
240
+ const keywordLocales = new Set(plans.flatMap(p => p.locales.filter(l => l.keywords.length).map(l => l.locale)));
241
+ const available = new Map<string, Set<string>>();
242
+ for (const locale of keywordLocales) {
243
+ const rows = await listAll(client, `/apps/${app.id}/searchKeywords?filter[platform]=IOS&filter[locale]=${encodeURIComponent(locale)}&limit=200`);
244
+ available.set(locale, new Set(rows.map((k: any) => String(k.id))));
245
+ }
246
+ const missing = plans.flatMap(p => p.locales.flatMap(l => l.keywords.filter(k => !available.get(l.locale)?.has(k)).map(k => `${p.name} [${l.locale}]: "${k}"`)));
247
+ if (missing.length) throw new Error(`Not keywords of the live App Store version, so a page cannot take them:\n ${missing.join('\n ')}`);
248
+
249
+ // 1. Find or create each page, and the version that takes the edits.
250
+ const targets: { plan: PagePlan; page: any; live: boolean; versionId: string; state: string; localizations: Map<string, any> }[] = [];
251
+ for (const plan of plans) {
252
+ let page = existing.find((p: any) => p.attributes?.name === plan.name);
253
+ let version: any;
254
+ if (!page) {
255
+ const vRef = '${new-version}';
256
+ const included: any[] = [{ type: 'appCustomProductPageVersions', id: vRef, relationships: { appCustomProductPageLocalizations: {
257
+ data: plan.locales.map((_, i) => ({ type: 'appCustomProductPageLocalizations', id: `\${new-localization-${i}}` })) } } }];
258
+ plan.locales.forEach((l, i) => included.push({ type: 'appCustomProductPageLocalizations', id: `\${new-localization-${i}}`,
259
+ attributes: { locale: l.locale, ...(l.promotionalText ? { promotionalText: l.promotionalText } : {}) } }));
260
+ const created = await client.api('/appCustomProductPages', { method: 'POST', body: JSON.stringify({
261
+ data: { type: 'appCustomProductPages', attributes: { name: plan.name }, relationships: {
262
+ app: { data: { type: 'apps', id: app.id } },
263
+ appCustomProductPageVersions: { data: [{ type: 'appCustomProductPageVersions', id: vRef }] },
264
+ } },
265
+ included,
266
+ }) });
267
+ page = created.data;
268
+ console.log(`\n${plan.name}: created`);
269
+ } else {
270
+ console.log(`\n${plan.name}: found (${page.id})`);
271
+ }
272
+ const versions = await listAll(client, `/appCustomProductPages/${page.id}/appCustomProductPageVersions?limit=50`);
273
+ version = versions.find((v: any) => EDITABLE_PAGE_STATES.has(v.attributes?.state));
274
+ if (!version) {
275
+ const locked = versions.find((v: any) => ['READY_FOR_REVIEW', 'WAITING_FOR_REVIEW', 'IN_REVIEW'].includes(v.attributes?.state));
276
+ if (locked) throw new Error(`${plan.name}: version ${locked.attributes.version ?? locked.id} is ${locked.attributes.state} and cannot change until it is reviewed or withdrawn.`);
277
+ // An approved page changes through a new version; its URL stays the same.
278
+ const created = await client.api('/appCustomProductPageVersions', { method: 'POST', body: JSON.stringify({ data: {
279
+ type: 'appCustomProductPageVersions',
280
+ relationships: { appCustomProductPage: { data: { type: 'appCustomProductPages', id: page.id } } },
281
+ } }) });
282
+ version = created.data;
283
+ console.log(` new version ${version.id}; the live page stays as it is until this one is approved`);
284
+ }
285
+ const locs = await listAll(client, `/appCustomProductPageVersions/${version.id}/appCustomProductPageLocalizations?limit=200`);
286
+ targets.push({ plan, page, live: versions.some((v: any) => v.attributes?.state === 'APPROVED'), versionId: version.id, state: version.attributes?.state ?? 'PREPARE_FOR_SUBMISSION',
287
+ localizations: new Map(locs.map((l: any) => [l.attributes.locale, l])) });
288
+ }
289
+
290
+ // 2. Copy, deep link, visibility and localizations.
291
+ for (const t of targets) {
292
+ if (t.plan.deepLink !== undefined) {
293
+ await client.api(`/appCustomProductPageVersions/${t.versionId}`, { method: 'PATCH', body: JSON.stringify({ data: {
294
+ type: 'appCustomProductPageVersions', id: t.versionId, attributes: { deepLink: t.plan.deepLink } } }) });
295
+ }
296
+ // Visibility is a switch on a live page; a page App Review has not approved yet has nothing to show or hide.
297
+ if (t.live && t.page.attributes?.visible !== t.plan.visible) {
298
+ await client.api(`/appCustomProductPages/${t.page.id}`, { method: 'PATCH', body: JSON.stringify({ data: {
299
+ type: 'appCustomProductPages', id: t.page.id, attributes: { visible: t.plan.visible } } }) });
300
+ }
301
+ for (const l of t.plan.locales) {
302
+ let loc = t.localizations.get(l.locale);
303
+ if (!loc) {
304
+ const created = await client.api('/appCustomProductPageLocalizations', { method: 'POST', body: JSON.stringify({ data: {
305
+ type: 'appCustomProductPageLocalizations',
306
+ attributes: { locale: l.locale, ...(l.promotionalText ? { promotionalText: l.promotionalText } : {}) },
307
+ relationships: { appCustomProductPageVersion: { data: { type: 'appCustomProductPageVersions', id: t.versionId } } },
308
+ } }) });
309
+ loc = created.data;
310
+ t.localizations.set(l.locale, loc);
311
+ } else if (l.promotionalText !== undefined && loc.attributes?.promotionalText !== l.promotionalText) {
312
+ await client.api(`/appCustomProductPageLocalizations/${loc.id}`, { method: 'PATCH', body: JSON.stringify({ data: {
313
+ type: 'appCustomProductPageLocalizations', id: loc.id, attributes: { promotionalText: l.promotionalText } } }) });
314
+ }
315
+ if (t.plan.manageKeywords) {
316
+ const current = await listAll(client, `/appCustomProductPageLocalizations/${loc.id}/relationships/searchKeywords?limit=200`);
317
+ const have = new Set(current.map((k: any) => String(k.id)));
318
+ const add = l.keywords.filter(k => !have.has(k));
319
+ const drop = [...have].filter(k => !l.keywords.includes(k));
320
+ const body = (ids: string[]) => JSON.stringify({ data: ids.map(id => ({ type: 'appKeywords', id })) });
321
+ if (add.length) await client.api(`/appCustomProductPageLocalizations/${loc.id}/relationships/searchKeywords`, { method: 'POST', body: body(add) });
322
+ if (drop.length) await client.api(`/appCustomProductPageLocalizations/${loc.id}/relationships/searchKeywords`, { method: 'DELETE', body: body(drop) });
323
+ }
324
+ }
325
+ }
326
+
327
+ // 3. Screenshots: upload everything first, then replace placements.
328
+ const uploaded = await uploadAll(client, app.id, plans.flatMap(p => p.locales.flatMap(l => l.screenshots.flatMap(s => s.files))));
329
+ for (const t of targets) {
330
+ for (const l of t.plan.locales) {
331
+ const loc = t.localizations.get(l.locale)!;
332
+ await placeScreenshots(client, { rel: 'appCustomProductPageLocalization', type: 'appCustomProductPageLocalizations', id: loc.id,
333
+ label: `${t.plan.name} ${l.locale}` }, l.screenshots, uploaded);
334
+ }
335
+ }
336
+
337
+ // 4. URLs, the thing to link and tag with.
338
+ const pushed: PushedPage[] = [];
339
+ for (const t of targets) {
340
+ const { data } = await client.api(`/appCustomProductPages/${t.page.id}`);
341
+ pushed.push({ id: t.page.id, name: t.plan.name, url: data?.attributes?.url, versionId: t.versionId, state: t.state });
342
+ }
343
+ console.log('\nPage URLs (each carries ?ppid=<page id>; send traffic here to show the page):');
344
+ for (const p of pushed) console.log(` ${p.name}: ${p.url ?? '(App Store Connect returns the URL once the page exists)'}`);
345
+
346
+ if (submit) {
347
+ console.log('\n→ App Review');
348
+ const result = await addToReview(client, app.id, pushed.map(p => ({ rel: 'appCustomProductPageVersion', type: 'appCustomProductPageVersions', id: p.versionId, label: p.name })));
349
+ for (const p of pushed) p.state = result === 'submitted' ? 'WAITING_FOR_REVIEW' : p.state;
350
+ } else {
351
+ console.log('\nNot submitted. A page goes live after App Review: run again with --submit, or submit it in App Store Connect.');
352
+ }
353
+ return pushed;
354
+ }
355
+
356
+ export interface TestStatus {
357
+ id: string;
358
+ name: string;
359
+ state: string;
360
+ trafficProportion?: number;
361
+ reviewRequired?: boolean;
362
+ startDate?: string;
363
+ endDate?: string;
364
+ treatments: { id: string; name: string }[];
365
+ }
366
+
367
+ /** The configured test by name, preferring one that is not finished. */
368
+ export async function findTest(client: AscClient, appId: string, name: string): Promise<any | undefined> {
369
+ const tests = await listAll(client, `/apps/${appId}/appStoreVersionExperimentsV2?limit=50`);
370
+ const named = tests.filter((t: any) => t.attributes?.name === name);
371
+ return named.find((t: any) => !FINISHED_TEST_STATES.has(t.attributes?.state)) ?? named[0];
372
+ }
373
+
374
+ export async function testStatus(client: AscClient, test: any): Promise<TestStatus> {
375
+ const treatments = await listAll(client, `/v2/appStoreVersionExperiments/${test.id}/appStoreVersionExperimentTreatments?limit=10`);
376
+ const a = test.attributes ?? {};
377
+ return { id: test.id, name: a.name, state: a.state, trafficProportion: a.trafficProportion, reviewRequired: a.reviewRequired,
378
+ startDate: a.startDate ?? undefined, endDate: a.endDate ?? undefined,
379
+ treatments: treatments.map((t: any) => ({ id: t.id, name: t.attributes?.name })) };
380
+ }
381
+
382
+ export interface PushTestOptions {
383
+ config: AppReleaseConfig;
384
+ localeMap?: Record<string, string>;
385
+ execute?: boolean;
386
+ /** Start the test, and send it to App Review when its treatments need it. */
387
+ start?: boolean;
388
+ /** Stop a running test. A stopped test cannot restart. */
389
+ stop?: boolean;
390
+ }
391
+
392
+ export async function pushProductPageTest({ config, localeMap, execute = false, start = false, stop = false }: PushTestOptions): Promise<TestStatus | undefined> {
393
+ if (start && stop) throw new Error('--start and --stop conflict.');
394
+ if (stop) {
395
+ const name = config.ascProductPageTest?.name;
396
+ if (!name) throw new Error('release.config.ts needs `ascProductPageTest.name` to find the test to stop.');
397
+ console.log(`Stop product page test "${name}" ${execute ? '(EXECUTE)' : '(DRY RUN)'}. A stopped test cannot restart.`);
398
+ if (!execute) return undefined;
399
+ const client = createAscClient(config);
400
+ const app = await client.findApp();
401
+ const test = await findTest(client, app.id, name);
402
+ if (!test) throw new Error(`No product page test named "${name}".`);
403
+ await client.api(`/v2/appStoreVersionExperiments/${test.id}`, { method: 'PATCH', body: JSON.stringify({ data: {
404
+ type: 'appStoreVersionExperiments', id: test.id, attributes: { started: false } } }) });
405
+ const { data } = await client.api(`/v2/appStoreVersionExperiments/${test.id}`);
406
+ const status = await testStatus(client, data);
407
+ console.log(` ${status.name}: ${status.state}`);
408
+ return status;
409
+ }
410
+
411
+ console.log(`App Store product page test ${execute ? '(EXECUTE)' : '(DRY RUN)'}`);
412
+ const plan = planTest(config, listingLocaleMap(config, 'apple', localeMap));
413
+ console.log(JSON.stringify({ name: plan.name, trafficProportion: plan.trafficProportion, treatments: plan.treatments.map(t => ({
414
+ name: t.name, appIconName: t.appIconName, locales: t.locales.map(l => ({ locale: l.locale, screenshots: l.screenshots })) })) }, null, 2));
415
+ console.log(`${plan.trafficProportion}% of the default page's visitors see a treatment, split evenly; the rest see the original.`);
416
+ if (plan.treatments.some(t => t.appIconName)) console.log('An alternate icon must be in the live binary, or App Store Connect refuses the treatment.');
417
+ if (!execute) return undefined;
418
+
419
+ const client = createAscClient(config);
420
+ const app = await client.findApp();
421
+ let test = await findTest(client, app.id, plan.name);
422
+ if (test && FINISHED_TEST_STATES.has(test.attributes?.state)) {
423
+ throw new Error(`"${plan.name}" already ran (${test.attributes.state}). A finished test cannot restart; give the next one a new name.`);
424
+ }
425
+ if (!test) {
426
+ const created = await client.api('/v2/appStoreVersionExperiments', { method: 'POST', body: JSON.stringify({ data: {
427
+ type: 'appStoreVersionExperiments',
428
+ attributes: { name: plan.name, platform: 'IOS', trafficProportion: plan.trafficProportion },
429
+ relationships: { app: { data: { type: 'apps', id: app.id } } },
430
+ } }) });
431
+ test = created.data;
432
+ console.log(`\n${plan.name}: created (${test.id})`);
433
+ } else {
434
+ console.log(`\n${plan.name}: found (${test.id}, ${test.attributes?.state})`);
435
+ }
436
+
437
+ const editable = EDITABLE_TEST_STATES.has(test.attributes?.state ?? 'PREPARE_FOR_SUBMISSION');
438
+ if (editable) {
439
+ if (test.attributes?.trafficProportion !== undefined && test.attributes.trafficProportion !== plan.trafficProportion) {
440
+ await client.api(`/v2/appStoreVersionExperiments/${test.id}`, { method: 'PATCH', body: JSON.stringify({ data: {
441
+ type: 'appStoreVersionExperiments', id: test.id, attributes: { trafficProportion: plan.trafficProportion } } }) });
442
+ }
443
+ const current = await listAll(client, `/v2/appStoreVersionExperiments/${test.id}/appStoreVersionExperimentTreatments?limit=10`);
444
+ for (const t of current) {
445
+ if (!plan.treatments.some(p => p.name === t.attributes?.name)) {
446
+ await client.api(`/appStoreVersionExperimentTreatments/${t.id}`, { method: 'DELETE' });
447
+ console.log(` removed treatment "${t.attributes?.name}"`);
448
+ }
449
+ }
450
+ const owners: { owner: Owner; sets: ScreenshotSet[] }[] = [];
451
+ for (const p of plan.treatments) {
452
+ let treatment = current.find((t: any) => t.attributes?.name === p.name);
453
+ if (!treatment) {
454
+ const created = await client.api('/appStoreVersionExperimentTreatments', { method: 'POST', body: JSON.stringify({ data: {
455
+ type: 'appStoreVersionExperimentTreatments',
456
+ attributes: { name: p.name, ...(p.appIconName ? { appIconName: p.appIconName } : {}) },
457
+ relationships: { appStoreVersionExperimentV2: { data: { type: 'appStoreVersionExperiments', id: test.id } } },
458
+ } }) });
459
+ treatment = created.data;
460
+ console.log(` treatment "${p.name}" created`);
461
+ } else if ((treatment.attributes?.appIconName ?? undefined) !== p.appIconName && p.appIconName !== undefined) {
462
+ await client.api(`/appStoreVersionExperimentTreatments/${treatment.id}`, { method: 'PATCH', body: JSON.stringify({ data: {
463
+ type: 'appStoreVersionExperimentTreatments', id: treatment.id, attributes: { appIconName: p.appIconName } } }) });
464
+ }
465
+ const locs = await listAll(client, `/appStoreVersionExperimentTreatments/${treatment.id}/appStoreVersionExperimentTreatmentLocalizations?limit=200`);
466
+ const byLocale = new Map(locs.map((l: any) => [l.attributes?.locale, l]));
467
+ for (const l of p.locales) {
468
+ let loc = byLocale.get(l.locale);
469
+ if (!loc) {
470
+ const created = await client.api('/appStoreVersionExperimentTreatmentLocalizations', { method: 'POST', body: JSON.stringify({ data: {
471
+ type: 'appStoreVersionExperimentTreatmentLocalizations',
472
+ attributes: { locale: l.locale },
473
+ relationships: { appStoreVersionExperimentTreatment: { data: { type: 'appStoreVersionExperimentTreatments', id: treatment.id } } },
474
+ } }) });
475
+ loc = created.data;
476
+ }
477
+ owners.push({ owner: { rel: 'appStoreVersionExperimentTreatmentLocalization', type: 'appStoreVersionExperimentTreatmentLocalizations',
478
+ id: loc.id, label: `${p.name} ${l.locale}` }, sets: l.screenshots });
479
+ }
480
+ }
481
+ const uploaded = await uploadAll(client, app.id, owners.flatMap(o => o.sets.flatMap(s => s.files)));
482
+ for (const o of owners) await placeScreenshots(client, o.owner, o.sets, uploaded);
483
+ } else {
484
+ console.log(` ${test.attributes?.state}: treatments are locked; nothing changed`);
485
+ }
486
+
487
+ if (start) {
488
+ console.log('\n→ Starting');
489
+ await client.api(`/v2/appStoreVersionExperiments/${test.id}`, { method: 'PATCH', body: JSON.stringify({ data: {
490
+ type: 'appStoreVersionExperiments', id: test.id, attributes: { started: true } } }) });
491
+ const { data } = await client.api(`/v2/appStoreVersionExperiments/${test.id}`);
492
+ test = data;
493
+ if (test.attributes?.reviewRequired) {
494
+ const item: ReviewItem = { rel: 'appStoreVersionExperimentV2', type: 'appStoreVersionExperiments', id: test.id, label: plan.name };
495
+ await addToReview(client, app.id, [item]);
496
+ console.log(' The test runs once App Review accepts its treatments.');
497
+ }
498
+ }
499
+ const status = await testStatus(client, test);
500
+ console.log(`\n${status.name}: ${status.state}${status.startDate ? `, started ${status.startDate}` : ''}`);
501
+ if (!start && editable) console.log('Not started. Run again with --start when the treatments look right.');
502
+ return status;
503
+ }
504
+
505
+ /** The configured test's current status, or undefined when App Store Connect has none by that name. */
506
+ export async function readProductPageTest(config: AppReleaseConfig): Promise<TestStatus | undefined> {
507
+ const name = config.ascProductPageTest?.name;
508
+ if (!name) throw new Error('release.config.ts needs `ascProductPageTest.name`.');
509
+ const client = createAscClient(config);
510
+ const app = await client.findApp();
511
+ const test = await findTest(client, app.id, name);
512
+ return test ? testStatus(client, test) : undefined;
513
+ }
@@ -83,3 +83,67 @@ export async function cancelSubmission(
83
83
  await sleep(15_000);
84
84
  }
85
85
  }
86
+
87
+ /** A page version or a test that goes to App Review through a review submission. */
88
+ export interface ReviewItem {
89
+ rel: 'appCustomProductPageVersion' | 'appStoreVersionExperimentV2';
90
+ /** The JSON:API type. A v2 experiment is still `appStoreVersionExperiments`. */
91
+ type: 'appCustomProductPageVersions' | 'appStoreVersionExperiments';
92
+ id: string;
93
+ label: string;
94
+ }
95
+
96
+ /**
97
+ * Put items on the app's draft review submission and submit it, without ever
98
+ * sending something else along. When the draft already holds other items (an
99
+ * app version being prepared, say), the items are added and the draft is left
100
+ * for whoever submits that, the same choice App Store Connect offers. A
101
+ * rejected submission is never cancelled from here: it may be someone's fix.
102
+ */
103
+ export async function addToReview(client: AscClient, appId: string, items: ReviewItem[], submit = true): Promise<'submitted' | 'drafted'> {
104
+ const submissions = await listSubmissions(client, appId);
105
+ const rejected = submissions.find(s => s.state === REJECTED_SUBMISSION_STATE);
106
+ if (rejected) {
107
+ throw new Error(`A rejected review submission (${rejected.id}) holds the app's submission slot. Resolve it with asc-submit or in App Store Connect, then run this again.`);
108
+ }
109
+ let draft = submissions.find(s => OPEN_SUBMISSION_STATES.has(s.state));
110
+ let others = 0;
111
+ const present = new Set<string>();
112
+ if (draft) {
113
+ const res = await client.api(`/reviewSubmissions/${draft.id}/items?include=appStoreVersion,appCustomProductPageVersion,appStoreVersionExperimentV2&limit=50`);
114
+ for (const item of res.data ?? []) {
115
+ const linked = Object.values(item.relationships ?? {}).map((r: any) => r?.data?.id).filter(Boolean) as string[];
116
+ const ours = linked.filter(id => items.some(i => i.id === id));
117
+ ours.forEach(id => present.add(id));
118
+ if (!ours.length) others++;
119
+ }
120
+ console.log(` reusing draft review submission ${draft.id}${others ? ` (${others} other item${others === 1 ? '' : 's'})` : ''}`);
121
+ } else {
122
+ const created = await client.api('/reviewSubmissions', { method: 'POST', body: JSON.stringify({ data: {
123
+ type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: { data: { type: 'apps', id: appId } } },
124
+ } }) });
125
+ draft = { id: created.data.id, state: created.data.attributes?.state ?? 'READY_FOR_REVIEW' };
126
+ console.log(` created review submission ${draft.id}`);
127
+ }
128
+ for (const item of items) {
129
+ if (present.has(item.id)) { console.log(` ${item.label}: already on the submission`); continue; }
130
+ await client.api('/reviewSubmissionItems', { method: 'POST', body: JSON.stringify({ data: {
131
+ type: 'reviewSubmissionItems',
132
+ relationships: {
133
+ reviewSubmission: { data: { type: 'reviewSubmissions', id: draft.id } },
134
+ [item.rel]: { data: { type: item.type, id: item.id } },
135
+ },
136
+ } }) });
137
+ console.log(` ${item.label}: added`);
138
+ }
139
+ if (others) {
140
+ console.log(' Not submitted: the draft holds other items. It goes to review when that submission is sent (asc-submit, ship, or App Store Connect).');
141
+ return 'drafted';
142
+ }
143
+ if (!submit) return 'drafted';
144
+ await client.api(`/reviewSubmissions/${draft.id}`, { method: 'PATCH', body: JSON.stringify({ data: {
145
+ type: 'reviewSubmissions', id: draft.id, attributes: { submitted: true },
146
+ } }) });
147
+ console.log(' submitted for review');
148
+ return 'submitted';
149
+ }
package/src/cli.ts CHANGED
@@ -15,6 +15,8 @@ import { uploadIpa } from './asc/upload.ts';
15
15
  import { submitForReview } from './asc/submit.ts';
16
16
  import { uploadAab } from './play/upload.ts';
17
17
  import { annotate, appSlugFromRepo } from './annotate.ts';
18
+ import { pushCustomProductPages, pushProductPageTest, readProductPageTest } from './asc/product-pages.ts';
19
+ import { printPageResults, readPageResults, resultsLabel } from './asc/page-results.ts';
18
20
 
19
21
  const has = (...names: string[]) => names.some((n) => process.argv.includes(`--${n}`));
20
22
  const value = (name: string) => {
@@ -44,7 +46,11 @@ const COMMANDS: Record<string, { usage: string; bool: string[]; values?: string[
44
46
  'asc-creative': { usage: 'asc-creative [--execute]', bool: ['execute'] },
45
47
  'play-screenshots': { usage: 'play-screenshots [--execute]', bool: ['execute'] },
46
48
  'play-graphics': { usage: 'play-graphics [--execute]', bool: ['execute'] },
49
+ pages: { usage: 'pages [--execute] [--submit]', bool: ['execute', 'submit'] },
50
+ 'page-test': { usage: 'page-test [--execute] [--start|--stop] | page-test --result <text> --annotate', bool: ['execute', 'start', 'stop'], values: ['result'] },
51
+ 'page-results': { usage: 'page-results [--days <n>] [--request-reports --execute]', bool: ['execute', 'request-reports'], values: ['days'] },
47
52
  };
53
+ for (const name of ['pages', 'page-test', 'page-results']) COMMANDS[`asc-${name}`] = COMMANDS[name];
48
54
 
49
55
  function printUsage(command?: string): void {
50
56
  const spec = command ? COMMANDS[command] : undefined;
@@ -54,9 +60,10 @@ function printUsage(command?: string): void {
54
60
  }
55
61
  console.log('Usage: sprid release <command> [flags]\n');
56
62
  console.log('Commands:');
57
- for (const name of ['ship', 'bump', 'credentials-pull', 'credentials-push', 'asc-upload', 'play-upload', 'asc-submit', 'metadata', 'screenshots', 'graphics', 'creative']) console.log(` ${COMMANDS[name].usage}`);
63
+ for (const name of ['ship', 'bump', 'credentials-pull', 'credentials-push', 'asc-upload', 'play-upload', 'asc-submit', 'metadata', 'screenshots', 'graphics', 'creative', 'pages', 'page-test', 'page-results']) console.log(` ${COMMANDS[name].usage}`);
58
64
  console.log('\nWithout --execute every command is a dry run: it prints what it would send.');
59
- console.log('Per-store names also work: asc-metadata, play-metadata, asc-screenshots, play-screenshots, play-graphics, asc-creative.');
65
+ console.log('Per-store names also work: asc-metadata, play-metadata, asc-screenshots, play-screenshots, play-graphics, asc-creative, asc-pages, asc-page-test, asc-page-results.');
66
+ console.log('page-results only reads; it needs no --execute except to create the report request.');
60
67
  console.log('\n--config <file> accepts TS, JS, MJS or JSON. Paths resolve beside that file.');
61
68
  console.log('--locale <locale,...> selects store locale codes. --annotate records executed changes in Sprid (opt-in).');
62
69
  console.log('\nCredentials (never read into an agent conversation):');
@@ -115,7 +122,9 @@ async function main() {
115
122
  return Object.fromEntries(selectedLocales.map(locale => [locale, map[locale]]));
116
123
  };
117
124
  const execute = has('execute');
118
- if (!execute) console.log('Dry run. Nothing is sent without --execute.\n');
125
+ const pageCommand = command.replace(/^asc-/, '');
126
+ const readOnly = pageCommand === 'page-results' || (pageCommand === 'page-test' && value('result') !== undefined);
127
+ if (!execute && !readOnly) console.log('Dry run. Nothing is sent without --execute.\n');
119
128
 
120
129
  const requireValue = (name: string) => { const v = value(name); if (!v) throw new Error(`--${name} is required.`); return v; };
121
130
  const bumpKinds = (['patch', 'minor', 'major'] as const).filter(k => has(k));
@@ -147,6 +156,12 @@ async function main() {
147
156
  return;
148
157
  }
149
158
 
159
+ if (['pages', 'page-test', 'page-results'].includes(pageCommand)) {
160
+ if (!config.appId && !config.ascAppId) throw new Error('Set appId or ascAppId for App Store commands.');
161
+ await pageCommands(config, pageCommand, command, execute, () => localeMap('apple'));
162
+ return;
163
+ }
164
+
150
165
  const needCopy = () => {
151
166
  if (!config.storeCopy) throw new Error('release.config.ts needs `storeCopy` for metadata commands.');
152
167
  return config.storeCopy;
@@ -218,6 +233,53 @@ async function main() {
218
233
  }
219
234
  }
220
235
 
236
+ const fit = (label: string) => (label.length > 200 ? `${label.slice(0, 199)}…` : label);
237
+ const annotated = (ok: boolean) => console.log(ok ? '\nRecorded in Sprid.' : '\nNot recorded in Sprid: sign in with `sprid login` or set SPRID_PAT.');
238
+
239
+ /** Custom product pages, the product page test and their results. */
240
+ async function pageCommands(config: AppReleaseConfig, name: string, command: string, execute: boolean, locales: () => Record<string, string>): Promise<void> {
241
+ const app = appSlugFromRepo(releasePath(config, '.'));
242
+ if (name === 'pages') {
243
+ const submit = has('submit');
244
+ if (submit && !execute) console.log('--submit sends the pages to App Review together with --execute.');
245
+ const pushed = await pushCustomProductPages({ config, localeMap: locales(), execute, submit });
246
+ if (execute && has('annotate') && pushed.length) {
247
+ annotated(await annotate({ kind: 'screenshots', app, areas: ['store'], meta: { command, customProductPages: pushed },
248
+ label: fit(`Custom product pages ${submit ? 'sent to review' : 'updated'}: ${pushed.map(p => p.name).join(', ')}`) }));
249
+ }
250
+ return;
251
+ }
252
+ if (name === 'page-test') {
253
+ const result = value('result');
254
+ if (result !== undefined) {
255
+ if (!has('annotate')) throw new Error('--result records what Apple shows for the test in Sprid; add --annotate.');
256
+ if (execute || has('start') || has('stop')) throw new Error('--result only records a reading; run it without --execute, --start or --stop.');
257
+ const status = await readProductPageTest(config);
258
+ if (!status) throw new Error(`App Store Connect has no product page test named "${config.ascProductPageTest?.name}".`);
259
+ annotated(await annotate({ kind: 'note', app, areas: ['store'], meta: { command, result, productPageTest: status },
260
+ label: fit(`Product page test "${status.name}": ${result}`) }));
261
+ return;
262
+ }
263
+ const start = has('start'), stop = has('stop');
264
+ const status = await pushProductPageTest({ config, localeMap: stop ? undefined : locales(), execute, start, stop });
265
+ if (execute && has('annotate') && status && (start || stop)) {
266
+ const label = stop ? `Product page test "${status.name}" stopped`
267
+ : `Product page test "${status.name}" started: ${status.treatments.length} treatment${status.treatments.length === 1 ? '' : 's'}, ${status.trafficProportion}% of visitors`;
268
+ annotated(await annotate({ kind: stop ? 'note' : 'screenshots', app, areas: ['store'], meta: { command, productPageTest: status }, label: fit(label) }));
269
+ }
270
+ return;
271
+ }
272
+ const days = value('days') === undefined ? 28 : Number(value('days'));
273
+ const results = await readPageResults({ config, days, requestReports: has('request-reports'), execute });
274
+ printPageResults(results);
275
+ if (has('annotate') && results.status === 'ok') {
276
+ const urls = new Map(results.pages.map(p => [p.name, p]));
277
+ const pages = results.rows.filter(r => urls.has(r.title) || /default/i.test(r.title)).map(r => ({ ...r, id: urls.get(r.title)?.id, url: urls.get(r.title)?.url }));
278
+ annotated(await annotate({ kind: 'note', app, areas: ['store'], label: resultsLabel(results),
279
+ meta: { command, window: results.window, coverage: results.coverage, pages, productPageTest: results.test } }));
280
+ }
281
+ }
282
+
221
283
  main().catch((err) => {
222
284
  console.error(err instanceof Error ? err.message : err);
223
285
  process.exit(1);
package/src/config.ts CHANGED
@@ -277,6 +277,61 @@ export interface AscCreativeConfig {
277
277
  posterFrame?: string;
278
278
  }
279
279
 
280
+ /** One ordered screenshot set for a page or a test treatment. The glob may contain `{lang}`. */
281
+ export interface AscPageScreenshots {
282
+ /** Base dir, relative to the config. */
283
+ dir: string;
284
+ /** Glob under `dir` whose last segment has one `*`, e.g. `{lang}/focus_*.png`. Sorted by name. */
285
+ glob: string;
286
+ /** Device profile (Asset Library placement group). Default `IPHONE_DYNAMIC_ISLAND_LARGE_PROFILE`. */
287
+ profile?: string;
288
+ }
289
+
290
+ /**
291
+ * A custom product page (for the `pages` command): its own screenshots, promotional
292
+ * text, optional deep link and search keywords, reached at its own URL (`?ppid=`).
293
+ */
294
+ export interface AscCustomProductPage {
295
+ /**
296
+ * Name in App Store Connect, unique within the app. Apple's analytics reports
297
+ * identify the page by this name, so renaming it splits its history.
298
+ */
299
+ name: string;
300
+ /** One set per device profile, e.g. iPhone and iPad. */
301
+ screenshots: AscPageScreenshots | AscPageScreenshots[];
302
+ /** Promotional text by copy-locale key, at most 170 characters. Default: the locale's `storeCopy.promotionalText`. */
303
+ promotionalText?: Record<string, string>;
304
+ /** Where the app opens from this page (iOS 18 and later; reviewed with the page). */
305
+ deepLink?: string;
306
+ /**
307
+ * Search keywords by copy-locale key that lead to this page instead of the
308
+ * default one. Each must already be a keyword of the live App Store version.
309
+ */
310
+ keywords?: Record<string, string[]>;
311
+ /** Whether the page is reachable once approved. Default true. */
312
+ visible?: boolean;
313
+ }
314
+
315
+ /** One treatment of a product page optimization test. */
316
+ export interface AscTestTreatment {
317
+ /** Name in App Store Connect and in the results. */
318
+ name: string;
319
+ /** An alternate app icon compiled into the live binary. */
320
+ appIconName?: string;
321
+ /** Screenshots shown to this treatment's share of visitors. */
322
+ screenshots?: AscPageScreenshots | AscPageScreenshots[];
323
+ }
324
+
325
+ /** A product page optimization test (for the `page-test` command). One runs at a time. */
326
+ export interface AscProductPageTest {
327
+ /** Name in App Store Connect. A finished test cannot restart, so a new test needs a new name. */
328
+ name: string;
329
+ /** Percent of App Store visitors who see a treatment instead of the original (1-100), split evenly between treatments. */
330
+ trafficProportion: number;
331
+ /** One to three treatments. */
332
+ treatments: AscTestTreatment[];
333
+ }
334
+
280
335
  /** Play feature-graphic + icon source (for the `play-graphics` command). */
281
336
  export interface PlayGraphicsConfig {
282
337
  /** Feature graphic PNG (1024×500); may contain `{lang}`. */
@@ -350,6 +405,10 @@ export interface AppReleaseConfig {
350
405
  playGraphics?: PlayGraphicsConfig;
351
406
  /** Source for `asc-creative` (product page header, search results asset, app previews). */
352
407
  ascCreative?: AscCreativeConfig;
408
+ /** Custom product pages, for the `pages` command. */
409
+ ascCustomProductPages?: AscCustomProductPage[];
410
+ /** The product page optimization test, for the `page-test` command. */
411
+ ascProductPageTest?: AscProductPageTest;
353
412
  /**
354
413
  * Listing-locale maps for the metadata pushes (which locales the *listings*
355
414
  * ship in — may be narrower than `locales`, which also drives release notes).