Merge origin/main into local-fonts
This commit is contained in:
commit
cde9424ce3
47 changed files with 2005 additions and 234 deletions
|
|
@ -10,6 +10,7 @@
|
|||
// text, screenshots, config): the days before vs after each change. Read-only on both stores except `setup`.
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { createOnce } from './lib/upsert';
|
||||
import { ascClient, type Asc, type J } from './apple/asc';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import {
|
||||
|
|
@ -102,7 +103,9 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
if (cur) { done(TAG, `apple: ONGOING report request exists (${cur.id})`); return; }
|
||||
const body = { data: { type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, relationships: { app: { data: { type: 'apps', id: appId } } } } };
|
||||
if (dry) { log(TAG, 'would POST /v1/analyticsReportRequests {accessType=ONGOING} (dry)'); return; }
|
||||
await c.asc('POST', '/v1/analyticsReportRequests', body);
|
||||
// one ONGOING request per app: a 409 or an unclear answer is checked by reading it back, never re-sent blindly
|
||||
await createOnce({ what: 'ONGOING analytics report request', tag: TAG, unique: true, find: () => ongoingRequest(c, appId),
|
||||
create: async () => (await c.asc('POST', '/v1/analyticsReportRequests', body)).data });
|
||||
done(TAG, 'apple: ONGOING report request created; the first reports appear after 1-2 days, then daily');
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
// Generic client for every App Store Connect and Google Play operation: the generated rows (apple.gen.ts, play.gen.ts)
|
||||
// plus a few helpers instead of a function per endpoint. Request building is pure (tests cover URLs and parameters);
|
||||
// sending retries 429 / 5xx with backoff (Retry-After honoured) and follows pages.
|
||||
// sending retries 429 (and 5xx / network errors of requests that are safe to send twice: not a POST create) with
|
||||
// backoff (Retry-After honoured) and follows pages.
|
||||
// Auth: the App Store Connect team key JWT from cli/apple/asc.ts, the Play service account token from
|
||||
// cli/lib/google-auth.ts (one scope per Google API). Credentials only come from env or .storebound/.
|
||||
import { AmbiguousWriteError, retrySafe } from '../lib/upsert';
|
||||
import { APPLE_OPS, APPLE_SPEC } from './apple.gen';
|
||||
import { PLAY_APIS, PLAY_OPS } from './play.gen';
|
||||
import type { AppleBody, AppleOp, AppleParams, AppleResponse, ParamValue, PlayBody, PlayOp, PlayParams, PlayResponse } from './types';
|
||||
|
|
@ -207,15 +209,20 @@ export async function send(req: BuiltRequest, auth: Auth, o: SendOptions = {}):
|
|||
const headers: Record<string, string> = { Authorization: await auth(req) };
|
||||
if (req.contentType) headers['Content-Type'] = req.contentType;
|
||||
if (req.accept) headers.Accept = req.accept;
|
||||
// 5xx and network errors are retried only for requests that end the same when sent twice: a POST create without
|
||||
// a clear answer may have been applied, so it is reported (AmbiguousWriteError) and never sent again by itself
|
||||
const safe = retrySafe(req.method, req.url);
|
||||
let r: Response;
|
||||
try {
|
||||
r = await doFetch(req.url, { method: req.method, headers, body: req.body as BodyInit | undefined });
|
||||
} catch (e) {
|
||||
if (!safe) throw new AmbiguousWriteError(`${req.method} ${short(req.url)}: no answer (${(e as Error).message}); not sent again: it may have been applied, check with a GET before you run it again`);
|
||||
if (attempt >= attempts) throw e;
|
||||
o.onRetry?.(`${req.method} ${short(req.url)}: ${(e as Error).message}, retry ${attempt}/${attempts - 1}`);
|
||||
await sleep(backoffMs(attempt));
|
||||
continue;
|
||||
}
|
||||
if (r.status >= 500 && !safe) throw new AmbiguousWriteError(`${req.method} ${short(req.url)} -> ${r.status} ${errorBody(await r.text())}; not sent again: it may have been applied, check with a GET before you run it again`, r.status);
|
||||
if ((r.status === 429 || r.status >= 500) && attempt < attempts) {
|
||||
const wait = backoffMs(attempt, r.headers.get('retry-after'));
|
||||
await r.body?.cancel();
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'appCustomProductPageVersions_updateInstance': 'apple/cpp',
|
||||
'appCustomProductPages_appCustomProductPageVersions_getToManyRelated': 'apple/cpp',
|
||||
'appCustomProductPages_createInstance': 'apple/cpp',
|
||||
'appCustomProductPages_getInstance': 'apple/cpp',
|
||||
'appCustomProductPages_updateInstance': 'apple/cpp',
|
||||
'appEncryptionDeclarations_getCollection': 'apple/encryption',
|
||||
'appEventLocalizations_appEventScreenshots_getToManyRelated': 'apple/events',
|
||||
|
|
@ -25,6 +26,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'appEventScreenshots_deleteInstance': 'apple/events',
|
||||
'appEventScreenshots_updateInstance': 'apple/events',
|
||||
'appEvents_createInstance': 'apple/events',
|
||||
'appEvents_getInstance': 'apple/events',
|
||||
'appEvents_localizations_getToManyRelated': 'apple/events',
|
||||
'appInfos_ageRatingDeclaration_getToOneRelated': 'apple/appinfo validate',
|
||||
'appInfos_appInfoLocalizations_getToManyRelated': 'apple/listing validate',
|
||||
|
|
@ -32,23 +34,20 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'appInfos_updateInstance': 'apple/appinfo',
|
||||
'appPreviewSets_appPreviews_getToManyRelated': 'apple/previews',
|
||||
'appPreviewSets_createInstance': 'apple/previews',
|
||||
'appPreviews_createInstance': 'apple/previews',
|
||||
'appPreviews_deleteInstance': 'apple/previews',
|
||||
'appPreviews_updateInstance': 'apple/previews',
|
||||
'appPriceSchedules_createInstance': 'apple/appinfo',
|
||||
'appScreenshotSets_appScreenshots_getToManyRelated': 'apple/ppo apple/screenshots validate',
|
||||
'appScreenshotSets_createInstance': 'apple/screenshots',
|
||||
'appScreenshots_createInstance': 'apple/screenshots',
|
||||
'appScreenshots_deleteInstance': 'apple/screenshots',
|
||||
'appScreenshots_updateInstance': 'apple/screenshots',
|
||||
'appStoreReviewDetails_createInstance': 'apple/review-details',
|
||||
'appStoreReviewDetails_updateInstance': 'apple/review-details',
|
||||
'appStoreVersionExperimentTreatmentLocalizations_appScreenshotSets_getToManyRelated': 'apple/ppo',
|
||||
'appStoreVersionExperimentTreatmentLocalizations_createInstance': 'lib/ppo',
|
||||
'appStoreVersionExperimentTreatments_appStoreVersionExperimentTreatmentLocalizations_getToManyRelated': 'apple/ppo',
|
||||
'appStoreVersionExperimentTreatments_createInstance': 'lib/ppo',
|
||||
'appStoreVersionExperimentTreatments_getInstance': 'apple/ppo',
|
||||
'appStoreVersionExperimentsV2_appStoreVersionExperimentTreatments_getToManyRelated': 'apple/ppo',
|
||||
'appStoreVersionExperimentsV2_createInstance': 'lib/ppo',
|
||||
'appStoreVersionExperimentsV2_getInstance': 'apple/ppo',
|
||||
'appStoreVersionExperimentsV2_updateInstance': 'lib/ppo',
|
||||
'appStoreVersionLocalizations_appPreviewSets_getToManyRelated': 'apple/previews',
|
||||
'appStoreVersionLocalizations_appScreenshotSets_getToManyRelated': 'apple/screenshots validate',
|
||||
|
|
@ -75,6 +74,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'apps_betaAppReviewDetail_getToOneRelated': 'apple/testflight',
|
||||
'apps_betaFeedbackCrashSubmissions_getToManyRelated': 'health',
|
||||
'apps_betaGroups_getToManyRelated': 'apple/testflight',
|
||||
'apps_buildUploads_getToManyRelated': 'apple/upload',
|
||||
'apps_customerReviews_getToManyRelated': 'reviews',
|
||||
'apps_getCollection': 'apple/asc apple/bundle apps lib/store-apps',
|
||||
'apps_getInstance': 'apple/appinfo apple/status',
|
||||
|
|
@ -98,11 +98,13 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'betaGroups_builds_getToManyRelated': 'apple/testflight',
|
||||
'betaGroups_createInstance': 'lib/testflight',
|
||||
'betaGroups_getCollection': 'apple/testflight',
|
||||
'betaGroups_getInstance': 'apple/testflight',
|
||||
'betaTesterInvitations_createInstance': 'lib/testflight',
|
||||
'betaTesters_createInstance': 'lib/testflight',
|
||||
'betaTesters_getCollection': 'apple/testflight',
|
||||
'buildUploadFiles_createInstance': 'lib/xcode',
|
||||
'buildUploadFiles_updateInstance': 'lib/xcode',
|
||||
'buildUploads_buildUploadFiles_getToManyRelated': 'apple/upload',
|
||||
'buildUploads_createInstance': 'lib/xcode',
|
||||
'buildUploads_getInstance': 'apple/upload',
|
||||
'builds_appEncryptionDeclaration_getToOneRelated': 'validate',
|
||||
|
|
@ -132,6 +134,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'inAppPurchaseOfferCodeOneTimeUseCodes_values_getToOneRelated': 'apple/offer-codes',
|
||||
'inAppPurchaseOfferCodes_createInstance': 'apple/offer-codes',
|
||||
'inAppPurchaseOfferCodes_customCodes_getToManyRelated': 'apple/offer-codes',
|
||||
'inAppPurchaseOfferCodes_getInstance': 'apple/offer-codes',
|
||||
'inAppPurchaseOfferCodes_oneTimeUseCodes_getToManyRelated': 'apple/offer-codes',
|
||||
'inAppPurchasePricePoints_equalizations_getToManyRelated': 'apple/offer-codes',
|
||||
'inAppPurchasePriceSchedules_automaticPrices_getToManyRelated': 'prices',
|
||||
|
|
@ -141,6 +144,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'inAppPurchaseVersions_createInstance': 'lib/review-submit',
|
||||
'inAppPurchasesV2_appStoreReviewScreenshot_getToOneRelated': 'apple/iap-review validate',
|
||||
'inAppPurchasesV2_createInstance': 'apple/iap',
|
||||
'inAppPurchasesV2_getInstance': 'apple/iap',
|
||||
'inAppPurchasesV2_iapPriceSchedule_getToOneRelated': 'apple/iap apple/iap-review catalog',
|
||||
'inAppPurchasesV2_inAppPurchaseAvailability_getToOneRelated': 'apple/iap apple/iap-review',
|
||||
'inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelated': 'apple/iap apple/iap-review catalog',
|
||||
|
|
@ -153,17 +157,20 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'profiles_getInstance': 'apple/signing',
|
||||
'promotedPurchases_createInstance': 'lib/offers',
|
||||
'promotedPurchases_updateInstance': 'lib/offers',
|
||||
'reviewSubmissionItems_createInstance': 'apple/events lib/cpp-events lib/review-submit',
|
||||
'reviewSubmissions_createInstance': 'apple/cpp apple/events lib/review-submit',
|
||||
'reviewSubmissions_getCollection': 'apple/cpp apple/events apple/iap-submit apple/status',
|
||||
'reviewSubmissions_items_getToManyRelated': 'apple/iap-submit',
|
||||
'reviewSubmissionItems_createInstance': 'apple/submission lib/cpp-events lib/review-submit',
|
||||
'reviewSubmissions_createInstance': 'apple/cpp apple/events apple/submission lib/review-submit',
|
||||
'reviewSubmissions_getCollection': 'apple/events apple/iap-submit apple/status apple/submission',
|
||||
'reviewSubmissions_getInstance': 'apple/submission',
|
||||
'reviewSubmissions_items_getToManyRelated': 'apple/iap-submit apple/submission',
|
||||
'reviewSubmissions_updateInstance': 'apple/cpp apple/events apple/iap-submit apple/status lib/review-submit',
|
||||
'salesReports_getCollection': 'lib/reports',
|
||||
'subscriptionAppStoreReviewScreenshots_createInstance': 'apple/subscriptions',
|
||||
'subscriptionAppStoreReviewScreenshots_deleteInstance': 'apple/subscriptions',
|
||||
'subscriptionAppStoreReviewScreenshots_updateInstance': 'apple/subscriptions',
|
||||
'subscriptionAvailabilities_createInstance': 'apple/subscriptions',
|
||||
'subscriptionGroupLocalizations_createInstance': 'apple/subscriptions',
|
||||
'subscriptionGroups_createInstance': 'apple/subscriptions',
|
||||
'subscriptionGroups_getInstance': 'apple/subscriptions',
|
||||
'subscriptionGroups_subscriptionGroupLocalizations_getToManyRelated': 'apple/subscriptions validate',
|
||||
'subscriptionGroups_subscriptions_getToManyRelated': 'apple/iap-submit apple/promoted apple/subscriptions apple/win-back catalog prices validate',
|
||||
'subscriptionGroups_versions_getToManyRelated': 'apple/iap-submit',
|
||||
|
|
@ -171,11 +178,13 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'subscriptionOfferCodeCustomCodes_createInstance': 'apple/subscriptions',
|
||||
'subscriptionOfferCodes_createInstance': 'apple/subscriptions',
|
||||
'subscriptionOfferCodes_customCodes_getToManyRelated': 'apple/subscriptions',
|
||||
'subscriptionOfferCodes_getInstance': 'apple/subscriptions',
|
||||
'subscriptionPricePoints_equalizations_getToManyRelated': 'apple/subscriptions apple/win-back',
|
||||
'subscriptionPromotionalOffers_createInstance': 'apple/subscriptions',
|
||||
'subscriptionVersions_createInstance': 'lib/review-submit',
|
||||
'subscriptions_appStoreReviewScreenshot_getToOneRelated': 'apple/subscriptions validate',
|
||||
'subscriptions_createInstance': 'apple/subscriptions',
|
||||
'subscriptions_getInstance': 'apple/subscriptions',
|
||||
'subscriptions_introductoryOffers_getToManyRelated': 'apple/subscriptions catalog',
|
||||
'subscriptions_offerCodes_getToManyRelated': 'apple/subscriptions catalog',
|
||||
'subscriptions_pricePoints_getToManyRelated': 'apple/subscriptions apple/win-back',
|
||||
|
|
@ -205,7 +214,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'androidpublisher.edits.insert': 'apps play/client validate',
|
||||
'androidpublisher.edits.listings.list': 'play/listing play/status validate',
|
||||
'androidpublisher.edits.listings.update': 'play/listing',
|
||||
'androidpublisher.edits.tracks.get': 'play/rollout play/upload',
|
||||
'androidpublisher.edits.tracks.get': 'play/release play/rollout play/upload',
|
||||
'androidpublisher.edits.tracks.list': 'play/next-version-code play/status validate',
|
||||
'androidpublisher.edits.tracks.update': 'play/release play/rollout play/upload',
|
||||
'androidpublisher.edits.validate': 'play/client',
|
||||
|
|
@ -216,11 +225,9 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'androidpublisher.monetization.onetimeproducts.patch': 'play/products prices',
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.batchUpdateStates': 'play/products',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.activate': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.activate': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.create': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.list': 'catalog play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.create': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.get': 'prices',
|
||||
'androidpublisher.monetization.subscriptions.get': 'play/subscriptions prices',
|
||||
'androidpublisher.monetization.subscriptions.list': 'catalog play/subscriptions validate',
|
||||
'androidpublisher.monetization.subscriptions.patch': 'play/subscriptions',
|
||||
'androidpublisher.reviews.list': 'reviews',
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ import type { Ctx } from '../lib/ctx';
|
|||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { textTable } from '../lib/table';
|
||||
import { createOnce } from '../lib/upsert';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
|
||||
const TAG = 'adhoc';
|
||||
|
|
@ -86,8 +87,11 @@ async function register(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
|
|||
let failed = 0;
|
||||
for (const d of plan.add) {
|
||||
try {
|
||||
await api.asc('POST', '/v1/devices', deviceCreateReq(d));
|
||||
log(TAG, `registered ${d.name} (${maskUdid(d.udid)})`);
|
||||
// a UDID is registered once per team: a 409 or an unclear answer is checked by a direct lookup, never re-sent blindly
|
||||
const r = await createOnce({ what: `device ${d.name} (${maskUdid(d.udid)})`, tag: TAG, unique: true,
|
||||
find: async () => (await api.all(`/v1/devices?filter[udid]=${encodeURIComponent(d.udid)}&limit=10`)).find((x: J) => String(x.attributes?.udid ?? '').toLowerCase() === d.udid.toLowerCase()) ?? null,
|
||||
create: async () => (await api.asc('POST', '/v1/devices', deviceCreateReq(d))).data });
|
||||
log(TAG, `${r.created ? 'registered' : 'already registered:'} ${d.name} (${maskUdid(d.udid)})`);
|
||||
} catch (e) {
|
||||
failed++;
|
||||
warn(TAG, `${d.name} (${maskUdid(d.udid)}) not registered: ${scrubUdids((e as Error).message, udids)}`);
|
||||
|
|
@ -110,13 +114,16 @@ async function profile(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
|
|||
const devices = profileDevices(await registered(api, 'IOS'));
|
||||
if (!devices.length) throw new Error('no enabled iOS devices: register them first (storebound apple adhoc register)');
|
||||
const want = devices.map(d => d.id);
|
||||
const existing = (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).filter((p: J) => p.attributes?.profileType === 'IOS_APP_ADHOC' && p.attributes?.name === name);
|
||||
// the profile and the dated ones an earlier run made when it had to replace it ("<name> YYYY-MM-DD"), newest first
|
||||
const dated = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}( \\d{4}-\\d{2}-\\d{2}( \\d{2}-\\d{2})?)?$`);
|
||||
const existing = (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).filter((p: J) => p.attributes?.profileType === 'IOS_APP_ADHOC' && dated.test(p.attributes?.name ?? ''))
|
||||
.sort((x: J, y: J) => String(y.attributes.name).localeCompare(String(x.attributes.name)));
|
||||
let newName = name;
|
||||
for (const p of existing) {
|
||||
const has = (await api.all(`/v1/profiles/${p.id}/devices?limit=200`)).map((d: J) => d.id as string);
|
||||
const st = profileCurrent(p.attributes.profileState, has, want);
|
||||
if (st.current) { done(TAG, `profile "${name}" is current (${has.length} devices, expires ${String(p.attributes.expirationDate ?? '').slice(0, 10)})`); return; }
|
||||
log(TAG, `profile "${name}" is ${p.attributes.profileState === 'ACTIVE' ? `missing ${st.missing} device(s)` : 'invalid'}; profiles cannot be changed, so a new one is created`);
|
||||
if (st.current) { done(TAG, `profile "${p.attributes.name}" is current (${has.length} devices, expires ${String(p.attributes.expirationDate ?? '').slice(0, 10)})`); return; }
|
||||
log(TAG, `profile "${p.attributes.name}" is ${p.attributes.profileState === 'ACTIVE' ? `missing ${st.missing} device(s)` : 'invalid'}; profiles cannot be changed, so a new one is created`);
|
||||
newName = `${name} ${new Date().toISOString().slice(0, 10)}`;
|
||||
}
|
||||
const classes = new Map<string, number>();
|
||||
|
|
@ -124,7 +131,10 @@ async function profile(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
|
|||
log(TAG, `plan: create IOS_APP_ADHOC "${newName}" for ${bundleId}: ${devices.length} devices (${[...classes].map(([k, v]) => `${v} ${k}`).join(', ')}), ${certs.length} distribution certificate(s)`);
|
||||
if (ctx.args.has('dry')) { log(TAG, 'dry run: nothing created'); return; }
|
||||
if (!(await confirm(ctx, `Create the ad-hoc provisioning profile "${newName}"?`))) { log(TAG, 'not confirmed, nothing created'); return; }
|
||||
const res = (await api.asc('POST', '/v1/profiles', profileCreateReq(newName, bid.id, certs, want))).data;
|
||||
if (existing.some((p: J) => p.attributes.name === newName)) newName = `${name} ${new Date().toISOString().slice(0, 16).replace('T', ' ').replace(':', '-')}`;
|
||||
const res = (await createOnce<J>({ what: `profile "${newName}"`, tag: TAG,
|
||||
find: async () => (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).find((p: J) => p.attributes?.name === newName) ?? null,
|
||||
create: async () => (await api.asc('POST', '/v1/profiles', profileCreateReq(newName, bid.id, certs, want))).data })).value;
|
||||
const content = res?.attributes?.profileContent as string | undefined;
|
||||
if (content) {
|
||||
const out = resolve(`build/adhoc/${newName.replace(/[^\w.-]+/g, '_')}.mobileprovision`);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { createHash, createPrivateKey, sign } from 'node:crypto';
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { ascKey } from '../lib/credentials';
|
||||
import { errorBody } from '../lib/http';
|
||||
import { AmbiguousWriteError, retrySafe } from '../lib/upsert';
|
||||
|
||||
const b64 = (b: Buffer | string): string => Buffer.from(b).toString('base64url');
|
||||
export const md5 = (b: Buffer | Uint8Array): string => createHash('md5').update(b).digest('hex');
|
||||
|
|
@ -24,6 +25,14 @@ export function setUpToDate(existing: { checksum?: string | null; state?: string
|
|||
return existing.length === want.length && existing.every((e, i) => e.checksum === want[i] && DELIVERED.includes(e.state ?? ''));
|
||||
}
|
||||
|
||||
/** How many leading assets of a set already hold the wanted files (same MD5 at the same position, delivered): those
|
||||
* stay when the set is synced. Pure. */
|
||||
export function keptPrefix(existing: { checksum?: string | null; state?: string | null }[], want: string[]): number {
|
||||
let k = 0;
|
||||
while (k < existing.length && k < want.length && existing[k]!.checksum === want[k] && DELIVERED.includes(existing[k]!.state ?? '')) k++;
|
||||
return k;
|
||||
}
|
||||
|
||||
/** Cached ES256 token getter for the team API key (env or .storebound/): valid 18 minutes, renewed after 15. Shared by
|
||||
* ascClient and the generic `storebound api apple` client (cli/api/client.ts). */
|
||||
export function ascJwt(root: string): { jwt: () => string; keyId: string } {
|
||||
|
|
@ -45,12 +54,28 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
const k = ascJwt(root);
|
||||
const jwt = k.jwt;
|
||||
|
||||
/**
|
||||
* One API request. 429 is retried (the request was refused, not applied). 5xx and network errors are retried only
|
||||
* for requests that end the same when sent twice (retrySafe: GET, PATCH, DELETE, relationship adds, the "create or
|
||||
* replace" singletons); a POST create then throws AmbiguousWriteError instead, so callers look before they create
|
||||
* again (cli/lib/upsert.ts). A DELETE answered 404 after a retry was applied by the first attempt.
|
||||
*/
|
||||
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 safe = retrySafe(method, path);
|
||||
let r: Response;
|
||||
try {
|
||||
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,
|
||||
});
|
||||
} catch (e) {
|
||||
if (safe && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
|
||||
if (!safe) throw new AmbiguousWriteError(`${method} ${path} -> no answer (${(e as Error).message})`);
|
||||
throw e;
|
||||
}
|
||||
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.status === 429 || (r.status >= 500 && safe)) && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
|
||||
if (r.status >= 500 && !safe) throw new AmbiguousWriteError(`${method} ${path} -> ${r.status} ${errorBody(t)}`, r.status);
|
||||
if (r.status === 404 && method === 'DELETE' && attempt > 1) return {};
|
||||
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t)}`);
|
||||
return t ? JSON.parse(t) : {};
|
||||
}
|
||||
|
|
@ -127,5 +152,38 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
return res.id;
|
||||
}
|
||||
|
||||
return { asc, all, maybe, getAs, bytes, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
||||
/**
|
||||
* Makes a screenshot or preview set hold exactly `files`, in this order, touching as little as possible: the leading
|
||||
* assets that already match stay, everything after them is deleted, the rest is uploaded in order. A crash midway
|
||||
* leaves a prefix of the wanted files (plus maybe one half-uploaded asset), which the next run keeps or removes, so
|
||||
* re-runs converge and never duplicate. A reservation with an unknown outcome is cleaned up (the set is read again and
|
||||
* any asset this run does not know is deleted) and sent once more. At the end the order is read back and, if Apple
|
||||
* shows another one, set through the set's relationship.
|
||||
*/
|
||||
async function syncAssets(o: { set: { type: 'appScreenshotSets' | 'appPreviewSets'; id: string }; existing: J[]; files: string[]; want: string[];
|
||||
state: (x: J) => string | undefined; attrs?: (file: string) => Record<string, unknown>; onUpload?: (file: string) => void }): Promise<{ uploaded: number; removed: number; kept: number }> {
|
||||
const asset = o.set.type === 'appScreenshotSets' ? 'appScreenshots' : 'appPreviews';
|
||||
const rel = { [o.set.type === 'appScreenshotSets' ? 'appScreenshotSet' : 'appPreviewSet']: { data: { type: o.set.type, id: o.set.id } } };
|
||||
const k = keptPrefix(o.existing.map(x => ({ checksum: x.attributes?.sourceFileChecksum, state: o.state(x) })), o.want);
|
||||
const ids: string[] = o.existing.slice(0, k).map(x => x.id);
|
||||
const extra = o.existing.slice(k);
|
||||
for (const x of extra) await asc('DELETE', `/v1/${asset}/${x.id}`);
|
||||
for (const f of o.files.slice(k)) {
|
||||
o.onUpload?.(f);
|
||||
try { ids.push(await uploadAsset(asset, rel, f, o.attrs?.(f) ?? {})); } catch (e) {
|
||||
if (!(e as { ambiguous?: boolean }).ambiguous) throw e;
|
||||
// the reservation may exist: remove whatever this run does not know, then upload this file once more
|
||||
for (const x of await all(`/v1/${o.set.type}/${o.set.id}/${asset}?limit=50`)) if (!ids.includes(x.id)) await asc('DELETE', `/v1/${asset}/${x.id}`);
|
||||
ids.push(await uploadAsset(asset, rel, f, o.attrs?.(f) ?? {}));
|
||||
}
|
||||
}
|
||||
if (o.files.length > k) {
|
||||
const now = (await all(`/v1/${o.set.type}/${o.set.id}/${asset}?limit=50`)).map(x => x.id as string);
|
||||
if (now.join() !== ids.join() && ids.every(id => now.includes(id)))
|
||||
await asc('PATCH', `/v1/${o.set.type}/${o.set.id}/relationships/${asset}`, { data: ids.map(id => ({ type: asset, id })) });
|
||||
}
|
||||
return { uploaded: o.files.length - k, removed: extra.length, kept: k };
|
||||
}
|
||||
|
||||
return { asc, all, maybe, getAs, bytes, app, editableVersion, editableAppInfo, uploadAsset, syncAssets, keyId: k.keyId };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { createOnce } from '../lib/upsert';
|
||||
import { ascClient } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
|
|
@ -16,8 +17,11 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
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`);
|
||||
// identifiers are unique per team: a 409 (or an unclear answer) is checked by a direct lookup, never re-sent blindly
|
||||
const r = await createOnce({ what: `bundle id ${bundleId}`, tag: 'apple', unique: true,
|
||||
find: async () => (await c.asc('GET', `/v1/bundleIds?filter[identifier]=${encodeURIComponent(bundleId)}`)).data?.find((b: { attributes: { identifier: string } }) => b.attributes.identifier === bundleId) ?? null,
|
||||
create: async () => (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' } } })).data });
|
||||
log('apple', `bundle id ${bundleId} ${r.created ? 'registered' : 'already 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`);
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ import { numberedImages } from '../play/images';
|
|||
import { variantRoot } from '../shots/lib';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute, one, type Req } from './jsonapi';
|
||||
import { addItem, draftSubmission, findDraft } from './submission';
|
||||
import { findOrCreate, getById } from '../lib/upsert';
|
||||
import { displaySets, syncScreenshotSet } from './screenshots';
|
||||
|
||||
const TAG = 'cpp';
|
||||
|
|
@ -35,11 +37,6 @@ async function pagesOf(c: Asc, appId: string): Promise<Page[]> {
|
|||
return out;
|
||||
}
|
||||
|
||||
/** A draft review submission of the app (READY_FOR_REVIEW), or the request that creates one. */
|
||||
async function draftSubmission(c: Asc, appId: string): Promise<string | null> {
|
||||
return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null;
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
|
|
@ -82,7 +79,18 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
if (pages.length + reqs.filter(r => r.path === '/v1/appCustomProductPages').length > CPP_LIMITS.pages) throw new Error(`more than ${CPP_LIMITS.pages} custom product pages`);
|
||||
if (a.has('json')) printJson({ dryRun: dry, requests: reqs.map(r => describeReq(r)) });
|
||||
if (!reqs.length) { done(TAG, 'custom product pages up to date'); return; }
|
||||
await execute(c.asc, reqs, { dry, tag: TAG });
|
||||
if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, `dry run: ${reqs.length} change(s)`); return; }
|
||||
// page names are not known to be unique on Apple's side: each new page is looked up right before it is created
|
||||
// (fresh list, then the journal of recent creates for the list lag) and never sent twice
|
||||
for (const r of reqs) {
|
||||
if (r.path !== '/v1/appCustomProductPages') { await execute(c.asc, [r], { dry, tag: TAG }); continue; }
|
||||
const name = (r.body as J).data.attributes.name as string;
|
||||
const made = await findOrCreate<J>({ what: `custom product page "${name}"`, tag: TAG,
|
||||
find: async () => (await c.all(`/v1/apps/${appId}/appCustomProductPages?limit=200`)).find((p: J) => p.attributes.name === name) ?? null,
|
||||
journal: { root, key: `apple:${appId}:cpp:${name}`, byId: id => getById(c.asc, `/v1/appCustomProductPages/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', r.path, r.body)).data });
|
||||
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
|
||||
}
|
||||
done(TAG, dry ? `dry run: ${reqs.length} change(s)` : `${reqs.length} change(s); next: storebound apple cpp upload --name "<page>"`);
|
||||
return;
|
||||
}
|
||||
|
|
@ -117,13 +125,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const { def, page } = pick();
|
||||
if (!page?.version) throw new Error(`"${def.name}" is not on App Store Connect yet (storebound apple cpp create)`);
|
||||
if (!['PREPARE_FOR_SUBMISSION', 'REJECTED'].includes(page.version.state)) { done(TAG, `"${def.name}": version is ${page.version.state}, nothing to submit`); return; }
|
||||
const draft = await draftSubmission(c, appId);
|
||||
const draft = await findDraft(c, appId);
|
||||
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
|
||||
const item = reviewItemReq(draft ?? '${submission}', 'appCustomProductPageVersion', page.version.id, `custom product page "${def.name}"`);
|
||||
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), item, { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `Send custom product page "${def.name}" to App Review now?`))) return;
|
||||
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
|
||||
await c.asc('POST', item.path, reviewItemReq(sid, 'appCustomProductPageVersion', page.version.id, '').body);
|
||||
const sid = draft ?? await draftSubmission(c, appId, root, TAG);
|
||||
await addItem(c, sid, 'appCustomProductPageVersion', page.version.id, `custom product page "${def.name}"`, TAG);
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
|
||||
done(TAG, `"${def.name}" submitted (review submission ${sid}); after approval: storebound apple cpp visible --name "${def.name}"`);
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ import { textTable } from '../lib/table';
|
|||
import { imageInfo } from '../shots/spec';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, one, type Req } from './jsonapi';
|
||||
import { addItem, draftSubmission } from './submission';
|
||||
import { findOrCreate, getById } from '../lib/upsert';
|
||||
|
||||
const TAG = 'events';
|
||||
const USAGE = 'usage: storebound apple events list | create [--name n] | upload --name n | submit --name n';
|
||||
|
|
@ -69,11 +71,21 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
done(TAG, 'dry run: nothing changed');
|
||||
return;
|
||||
}
|
||||
const out = await execute(c.asc, reqs, { dry: false, tag: TAG }) as J[];
|
||||
for (const x of created) {
|
||||
const id = out[x.index].data.id as string;
|
||||
// reference names are not known to be unique on Apple's side: each new event is looked up right before it is
|
||||
// created (fresh list, then the journal of recent creates for the list lag) and never sent twice
|
||||
for (const [i, r] of reqs.entries()) {
|
||||
const x = created.find(e => e.index === i);
|
||||
if (!x) { await execute(c.asc, [r], { dry: false, tag: TAG }); continue; }
|
||||
const name = x.def.referenceName;
|
||||
const made = await findOrCreate<J>({ what: `in-app event "${name}"`, tag: TAG,
|
||||
find: async () => (await c.all(`/v1/apps/${appId}/appEvents?limit=200`)).find((e: J) => e.attributes.referenceName === name) ?? null,
|
||||
journal: { root, key: `apple:${appId}:event:${name}`, byId: id => getById(c.asc, `/v1/appEvents/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', r.path, r.body)).data });
|
||||
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
|
||||
const id = made.value.id as string;
|
||||
const want = Object.entries(x.def.listings).flatMap(([lang, t]) => { const locale = localeOf(lang); return locale ? [{ locale, ...t }] : []; });
|
||||
await execute(c.asc, planEventLocales(id, [], want), { dry: false, tag: TAG });
|
||||
const have = made.created ? [] : (await c.all(`/v1/appEvents/${id}/localizations?limit=200`)).map((l: J) => ({ id: l.id, ...l.attributes }));
|
||||
await execute(c.asc, planEventLocales(id, have, want), { dry: false, tag: TAG });
|
||||
}
|
||||
done(TAG, 'in-app events created / updated; next: storebound apple events upload --name "<event>"');
|
||||
return;
|
||||
|
|
@ -96,7 +108,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const info = imageInfo(readFileSync(file));
|
||||
const problems = checkEventMedia(kind, info.w, info.h, info.format);
|
||||
if (problems.length) throw new Error(`${file}: ${problems.join('; ')}`);
|
||||
if (have.some((s: J) => s.attributes.appEventAssetType === kind && s.attributes.fileSize === info.bytes)) { log(TAG, `${loc.attributes.locale} ${kind}: up to date`); continue; }
|
||||
if (have.some((s: J) => s.attributes.appEventAssetType === kind && s.attributes.fileSize === info.bytes && ['COMPLETE', 'UPLOAD_COMPLETE'].includes(s.attributes.assetDeliveryState?.state ?? 'COMPLETE'))) { log(TAG, `${loc.attributes.locale} ${kind}: up to date`); continue; }
|
||||
if (dry) { log(TAG, `${loc.attributes.locale} ${kind}: would upload ${file} (${info.w}x${info.h})`); n++; continue; }
|
||||
for (const s of have.filter((x: J) => x.attributes.appEventAssetType === kind)) await c.asc('DELETE', `/v1/appEventScreenshots/${s.id}`);
|
||||
await c.uploadAsset('appEventScreenshots', { appEventLocalization: { data: { type: 'appEventLocalizations', id: loc.id } } }, file, { appEventAssetType: kind });
|
||||
|
|
@ -116,8 +128,8 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
|
||||
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), reviewItemReq(draft ?? '${submission}', 'appEvent', ev.id, `in-app event "${def.referenceName}"`), { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `Send in-app event "${def.referenceName}" to App Review? Once approved it is published on ${def.schedule.publishStart} by its schedule.`))) return;
|
||||
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
|
||||
await c.asc('POST', '/v1/reviewSubmissionItems', reviewItemReq(sid, 'appEvent', ev.id, '').body);
|
||||
const sid = draft ?? await draftSubmission(c, appId, root, TAG);
|
||||
await addItem(c, sid, 'appEvent', ev.id, `in-app event "${def.referenceName}"`, TAG);
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
|
||||
done(TAG, `"${def.referenceName}" submitted (review submission ${sid})`);
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import { allSubscriptions } from '../lib/subscriptions';
|
|||
import { bindIds, latestVersion, newVersionReq, type PIap, planIapSubmission, type PSub, type SubmitState, versionsOf } from '../lib/review-submit';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
import { addItem, draftSubmission } from './submission';
|
||||
|
||||
const TAG = 'iap-submit';
|
||||
|
||||
|
|
@ -95,10 +96,18 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
}
|
||||
const what = `${plan.items.length} item(s)${plan.appVersion ? `, including app version ${plan.appVersion.versionString}` : ''}`;
|
||||
if (!(await confirm(ctx, `Add ${what} to ${state.draft ? 'the draft' : 'a new draft'} review submission?`))) return;
|
||||
let sid = state.draft?.id;
|
||||
// the draft is reused (or created once); the plan left out items already in it (readSubmitState read them), and an
|
||||
// item the store says is in there already (409) is not added twice (cli/apple/submission.ts)
|
||||
const sid = state.draft?.id ?? await draftSubmission(c, appId, root, TAG);
|
||||
for (const r of prepare) {
|
||||
const out = await c.asc(r.method, r.path, bindIds(r, { submission: sid }).body);
|
||||
if (r.path === '/v1/reviewSubmissions') sid = out.data.id;
|
||||
if (r.path === '/v1/reviewSubmissions') continue;
|
||||
if (r.path === '/v1/reviewSubmissionItems') {
|
||||
const rels = (r.body as J).data.relationships as Record<string, { data: { id: string } }>;
|
||||
const kind = Object.keys(rels).find(k => k !== 'reviewSubmission')!;
|
||||
if (await addItem(c, sid, kind, rels[kind]!.data.id, r.note ?? kind, TAG, { checked: true })) log(TAG, `${describeReq(bindIds(r, { submission: sid }))}: done`);
|
||||
continue;
|
||||
}
|
||||
await c.asc(r.method, r.path, bindIds(r, { submission: sid }).body);
|
||||
log(TAG, `${describeReq(bindIds(r, { submission: sid }))}: done`);
|
||||
}
|
||||
if (a.has('no-submit')) { done(TAG, `draft review submission ${sid} ready: press "Submit for Review" in App Store Connect (Apps > Distribution > App Review)`); return; }
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { dryPlan, type PlanRow } from '../lib/dry';
|
|||
import { done, log, step } from '../lib/log';
|
||||
import { LAG_HINT, reportMissing } from '../lib/store-lag';
|
||||
import { appleTerritory, nearestPrices, samePrice } from '../lib/money';
|
||||
import { createOnce, findOrCreate, getById } from '../lib/upsert';
|
||||
import { ascClient, type J } from './asc';
|
||||
|
||||
/** Product type -> InAppPurchaseType (POST /v2/inAppPurchases). */
|
||||
|
|
@ -44,26 +45,31 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const created: string[] = [];
|
||||
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) { rows.push(await planProduct(p, id, found.data[0]?.attributes?.state)); continue; }
|
||||
if (!id) {
|
||||
const first = Object.values(p.listings)[0]!;
|
||||
id = (await c.asc('POST', '/v2/inAppPurchases', { data: { type: 'inAppPurchases',
|
||||
const lookup = async (): Promise<J | null> => (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`)).data
|
||||
?.find((x: J) => x.attributes?.productId === p.id) ?? null;
|
||||
if (dry) { const f = await lookup(); rows.push(await planProduct(p, f?.id, f?.attributes?.state)); continue; }
|
||||
// product ids are unique per app: a 409 finds the existing one; the journal covers the list lag after a create
|
||||
const first = Object.values(p.listings)[0]!;
|
||||
const made = await findOrCreate<J>({ what: `in-app purchase ${p.id}`, tag: 'apple', unique: true, find: lookup,
|
||||
journal: { root, key: `apple:${bundleId}:iap:${p.id}`, byId: id => getById(c.asc, `/v2/inAppPurchases/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', '/v2/inAppPurchases', { data: { type: 'inAppPurchases',
|
||||
attributes: { name: p.referenceName ?? first.title, productId: p.id, inAppPurchaseType: APPLE_IAP_TYPE[p.type],
|
||||
familySharable: p.familySharable ?? false, ...(p.reviewNote ? { reviewNote: p.reviewNote } : {}) },
|
||||
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
|
||||
created.push(p.id);
|
||||
log('apple', `${tag}: created`);
|
||||
} else log('apple', `${tag}: exists`);
|
||||
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data });
|
||||
const id: string = made.value.id;
|
||||
if (made.created) created.push(p.id);
|
||||
log('apple', `${tag}: ${made.created ? 'created' : 'exists'}`);
|
||||
|
||||
const have = new Set((await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`)).map((l: J) => l.attributes.locale));
|
||||
const locsOf = async () => await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`);
|
||||
const have = new Set((await locsOf()).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 > APPLE_IAP_LIMITS.description) throw new Error(`${p.id} ${locale}: description over ${APPLE_IAP_LIMITS.description} 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 } } } } });
|
||||
await createOnce({ what: `${p.id} localization ${locale}`, tag: 'apple', unique: true,
|
||||
find: async () => (await locsOf()).find((x: J) => x.attributes.locale === locale) ?? null,
|
||||
create: async () => (await c.asc('POST', '/v1/inAppPurchaseLocalizations', { data: { type: 'inAppPurchaseLocalizations', attributes: { locale, name: l.title, description: l.description },
|
||||
relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id } } } } })).data });
|
||||
log('apple', ` localization ${locale}`);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
// JSON:API request builders for App Store Connect. Pure: commands build `Req`s, print them on --dry and send them
|
||||
// with the client otherwise. Request / response format: https://developer.apple.com/documentation/appstoreconnectapi
|
||||
import { log } from '../lib/log';
|
||||
import { log, warn } from '../lib/log';
|
||||
import { isAmbiguous, isConflict } from '../lib/upsert';
|
||||
|
||||
export interface Req { method: 'GET' | 'POST' | 'PATCH' | 'DELETE'; path: string; body?: unknown; note?: string }
|
||||
|
||||
|
|
@ -16,13 +17,23 @@ export function describeReq(r: Req, hide: string[] = ['email', 'demoAccountPassw
|
|||
return `${r.method} ${r.path}${keys.length ? ` {${keys.join(', ')}}` : ''}${r.note ? ` # ${r.note}` : ''}`;
|
||||
}
|
||||
|
||||
/** Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). */
|
||||
/**
|
||||
* Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). The plans come
|
||||
* from a fresh read of the store, so a create the store refuses as a duplicate (409 already exists) means an earlier
|
||||
* run made it: it is logged and skipped (its slot in the result is null), never sent again. A create with an unknown
|
||||
* outcome (timeout, 5xx) stops the run without a retry: running the command again reads the store and plans only
|
||||
* what is still missing.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export async function execute(asc: (m: string, p: string, b?: unknown) => Promise<any>, reqs: Req[], o: { dry: boolean; tag: string }): Promise<unknown[]> {
|
||||
const out: unknown[] = [];
|
||||
for (const r of reqs) {
|
||||
for (const [i, r] of reqs.entries()) {
|
||||
if (o.dry) { log(o.tag, `would ${describeReq(r)}`); continue; }
|
||||
out.push(await asc(r.method, r.path, r.body));
|
||||
try { out.push(await asc(r.method, r.path, r.body)); } catch (e) {
|
||||
if (r.method === 'POST' && isConflict(e)) { warn(o.tag, `${describeReq(r)}: already exists, left as it is`); out.push(null); continue; }
|
||||
if (isAmbiguous(e)) throw new Error(`${describeReq(r)}: no clear answer (${(e as Error).message.slice(0, 200)}). Not sent again, so nothing is created twice; ${reqs.length - i - 1} later request(s) not sent. Run the command again: it reads the store and does only what is still missing.`);
|
||||
throw e;
|
||||
}
|
||||
log(o.tag, `${describeReq(r)}: done`);
|
||||
}
|
||||
return out;
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import { applePoints, pickPoint } from '../lib/subscriptions';
|
|||
import { pages } from '../prices';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, type Req } from './jsonapi';
|
||||
import { findOrCreate, getById } from '../lib/upsert';
|
||||
|
||||
const TAG = 'offer-codes';
|
||||
|
||||
|
|
@ -60,7 +61,16 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const body = iapOfferCodeBody(iap.id, oc, await prices(oc));
|
||||
const req: Req = { method: 'POST', path: '/v1/inAppPurchaseOfferCodes', body, note: `${p.id}: campaign "${oc.name}" (${oc.free ? 'free' : `USD ${oc.usd}`}, ${body.included.length} territories)` };
|
||||
if (dry) log(TAG, `would ${describeReq(req)}`);
|
||||
else { id = ((await execute(c.asc, [req], { dry, tag: TAG }))[0] as J).data.id; active++; }
|
||||
else {
|
||||
// campaign names are not known to be unique: looked up right before the create, never sent twice
|
||||
const made = await findOrCreate<J>({ what: `${p.id} campaign "${oc.name}"`, tag: TAG,
|
||||
find: async () => (await c.all(`/v2/inAppPurchases/${iap.id}/offerCodes?limit=200`)).find((x: J) => x.attributes.name === oc.name) ?? null,
|
||||
journal: { root, key: `apple:${appId}:iapOfferCode:${p.id}:${oc.name}`, byId: x => getById(c.asc, `/v1/inAppPurchaseOfferCodes/${x}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', req.path, req.body)).data });
|
||||
id = made.value.id;
|
||||
log(TAG, `${describeReq(req)}: ${made.created ? 'done' : 'exists already'}`);
|
||||
if (made.created) active++;
|
||||
}
|
||||
} else log(TAG, `${p.id}: campaign "${oc.name}" exists (${cur.attributes.active ? 'active' : 'inactive'}, ${cur.attributes.productionCodeCount ?? 0} production codes)`);
|
||||
const haveCustom = new Set(cur ? (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/customCodes?limit=200`)).map((x: J) => x.attributes.customCode) : []);
|
||||
for (const cc of oc.customCodes ?? []) if (!haveCustom.has(cc.code)) codeReqs.push({ req: iapCustomCodeReq(id ?? '${new campaign}', cc), product: p.id, campaign: oc.name, oneTime: false });
|
||||
|
|
@ -78,8 +88,8 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
if (!(await confirm(ctx, `Create ${codeReqs.length} code request(s) (${codeReqs.map(x => x.req.note).join('; ')})? Codes count against the 1 million per quarter and can be redeemed by anyone who gets them.`))) return;
|
||||
const dir = resolve('.storebound/offer-codes');
|
||||
for (const x of codeReqs) {
|
||||
const out = (await execute(c.asc, [x.req], { dry: false, tag: TAG }))[0] as J;
|
||||
if (!x.oneTime) continue;
|
||||
const out = (await execute(c.asc, [x.req], { dry: false, tag: TAG }))[0] as J | null;
|
||||
if (!x.oneTime || !out) continue;
|
||||
// the codes of a one-time-use batch (text/csv); saved locally, never printed
|
||||
const values = await c.bytes(`/v1/inAppPurchaseOfferCodeOneTimeUseCodes/${out.data.id}/values`, 'text/csv');
|
||||
if (!values) { warn(TAG, `${x.product} "${x.campaign}": codes not ready yet; download them in App Store Connect`); continue; }
|
||||
|
|
|
|||
|
|
@ -21,7 +21,8 @@ import { textTable } from '../lib/table';
|
|||
import { numberedImages } from '../play/images';
|
||||
import { variantRoot } from '../shots/lib';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { execute } from './jsonapi';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
import { findOrCreate, getById } from '../lib/upsert';
|
||||
import { displaySets, syncScreenshotSet } from './screenshots';
|
||||
|
||||
const TAG = 'ppo';
|
||||
|
|
@ -78,12 +79,29 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
let exp = pickExperiment(list, name);
|
||||
if (!exp) {
|
||||
if (dry) { await execute(c.asc, [createExperimentReq(appId, name, traffic)], { dry, tag: TAG }); log(TAG, `then: ${variants.length} treatment(s) x ${locales.length} locale(s)`); done(TAG, 'create checked (dry run)'); return; }
|
||||
const r = (await execute(c.asc, [createExperimentReq(appId, name, traffic)], { dry, tag: TAG }))[0] as J;
|
||||
exp = experimentFromApi(r.data);
|
||||
// test names are not known to be unique: looked up right before the create (and in the journal), never sent twice
|
||||
const req = createExperimentReq(appId, name, traffic);
|
||||
const made = await findOrCreate<J>({ what: `experiment "${name}"`, tag: TAG,
|
||||
find: async () => (await c.all(`/v1/apps/${appId}/appStoreVersionExperimentsV2?limit=50`)).find((x: J) => x.attributes.name === name && !['COMPLETED', 'STOPPED'].includes(x.attributes.state)) ?? null,
|
||||
journal: { root, key: `apple:${appId}:ppo:${name}`, byId: id => getById(c.asc, `/v2/appStoreVersionExperiments/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', req.path, req.body)).data });
|
||||
log(TAG, `${describeReq(req)}: ${made.created ? 'done' : 'exists already'}`);
|
||||
exp = experimentFromApi(made.value);
|
||||
} else log(TAG, `experiment "${name}": exists (${exp.state})`);
|
||||
const ts = await treatments(c, exp.id);
|
||||
const created = (await execute(c.asc, planTreatments(exp.id, ts.map((t: J) => ({ id: t.id, name: t.attributes.name })), variants), { dry, tag: TAG })) as J[];
|
||||
const all = [...ts, ...created.map(r => r.data)].filter(t => variants.includes(t.attributes.name));
|
||||
const planned = planTreatments(exp.id, ts.map((t: J) => ({ id: t.id, name: t.attributes.name })), variants);
|
||||
const all: J[] = ts.filter((t: J) => variants.includes(t.attributes.name));
|
||||
if (dry) await execute(c.asc, planned, { dry, tag: TAG });
|
||||
else for (const r of planned) {
|
||||
const tname = (r.body as J).data.attributes.name as string;
|
||||
const expId = exp.id;
|
||||
const made = await findOrCreate<J>({ what: `treatment "${tname}"`, tag: TAG,
|
||||
find: async () => (await treatments(c, expId)).find((t: J) => t.attributes.name === tname) ?? null,
|
||||
journal: { root, key: `apple:${appId}:ppoTreatment:${expId}:${tname}`, byId: id => getById(c.asc, `/v1/appStoreVersionExperimentTreatments/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', r.path, r.body)).data });
|
||||
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
|
||||
all.push(made.value);
|
||||
}
|
||||
for (const t of all) await execute(c.asc, planTreatmentLocales(t.id, (await treatmentLocs(c, t.id)).map((l: J) => l.attributes.locale), locales), { dry, tag: TAG });
|
||||
done(TAG, dry ? 'create checked (dry run)' : `test "${name}" ready: storebound apple ppo upload --variant ${variants[0]}`);
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@ import { done, log, warn } from '../lib/log';
|
|||
import { ffprobe } from '../shots/report';
|
||||
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from '../shots/spec';
|
||||
import { timeCode } from '../shots/video';
|
||||
import { ascClient, md5, setUpToDate, type J } from './asc';
|
||||
import { findOrCreate } from '../lib/upsert';
|
||||
import { ascClient, keptPrefix, md5, setUpToDate, type J } from './asc';
|
||||
|
||||
/** Video target folder -> ASC previewType, for this project (iPad only with apple.ipad). */
|
||||
export const previewSets = (apple: { ipad?: boolean } | undefined): Record<string, string> =>
|
||||
|
|
@ -100,15 +101,22 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
log('apple', `${tag}: poster frame ${tc}`);
|
||||
continue;
|
||||
}
|
||||
if (dry) { log('apple', `${tag}: would replace ${existing.length} with ${fs.length}`); continue; }
|
||||
if (!set) set = (await c.asc('POST', '/v1/appPreviewSets', { data: { type: 'appPreviewSets', attributes: { previewType: type },
|
||||
relationships: { appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: loc.id } } } } })).data;
|
||||
for (const p of existing) await c.asc('DELETE', `/v1/appPreviews/${p.id}`);
|
||||
for (const f of fs) {
|
||||
log('apple', `${tag}: uploading ${f.slice(src.length + 1)}`);
|
||||
await c.uploadAsset('appPreviews', { appPreviewSet: { data: { type: 'appPreviewSets', id: set.id } } }, f, previewAttrs(f, poster));
|
||||
const kept = keptPrefix(existing.map(p => ({ checksum: p.attributes.sourceFileChecksum, state: state(p) })), want);
|
||||
if (dry) { log('apple', `${tag}: would keep ${kept}, replace ${existing.length - kept} with ${fs.length - kept}`); continue; }
|
||||
if (!set) {
|
||||
const r = await findOrCreate<J>({ what: `${tag} preview set`, tag: 'apple', unique: true,
|
||||
find: async () => (await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/appPreviewSets`)).find((s: J) => s.attributes.previewType === type) ?? null,
|
||||
create: async () => (await c.asc('POST', '/v1/appPreviewSets', { data: { type: 'appPreviewSets', attributes: { previewType: type },
|
||||
relationships: { appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: loc.id } } } } })).data });
|
||||
set = r.value;
|
||||
if (!r.created) existing.push(...await c.all(`/v1/appPreviewSets/${set.id}/appPreviews`));
|
||||
}
|
||||
log('apple', `${tag}: uploaded ${fs.length} (removed ${existing.length})`);
|
||||
const r = await c.syncAssets({ set: { type: 'appPreviewSets', id: set.id }, existing, files: fs, want, state, attrs: f => previewAttrs(f, poster),
|
||||
onUpload: f => log('apple', `${tag}: uploading ${f.slice(src.length + 1)}`) });
|
||||
const tc = timeCode(poster);
|
||||
for (const p of existing.slice(0, r.kept).filter(p => p.attributes.previewFrameTimeCode && p.attributes.previewFrameTimeCode !== tc))
|
||||
await c.asc('PATCH', `/v1/appPreviews/${p.id}`, { data: { type: 'appPreviews', id: p.id, attributes: { previewFrameTimeCode: tc } } });
|
||||
log('apple', `${tag}: uploaded ${r.uploaded}${r.kept ? `, kept ${r.kept}` : ''} (removed ${r.removed})`);
|
||||
}
|
||||
}
|
||||
if (dry) return done('apple', 'previews checked (dry run, nothing sent)');
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import type { Ctx } from '../lib/ctx';
|
|||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { type PhasedAction, phasedRequest } from '../lib/release';
|
||||
import { createOnce } from '../lib/upsert';
|
||||
import { ascClient, type J } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
|
|
@ -50,8 +51,11 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
if (dry) { log('apple', `${tag}: would ${req.method === 'POST' ? 'turn phased release on' : `set phased release ${req.state}`} (dry)`); return; }
|
||||
if ((phased === 'resume' || phased === 'complete') && !(await confirm(ctx, `${phased === 'complete' ? 'Release' : 'Resume the phased release of'} ${tag} ${phased === 'complete' ? 'to every user now' : ''}?`))) return;
|
||||
if (req.method === 'POST') {
|
||||
await c.asc('POST', '/v1/appStoreVersionPhasedReleases', { data: { type: 'appStoreVersionPhasedReleases',
|
||||
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: v.id } } } } });
|
||||
// one phased release per version: a 409 or an unclear answer is checked by reading it back, never re-sent blindly
|
||||
await createOnce({ what: `phased release of ${tag}`, tag: 'apple', unique: true,
|
||||
find: async () => (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreVersionPhasedRelease`))?.data ?? null,
|
||||
create: async () => (await c.asc('POST', '/v1/appStoreVersionPhasedReleases', { data: { type: 'appStoreVersionPhasedReleases',
|
||||
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: v.id } } } } })).data });
|
||||
} else {
|
||||
await c.asc('PATCH', `/v1/appStoreVersionPhasedReleases/${cur!.id}`, { data: { type: 'appStoreVersionPhasedReleases', id: cur!.id, attributes: { phasedReleaseState: req.state } } });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { need } from '../lib/ctx';
|
|||
import { reviewContact, reviewDemoAccount } from '../lib/credentials';
|
||||
import { reviewDetailPlan } from '../lib/review-details';
|
||||
import { done, log } from '../lib/log';
|
||||
import { createOnce } from '../lib/upsert';
|
||||
import { ascClient } from './asc';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
|
|
@ -34,9 +35,17 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
|
||||
const { attributes, summary } = reviewDetailPlan(config, contact, reviewDemoAccount(root));
|
||||
if (ctx.args.has('dry')) { log('apple', `would set review details (contact ${from ? 'copied from ' + from : 'from credentials'}, ${summary})`); 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 } } } } });
|
||||
const read = async () => (await c.maybe(`/v1/appStoreVersions/${version.id}/appStoreReviewDetail`))?.data ?? null;
|
||||
const cur = await read();
|
||||
// one review detail per version: only changed fields are sent; a new one is created once (a 409 finds it)
|
||||
const changed = cur ? Object.fromEntries(Object.entries(attributes).filter(([k, v]) => (cur.attributes?.[k] ?? null) !== (v ?? null))) : attributes;
|
||||
if (cur && !Object.keys(changed).length) { done('apple', `review details on ${version.attributes.versionString} up to date (${summary})`); return; }
|
||||
if (cur) await c.asc('PATCH', `/v1/appStoreReviewDetails/${cur.id}`, { data: { type: 'appStoreReviewDetails', id: cur.id, attributes: changed } });
|
||||
else {
|
||||
const r = await createOnce({ what: 'App Review details', tag: 'apple', unique: true, find: read,
|
||||
create: async () => (await c.asc('POST', '/v1/appStoreReviewDetails', { data: { type: 'appStoreReviewDetails', attributes,
|
||||
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: version.id } } } } })).data });
|
||||
if (!r.created) await c.asc('PATCH', `/v1/appStoreReviewDetails/${r.value.id}`, { data: { type: 'appStoreReviewDetails', id: r.value.id, attributes } });
|
||||
}
|
||||
done('apple', `review details set on ${version.attributes.versionString} (${summary})`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ import { byAppleLocale, need } from '../lib/ctx';
|
|||
import { done, log, warn } from '../lib/log';
|
||||
import { numberedImages } from '../play/images';
|
||||
import { variantRoot } from '../shots/lib';
|
||||
import { type Asc, ascClient, md5, setUpToDate, type J } from './asc';
|
||||
import { findOrCreate } from '../lib/upsert';
|
||||
import { type Asc, ascClient, keptPrefix, md5, setUpToDate, type J } from './asc';
|
||||
|
||||
/** Render size key -> ASC screenshotDisplayType (iPhone sets). */
|
||||
export const DISPLAY: Record<string, string> = { ios69: 'APP_IPHONE_67', ios65: 'APP_IPHONE_65' };
|
||||
|
|
@ -33,19 +34,32 @@ export const displaySets = (apple: { ipad?: boolean; iphoneMedium?: boolean } |
|
|||
export const requiredDisplayTypes = (apple: { ipad?: boolean; screenshotTypes?: string[] } | undefined): string[] =>
|
||||
apple?.screenshotTypes ?? ['APP_IPHONE_67', ...(apple?.ipad ? ['APP_IPAD_PRO_3GEN_129'] : [])];
|
||||
|
||||
/** Makes one screenshot set (of a version localization, or of a Product Page Optimization treatment localization)
|
||||
* hold exactly `files`, in order: left alone when the MD5s match, else emptied and re-uploaded. Creates the set. */
|
||||
/** Makes one screenshot set (of a version localization, a custom product page localization or a Product Page
|
||||
* Optimization treatment localization) hold exactly `files`, in order: left alone when the MD5s match, else the
|
||||
* matching leading screenshots stay and the rest is replaced (c.syncAssets). The set is created when missing, after a
|
||||
* fresh look (one set per display type: a 409 finds the existing one). */
|
||||
export async function syncScreenshotSet(c: Asc, parent: { rel: string; type: string; id: string }, sets: J[], type: string, files: string[], tag: string, dry: boolean): Promise<void> {
|
||||
let set = sets.find(s => s.attributes.screenshotDisplayType === type);
|
||||
const existing = set ? await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots`) : [];
|
||||
const existing = set ? await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots?limit=50`) : [];
|
||||
const want = files.map(f => md5(readFileSync(f)));
|
||||
if (set && setUpToDate(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: s.attributes.assetDeliveryState?.state })), want)) { log('apple', `${tag}: ${files.length} up to date`); return; }
|
||||
if (dry) { log('apple', `${tag}: would ${set ? `replace ${existing.length}` : 'create the set and upload'} with ${files.length}`); return; }
|
||||
if (!set) set = (await c.asc('POST', '/v1/appScreenshotSets', { data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: type },
|
||||
relationships: { [parent.rel]: { data: { type: parent.type, id: parent.id } } } } })).data;
|
||||
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 state = (s: J) => s.attributes.assetDeliveryState?.state;
|
||||
if (set && setUpToDate(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: state(s) })), want)) { log('apple', `${tag}: ${files.length} up to date`); return; }
|
||||
if (dry) {
|
||||
const k = keptPrefix(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: state(s) })), want);
|
||||
log('apple', `${tag}: would ${set ? `keep ${k}, replace ${existing.length - k}` : 'create the set and upload'} with ${files.length - k} new`);
|
||||
return;
|
||||
}
|
||||
if (!set) {
|
||||
const find = async () => (await c.all(`/v1/${parent.type}/${parent.id}/appScreenshotSets?limit=50`)).find((s: J) => s.attributes.screenshotDisplayType === type) ?? null;
|
||||
const r = await findOrCreate<J>({ what: `${tag} screenshot set`, tag: 'apple', unique: true, find,
|
||||
create: async () => (await c.asc('POST', '/v1/appScreenshotSets', { data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: type },
|
||||
relationships: { [parent.rel]: { data: { type: parent.type, id: parent.id } } } } })).data });
|
||||
set = r.value;
|
||||
// a set found now (made by an earlier run the first read missed) may already hold screenshots
|
||||
if (!r.created) existing.push(...await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots?limit=50`));
|
||||
}
|
||||
const r = await c.syncAssets({ set: { type: 'appScreenshotSets', id: set.id }, existing, files, want, state });
|
||||
log('apple', `${tag}: uploaded ${r.uploaded}${r.kept ? `, kept ${r.kept}` : ''} (removed ${r.removed})`);
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import {
|
|||
import { textTable } from '../lib/table';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute, type Req } from './jsonapi';
|
||||
import { createOnce, isAmbiguous, upsertTiming } from '../lib/upsert';
|
||||
|
||||
const TAG = 'signing';
|
||||
const USAGE = 'usage: storebound apple signing status | ensure [--dry] [--keychain [path]] [--no-install]';
|
||||
|
|
@ -194,9 +195,23 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const csr = buildCsr(key, { commonName: `storebound ${config.app.name}`.slice(0, 64) });
|
||||
created = (await c.asc('POST', '/v1/certificates', certificateReq(certType, csrContent(csr)).body)).data;
|
||||
} catch (e) {
|
||||
rmSync(pending, { force: true });
|
||||
const why = explainCertError(e, certType);
|
||||
throw new Error(why ? `${(e as Error).message}\n\n${why}` : (e as Error).message);
|
||||
if (isAmbiguous(e)) {
|
||||
// the certificate may exist: it is the one whose public key is this pending key's. The key stays on disk either
|
||||
// way (a later run finds the certificate through it), so no certificate is ever orphaned or made twice.
|
||||
const mine = spkiOfKey(readFileSync(pending, 'utf8'));
|
||||
let found: J | undefined;
|
||||
for (let i = 0; i < 4 && !found; i++) {
|
||||
if (i) await upsertTiming.sleep(upsertTiming.waitMs * i);
|
||||
found = (await c.all(`/v1/certificates?filter[certificateType]=${certType}&limit=200`)).find((x: ApiCert) => !!x.attributes.certificateContent && certSpki(x.attributes.certificateContent) === mine);
|
||||
}
|
||||
if (!found) throw new Error(`${(e as Error).message}\n\nThe certificate request got no clear answer and App Store Connect does not list a certificate for the new key (yet). The key is kept in ${pending.replace(root + '/', '')}; run \`storebound apple signing ensure\` again in a minute: it finds the certificate through that key instead of making another one.`);
|
||||
created = found;
|
||||
log(TAG, 'the certificate request went through (found by its public key)');
|
||||
} else {
|
||||
rmSync(pending, { force: true });
|
||||
const why = explainCertError(e, certType);
|
||||
throw new Error(why ? `${(e as Error).message}\n\n${why}` : (e as Error).message);
|
||||
}
|
||||
}
|
||||
const keyFile = join(dir, `${created.id}.key`), cerFile = join(dir, `${created.id}.cer`);
|
||||
renameSync(pending, keyFile);
|
||||
|
|
@ -212,7 +227,14 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const p = planProfile(list, { bundleId: id, bundleIdId: b.id, certId: cert!.id, type: profileType });
|
||||
let prof: ApiProfile;
|
||||
if (p.create) {
|
||||
const r = (await c.asc('POST', p.create.path, p.create.body)).data;
|
||||
// an unclear answer is checked by reading the bundle id's profiles again (one active profile with this
|
||||
// certificate is reused), never re-sent blindly
|
||||
const r = (await createOnce<J>({ what: `${id} profile`, tag: TAG,
|
||||
find: async () => {
|
||||
const again = planProfile(await profilesOf(c, b.id, profileType), { bundleId: id, bundleIdId: b.id, certId: cert!.id, type: profileType });
|
||||
return again.reuse ? { id: again.reuse.id, attributes: (await c.asc('GET', `/v1/profiles/${again.reuse.id}`)).data.attributes } : null;
|
||||
},
|
||||
create: async () => (await c.asc('POST', p.create!.path, p.create!.body)).data })).value;
|
||||
prof = { id: r.id, attributes: r.attributes };
|
||||
log(TAG, `${id}: profile "${prof.attributes.name}" created (${prof.attributes.uuid})`);
|
||||
} else {
|
||||
|
|
|
|||
47
cli/apple/submission.ts
Normal file
47
cli/apple/submission.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// The app's one draft review submission and the items in it, without duplicates: a draft (READY_FOR_REVIEW) is
|
||||
// reused, a new one is created only after a fresh look (Apple keeps one open draft per app and platform), and an item
|
||||
// already in the draft is not added again (a 409 or a re-read finds it). Used by iap-submit, cpp submit and events
|
||||
// submit. Submitting itself (PATCH submitted: true) stays the owner's confirmed step in those commands.
|
||||
import { log } from '../lib/log';
|
||||
import { createOnce, findOrCreate } from '../lib/upsert';
|
||||
import type { Asc, J } from './asc';
|
||||
import { one } from './jsonapi';
|
||||
|
||||
/** The draft review submission of the app (READY_FOR_REVIEW, iOS), or null. */
|
||||
export async function findDraft(c: Asc, appId: string): Promise<string | null> {
|
||||
return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null;
|
||||
}
|
||||
|
||||
/** The draft's id: the existing one, else a new draft created once. */
|
||||
export async function draftSubmission(c: Asc, appId: string, root: string, tag: string): Promise<string> {
|
||||
const r = await findOrCreate<string>({ what: 'draft review submission', tag, unique: true,
|
||||
find: () => findDraft(c, appId),
|
||||
journal: { root, key: `apple:${appId}:reviewSubmission:draft`, idOf: id => id,
|
||||
byId: async id => { const d = (await c.maybe(`/v1/reviewSubmissions/${id}`))?.data; return d?.attributes?.state === 'READY_FOR_REVIEW' ? id : null; } },
|
||||
create: async () => (await c.asc('POST', '/v1/reviewSubmissions', { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } })).data.id as string });
|
||||
if (r.created) log(tag, `draft review submission ${r.value} created`);
|
||||
return r.value;
|
||||
}
|
||||
|
||||
const TYPE: Record<string, string> = {
|
||||
appStoreVersion: 'appStoreVersions', inAppPurchaseVersion: 'inAppPurchaseVersions', subscriptionVersion: 'subscriptionVersions',
|
||||
subscriptionGroupVersion: 'subscriptionGroupVersions', appCustomProductPageVersion: 'appCustomProductPageVersions', appEvent: 'appEvents',
|
||||
appStoreVersionExperiment: 'appStoreVersionExperiments',
|
||||
};
|
||||
|
||||
/** Whether the draft already holds `id` as `kind` (e.g. inAppPurchaseVersion). */
|
||||
export async function inDraft(c: Asc, sid: string, kind: string, id: string): Promise<boolean> {
|
||||
const items = await c.all(`/v1/reviewSubmissions/${sid}/items?include=${kind}&limit=200`);
|
||||
return items.some((it: J) => it.relationships?.[kind]?.data?.id === id);
|
||||
}
|
||||
|
||||
/** Adds one item to the draft unless it is in there already (`checked`: the caller read the draft's items a moment
|
||||
* ago). true when it was added now. */
|
||||
export async function addItem(c: Asc, sid: string, kind: string, id: string, label: string, tag: string, o: { checked?: boolean } = {}): Promise<boolean> {
|
||||
if (!o.checked && await inDraft(c, sid, kind, id)) { log(tag, `${label}: already in draft ${sid}`); return false; }
|
||||
const r = await createOnce({ what: `${label} in draft ${sid}`, tag, unique: true,
|
||||
find: async () => ((await inDraft(c, sid, kind, id)) ? id : null),
|
||||
create: async () => (await c.asc('POST', '/v1/reviewSubmissionItems', { data: { type: 'reviewSubmissionItems',
|
||||
relationships: { reviewSubmission: one('reviewSubmissions', sid), [kind]: one(TYPE[kind] ?? `${kind}s`, id) } } })).data?.id ?? id });
|
||||
return r.created;
|
||||
}
|
||||
|
|
@ -25,7 +25,8 @@ import {
|
|||
type ApplePoint, pickPoint,
|
||||
} from '../lib/subscriptions';
|
||||
import { pages } from '../prices';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { createOnce, findOrCreate, getById } from '../lib/upsert';
|
||||
import { type Asc, ascClient, md5, type J } from './asc';
|
||||
|
||||
const TAG = 'apple';
|
||||
|
||||
|
|
@ -68,7 +69,8 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
.map(g => ({ ...g, subscriptions: g.subscriptions.filter(s => (!only.length || only.includes(s.id)) && sellsOn(config, s, 'apple')) })).filter(g => g.subscriptions.length);
|
||||
const dry = ctx.args.has('dry');
|
||||
const csv = subscriptionCsv(ctx, 'apple');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
|
||||
const c = await ascClient(root, bundleId, config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
log(TAG, 'reading subscription groups, subscriptions, localizations, prices, offers');
|
||||
const state = await readState(c, appId);
|
||||
|
|
@ -87,33 +89,57 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const territories: string[] = (await c.all('/v1/territories?limit=200')).map((t: J) => t.id);
|
||||
for (const g of groups) {
|
||||
let gid = state.groups.find(x => x.referenceName === g.name)?.id;
|
||||
if (!gid) { gid = (await c.asc('POST', '/v1/subscriptionGroups', appleGroupBody(appId, g))).data.id as string; log(TAG, `group "${g.name}" created`); }
|
||||
const gLocs = state.groups.find(x => x.id === gid)?.locales ?? [];
|
||||
if (!gid) {
|
||||
const r = await findOrCreate<J>({ what: `subscription group "${g.name}"`, tag: TAG, unique: true,
|
||||
find: async () => (await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`)).find((x: J) => x.attributes.referenceName === g.name) ?? null,
|
||||
journal: { root, key: `apple:${bundleId}:subscriptionGroup:${g.name}`, byId: id => getById(c.asc, `/v1/subscriptionGroups/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', '/v1/subscriptionGroups', appleGroupBody(appId, g))).data });
|
||||
gid = r.value.id as string;
|
||||
log(TAG, `group "${g.name}" ${r.created ? 'created' : 'exists'}`);
|
||||
}
|
||||
const groupId = gid;
|
||||
const gLocs = state.groups.find(x => x.id === gid)?.locales ?? (await c.all(`/v1/subscriptionGroups/${gid}/subscriptionGroupLocalizations?limit=200`)).map((l: J) => l.attributes.locale);
|
||||
for (const [lang, l] of Object.entries(g.listings)) {
|
||||
const loc = locale.get(lang);
|
||||
if (!loc || gLocs.includes(loc)) continue;
|
||||
await c.asc('POST', '/v1/subscriptionGroupLocalizations', appleGroupLocBody(gid, loc, l));
|
||||
await createOnce({ what: `group "${g.name}" ${loc}`, tag: TAG, unique: true,
|
||||
find: async () => (await c.all(`/v1/subscriptionGroups/${groupId}/subscriptionGroupLocalizations?limit=200`)).find((x: J) => x.attributes.locale === loc) ?? null,
|
||||
create: async () => (await c.asc('POST', '/v1/subscriptionGroupLocalizations', appleGroupLocBody(groupId, loc, l))).data });
|
||||
log(TAG, ` group ${loc}`);
|
||||
}
|
||||
for (const [i, s] of g.subscriptions.entries()) {
|
||||
const tag = step(i + 1, g.subscriptions.length, s.id);
|
||||
const cur = state.subscriptions.find(x => x.productId === s.id);
|
||||
let id = cur?.id;
|
||||
if (!id) { id = (await c.asc('POST', '/v1/subscriptions', appleSubscriptionBody(gid, s))).data.id as string; log(TAG, `${tag}: created`); }
|
||||
let subLocs = cur?.locales;
|
||||
if (!id) {
|
||||
const r = await findOrCreate<J>({ what: `subscription ${s.id}`, tag: TAG, unique: true,
|
||||
find: async () => (await c.all(`/v1/subscriptionGroups/${groupId}/subscriptions?limit=200`)).find((x: J) => x.attributes.productId === s.id) ?? null,
|
||||
journal: { root, key: `apple:${bundleId}:subscription:${s.id}`, byId: x => getById(c.asc, `/v1/subscriptions/${x}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', '/v1/subscriptions', appleSubscriptionBody(groupId, s))).data });
|
||||
id = r.value.id as string;
|
||||
if (!r.created) subLocs = (await c.all(`/v1/subscriptions/${id}/subscriptionLocalizations?limit=200`)).map((l: J) => l.attributes.locale);
|
||||
log(TAG, `${tag}: ${r.created ? 'created' : 'exists'}`);
|
||||
}
|
||||
const subId = id;
|
||||
for (const [lang, l] of Object.entries(s.listings)) {
|
||||
const loc = locale.get(lang);
|
||||
if (!loc || cur?.locales.includes(loc)) continue;
|
||||
await c.asc('POST', '/v1/subscriptionLocalizations', appleSubLocBody(id, loc, l));
|
||||
if (!loc || subLocs?.includes(loc)) continue;
|
||||
await createOnce({ what: `${s.id} ${loc}`, tag: TAG, unique: true,
|
||||
find: async () => (await c.all(`/v1/subscriptions/${subId}/subscriptionLocalizations?limit=200`)).find((x: J) => x.attributes.locale === loc) ?? null,
|
||||
create: async () => (await c.asc('POST', '/v1/subscriptionLocalizations', appleSubLocBody(subId, loc, l))).data });
|
||||
log(TAG, ` ${loc}`);
|
||||
}
|
||||
if (!cur?.availability) { await c.asc('POST', '/v1/subscriptionAvailabilities', appleAvailabilityBody(id, territories)); log(TAG, ` available in ${territories.length} territories + new ones`); }
|
||||
if (!cur?.availability && !(await c.maybe(`/v1/subscriptions/${id}/subscriptionAvailability`))?.data) { await c.asc('POST', '/v1/subscriptionAvailabilities', appleAvailabilityBody(id, territories)); log(TAG, ` available in ${territories.length} territories + new ones`); }
|
||||
|
||||
// prices: USA point -> equalizations -> overrides / CSV; only what differs from today's prices
|
||||
const usaPoints = applePoints(await pages(c, `/v1/subscriptions/${id}/pricePoints?filter[territory]=USA&include=territory&limit=200`));
|
||||
const usa = pickPoint(usaPoints, 'USA', s.usd);
|
||||
const equalized = applePoints(await pages(c, `/v1/subscriptionPricePoints/${usa.id}/equalizations?include=territory&limit=200`));
|
||||
const known: ApplePoint[] = [usa, ...equalized];
|
||||
const current = cur?.hasPrices ? appleSubPrices(await pages(c, `/v1/subscriptions/${id}/prices?include=subscriptionPricePoint,territory&limit=200`)) : [];
|
||||
// a subscription the first read missed (list lag) is read live, so nothing is sent twice
|
||||
const hasPrices = cur ? cur.hasPrices : !!(await c.asc('GET', `/v1/subscriptions/${id}/prices?limit=1`)).data?.length;
|
||||
const current = hasPrices ? appleSubPrices(await pages(c, `/v1/subscriptions/${id}/prices?include=subscriptionPricePoint,territory&limit=200`)) : [];
|
||||
const changes = applePriceChanges(current, appleWantedPrices(s, equalized, csv), csv.filter(r => r.product === s.id));
|
||||
if (!changes.length) log(TAG, ' prices up to date');
|
||||
else if (current.length && !liveOk) warn(TAG, ` ${changes.length} price change(s) skipped: run in a terminal to confirm`);
|
||||
|
|
@ -140,27 +166,42 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const eq = applePoints(await pages(c, `/v1/subscriptionPricePoints/${ip.id}/equalizations?include=territory&limit=200`));
|
||||
return [{ territory: 'USA', pointId: ip.id }, ...eq.filter(p => p.territory !== 'USA').map(p => ({ territory: p.territory, pointId: p.id }))];
|
||||
};
|
||||
if (s.intro && !cur?.introTerritories) {
|
||||
if (s.intro && !(cur ? cur.introTerritories : (await c.asc('GET', `/v1/subscriptions/${id}/introductoryOffers?limit=1`)).data?.length)) {
|
||||
const offers = await offerPrices(s.intro);
|
||||
await c.asc('PATCH', `/v1/subscriptions/${id}`, appleIntroPatch(id, s, offers));
|
||||
log(TAG, ` introductory offer in ${offers.length} territories`);
|
||||
}
|
||||
for (const o of s.offers ?? []) {
|
||||
if (cur?.promoOffers?.includes(o.id)) continue;
|
||||
await c.asc('POST', '/v1/subscriptionPromotionalOffers', applePromoOfferBody(id, s, o, await offerPrices(o)));
|
||||
log(TAG, ` promotional offer ${o.id}`);
|
||||
// offer codes (the offer's identifier) are unique per subscription: a 409 finds the existing one
|
||||
const r = await createOnce({ what: `${s.id} promotional offer ${o.id}`, tag: TAG, unique: true,
|
||||
find: async () => (await c.all(`/v1/subscriptions/${subId}/promotionalOffers?limit=200`)).find((x: J) => x.attributes.offerCode === o.id) ?? null,
|
||||
create: async () => (await c.asc('POST', '/v1/subscriptionPromotionalOffers', applePromoOfferBody(subId, s, o, await offerPrices(o)))).data });
|
||||
if (r.created) log(TAG, ` promotional offer ${o.id}`);
|
||||
}
|
||||
for (const oc of s.offerCodes ?? []) {
|
||||
let ocId: string | undefined;
|
||||
if (!cur?.offerCodes?.includes(oc.name)) {
|
||||
ocId = (await c.asc('POST', '/v1/subscriptionOfferCodes', appleOfferCodeBody(id, s, oc, await offerPrices(oc)))).data.id as string;
|
||||
log(TAG, ` offer code campaign "${oc.name}"`);
|
||||
// campaign names are not known to be unique: look right before, never send the create twice
|
||||
const r = await findOrCreate<J>({ what: `${s.id} offer code campaign "${oc.name}"`, tag: TAG,
|
||||
find: async () => (await c.all(`/v1/subscriptions/${subId}/offerCodes?limit=200`)).find((x: J) => x.attributes.name === oc.name) ?? null,
|
||||
journal: { root, key: `apple:${bundleId}:subscriptionOfferCode:${s.id}:${oc.name}`, byId: x => getById(c.asc, `/v1/subscriptionOfferCodes/${x}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', '/v1/subscriptionOfferCodes', appleOfferCodeBody(subId, s, oc, await offerPrices(oc)))).data });
|
||||
ocId = r.value.id as string;
|
||||
if (r.created) log(TAG, ` offer code campaign "${oc.name}"`);
|
||||
}
|
||||
if (oc.customCodes?.length) await customCodes(c, ctx, id, s, oc, ocId);
|
||||
if (oc.customCodes?.length) await customCodes(c, ctx, subId, s, oc, ocId);
|
||||
}
|
||||
if (s.reviewScreenshot && !cur?.reviewScreenshot) {
|
||||
await c.uploadAsset('subscriptionAppStoreReviewScreenshots', { subscription: { data: { type: 'subscriptions', id } } }, resolve(s.reviewScreenshot));
|
||||
log(TAG, ` review screenshot ${s.reviewScreenshot}`);
|
||||
if (s.reviewScreenshot) {
|
||||
// one screenshot per subscription: kept when Apple has these bytes (MD5) and did not fail them, else replaced
|
||||
const file = resolve(s.reviewScreenshot);
|
||||
const shot = cur?.reviewScreenshot || !cur ? (await c.maybe(`/v1/subscriptions/${subId}/appStoreReviewScreenshot`))?.data : null;
|
||||
const ok = shot && shot.attributes?.sourceFileChecksum === md5(readFileSync(file)) && shot.attributes?.assetDeliveryState?.state !== 'FAILED';
|
||||
if (!ok) {
|
||||
if (shot) await c.asc('DELETE', `/v1/subscriptionAppStoreReviewScreenshots/${shot.id}`);
|
||||
await c.uploadAsset('subscriptionAppStoreReviewScreenshots', { subscription: { data: { type: 'subscriptions', id: subId } } }, file);
|
||||
log(TAG, ` review screenshot ${s.reviewScreenshot}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -178,5 +219,11 @@ async function customCodes(c: Asc, ctx: Ctx, subId: string, s: Subscription, oc:
|
|||
const todo = oc.customCodes!.filter(cc => !have.has(cc.code));
|
||||
if (!todo.length) return;
|
||||
if (!(await confirm({ ...ctx, args: { ...ctx.args, has: (n: string) => n !== 'yes' && ctx.args.has(n) } }, `Create ${todo.length} custom offer code(s) for ${s.id} (${todo.map(x => `${x.code} x${x.count}`).join(', ')})? Anyone with a code can redeem it.`))) return;
|
||||
for (const cc of todo) { await c.asc('POST', '/v1/subscriptionOfferCodeCustomCodes', appleCustomCodeBody(id, cc)); log(TAG, ` custom code ${cc.code} (${cc.count})`); }
|
||||
for (const cc of todo) {
|
||||
// a custom code is unique: a 409 finds the existing one
|
||||
await createOnce({ what: `custom code ${cc.code}`, tag: TAG, unique: true,
|
||||
find: async () => (await c.all(`/v1/subscriptionOfferCodes/${id}/customCodes?limit=200`)).find((x: J) => x.attributes.customCode === cc.code) ?? null,
|
||||
create: async () => (await c.asc('POST', '/v1/subscriptionOfferCodeCustomCodes', appleCustomCodeBody(id, cc))).data });
|
||||
log(TAG, ` custom code ${cc.code} (${cc.count})`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ import {
|
|||
parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing,
|
||||
} from '../lib/testflight';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { execute } from './jsonapi';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
import { findOrCreate, getById } from '../lib/upsert';
|
||||
|
||||
const TAG = 'testflight';
|
||||
const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group <names> | wait --build N | expire --keep N | --older-than D';
|
||||
|
|
@ -138,7 +139,16 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const plan = planGroups(appId, await groups(c, appId), tf?.groups ?? []);
|
||||
if (!tf?.groups?.length) warn(TAG, 'apple.testflight.groups is empty: nothing to create');
|
||||
for (const n of plan.existing) log(TAG, `group "${n}": exists`);
|
||||
await execute(c.asc, plan.create, { dry, tag: TAG });
|
||||
if (dry) await execute(c.asc, plan.create, { dry, tag: TAG });
|
||||
else for (const r of plan.create) {
|
||||
// looked up right before the create (fresh list, then the journal for the list lag); a 409 finds it
|
||||
const name = (r.body as J).data.attributes.name as string;
|
||||
const made = await findOrCreate<J>({ what: `beta group "${name}"`, tag: TAG, unique: true,
|
||||
find: async () => (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).find((g: J) => g.attributes.name === name) ?? null,
|
||||
journal: { root, key: `apple:${appId}:betaGroup:${name}`, byId: id => getById(c.asc, `/v1/betaGroups/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', r.path, r.body)).data });
|
||||
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
|
||||
}
|
||||
done(TAG, dry ? `groups checked (dry run): ${plan.create.length} to create` : `groups done (${plan.create.length} created)`);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import { BUILD_WAIT_EXIT } from '../lib/build-ops';
|
|||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { waitForBuild, waitMessage } from './testflight';
|
||||
import { describeReq } from './jsonapi';
|
||||
import { createOnce } from '../lib/upsert';
|
||||
|
||||
const TAG = 'upload';
|
||||
|
||||
|
|
@ -44,9 +45,20 @@ function slice(path: string, offset: number, length: number): Buffer {
|
|||
async function apiUpload(c: Asc, appId: string, ipa: string, info: ReturnType<typeof ipaInfo>, deadline: number): Promise<void> {
|
||||
const size = statSync(ipa).size;
|
||||
const reqs = buildUploadReqs(appId, info, basename(ipa), size);
|
||||
const up = (await c.asc('POST', reqs.upload.path, reqs.upload.body)).data;
|
||||
log(TAG, `build upload ${up.id} created`);
|
||||
const file = (await c.asc('POST', reqs.file(up.id).path, reqs.file(up.id).body)).data;
|
||||
// one build upload per version + build number: an earlier one that did not fail is resumed, never doubled
|
||||
const prior = (await uploadsOf(c, appId, info)).find((u: J) => u.attributes?.state?.state !== 'FAILED');
|
||||
const made = prior ? { value: prior, created: false } : await createOnce<J>({ what: `build upload ${info.version} (${info.build})`, tag: TAG,
|
||||
find: async () => (await uploadsOf(c, appId, info)).find((u: J) => u.attributes?.state?.state !== 'FAILED') ?? null,
|
||||
create: async () => (await c.asc('POST', reqs.upload.path, reqs.upload.body)).data });
|
||||
const up = made.value;
|
||||
log(TAG, made.created ? `build upload ${up.id} created` : `build upload ${up.id} exists (${up.attributes?.state?.state ?? '?'}): resuming it`);
|
||||
const filesOf = async () => (await c.all(`/v1/buildUploads/${up.id}/buildUploadFiles?limit=10`)).filter((f: J) => f.attributes?.fileName === basename(ipa));
|
||||
const fileNow = made.created ? undefined : (await filesOf())[0];
|
||||
const file = fileNow ?? (await createOnce<J>({ what: `file reservation of build upload ${up.id}`, tag: TAG,
|
||||
find: async () => (await filesOf())[0] ?? null,
|
||||
create: async () => (await c.asc('POST', reqs.file(up.id).path, reqs.file(up.id).body)).data })).value;
|
||||
if (fileNow && !(fileNow.attributes?.uploadOperations ?? []).length)
|
||||
throw new Error(`build upload ${up.id} already has ${basename(ipa)} (${fileNow.attributes?.assetDeliveryState?.state ?? 'state unknown'}) and App Store Connect gives no upload parts for it: wait for it (storebound apple testflight wait --build ${info.build}), or raise the build number (storebound apple build)`);
|
||||
const ops = (file.attributes.uploadOperations ?? []) as J[];
|
||||
log(TAG, `uploading ${(size / 1048576).toFixed(1)} MB in ${ops.length} part(s)`);
|
||||
let sent = 0;
|
||||
|
|
@ -82,6 +94,10 @@ async function apiUpload(c: Asc, appId: string, ipa: string, info: ReturnType<ty
|
|||
}
|
||||
}
|
||||
|
||||
/** Build uploads of this version + build number (any state), newest first. */
|
||||
const uploadsOf = (c: Asc, appId: string, info: { version: string; build: string }): Promise<J[]> =>
|
||||
c.all(`/v1/apps/${appId}/buildUploads?filter[cfBundleShortVersionString]=${encodeURIComponent(info.version)}&filter[cfBundleVersion]=${encodeURIComponent(info.build)}&filter[platform]=IOS&limit=20`);
|
||||
|
||||
async function altoolUpload(root: string, ipa: string): Promise<void> {
|
||||
if (process.platform !== 'darwin' || !Bun.which('xcrun')) throw new Error('--via altool needs macOS with Xcode; use --via api elsewhere');
|
||||
const k = ascKeyFile(root);
|
||||
|
|
@ -122,6 +138,16 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const builds = await c.all(`/v1/builds?filter[app]=${appId}&limit=200&fields[builds]=version`);
|
||||
const numbers = builds.map(b => String(b.attributes.version));
|
||||
const next = nextBuildNumber(numbers);
|
||||
// the same IPA uploaded by an earlier run: nothing to send again, only the wait
|
||||
const already = via === 'api' && !dry ? (await uploadsOf(c, appId, info).catch(() => [])).find((u: J) => u.attributes?.state?.state === 'COMPLETE') : undefined;
|
||||
if (already) {
|
||||
log(TAG, `build ${info.version} (${info.build}) was uploaded already (build upload ${already.id}); not sending it again`);
|
||||
if (!wait) { if (json) printJson({ ...{ ipa: relative(root, ipa), version: info.version, build: info.build }, uploaded: true, alreadyUploaded: true }); done(TAG, `build ${info.build} already uploaded`); return; }
|
||||
const r = await waitForBuild(c, appId, info.build, { marketing: info.version, timeoutMs: timeout, tag: TAG });
|
||||
if (json) printJson({ ipa: relative(root, ipa), version: info.version, build: info.build, uploaded: true, alreadyUploaded: true, processingState: r.seen.processingState ?? null });
|
||||
if (r.outcome === 'valid') { done(TAG, waitMessage(info.build, r)); return; }
|
||||
process.exit(r.outcome === 'failed' ? BUILD_WAIT_EXIT.failed : BUILD_WAIT_EXIT.timeout);
|
||||
}
|
||||
if (numbers.includes(info.build)) throw new Error(`build ${info.build} is already on App Store Connect: rebuild with --build-number ${next} (storebound apple build)`);
|
||||
if (numbers.length && compareBuild(info.build, next) < 0) warn(TAG, `build ${info.build} is lower than the highest uploaded one (next free: ${next}); Apple accepts it only if this version train has no higher build`);
|
||||
const reqs = buildUploadReqs(appId, info, basename(ipa), size);
|
||||
|
|
|
|||
|
|
@ -130,6 +130,9 @@ async function main(): Promise<void> {
|
|||
if (!key) { console.error(`unknown command: ${argv.slice(0, 2).join(' ')}\n`); help(); process.exit(2); }
|
||||
const args = parseArgs(argv.slice(key.split(' ').length));
|
||||
const loaded = await loadConfig(args.get('config'));
|
||||
// one writer per app and store (cli/lib/lock.ts): dry runs and reads take no lock
|
||||
const { acquireLock, lockKeys } = await import('./lib/lock');
|
||||
for (const k of lockKeys(key, args, loaded.config)) acquireLock(loaded.root, k, argv.filter(x => x !== '--force-unlock').join(' '), { force: args.has('force-unlock') });
|
||||
await (await COMMANDS[key]![0]()).run({ loaded, args });
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args {
|
|||
const repeated = new Map<string, string[]>();
|
||||
const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); };
|
||||
const _: string[] = [];
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'include-drafts', ...booleans]);
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'force-unlock', 'include-drafts', ...booleans]);
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]!;
|
||||
if (!a.startsWith('--')) { _.push(a); continue; }
|
||||
|
|
|
|||
|
|
@ -129,7 +129,9 @@ export function normalizeKeywords(text: string, o: { name?: string; subtitle?: s
|
|||
return { text: kept.join(','), dropped };
|
||||
}
|
||||
|
||||
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; limit: number; problems: string[] }
|
||||
/** `chars` is what the store counts: characters, except App Store keywords, which App Store Connect limits in UTF-8 bytes
|
||||
* (`unit` says which). */
|
||||
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; unit: 'chars' | 'bytes'; limit: number; problems: string[] }
|
||||
|
||||
/** Limits and rules of one translated section. `source` = the source language's fields (identical text is flagged). */
|
||||
export function checkFields(store: 'apple' | 'play', f: Record<string, string | undefined>, source: Record<string, string | undefined> = {}, status?: TStatus): FieldCheck[] {
|
||||
|
|
@ -139,10 +141,11 @@ export function checkFields(store: 'apple' | 'play', f: Record<string, string |
|
|||
const v = f[k];
|
||||
if (v === undefined) continue;
|
||||
const limit = (FIELD_LIMITS[store] as Record<string, number>)[k]!;
|
||||
const c: FieldCheck = { store, field: k, chars: len(v), limit, problems: [] };
|
||||
if (len(v) > limit) c.problems.push(`${len(v)} > ${limit} characters`);
|
||||
if (store === 'apple' && k === 'keywords') {
|
||||
if (Buffer.byteLength(v) > limit) c.problems.push(`${Buffer.byteLength(v)} bytes > ${limit}`);
|
||||
const bytes = store === 'apple' && k === 'keywords';
|
||||
const n = bytes ? Buffer.byteLength(v, 'utf8') : len(v);
|
||||
const c: FieldCheck = { store, field: k, chars: n, unit: bytes ? 'bytes' : 'chars', limit, problems: [] };
|
||||
if (n > limit) c.problems.push(`${n} > ${limit} ${bytes ? 'bytes' : 'characters'}`);
|
||||
if (bytes) {
|
||||
if (/,\s|\s,/.test(v)) c.problems.push('spaces around commas');
|
||||
const words = v.split(',').map(w => w.trim().toLocaleLowerCase()).filter(Boolean);
|
||||
const dup = words.filter((w, i) => words.indexOf(w) !== i);
|
||||
|
|
|
|||
90
cli/lib/lock.ts
Normal file
90
cli/lib/lock.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// One writer per app and store: a write command takes .storebound/locks/<store>-<app>.lock before it changes
|
||||
// anything, so two storebound runs (two terminals, an agent and a CI job, a flow and a hand run) never write to the
|
||||
// same app at once and race each other into duplicates. Dry runs and reads take no lock.
|
||||
// A lock whose process is gone (same machine) is taken over; a live one stops the run with who holds it. A lock
|
||||
// left by a crash on another machine (shared folder) stays until --force-unlock or 12 hours.
|
||||
import { hostname } from 'node:os';
|
||||
import { mkdirSync, openSync, readFileSync, rmSync, writeSync, closeSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { ShipConfig } from './config';
|
||||
import type { Args } from './args';
|
||||
|
||||
export interface LockInfo { pid: number; host: string; command: string; startedAt: string }
|
||||
const STALE_MS = 12 * 3600_000;
|
||||
|
||||
export const lockPath = (root: string, key: string): string => join(root, '.storebound', 'locks', `${key.replace(/[^A-Za-z0-9._-]+/g, '_')}.lock`);
|
||||
|
||||
function alive(pid: number): boolean {
|
||||
try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }
|
||||
}
|
||||
|
||||
/** Whether a lock may be taken over: its process is gone (same host) or it is older than 12 hours. Pure apart from
|
||||
* the process check. */
|
||||
export function staleLock(l: LockInfo | null, now = Date.now(), host = hostname(), isAlive = alive): boolean {
|
||||
if (!l) return true;
|
||||
if (now - Date.parse(l.startedAt) > STALE_MS) return true;
|
||||
return l.host === host && !isAlive(l.pid);
|
||||
}
|
||||
|
||||
const held = new Set<string>();
|
||||
let hooked = false;
|
||||
|
||||
/** Takes the lock `key` for `command` (`apple iap`); throws with the holder when another run has it. Released when the
|
||||
* process exits. `force` removes a lock first (--force-unlock). */
|
||||
export function acquireLock(root: string, key: string, command: string, o: { force?: boolean } = {}): () => void {
|
||||
const path = lockPath(root, key);
|
||||
mkdirSync(join(root, '.storebound', 'locks'), { recursive: true });
|
||||
if (o.force) rmSync(path, { force: true });
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
const fd = openSync(path, 'wx', 0o600);
|
||||
const info: LockInfo = { pid: process.pid, host: hostname(), command, startedAt: new Date().toISOString() };
|
||||
writeSync(fd, JSON.stringify(info) + '\n');
|
||||
closeSync(fd);
|
||||
break;
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'EEXIST' || attempt > 2) throw e;
|
||||
let cur: LockInfo | null = null;
|
||||
try { cur = JSON.parse(readFileSync(path, 'utf8')) as LockInfo; } catch { /* half written or unreadable: treat as stale */ }
|
||||
if (!staleLock(cur)) {
|
||||
throw new Error(`another storebound run is writing to ${key.replace(/^(\w+)-/, '$1 ')}: \`storebound ${cur!.command}\` (pid ${cur!.pid} on ${cur!.host}, since ${cur!.startedAt.slice(0, 16).replace('T', ' ')} UTC). `
|
||||
+ `Two writers at once can create duplicates, so this run stops. Wait for it to finish; if it is no longer running, re-run with --force-unlock (removes ${join('.storebound', 'locks', path.split('/').pop()!)}).`);
|
||||
}
|
||||
rmSync(path, { force: true });
|
||||
}
|
||||
}
|
||||
held.add(path);
|
||||
if (!hooked) { hooked = true; process.on('exit', () => { for (const p of held) rmSync(p, { force: true }); }); }
|
||||
return () => { rmSync(path, { force: true }); held.delete(path); };
|
||||
}
|
||||
|
||||
/** Read-only subcommands and flags: no lock. */
|
||||
const READ_SUBS = new Set(['status', 'list', 'devices', 'diff', 'export', 'pull', 'wait', 'options', 'coverage', 'report', 'campaigns', 'check', 'help']);
|
||||
|
||||
/**
|
||||
* The lock keys a command run needs: none for dry runs and reads, `apple-<bundle id>` / `play-<package>` for store
|
||||
* writes, both for `prices import`, `revenuecat-<project>` for revenuecat sync. Pure.
|
||||
*/
|
||||
export function lockKeys(command: string, args: Args, config: ShipConfig): string[] {
|
||||
// a dry run never writes, so it never waits for (or blocks) a writer
|
||||
const readOnly = args.has('dry');
|
||||
if (readOnly) return [];
|
||||
const sub = args._[0];
|
||||
const apple = config.apple?.bundleId ? [`apple-${config.apple.bundleId}`] : [];
|
||||
const play = config.play?.packageName ? [`play-${config.play.packageName}`] : [];
|
||||
if (command.startsWith('apple ')) {
|
||||
if (['apple status', 'apple next-build', 'apple build'].includes(command)) return [];
|
||||
if (command === 'apple listing' && sub === 'pull') return [];
|
||||
if (sub && READ_SUBS.has(sub)) return [];
|
||||
if (command === 'apple adhoc' && ['options', 'export'].includes(sub ?? '')) return [];
|
||||
return apple;
|
||||
}
|
||||
if (command.startsWith('play ')) {
|
||||
if (['play status', 'play next-version-code', 'play build'].includes(command)) return [];
|
||||
if (command === 'play listing' && sub === 'pull') return [];
|
||||
return play;
|
||||
}
|
||||
if (command === 'prices') return sub === 'import' && !args.has('json') ? [...apple, ...play] : [];
|
||||
if (command === 'revenuecat') return sub === 'sync' ? [`revenuecat-${config.apple?.bundleId ?? config.play?.packageName ?? 'project'}`] : [];
|
||||
return [];
|
||||
}
|
||||
152
cli/lib/upsert.ts
Normal file
152
cli/lib/upsert.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// Idempotent writes against the stores. Every create in storebound goes through here or follows the same rules
|
||||
// (docs/idempotency.md):
|
||||
// 1. Look the thing up by its stable key first (product id, locale, version string, display type, name) and update or
|
||||
// leave it instead of creating it again.
|
||||
// 2. Right before a create, look again with a fresh GET (findOrCreate), and ask a journal of recent creates
|
||||
// (.storebound/created.json) for an id the store's list may not show yet: a direct GET by id is not subject to the
|
||||
// minute of list lag right after a create.
|
||||
// 3. A create answered with 409 / ALREADY_EXISTS is "found": look it up and use it, never create again (createOnce).
|
||||
// 4. A create whose outcome is unknown (timeout, connection reset, 5xx on a POST) is never sent blindly again: look
|
||||
// first; only when the store itself refuses duplicates of that key (unique) is a second attempt safe (its 409
|
||||
// then finds the first one). Otherwise stop with a message: re-running reads the store and converges.
|
||||
// Retries of 429 / 5xx in the API clients are only for requests that end the same when sent twice (retrySafe).
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { log, warn } from './log';
|
||||
|
||||
/** A write whose outcome is unknown: it may or may not have been applied (timeout, connection reset, 5xx answer to a
|
||||
* POST). The API clients throw this instead of retrying such a request. */
|
||||
export class AmbiguousWriteError extends Error {
|
||||
readonly ambiguous = true;
|
||||
constructor(message: string, readonly status: number | null = null) { super(message); this.name = 'AmbiguousWriteError'; }
|
||||
}
|
||||
|
||||
export const isAmbiguous = (e: unknown): boolean => e instanceof AmbiguousWriteError || (e as { ambiguous?: boolean } | null)?.ambiguous === true;
|
||||
|
||||
/**
|
||||
* The store refused a create because the thing already exists: Google ALREADY_EXISTS / 409, App Store Connect 409 with
|
||||
* a "duplicate / already / unique / in use / taken" detail (Apple also answers 409 for plain validation errors, which
|
||||
* are not conflicts), RevenueCat 409. Pure.
|
||||
*/
|
||||
export function isConflict(e: unknown): boolean {
|
||||
const s = String((e as Error)?.message ?? e);
|
||||
if (/ALREADY_EXISTS/.test(s)) return true;
|
||||
if (!/(-> |: )409\b/.test(s)) return false;
|
||||
return /duplicate|already|unique|in use|taken|exists/i.test(s.replace(/^.*?409/, ''));
|
||||
}
|
||||
|
||||
/** POSTs that end the same when sent twice: relationship adds, Google custom actions that set a state, and the App
|
||||
* Store "create or replace" singletons (price schedules, availability). */
|
||||
const IDEMPOTENT_POST: RegExp[] = [
|
||||
/\/relationships\//,
|
||||
/:(validate|convertRegionPrices|batchUpdateStates|activate|deactivate|query|batchGet|reply)(\?|$)/,
|
||||
/\/edits(\?|$)/, // a new edit; an unused one expires on its own and changes nothing
|
||||
/\/dataSafety(\?|$)/,
|
||||
/^\/v1\/(inAppPurchasePriceSchedules|appPriceSchedules|inAppPurchaseAvailabilities|subscriptionAvailabilities)(\?|$)/,
|
||||
/^\/v2\/appAvailabilities(\?|$)/,
|
||||
];
|
||||
|
||||
/** Whether a request may be sent again after a 5xx or a network error. GET, HEAD, PUT, PATCH and DELETE set a state;
|
||||
* a POST creates unless its path is a known idempotent action. `path` may be a full URL. Pure. */
|
||||
export function retrySafe(method: string, path: string): boolean {
|
||||
const m = method.toUpperCase();
|
||||
if (m !== 'POST') return true;
|
||||
const p = path.replace(/^https:\/\/[^/]+/, '').replace(/^\/(androidpublisher|upload\/androidpublisher)\/v3\/applications\/[^/]+/, '');
|
||||
return IDEMPOTENT_POST.some(re => re.test(p));
|
||||
}
|
||||
|
||||
/** Waits between re-checks (STOREBOUND_UPSERT_WAIT_MS; the test preload sets 0). */
|
||||
export const upsertTiming = { waitMs: Number(process.env.STOREBOUND_UPSERT_WAIT_MS ?? 3000), tries: 4, sleep: (ms: number): Promise<void> => (ms > 0 ? Bun.sleep(ms) : Promise.resolve()) };
|
||||
|
||||
export interface CreateOnce<T> {
|
||||
/** what is being created, for log lines and errors: `in-app purchase com.example.gems` */
|
||||
what: string;
|
||||
/** the create request; returns the created thing */
|
||||
create: () => Promise<T>;
|
||||
/** a fresh lookup by the stable key (GET with a filter, or the list), null when it is not there */
|
||||
find: () => Promise<T | null | undefined>;
|
||||
/** the store refuses a second one with this key (409): a create may then be tried again after an unknown outcome */
|
||||
unique?: boolean;
|
||||
/** log tag */
|
||||
tag?: string;
|
||||
}
|
||||
|
||||
async function recheck<T>(o: CreateOnce<T>): Promise<T | null> {
|
||||
for (let i = 0; i < upsertTiming.tries; i++) {
|
||||
const v = await o.find();
|
||||
if (v) return v;
|
||||
if (i < upsertTiming.tries - 1) await upsertTiming.sleep(upsertTiming.waitMs * (i + 1));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One create, never two: a conflict finds the existing one, an unknown outcome looks before (maybe) trying again. */
|
||||
export async function createOnce<T>(o: CreateOnce<T>, attempt = 1): Promise<{ value: T; created: boolean }> {
|
||||
try {
|
||||
return { value: await o.create(), created: true };
|
||||
} catch (e) {
|
||||
const msg = (e as Error).message;
|
||||
if (isConflict(e)) {
|
||||
const v = await recheck(o);
|
||||
if (v) { log(o.tag ?? 'upsert', `${o.what}: already exists, using it (not created again)`); return { value: v, created: false }; }
|
||||
throw new Error(`${o.what}: the store says it already exists but does not list it yet (its lists lag right after a create). Nothing was created twice; run the command again in a minute.\n${msg}`);
|
||||
}
|
||||
if (!isAmbiguous(e)) throw e;
|
||||
warn(o.tag ?? 'upsert', `${o.what}: no clear answer to the create (${msg.slice(0, 160)}); checking whether it exists before anything else`);
|
||||
const v = await recheck(o);
|
||||
if (v) { log(o.tag ?? 'upsert', `${o.what}: the create went through`); return { value: v, created: true }; }
|
||||
if (o.unique && attempt < 2) return createOnce(o, attempt + 1);
|
||||
throw new Error(`${o.what}: the create got no clear answer and the store does not list it (yet). It was not sent again, so nothing is created twice: run the command again in a minute (it reads the store first).\n${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- journal of creates
|
||||
|
||||
/** Creates of the last day, keyed by store + kind + stable key: { id, at }. Lives in .storebound/created.json. */
|
||||
type Journal = Record<string, { id: string; at: string }>;
|
||||
const JOURNAL_MS = 24 * 3600_000;
|
||||
const journalPath = (root: string): string => join(root, '.storebound', 'created.json');
|
||||
|
||||
export function readJournal(root: string, now = Date.now()): Journal {
|
||||
try {
|
||||
const j = JSON.parse(readFileSync(journalPath(root), 'utf8')) as Journal;
|
||||
return Object.fromEntries(Object.entries(j).filter(([, v]) => v && now - Date.parse(v.at) < JOURNAL_MS));
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
export function remember(root: string, key: string, id: string, now = new Date()): void {
|
||||
try {
|
||||
const j = readJournal(root, now.getTime());
|
||||
j[key] = { id, at: now.toISOString() };
|
||||
mkdirSync(join(root, '.storebound'), { recursive: true });
|
||||
const tmp = journalPath(root) + `.${process.pid}.tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(j, null, 2) + '\n');
|
||||
renameSync(tmp, journalPath(root));
|
||||
} catch (e) { warn('upsert', `could not note the create in .storebound/created.json: ${(e as Error).message}`); }
|
||||
}
|
||||
|
||||
export interface FindOrCreate<T> extends CreateOnce<T> {
|
||||
/** journal of recent creates: guards against the list lag right after a create of an earlier run */
|
||||
journal?: { root: string; key: string; byId: (id: string) => Promise<T | null | undefined>; idOf: (v: T) => string };
|
||||
}
|
||||
|
||||
/** Looks with a fresh GET, then in the journal (direct GET by id), and only then creates (createOnce). */
|
||||
export async function findOrCreate<T>(o: FindOrCreate<T>): Promise<{ value: T; created: boolean }> {
|
||||
const found = await o.find();
|
||||
if (found) return { value: found, created: false };
|
||||
if (o.journal && existsSync(join(o.journal.root, '.storebound'))) {
|
||||
const hit = readJournal(o.journal.root)[o.journal.key];
|
||||
if (hit) {
|
||||
const v = await o.journal.byId(hit.id).catch(() => null);
|
||||
if (v) { log(o.tag ?? 'upsert', `${o.what}: created ${hit.at.slice(11, 16)} UTC by an earlier run (${hit.id}); the store's list does not show it yet, using it`); return { value: v, created: false }; }
|
||||
}
|
||||
}
|
||||
const r = await createOnce(o);
|
||||
if (o.journal && r.created) remember(o.journal.root, o.journal.key, o.journal.idOf(r.value));
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Apple: GET of one resource by id, null on 404. For FindOrCreate.journal.byId. */
|
||||
export async function getById(asc: (m: string, p: string) => Promise<{ data?: unknown }>, path: string): Promise<unknown | null> {
|
||||
try { return (await asc('GET', path)).data ?? null; } catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
|
||||
}
|
||||
|
|
@ -127,7 +127,7 @@ async function translate(ctx: Ctx): Promise<void> {
|
|||
if (a.has('json')) printJson({ source: src.id, dryRun: dry, hook: !!hook, files: { apple: files.apple?.path ?? null, play: files.play?.path ?? null }, results: rows.map(r => ({ ...r, problems: problemsOf(r) })) });
|
||||
else {
|
||||
console.log(textTable(['language', 'store', 'section', 'fields', 'problems'], rows.map(r => [r.lang, r.store === 'apple' ? 'App Store' : 'Google Play', r.action,
|
||||
r.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '), problemsOf(r).join('; ')])));
|
||||
r.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '), problemsOf(r).join('; ')])));
|
||||
}
|
||||
const json = a.has('json');
|
||||
if (dry) { if (!json) done(TAG, 'dry run: listing files not written'); return; }
|
||||
|
|
@ -167,7 +167,7 @@ function check(ctx: Ctx): void {
|
|||
if (ctx.args.has('json')) printJson({ sections: r, ok: !bad.length, drafts: drafts.map(d => `${d.store}:${d.lang}`) });
|
||||
else {
|
||||
console.log(textTable(['store', 'language', 'status', 'fields', 'problems'], r.map(x => [x.store === 'apple' ? 'App Store' : 'Google Play', x.lang,
|
||||
x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '),
|
||||
x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '),
|
||||
x.checks.flatMap(c => c.problems.map(p => `${c.field}: ${p}`)).join('; ')])));
|
||||
if (drafts.length) warn(TAG, `${drafts.length} machine-translated draft(s) not reviewed yet: ${drafts.map(d => `${d.store}:${d.lang}`).join(', ')} (storebound listing reviewed --lang <ids> after reading them)`);
|
||||
done(TAG, bad.length ? `${bad.length} section(s) with problems` : `${r.length} section(s) within the store limits`);
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { playServiceAccount } from '../lib/credentials';
|
|||
import { tokenSource } from '../lib/google-auth';
|
||||
import { log, warn } from '../lib/log';
|
||||
import { errorBody } from '../lib/http';
|
||||
import { AmbiguousWriteError, isAmbiguous, retrySafe } from '../lib/upsert';
|
||||
|
||||
export type PlayClient = Awaited<ReturnType<typeof playClient>>;
|
||||
|
||||
|
|
@ -11,41 +12,88 @@ export async function playClient(root: string, packageName: string) {
|
|||
const API = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}`;
|
||||
const UPLOAD = `https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${packageName}`;
|
||||
|
||||
/** JSON call (object body) or media upload (Uint8Array body + Content-Type). Throws with the API's text. */
|
||||
/**
|
||||
* JSON call (object body) or media upload (Uint8Array body + Content-Type). Throws with the API's text. 429 is
|
||||
* retried (refused, not applied); 5xx and network errors only for requests that end the same when sent twice
|
||||
* (retrySafe). A create or upload POST then throws AmbiguousWriteError instead of being sent again.
|
||||
*/
|
||||
async function call<T = unknown>(method: string, url: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
|
||||
const bin = body instanceof Uint8Array;
|
||||
const safe = retrySafe(method, url);
|
||||
const short = (): string => url.replace(API, '').replace(UPLOAD, '');
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const r = await fetch(url, {
|
||||
method,
|
||||
headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined || bin ? {} : { 'Content-Type': 'application/json' }), ...headers },
|
||||
body: body === undefined ? undefined : bin ? (body as unknown as BodyInit) : JSON.stringify(body),
|
||||
});
|
||||
let r: Response;
|
||||
try {
|
||||
r = await fetch(url, {
|
||||
method,
|
||||
headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined || bin ? {} : { 'Content-Type': 'application/json' }), ...headers },
|
||||
body: body === undefined ? undefined : bin ? (body as unknown as BodyInit) : JSON.stringify(body),
|
||||
});
|
||||
} catch (e) {
|
||||
if (safe && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
|
||||
if (!safe) throw new AmbiguousWriteError(`${method} ${short()} -> no answer (${(e as Error).message})`);
|
||||
throw e;
|
||||
}
|
||||
const text = await r.text();
|
||||
if (r.ok) return (text ? JSON.parse(text) : {}) as T;
|
||||
if ((r.status === 429 || r.status >= 500) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
|
||||
const short = url.replace(API, '').replace(UPLOAD, '');
|
||||
if ((r.status === 429 || (r.status >= 500 && safe)) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
|
||||
// A wrong path casing answers with an HTML 404 page, not JSON: say so instead of dumping the HTML.
|
||||
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : errorBody(text);
|
||||
throw new Error(`${method} ${short} -> ${r.status} ${msg}`);
|
||||
if (r.status >= 500 && !safe) throw new AmbiguousWriteError(`${method} ${short()} -> ${r.status} ${msg}`, r.status);
|
||||
if (r.status === 404 && method === 'DELETE' && attempt > 0) return {} as T;
|
||||
throw new Error(`${method} ${short()} -> ${r.status} ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function editOnce<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string }): Promise<T> {
|
||||
/** At most one open edit per run: a second one would be invalidated by the first commit (or invalidate it). */
|
||||
let openEdit: string | null = null;
|
||||
async function openOne(): Promise<string> {
|
||||
if (openEdit) throw new Error(`a Play edit (${openEdit}) is already open in this run: storebound never opens a second one`);
|
||||
const e = await call<{ id: string }>('POST', `${API}/edits`, {});
|
||||
log('play', `edit ${e.id} opened`);
|
||||
openEdit = e.id;
|
||||
return e.id;
|
||||
}
|
||||
async function closeOne(id: string, what: string): Promise<void> {
|
||||
try { await call('DELETE', `${API}/edits/${id}`); } catch (err) {
|
||||
// an edit that was committed or expired is gone already; anything else is reported (Play drops it later)
|
||||
if (!/-> 404|not found|has been deleted|already been committed/i.test(String(err))) warn('play', `${what} edit ${id} not deleted: ${(err as Error).message.slice(0, 200)}`);
|
||||
} finally { if (openEdit === id) openEdit = null; }
|
||||
}
|
||||
|
||||
/** Thrown when a commit got no clear answer: the edit may be live, so it is never redone. */
|
||||
class CommitUnknown extends Error { readonly noRedo = true; }
|
||||
|
||||
/** Controls of an edit: `unchanged()` when fn found nothing to change; the edit is then deleted, not committed. */
|
||||
interface EditCtl { unchanged(): void }
|
||||
|
||||
async function editOnce<T>(fn: (id: string, ctl: EditCtl) => Promise<T>, o: { dry?: boolean; commitQuery?: string }): Promise<T> {
|
||||
const id = await openOne();
|
||||
log('play', `edit ${id} opened`);
|
||||
let same = false;
|
||||
let committing = false;
|
||||
try {
|
||||
const out = await fn(e.id);
|
||||
const out = await fn(id, { unchanged: () => { same = true; } });
|
||||
if (o.dry) {
|
||||
await call('POST', `${API}/edits/${e.id}:validate`);
|
||||
await call('POST', `${API}/edits/${id}:validate`);
|
||||
log('play', 'dry run: edit validated, discarding');
|
||||
await call('DELETE', `${API}/edits/${e.id}`);
|
||||
await closeOne(id, 'dry run');
|
||||
} else if (same) {
|
||||
log('play', 'nothing to change: edit discarded, not committed');
|
||||
await closeOne(id, 'unchanged');
|
||||
} else {
|
||||
await call('POST', `${API}/edits/${e.id}:commit${o.commitQuery ?? ''}`);
|
||||
log('play', `edit ${e.id} committed`);
|
||||
committing = true;
|
||||
try { await call('POST', `${API}/edits/${id}:commit${o.commitQuery ?? ''}`); } catch (err) {
|
||||
if (!isAmbiguous(err)) throw err;
|
||||
openEdit = null;
|
||||
throw new CommitUnknown(`the commit of edit ${id} got no clear answer (${(err as Error).message.slice(0, 200)}): it may be live. Not redone, so nothing is applied twice; check with \`storebound play status\` (or the dry run of this command) before running it again.`);
|
||||
}
|
||||
openEdit = null;
|
||||
log('play', `edit ${id} committed`);
|
||||
}
|
||||
return out;
|
||||
} catch (err) {
|
||||
await call('DELETE', `${API}/edits/${e.id}`).catch(() => {});
|
||||
// nothing of an uncommitted edit is live: delete it (also after a failed commit, which leaves the edit open)
|
||||
if (!(err instanceof CommitUnknown)) await closeOne(id, committing ? 'failed commit' : 'failed');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
|
@ -57,21 +105,23 @@ export async function playClient(root: string, packageName: string) {
|
|||
* A failed delete is reported (Play drops an unused edit on its own after a while, but it should not linger).
|
||||
*/
|
||||
async read<T>(fn: (id: string) => Promise<T>): Promise<T> {
|
||||
const e = await call<{ id: string }>('POST', `${API}/edits`, {});
|
||||
try { return await fn(e.id); } finally {
|
||||
await call('DELETE', `${API}/edits/${e.id}`).catch(err => warn('play', `read-only edit not deleted: ${(err as Error).message.slice(0, 200)}`));
|
||||
}
|
||||
const id = await openOne();
|
||||
try { return await fn(id); } finally { await closeOne(id, 'read-only'); }
|
||||
},
|
||||
/**
|
||||
* Opens an edit, runs fn, then commits (or validates and discards when dry). Any Console save or other edit commit
|
||||
* invalidates an open edit ("A change was made to the application outside of this Edit"); then the whole edit is
|
||||
* redone, up to `retries` times. Keep edits small (e.g. one per language for images) so a retry is cheap.
|
||||
*/
|
||||
async edit<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string; retries?: number } = {}): Promise<T> {
|
||||
async edit<T>(fn: (id: string, ctl: EditCtl) => Promise<T>, o: { dry?: boolean; commitQuery?: string; retries?: number } = {}): Promise<T> {
|
||||
for (let left = o.retries ?? 3; ; left--) {
|
||||
try { return await editOnce(fn, o); } catch (err) {
|
||||
if (left <= 0 || !/outside of this Edit|Edit has been deleted|edit.*(expired|not found)/i.test(String(err))) throw err;
|
||||
log('play', `app changed outside the edit (Console?), redoing it (${left} retries left)`);
|
||||
// redo only what never went live: an edit invalidated before or at its commit, or a request inside the edit
|
||||
// without a clear answer (the edit was deleted, so nothing of it applies). Never after an unclear commit.
|
||||
if (left <= 0 || (err as { noRedo?: boolean }).noRedo) throw err;
|
||||
const outside = /outside of this Edit|Edit has been deleted|edit.*(expired|not found)/i.test(String(err));
|
||||
if (!outside && !isAmbiguous(err)) throw err;
|
||||
log('play', `${outside ? 'app changed outside the edit (Console?)' : 'a request got no clear answer; the edit was discarded'}, redoing it (${left} retries left)`);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@
|
|||
// storebound play images [--dry] [--only en-US,de-DE] [--src store/renders] [--variant b]
|
||||
// Per Play language, from <renders>/<language id>/: icon (play.icon, 512x512), featureGraphic (feature/1024x500.*),
|
||||
// phoneScreenshots (play/NN.*), sevenInchScreenshots (tab7/NN.*), tenInchScreenshots (tab10/NN.*). A .jpg next to a
|
||||
// .png wins (JPEG q92 uploads about 4x faster; `storebound shots jpeg` makes them). Each image type is cleared
|
||||
// before uploading, so re-runs are idempotent. --variant <id> uploads <renders>/<id>/<lang>/... (an A/B variant from
|
||||
// .png wins (JPEG q92 uploads about 4x faster; `storebound shots jpeg` makes them). Play's images are compared with
|
||||
// the local files first (sha256, in order): only a changed image type is cleared and uploaded, in one edit per
|
||||
// language that is committed whole or not at all, so a re-run changes nothing and never doubles an image. --variant <id> uploads <renders>/<id>/<lang>/... (an A/B variant from
|
||||
// shots.variants) to the main listing: Play store listing experiments themselves are set up in Play Console (no API).
|
||||
// Uploads are slow: run in the background with a log file.
|
||||
// --dry is read-only: one throwaway edit, the images Play has now (their sha256) compared with the local files per
|
||||
|
|
@ -71,36 +72,51 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
log('play', `${codes.length} languages, ${[...sets.values()][0]?.reduce((n, [, f]) => n + f.length, 0) ?? 0} images each`);
|
||||
|
||||
const play = await playClient(root, pkg);
|
||||
// one read-only edit: what Play has now (sha256 per image, in order) against the local files, per language and type
|
||||
const plan = new Map<string, ImageChange[]>();
|
||||
await play.read(async id => {
|
||||
for (const code of codes) {
|
||||
const out: ImageChange[] = [];
|
||||
for (const [type, files] of sets.get(code)!) {
|
||||
const remote = (await play.call<{ images?: { sha256?: string }[] }>('GET', `${play.API}/edits/${id}/listings/${code}/${type}`)).images ?? [];
|
||||
out.push(imageChange(type, remote, files.map(sha256)));
|
||||
}
|
||||
plan.set(code, out);
|
||||
}
|
||||
});
|
||||
const changedTypes = (code: string) => plan.get(code)!.filter(c => c.change === 'replace');
|
||||
if (ctx.args.has('dry')) {
|
||||
let changed = 0;
|
||||
await play.read(async id => {
|
||||
for (const [i, code] of codes.entries()) {
|
||||
const out: ImageChange[] = [];
|
||||
for (const [type, files] of sets.get(code)!) {
|
||||
const remote = (await play.call<{ images?: { sha256?: string }[] }>('GET', `${play.API}/edits/${id}/listings/${code}/${type}`)).images ?? [];
|
||||
out.push(imageChange(type, remote, files.map(sha256)));
|
||||
}
|
||||
const rep = out.filter(c => c.change === 'replace');
|
||||
changed += rep.length;
|
||||
log('play', `${step(i + 1, codes.length, code)}: ${rep.length ? 'would replace ' + rep.map(c => `${c.type} (${c.remote} -> ${c.local})`).join(', ') : 'unchanged'}`);
|
||||
}
|
||||
});
|
||||
for (const [i, code] of codes.entries()) {
|
||||
const rep = changedTypes(code);
|
||||
changed += rep.length;
|
||||
log('play', `${step(i + 1, codes.length, code)}: ${rep.length ? 'would replace ' + rep.map(c => `${c.type} (${c.remote} -> ${c.local})`).join(', ') : 'unchanged'}`);
|
||||
}
|
||||
done('play', `dry run: ${changed ? changed + ' image set(s) would be replaced' : 'every image set is already on Play'}; read-only, nothing uploaded`);
|
||||
return;
|
||||
}
|
||||
for (const [i, code] of codes.entries()) {
|
||||
// only languages with a changed image type get an edit, and in it only the changed types are cleared and uploaded.
|
||||
// The edit is all or nothing: a failure (or an upload without a clear answer) deletes it, and the redo starts from
|
||||
// what Play has, so a re-run never doubles an image.
|
||||
const todo = codes.filter(code => changedTypes(code).length);
|
||||
if (!todo.length) { done('play', 'every image set is already on Play: nothing uploaded'); return; }
|
||||
for (const [i, code] of todo.entries()) {
|
||||
const set = sets.get(code)!;
|
||||
await play.edit(async id => {
|
||||
let n = 0;
|
||||
await play.edit(async (id, ctl) => {
|
||||
let n = 0, types = 0;
|
||||
await Promise.all(set.map(async ([type, files]) => {
|
||||
await play.call('DELETE', `${play.API}/edits/${id}/listings/${code}/${type}`);
|
||||
const remote = (await play.call<{ images?: { sha256?: string }[] }>('GET', `${play.API}/edits/${id}/listings/${code}/${type}`)).images ?? [];
|
||||
if (imageChange(type, remote, files.map(sha256)).change === 'same') return;
|
||||
types++;
|
||||
if (remote.length) await play.call('DELETE', `${play.API}/edits/${id}/listings/${code}/${type}`);
|
||||
for (const f of files) {
|
||||
await play.call('POST', `${play.UPLOAD}/edits/${id}/listings/${code}/${type}?uploadType=media`, new Uint8Array(readFileSync(f)),
|
||||
{ 'Content-Type': /\.png$/i.test(f) ? 'image/png' : 'image/jpeg' });
|
||||
n++;
|
||||
}
|
||||
}));
|
||||
log('play', `${step(i + 1, codes.length, code)}: ${n} images`);
|
||||
if (!types) ctl.unchanged();
|
||||
log('play', `${step(i + 1, todo.length, code)}: ${n} images in ${types} set(s)`);
|
||||
});
|
||||
}
|
||||
done('play', 'images done');
|
||||
|
|
|
|||
|
|
@ -10,10 +10,26 @@ import { readFileSync, statSync } from 'node:fs';
|
|||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { aabInfo } from '../lib/gradle';
|
||||
import { playClient } from './client';
|
||||
import { usedVersionCodes } from './next-version-code';
|
||||
import { readPlayCopy } from './listing';
|
||||
|
||||
const TRACKS = ['internal', 'alpha', 'beta', 'production'];
|
||||
|
||||
export interface PlayTrackRelease { versionCodes?: string[]; status?: string; userFraction?: number; name?: string; releaseNotes?: { language: string; text: string }[] }
|
||||
|
||||
/** The track holds exactly this release already (one release, same codes, status, fraction, name and notes): a PUT
|
||||
* would change nothing. Pure. */
|
||||
export function sameRelease(cur: PlayTrackRelease[], want: PlayTrackRelease): boolean {
|
||||
if (cur.length !== 1) return false;
|
||||
const c = cur[0]!;
|
||||
const notes = (n?: { language: string; text: string }[]) => JSON.stringify([...(n ?? [])].sort((x, y) => x.language.localeCompare(y.language)).map(x => [x.language, x.text.trim()]));
|
||||
return (c.versionCodes ?? []).map(String).join() === (want.versionCodes ?? []).join() && c.status === want.status
|
||||
&& (want.userFraction === undefined || Math.abs((c.userFraction ?? -1) - want.userFraction) < 1e-9)
|
||||
&& (want.name === undefined || c.name === want.name)
|
||||
&& (want.releaseNotes === undefined || notes(c.releaseNotes) === notes(want.releaseNotes));
|
||||
}
|
||||
const STATUSES = ['completed', 'draft', 'inProgress', 'halted'];
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
|
|
@ -33,23 +49,37 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const notes = readPlayCopy(ctx).filter(c => c.whatsNew).map(c => ({ language: c.lang, text: c.whatsNew }));
|
||||
const play = await playClient(root, pkg);
|
||||
try {
|
||||
await play.edit(async id => {
|
||||
await play.edit(async (id, ctl) => {
|
||||
let code = fixed ?? '';
|
||||
let uploaded = false;
|
||||
if (aab) {
|
||||
log('play', `uploading ${aab} (${(statSync(aab).size / 1048576).toFixed(1)} MB), this can take minutes`);
|
||||
const b = await play.call<{ versionCode: number }>('POST', `${play.UPLOAD}/edits/${id}/bundles?uploadType=media`,
|
||||
new Uint8Array(readFileSync(aab)), { 'Content-Type': 'application/octet-stream' });
|
||||
code = String(b.versionCode);
|
||||
log('play', `uploaded versionCode ${code}`);
|
||||
// a versionCode Play already has (an earlier run uploaded it) is reused, never uploaded twice
|
||||
const info = aabInfo(aab);
|
||||
if ((await usedVersionCodes(play, id)).includes(info.versionCode)) {
|
||||
code = String(info.versionCode);
|
||||
log('play', `versionCode ${code} is on Play already: not uploaded again`);
|
||||
} else {
|
||||
log('play', `uploading ${aab} (${(statSync(aab).size / 1048576).toFixed(1)} MB), this can take minutes`);
|
||||
const b = await play.call<{ versionCode: number }>('POST', `${play.UPLOAD}/edits/${id}/bundles?uploadType=media`,
|
||||
new Uint8Array(readFileSync(aab)), { 'Content-Type': 'application/octet-stream' });
|
||||
code = String(b.versionCode);
|
||||
uploaded = true;
|
||||
log('play', `uploaded versionCode ${code}`);
|
||||
}
|
||||
}
|
||||
let changed = 0;
|
||||
for (const t of tracks) {
|
||||
const release: Record<string, unknown> = { versionCodes: [code], status: t.status };
|
||||
const release: PlayTrackRelease = { versionCodes: [code], status: t.status };
|
||||
if (notes.length) release.releaseNotes = notes;
|
||||
if (a.get('name')) release.name = a.get('name');
|
||||
if (t.status === 'inProgress') release.userFraction = Number(fraction ?? 0.1);
|
||||
const cur = (await play.call<{ releases?: PlayTrackRelease[] }>('GET', `${play.API}/edits/${id}/tracks/${t.track}`).catch(() => ({ releases: [] }))).releases ?? [];
|
||||
if (sameRelease(cur, release)) { log('play', `${t.track}: already ${t.status} ${code}, unchanged`); continue; }
|
||||
await play.call('PUT', `${play.API}/edits/${id}/tracks/${t.track}`, { track: t.track, releases: [release] });
|
||||
changed++;
|
||||
log('play', `${t.track} <- ${code} (${t.status}, notes in ${notes.length} languages)`);
|
||||
}
|
||||
if (!changed && !uploaded) ctl.unchanged();
|
||||
}, { dry: a.has('dry'), retries: aab ? 0 : 3 });
|
||||
} catch (e) {
|
||||
if (/draft app|status draft/i.test(String(e)))
|
||||
|
|
|
|||
|
|
@ -10,6 +10,13 @@ import { done, log } from '../lib/log';
|
|||
import { type PlayRelease, type RolloutAction, rolloutReleases } from '../lib/release';
|
||||
import { playClient } from './client';
|
||||
|
||||
/** Same releases on the track, whatever their order and key order. Pure. */
|
||||
export function sameReleases(a: PlayRelease[], b: PlayRelease[]): boolean {
|
||||
const canon = (x: unknown): unknown => (Array.isArray(x) ? x.map(canon) : x && typeof x === 'object' ? Object.fromEntries(Object.entries(x).sort(([k], [l]) => k.localeCompare(l)).map(([k, v]) => [k, canon(v)])) : x);
|
||||
const key = (rs: PlayRelease[]) => JSON.stringify(rs.map(r => JSON.stringify(canon(r))).sort());
|
||||
return key(a) === key(b);
|
||||
}
|
||||
|
||||
export function rolloutAction(a: Ctx['args']): RolloutAction {
|
||||
const picked = ['halt', 'resume', 'complete'].filter(k => a.has(k));
|
||||
if (picked.length > 1) throw new Error('pick one of --halt, --resume, --complete');
|
||||
|
|
@ -30,10 +37,12 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const dry = ctx.args.has('dry');
|
||||
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
|
||||
let confirmed = dry || action.kind === 'halt' || track !== 'production';
|
||||
await play.edit(async id => {
|
||||
await play.edit(async (id, ctl) => {
|
||||
const cur = await play.call<{ releases?: PlayRelease[] }>('GET', `${play.API}/edits/${id}/tracks/${track}`);
|
||||
const next = rolloutReleases(cur.releases ?? [], action);
|
||||
log('play', `${track}: ${next.summary}${dry ? ' (dry)' : ''}`);
|
||||
// already like that (a re-run, or the same command twice): nothing is committed
|
||||
if (sameReleases(next.releases, cur.releases ?? [])) { ctl.unchanged(); return; }
|
||||
if (!confirmed) confirmed = await confirm(ctx, `${track}: ${next.summary}. Apply?`);
|
||||
if (!confirmed) throw new Error('not confirmed, nothing changed');
|
||||
await play.call('PUT', `${play.API}/edits/${id}/tracks/${track}`, { track, releases: next.releases });
|
||||
|
|
|
|||
|
|
@ -20,7 +20,13 @@ import {
|
|||
playSubscriptionBody,
|
||||
} from '../lib/subscriptions';
|
||||
import { subscriptionCsv } from '../apple/subscriptions';
|
||||
import { playClient } from './client';
|
||||
import { createOnce } from '../lib/upsert';
|
||||
import { playClient, type PlayClient } from './client';
|
||||
|
||||
/** GET of one Play resource, null on 404. */
|
||||
export async function getOrNull<T>(play: PlayClient, url: string): Promise<T | null> {
|
||||
try { return await play.call<T>('GET', url); } catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
|
||||
}
|
||||
|
||||
const TAG = 'play';
|
||||
interface Converted { convertedRegionPrices?: Record<string, { regionCode: string; price: Money }>; convertedOtherRegionsPrice?: { usdPrice: Money; eurPrice: Money }; regionVersion?: { version: string } }
|
||||
|
|
@ -86,8 +92,12 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const id = encodeURIComponent(s.id);
|
||||
const cur = existing.get(s.id);
|
||||
if (diff.create) {
|
||||
await play.call('POST', `${play.API}/subscriptions?productId=${id}®ionsVersion.version=${v}`, body);
|
||||
log(TAG, `${s.id}: created`);
|
||||
// product ids are unique: a 409 (or an unclear answer, then a fresh GET) finds the existing one, never a second
|
||||
const r = await createOnce({ what: `subscription ${s.id}`, tag: TAG, unique: true,
|
||||
find: () => getOrNull<PlaySubscription>(play, `${play.API}/subscriptions/${id}`),
|
||||
create: () => play.call<PlaySubscription>('POST', `${play.API}/subscriptions?productId=${id}®ionsVersion.version=${v}`, body) });
|
||||
log(TAG, `${s.id}: ${r.created ? 'created' : 'exists already (made by an earlier run); run again to compare it with the config'}`);
|
||||
if (!r.created) continue;
|
||||
} else if (diff.listings.length || diff.basePlan !== 'same') {
|
||||
if (diff.basePlan === 'changed' && diff.priceChanges.length && !liveOk) warn(TAG, `${s.id}: ${diff.priceChanges.length} price change(s) skipped (run in a terminal to confirm)`);
|
||||
else {
|
||||
|
|
@ -107,10 +117,14 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
offerRegions = { regions: Object.values(oc.convertedRegionPrices).map(r => ({ regionCode: r.regionCode, price: r.price })), other: oc.convertedOtherRegionsPrice };
|
||||
}
|
||||
const ob = playOfferBody(pkg, s, regions, offerRegions, extra);
|
||||
await play.call('POST', `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers?offerId=${encodeURIComponent(ob.offerId)}®ionsVersion.version=${v}`, ob);
|
||||
await play.call('POST', `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers/${encodeURIComponent(ob.offerId)}:activate`,
|
||||
{ packageName: pkg, productId: s.id, basePlanId: basePlanId(s), offerId: ob.offerId });
|
||||
log(TAG, `${s.id}: offer ${ob.offerId} created and activated`);
|
||||
const offerUrl = `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers`;
|
||||
// offer ids are unique per base plan: a 409 or an unclear answer finds the existing offer, never a second one
|
||||
const r = await createOnce({ what: `${s.id} offer ${ob.offerId}`, tag: TAG, unique: true,
|
||||
find: () => getOrNull<{ state?: string }>(play, `${offerUrl}/${encodeURIComponent(ob.offerId)}`),
|
||||
create: () => play.call<{ state?: string }>('POST', `${offerUrl}?offerId=${encodeURIComponent(ob.offerId)}®ionsVersion.version=${v}`, ob) });
|
||||
if (r.value.state !== 'ACTIVE')
|
||||
await play.call('POST', `${offerUrl}/${encodeURIComponent(ob.offerId)}:activate`, { packageName: pkg, productId: s.id, basePlanId: basePlanId(s), offerId: ob.offerId });
|
||||
log(TAG, `${s.id}: offer ${ob.offerId} ${r.created ? 'created and activated' : 'exists already, active'}`);
|
||||
};
|
||||
if (s.intro && offerMissing) await createOffer(s.intro);
|
||||
for (const o of (s.offers ?? []).filter(x => extraMissing.includes(x.id))) await createOffer(o, o);
|
||||
|
|
|
|||
|
|
@ -48,6 +48,12 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
used: await usedVersionCodes(play, id),
|
||||
current: (await play.call<{ releases?: { status: string; versionCodes?: string[] }[] }>('GET', `${play.API}/edits/${id}/tracks/${track}`).catch(() => ({ releases: [] }))).releases ?? [],
|
||||
}));
|
||||
// an earlier run did it already (the bundle is on Play and on this track): nothing to send again
|
||||
if (used.includes(info.versionCode) && current.some(r => (r.versionCodes ?? []).includes(String(info.versionCode)) && r.status === status)) {
|
||||
if (json) { printJson({ aab: relative(root, aab), packageName: info.packageName, versionCode: info.versionCode, track, status, uploaded: true, alreadyThere: true }); return; }
|
||||
done(TAG, `versionCode ${info.versionCode} is on ${track} (${status}) already: nothing uploaded`);
|
||||
return;
|
||||
}
|
||||
if (used.includes(info.versionCode)) throw new Error(`versionCode ${info.versionCode} is already on Google Play: rebuild with --version-code ${nextVersionCode(used)} (storebound play build)`);
|
||||
const summary = { aab: relative(root, aab), packageName: info.packageName, versionCode: info.versionCode, versionName: info.versionName ?? null, sizeMB: Math.round(size / 104857.6) / 10,
|
||||
track, status, notes: notes.map(n => n.language), replaces: current.map(r => `${r.status} ${(r.versionCodes ?? []).join(',')}`) };
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@
|
|||
// POST .../packages/{id}/actions/attach_products
|
||||
import { credentialValue } from './lib/credentials';
|
||||
import { confirm, type Ctx, need } from './lib/ctx';
|
||||
import { AmbiguousWriteError, createOnce } from './lib/upsert';
|
||||
import { errorBody } from './lib/http';
|
||||
import { done, log, printJson, warn } from './lib/log';
|
||||
import {
|
||||
|
|
@ -46,11 +47,18 @@ export function rcClient(key: string, o: { retries?: number } = {}): RcClient {
|
|||
const u = new URL(url, ORIGIN);
|
||||
if (u.origin !== ORIGIN) throw new Error(`RevenueCat: refusing to send the key to ${u.origin}`);
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const r = await fetch(u, {
|
||||
method, signal: AbortSignal.timeout(30_000),
|
||||
headers: { 'Authorization': `Bearer ${key}`, 'Accept': 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
let r: Response;
|
||||
try {
|
||||
r = await fetch(u, {
|
||||
method, signal: AbortSignal.timeout(30_000),
|
||||
headers: { 'Authorization': `Bearer ${key}`, 'Accept': 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
} catch (e) {
|
||||
// a POST without an answer may have been applied: callers look before sending it again (createOnce)
|
||||
if (method === 'POST') throw new AmbiguousWriteError(redact(`RevenueCat ${method} ${u.pathname}: no answer (${(e as Error).message})`));
|
||||
throw e;
|
||||
}
|
||||
if (r.status === 429 && attempt < (o.retries ?? 3)) {
|
||||
const s = Math.min(60, Math.max(0, Number(r.headers.get('retry-after') ?? '5') || 0));
|
||||
warn(TAG, `rate limited, waiting ${s}s`);
|
||||
|
|
@ -59,6 +67,7 @@ export function rcClient(key: string, o: { retries?: number } = {}): RcClient {
|
|||
continue;
|
||||
}
|
||||
const text = await r.text();
|
||||
if (!r.ok && r.status >= 500 && method === 'POST') throw new AmbiguousWriteError(redact(`RevenueCat ${method} ${u.pathname}: ${r.status} ${errorBody(text, 500)}`), r.status);
|
||||
if (!r.ok) {
|
||||
const hint = r.status === 401 || r.status === 403 ? ' (REVENUECAT_SECRET_KEY: a v2 secret key with project configuration permissions for this project)' : '';
|
||||
throw new Error(redact(`RevenueCat ${method} ${u.pathname}: ${r.status} ${errorBody(text, 500)}${hint}`));
|
||||
|
|
@ -172,15 +181,22 @@ export async function execute(c: RcClient, projectId: string, plan: RcStep[], st
|
|||
let offering = current?.id ?? '';
|
||||
const pkgId = new Map((current?.packages ?? []).map(p => [p.lookup_key, p.id] as const));
|
||||
const pid = (k: string) => { const id = productId.get(k); if (!id) throw new Error(`RevenueCat product ${k} was not created`); return id; };
|
||||
// creates go through createOnce: a 409 (lookup key / store identifier taken) or an unclear answer finds the existing
|
||||
// one by its key with a fresh list, never a second one; attaching and is_current are the same when sent twice
|
||||
const once = async (what: string, list: string, match: (x: J) => boolean, create: () => Promise<J>): Promise<string> =>
|
||||
(await createOnce<J>({ what, tag: TAG, unique: true, find: async () => (await c.all(list)).find(match) ?? null, create })).value.id as string;
|
||||
for (const [i, s] of plan.entries()) {
|
||||
log(TAG, `${i + 1}/${plan.length} ${s.what}`);
|
||||
switch (s.op) {
|
||||
case 'create-product': productId.set(s.key, (await c.post(`${P}/products`, s.body)).id); break;
|
||||
case 'create-entitlement': entId.set(s.lookupKey, (await c.post(`${P}/entitlements`, s.body)).id); break;
|
||||
case 'create-product': productId.set(s.key, await once(s.what, `${P}/products?limit=100`, x => x.app_id === s.body.app_id && x.store_identifier === s.body.store_identifier, () => c.post(`${P}/products`, s.body))); break;
|
||||
case 'create-entitlement': entId.set(s.lookupKey, await once(s.what, `${P}/entitlements?limit=100`, x => x.lookup_key === s.lookupKey, () => c.post(`${P}/entitlements`, s.body))); break;
|
||||
case 'attach-entitlement':
|
||||
await c.post(`${P}/entitlements/${encodeURIComponent(entId.get(s.lookupKey)!)}/actions/attach_products`, { product_ids: s.products.map(pid) }); break;
|
||||
case 'create-offering': offering = (await c.post(`${P}/offerings`, s.body)).id; break;
|
||||
case 'create-package': pkgId.set(s.lookupKey, (await c.post(`${P}/offerings/${encodeURIComponent(offering)}/packages`, s.body)).id); break;
|
||||
case 'create-offering': offering = await once(s.what, `${P}/offerings?limit=100`, x => x.lookup_key === s.lookupKey, () => c.post(`${P}/offerings`, s.body)); break;
|
||||
case 'create-package': {
|
||||
const pkgs = `${P}/offerings/${encodeURIComponent(offering)}/packages`;
|
||||
pkgId.set(s.lookupKey, await once(s.what, `${pkgs}?limit=100`, x => x.lookup_key === s.lookupKey, () => c.post(pkgs, s.body))); break;
|
||||
}
|
||||
case 'attach-package':
|
||||
await c.post(`${P}/packages/${encodeURIComponent(pkgId.get(s.lookupKey)!)}/actions/attach_products`, { products: s.products.map(k => ({ product_id: pid(k), eligibility_criteria: 'all' })) }); break;
|
||||
case 'set-current': await c.post(`${P}/offerings/${encodeURIComponent(offering)}`, { is_current: true }); break;
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@
|
|||
// Google Play's API only returns reviews created or edited in the last 7 days.
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { isConflict } from './lib/upsert';
|
||||
import { ascClient, type J } from './apple/asc';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { confirm } from './lib/ctx';
|
||||
|
|
@ -138,8 +139,14 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
for (const d of plan.send) {
|
||||
const req = replyRequest(d, config.play?.packageName);
|
||||
try {
|
||||
if (d.store === 'apple') await c!.asc(req.method, req.url, req.body);
|
||||
else await play!.call(req.method, req.url, req.body);
|
||||
// Play's :reply replaces the reply (safe to send again); Apple keeps one response per review and answers a
|
||||
// second one with 409: then an earlier run sent it (and stopped before noting it), so it is noted now
|
||||
if (d.store === 'apple') {
|
||||
try { await c!.asc(req.method, req.url, req.body); } catch (e) {
|
||||
if (!isConflict(e)) throw e;
|
||||
warn(TAG, `${d.file.split('/').pop()}: the review already has a response on the App Store (an earlier run sent it); noted as sent, not sent again`);
|
||||
}
|
||||
} else await play!.call(req.method, req.url, req.body);
|
||||
writeFileSync(d.file, markSent(texts.get(d.file)!, new Date().toISOString()));
|
||||
sent++;
|
||||
log(TAG, `sent ${d.file.split('/').pop()}`);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue