@sprid/release 1.3.0 → 1.5.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,28 @@
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.5.0 - 2026-10-31
7
+
8
+ - `asc-submit` applies `ageRating` from the release config to the editable app
9
+ info's age rating declaration before submitting, and names questions still
10
+ unanswered. Apple's 409 for a missing answer (`socialMedia`, added October
11
+ 2026) now reads as the config key to set.
12
+
13
+ ## 1.4.0 - 2026-10-30
14
+
15
+ - `pages` (`asc-pages`) creates and updates App Store custom product pages from
16
+ `ascCustomProductPages`: screenshots per device profile, promotional text, deep
17
+ link, search keywords and visibility. It prints each page's URL; `--submit`
18
+ sends the page versions to App Review.
19
+ - `page-test` (`asc-page-test`) creates a product page optimization test from
20
+ `ascProductPageTest` with up to three treatments; `--start` starts it and sends
21
+ it to App Review when needed, `--stop` ends it. `--result <text> --annotate`
22
+ records the result Apple shows, since Apple's API has none.
23
+ - `page-results` (`asc-page-results`) reads page views and first-time downloads
24
+ per page from Apple's Detailed analytics reports, each date counted once.
25
+ `--annotate` records the comparison in Sprid.
26
+ - Neither command submits a draft review submission that holds other items.
27
+
6
28
  ## 1.3.0 - 2026-10-30
7
29
 
8
30
  - `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
@@ -169,6 +230,12 @@ beside that file (`credentialsPathBase` overrides). `build.envFile: { path, keys
169
230
  allowlist without printing values. `requiredProdEnv` rejects missing values and
170
231
  local URLs. Gradle memory settings change only with `build.gradleJvmArgs`.
171
232
 
233
+ `asc-submit` writes `reviewContact` onto the version and `ageRating` onto the
234
+ editable app info before it submits, e.g. `ageRating: { socialMedia: false }`
235
+ with keys from Apple's `ageRatingDeclarations`. Apple adds required age rating
236
+ questions between releases; the submit names any still unanswered, and Apple's
237
+ 409 for one comes back as the config key to set.
238
+
172
239
  For another toolchain, `build.commands.ios` or `.android` replaces that platform's
173
240
  native build and signing steps with `{ command: ['tool', 'arg'], artifact: 'path' }`.
174
241
  Commands run in `appDir`; artifact paths resolve beside the release config. The
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprid/release",
3
- "version": "1.3.0",
3
+ "version": "1.5.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
  });
@@ -0,0 +1,86 @@
1
+ /** App Store age rating answers, written onto the editable app info before review. */
2
+ import type { AgeRatingAnswers } from '../config.ts';
3
+ import type { AscClient } from './client.ts';
4
+
5
+ /** App info states whose age rating declaration still accepts edits. */
6
+ const EDITABLE_APP_INFO_STATES = new Set([
7
+ 'PREPARE_FOR_SUBMISSION',
8
+ 'DEVELOPER_REJECTED',
9
+ 'REJECTED',
10
+ 'METADATA_REJECTED',
11
+ ]);
12
+
13
+ /**
14
+ * Attributes Apple leaves null on a complete declaration: kids-category band,
15
+ * Korean classification, an optional info URL, and the overrides. Any other
16
+ * null is a question nobody answered, usually one Apple added since the last
17
+ * release (`socialMedia`, October 2026).
18
+ */
19
+ const OPTIONAL_ATTRIBUTES = new Set([
20
+ 'kidsAgeBand',
21
+ 'gracRatingClassificationNumber',
22
+ 'developerAgeRatingInfoUrl',
23
+ 'ageRatingOverride',
24
+ 'ageRatingOverrideV2',
25
+ 'koreaAgeRatingOverride',
26
+ ]);
27
+
28
+ /** Questions Apple asks only after another answer, keyed by that answer. */
29
+ const FOLLOW_UPS: Record<string, string> = { socialMediaAgeRestricted: 'socialMedia' };
30
+
31
+ export function unansweredAgeRatingQuestions(attributes: Record<string, unknown>): string[] {
32
+ return Object.entries(attributes)
33
+ .filter(([key, value]) => value === null && !OPTIONAL_ATTRIBUTES.has(key))
34
+ .filter(([key]) => !FOLLOW_UPS[key] || attributes[FOLLOW_UPS[key]] === true)
35
+ .map(([key]) => key);
36
+ }
37
+
38
+ /**
39
+ * Applies `ageRating` from the release config to the editable app info's
40
+ * declaration, then names every question still unanswered. Apple adds
41
+ * required questions without notice and `POST /reviewSubmissionItems` 409s on
42
+ * the first null one, after the build, metadata and screenshots are already up.
43
+ */
44
+ export async function ensureAgeRating(client: AscClient, appId: string, answers: AgeRatingAnswers | undefined): Promise<void> {
45
+ console.log(`\n→ Age rating`);
46
+ const infos = await client.api(`/apps/${appId}/appInfos?limit=10`);
47
+ const info = (infos.data ?? []).find((i: any) => EDITABLE_APP_INFO_STATES.has(i.attributes?.state ?? i.attributes?.appStoreState));
48
+ if (!info) {
49
+ console.log(' · no editable app info; the live declaration carries forward');
50
+ return;
51
+ }
52
+ const declaration = (await client.api(`/appInfos/${info.id}/ageRatingDeclaration`)).data;
53
+ let attributes: Record<string, unknown> = declaration.attributes ?? {};
54
+
55
+ const changes = Object.fromEntries(Object.entries(answers ?? {}).filter(([key, value]) => attributes[key] !== value));
56
+ if (Object.keys(changes).length) {
57
+ const patched = await client.api(`/ageRatingDeclarations/${declaration.id}`, {
58
+ method: 'PATCH',
59
+ body: JSON.stringify({ data: { type: 'ageRatingDeclarations', id: declaration.id, attributes: changes } }),
60
+ });
61
+ attributes = patched?.data?.attributes ?? { ...attributes, ...changes };
62
+ console.log(` ✓ set ${Object.entries(changes).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(', ')}`);
63
+ } else {
64
+ console.log(' ✓ matches release config');
65
+ }
66
+
67
+ const unanswered = unansweredAgeRatingQuestions(attributes);
68
+ if (unanswered.length) {
69
+ console.log(` ⚠ unanswered: ${unanswered.join(', ')}. Add them to ageRating in the release config, or review will refuse the version.`);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Turns Apple's 409 for a version with unanswered age rating questions into
75
+ * one line naming the config keys. Returns undefined for any other error.
76
+ */
77
+ export function ageRatingSubmissionError(error: unknown): Error | undefined {
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ if (!message.includes('/ageRatingDeclarations/')) return undefined;
80
+ const missing = [...message.matchAll(/value for the attribute '([^']+)'/g)].map(match => match[1]);
81
+ if (!missing.length) return undefined;
82
+ return new Error(
83
+ `App Store age rating is missing ${[...new Set(missing)].join(', ')}. ` +
84
+ `Answer ${missing.length > 1 ? 'them' : 'it'} in ageRating in the release config and run asc-submit again.`,
85
+ );
86
+ }
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
+ }