Merge store-ops: TestFlight wait / expire, IAP review submissions, pulls, offers, CPP, events, reports, triage, ASO rank, ads scan
Conflicts resolved for both sides: - cli/lib/plist.ts, cli/lib/zip.ts: one implementation each. plist reads XML (text or bytes, attributes tolerated) and binary plists; ads scan now reads bytes, so a binary Info.plist works too. zip gains unzip() for the Play report exports on top of zipEntries / zipRead. - apple upload waits with testflight wait's loop (waitForBuild) instead of its own copy; BUILD_DONE removed. - config, credentials (profiles, keystore, ASC_VENDOR_NUMBER, now also a profile key), command table, MCP tools, credentials template, README, CHANGELOG: union. - MCP: --write stays forbidden; the three pull tools are the listed local-file exception (LOCAL_WRITE_TOOLS), so scan --write remains unreachable. - Adapters and API coverage tables regenerated.
This commit is contained in:
commit
b724cd4043
60 changed files with 4500 additions and 183 deletions
107
tests/helpers/store-mock.ts
Normal file
107
tests/helpers/store-mock.ts
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// Recorded-response harness for command tests: throwaway API keys, a fetch router that answers like App Store Connect,
|
||||
// Google and the iTunes Search API did (sanitized: every id, name and email is a placeholder), a temp project with a
|
||||
// config, and capture of stdout / stderr / process.exit. Nothing here reaches the network.
|
||||
import { generateKeyPairSync } from 'node:crypto';
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, isAbsolute, join } from 'node:path';
|
||||
import { parseArgs } from '../../cli/lib/args';
|
||||
import type { Loaded, ShipConfig } from '../../cli/lib/config';
|
||||
import type { Ctx } from '../../cli/lib/ctx';
|
||||
|
||||
export type J = Record<string, unknown>;
|
||||
export interface Call { method: string; url: string; path: string; body: unknown }
|
||||
type Answer = Response | J | ((c: Call) => Response | J | Promise<Response | J>);
|
||||
export interface Route { method?: string; match: RegExp; answer: Answer; times?: number }
|
||||
|
||||
export const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json' } });
|
||||
export const notFound = () => json({ errors: [{ id: '00000000-0000-0000-0000-000000000000', status: '404', code: 'NOT_FOUND', title: 'The specified resource does not exist', detail: 'There is no resource' }] }, 404);
|
||||
|
||||
const saved = { ...process.env };
|
||||
const realFetch = globalThis.fetch;
|
||||
|
||||
export function ascEnv(): void {
|
||||
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||
process.env.ASC_KEY_ID = 'ABCDE12345';
|
||||
process.env.ASC_ISSUER_ID = '00000000-0000-0000-0000-000000000000';
|
||||
process.env.ASC_P8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
|
||||
}
|
||||
|
||||
export function playEnv(): void {
|
||||
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
process.env.PLAY_SERVICE_ACCOUNT = JSON.stringify({ client_email: 'sb@example.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' });
|
||||
}
|
||||
|
||||
/** Installs the router; unknown requests fail the test loudly (answer 599 with the path). Returns the call log. */
|
||||
export function mockFetch(routes: Route[]): Call[] {
|
||||
const calls: Call[] = [];
|
||||
const left = routes.map(r => ({ ...r, left: r.times ?? Infinity }));
|
||||
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const url = String(input instanceof Request ? input.url : input);
|
||||
const method = (init?.method ?? 'GET').toUpperCase();
|
||||
const raw = init?.body;
|
||||
let body: unknown = raw;
|
||||
if (typeof raw === 'string') { try { body = JSON.parse(raw); } catch { body = raw; } }
|
||||
const path = url.replace(/^https:\/\/[^/]+/, '');
|
||||
const c: Call = { method, url, path, body };
|
||||
if (url === 'https://oauth2.googleapis.com/token') return json({ access_token: 'ya29.test', expires_in: 3600 });
|
||||
calls.push(c);
|
||||
const r = left.find(x => x.left > 0 && (x.method ?? 'GET') === method && x.match.test(decodeURIComponent(path)));
|
||||
if (!r) return new Response(`not recorded: ${method} ${path}`, { status: 599 });
|
||||
r.left--;
|
||||
const a = typeof r.answer === 'function' ? await r.answer(c) : r.answer;
|
||||
return a instanceof Response ? a : json(a);
|
||||
}) as typeof fetch;
|
||||
return calls;
|
||||
}
|
||||
|
||||
export function restore(): void {
|
||||
globalThis.fetch = realFetch;
|
||||
for (const k of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT', 'ASC_VENDOR_NUMBER']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; }
|
||||
}
|
||||
|
||||
export const BASE: ShipConfig = {
|
||||
app: { name: 'Example Notes', profile: 'app', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' },
|
||||
languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }, { id: 'de', apple: 'de-DE', play: 'de-DE' }, { id: 'tr', apple: 'tr', play: 'tr-TR' }],
|
||||
apple: { bundleId: 'com.example.notes', appId: '6400000101' },
|
||||
play: { packageName: 'com.example.notes', reportsBucket: 'pubsite_prod_rev_01234567890123456789' },
|
||||
};
|
||||
|
||||
/** A temp project folder with optional files; returns a Ctx factory for that config. */
|
||||
export function project(config: ShipConfig = BASE, files: Record<string, string | Uint8Array> = {}): { root: string; ctx: (argv: string[], booleans?: string[]) => Ctx; loaded: Loaded } {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sb-ops-'));
|
||||
for (const [p, t] of Object.entries(files)) { mkdirSync(dirname(join(root, p)), { recursive: true }); writeFileSync(join(root, p), t); }
|
||||
const loaded: Loaded = { config, root, path: join(root, 'storebound.config.ts'), resolve: (p: string) => (isAbsolute(p) ? p : join(root, p)) };
|
||||
return { root, loaded, ctx: (argv, booleans = []) => ({ loaded, args: parseArgs(argv, booleans) }) };
|
||||
}
|
||||
|
||||
/** Runs fn with console output captured and process.exit turned into a thrown { exit } (the code is returned). */
|
||||
export async function capture(fn: () => Promise<void>): Promise<{ out: string; err: string; exit: number | null }> {
|
||||
const out: string[] = [], err: string[] = [];
|
||||
const log = console.log, warn = console.warn, error = console.error, exit = process.exit, write = process.stdout.write;
|
||||
console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
|
||||
console.warn = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
|
||||
console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
|
||||
process.stdout.write = ((s: string) => { out.push(String(s)); return true; }) as typeof process.stdout.write;
|
||||
let code: number | null = null;
|
||||
process.exit = ((c?: number) => { code = c ?? 0; throw new ExitSignal(code); }) as typeof process.exit;
|
||||
const before = process.exitCode;
|
||||
process.exitCode = 0;
|
||||
try { await fn(); } catch (e) { if (!(e instanceof ExitSignal)) { restoreIo(); throw e; } }
|
||||
restoreIo();
|
||||
if (code === null && process.exitCode) code = Number(process.exitCode);
|
||||
process.exitCode = before ?? 0;
|
||||
return { out: out.join('\n'), err: err.join('\n'), exit: code };
|
||||
function restoreIo(): void { console.log = log; console.warn = warn; console.error = error; process.exit = exit; process.stdout.write = write; }
|
||||
}
|
||||
|
||||
class ExitSignal extends Error { constructor(readonly code: number) { super(`exit ${code}`); } }
|
||||
|
||||
/** The --json object printed by a command (printJson pretty-prints one object; log lines may follow). */
|
||||
export function jsonOut(out: string): J {
|
||||
const i = out.indexOf('\n{\n') >= 0 ? out.indexOf('\n{\n') + 1 : out.indexOf('{\n');
|
||||
if (i < 0) throw new Error(`no JSON in output:\n${out.slice(0, 500)}`);
|
||||
// find the matching closing brace at column 0
|
||||
const end = out.indexOf('\n}', i);
|
||||
return JSON.parse(out.slice(i, end + 2)) as J;
|
||||
}
|
||||
363
tests/store-ops-apple.test.ts
Normal file
363
tests/store-ops-apple.test.ts
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
// TestFlight wait / expire, IAP review submissions, offers (offer codes, win-back, promoted, pre-orders), custom
|
||||
// product pages and in-app events: pure planners plus the commands against recorded App Store Connect answers
|
||||
// (shapes as documented in the App Store Connect API 4.5.1 OpenAPI spec; every id and name is a placeholder).
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { planExpire, expireCandidates, waitOutcome, waitDelay } from '../cli/lib/build-ops';
|
||||
import { bindIds, planIapSubmission, type SubmitState } from '../cli/lib/review-submit';
|
||||
import {
|
||||
endPreOrderReq, iapOfferCodeBody, planPreOrder, planPromoted, promotedOrderReq, territoryRows, validateIapOfferCodes, validatePromoted, validateWinBack, winBackBody,
|
||||
} from '../cli/lib/offers';
|
||||
import { checkEventMedia, cppCreateBody, eventCreateBody, planCppLocales, planEventLocales, validateCpp, validateEvents } from '../cli/lib/cpp-events';
|
||||
import { validateConfig } from '../cli/lib/config';
|
||||
import { run as testflight } from '../cli/apple/testflight';
|
||||
import { run as iapSubmit } from '../cli/apple/iap-submit';
|
||||
import { run as preorder } from '../cli/apple/preorder';
|
||||
import { run as promoted } from '../cli/apple/promoted';
|
||||
import { run as offerCodes } from '../cli/apple/offer-codes';
|
||||
import { run as winBack } from '../cli/apple/win-back';
|
||||
import { run as cpp } from '../cli/apple/cpp';
|
||||
import { run as events } from '../cli/apple/events';
|
||||
import { ascEnv, BASE, capture, jsonOut, mockFetch, project, restore } from './helpers/store-mock';
|
||||
|
||||
afterEach(restore);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const page = (data: unknown[], included: unknown[] = []): any => ({ data, included, links: { self: 'https://api.appstoreconnect.apple.com/v1/x' }, meta: { paging: { total: data.length, limit: 200 } } });
|
||||
|
||||
// builds of one app as GET /v1/builds?include=preReleaseVersion,appStoreVersion answers them
|
||||
const BUILDS = page([
|
||||
{ type: 'builds', id: 'b-50', attributes: { version: '50', uploadedDate: '2026-10-10T10:00:00-07:00', processingState: 'VALID', expired: false }, relationships: { preReleaseVersion: { data: { type: 'preReleaseVersions', id: 'p-12' } }, appStoreVersion: { data: null } } },
|
||||
{ type: 'builds', id: 'b-49', attributes: { version: '49', uploadedDate: '2026-09-30T10:00:00-07:00', processingState: 'VALID', expired: false }, relationships: { preReleaseVersion: { data: { type: 'preReleaseVersions', id: 'p-12' } }, appStoreVersion: { data: { type: 'appStoreVersions', id: 'v-12' } } } },
|
||||
{ type: 'builds', id: 'b-48', attributes: { version: '48', uploadedDate: '2026-08-01T10:00:00-07:00', processingState: 'VALID', expired: false }, relationships: { preReleaseVersion: { data: { type: 'preReleaseVersions', id: 'p-11' } }, appStoreVersion: { data: null } } },
|
||||
{ type: 'builds', id: 'b-47', attributes: { version: '47', uploadedDate: '2026-07-01T10:00:00-07:00', processingState: 'VALID', expired: false }, relationships: { preReleaseVersion: { data: { type: 'preReleaseVersions', id: 'p-11' } }, appStoreVersion: { data: null } } },
|
||||
{ type: 'builds', id: 'b-46', attributes: { version: '46', uploadedDate: '2026-06-01T10:00:00-07:00', processingState: 'PROCESSING', expired: false }, relationships: { preReleaseVersion: { data: { type: 'preReleaseVersions', id: 'p-11' } }, appStoreVersion: { data: null } } },
|
||||
], [{ type: 'preReleaseVersions', id: 'p-12', attributes: { version: '1.2.0', platform: 'IOS' } }, { type: 'preReleaseVersions', id: 'p-11', attributes: { version: '1.1.0', platform: 'IOS' } }]);
|
||||
|
||||
describe('testflight wait', () => {
|
||||
test('outcomes and poll delays', () => {
|
||||
expect(waitOutcome({ found: false })).toBe('missing');
|
||||
expect(waitOutcome({ found: true, processingState: 'PROCESSING' })).toBe('processing');
|
||||
expect(waitOutcome({ found: true, processingState: 'VALID' })).toBe('valid');
|
||||
expect(waitOutcome({ found: true, processingState: 'INVALID' })).toBe('failed');
|
||||
expect([waitDelay(null), waitDelay(20_000), waitDelay(100_000)]).toEqual([20_000, 30_000, 120_000]);
|
||||
});
|
||||
test('VALID build: exit 0 with the beta state in --json; FAILED: exit 1; not listed + --dry: exit 7 after one look', async () => {
|
||||
ascEnv();
|
||||
const p = project();
|
||||
const one = (state: string) => page([{ type: 'builds', id: 'b-50', attributes: { version: '50', processingState: state }, relationships: { preReleaseVersion: { data: { type: 'preReleaseVersions', id: 'p-12' } }, buildBetaDetail: { data: { type: 'buildBetaDetails', id: 'd-50' } } } }],
|
||||
[{ type: 'preReleaseVersions', id: 'p-12', attributes: { version: '1.2.0' } }, { type: 'buildBetaDetails', id: 'd-50', attributes: { internalBuildState: 'MISSING_EXPORT_COMPLIANCE', externalBuildState: 'MISSING_EXPORT_COMPLIANCE' } }]);
|
||||
let calls = mockFetch([{ match: /^\/v1\/builds\?.*filter\[version\]=50/, answer: one('VALID') }]);
|
||||
let r = await capture(() => testflight(p.ctx(['wait', '--build', '50', '--json'])));
|
||||
expect(r.exit).toBe(0);
|
||||
expect(jsonOut(r.out)).toMatchObject({ build: '50', version: '1.2.0', outcome: 'valid', internal: 'MISSING_EXPORT_COMPLIANCE' });
|
||||
expect(r.out).toContain('storebound apple encryption --build 50');
|
||||
expect(calls[0]!.path).toContain('include=preReleaseVersion%2CbuildBetaDetail');
|
||||
mockFetch([{ match: /^\/v1\/builds\?/, answer: one('FAILED') }]);
|
||||
r = await capture(() => testflight(p.ctx(['wait', '--build', '50'])));
|
||||
expect(r.exit).toBe(1);
|
||||
calls = mockFetch([{ match: /^\/v1\/builds\?/, answer: page([]) }]);
|
||||
r = await capture(() => testflight(p.ctx(['wait', '--build', '51', '--dry'])));
|
||||
expect(r.exit).toBe(7);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(r.out).toContain('not listed yet');
|
||||
});
|
||||
});
|
||||
|
||||
describe('testflight expire', () => {
|
||||
test('plan: newest kept, attached and processing builds protected, --keep / --older-than combine', () => {
|
||||
const c = expireCandidates([BUILDS]);
|
||||
expect(c.map(b => [b.build, b.version, b.attached])).toEqual([['50', '1.2.0', false], ['49', '1.2.0', true], ['48', '1.1.0', false], ['47', '1.1.0', false], ['46', '1.1.0', false]]);
|
||||
const now = Date.parse('2026-10-11T00:00:00Z');
|
||||
const k = planExpire(c, { keep: 2, now });
|
||||
expect(k.expire.map(b => b.build)).toEqual(['48', '47']);
|
||||
expect(k.protected.map(p => [p.b.build, p.why])).toEqual([['49', 'attached to an App Store version'], ['46', 'still PROCESSING']]);
|
||||
expect(k.reqs[0]).toEqual({ method: 'PATCH', path: '/v1/builds/b-48', note: 'expire build 48 (1.1.0), uploaded 2026-08-01', body: { data: { type: 'builds', id: 'b-48', attributes: { expired: true } } } });
|
||||
expect(planExpire(c, { olderThanDays: 80, now }).expire.map(b => b.build)).toEqual(['47']);
|
||||
expect(planExpire(c, { keep: 3, olderThanDays: 30, now }).expire.map(b => b.build)).toEqual(['47']);
|
||||
expect(() => planExpire(c, {})).toThrow('--keep');
|
||||
expect(() => planExpire(c, { keep: 0 })).toThrow('>= 1');
|
||||
});
|
||||
test('dry run sends nothing; without --yes in a non-terminal nothing is expired; --yes sends the PATCHes', async () => {
|
||||
ascEnv();
|
||||
const p = project();
|
||||
let calls = mockFetch([{ match: /^\/v1\/builds\?.*filter\[expired\]=false/, answer: BUILDS }, { method: 'PATCH', match: /^\/v1\/builds\/b-4[78]$/, answer: { data: {} } }]);
|
||||
let r = await capture(() => testflight(p.ctx(['expire', '--keep', '2', '--dry', '--json'])));
|
||||
expect(jsonOut(r.out)).toMatchObject({ dryRun: true, expire: [{ build: '48' }, { build: '47' }], keep: 1 });
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
r = await capture(() => testflight(p.ctx(['expire', '--keep', '2'])));
|
||||
expect(r.out).toContain('re-run with --yes');
|
||||
calls = mockFetch([{ match: /^\/v1\/builds\?/, answer: BUILDS }, { method: 'PATCH', match: /^\/v1\/builds\/b-4[78]$/, answer: { data: {} } }]);
|
||||
r = await capture(() => testflight(p.ctx(['expire', '--keep', '2', '--yes'])));
|
||||
expect(calls.filter(c => c.method === 'PATCH').map(c => [c.path, c.body])).toEqual([
|
||||
['/v1/builds/b-48', { data: { type: 'builds', id: 'b-48', attributes: { expired: true } } }], ['/v1/builds/b-47', { data: { type: 'builds', id: 'b-47', attributes: { expired: true } } }]]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- IAP review submissions ----
|
||||
|
||||
const STATE: SubmitState = {
|
||||
appVersions: [{ id: 'v-2', versionString: '1.2.0', state: 'PREPARE_FOR_SUBMISSION' }, { id: 'v-1', versionString: '1.1.0', state: 'READY_FOR_DISTRIBUTION' }],
|
||||
iaps: [
|
||||
{ id: 'i-coins', productId: 'com.example.notes.coins_100', type: 'CONSUMABLE', state: 'APPROVED', versions: [{ id: 'iv-1', version: 1, state: 'APPROVED' }] },
|
||||
{ id: 'i-coins2', productId: 'com.example.notes.coins_500', type: 'CONSUMABLE', state: 'READY_TO_SUBMIT', versions: [{ id: 'iv-2', version: 1, state: 'PREPARE_FOR_SUBMISSION' }] },
|
||||
{ id: 'i-pro', productId: 'com.example.notes.pro', type: 'NON_CONSUMABLE', state: 'READY_TO_SUBMIT', versions: [{ id: 'iv-3', version: 1, state: 'PREPARE_FOR_SUBMISSION' }] },
|
||||
{ id: 'i-meta', productId: 'com.example.notes.theme', type: 'NON_CONSUMABLE', state: 'MISSING_METADATA', versions: [] },
|
||||
],
|
||||
subs: [{ id: 's-m', productId: 'com.example.notes.plus_monthly', groupId: 'g-1', state: 'READY_TO_SUBMIT', versions: [{ id: 'sv-1', version: 1, state: 'PREPARE_FOR_SUBMISSION' }] }],
|
||||
groups: [{ id: 'g-1', name: 'Plus', versions: [{ id: 'gv-1', version: 1, state: 'PREPARE_FOR_SUBMISSION' }] }],
|
||||
draft: null,
|
||||
};
|
||||
|
||||
describe('IAP review submission plan', () => {
|
||||
test('a later consumable goes alone; first non-consumable / first subscription need the app version', () => {
|
||||
const later = planIapSubmission(STATE, ['com.example.notes.coins_500']);
|
||||
expect(later.blockers).toEqual([]);
|
||||
expect(later.needsAppVersion).toBe(false);
|
||||
expect(later.items).toEqual([{ kind: 'inAppPurchaseVersion', versionId: 'iv-2', label: 'com.example.notes.coins_500 (consumable, version 1)' }]);
|
||||
expect(later.prepare.map(r => `${r.method} ${r.path}`)).toEqual(['POST /v1/reviewSubmissions', 'POST /v1/reviewSubmissionItems']);
|
||||
expect(bindIds(later.prepare[1]!, { submission: 'rs-9' }).body).toEqual({ data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: { data: { type: 'reviewSubmissions', id: 'rs-9' } }, inAppPurchaseVersion: { data: { type: 'inAppPurchaseVersions', id: 'iv-2' } } } } });
|
||||
expect(bindIds(later.submit, { submission: 'rs-9' }).body).toEqual({ data: { type: 'reviewSubmissions', id: 'rs-9', attributes: { submitted: true } } });
|
||||
|
||||
const first = planIapSubmission(STATE, ['com.example.notes.pro', 'com.example.notes.plus_monthly', 'com.example.notes.theme', 'com.example.notes.coins_100', 'com.example.nope']);
|
||||
expect(first.firstOfType.sort()).toEqual(['auto-renewable subscription', 'non-consumable']);
|
||||
expect(first.blockers[0]).toContain('--with-version');
|
||||
expect(first.blockers[0]).toContain('1.2.0');
|
||||
expect(first.items.map(i => i.kind)).toEqual(['inAppPurchaseVersion', 'subscriptionVersion', 'subscriptionGroupVersion']);
|
||||
expect(Object.fromEntries(first.skipped.map(s => [s.id, s.why.split(' (')[0]!.split(':')[0]]))).toEqual({
|
||||
'com.example.notes.theme': 'missing metadata', 'com.example.notes.coins_100': 'latest version is APPROVED', 'com.example.nope': 'not on App Store Connect' });
|
||||
|
||||
const withV = planIapSubmission(STATE, ['com.example.notes.pro'], { withVersion: true });
|
||||
expect(withV.blockers).toEqual([]);
|
||||
expect(withV.items.map(i => i.kind)).toEqual(['appStoreVersion', 'inAppPurchaseVersion']);
|
||||
expect(withV.appVersion?.versionString).toBe('1.2.0');
|
||||
});
|
||||
test('no approved app version yet: even a later type needs the version; a draft is reused and items in it are skipped', () => {
|
||||
const fresh = planIapSubmission({ ...STATE, appVersions: [{ id: 'v-1', versionString: '1.0.0', state: 'PREPARE_FOR_SUBMISSION' }] }, ['com.example.notes.coins_500']);
|
||||
expect(fresh.needsAppVersion).toBe(true);
|
||||
expect(fresh.blockers[0]).toContain('no approved version');
|
||||
const draft = planIapSubmission({ ...STATE, draft: { id: 'rs-1', itemVersionIds: ['iv-2'] } }, ['com.example.notes.coins_500', 'com.example.notes.pro'], { withVersion: true });
|
||||
expect(draft.prepare.map(r => r.path)).not.toContain('/v1/reviewSubmissions');
|
||||
expect(draft.skipped.find(s => s.id === 'com.example.notes.coins_500')?.why).toBe('already in the draft submission');
|
||||
expect(draft.submit.path).toBe('/v1/reviewSubmissions/rs-1');
|
||||
expect(planIapSubmission({ ...STATE, draft: { id: 'rs-1', itemVersionIds: Array.from({ length: 200 }, (_, i) => `x${i}`) } }, ['com.example.notes.coins_500']).blockers[0]).toContain('200');
|
||||
});
|
||||
test('command: --dry --json plans; a real run asks, creates the draft, adds the items, submits', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, products: [{ id: 'com.example.notes.coins_500', type: 'consumable', usd: 4.99, listings: { en: { title: '500 coins', description: 'A bag of coins' } } }] });
|
||||
const routes = () => mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/appStoreVersions\?/, answer: page([{ type: 'appStoreVersions', id: 'v-1', attributes: { versionString: '1.1.0', appVersionState: 'READY_FOR_DISTRIBUTION', platform: 'IOS' } }]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?/, answer: page([
|
||||
{ type: 'inAppPurchases', id: 'i-coins', attributes: { productId: 'com.example.notes.coins_100', inAppPurchaseType: 'CONSUMABLE', state: 'APPROVED' } },
|
||||
{ type: 'inAppPurchases', id: 'i-coins2', attributes: { productId: 'com.example.notes.coins_500', inAppPurchaseType: 'CONSUMABLE', state: 'READY_TO_SUBMIT' } }]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-coins2\/versions/, answer: page([{ type: 'inAppPurchaseVersions', id: 'iv-2', attributes: { version: 1, state: 'PREPARE_FOR_SUBMISSION' } }]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/subscriptionGroups/, answer: page([]) },
|
||||
{ match: /^\/v1\/reviewSubmissions\?filter\[app\]=6400000101&filter\[platform\]=IOS&filter\[state\]=READY_FOR_REVIEW/, answer: page([]) },
|
||||
{ method: 'POST', match: /^\/v1\/reviewSubmissions$/, answer: { data: { type: 'reviewSubmissions', id: 'rs-new', attributes: { state: 'READY_FOR_REVIEW' } } } },
|
||||
{ method: 'POST', match: /^\/v1\/reviewSubmissionItems$/, answer: { data: { type: 'reviewSubmissionItems', id: 'it-1' } } },
|
||||
{ method: 'PATCH', match: /^\/v1\/reviewSubmissions\/rs-new$/, answer: { data: { type: 'reviewSubmissions', id: 'rs-new', attributes: { state: 'WAITING_FOR_REVIEW' } } } },
|
||||
]);
|
||||
let calls = routes();
|
||||
let r = await capture(() => iapSubmit(p.ctx(['--dry', '--json'])));
|
||||
const plan = jsonOut(r.out);
|
||||
expect(plan).toMatchObject({ dryRun: true, blockers: [], needsAppVersion: false, hasApprovedVersion: true });
|
||||
expect((plan.requests as string[]).at(-1)).toContain('PATCH /v1/reviewSubmissions/${submission} {submitted=true}');
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
calls = routes();
|
||||
r = await capture(() => iapSubmit(p.ctx(['--yes'])));
|
||||
expect(calls.filter(c => c.method !== 'GET').map(c => `${c.method} ${c.path}`)).toEqual(['POST /v1/reviewSubmissions', 'POST /v1/reviewSubmissionItems', 'PATCH /v1/reviewSubmissions/rs-new']);
|
||||
expect(calls.find(c => c.path === '/v1/reviewSubmissionItems')!.body).toEqual({ data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: { data: { type: 'reviewSubmissions', id: 'rs-new' } }, inAppPurchaseVersion: { data: { type: 'inAppPurchaseVersions', id: 'iv-2' } } } } });
|
||||
calls = routes();
|
||||
r = await capture(() => iapSubmit(p.ctx(['--yes', '--no-submit'])));
|
||||
expect(calls.filter(c => c.method === 'PATCH')).toHaveLength(0);
|
||||
expect(r.out).toContain('Submit for Review');
|
||||
});
|
||||
});
|
||||
|
||||
// ---- offers ----
|
||||
|
||||
describe('offer codes, win-back, promoted, pre-orders: config and bodies', () => {
|
||||
test('config checks (date rules only right before creating)', () => {
|
||||
expect(validateIapOfferCodes('p', [{ name: 'Spring', eligibility: ['NON_SPENDER'], usd: 0.99, oneTimeCodes: [{ count: 500, expires: '2027-01-01' }] }], 'non_consumable')).toEqual([]);
|
||||
const e = validateIapOfferCodes('p', [{ name: 'X', eligibility: ['NEW' as never], customCodes: [{ code: 'NO WAY', count: 30000 }], oneTimeCodes: [{ count: 10, expires: '2030-01-01' }] }], 'non_consumable', '2026-10-11').join('\n');
|
||||
for (const m of ['eligibility', 'free: true or usd', 'letters and digits', '1-25000', '500-25000', 'within 6 months']) expect(e).toContain(m);
|
||||
const wb = { id: 'come-back', type: 'pay-up-front' as const, duration: 'P3M', usd: 9.99, paidMonths: 6, lapsedMonths: { min: 2, max: 24 }, start: '2026-11-01', end: '2026-11-30' };
|
||||
expect(validateWinBack('s', [wb])).toEqual([]);
|
||||
expect(validateWinBack('s', [{ ...wb, start: '2026-10-11' }], '2026-10-11').join()).toContain('at the earliest tomorrow');
|
||||
expect(validateWinBack('s', [{ ...wb, paidMonths: 30, lapsedMonths: { min: 0, max: 30 }, waitMonths: 1, end: '2026-11-02' }]).join('\n')).toMatch(/paidMonths[\s\S]*lapsedMonths[\s\S]*waitMonths[\s\S]*at least 3 days/);
|
||||
expect(validatePromoted({ products: Array.from({ length: 21 }, (_, i) => `p${i}`) }, new Set(['p0'])).join()).toContain('at most 20');
|
||||
// a config with them validates, an old campaign never breaks the config
|
||||
const cfg = { ...BASE, products: [{ id: 'com.example.notes.pro', type: 'non_consumable' as const, usd: 4.99, listings: { en: { title: 'Pro', description: 'All features' } }, offerCodes: [{ name: 'Old', eligibility: ['CHURNED_SPENDER' as const], free: true, oneTimeCodes: [{ count: 500, expires: '2020-01-01' }] }] }],
|
||||
apple: { ...BASE.apple!, promoted: { products: ['com.example.notes.pro'] } } };
|
||||
expect(validateConfig(cfg)).toEqual([]);
|
||||
});
|
||||
test('IAP offer code body: paid per territory, free without a price point', () => {
|
||||
const b = iapOfferCodeBody('i-pro', { name: 'Spring', eligibility: ['NON_SPENDER', 'CHURNED_SPENDER'], usd: 1.99 }, [{ territory: 'USA', pointId: 'pp-usa' }, { territory: 'DEU', pointId: 'pp-deu' }]);
|
||||
expect(b.data).toEqual({ type: 'inAppPurchaseOfferCodes', attributes: { name: 'Spring', customerEligibilities: ['NON_SPENDER', 'CHURNED_SPENDER'] },
|
||||
relationships: { inAppPurchase: { data: { type: 'inAppPurchases', id: 'i-pro' } }, prices: { data: [{ type: 'inAppPurchaseOfferPrices', id: '${iapcode-0}' }, { type: 'inAppPurchaseOfferPrices', id: '${iapcode-1}' }] } } });
|
||||
expect(b.included[1]).toEqual({ type: 'inAppPurchaseOfferPrices', id: '${iapcode-1}', relationships: { territory: { data: { type: 'territories', id: 'DEU' } }, pricePoint: { data: { type: 'inAppPurchasePricePoints', id: 'pp-deu' } } } });
|
||||
expect(iapOfferCodeBody('i', { name: 'Free', eligibility: ['NON_SPENDER'], free: true }, [{ territory: 'USA' }]).included[0]!.relationships).toEqual({ territory: { data: { type: 'territories', id: 'USA' } } });
|
||||
expect(() => iapOfferCodeBody('i', { name: 'P', eligibility: ['NON_SPENDER'], usd: 1 }, [{ territory: 'USA' }])).toThrow('needs a price point');
|
||||
});
|
||||
test('win-back body like Apple\'s example request', () => {
|
||||
const b = winBackBody('s-1', 'P1M', { id: '6Monthfor3_a', name: '6 Months for 3 A', type: 'pay-up-front', duration: 'P6M', usd: 3, paidMonths: 6, lapsedMonths: { min: 2, max: 24 }, waitMonths: 2,
|
||||
start: '2026-11-01', end: '2026-11-30', priority: 'high', promote: true }, [{ territory: 'USA', pointId: 'sp-usa' }]);
|
||||
expect(b.data.attributes).toEqual({ referenceName: '6 Months for 3 A', offerId: '6Monthfor3_a', duration: 'SIX_MONTHS', offerMode: 'PAY_UP_FRONT', periodCount: 1,
|
||||
customerEligibilityPaidSubscriptionDurationInMonths: 6, customerEligibilityTimeSinceLastSubscribedInMonths: { minimum: 2, maximum: 24 }, customerEligibilityWaitBetweenOffersInMonths: 2,
|
||||
startDate: '2026-11-01', endDate: '2026-11-30', priority: 'HIGH', promotionIntent: 'USE_AUTO_GENERATED_ASSETS' });
|
||||
expect(b.included[0]).toEqual({ type: 'winBackOfferPrices', id: '${winback-0}', relationships: { subscriptionPricePoint: { data: { type: 'subscriptionPricePoints', id: 'sp-usa' } } } });
|
||||
expect(winBackBody('s', 'P1M', { id: 'x', type: 'pay-as-you-go', usd: 1, periods: 3, paidMonths: 1, lapsedMonths: { min: 1, max: 3 }, start: '2026-11-01' }, [{ territory: 'USA', pointId: 'p' }]).data.attributes).toMatchObject({ duration: 'ONE_MONTH', offerMode: 'PAY_AS_YOU_GO', periodCount: 3, priority: 'NORMAL', promotionIntent: 'NOT_PROMOTED' });
|
||||
});
|
||||
test('promoted: create disabled, enable only with --enable, order configured first', () => {
|
||||
const prods = new Map([['a', { apiId: 'i-a', kind: 'iap' as const }], ['b', { apiId: 's-b', kind: 'sub' as const }]]);
|
||||
const now = [{ id: 'pp-x', productId: 'x', enabled: true, visibleForAllUsers: true }, { id: 'pp-b', productId: 'b', enabled: false, visibleForAllUsers: false }];
|
||||
const p = planPromoted('app', { products: ['a', 'b', 'zzz'] }, now, prods);
|
||||
expect(p.create[0]!.body).toEqual({ data: { type: 'promotedPurchases', attributes: { visibleForAllUsers: true, enabled: false }, relationships: { app: { data: { type: 'apps', id: 'app' } }, inAppPurchaseV2: { data: { type: 'inAppPurchases', id: 'i-a' } } } } });
|
||||
expect(p.update.map(r => r.note)).toEqual(['b: visibleForAllUsers=true']);
|
||||
expect(p.unknown).toEqual(['zzz']);
|
||||
expect(p.extra).toEqual(['x']);
|
||||
expect(planPromoted('app', { products: ['b'] }, now, prods, { enable: true }).update[0]!.body).toEqual({ data: { type: 'promotedPurchases', id: 'pp-b', attributes: { visibleForAllUsers: true, enabled: true } } });
|
||||
expect(promotedOrderReq('app', { products: ['b'] }, now)).toEqual({ method: 'PATCH', path: '/v1/apps/app/relationships/promotedPurchases', note: 'promoted purchase order', body: { data: [{ type: 'promotedPurchases', id: 'pp-b' }, { type: 'promotedPurchases', id: 'pp-x' }] } });
|
||||
expect(promotedOrderReq('app', { products: ['x'] }, now)).toBeNull();
|
||||
});
|
||||
test('pre-order: 2-365 days, released territories skipped, end releases now', () => {
|
||||
const rows = territoryRows([page([
|
||||
{ type: 'territoryAvailabilities', id: 'ta-usa', attributes: { available: true, releaseDate: null, preOrderEnabled: false, contentStatuses: ['AVAILABLE_FOR_SALE_UNRELEASED_APP'] }, relationships: { territory: { data: { type: 'territories', id: 'USA' } } } },
|
||||
{ type: 'territoryAvailabilities', id: 'ta-deu', attributes: { available: true, releaseDate: '2026-12-01', preOrderEnabled: true, contentStatuses: ['AVAILABLE_FOR_PREORDER_ON_DATE'] }, relationships: { territory: { data: { type: 'territories', id: 'DEU' } } } },
|
||||
{ type: 'territoryAvailabilities', id: 'ta-tur', attributes: { available: true, contentStatuses: ['AVAILABLE'] }, relationships: { territory: { data: { type: 'territories', id: 'TUR' } } } },
|
||||
])]);
|
||||
const p = planPreOrder(rows, '2026-12-01', null, '2026-10-11');
|
||||
expect(p.problems).toEqual([]);
|
||||
expect(p.reqs.map(r => r.path)).toEqual(['/v1/territoryAvailabilities/ta-usa']);
|
||||
expect(p.reqs[0]!.body).toEqual({ data: { type: 'territoryAvailabilities', id: 'ta-usa', attributes: { available: true, preOrderEnabled: true, releaseDate: '2026-12-01' } } });
|
||||
expect(p.warnings).toEqual(['TUR: already released there, no pre-order possible']);
|
||||
expect(planPreOrder(rows, '2026-10-12', null, '2026-10-11').problems[0]).toContain('at least 2 days');
|
||||
expect(planPreOrder(rows, '2027-06-01', null, '2026-10-11').warnings[0]).toContain('180 days');
|
||||
expect(planPreOrder(rows, '2026-12-01', ['FRA'], '2026-10-11').problems[0]).toContain('FRA');
|
||||
expect(endPreOrderReq(rows, null)!.body).toEqual({ data: { type: 'endAppAvailabilityPreOrders', relationships: { territoryAvailabilities: { data: [{ type: 'territoryAvailabilities', id: 'ta-deu' }] } } } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('offer commands against recorded answers', () => {
|
||||
test('preorder status --json and enable --dry', async () => {
|
||||
ascEnv();
|
||||
const p = project();
|
||||
mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/appAvailabilityV2$/, answer: { data: { type: 'appAvailabilities', id: 'av-1', attributes: { availableInNewTerritories: true } } } },
|
||||
{ match: /^\/v2\/appAvailabilities\/av-1\/territoryAvailabilities\?include=territory/, answer: page([
|
||||
{ type: 'territoryAvailabilities', id: 'ta-usa', attributes: { available: true, releaseDate: null, preOrderEnabled: false, preOrderPublishDate: null, contentStatuses: ['AVAILABLE_FOR_SALE_UNRELEASED_APP'] }, relationships: { territory: { data: { type: 'territories', id: 'USA' } } } }]) },
|
||||
]);
|
||||
let r = await capture(() => preorder(p.ctx(['status', '--json'])));
|
||||
expect(jsonOut(r.out)).toMatchObject({ availableInNewTerritories: true, territories: [{ territory: 'USA', preOrderEnabled: false }] });
|
||||
const future = new Date(Date.now() + 30 * 86_400_000).toISOString().slice(0, 10);
|
||||
r = await capture(() => preorder(p.ctx(['enable', '--release-date', future, '--dry', '--json'])));
|
||||
expect((jsonOut(r.out).requests as string[])[0]).toContain('PATCH /v1/territoryAvailabilities/ta-usa {available=true, preOrderEnabled=true');
|
||||
});
|
||||
test('promoted: status without config; plan with config is a dry run', async () => {
|
||||
ascEnv();
|
||||
const routes = [
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2/, answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: 'com.example.notes.pro', inAppPurchaseType: 'NON_CONSUMABLE', state: 'APPROVED' } }]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/subscriptionGroups/, answer: page([]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/promotedPurchases\?include=/, answer: page([]) },
|
||||
];
|
||||
mockFetch(routes);
|
||||
let r = await capture(() => promoted(project().ctx(['--json'])));
|
||||
expect(jsonOut(r.out)).toEqual({ promoted: [] });
|
||||
const calls = mockFetch(routes);
|
||||
r = await capture(() => promoted(project({ ...BASE, apple: { ...BASE.apple!, promoted: { products: ['com.example.notes.pro'] } } }).ctx(['--dry', '--json'])));
|
||||
expect((jsonOut(r.out).requests as string[])[0]).toContain('POST /v1/promotedPurchases {visibleForAllUsers=true, enabled=false}');
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
test('offer-codes --dry: campaign with equalized prices; codes need --codes', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, products: [{ id: 'com.example.notes.pro', type: 'non_consumable', usd: 4.99, listings: { en: { title: 'Pro', description: 'All features' } },
|
||||
offerCodes: [{ name: 'Spring', eligibility: ['NON_SPENDER'], usd: 0.99, customCodes: [{ code: 'SPRING26', count: 100 }] }] }] });
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?filter\[productId\]=com.example.notes.pro/, answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: 'com.example.notes.pro', state: 'APPROVED' } }]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/offerCodes/, answer: page([]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/pricePoints\?filter\[territory\]=USA/, answer: page([
|
||||
{ type: 'inAppPurchasePricePoints', id: 'pp-usa-099', attributes: { customerPrice: '0.99', proceeds: '0.84' }, relationships: { territory: { data: { type: 'territories', id: 'USA' } } } },
|
||||
{ type: 'inAppPurchasePricePoints', id: 'pp-usa-499', attributes: { customerPrice: '4.99', proceeds: '4.24' }, relationships: { territory: { data: { type: 'territories', id: 'USA' } } } }]) },
|
||||
{ match: /^\/v1\/inAppPurchasePricePoints\/pp-usa-099\/equalizations/, answer: page([
|
||||
{ type: 'inAppPurchasePricePoints', id: 'pp-deu-099', attributes: { customerPrice: '0.99' }, relationships: { territory: { data: { type: 'territories', id: 'DEU' } } } }]) },
|
||||
]);
|
||||
const r = await capture(() => offerCodes(p.ctx(['--dry', '--json'])));
|
||||
expect(r.out).toContain('would POST /v1/inAppPurchaseOfferCodes {name="Spring"');
|
||||
expect(r.out).toContain('2 territories');
|
||||
expect(jsonOut(r.out).codes).toEqual(['POST /v1/inAppPurchaseOfferCodeCustomCodes {customCode="SPRING26", numberOfCodes=100} # custom code SPRING26 (100 redemptions)']);
|
||||
expect(r.out).toContain('run with --codes');
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
test('win-back --dry: an approved subscription gets the plan, others are skipped with the reason', async () => {
|
||||
ascEnv();
|
||||
const start = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);
|
||||
const sub = (id: string) => ({ id, period: 'P1M' as const, level: 1, usd: 4.99, listings: { en: { title: 'Plus', description: 'Everything' } },
|
||||
winBack: [{ id: `wb-${id.slice(-1)}`, type: 'free' as const, duration: 'P1M', paidMonths: 3, lapsedMonths: { min: 1, max: 12 }, start }] });
|
||||
const p = project({ ...BASE, subscriptions: [{ name: 'Plus', listings: { en: { name: 'Plus' } }, subscriptions: [sub('com.example.notes.plus_a'), sub('com.example.notes.plus_b')] }] });
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/subscriptionGroups/, answer: page([{ type: 'subscriptionGroups', id: 'g-1', attributes: { referenceName: 'Plus' } }]) },
|
||||
{ match: /^\/v1\/subscriptionGroups\/g-1\/subscriptions/, answer: page([{ type: 'subscriptions', id: 's-a', attributes: { productId: 'com.example.notes.plus_a', state: 'APPROVED' } }, { type: 'subscriptions', id: 's-b', attributes: { productId: 'com.example.notes.plus_b', state: 'READY_TO_SUBMIT' } }]) },
|
||||
{ match: /^\/v1\/subscriptions\/s-[ab]\/winBackOffers/, answer: page([]) },
|
||||
{ match: /^\/v1\/subscriptions\/s-a\/prices\?include=territory/, answer: page([{ type: 'subscriptionPrices', id: 'sp1', relationships: { territory: { data: { type: 'territories', id: 'USA' } } } }]) },
|
||||
]);
|
||||
const r = await capture(() => winBack(p.ctx(['--dry', '--json'])));
|
||||
const j = jsonOut(r.out);
|
||||
expect((j.create as string[])[0]).toContain('POST /v1/winBackOffers {referenceName="wb-a", offerId="wb-a", duration="ONE_MONTH", offerMode="FREE_TRIAL"');
|
||||
expect(j.skipped).toEqual([{ id: 'com.example.notes.plus_b', why: 'subscription is READY_TO_SUBMIT: win-back offers need an approved subscription' }]);
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- custom product pages and in-app events ----
|
||||
|
||||
describe('custom product pages and in-app events', () => {
|
||||
const EV = { referenceName: 'Winter Challenge', badge: 'CHALLENGE' as const, purpose: 'KEEP_ACTIVE_USERS_INFORMED' as const,
|
||||
schedule: { publishStart: '2026-12-01T00:00:00Z', eventStart: '2026-12-10T00:00:00Z', eventEnd: '2026-12-20T00:00:00Z' },
|
||||
listings: { en: { name: 'Winter Challenge', shortDescription: 'Finish ten lists before New Year', longDescription: 'Ten lists, one badge. Share your progress with friends.' } },
|
||||
media: { card: 'store/events/winter/{lang}-card.png' } };
|
||||
test('config checks', () => {
|
||||
expect(validateCpp([{ name: 'Students', variant: 'b', promotionalText: { en: 'For class notes.' }, deepLink: 'https://example.com/students' }], new Set(['en']), ['b'])).toEqual([]);
|
||||
expect(validateCpp([{ name: 'A', variant: 'z', deepLink: 'not a link', promotionalText: { xx: 'x'.repeat(171) } }], new Set(['en']), []).join('\n')).toMatch(/variant[\s\S]*deepLink[\s\S]*not in languages[\s\S]*171 > 170/);
|
||||
expect(validateEvents([EV], new Set(['en']))).toEqual([]);
|
||||
const bad = validateEvents([{ ...EV, schedule: { publishStart: '2026-11-01T00:00:00Z', eventStart: '2026-12-10T00:00:00Z', eventEnd: '2027-02-10T00:00:00Z' }, listings: { en: { name: 'x'.repeat(31), shortDescription: '', longDescription: 'ok' } } }], new Set(['en'])).join('\n');
|
||||
for (const m of ['at most 31 days', 'at most 14 days', 'name: 31 > 30', 'shortDescription: missing']) expect(bad).toContain(m);
|
||||
expect(checkEventMedia('EVENT_CARD', 1920, 1080, 'png')).toEqual([]);
|
||||
expect(checkEventMedia('EVENT_DETAILS_PAGE', 1920, 1080, 'png').join()).toContain('9:16');
|
||||
});
|
||||
test('request bodies', () => {
|
||||
const b = cppCreateBody('6400000101', { name: 'Students', deepLink: 'https://example.com/s' }, [{ locale: 'en-US', promotionalText: 'For class notes.' }, { locale: 'de-DE' }]);
|
||||
expect(b.data.relationships.appCustomProductPageVersions).toEqual({ data: [{ type: 'appCustomProductPageVersions', id: '${cpp-version}' }] });
|
||||
expect(b.included[0]).toEqual({ type: 'appCustomProductPageVersions', id: '${cpp-version}', attributes: { deepLink: 'https://example.com/s' }, relationships: { appCustomProductPageLocalizations: { data: [{ type: 'appCustomProductPageLocalizations', id: '${cpp-loc-0}' }, { type: 'appCustomProductPageLocalizations', id: '${cpp-loc-1}' }] } } });
|
||||
expect(b.included[2]).toEqual({ type: 'appCustomProductPageLocalizations', id: '${cpp-loc-1}', attributes: { locale: 'de-DE' } });
|
||||
expect(planCppLocales('cv', [{ id: 'l1', locale: 'en-US', promotionalText: 'old' }], [{ locale: 'en-US', promotionalText: 'new' }, { locale: 'tr' }]).map(r => `${r.method} ${r.path}`)).toEqual(['PATCH /v1/appCustomProductPageLocalizations/l1', 'POST /v1/appCustomProductPageLocalizations']);
|
||||
const e = eventCreateBody('6400000101', EV, 'en-US', ['USA', 'DEU']);
|
||||
expect(e.data.attributes).toEqual({ referenceName: 'Winter Challenge', badge: 'CHALLENGE', primaryLocale: 'en-US', priority: 'NORMAL', purpose: 'KEEP_ACTIVE_USERS_INFORMED',
|
||||
territorySchedules: [{ territories: ['USA', 'DEU'], publishStart: '2026-12-01T00:00:00Z', eventStart: '2026-12-10T00:00:00Z', eventEnd: '2026-12-20T00:00:00Z' }] });
|
||||
expect(planEventLocales('ev', [{ id: 'l', locale: 'en-US', name: 'Winter Challenge', shortDescription: 'old', longDescription: 'Ten lists, one badge. Share your progress with friends.' }], [{ locale: 'en-US', ...EV.listings.en }])[0]!.note).toBe('en-US shortDescription');
|
||||
});
|
||||
test('cpp create --dry --json and events create --dry against recorded answers', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, apple: { ...BASE.apple!, customProductPages: [{ name: 'Students', promotionalText: { en: 'For class notes.' } }], events: [EV] } });
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/appCustomProductPages/, answer: page([]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/appEvents/, answer: page([]) },
|
||||
{ match: /^\/v1\/territories/, answer: page([{ type: 'territories', id: 'USA' }, { type: 'territories', id: 'DEU' }]) },
|
||||
]);
|
||||
let r = await capture(() => cpp(p.ctx(['create', '--dry', '--json'])));
|
||||
expect(jsonOut(r.out).requests).toEqual(['POST /v1/appCustomProductPages {name="Students"} # page "Students" with 3 locale(s)']);
|
||||
r = await capture(() => events(p.ctx(['create', '--dry', '--json'])));
|
||||
expect((jsonOut(r.out).requests as string[])[0]).toContain('POST /v1/appEvents {referenceName="Winter Challenge", badge="CHALLENGE", primaryLocale="en-US"');
|
||||
expect(r.out).toContain('then: 1 localization(s)');
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
// submit of a created page: the dry run shows draft, item and submit, and sends nothing
|
||||
const sent = mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/appCustomProductPages/, answer: page([{ type: 'appCustomProductPages', id: 'cpp-1', attributes: { name: 'Students', visible: false, url: 'https://apps.apple.com/us/app/id6400000101?ppid=cpp-1' } }]) },
|
||||
{ match: /^\/v1\/appCustomProductPages\/cpp-1\/appCustomProductPageVersions/, answer: page([{ type: 'appCustomProductPageVersions', id: 'cv-1', attributes: { version: '1', state: 'PREPARE_FOR_SUBMISSION', deepLink: null } }]) },
|
||||
{ match: /^\/v1\/reviewSubmissions\?filter\[app\]=6400000101/, answer: page([]) },
|
||||
]);
|
||||
r = await capture(() => cpp(p.ctx(['submit', '--name', 'Students', '--dry'])));
|
||||
expect(r.out).toContain('would POST /v1/reviewSubmissionItems');
|
||||
expect(r.out).toContain('would PATCH /v1/reviewSubmissions/${submission}');
|
||||
r = await capture(() => cpp(p.ctx(['submit', '--name', 'Students'])));
|
||||
expect(r.out).toContain('re-run with --yes');
|
||||
expect(sent.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
202
tests/store-ops-reports.test.ts
Normal file
202
tests/store-ops-reports.test.ts
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
// Sales / finance reports and crash / feedback triage: parsers and summaries on sanitized report files, plus the
|
||||
// commands against recorded App Store Connect, Cloud Storage and Play Developer Reporting answers.
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { deflateRawSync } from 'node:zlib';
|
||||
import {
|
||||
appleFinancePath, appleReportDate, appleSalesPath, parsePlayCsv, parseTsv, playReportPrefix, summarizeAppleFinance, summarizeAppleSales, summarizePlayEarnings, summarizePlaySales, totalsByCurrency,
|
||||
} from '../cli/lib/reports';
|
||||
import { unzip } from '../cli/lib/zip';
|
||||
import { cluster, crashSignature, feedbackItems, playIssues, playReportItems, reportsQuery } from '../cli/lib/triage';
|
||||
import { run as reports } from '../cli/reports';
|
||||
import { run as triage } from '../cli/triage';
|
||||
import { ascEnv, BASE, capture, jsonOut, mockFetch, playEnv, project, restore } from './helpers/store-mock';
|
||||
|
||||
afterEach(restore);
|
||||
|
||||
/** A ZIP with deflated entries (what Play puts in the reports bucket). */
|
||||
function zip(files: Record<string, string>): Uint8Array {
|
||||
const parts: Uint8Array[] = [], central: Uint8Array[] = [];
|
||||
let off = 0;
|
||||
for (const [name, text] of Object.entries(files)) {
|
||||
const raw = new TextEncoder().encode(text), data = deflateRawSync(raw), n = new TextEncoder().encode(name);
|
||||
const h = new DataView(new ArrayBuffer(30));
|
||||
h.setUint32(0, 0x04034b50, true); h.setUint16(8, 8, true); h.setUint32(18, data.length, true); h.setUint32(22, raw.length, true); h.setUint16(26, n.length, true);
|
||||
const c = new DataView(new ArrayBuffer(46));
|
||||
c.setUint32(0, 0x02014b50, true); c.setUint16(10, 8, true); c.setUint32(20, data.length, true); c.setUint32(24, raw.length, true); c.setUint16(28, n.length, true); c.setUint32(42, off, true);
|
||||
parts.push(new Uint8Array(h.buffer), n, data);
|
||||
central.push(new Uint8Array(c.buffer), n);
|
||||
off += 30 + n.length + data.length;
|
||||
}
|
||||
const cdSize = central.reduce((s, x) => s + x.length, 0);
|
||||
const e = new DataView(new ArrayBuffer(22));
|
||||
e.setUint32(0, 0x06054b50, true); e.setUint16(8, Object.keys(files).length, true); e.setUint16(10, Object.keys(files).length, true); e.setUint32(12, cdSize, true); e.setUint32(16, off, true);
|
||||
const all = [...parts, ...central, new Uint8Array(e.buffer)];
|
||||
const out = new Uint8Array(all.reduce((s, x) => s + x.length, 0));
|
||||
let p = 0;
|
||||
for (const x of all) { out.set(x, p); p += x.length; }
|
||||
return out;
|
||||
}
|
||||
|
||||
// Summary Sales Report 1_0 (tab-separated, header as in App Store Connect Help); values are made up
|
||||
const SALES_TSV = ['Provider\tProvider Country\tSKU\tDeveloper\tTitle\tVersion\tProduct Type Identifier\tUnits\tDeveloper Proceeds\tBegin Date\tEnd Date\tCustomer Currency\tCountry Code\tCurrency of Proceeds\tApple Identifier\tCustomer Price',
|
||||
'APPLE\tUS\tcom.example.notes.pro\tExample\tPro\t\tIA1\t3\t3.49\t10/09/2026\t10/09/2026\tUSD\tUS\tUSD\t6400000301\t4.99',
|
||||
'APPLE\tUS\tcom.example.notes.pro\tExample\tPro\t\tIA1\t1\t3.49\t10/09/2026\t10/09/2026\tUSD\tCA\tUSD\t6400000301\t4.99',
|
||||
'APPLE\tUS\tcom.example.notes.pro\tExample\tPro\t\tIA1\t2\t4.12\t10/09/2026\t10/09/2026\tEUR\tDE\tEUR\t6400000301\t5.99',
|
||||
'APPLE\tUS\tNOTES1\tExample\tExample Notes\t1.2.0\t1F\t40\t0\t10/09/2026\t10/09/2026\tUSD\tUS\tUSD\t6400000101\t0', ''].join('\n');
|
||||
const FINANCE_TSV = ['Start Date\tEnd Date\tUPC\tISRC/ISBN\tVendor Identifier\tQuantity\tPartner Share\tExtended Partner Share\tPartner Share Currency\tSales or Return\tApple Identifier\tArtist/Show/Developer/Author\tTitle',
|
||||
'09/01/2026\t09/30/2026\t\t\tcom.example.notes.pro\t10\t3.49\t34.90\tUSD\tS\t6400000301\tExample\tPro',
|
||||
'09/01/2026\t09/30/2026\t\t\tcom.example.notes.pro\t-1\t3.49\t-3.49\tUSD\tR\t6400000301\tExample\tPro', '', 'Total_Rows\t2', 'Total_Amount\t31.41'].join('\n');
|
||||
const EARNINGS_CSV = 'Description,Transaction Date,Transaction Time,Tax Type,Transaction Type,Refund Type,Product Title,Package ID,Product Type,SKU ID,Hardware,Buyer Country,Buyer State,Buyer Postcode,Buyer Currency,Amount (Buyer Currency),Currency Conversion Rate,Merchant Currency,Amount (Merchant Currency)\n'
|
||||
+ 'GPA.0000-0000-0000-00001,"Sep 3, 2026",10:00:00 AM PDT,,Charge,,Pro (Example Notes),com.example.notes,inapp,com.example.notes.pro,phone,US,CA,9xxxx,USD,4.99,1,USD,4.99\n'
|
||||
+ 'GPA.0000-0000-0000-00001,"Sep 3, 2026",10:00:00 AM PDT,,Google fee,,Pro (Example Notes),com.example.notes,inapp,com.example.notes.pro,phone,US,CA,9xxxx,USD,-0.75,1,USD,-0.75\n'
|
||||
+ 'GPA.0000-0000-0000-00002,"Sep 4, 2026",11:00:00 AM PDT,,Charge,,Pro (Example Notes),com.example.notes,inapp,com.example.notes.pro,phone,DE,,,EUR,5.49,1.08,USD,5.93\n';
|
||||
const SALES_CSV = 'Order Number,Order Charged Date,Order Charged Timestamp,Financial Status,Device Model,Product Title,Package ID,Product Type,SKU ID,Currency of Sale,Item Price,Taxes Collected,Charged Amount,City of Buyer,State of Buyer,Postcode of Buyer,Country of Buyer\n'
|
||||
+ 'GPA.0000-0000-0000-00001,2026-09-03,1788000000,Charged,phone1,Pro,com.example.notes,inapp,com.example.notes.pro,USD,4.99,0.00,4.99,,CA,,US\n'
|
||||
+ 'GPA.0000-0000-0000-00003,2026-09-05,1788100000,Refund,phone2,Pro,com.example.notes,inapp,com.example.notes.pro,USD,4.99,0.00,4.99,,TX,,US\n';
|
||||
|
||||
describe('report parsers and summaries', () => {
|
||||
test('request paths follow the allowed combinations', () => {
|
||||
expect(appleSalesPath('12345678', { type: 'SALES', frequency: 'DAILY', date: '2026-10-09' })).toBe('/v1/salesReports?filter%5BvendorNumber%5D=12345678&filter%5BreportType%5D=SALES&filter%5BreportSubType%5D=SUMMARY&filter%5Bfrequency%5D=DAILY&filter%5BreportDate%5D=2026-10-09&filter%5Bversion%5D=1_0');
|
||||
expect(appleSalesPath('12345678', { type: 'SUBSCRIPTION', frequency: 'DAILY', date: '2026-10-09' })).toContain('filter%5Bversion%5D=1_3');
|
||||
expect(() => appleSalesPath('1', { type: 'SUBSCRIPTION', frequency: 'MONTHLY', date: '2026-09' })).toThrow('DAILY only');
|
||||
expect(appleFinancePath('12345678', '2026-09')).toContain('filter%5BreportType%5D=FINANCIAL&filter%5BregionCode%5D=ZZ&filter%5BreportDate%5D=2026-09');
|
||||
expect(appleFinancePath('12345678', '2026-09', { type: 'FINANCE_DETAIL' })).toContain('regionCode%5D=Z1');
|
||||
expect(appleReportDate('MONTHLY', undefined, new Date('2026-01-15T00:00:00Z'))).toBe('2025-12');
|
||||
expect(appleReportDate('DAILY', undefined, new Date('2026-10-11T12:00:00Z'))).toBe('2026-10-09');
|
||||
expect(() => appleReportDate('YEARLY', '2026-01')).toThrow('YYYY');
|
||||
expect(playReportPrefix('earnings', '2026-09')).toBe('earnings/earnings_202609');
|
||||
});
|
||||
test('Apple sales and finance: units x proceeds per SKU and currency, totals never mix currencies', () => {
|
||||
const s = summarizeAppleSales(parseTsv(SALES_TSV));
|
||||
expect(s).toEqual([
|
||||
{ key: 'NOTES1', title: 'Example Notes', currency: 'USD', units: 40, amount: 0, rows: 1 },
|
||||
{ key: 'com.example.notes.pro', title: 'Pro', currency: 'EUR', units: 2, amount: 8.24, rows: 1 },
|
||||
{ key: 'com.example.notes.pro', title: 'Pro', currency: 'USD', units: 4, amount: 13.96, rows: 2 },
|
||||
]);
|
||||
expect(totalsByCurrency(s)).toEqual([{ currency: 'EUR', units: 2, amount: 8.24 }, { currency: 'USD', units: 44, amount: 13.96 }]);
|
||||
expect(summarizeAppleFinance(parseTsv(FINANCE_TSV))).toEqual([{ key: 'com.example.notes.pro', title: 'Pro', currency: 'USD', units: 9, amount: 31.41, rows: 2 }]);
|
||||
});
|
||||
test('Play earnings and estimated sales out of the zip', () => {
|
||||
const files = unzip(zip({ 'PlayApps_202609.csv': EARNINGS_CSV }));
|
||||
expect(files.map(f => f.name)).toEqual(['PlayApps_202609.csv']);
|
||||
const e = summarizePlayEarnings(parsePlayCsv(new TextDecoder().decode(files[0]!.data)));
|
||||
expect(e).toEqual([
|
||||
{ key: 'com.example.notes.pro · Charge', title: 'Pro (Example Notes)', currency: 'USD', units: 2, amount: 10.92, rows: 2 },
|
||||
{ key: 'com.example.notes.pro · Google fee', title: 'Pro (Example Notes)', currency: 'USD', units: 0, amount: -0.75, rows: 1 },
|
||||
]);
|
||||
expect(summarizePlaySales(parsePlayCsv(SALES_CSV)).map(r => [r.key, r.amount])).toEqual([['com.example.notes.pro · Charged', 4.99], ['com.example.notes.pro · Refund', 4.99]]);
|
||||
expect(() => unzip(new Uint8Array(40))).toThrow('not a ZIP');
|
||||
});
|
||||
});
|
||||
|
||||
describe('reports command', () => {
|
||||
test('apple-sales: --dry hides the vendor number; a run saves the TSV and the summary CSV', async () => {
|
||||
ascEnv();
|
||||
process.env.ASC_VENDOR_NUMBER = '12345678';
|
||||
const p = project();
|
||||
const calls = mockFetch([{ match: /^\/v1\/salesReports\?/, answer: new Response(Bun.gzipSync(new TextEncoder().encode(SALES_TSV)), { headers: { 'content-type': 'application/a-gzip' } }) }]);
|
||||
let r = await capture(() => reports(p.ctx(['apple-sales', '--date', '2026-10-09', '--dry', '--json'])));
|
||||
expect(jsonOut(r.out).request).toContain('filter[vendorNumber]=<vendor>'.replace(/[[\]]/g, m => encodeURIComponent(m)));
|
||||
expect(calls).toHaveLength(0);
|
||||
r = await capture(() => reports(p.ctx(['apple-sales', '--date', '2026-10-09', '--json'])));
|
||||
const j = jsonOut(r.out);
|
||||
expect(j.rows).toBe(4);
|
||||
expect(j.totals).toEqual([{ currency: 'EUR', units: 2, amount: 8.24 }, { currency: 'USD', units: 44, amount: 13.96 }]);
|
||||
expect(calls[0]!.path).toContain('filter%5BvendorNumber%5D=12345678');
|
||||
expect(readFileSync(join(p.root, '.storebound/reports/apple-sales-daily-2026-10-09.tsv'), 'utf8')).toBe(SALES_TSV);
|
||||
expect(readFileSync(join(p.root, '.storebound/reports/apple-sales-daily-2026-10-09.summary.csv'), 'utf8')).toStartWith('key,title,currency,units,amount,rows\nNOTES1,Example Notes,USD,40,0,1\n');
|
||||
});
|
||||
test('apple-finance: 404 means no report yet; missing vendor number is explained', async () => {
|
||||
ascEnv();
|
||||
const p = project();
|
||||
await expect(capture(() => reports(p.ctx(['apple-finance', '--month', '2026-09'])))).rejects.toThrow('ASC_VENDOR_NUMBER');
|
||||
mockFetch([{ match: /^\/v1\/financeReports\?/, answer: new Response('{"errors":[{"status":"404","code":"NOT_FOUND","title":"The request expected results but none were found"}]}', { status: 404 }) }]);
|
||||
const r = await capture(() => reports(p.ctx(['apple-finance', '--month', '2026-09', '--vendor', '12345678'])));
|
||||
expect(r.out).toContain('no report for that date');
|
||||
});
|
||||
test('play-earnings: lists the bucket, unzips, summarizes', async () => {
|
||||
playEnv();
|
||||
const p = project();
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/storage\/v1\/b\/pubsite_prod_rev_01234567890123456789\/o\?prefix=earnings\/earnings_202609$/, answer: { kind: 'storage#objects', items: [{ kind: 'storage#object', name: 'earnings/earnings_202609_0123456789-1.zip', size: '512' }] } },
|
||||
{ match: /^\/storage\/v1\/b\/pubsite_prod_rev_01234567890123456789\/o\/earnings\/earnings_202609_0123456789-1\.zip\?alt=media$/, answer: new Response(zip({ 'PlayApps_202609.csv': EARNINGS_CSV }) as Uint8Array<ArrayBuffer>) },
|
||||
]);
|
||||
const r = await capture(() => reports(p.ctx(['play-earnings', '--month', '2026-09', '--json'])));
|
||||
expect(jsonOut(r.out)).toMatchObject({ rows: 3, totals: [{ currency: 'USD', units: 2, amount: 10.17 }] });
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(existsSync(join(p.root, '.storebound/reports/play-earnings-2026-09.csv'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- triage ----
|
||||
|
||||
const TEXT_CRASH = `Incident Identifier: 00000000-0000-0000-0000-000000000000
|
||||
Hardware Model: iPhone16,2
|
||||
Process: ExampleNotes [1234]
|
||||
Identifier: com.example.notes
|
||||
Version: 1.2.0 (50)
|
||||
OS Version: iPhone OS 26.0 (23A341)
|
||||
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
|
||||
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000010
|
||||
Crashed Thread: 3
|
||||
|
||||
Thread 0 name: Dispatch queue: com.apple.main-thread
|
||||
Thread 0:
|
||||
0 libsystem_kernel.dylib 0x00000001e0f0a1b4 mach_msg2_trap + 8
|
||||
|
||||
Thread 3 Crashed:
|
||||
0 libswiftCore.dylib 0x0000000190a1b2c4 swift_retain + 12
|
||||
1 ExampleNotes 0x0000000100f1a2b4 ListStore.sync(_:) + 220 (ListStore.swift:88)
|
||||
2 ExampleNotes 0x0000000100f1a000 closure #1 in ListStore.start() + 40
|
||||
|
||||
Thread 4:
|
||||
0 libsystem_pthread.dylib 0x00000001f0a0b0c0 start_wqthread + 0
|
||||
`;
|
||||
const IPS_CRASH = `{"app_name":"ExampleNotes","bundleID":"com.example.notes","app_version":"1.2.0","build_version":"50","os_version":"iPhone OS 26.0 (23A341)","name":"ExampleNotes"}
|
||||
{"procName":"ExampleNotes","exception":{"type":"EXC_CRASH","signal":"SIGABRT"},"faultingThread":0,"threads":[{"triggered":true,"frames":[{"imageIndex":1,"symbol":"__pthread_kill","imageOffset":8},{"imageIndex":0,"symbol":"ListStore.save()","imageOffset":4096}]}],"usedImages":[{"name":"ExampleNotes"},{"name":"libsystem_kernel.dylib"}]}`;
|
||||
|
||||
describe('triage parts', () => {
|
||||
test('crash signatures: first app frame of the crashed thread, text and .ips', () => {
|
||||
expect(crashSignature(TEXT_CRASH)).toBe('EXC_BAD_ACCESS (SIGSEGV) @ ExampleNotes ListStore.sync(_:) + 220 (ListStore.swift:88)');
|
||||
expect(crashSignature(IPS_CRASH)).toBe('EXC_CRASH SIGABRT @ ExampleNotes ListStore.save()');
|
||||
expect(crashSignature('garbage')).toBe('crash');
|
||||
});
|
||||
test('clusters with top devices, OS versions and builds; Play reports grouped by issue', () => {
|
||||
const items = feedbackItems([
|
||||
{ id: 'c1', attributes: { createdDate: '2026-10-09T10:00:00Z', deviceModel: 'iPhone16,2', osVersion: '26.0', comment: 'It crashed when I synced' }, relationships: { build: { data: { id: 'b-50' } } } },
|
||||
{ id: 'c2', attributes: { createdDate: '2026-10-10T10:00:00Z', deviceModel: 'iPhone16,2', osVersion: '26.0.1' }, relationships: { build: { data: { id: 'b-50' } } } },
|
||||
{ id: 'c3', attributes: { createdDate: '2026-10-10T11:00:00Z', deviceModel: 'iPhone15,3', osVersion: '26.0' }, relationships: { build: { data: { id: 'b-49' } } } },
|
||||
], new Map([['b-50', '50'], ['b-49', '49']]), new Map([['c1', 'A'], ['c2', 'A'], ['c3', 'B']]));
|
||||
const cs = cluster(items, { comments: 2 });
|
||||
expect(cs[0]).toEqual({ signature: 'A', count: 2, devices: [['iPhone16,2', 2]], os: [['26.0', 1], ['26.0.1', 1]], builds: [['50', 2]], first: '2026-10-09T10:00:00Z', last: '2026-10-10T10:00:00Z', comments: ['It crashed when I synced'] });
|
||||
const issues = playIssues({ errorIssues: [{ name: 'apps/com.example.notes/errorIssues/1111', type: 'CRASH', cause: 'java.lang.IllegalStateException', location: 'com.example.notes.ListStore.sync', errorReportCount: '12', distinctUsers: '9' }] });
|
||||
const play = playReportItems({ errorReports: [
|
||||
{ issue: 'apps/com.example.notes/errorIssues/1111', type: 'CRASH', eventTime: '2026-10-09T00:00:00Z', deviceModel: { marketingName: 'Pixel 9', deviceId: { buildBrand: 'google', buildDevice: 'tokay' } }, osVersion: { apiLevel: '36' }, appVersion: { versionCode: '120' } },
|
||||
{ issue: 'apps/com.example.notes/errorIssues/1111', type: 'CRASH', deviceModel: { deviceId: { buildBrand: 'samsung', buildDevice: 'dm3q' } }, osVersion: { apiLevel: '35' }, appVersion: { versionCode: '120' } },
|
||||
] }, issues);
|
||||
expect(cluster(play)[0]).toMatchObject({ signature: 'CRASH java.lang.IllegalStateException @ com.example.notes.ListStore.sync', count: 2, devices: [['Pixel 9', 1], ['samsung/dm3q', 1]], os: [['API 35', 1], ['API 36', 1]], builds: [['120', 2]] });
|
||||
expect(reportsQuery('1111', new Date('2026-09-27T00:00:00Z'), new Date('2026-10-11T00:00:00Z'))).toContain('filter=errorIssueId+%3D+1111');
|
||||
});
|
||||
test('command: both stores, emails never requested, --json', async () => {
|
||||
ascEnv(); playEnv();
|
||||
const p = project();
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/builds\?filter\[app\]=6400000101/, answer: { data: [{ type: 'builds', id: 'b-50', attributes: { version: '50' } }], links: {} } },
|
||||
{ match: /^\/v1\/apps\/6400000101\/betaFeedbackCrashSubmissions\?/, answer: { data: [{ type: 'betaFeedbackCrashSubmissions', id: 'c1', attributes: { createdDate: new Date().toISOString(), deviceModel: 'iPhone16,2', osVersion: '26.0' }, relationships: { build: { data: { type: 'builds', id: 'b-50' } } } }], links: {} } },
|
||||
{ match: /^\/v1\/betaFeedbackCrashSubmissions\/c1\/crashLog$/, answer: { data: { type: 'betaCrashLogs', id: 'cl1', attributes: { logText: TEXT_CRASH } } } },
|
||||
{ match: /^\/v1\/apps\/6400000101\/betaFeedbackScreenshotSubmissions\?/, answer: { data: [], links: {} } },
|
||||
{ match: /^\/v1beta1\/apps\/com\.example\.notes\/errorIssues:search\?/, answer: { errorIssues: [{ name: 'apps/com.example.notes/errorIssues/1111', type: 'ANR', cause: 'Input dispatching timed out', location: 'com.example.notes.MainActivity', errorReportCount: '4', distinctUsers: '3' }] } },
|
||||
{ match: /^\/v1beta1\/apps\/com\.example\.notes\/errorReports:search\?/, answer: { errorReports: [{ issue: 'apps/com.example.notes/errorIssues/1111', type: 'ANR', deviceModel: { marketingName: 'Pixel 9' }, osVersion: { apiLevel: '36' }, appVersion: { versionCode: '120' } }] } },
|
||||
]);
|
||||
const r = await capture(() => triage(p.ctx(['--days', '14', '--json'])));
|
||||
const j = jsonOut(r.out) as { apple: { crashes: { signature: string }[] }; play: { issues: { signature: string; reports: number }[] } };
|
||||
expect(j.apple.crashes[0]!.signature).toContain('ListStore.sync');
|
||||
expect(j.play.issues[0]).toMatchObject({ signature: 'ANR Input dispatching timed out @ com.example.notes.MainActivity', count: 1, reports: 4 });
|
||||
const fb = calls.filter(c => c.path.includes('betaFeedback') && c.path.includes('fields'));
|
||||
expect(fb).toHaveLength(2);
|
||||
for (const c of fb) { expect(decodeURIComponent(c.path)).not.toContain('email'); expect(decodeURIComponent(c.path)).not.toContain('tester'); }
|
||||
expect(BASE.app.contactEmail).toBe('support@example.com');
|
||||
});
|
||||
});
|
||||
283
tests/store-ops-text.test.ts
Normal file
283
tests/store-ops-text.test.ts
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
// Listing pulls, release notes in many languages, keyword ranks and the AdAttributionKit scan: pure parts plus the
|
||||
// commands against recorded store answers (placeholders only).
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { compactDiff, lineDiff } from '../cli/lib/diff';
|
||||
import { catalogProposal, mergeAppleListing, mergePlayListing, overLimits } from '../cli/lib/listing-pull';
|
||||
import { applyLanguageNotes, checkLanguageNotes, notesFileText, parseNotesFile, resolveLanguages } from '../cli/lib/whats-new';
|
||||
import { competitors, keywordList, parseStorefronts, rankDelta, rankOf, searchUrl } from '../cli/lib/aso-rank';
|
||||
import { parsePlist } from '../cli/lib/plist';
|
||||
import { evaluateAdAttribution, sourceSignals } from '../cli/lib/adattribution';
|
||||
import { parseArgs } from '../cli/lib/args';
|
||||
import { run as appleListing } from '../cli/apple/listing';
|
||||
import { run as playListing } from '../cli/play/listing';
|
||||
import { run as catalog } from '../cli/catalog';
|
||||
import { run as whatsNew } from '../cli/whats-new';
|
||||
import { run as aso } from '../cli/aso';
|
||||
import { run as ads } from '../cli/ads';
|
||||
import { TOOLS, toArgv } from '../cli/mcp-tools';
|
||||
import { ascEnv, BASE, capture, jsonOut, mockFetch, playEnv, project, restore } from './helpers/store-mock';
|
||||
|
||||
afterEach(restore);
|
||||
const page = (data: unknown[]) => ({ data, links: { self: 'x' } });
|
||||
|
||||
const APPLE_MD = '# App Store\n\n## en-US · English\n\n### subtitle\n```\nNotes that sync\n```\n\n### keywords\n```\nnotes,lists\n```\n\n### description\n```\nOld text.\n```\n\n## Notes\n\nprose\n';
|
||||
const PLAY_MD = '# Play\n\n## English\n<!-- play: en-US -->\n\n### Play short description (max 80)\n```\nOld short\n```\n\n### Play full description (max 4000)\n```\nOld full.\n```\n\n## Spanish\n<!-- play: es-ES, es-419 -->\n\n### short\n```\nCorta\n```\n\n### full\n```\nLarga.\n```\n';
|
||||
|
||||
describe('diff', () => {
|
||||
test('line diff and compact diff', () => {
|
||||
expect(lineDiff('a\nb\nc', 'a\nx\nc')).toEqual([' a', '-b', '+x', ' c']);
|
||||
expect(compactDiff('1\n2\n3\n4\n5\n6\n7\n8', '1\n2\n3\n4\n5\n6\n7\nX', 1)).toEqual([' 7', '-8', '+X']);
|
||||
expect(compactDiff('same', 'same')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listing pull merges', () => {
|
||||
test('App Store: changed blocks replaced, missing ones added, new locales appended, prose kept', () => {
|
||||
const r = mergeAppleListing(APPLE_MD, { 'en-US': { subtitle: 'Notes that sync', description: 'New text.', promotionalText: 'Now with lists.' }, 'tr': { subtitle: 'Senkron notlar', keywords: 'not,liste' } });
|
||||
expect(r.changes.map(c => `${c.section} ${c.field} ${c.from === null ? 'new' : 'changed'}`)).toEqual(['en-US promotionalText new', 'en-US description changed', 'tr subtitle new', 'tr keywords new']);
|
||||
expect(r.md).toContain('### description\n```\nNew text.\n```');
|
||||
expect(r.md).toContain('### promotionalText\n```\nNow with lists.\n```');
|
||||
expect(r.md).toContain('## Notes\n\nprose');
|
||||
expect(r.md).toContain('## tr\n\n### subtitle\n```\nSenkron notlar\n```');
|
||||
expect(r.added).toEqual(['tr']);
|
||||
expect(overLimits([{ section: 'tr', field: 'subtitle', from: null, to: 'x'.repeat(31) }], 'apple')).toEqual(['tr subtitle: 31 > 30']);
|
||||
});
|
||||
test('Play: per section, shared sections only when the codes agree, title equal to the app name left out', () => {
|
||||
const r = mergePlayListing(PLAY_MD, [
|
||||
{ language: 'en-US', title: 'Example Notes', shortDescription: 'New short', fullDescription: 'Old full.' },
|
||||
{ language: 'es-ES', shortDescription: 'Corta nueva', fullDescription: 'Larga.' }, { language: 'es-419', shortDescription: 'Otra corta', fullDescription: 'Larga.' },
|
||||
{ language: 'fr-FR', title: 'Notes Exemple', shortDescription: 'Court', fullDescription: 'Long.' },
|
||||
], 'Example Notes');
|
||||
expect(r.changes.map(c => `${c.section} ${c.field}`)).toEqual(['en-US shortDescription', 'fr-FR title', 'fr-FR shortDescription', 'fr-FR fullDescription']);
|
||||
expect(r.conflicts[0]).toContain('es-ES, es-419: shortDescription differs');
|
||||
expect(r.md).toContain('### Play short description (max 80)\n```\nNew short\n```');
|
||||
expect(r.md).not.toContain('### Title (max 30)\n```\nExample Notes');
|
||||
expect(r.md).toContain('## fr-FR\n<!-- play: fr-FR -->\n\n### Title (max 30)\n```\nNotes Exemple\n```');
|
||||
});
|
||||
test('catalog proposal maps store languages to language ids and never touches unknown products', () => {
|
||||
const cfg = { ...BASE, products: [{ id: 'com.example.notes.pro', type: 'non_consumable' as const, usd: 4.99, listings: { en: { title: 'Pro', description: 'All features' } } }] };
|
||||
const p = catalogProposal(cfg, { apple: { 'com.example.notes.pro': { 'en-US': { title: 'Pro', description: 'Every feature' }, 'tr': { title: 'Pro', description: 'Tüm özellikler' }, 'ja': { title: 'プロ', description: 'x' } }, 'com.example.notes.other': {} },
|
||||
play: { 'com.example.notes.pro': { 'en-US': { title: 'Pro unlock', description: 'All features' } } } });
|
||||
expect(p.changes.map(c => `${c.store} ${c.lang} ${c.field}`)).toEqual(['play en title', 'apple en description', 'apple tr title', 'apple tr description']);
|
||||
expect(p.listings['com.example.notes.pro']!.tr).toEqual({ title: 'Pro', description: 'Tüm özellikler' });
|
||||
expect(p.unmapped).toEqual(['apple:ja']);
|
||||
expect(p.unknown).toEqual(['com.example.notes.other']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listing pull commands', () => {
|
||||
test('apple listing pull: diff without --write, file updated with --write', async () => {
|
||||
ascEnv();
|
||||
const p = project(BASE, { 'store/appstore.md': APPLE_MD });
|
||||
mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/appStoreVersions\?filter\[platform\]=IOS/, answer: page([{ type: 'appStoreVersions', id: 'v-1', attributes: { versionString: '1.1.0', appVersionState: 'READY_FOR_DISTRIBUTION', createdDate: '2026-09-01T00:00:00-07:00' } }]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/appInfos/, answer: page([{ type: 'appInfos', id: 'ai-1', attributes: { state: 'READY_FOR_DISTRIBUTION' } }]) },
|
||||
{ match: /^\/v1\/appInfos\/ai-1\/appInfoLocalizations/, answer: page([{ type: 'appInfoLocalizations', id: 'l', attributes: { locale: 'en-US', name: 'Example Notes', subtitle: 'Notes that sync', privacyPolicyUrl: 'https://example.com/privacy' } }]) },
|
||||
{ match: /^\/v1\/appStoreVersions\/v-1\/appStoreVersionLocalizations/, answer: page([{ type: 'appStoreVersionLocalizations', id: 'vl', attributes: { locale: 'en-US', description: 'Live text.', keywords: 'notes,lists', promotionalText: null, whatsNew: 'Faster sync.' } }]) },
|
||||
]);
|
||||
let r = await capture(() => appleListing(p.ctx(['pull', '--json'])));
|
||||
const j = jsonOut(r.out);
|
||||
expect(j).toMatchObject({ version: '1.1.0', write: false, added: [] });
|
||||
expect((j.changes as { field: string }[]).map(c => c.field)).toEqual(['name', 'description', 'whatsNew']);
|
||||
expect(j.diff).toContain('-Old text.');
|
||||
expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toBe(APPLE_MD);
|
||||
r = await capture(() => appleListing(p.ctx(['pull', '--write'])));
|
||||
expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toContain('### whatsNew\n```\nFaster sync.\n```');
|
||||
expect(r.out).toContain('3 change(s) written');
|
||||
});
|
||||
test('play listing pull: one read-only edit, deleted; --write updates the file', async () => {
|
||||
playEnv();
|
||||
const p = project(BASE, { 'store/listing.md': PLAY_MD });
|
||||
const routes = () => mockFetch([
|
||||
{ method: 'POST', match: /\/applications\/com\.example\.notes\/edits$/, answer: { id: 'edit-1', expiryTimeSeconds: '1760000000' } },
|
||||
{ match: /\/edits\/edit-1\/listings$/, answer: { kind: 'androidpublisher#listingsListResponse', listings: [{ language: 'en-US', title: 'Example Notes', shortDescription: 'Live short', fullDescription: 'Old full.' }] } },
|
||||
{ method: 'DELETE', match: /\/edits\/edit-1$/, answer: new Response(null, { status: 204 }) },
|
||||
]);
|
||||
let calls = routes();
|
||||
let r = await capture(() => playListing(p.ctx(['pull', '--json'])));
|
||||
expect(jsonOut(r.out)).toMatchObject({ write: false, languages: ['en-US'], changes: [{ section: 'en-US', field: 'shortDescription', from: 'Old short', to: 'Live short' }] });
|
||||
expect(calls.map(c => c.method)).toEqual(['POST', 'GET', 'DELETE']);
|
||||
calls = routes();
|
||||
r = await capture(() => playListing(p.ctx(['pull', '--write'])));
|
||||
expect(readFileSync(join(p.root, 'store/listing.md'), 'utf8')).toContain('```\nLive short\n```');
|
||||
expect(calls.some(c => c.path.includes(':commit'))).toBe(false);
|
||||
});
|
||||
test('catalog pull --write saves a proposal next to an unchanged config', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, play: undefined, products: [{ id: 'com.example.notes.pro', type: 'non_consumable', usd: 4.99, listings: { en: { title: 'Pro', description: 'All features' } } }] });
|
||||
mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2/, answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: 'com.example.notes.pro' } }]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseLocalizations/, answer: page([{ type: 'inAppPurchaseLocalizations', id: 'l1', attributes: { locale: 'en-US', name: 'Pro', description: 'Every feature' } }]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/subscriptionGroups/, answer: page([]) },
|
||||
]);
|
||||
const r = await capture(() => catalog(p.ctx(['pull', '--store', 'apple', '--write'])));
|
||||
const saved = JSON.parse(readFileSync(join(p.root, '.storebound/pull/catalog.json'), 'utf8'));
|
||||
expect(saved.listings['com.example.notes.pro'].en).toEqual({ title: 'Pro', description: 'Every feature' });
|
||||
expect(r.out).toContain('storebound.config.ts is unchanged');
|
||||
});
|
||||
});
|
||||
|
||||
describe('release notes in many languages', () => {
|
||||
const langs = BASE.languages;
|
||||
test('language files, limits per store, apply into both listing files', () => {
|
||||
expect(resolveLanguages(langs, ['en-US', 'de', 'tr-TR']).map(l => l.id)).toEqual(['en', 'de', 'tr']);
|
||||
expect(() => resolveLanguages(langs, ['fr'])).toThrow('not a language of the config');
|
||||
const f = { lang: 'de', source: 'en', status: 'translate' as const, text: 'New: lists.' };
|
||||
expect(parseNotesFile(notesFileText(f), 'de')).toEqual(f);
|
||||
expect(parseNotesFile('Plain text', 'tr')).toEqual({ lang: 'tr', source: '', status: 'translated', text: 'Plain text' });
|
||||
expect(checkLanguageNotes(langs[1]!, f, 'New: lists.').problems).toEqual(['not translated yet (status=translate)']);
|
||||
expect(checkLanguageNotes(langs[1]!, { ...f, status: 'translated' }, 'New: lists.').problems).toEqual(['identical to the source language: translate it']);
|
||||
const long = checkLanguageNotes(langs[2]!, { ...f, status: 'translated', text: 'x'.repeat(501) });
|
||||
expect(long.play).toEqual({ limit: 500, ok: false });
|
||||
expect(long.apple).toEqual({ limit: 4000, ok: true });
|
||||
expect(checkLanguageNotes({ id: 'ios-only', apple: 'ja' }, { ...f, status: 'translated', text: 'x'.repeat(600) }).problems.filter(p => !p.startsWith('first line'))).toEqual([]);
|
||||
const out = applyLanguageNotes({ play: PLAY_MD.replace('<!-- play: en-US -->', '<!-- play: en-US -->').replace('## Spanish', '## German\n<!-- play: de-DE -->\n\n### short\n```\nk\n```\n\n### full\n```\nl\n```\n\n## Spanish'), apple: APPLE_MD.replace('## Notes', '## de-DE\n\n### subtitle\n```\nx\n```\n\n## Notes') }, langs[1]!, 'Neu: Listen.');
|
||||
expect(out.changed).toEqual(['play:de-DE', 'apple:de-DE']);
|
||||
expect(out.play).toContain("### What's new (max 500)\n```\nNeu: Listen.\n```");
|
||||
expect(out.apple).toContain('### whatsNew\n```\nNeu: Listen.\n```');
|
||||
});
|
||||
test('command: --languages writes one file per language, a --translate hook fills them, check and apply', async () => {
|
||||
const p = project(BASE, { 'store/listing.md': PLAY_MD.replace('## Spanish', '## German\n<!-- play: de-DE -->\n\n### short\n```\nk\n```\n\n### full\n```\nl\n```\n\n## Spanish'), 'store/appstore.md': APPLE_MD });
|
||||
const git = (...a: string[]) => Bun.spawnSync(['git', ...a], { cwd: p.root, env: { ...process.env, GIT_AUTHOR_NAME: 'T', GIT_AUTHOR_EMAIL: 't@example.com', GIT_COMMITTER_NAME: 'T', GIT_COMMITTER_EMAIL: 't@example.com' } });
|
||||
git('init', '-q'); git('add', '.'); git('commit', '-qm', 'chore: init'); git('tag', 'v1.0.0'); git('commit', '-q', '--allow-empty', '-m', 'feat: shared lists');
|
||||
let r = await capture(() => whatsNew(p.ctx(['--languages', 'en,de', '--dry', '--json'])));
|
||||
expect((jsonOut(r.out).files as { status: string }[]).map(f => f.status)).toEqual(['source', 'translate']);
|
||||
expect(existsSync(join(p.root, 'store/whats-new'))).toBe(false);
|
||||
r = await capture(() => whatsNew(p.ctx(['--languages', 'en,de'])));
|
||||
expect(readFileSync(join(p.root, 'store/whats-new/de.md'), 'utf8')).toMatch(/^<!-- whats-new lang=de source=en status=translate -->\nNew in this update:\n• Shared lists\./);
|
||||
r = await capture(() => whatsNew(p.ctx(['check', '--json'])));
|
||||
expect(r.exit).toBe(1);
|
||||
expect((jsonOut(r.out).checks as { lang: string; problems: string[] }[])[1]!.problems).toContain('not translated yet (status=translate)');
|
||||
r = await capture(() => whatsNew(p.ctx(['apply'])));
|
||||
expect(r.out).toContain('nothing written');
|
||||
// the provider hook: any command; here one that upper-cases the text
|
||||
r = await capture(() => whatsNew(p.ctx(['--languages', 'en,de', '--translate', 'tr a-z A-Z'])));
|
||||
expect(readFileSync(join(p.root, 'store/whats-new/de.md'), 'utf8')).toContain('status=translated -->\nNEW IN THIS UPDATE:');
|
||||
r = await capture(() => whatsNew(p.ctx(['apply', '--json'])));
|
||||
expect(jsonOut(r.out).changed).toEqual(['play:en-US', 'apple:en-US', 'play:de-DE']);
|
||||
expect(readFileSync(join(p.root, 'store/listing.md'), 'utf8')).toContain('NEW IN THIS UPDATE:');
|
||||
});
|
||||
});
|
||||
|
||||
describe('keyword ranks (iTunes Search API)', () => {
|
||||
const RESULTS = { resultCount: 3, results: [
|
||||
{ trackId: 6400000999, trackName: 'Other Notes', bundleId: 'com.example.other', sellerName: 'Other Studio', averageUserRating: 4.5, userRatingCount: 1200, primaryGenreName: 'Productivity' },
|
||||
{ trackId: 6400000101, trackName: 'Example Notes', bundleId: 'com.example.notes', sellerName: 'Example', averageUserRating: 4.8, userRatingCount: 50 },
|
||||
{ trackId: 6400000998, trackName: 'Lists Pro', bundleId: 'com.example.lists', sellerName: 'Lists Inc' },
|
||||
] };
|
||||
test('pure parts', () => {
|
||||
expect(searchUrl('shared lists', 'US', 500)).toBe('https://itunes.apple.com/search?term=shared+lists&country=us&media=software&entity=software&limit=200');
|
||||
expect(() => searchUrl('x', 'usa')).toThrow('two-letter');
|
||||
expect(keywordList('notes, lists,Notes,,todo', ['todo', 'planner'])).toEqual(['notes', 'lists', 'todo', 'planner']);
|
||||
expect(parseStorefronts(['us', 'de=de-DE'], 'en-US')).toEqual([{ storefront: 'us', locale: 'en-US' }, { storefront: 'de', locale: 'de-DE' }]);
|
||||
expect(rankOf(RESULTS.results, { appId: '6400000101' })).toBe(2);
|
||||
expect(rankOf(RESULTS.results, { bundleId: 'com.example.lists' })).toBe(3);
|
||||
expect(rankOf(RESULTS.results, { appId: '1' })).toBeNull();
|
||||
expect(competitors(RESULTS.results, { appId: '6400000101' }, 2)).toEqual([{ rank: 1, title: 'Other Notes', developer: 'Other Studio', rating: 4.5, ratings: 1200, genre: 'Productivity' }, { rank: 3, title: 'Lists Pro', developer: 'Lists Inc', rating: null, ratings: 0, genre: '' }]);
|
||||
expect(rankDelta([{ storefront: 'us', locale: 'en-US', keyword: 'Notes', rank: 2, results: 3, competitors: [] }], [{ storefront: 'us', locale: 'en-US', keyword: 'notes', rank: 5, results: 3, competitors: [] }]).get('us|notes')).toBe(3);
|
||||
});
|
||||
test('command: --dry lists the queries; a run saves a snapshot', async () => {
|
||||
const p = project(BASE, { 'store/appstore.md': '## en-US\n\n### keywords\n```\nnotes\n```\n' });
|
||||
const calls = mockFetch([{ match: /^\/search\?term=notes&country=us/, answer: RESULTS }]);
|
||||
let r = await capture(() => aso(p.ctx(['rank', '--dry', '--json'])));
|
||||
expect(jsonOut(r.out).queries).toEqual([{ storefront: 'us', keyword: 'notes', url: 'https://itunes.apple.com/search?term=notes&country=us&media=software&entity=software&limit=200' }]);
|
||||
expect(calls).toHaveLength(0);
|
||||
r = await capture(() => aso(p.ctx(['rank', '--json'])));
|
||||
expect((jsonOut(r.out).rows as { rank: number; competitors: unknown[] }[])[0]).toMatchObject({ keyword: 'notes', rank: 2, results: 3 });
|
||||
expect(calls).toHaveLength(1);
|
||||
const snap = JSON.parse(readFileSync(join(p.root, '.storebound/aso', `${new Date().toISOString().slice(0, 10)}.json`), 'utf8'));
|
||||
expect(snap.rows[0].competitors[0].title).toBe('Other Notes');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AdAttributionKit scan', () => {
|
||||
const PLIST = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key><string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>SKAdNetworkItems</key>
|
||||
<array>
|
||||
<dict><key>SKAdNetworkIdentifier</key><string>cstr6suwn9.skadnetwork</string></dict>
|
||||
<dict><key>SKAdNetworkIdentifier</key><string>4FZDC2EVR5.skadnetwork</string></dict>
|
||||
</array>
|
||||
<key>AdNetworkIdentifiers</key>
|
||||
<array><string>cstr6suwn9.skadnetwork</string><string>f2d92a.adattributionkit</string></array>
|
||||
<key>AdAttributionKit</key>
|
||||
<dict>
|
||||
<key>AttributionCopyEndpoint</key><string>https://postbacks.example.com/attribution</string>
|
||||
<key>EligibleForAdAttributionKitReengagementPostbackCopies</key><true/>
|
||||
</dict>
|
||||
<key>NSAdvertisingAttributionReportEndpoint</key><string>https://example.com</string>
|
||||
<key>AdAttributionKitConfigurations</key>
|
||||
<dict>
|
||||
<key>AttributionWindows</key>
|
||||
<dict>
|
||||
<key>global</key><dict><key>install</key><dict><key>view</key><integer>9</integer><key>ignoreInteractionType</key><string>view</string></dict></dict>
|
||||
<key>f2d92a.adattributionkit</key><dict><key>install</key><dict><key>click</key><integer>23</integer></dict></dict>
|
||||
</dict>
|
||||
<key>AttributionCooldown</key><dict><key>install-cooldown-hours</key><integer>24</integer><key>re-engagement-cooldown-hours</key><integer>900</integer></dict>
|
||||
</dict>
|
||||
<key>Empty</key><string/>
|
||||
<key>Ratio</key><real>1.5</real>
|
||||
</dict>
|
||||
</plist>`;
|
||||
test('plist reader', () => {
|
||||
const p = parsePlist(PLIST) as Record<string, unknown>;
|
||||
expect(p.CFBundleIdentifier).toBe('$(PRODUCT_BUNDLE_IDENTIFIER)');
|
||||
expect(p.Empty).toBe('');
|
||||
expect(p.Ratio).toBe(1.5);
|
||||
expect((p.AdAttributionKit as Record<string, unknown>).EligibleForAdAttributionKitReengagementPostbackCopies).toBe(true);
|
||||
expect(() => parsePlist('bplist00...')).toThrow('binary plist');
|
||||
});
|
||||
test('findings: id case, windows and cooldown ranges, global ignore, endpoints, missing conversion updates', () => {
|
||||
const sig = sourceSignals([{ path: 'Podfile.lock', text: 'PODS:\n - Google-Mobile-Ads-SDK (11.0.0)\n' }, { path: 'App/AppDelegate.swift', text: 'import UIKit\nimport AdAttributionKit\n' }]);
|
||||
expect(sig).toEqual({ aakImport: true, conversionUpdates: false, adSdks: ['Google Mobile Ads (AdMob)'], mmpSdks: [] });
|
||||
const f = evaluateAdAttribution(parsePlist(PLIST) as Record<string, never>, sig);
|
||||
const codes = f.map(x => `${x.level}:${x.code}`);
|
||||
for (const c of ['blocker:id-case', 'info:aak-ids-partial', 'warn:endpoint-path', 'ok:copy-endpoint', 'ok:skan-endpoint', 'blocker:window-view', 'warn:ignore-global', 'blocker:cooldown-range', 'warn:no-conversion-update'])
|
||||
expect(codes).toContain(c);
|
||||
expect(codes).not.toContain('warn:windows-unknown-network');
|
||||
expect(f.find(x => x.code === 'copy-endpoint')!.msg).toContain('https://example.com/.well-known/appattribution/report-attribution/');
|
||||
// a publisher with an ad SDK and no ids at all, the top-level copy key, an MMP SDK doing the conversion updates
|
||||
const g = evaluateAdAttribution({ AttributionCopyEndpoint: 'http://example.com' } as never, { aakImport: false, conversionUpdates: false, adSdks: ['AppLovin MAX'], mmpSdks: ['AppsFlyer'] });
|
||||
expect(g.map(x => x.code)).toEqual(['no-network-ids', 'endpoint-url']);
|
||||
expect(evaluateAdAttribution({}, { aakImport: false, conversionUpdates: false, adSdks: [], mmpSdks: [] }).map(x => x.code)).toEqual(['none']);
|
||||
});
|
||||
test('command: scans the app Info.plist, skips Pods and tests, exit 1 on a blocker', async () => {
|
||||
const p = project(BASE, { 'ios/App/App/Info.plist': PLIST, 'ios/App/Pods/X/Info.plist': '<plist><dict/></plist>', 'ios/App/AppTests/Info.plist': '<plist><dict/></plist>', 'ios/App/Podfile.lock': 'PODS:\n - AppLovinSDK (13.0.0)\n',
|
||||
'ios/App/App/Attribution.swift': 'import AdAttributionKit\nfunc first() async { try? await Postback.updateConversionValue(1, lockPostback: false) }\n' });
|
||||
const r = await capture(() => ads(parseArgs(['scan', '--ios', join(p.root, 'ios/App'), '--json'])));
|
||||
const j = jsonOut(r.out);
|
||||
expect((j.results as { plist: string }[]).map(x => x.plist.split('/').slice(-3).join('/'))).toEqual(['App/App/Info.plist']);
|
||||
expect(j.signals).toEqual({ aakImport: true, conversionUpdates: true, adSdks: ['AppLovin MAX'], mmpSdks: [] });
|
||||
expect(j.blockers).toBe(3);
|
||||
expect(r.exit).toBe(1);
|
||||
mkdirSync(join(p.root, 'empty'), { recursive: true });
|
||||
writeFileSync(join(p.root, 'empty/readme.txt'), 'no app');
|
||||
const e = await capture(() => ads(parseArgs(['scan', '--ios', join(p.root, 'empty')])));
|
||||
expect(e.out).toContain('no app Info.plist');
|
||||
expect(e.exit).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MCP tools of the store operations', () => {
|
||||
const t = (n: string) => TOOLS.find(x => x.name === n)!;
|
||||
test('pulls write only with dry_run false; plans and reads stay read-only; owner steps are not tools', () => {
|
||||
expect(toArgv(t('apple_listing_pull')).argv).toEqual(['apple', 'listing', 'pull', '--json', '--dry']);
|
||||
expect(toArgv(t('apple_listing_pull'), { dry_run: false }).argv).toEqual(['apple', 'listing', 'pull', '--json', '--write']);
|
||||
expect(toArgv(t('play_listing_pull'), { dry_run: false }).argv).toEqual(['play', 'listing', 'pull', '--json', '--write']);
|
||||
expect(toArgv(t('apple_iap_review_plan'), { with_version: true }).argv).toEqual(['apple', 'iap-submit', '--with-version', '--json', '--dry']);
|
||||
expect(toArgv(t('apple_testflight_wait'), { build: '50', check_once: true }).argv).toEqual(['apple', 'testflight', 'wait', '--build', '50', '--timeout', '30m', '--json', '--dry']);
|
||||
expect(toArgv(t('reports'), { kind: 'play-earnings', month: '2026-09' }).argv).toEqual(['reports', 'play-earnings', '--month', '2026-09', '--json', '--dry']);
|
||||
expect(toArgv(t('aso_rank'), { storefronts: 'us,de=de-DE' }).argv).toEqual(['aso', 'rank', '--storefronts', 'us,de=de-DE', '--json', '--dry']);
|
||||
expect(t('triage')).toMatchObject({ write: false });
|
||||
expect(t('ads_scan')).toMatchObject({ write: false, network: false });
|
||||
const commands = TOOLS.map(x => x.command.join(' '));
|
||||
for (const c of ['apple offer-codes', 'apple win-back', 'apple promoted', 'apple preorder enable', 'apple preorder end', 'apple cpp submit', 'apple cpp visible', 'apple events submit', 'apple testflight expire'])
|
||||
expect(commands).not.toContain(c);
|
||||
for (const x of TOOLS) expect(toArgv(x, { dry_run: false, kind: 'apple-sales', build: '1', languages: 'en', name: 'x', ios: 'ios' }).argv.join(' ')).not.toMatch(/--(codes|enable|yes|translate|no-submit)\b/);
|
||||
});
|
||||
});
|
||||
|
|
@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
|
|||
import { join } from 'node:path';
|
||||
import { generate, parseSkill, readSkills } from '../tools/gen-adapters';
|
||||
import { scan } from '../tools/scrub';
|
||||
import { FORBIDDEN_ARGS, listTools, TOOLS, toArgv, validateInput } from '../cli/mcp-tools';
|
||||
import { FORBIDDEN_ARGS, listTools, LOCAL_WRITE_TOOLS, TOOLS, toArgv, validateInput } from '../cli/mcp-tools';
|
||||
import { handle, LEGACY_PROTOCOL as PROTOCOL } from '../cli/mcp';
|
||||
import { auditAppleKeywords, auditAso, auditPlayListing, crossLocaleHint } from '../cli/lib/aso';
|
||||
import { checkNotes, formatNotes, noteItems, setAppleWhatsNew, setPlayWhatsNew } from '../cli/lib/whats-new';
|
||||
|
|
@ -81,9 +81,12 @@ describe('mcp tools', () => {
|
|||
for (const combo of [{}, ...enums.map(e => Object.fromEntries(Object.entries(t.props ?? {}).filter(([, p]) => p.enum?.includes(e)).map(([k]) => [k, e])))]) {
|
||||
const input: Record<string, unknown> = { ...Object.fromEntries((t.required ?? []).map(r => [r, r === 'action' ? 'on' : r === 'version' ? '1.0.0' : 'x'])), ...combo, dry_run: false };
|
||||
const argv = toArgv(t, input).argv;
|
||||
for (const f of FORBIDDEN_ARGS) expect({ tool: t.name, argv, hit: argv.includes(f) }).toEqual({ tool: t.name, argv, hit: false });
|
||||
for (const f of FORBIDDEN_ARGS.filter(x => !LOCAL_WRITE_TOOLS[t.name]?.includes(x))) expect({ tool: t.name, argv, hit: argv.includes(f) }).toEqual({ tool: t.name, argv, hit: false });
|
||||
}
|
||||
}
|
||||
// the local-write exception covers only the pull tools, and only with dry_run false
|
||||
expect(Object.keys(LOCAL_WRITE_TOOLS).sort()).toEqual(['apple_listing_pull', 'catalog_pull', 'play_listing_pull']);
|
||||
for (const n of Object.keys(LOCAL_WRITE_TOOLS)) expect(toArgv(TOOLS.find(t => t.name === n)!, {}).argv).not.toContain('--write');
|
||||
const phased = TOOLS.find(t => t.name === 'apple_phased_release')!;
|
||||
expect(phased.props!.action!.enum).toEqual(['on', 'pause']);
|
||||
expect(TOOLS.find(t => t.name === 'play_release_testing')!.props!.track!.enum).not.toContain('production');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue