crt-ship 0.1.0: CLI, Claude Code skills and templates for shipping mobile games to Google Play and the App Store
This commit is contained in:
commit
ecb3dc3dc3
64 changed files with 4509 additions and 0 deletions
71
cli/apple/appinfo.ts
Normal file
71
cli/apple/appinfo.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// App-level App Store settings (idempotent), from apple.info in crt-ship.config.ts:
|
||||
// crt-ship apple appinfo [--dry]
|
||||
// - categories (primary + up to two game subcategories, secondary)
|
||||
// - age rating declaration: every content question NONE / false unless overridden in apple.info.ageRating
|
||||
// - content rights declaration
|
||||
// - price Free (USA base) and availability in every territory + new ones (when apple.info.free !== false)
|
||||
// App Privacy ("nutrition label") has no API: web UI only (store-declarations skill).
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { ascClient } from './asc';
|
||||
|
||||
/** Every question of the current age rating declaration at its "nothing" answer. */
|
||||
export const AGE_RATING_NONE: Record<string, string | boolean | null> = {
|
||||
advertising: false, ageAssurance: false, alcoholTobaccoOrDrugUseOrReferences: 'NONE', contests: 'NONE', gambling: false,
|
||||
gamblingSimulated: 'NONE', gunsOrOtherWeapons: 'NONE', healthOrWellnessTopics: false, horrorOrFearThemes: 'NONE', lootBox: false,
|
||||
matureOrSuggestiveThemes: 'NONE', medicalOrTreatmentInformation: 'NONE', messagingAndChat: false, parentalControls: false,
|
||||
profanityOrCrudeHumor: 'NONE', sexualContentGraphicAndNudity: 'NONE', sexualContentOrNudity: 'NONE', unrestrictedWebAccess: false,
|
||||
userGeneratedContent: false, violenceCartoonOrFantasy: 'NONE', violenceRealistic: 'NONE',
|
||||
violenceRealisticProlongedGraphicOrSadistic: 'NONE', kidsAgeBand: null,
|
||||
};
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const info = config.apple?.info ?? {};
|
||||
const dry = ctx.args.has('dry');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const appInfo = await c.editableAppInfo();
|
||||
const say = (m: string) => log('apple', dry ? `${m} (dry)` : m);
|
||||
|
||||
if (info.categories) {
|
||||
const k = info.categories;
|
||||
const rel = (id?: string) => ({ data: id ? { type: 'appCategories', id } : null });
|
||||
if (!dry) await c.asc('PATCH', `/v1/appInfos/${appInfo.id}`, { data: { type: 'appInfos', id: appInfo.id, relationships: {
|
||||
primaryCategory: rel(k.primary), primarySubcategoryOne: rel(k.primarySubOne), primarySubcategoryTwo: rel(k.primarySubTwo), secondaryCategory: rel(k.secondary) } } });
|
||||
say(`categories: ${[k.primary, k.primarySubOne, k.primarySubTwo].filter(Boolean).join(' / ')}${k.secondary ? `, secondary ${k.secondary}` : ''}`);
|
||||
}
|
||||
|
||||
const attributes = { ...AGE_RATING_NONE, ...(info.ageRating ?? {}) };
|
||||
if (!dry) await c.asc('PATCH', `/v1/ageRatingDeclarations/${appInfo.id}`, { data: { type: 'ageRatingDeclarations', id: appInfo.id, attributes } });
|
||||
say(`age rating declaration: ${Object.entries(info.ageRating ?? {}).map(([q, v]) => `${q}=${v}`).join(', ') || 'all NONE'}`);
|
||||
|
||||
if (info.contentRights) {
|
||||
if (!dry) await c.asc('PATCH', `/v1/apps/${appId}`, { data: { type: 'apps', id: appId, attributes: { contentRightsDeclaration: info.contentRights } } });
|
||||
say(`content rights: ${info.contentRights}`);
|
||||
}
|
||||
|
||||
if (info.free !== false) {
|
||||
const sched = await c.maybe(`/v1/apps/${appId}/appPriceSchedule?include=manualPrices`);
|
||||
if (!sched?.included?.some((x: { type: string }) => x.type === 'appPrices')) {
|
||||
const free = (await c.all(`/v1/apps/${appId}/appPricePoints?filter[territory]=USA&limit=200`)).find(p => Number(p.attributes.customerPrice) === 0);
|
||||
if (!free) throw new Error('no free price point for USA');
|
||||
if (!dry) await c.asc('POST', '/v1/appPriceSchedules', { data: { type: 'appPriceSchedules', relationships: {
|
||||
app: { data: { type: 'apps', id: appId } }, baseTerritory: { data: { type: 'territories', id: 'USA' } },
|
||||
manualPrices: { data: [{ type: 'appPrices', id: '${free}' }] } } },
|
||||
included: [{ type: 'appPrices', id: '${free}', attributes: { startDate: null }, relationships: { appPricePoint: { data: { type: 'appPricePoints', id: free.id } } } }] });
|
||||
say('price: Free (USA base)');
|
||||
} else log('apple', 'price schedule exists');
|
||||
|
||||
const avail = await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`);
|
||||
if (!avail?.data) {
|
||||
const ts: string[] = (await c.all('/v1/territories?limit=200')).map(t => t.id);
|
||||
if (!dry) await c.asc('POST', '/v2/appAvailabilities', { data: { type: 'appAvailabilities', attributes: { availableInNewTerritories: true },
|
||||
relationships: { app: { data: { type: 'apps', id: appId } }, territoryAvailabilities: { data: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}' })) } } },
|
||||
included: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}', attributes: { available: true }, relationships: { territory: { data: { type: 'territories', id: t } } } })) });
|
||||
say(`availability: ${ts.length} territories + new ones`);
|
||||
} else log('apple', 'availability exists');
|
||||
}
|
||||
done('apple', 'appinfo done (App Privacy is UI-only: store-declarations skill)');
|
||||
}
|
||||
89
cli/apple/asc.ts
Normal file
89
cli/apple/asc.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// 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']);
|
||||
|
||||
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) : {};
|
||||
}
|
||||
|
||||
/** 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). */
|
||||
async function uploadAsset(type: string, rel: Record<string, unknown>, file: string): 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 }, 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, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
||||
}
|
||||
26
cli/apple/bundle.ts
Normal file
26
cli/apple/bundle.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Register the bundle id (Certificates, Identifiers & Profiles) through the API. Idempotent.
|
||||
// crt-ship apple bundle [--name "My Game"] [--dry]
|
||||
// The App Store Connect app record itself can NOT be created through the API: do that in the web UI afterwards
|
||||
// (Apps > + > New App, pick this bundle id), see the appstore-first-release skill.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { ascClient } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
|
||||
const c = await ascClient(root, bundleId, config.apple?.appId);
|
||||
const found = (await c.asc('GET', `/v1/bundleIds?filter[identifier]=${encodeURIComponent(bundleId)}`)).data
|
||||
.filter((b: { attributes: { identifier: string } }) => b.attributes.identifier === bundleId);
|
||||
if (found.length) { log('apple', `bundle id ${bundleId} already registered (${found[0].attributes.platform})`); }
|
||||
else if (ctx.args.has('dry')) { log('apple', `bundle id ${bundleId} missing (dry run, not registering)`); return; }
|
||||
else {
|
||||
await c.asc('POST', '/v1/bundleIds', { data: { type: 'bundleIds', attributes: { identifier: bundleId, name: ctx.args.str('name', config.app.name).replace(/[^A-Za-z0-9 ]/g, ' ').trim(), platform: 'IOS' } } });
|
||||
log('apple', `bundle id ${bundleId} registered`);
|
||||
}
|
||||
const apps = (await c.asc('GET', `/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}`)).data;
|
||||
if (apps.length) log('apple', `app record: ${apps[0].attributes.name} (Apple ID ${apps[0].id}); put it in apple.appId`);
|
||||
else log('apple', 'no app record yet: App Store Connect > Apps > + > New App (UI only), then re-run `apple status`');
|
||||
done('apple', 'bundle done');
|
||||
}
|
||||
35
cli/apple/iap-review.ts
Normal file
35
cli/apple/iap-review.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// Upload the App Review screenshot of every in-app purchase (idempotent: a screenshot whose MD5 matches is kept) and
|
||||
// print each product's state. Nothing is submitted.
|
||||
// crt-ship apple iap-review [--dry]
|
||||
// Screenshot per product: products[].reviewScreenshot, else apple.reviewShots/<product id>.(png|jpg).
|
||||
// Size: a real device screenshot size (e.g. 1290 x 2796); other sizes fail with IMAGE_INCORRECT_DIMENSIONS.
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log, warn } from '../lib/log';
|
||||
import { ascClient, md5 } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const defs = new Map((config.products ?? []).map(p => [p.id, p]));
|
||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
|
||||
const sku: string = p.attributes.productId;
|
||||
const def = defs.get(sku);
|
||||
const file = def?.reviewScreenshot ? resolve(def.reviewScreenshot)
|
||||
: ['png', 'jpg', 'jpeg'].map(e => resolve(join(config.apple?.reviewShots ?? 'store/iap-review', `${sku}.${e}`))).find(existsSync);
|
||||
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); continue; }
|
||||
const buf = readFileSync(file);
|
||||
const cur = (await c.maybe(`/v2/inAppPurchases/${p.id}/appStoreReviewScreenshot`))?.data;
|
||||
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && cur.attributes.assetDeliveryState?.state !== 'FAILED') { log('apple', `${sku}: screenshot up to date`); continue; }
|
||||
if (ctx.args.has('dry')) { log('apple', `${sku}: would upload ${file}`); continue; }
|
||||
if (cur) await c.asc('DELETE', `/v1/inAppPurchaseAppStoreReviewScreenshots/${cur.id}`);
|
||||
await c.uploadAsset('inAppPurchaseAppStoreReviewScreenshots', { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: p.id } } }, file);
|
||||
log('apple', `${sku}: screenshot uploaded`);
|
||||
}
|
||||
await Bun.sleep(3000);
|
||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) log('apple', `${p.attributes.productId}: ${p.attributes.state}`);
|
||||
done('apple', 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
|
||||
}
|
||||
81
cli/apple/iap.ts
Normal file
81
cli/apple/iap.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
// In-app purchases on App Store Connect: create missing products, localizations, price schedule (USA base + your
|
||||
// overrides; Apple equalizes every other storefront) and availability (every territory + new ones). Idempotent:
|
||||
// existing products and schedules are left alone (prices of an existing schedule are not changed; do that in the UI).
|
||||
// crt-ship apple iap [--dry] [--only id1,id2]
|
||||
// Then `apple iap-review` for the review screenshots. First IAPs can only be submitted together with an app version,
|
||||
// from the IAP page in the web UI (see the store-iap-setup skill).
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log, step } from '../lib/log';
|
||||
import { appleTerritory, nearestPrices, samePrice } from '../lib/money';
|
||||
import { ascClient, type J } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
|
||||
const only = ctx.args.list('only');
|
||||
const products = need(config.products, 'products').filter(p => !only.length || only.includes(p.id));
|
||||
const dry = ctx.args.has('dry');
|
||||
const c = await ascClient(root, bundleId, config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const langs = new Map(config.languages.map(l => [l.id, l]));
|
||||
const territories: string[] = (await c.all('/v1/territories?limit=200')).map(t => t.id);
|
||||
|
||||
async function pricePoint(iapId: string, territory: string, price: number): Promise<string> {
|
||||
const seen: number[] = [];
|
||||
for (const p of await c.all(`/v2/inAppPurchases/${iapId}/pricePoints?filter[territory]=${territory}&limit=200`)) {
|
||||
if (samePrice(p.attributes.customerPrice, price)) return p.id;
|
||||
seen.push(Number(p.attributes.customerPrice));
|
||||
}
|
||||
throw new Error(`${territory} has no ${price} price point (nearest ${nearestPrices(seen, price).join(', ')})`);
|
||||
}
|
||||
|
||||
for (const [i, p] of products.entries()) {
|
||||
const tag = step(i + 1, products.length, p.id);
|
||||
const found = await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`);
|
||||
let id: string = found.data[0]?.id;
|
||||
if (dry) { log('apple', `${tag}: ${id ? `exists (${found.data[0].attributes.state})` : 'missing'} (dry)`); continue; }
|
||||
if (!id) {
|
||||
const first = Object.values(p.listings)[0]!;
|
||||
id = (await c.asc('POST', '/v2/inAppPurchases', { data: { type: 'inAppPurchases',
|
||||
attributes: { name: p.referenceName ?? first.title, productId: p.id, inAppPurchaseType: p.type === 'consumable' ? 'CONSUMABLE' : 'NON_CONSUMABLE',
|
||||
familySharable: p.familySharable ?? false, ...(p.reviewNote ? { reviewNote: p.reviewNote } : {}) },
|
||||
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
|
||||
log('apple', `${tag}: created`);
|
||||
} else log('apple', `${tag}: exists`);
|
||||
|
||||
const have = new Set((await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`)).map((l: J) => l.attributes.locale));
|
||||
for (const [langId, l] of Object.entries(p.listings)) {
|
||||
const locale = langs.get(langId)?.apple;
|
||||
if (!locale || have.has(locale)) continue;
|
||||
if ([...l.description].length > 55) throw new Error(`${p.id} ${locale}: description over 55 characters (Apple limit)`);
|
||||
await c.asc('POST', '/v1/inAppPurchaseLocalizations', { data: { type: 'inAppPurchaseLocalizations', attributes: { locale, name: l.title, description: l.description },
|
||||
relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id } } } } });
|
||||
log('apple', ` localization ${locale}`);
|
||||
}
|
||||
|
||||
const sched = await c.maybe(`/v2/inAppPurchases/${id}/iapPriceSchedule?include=manualPrices`);
|
||||
if (!sched?.included?.length) {
|
||||
const manual = [{ territory: 'USA', price: p.usd }, ...(p.overrides ?? []).map(o => ({ territory: appleTerritory(o), price: o.price }))];
|
||||
const points = await Promise.all(manual.map(m => pricePoint(id, m.territory, m.price)));
|
||||
await c.asc('POST', '/v1/inAppPurchasePriceSchedules', {
|
||||
data: { type: 'inAppPurchasePriceSchedules', relationships: {
|
||||
inAppPurchase: { data: { type: 'inAppPurchases', id } },
|
||||
baseTerritory: { data: { type: 'territories', id: 'USA' } },
|
||||
manualPrices: { data: manual.map(m => ({ type: 'inAppPurchasePrices', id: '${' + m.territory + '}' })) } } },
|
||||
included: manual.map((m, k) => ({ type: 'inAppPurchasePrices', id: '${' + m.territory + '}', attributes: { startDate: null },
|
||||
relationships: { inAppPurchasePricePoint: { data: { type: 'inAppPurchasePricePoints', id: points[k] } } } })),
|
||||
});
|
||||
log('apple', ` prices ${manual.map(m => `${m.territory} ${m.price}`).join(', ')}`);
|
||||
}
|
||||
|
||||
const avail = await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`);
|
||||
if (!avail?.data) {
|
||||
await c.asc('POST', '/v1/inAppPurchaseAvailabilities', { data: { type: 'inAppPurchaseAvailabilities', attributes: { availableInNewTerritories: true },
|
||||
relationships: { inAppPurchase: { data: { type: 'inAppPurchases', id } },
|
||||
availableTerritories: { data: territories.map(t => ({ type: 'territories', id: t })) } } } });
|
||||
log('apple', ` available in ${territories.length} territories + new ones`);
|
||||
}
|
||||
}
|
||||
done('apple', dry ? 'iap checked (dry run)' : 'iap done (next: apple iap-review for the review screenshots)');
|
||||
}
|
||||
77
cli/apple/listing.ts
Normal file
77
cli/apple/listing.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// App Store version + listing text (idempotent; re-run after editing the App Store listing file).
|
||||
// crt-ship apple listing --version 1.0.0 [--build 3] [--dry]
|
||||
// - the editable iOS version: versionString, copyright, release type MANUAL; with --build that processed build is attached
|
||||
// - appInfoLocalizations: name, subtitle, privacy policy URL per locale
|
||||
// - appStoreVersionLocalizations: description, keywords, promotional text, what's new (not on a first version),
|
||||
// support + marketing URL per locale
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { parseAppStoreListing } from '../lib/copy';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { ascClient, type J } from './asc';
|
||||
|
||||
export function readAppleCopy(ctx: Ctx) {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const only = ctx.args.list('only');
|
||||
const all = parseAppStoreListing(readFileSync(resolve(config.apple?.listing ?? 'store/appstore.md'), 'utf8'));
|
||||
return Object.fromEntries(Object.entries(all).filter(([l]) => !only.length || only.includes(l)));
|
||||
}
|
||||
|
||||
async function upsertLocs(c: Awaited<ReturnType<typeof ascClient>>, list: string, type: string, parentRel: string, parentType: string, parentId: string,
|
||||
want: Record<string, Record<string, string | undefined>>): Promise<void> {
|
||||
const have = new Map((await c.all(`${list}?limit=200`)).map((l: J) => [l.attributes.locale, l] as const));
|
||||
for (const [locale, raw] of Object.entries(want)) {
|
||||
const attributes = Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== undefined));
|
||||
const cur = have.get(locale);
|
||||
if (!cur) {
|
||||
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale, ...attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
|
||||
log('apple', `${type} ${locale}: created`);
|
||||
} else if (Object.entries(attributes).some(([k, v]) => cur.attributes[k] !== v)) {
|
||||
await c.asc('PATCH', `/v1/${type}/${cur.id}`, { data: { type, id: cur.id, attributes } });
|
||||
log('apple', `${type} ${locale}: updated`);
|
||||
} else log('apple', `${type} ${locale}: up to date`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const version = a.get('version');
|
||||
if (!version) throw new Error('usage: apple listing --version 1.0.0 [--build N] [--dry]');
|
||||
const listing = readAppleCopy(ctx);
|
||||
log('apple', `listing: ${Object.keys(listing).length} locales (${Object.keys(listing).join(', ')})`);
|
||||
if (a.has('dry')) return;
|
||||
const app = config.app;
|
||||
const copyright = app.copyright ?? `${new Date().getFullYear()} ${app.name}`;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
|
||||
let v = await c.editableVersion();
|
||||
if (!v) {
|
||||
v = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
|
||||
attributes: { platform: 'IOS', versionString: version, copyright, releaseType: 'MANUAL' },
|
||||
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data;
|
||||
log('apple', `version ${version} created`);
|
||||
} else if (v.attributes.versionString !== version || v.attributes.copyright !== copyright || v.attributes.releaseType !== 'MANUAL') {
|
||||
await c.asc('PATCH', `/v1/appStoreVersions/${v.id}`, { data: { type: 'appStoreVersions', id: v.id, attributes: { versionString: version, copyright, releaseType: 'MANUAL' } } });
|
||||
log('apple', `version ${v.attributes.versionString} -> ${version}, copyright, release MANUAL`);
|
||||
}
|
||||
|
||||
const build = a.get('build');
|
||||
if (build) {
|
||||
const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${build}&filter[preReleaseVersion.version]=${version}&filter[preReleaseVersion.platform]=IOS`))[0];
|
||||
if (!b) throw new Error(`build ${version} (${build}) not found (still uploading? check TestFlight)`);
|
||||
if (b.attributes.processingState !== 'VALID') throw new Error(`build ${build} is ${b.attributes.processingState}; wait until VALID`);
|
||||
await c.asc('PATCH', `/v1/appStoreVersions/${v.id}/relationships/build`, { data: { type: 'builds', id: b.id } });
|
||||
log('apple', `build ${version} (${build}) attached`);
|
||||
}
|
||||
|
||||
const info = await c.editableAppInfo();
|
||||
await upsertLocs(c, `/v1/appInfos/${info.id}/appInfoLocalizations`, 'appInfoLocalizations', 'appInfo', 'appInfos', info.id,
|
||||
Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { name: f.name ?? app.name, subtitle: f.subtitle, privacyPolicyUrl: app.privacyPolicyUrl }])));
|
||||
await upsertLocs(c, `/v1/appStoreVersions/${v.id}/appStoreVersionLocalizations`, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', v.id,
|
||||
Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { description: f.description, keywords: f.keywords, promotionalText: f.promotionalText,
|
||||
whatsNew: f.whatsNew, supportUrl: app.supportUrl, marketingUrl: app.marketingUrl ?? app.website }])));
|
||||
done('apple', 'listing done');
|
||||
}
|
||||
39
cli/apple/review-details.ts
Normal file
39
cli/apple/review-details.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// App Review information on the editable version: contact, demo account (none), notes. Idempotent.
|
||||
// crt-ship apple review-details [--contact-from <Apple ID of another app>] [--dry]
|
||||
// The contact (name, phone, email) is personal data, so it is never in the config: it comes from
|
||||
// .crt-ship/credentials.json "reviewContact", or is copied from another app of the same team with --contact-from.
|
||||
// Notes: apple.info.reviewNotes in crt-ship.config.ts.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { reviewContact } from '../lib/credentials';
|
||||
import { done, log } from '../lib/log';
|
||||
import { ascClient } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const version = await c.editableVersion();
|
||||
if (!version) throw new Error('no editable App Store version (apple listing --version x.y.z creates it)');
|
||||
|
||||
let contact: Record<string, string> | null = null;
|
||||
const from = ctx.args.get('contact-from');
|
||||
if (from) {
|
||||
for (const v of await c.all(`/v1/apps/${from}/appStoreVersions?limit=10`)) {
|
||||
const a = (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreReviewDetail`))?.data?.attributes;
|
||||
if (a?.contactEmail) { contact = { contactFirstName: a.contactFirstName, contactLastName: a.contactLastName, contactPhone: a.contactPhone, contactEmail: a.contactEmail }; break; }
|
||||
}
|
||||
if (!contact) throw new Error(`app ${from} has no review contact on its recent versions`);
|
||||
} else {
|
||||
const rc = reviewContact(root);
|
||||
if (rc) contact = { contactFirstName: rc.firstName, contactLastName: rc.lastName, contactPhone: rc.phone, contactEmail: rc.email };
|
||||
}
|
||||
if (!contact) throw new Error('no review contact: add "reviewContact" to .crt-ship/credentials.json or pass --contact-from <app id>');
|
||||
|
||||
const attributes = { ...contact, demoAccountRequired: false, demoAccountName: null, demoAccountPassword: null, notes: config.apple?.info?.reviewNotes ?? '' };
|
||||
if (ctx.args.has('dry')) { log('apple', `would set review details (contact ${from ? 'copied from ' + from : 'from credentials'}, notes ${attributes.notes.length} chars)`); return; }
|
||||
const cur = (await c.maybe(`/v1/appStoreVersions/${version.id}/appStoreReviewDetail`))?.data;
|
||||
if (cur) await c.asc('PATCH', `/v1/appStoreReviewDetails/${cur.id}`, { data: { type: 'appStoreReviewDetails', id: cur.id, attributes } });
|
||||
else await c.asc('POST', '/v1/appStoreReviewDetails', { data: { type: 'appStoreReviewDetails', attributes,
|
||||
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: version.id } } } } });
|
||||
done('apple', `review details set on ${version.attributes.versionString} (no demo account, notes ${attributes.notes.length} chars)`);
|
||||
}
|
||||
70
cli/apple/screenshots.ts
Normal file
70
cli/apple/screenshots.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
// Store screenshots of every locale on the editable App Store version (idempotent: a set whose files already match
|
||||
// by MD5 and order is left alone, otherwise it is emptied and re-uploaded).
|
||||
// crt-ship apple screenshots [--src store/renders] [--only en-US,tr] [--jobs 4]
|
||||
// Source per language: <renders>/<language id>/ios69/NN.png (6.9", 1320 x 2868 -> APP_IPHONE_67) and
|
||||
// ios65/NN.png (6.5", 1284 x 2778 -> APP_IPHONE_65). Up to 10 per set. Apple processes uploads asynchronously; failed
|
||||
// ones are reported at the end. Long: run in the background with a log file.
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { byAppleLocale, need } from '../lib/ctx';
|
||||
import { done, log, warn } from '../lib/log';
|
||||
import { numberedImages } from '../play/images';
|
||||
import { ascClient, md5, type J } from './asc';
|
||||
|
||||
export const DISPLAY: Record<string, string> = { ios69: 'APP_IPHONE_67', ios65: 'APP_IPHONE_65' };
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const src = resolve(ctx.args.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders');
|
||||
const only = ctx.args.list('only');
|
||||
const jobs = ctx.args.num('jobs', 4);
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const version = await c.editableVersion();
|
||||
if (!version) throw new Error('no editable App Store version (run apple listing --version x.y.z first)');
|
||||
const langOf = byAppleLocale(config.languages);
|
||||
const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`);
|
||||
|
||||
async function syncSet(locId: string, sets: J[], type: string, files: string[], tag: string): Promise<void> {
|
||||
let set = sets.find(s => s.attributes.screenshotDisplayType === type);
|
||||
if (!set) set = (await c.asc('POST', '/v1/appScreenshotSets', { data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: type },
|
||||
relationships: { appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: locId } } } } })).data;
|
||||
const existing = await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots`);
|
||||
const want = files.map(f => md5(readFileSync(f)));
|
||||
const have = existing.map(s => s.attributes.sourceFileChecksum);
|
||||
const ok = existing.every(s => ['COMPLETE', 'UPLOAD_COMPLETE'].includes(s.attributes.assetDeliveryState?.state));
|
||||
if (ok && have.length === want.length && have.every((h, i) => h === want[i])) { log('apple', `${tag}: ${files.length} up to date`); return; }
|
||||
if (ctx.args.has('dry')) { log('apple', `${tag}: would replace ${existing.length} with ${files.length}`); return; }
|
||||
for (const s of existing) await c.asc('DELETE', `/v1/appScreenshots/${s.id}`);
|
||||
for (const f of files) await c.uploadAsset('appScreenshots', { appScreenshotSet: { data: { type: 'appScreenshotSets', id: set.id } } }, f);
|
||||
log('apple', `${tag}: uploaded ${files.length} (removed ${existing.length})`);
|
||||
}
|
||||
|
||||
const tasks: (() => Promise<void>)[] = [];
|
||||
for (const loc of locs) {
|
||||
const locale: string = loc.attributes.locale;
|
||||
if (only.length && !only.includes(locale)) continue;
|
||||
const lang = langOf.get(locale);
|
||||
if (!lang) { warn('apple', `${locale}: no language with apple: "${locale}", skipped`); continue; }
|
||||
tasks.push(async () => {
|
||||
const sets = await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/appScreenshotSets`);
|
||||
for (const [dir, type] of Object.entries(DISPLAY)) {
|
||||
const d = join(src, lang.id, dir);
|
||||
const files = numberedImages(d).filter(f => f.endsWith('.png')).slice(0, 10);
|
||||
if (!existsSync(d) || !files.length) { warn('apple', `${locale}: nothing in ${d}, skipped`); continue; }
|
||||
await syncSet(loc.id, sets, type, files, `${locale} ${type}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
log('apple', `${tasks.length} locales, ${jobs} in parallel`);
|
||||
let next = 0;
|
||||
await Promise.all(Array.from({ length: jobs }, async () => { while (next < tasks.length) await tasks[next++]!(); }));
|
||||
|
||||
let bad = 0;
|
||||
for (const loc of locs) for (const set of await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/appScreenshotSets`))
|
||||
for (const s of await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots`)) {
|
||||
const st = s.attributes.assetDeliveryState;
|
||||
if (st?.state === 'FAILED') { bad++; warn('apple', `${loc.attributes.locale} ${set.attributes.screenshotDisplayType} ${s.attributes.fileName}: ${JSON.stringify(st.errors)}`); }
|
||||
}
|
||||
done('apple', bad ? `${bad} screenshots failed processing (re-run to retry)` : 'screenshots done');
|
||||
}
|
||||
36
cli/apple/status.ts
Normal file
36
cli/apple/status.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// Read-only overview: app record, versions + attached build, recent builds, in-app purchases, review submissions.
|
||||
// crt-ship apple status [--json]
|
||||
// And the one write it offers: cancel a review submission (to re-add first IAPs to it from the web UI):
|
||||
// crt-ship apple status --cancel-submission <id> [--yes]
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { log } from '../lib/log';
|
||||
import { ascClient } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
|
||||
const cancel = ctx.args.get('cancel-submission');
|
||||
if (cancel) {
|
||||
if (!(await confirm(ctx, `Cancel review submission ${cancel}? (the version goes back to "Prepare for Submission")`))) return;
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${cancel}`, { data: { type: 'reviewSubmissions', id: cancel, attributes: { canceled: true } } });
|
||||
log('apple', `review submission ${cancel} canceled; it takes a minute to settle`);
|
||||
return;
|
||||
}
|
||||
|
||||
const app = (await c.asc('GET', `/v1/apps/${appId}`)).data;
|
||||
const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?limit=10&include=build`);
|
||||
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5&include=preReleaseVersion`));
|
||||
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
|
||||
const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&limit=20`);
|
||||
if (ctx.args.has('json')) { console.log(JSON.stringify({ app, versions, builds: builds.data, iaps, subs }, null, 2)); return; }
|
||||
|
||||
console.log(`${app.attributes.name} · ${app.attributes.bundleId} · Apple ID ${appId}`);
|
||||
for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`);
|
||||
const pre = new Map((builds.included ?? []).map((p: { id: string; attributes: { version: string } }) => [p.id, p.attributes.version]));
|
||||
for (const b of builds.data) console.log(` build ${String(pre.get(b.relationships?.preReleaseVersion?.data?.id) ?? '?')} (${b.attributes.version}) ${b.attributes.processingState} ${b.attributes.uploadedDate?.slice(0, 10) ?? ''}`);
|
||||
for (const p of iaps) console.log(` iap ${p.attributes.productId.padEnd(40)} ${p.attributes.inAppPurchaseType} ${p.attributes.state}`);
|
||||
for (const s of subs) console.log(` review submission ${s.id} ${s.attributes.state} ${s.attributes.submittedDate?.slice(0, 10) ?? ''}`);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue