Play Developer Reporting API v1beta1 (crashRateMetricSet / anrRateMetricSet DAILY queries in America/Los_Angeles, user-perceived 28-day rates, worst device models, errorIssues:search) and App Store Connect perfPowerMetrics, diagnostic signatures and TestFlight crash submissions. Thresholds 1.09 % crash / 0.47 % ANR / 8 % per device (developer.android.com/topic/performance/vitals): over = blocker, from 80 % = warn, in validate too (--no-health). Weekly Markdown report with week-over-week change in .storebound/health/. MCP: health (read-only), health_report.
110 lines
6.1 KiB
TypeScript
110 lines
6.1 KiB
TypeScript
// App Store Connect API client: ES256 JWT from a team API key (Users and Access > Integrations > App Store Connect
|
|
// API; role Admin or App Manager), paging, retries, the asset upload protocol, and the app / version lookups.
|
|
import { createHash, createPrivateKey, sign } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { ascKey } from '../lib/credentials';
|
|
|
|
const b64 = (b: Buffer | string): string => Buffer.from(b).toString('base64url');
|
|
export const md5 = (b: Buffer | Uint8Array): string => createHash('md5').update(b).digest('hex');
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
export type J = any;
|
|
export type Asc = Awaited<ReturnType<typeof ascClient>>;
|
|
|
|
/** Versions that can still be edited (being prepared or sent back). */
|
|
export const EDITABLE = new Set(['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'METADATA_REJECTED', 'INVALID_BINARY']);
|
|
|
|
/** Delivery states after which an uploaded screenshot / preview counts as there. */
|
|
const DELIVERED = ['COMPLETE', 'UPLOAD_COMPLETE', 'PROCESSING'];
|
|
|
|
/** A screenshot / preview set already holds exactly these files (same MD5s, same order, none failed or half uploaded):
|
|
* then a sync leaves it alone. Pure. */
|
|
export function setUpToDate(existing: { checksum?: string | null; state?: string | null }[], want: string[]): boolean {
|
|
return existing.length === want.length && existing.every((e, i) => e.checksum === want[i] && DELIVERED.includes(e.state ?? ''));
|
|
}
|
|
|
|
export async function ascClient(root: string, bundleId: string, appIdHint?: string) {
|
|
const k = ascKey(root);
|
|
const key = createPrivateKey(k.pem);
|
|
let cached = { jwt: '', until: 0 };
|
|
function jwt(): string {
|
|
const now = Math.floor(Date.now() / 1000);
|
|
if (cached.jwt && now < cached.until) return cached.jwt;
|
|
const h = b64(JSON.stringify({ alg: 'ES256', kid: k.keyId, typ: 'JWT' }));
|
|
const p = b64(JSON.stringify({ iss: k.issuerId, iat: now, exp: now + 1100, aud: 'appstoreconnect-v1' }));
|
|
cached = { jwt: `${h}.${p}.${b64(sign('sha256', Buffer.from(h + '.' + p), { key, dsaEncoding: 'ieee-p1363' }))}`, until: now + 900 };
|
|
return cached.jwt;
|
|
}
|
|
|
|
async function asc(method: string, path: string, body?: unknown, attempt = 1): Promise<J> {
|
|
const r = await fetch(path.startsWith('http') ? path : 'https://api.appstoreconnect.apple.com' + path, {
|
|
method, headers: { Authorization: 'Bearer ' + jwt(), 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
const t = await r.text();
|
|
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
|
|
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${t.slice(0, 1500)}`);
|
|
return t ? JSON.parse(t) : {};
|
|
}
|
|
|
|
/** GET with a vendor media type, e.g. perfPowerMetrics (application/vnd.apple.xcode-metrics+json). Parsed JSON. */
|
|
async function getAs(path: string, accept: string): Promise<J> {
|
|
for (let attempt = 1; ; attempt++) {
|
|
const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } });
|
|
const t = await r.text();
|
|
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); continue; }
|
|
if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${t.slice(0, 800)}`);
|
|
return t ? JSON.parse(t) : {};
|
|
}
|
|
}
|
|
|
|
/** Every item of a paged GET. */
|
|
async function all(path: string): Promise<J[]> {
|
|
const out: J[] = [];
|
|
let url: string | null = path;
|
|
while (url) { const page: J = await asc('GET', url); out.push(...(page.data ?? [])); url = page.links?.next ?? null; }
|
|
return out;
|
|
}
|
|
|
|
/** null on 404 (relationship not created yet). */
|
|
async function maybe(path: string): Promise<J | null> {
|
|
try { return await asc('GET', path); } catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
|
|
}
|
|
|
|
let appId = appIdHint ?? '';
|
|
async function app(): Promise<string> {
|
|
if (appId) return appId;
|
|
const found = await asc('GET', `/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}`);
|
|
const hit = (found.data as J[]).find(a => a.attributes.bundleId === bundleId);
|
|
if (!hit) throw new Error(`no App Store Connect app with bundle id ${bundleId}: create the app record in the web UI first (Apps > + > New App); see the appstore-first-release skill`);
|
|
appId = hit.id;
|
|
return appId;
|
|
}
|
|
|
|
async function editableVersion(): Promise<J | null> {
|
|
const vs = await all(`/v1/apps/${await app()}/appStoreVersions?filter[platform]=IOS&limit=50`);
|
|
return vs.find(v => EDITABLE.has(v.attributes.appVersionState ?? v.attributes.appStoreState)) ?? null;
|
|
}
|
|
|
|
async function editableAppInfo(): Promise<J> {
|
|
const infos = await all(`/v1/apps/${await app()}/appInfos`);
|
|
return infos.find(i => !['READY_FOR_DISTRIBUTION', 'REPLACED_WITH_NEW_INFO'].includes(i.attributes.state ?? i.attributes.appStoreState)) ?? infos[0];
|
|
}
|
|
|
|
/** Reserve -> PUT the parts -> commit with the MD5 (screenshots, IAP review screenshots, app previews). `attrs` go into
|
|
* the reservation (app previews: mimeType, previewFrameTimeCode). */
|
|
async function uploadAsset(type: string, rel: Record<string, unknown>, file: string, attrs: Record<string, unknown> = {}): Promise<string> {
|
|
const buf = readFileSync(file);
|
|
const name = file.split('/').pop()!;
|
|
const res = (await asc('POST', `/v1/${type}`, { data: { type, attributes: { fileName: name, fileSize: buf.length, ...attrs }, relationships: rel } })).data;
|
|
for (const op of res.attributes.uploadOperations as J[]) {
|
|
const headers: Record<string, string> = {};
|
|
for (const h of op.requestHeaders) headers[h.name] = h.value;
|
|
const r = await fetch(op.url, { method: op.method, headers, body: buf.subarray(op.offset, op.offset + op.length) });
|
|
if (!r.ok) throw new Error(`upload ${name} part ${op.offset} -> ${r.status}`);
|
|
}
|
|
await asc('PATCH', `/v1/${type}/${res.id}`, { data: { type, id: res.id, attributes: { uploaded: true, sourceFileChecksum: md5(buf) } } });
|
|
return res.id;
|
|
}
|
|
|
|
return { asc, all, maybe, getAs, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
|
}
|