crt-ship 0.1.0: CLI, Claude Code skills and templates for shipping mobile games to Google Play and the App Store
This commit is contained in:
commit
ecb3dc3dc3
64 changed files with 4509 additions and 0 deletions
34
cli/lib/args.ts
Normal file
34
cli/lib/args.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// Tiny argv parser: positionals, --flag, --key value, --key=value.
|
||||
export interface Args {
|
||||
_: string[];
|
||||
has(name: string): boolean;
|
||||
get(name: string): string | undefined;
|
||||
str(name: string, d: string): string;
|
||||
num(name: string, d: number): number;
|
||||
list(name: string): string[];
|
||||
}
|
||||
|
||||
export function parseArgs(argv: string[], booleans: string[] = []): Args {
|
||||
const flags = new Map<string, string>();
|
||||
const _: string[] = [];
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', ...booleans]);
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]!;
|
||||
if (!a.startsWith('--')) { _.push(a); continue; }
|
||||
const eq = a.indexOf('=');
|
||||
if (eq > 0) { flags.set(a.slice(2, eq), a.slice(eq + 1)); continue; }
|
||||
const name = a.slice(2);
|
||||
const next = argv[i + 1];
|
||||
if (bool.has(name) || name.startsWith('no-') || next === undefined || next.startsWith('--')) flags.set(name, 'true');
|
||||
else { flags.set(name, next); i++; }
|
||||
}
|
||||
const get = (n: string) => flags.get(n);
|
||||
return {
|
||||
_,
|
||||
has: n => flags.has(n),
|
||||
get,
|
||||
str: (n, d) => get(n) ?? d,
|
||||
num: (n, d) => { const v = get(n); const x = v === undefined ? d : Number(v); if (Number.isNaN(x)) throw new Error(`--${n}: not a number`); return x; },
|
||||
list: n => (get(n) ?? '').split(',').map(s => s.trim()).filter(Boolean),
|
||||
};
|
||||
}
|
||||
252
cli/lib/config.ts
Normal file
252
cli/lib/config.ts
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
// Per-project config (crt-ship.config.ts at the project root). Everything game-specific lives here; credentials never
|
||||
// do (see credentials.ts). The file default-exports a plain object; `import type { ShipConfig }` is optional.
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
||||
|
||||
export type ProductType = 'consumable' | 'non_consumable';
|
||||
|
||||
export interface PriceOverride {
|
||||
/** ISO 3166-1 alpha-2 region for Play, e.g. "TR". */
|
||||
region: string;
|
||||
/** App Store territory (alpha-3), e.g. "TUR". Looked up from `region` when left out. */
|
||||
territory?: string;
|
||||
/** ISO 4217 currency, e.g. "TRY". */
|
||||
currency: string;
|
||||
/** Customer price in that currency, e.g. 129.99. Apple needs an existing price point with exactly this value. */
|
||||
price: number;
|
||||
}
|
||||
|
||||
export interface ProductListing { title: string; description: string }
|
||||
|
||||
export interface Product {
|
||||
/** Store product id (same on both stores), e.g. "com.example.game.no_ads". */
|
||||
id: string;
|
||||
type: ProductType;
|
||||
/** Base price in USD. Play converts it per region (convertRegionPrices); Apple equalizes it from the USA base. */
|
||||
usd: number;
|
||||
overrides?: PriceOverride[];
|
||||
/** Language id (see `languages`) -> title + description. Apple caps the description at 55 characters. */
|
||||
listings: Record<string, ProductListing>;
|
||||
/** Apple only: internal reference name (defaults to the first listing title). */
|
||||
referenceName?: string;
|
||||
/** Apple only: note for the reviewer on this product. */
|
||||
reviewNote?: string;
|
||||
/** Apple only: review screenshot (path relative to the project root). */
|
||||
reviewScreenshot?: string;
|
||||
familySharable?: boolean;
|
||||
}
|
||||
|
||||
export interface Language {
|
||||
/** Your id for the language; also the folder name under the renders dir and the key in copy files. */
|
||||
id: string;
|
||||
/** Play listing language code(s), e.g. "en-US" or ["es-ES", "es-419"]. Leave out to skip on Play. */
|
||||
play?: string | string[];
|
||||
/** App Store Connect locale, e.g. "en-US", "tr", "zh-Hans". Leave out to skip on the App Store. */
|
||||
apple?: string;
|
||||
rtl?: boolean;
|
||||
}
|
||||
|
||||
export type PlayPurpose = 'functionality' | 'analytics' | 'communications' | 'fraud' | 'advertising' | 'personalization' | 'account';
|
||||
|
||||
export interface DataUsage {
|
||||
/** Transferred to a third party that is not your service provider (ad networks usually are "shared"). */
|
||||
shared: boolean;
|
||||
ephemeral?: boolean;
|
||||
/** Only true when the user can really choose (Play rejects "optional" otherwise). */
|
||||
optional?: boolean;
|
||||
collect: PlayPurpose[];
|
||||
share?: PlayPurpose[];
|
||||
}
|
||||
|
||||
export interface DataSafety {
|
||||
collectsData: boolean;
|
||||
encryptedInTransit: boolean;
|
||||
deletionRequest: boolean;
|
||||
/** Response ids for PSL_SUPPORTED_ACCOUNT_CREATION_METHODS. Default ["PSL_ACM_NONE"] (no accounts). */
|
||||
accountCreation?: string[];
|
||||
/** Play data type id (e.g. "PSL_DEVICE_ID") -> usage. Types not listed are "not collected". */
|
||||
data: Record<string, DataUsage>;
|
||||
}
|
||||
|
||||
export interface ShotBadgeSlot { y: number; side: 'l' | 'r'; icon?: string; iconBg?: string; hot?: boolean; stars?: boolean; rot?: number }
|
||||
export interface ShotFrame { src: string; x?: number; dy?: number; scale?: number; rotate?: number }
|
||||
export interface Palette { bg: [string, string, string]; glow: string; ink: string; shadow: string }
|
||||
export interface ShotScene { id: string; palette: string | Palette; hero?: boolean; frames: ShotFrame[]; badges?: ShotBadgeSlot[]; over?: number }
|
||||
|
||||
export interface ShotsConfig {
|
||||
/** JSON file: { [languageId]: { [sceneId]: { eyebrow, title: [line1, line2], sub, badges: [[big, small?]] } } } */
|
||||
copy: string;
|
||||
/** Raw frames: <frames>/<languageId>/<phone|tablet>/<name>.png */
|
||||
frames: string;
|
||||
/** Output: <out>/<languageId>/<size>/NN.png and feature/1024x500.png */
|
||||
out: string;
|
||||
/** Optional logo image for the hero scene and the feature graphic. */
|
||||
logo?: string;
|
||||
/** Google Fonts families for titles / body text (downloaded and subset by `shots fonts`). */
|
||||
fonts?: { title?: string; body?: string };
|
||||
scenes: ShotScene[];
|
||||
feature?: { frame: string; palette?: string | Palette };
|
||||
/** Phone screen size of the raw frames in CSS px (default 440 x 902, iPhone 6.9" minus the 54 px status bar). */
|
||||
phone?: { w: number; h: number; dpr?: number };
|
||||
tablet?: { w: number; h: number; dpr?: number };
|
||||
/** Optional capture of raw frames from a running build of your game. */
|
||||
capture?: {
|
||||
baseUrl: string;
|
||||
/** Appended to every URL, e.g. "noads=1&noanalytics=1". "{lang}" is replaced. */
|
||||
query?: string;
|
||||
shots: Record<string, { path: string; waitFor?: string; delayMs?: number; eval?: string[]; device?: 'phone' | 'tablet' | 'both' }>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IconsConfig {
|
||||
/** 1024 opaque composite (the full icon). */
|
||||
composite: string;
|
||||
/** 1024 RGBA subject on transparent background (adaptive foreground). */
|
||||
foreground?: string;
|
||||
/** 1024 opaque background (adaptive background). */
|
||||
background?: string;
|
||||
/** Output dir for the store icons (app-store-1024.png, play-512.png). */
|
||||
out: string;
|
||||
/** Web icons (icon-512/192/180, favicon-64/32, maskable-512). */
|
||||
web?: string;
|
||||
/** @capacitor/assets source dir (icon-only, icon-foreground, icon-background). */
|
||||
capacitorAssets?: string;
|
||||
/** Command to run after writing the capacitor sources, e.g. "bunx @capacitor/assets generate". */
|
||||
capacitorCommand?: string;
|
||||
/** Android res dir; legacy ic_launcher{,_round}.png get redrawn from the adaptive layers. */
|
||||
androidRes?: string;
|
||||
adaptiveScale?: number;
|
||||
maskableScale?: number;
|
||||
}
|
||||
|
||||
export interface AppleAppInfo {
|
||||
categories?: { primary: string; primarySubOne?: string; primarySubTwo?: string; secondary?: string };
|
||||
/** Overrides for the age rating declaration; everything else is NONE / false. */
|
||||
ageRating?: Record<string, string | boolean | null>;
|
||||
contentRights?: 'DOES_NOT_USE_THIRD_PARTY_CONTENT' | 'USES_THIRD_PARTY_CONTENT';
|
||||
/** Free app, available in every territory and new ones. */
|
||||
free?: boolean;
|
||||
reviewNotes?: string;
|
||||
}
|
||||
|
||||
export interface ShipConfig {
|
||||
app: {
|
||||
name: string;
|
||||
copyright?: string;
|
||||
privacyPolicyUrl: string;
|
||||
supportUrl: string;
|
||||
marketingUrl?: string;
|
||||
website: string;
|
||||
contactEmail: string;
|
||||
};
|
||||
languages: Language[];
|
||||
play?: { packageName: string; defaultLanguage?: string; listing?: string; icon?: string };
|
||||
apple?: { bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string };
|
||||
products?: Product[];
|
||||
dataSafety?: DataSafety;
|
||||
/** Rendered store graphics dir (<renders>/<languageId>/<size>/NN.png|jpg). Defaults to shots.out. */
|
||||
renders?: string;
|
||||
shots?: ShotsConfig;
|
||||
icons?: IconsConfig;
|
||||
}
|
||||
|
||||
/** Identity helper for typed configs: `export default defineConfig({...})`. */
|
||||
export const defineConfig = (c: ShipConfig): ShipConfig => c;
|
||||
|
||||
const ID_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/;
|
||||
const PRODUCT_RE = /^[A-Za-z0-9._]+$/;
|
||||
const URL_RE = /^https:\/\/\S+$/;
|
||||
|
||||
/** Every problem with a config, empty when it is fine. Pure (no IO). */
|
||||
export function validateConfig(c: unknown): string[] {
|
||||
const e: string[] = [];
|
||||
const cfg = c as Partial<ShipConfig>;
|
||||
if (!cfg || typeof cfg !== 'object') return ['config must be an object'];
|
||||
const app = cfg.app;
|
||||
if (!app) e.push('app: missing');
|
||||
else {
|
||||
if (!app.name) e.push('app.name: missing');
|
||||
for (const k of ['privacyPolicyUrl', 'supportUrl', 'website'] as const) if (!URL_RE.test(app[k] ?? '')) e.push(`app.${k}: must be an https URL`);
|
||||
if (app.marketingUrl && !URL_RE.test(app.marketingUrl)) e.push('app.marketingUrl: must be an https URL');
|
||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(app.contactEmail ?? '')) e.push('app.contactEmail: not an email address');
|
||||
}
|
||||
const langs = cfg.languages;
|
||||
if (!Array.isArray(langs) || !langs.length) e.push('languages: at least one language');
|
||||
const ids = new Set<string>();
|
||||
for (const [i, l] of (langs ?? []).entries()) {
|
||||
if (!l.id) e.push(`languages[${i}].id: missing`);
|
||||
if (ids.has(l.id)) e.push(`languages[${i}].id: duplicate "${l.id}"`);
|
||||
ids.add(l.id);
|
||||
}
|
||||
if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)');
|
||||
if (cfg.apple) {
|
||||
if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)');
|
||||
if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)');
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
for (const [i, p] of (cfg.products ?? []).entries()) {
|
||||
const at = `products[${i}]`;
|
||||
if (!PRODUCT_RE.test(p.id ?? '')) e.push(`${at}.id: letters, digits, "." and "_" only`);
|
||||
if (seen.has(p.id)) e.push(`${at}.id: duplicate "${p.id}"`);
|
||||
seen.add(p.id);
|
||||
if (p.type !== 'consumable' && p.type !== 'non_consumable') e.push(`${at}.type: consumable | non_consumable`);
|
||||
if (!(typeof p.usd === 'number' && p.usd > 0)) e.push(`${at}.usd: positive number`);
|
||||
if (!p.listings || !Object.keys(p.listings).length) e.push(`${at}.listings: at least one language`);
|
||||
for (const [lang, l] of Object.entries(p.listings ?? {})) {
|
||||
if (!ids.has(lang)) e.push(`${at}.listings.${lang}: not in languages`);
|
||||
if (!l.title) e.push(`${at}.listings.${lang}.title: missing`);
|
||||
if ([...(l.title ?? '')].length > 30) e.push(`${at}.listings.${lang}.title: over 30 characters (App Store limit)`);
|
||||
if (!l.description) e.push(`${at}.listings.${lang}.description: missing`);
|
||||
}
|
||||
for (const o of p.overrides ?? []) {
|
||||
if (!/^[A-Z]{2}$/.test(o.region)) e.push(`${at}.overrides: region "${o.region}" must be ISO alpha-2 (TR)`);
|
||||
if (!/^[A-Z]{3}$/.test(o.currency)) e.push(`${at}.overrides: currency "${o.currency}" must be ISO 4217 (TRY)`);
|
||||
if (!(o.price > 0)) e.push(`${at}.overrides: price must be positive`);
|
||||
}
|
||||
}
|
||||
if (cfg.dataSafety) {
|
||||
for (const [t, u] of Object.entries(cfg.dataSafety.data ?? {})) {
|
||||
if (!/^PSL_[A-Z_]+$/.test(t)) e.push(`dataSafety.data.${t}: use the Play type id (PSL_DEVICE_ID, ...)`);
|
||||
if (!u.collect?.length) e.push(`dataSafety.data.${t}: at least one collection purpose`);
|
||||
if (u.shared && !u.share?.length) e.push(`dataSafety.data.${t}: shared, so it needs sharing purposes`);
|
||||
}
|
||||
}
|
||||
if (cfg.shots) {
|
||||
const s = cfg.shots;
|
||||
for (const k of ['copy', 'frames', 'out'] as const) if (!s[k]) e.push(`shots.${k}: missing`);
|
||||
if (!s.scenes?.length) e.push('shots.scenes: at least one scene');
|
||||
for (const sc of s.scenes ?? []) if (!sc.frames?.length) e.push(`shots.scenes[${sc.id}].frames: at least one frame`);
|
||||
}
|
||||
if (cfg.icons) {
|
||||
if (!cfg.icons.composite) e.push('icons.composite: missing');
|
||||
if (!cfg.icons.out) e.push('icons.out: missing');
|
||||
if (cfg.icons.androidRes && !(cfg.icons.foreground && cfg.icons.background)) e.push('icons.androidRes needs icons.foreground + icons.background');
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
export interface Loaded { config: ShipConfig; root: string; path: string; resolve(p: string): string }
|
||||
|
||||
const NAMES = ['crt-ship.config.ts', 'crt-ship.config.js', 'crt-ship.config.json'];
|
||||
|
||||
/** Finds crt-ship.config.* from `start` upwards (or uses `explicit`), imports and validates it. */
|
||||
export async function loadConfig(explicit?: string, start = process.cwd()): Promise<Loaded> {
|
||||
let path = explicit ? resolve(explicit) : '';
|
||||
if (!path) {
|
||||
for (let d = resolve(start); ; d = dirname(d)) {
|
||||
const hit = NAMES.map(n => join(d, n)).find(existsSync);
|
||||
if (hit) { path = hit; break; }
|
||||
if (dirname(d) === d) break;
|
||||
}
|
||||
}
|
||||
if (!path || !existsSync(path)) throw new Error('no crt-ship.config.ts found (run `crt-ship init` or pass --config)');
|
||||
const mod = await import(path);
|
||||
const config = (mod.default ?? mod) as ShipConfig;
|
||||
const errors = validateConfig(config);
|
||||
if (errors.length) throw new Error(`${path}:\n ` + errors.join('\n '));
|
||||
const root = dirname(path);
|
||||
return { config, root, path, resolve: (p: string) => (isAbsolute(p) ? p : join(root, p)) };
|
||||
}
|
||||
|
||||
/** Play language codes of a language entry. */
|
||||
export const playCodes = (l: Language): string[] => (l.play === undefined ? [] : Array.isArray(l.play) ? l.play : [l.play]);
|
||||
81
cli/lib/copy.ts
Normal file
81
cli/lib/copy.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
// Store copy lives in two human-edited Markdown files (templates/listing.md, templates/appstore.md). Pure parsers +
|
||||
// limit checks; the consoles count characters (code points), so do we.
|
||||
|
||||
export const PLAY_LIMITS = { title: 30, short: 80, full: 4000, whatsNew: 500 } as const;
|
||||
export const APPLE_LIMITS = { name: 30, subtitle: 30, promotionalText: 170, keywords: 100, description: 4000, whatsNew: 4000 } as const;
|
||||
|
||||
export interface PlayCopy { lang: string; title: string; short: string; full: string; whatsNew: string }
|
||||
export type AppleField = keyof typeof APPLE_LIMITS;
|
||||
export type AppleCopy = Partial<Record<AppleField, string>>;
|
||||
|
||||
export const len = (s: string): number => [...s].length;
|
||||
|
||||
/** "### heading" sub-sections of a "## " section, each with its first fenced block. */
|
||||
function blocks(section: string): { heading: string; text: string }[] {
|
||||
const out: { heading: string; text: string }[] = [];
|
||||
for (const part of section.split(/^### /m).slice(1)) {
|
||||
const heading = part.split('\n')[0]!.trim();
|
||||
const m = /^```[^\n]*\n([\s\S]*?)\n```/m.exec(part);
|
||||
if (m) out.push({ heading, text: m[1]!.trim() });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Play copy. Every "## ..." section with a `<!-- play: en-US[, en-GB] -->` line contributes, under "### " headings
|
||||
* that contain (case-insensitive): "title" (optional, defaults to `defaultTitle`), "short", "full", "what's new"
|
||||
* (or "release notes"). One section can serve several Play languages.
|
||||
*/
|
||||
export function parsePlayListing(md: string, defaultTitle: string): PlayCopy[] {
|
||||
const out: PlayCopy[] = [];
|
||||
const errors: string[] = [];
|
||||
for (const sec of md.split(/^## /m).slice(1)) {
|
||||
const m = /^<!--\s*play:\s*([^>]+?)\s*-->$/m.exec(sec);
|
||||
if (!m) continue;
|
||||
const name = sec.split('\n')[0]!.trim();
|
||||
const bs = blocks(sec);
|
||||
const find = (re: RegExp): string | undefined => bs.find(b => re.test(b.heading))?.text;
|
||||
const title = find(/\btitle\b/i) ?? defaultTitle;
|
||||
const short = find(/\bshort\b/i);
|
||||
const full = find(/\bfull\b/i);
|
||||
const whatsNew = find(/what'?s new|release notes/i) ?? '';
|
||||
if (!short) errors.push(`"${name}": no "### ... short ..." block`);
|
||||
if (!full) errors.push(`"${name}": no "### ... full ..." block`);
|
||||
if (!short || !full) continue;
|
||||
for (const lang of m[1]!.split(',').map(s => s.trim()).filter(Boolean)) {
|
||||
const c: PlayCopy = { lang, title, short, full, whatsNew };
|
||||
for (const k of Object.keys(PLAY_LIMITS) as (keyof typeof PLAY_LIMITS)[])
|
||||
if (len(c[k]) > PLAY_LIMITS[k]) errors.push(`${lang}: ${k} is ${len(c[k])} > ${PLAY_LIMITS[k]}`);
|
||||
if (out.some(o => o.lang === lang)) errors.push(`${lang}: listed in two sections`);
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
if (errors.length) throw new Error('listing: ' + errors.join('; '));
|
||||
return out;
|
||||
}
|
||||
|
||||
const APPLE_REQUIRED: AppleField[] = ['subtitle', 'promotionalText', 'keywords', 'description'];
|
||||
|
||||
/**
|
||||
* App Store copy. One "## <ASC locale> ..." section per locale (the first word is the locale), with "### <field>"
|
||||
* headings named exactly like the API attributes: name (optional), subtitle, promotionalText, keywords, description,
|
||||
* whatsNew (optional; not allowed on a first version).
|
||||
*/
|
||||
export function parseAppStoreListing(md: string): Record<string, AppleCopy> {
|
||||
const out: Record<string, AppleCopy> = {};
|
||||
const errors: string[] = [];
|
||||
for (const sec of md.split(/^## /m).slice(1)) {
|
||||
const locale = sec.split(/[\s·]/)[0]!.trim();
|
||||
if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(locale)) continue; // prose sections
|
||||
const f: AppleCopy = {};
|
||||
for (const b of blocks(sec)) if (b.heading in APPLE_LIMITS) f[b.heading as AppleField] = b.text;
|
||||
for (const k of APPLE_REQUIRED) if (!f[k]) errors.push(`${locale}: missing ${k}`);
|
||||
for (const [k, v] of Object.entries(f) as [AppleField, string][])
|
||||
if (len(v) > APPLE_LIMITS[k]) errors.push(`${locale}: ${k} is ${len(v)} > ${APPLE_LIMITS[k]}`);
|
||||
if (f.keywords && Buffer.byteLength(f.keywords) > 100) errors.push(`${locale}: keywords are ${Buffer.byteLength(f.keywords)} bytes > 100`);
|
||||
if (f.keywords && /,\s/.test(f.keywords)) errors.push(`${locale}: keywords: no spaces after commas (they count)`);
|
||||
out[locale] = f;
|
||||
}
|
||||
if (errors.length) throw new Error('appstore listing: ' + errors.join('; '));
|
||||
return out;
|
||||
}
|
||||
61
cli/lib/credentials.ts
Normal file
61
cli/lib/credentials.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// Credentials never live in crt-ship.config.ts or in git. Sources, first hit wins:
|
||||
// 1. environment: PLAY_SERVICE_ACCOUNT (path to the JSON key, or the JSON itself), ASC_KEY_ID, ASC_ISSUER_ID,
|
||||
// ASC_P8 (path to AuthKey_<id>.p8, or the PEM itself)
|
||||
// 2. <project>/.crt-ship/credentials.json (gitignored), same names:
|
||||
// { "PLAY_SERVICE_ACCOUNT": "...", "ASC_KEY_ID": "...", "ASC_ISSUER_ID": "...", "ASC_P8": "...",
|
||||
// "reviewContact": { "firstName": "", "lastName": "", "phone": "", "email": "" } }
|
||||
// 3. ASC_P8 only: ~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8 (where Xcode / altool keep it)
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export interface ServiceAccount { client_email: string; private_key: string; token_uri?: string }
|
||||
export interface AscKey { keyId: string; issuerId: string; pem: string }
|
||||
export interface ReviewContact { firstName: string; lastName: string; phone: string; email: string }
|
||||
|
||||
type Store = Record<string, unknown>;
|
||||
|
||||
function fileStore(root: string): Store {
|
||||
const p = join(root, '.crt-ship', 'credentials.json');
|
||||
if (!existsSync(p)) return {};
|
||||
try { return JSON.parse(readFileSync(p, 'utf8')) as Store; } catch (e) { throw new Error(`${p}: ${(e as Error).message}`); }
|
||||
}
|
||||
|
||||
function value(root: string, name: string): string | undefined {
|
||||
const env = process.env[name];
|
||||
if (env) return env;
|
||||
const v = fileStore(root)[name];
|
||||
return typeof v === 'string' && v ? v : undefined;
|
||||
}
|
||||
|
||||
/** A path or the inline content itself. */
|
||||
const inline = (v: string, marker: RegExp): string => (marker.test(v) ? v : readFileSync(v.replace(/^~(?=\/)/, homedir()), 'utf8'));
|
||||
|
||||
export function parseServiceAccount(text: string): ServiceAccount {
|
||||
const j = JSON.parse(text) as Partial<ServiceAccount>;
|
||||
if (typeof j.client_email !== 'string' || typeof j.private_key !== 'string' || !j.private_key.includes('PRIVATE KEY'))
|
||||
throw new Error('not a Google service account JSON key (client_email / private_key missing)');
|
||||
return { client_email: j.client_email, private_key: j.private_key, token_uri: j.token_uri };
|
||||
}
|
||||
|
||||
export function playServiceAccount(root: string): ServiceAccount {
|
||||
const v = value(root, 'PLAY_SERVICE_ACCOUNT');
|
||||
if (!v) throw new Error('PLAY_SERVICE_ACCOUNT is not set (env, or .crt-ship/credentials.json): path to the service account JSON key');
|
||||
return parseServiceAccount(inline(v, /^\s*\{/));
|
||||
}
|
||||
|
||||
export function ascKey(root: string): AscKey {
|
||||
const keyId = value(root, 'ASC_KEY_ID');
|
||||
const issuerId = value(root, 'ASC_ISSUER_ID');
|
||||
if (!keyId || !issuerId) throw new Error('ASC_KEY_ID and ASC_ISSUER_ID are not set (env, or .crt-ship/credentials.json)');
|
||||
const p8 = value(root, 'ASC_P8') ?? join(homedir(), '.appstoreconnect/private_keys', `AuthKey_${keyId}.p8`);
|
||||
if (!/BEGIN PRIVATE KEY/.test(p8) && !existsSync(p8.replace(/^~(?=\/)/, homedir()))) throw new Error(`App Store Connect key not found: ${p8} (set ASC_P8)`);
|
||||
return { keyId, issuerId, pem: inline(p8, /BEGIN PRIVATE KEY/) };
|
||||
}
|
||||
|
||||
/** App Review contact from .crt-ship/credentials.json (personal data, so never in the config). */
|
||||
export function reviewContact(root: string): ReviewContact | null {
|
||||
const c = fileStore(root).reviewContact as Partial<ReviewContact> | undefined;
|
||||
if (!c?.email) return null;
|
||||
return { firstName: c.firstName ?? '', lastName: c.lastName ?? '', phone: c.phone ?? '', email: c.email };
|
||||
}
|
||||
31
cli/lib/ctx.ts
Normal file
31
cli/lib/ctx.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import type { Args } from './args';
|
||||
import type { Language, Loaded } from './config';
|
||||
import { playCodes } from './config';
|
||||
|
||||
export interface Ctx { loaded: Loaded; args: Args }
|
||||
|
||||
export function need<T>(v: T | undefined, what: string): T {
|
||||
if (v === undefined || v === null) throw new Error(`crt-ship.config.ts: ${what} is not set`);
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Play language code -> language entry. */
|
||||
export function byPlayCode(langs: Language[]): Map<string, Language> {
|
||||
const m = new Map<string, Language>();
|
||||
for (const l of langs) for (const c of playCodes(l)) m.set(c, l);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** App Store locale -> language entry. */
|
||||
export function byAppleLocale(langs: Language[]): Map<string, Language> {
|
||||
return new Map(langs.filter(l => l.apple).map(l => [l.apple!, l] as const));
|
||||
}
|
||||
|
||||
/** Asks on the terminal unless --yes. Store actions that are public or irreversible go through this. */
|
||||
export async function confirm(ctx: Ctx, question: string): Promise<boolean> {
|
||||
if (ctx.args.has('yes')) return true;
|
||||
if (!process.stdin.isTTY) { console.log(`${question}\n not a terminal: re-run with --yes to confirm`); return false; }
|
||||
process.stdout.write(`${question} [y/N] `);
|
||||
for await (const line of console) return /^y(es)?$/i.test(line.trim());
|
||||
return false;
|
||||
}
|
||||
69
cli/lib/data-safety.ts
Normal file
69
cli/lib/data-safety.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// Google Play Data safety form as Play's CSV import format (the same layout Play Console exports from the Data safety
|
||||
// page: "Export to CSV"). One row per question / choice. Importing replaces every earlier answer. Pure.
|
||||
// Play names a missing answer "Response missing for <ID>" and a wrong choice "Invalid response ID <ID>".
|
||||
import type { DataSafety, PlayPurpose } from './config';
|
||||
|
||||
export const PURPOSE_IDS: Record<PlayPurpose, string> = {
|
||||
functionality: 'PSL_APP_FUNCTIONALITY',
|
||||
analytics: 'PSL_ANALYTICS',
|
||||
communications: 'PSL_DEVELOPER_COMMUNICATIONS',
|
||||
fraud: 'PSL_FRAUD_PREVENTION_SECURITY',
|
||||
advertising: 'PSL_ADVERTISING',
|
||||
personalization: 'PSL_PERSONALIZATION',
|
||||
account: 'PSL_ACCOUNT_MANAGEMENT',
|
||||
};
|
||||
const PURPOSES = Object.values(PURPOSE_IDS);
|
||||
|
||||
/** Every category and data type of the form, in form order. */
|
||||
export const CATEGORIES: [string, string[]][] = [
|
||||
['PSL_DATA_TYPES_PERSONAL', ['PSL_NAME', 'PSL_EMAIL', 'PSL_USER_ACCOUNT', 'PSL_ADDRESS', 'PSL_PHONE', 'PSL_RACE_ETHNICITY', 'PSL_POLITICAL_RELIGIOUS', 'PSL_SEXUAL_ORIENTATION_GENDER_IDENTITY', 'PSL_OTHER_PERSONAL']],
|
||||
['PSL_DATA_TYPES_FINANCIAL', ['PSL_PURCHASE_HISTORY', 'PSL_CREDIT_SCORE', 'PSL_CREDIT_DEBIT_BANK_ACCOUNT_NUMBER', 'PSL_OTHER']],
|
||||
['PSL_DATA_TYPES_LOCATION', ['PSL_APPROX_LOCATION', 'PSL_PRECISE_LOCATION']],
|
||||
['PSL_DATA_TYPES_SEARCH_AND_BROWSING', ['PSL_WEB_BROWSING_HISTORY']],
|
||||
['PSL_DATA_TYPES_EMAIL_AND_TEXT', ['PSL_EMAILS', 'PSL_SMS_CALL_LOG', 'PSL_OTHER_MESSAGES']],
|
||||
['PSL_DATA_TYPES_PHOTOS_AND_VIDEOS', ['PSL_PHOTOS', 'PSL_VIDEOS']],
|
||||
['PSL_DATA_TYPES_AUDIO', ['PSL_AUDIO', 'PSL_MUSIC', 'PSL_OTHER_AUDIO']],
|
||||
['PSL_DATA_TYPES_HEALTH_AND_FITNESS', ['PSL_HEALTH', 'PSL_FITNESS']],
|
||||
['PSL_DATA_TYPES_CONTACTS', ['PSL_CONTACTS']],
|
||||
['PSL_DATA_TYPES_CALENDAR', ['PSL_CALENDAR']],
|
||||
['PSL_DATA_TYPES_APP_PERFORMANCE', ['PSL_CRASH_LOGS', 'PSL_PERFORMANCE_DIAGNOSTICS', 'PSL_OTHER_PERFORMANCE']],
|
||||
['PSL_DATA_TYPES_FILES_AND_DOCS', ['PSL_FILES_AND_DOCS']],
|
||||
['PSL_DATA_TYPES_APP_ACTIVITY', ['PSL_USER_INTERACTION', 'PSL_IN_APP_SEARCH_HISTORY', 'PSL_APPS_ON_DEVICE', 'PSL_USER_GENERATED_CONTENT', 'PSL_OTHER_APP_ACTIVITY']],
|
||||
['PSL_DATA_TYPES_IDENTIFIERS', ['PSL_DEVICE_ID']],
|
||||
];
|
||||
export const ALL_TYPES = new Set(CATEGORIES.flatMap(([, t]) => t));
|
||||
|
||||
const HEADER = ['Question ID (machine readable)', 'Response ID (machine readable)', 'Response value', 'Answer requirement', 'Human-friendly question label'];
|
||||
|
||||
export function csvCell(s: string): string { return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; }
|
||||
|
||||
export function dataSafetyRows(ds: DataSafety): string[][] {
|
||||
for (const t of Object.keys(ds.data)) if (!ALL_TYPES.has(t)) throw new Error(`dataSafety: unknown data type ${t}`);
|
||||
const b = (v: boolean) => (v ? 'TRUE' : 'FALSE');
|
||||
const pick = (v: boolean) => (v ? 'TRUE' : '');
|
||||
const rows: string[][] = [HEADER];
|
||||
rows.push(['PSL_DATA_COLLECTION_COLLECTS_PERSONAL_DATA', '', b(ds.collectsData), 'REQUIRED', 'Does your app collect or share any of the required user data types?']);
|
||||
rows.push(['PSL_DATA_COLLECTION_ENCRYPTED_IN_TRANSIT', '', b(ds.encryptedInTransit), 'MAYBE_REQUIRED', 'Is all of the user data collected by your app encrypted in transit?']);
|
||||
rows.push(['PSL_DATA_COLLECTION_USER_REQUEST_DELETE', '', b(ds.deletionRequest), 'MAYBE_REQUIRED', 'Do you provide a way for users to request that their data is deleted?']);
|
||||
// Newer form question that Google's older sample CSV does not have; the import fails without it.
|
||||
for (const id of ds.accountCreation ?? ['PSL_ACM_NONE'])
|
||||
rows.push(['PSL_SUPPORTED_ACCOUNT_CREATION_METHODS', id, 'TRUE', 'MULTIPLE_CHOICE', `Account creation / ${id}`]);
|
||||
for (const [cat, types] of CATEGORIES) for (const t of types) rows.push([cat, t, pick(!!ds.data[t]), 'MULTIPLE_CHOICE', `${cat} / ${t}`]);
|
||||
for (const [, types] of CATEGORIES) for (const t of types) {
|
||||
const u = ds.data[t];
|
||||
const q = (s: string) => `PSL_DATA_USAGE_RESPONSES:${t}:${s}`;
|
||||
const label = `Data usage and handling (${t})`;
|
||||
const collect = new Set((u?.collect ?? []).map(p => PURPOSE_IDS[p]));
|
||||
const share = new Set((u?.shared ? u.share ?? [] : []).map(p => PURPOSE_IDS[p]));
|
||||
rows.push([q('PSL_DATA_USAGE_COLLECTION_AND_SHARING'), 'PSL_DATA_USAGE_ONLY_COLLECTED', pick(!!u), 'MULTIPLE_CHOICE', label + ' / Collected']);
|
||||
rows.push([q('PSL_DATA_USAGE_COLLECTION_AND_SHARING'), 'PSL_DATA_USAGE_ONLY_SHARED', pick(!!u?.shared), 'MULTIPLE_CHOICE', label + ' / Shared']);
|
||||
rows.push([q('PSL_DATA_USAGE_EPHEMERAL'), '', u ? b(!!u.ephemeral) : '', 'MAYBE_REQUIRED', label + ' / Processed ephemerally']);
|
||||
rows.push([q('DATA_USAGE_USER_CONTROL'), 'PSL_DATA_USAGE_USER_CONTROL_OPTIONAL', pick(!!u?.optional), 'SINGLE_CHOICE', label + ' / Optional']);
|
||||
rows.push([q('DATA_USAGE_USER_CONTROL'), 'PSL_DATA_USAGE_USER_CONTROL_REQUIRED', pick(!!u && !u.optional), 'SINGLE_CHOICE', label + ' / Required']);
|
||||
for (const p of PURPOSES) rows.push([q('DATA_USAGE_COLLECTION_PURPOSE'), p, pick(collect.has(p)), 'MULTIPLE_CHOICE', label + ' / Collection purpose']);
|
||||
for (const p of PURPOSES) rows.push([q('DATA_USAGE_SHARING_PURPOSE'), p, pick(share.has(p)), 'MULTIPLE_CHOICE', label + ' / Sharing purpose']);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export const dataSafetyCsv = (ds: DataSafety): string => dataSafetyRows(ds).map(r => r.map(csvCell).join(',')).join('\n') + '\n';
|
||||
40
cli/lib/google-auth.ts
Normal file
40
cli/lib/google-auth.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// OAuth 2.0 service account flow (RS256 JWT assertion -> access token) with WebCrypto, no googleapis dependency.
|
||||
import type { ServiceAccount } from './credentials';
|
||||
|
||||
export const PLAY_SCOPE = 'https://www.googleapis.com/auth/androidpublisher';
|
||||
const b64u = (b: ArrayBuffer | string): string => Buffer.from(typeof b === 'string' ? b : new Uint8Array(b)).toString('base64url');
|
||||
|
||||
function pemToDer(pem: string): ArrayBuffer {
|
||||
const bytes = Buffer.from(pem.replace(/-----(BEGIN|END) PRIVATE KEY-----/g, '').replace(/\s+/g, ''), 'base64');
|
||||
const out = new ArrayBuffer(bytes.length);
|
||||
new Uint8Array(out).set(bytes);
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function signAssertion(sa: ServiceAccount, nowS: number, scope = PLAY_SCOPE): Promise<string> {
|
||||
const key = await crypto.subtle.importKey('pkcs8', pemToDer(sa.private_key), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign']);
|
||||
const head = b64u(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
|
||||
const claims = b64u(JSON.stringify({ iss: sa.client_email, scope, aud: sa.token_uri || 'https://oauth2.googleapis.com/token', iat: nowS, exp: nowS + 3600 }));
|
||||
const sig = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(`${head}.${claims}`));
|
||||
return `${head}.${claims}.${b64u(sig)}`;
|
||||
}
|
||||
|
||||
/** Cached access token getter (refreshes 5 minutes before expiry). */
|
||||
export function tokenSource(sa: ServiceAccount): () => Promise<string> {
|
||||
let token = '';
|
||||
let until = 0;
|
||||
return async () => {
|
||||
if (token && Date.now() < until) return token;
|
||||
const assertion = await signAssertion(sa, Math.floor(Date.now() / 1000));
|
||||
const r = await fetch(sa.token_uri || 'https://oauth2.googleapis.com/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }),
|
||||
});
|
||||
const j = (await r.json()) as { access_token?: string; expires_in?: number; error_description?: string };
|
||||
if (!j.access_token) throw new Error('Google token: ' + (j.error_description ?? r.status));
|
||||
token = j.access_token;
|
||||
until = Date.now() + ((j.expires_in ?? 3600) - 300) * 1000;
|
||||
return token;
|
||||
};
|
||||
}
|
||||
12
cli/lib/log.ts
Normal file
12
cli/lib/log.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
// Plain, line-based progress output: easy to follow live and easy to tail when a long upload runs in the background
|
||||
// (`crt-ship play images > .crt-ship/images.log 2>&1 &`). Every line carries a timestamp and a tag.
|
||||
const t0 = Date.now();
|
||||
const stamp = (): string => new Date().toISOString().slice(11, 19);
|
||||
const since = (): string => `${((Date.now() - t0) / 1000).toFixed(0)}s`;
|
||||
|
||||
export const log = (tag: string, msg: string): void => console.log(`${stamp()} [${tag}] ${msg}`);
|
||||
export const warn = (tag: string, msg: string): void => console.warn(`${stamp()} [${tag}] WARN ${msg}`);
|
||||
export const done = (tag: string, msg: string): void => console.log(`${stamp()} [${tag}] ${msg} (${since()})`);
|
||||
|
||||
/** "3/14 de-DE" style counters. */
|
||||
export const step = (i: number, n: number, what: string): string => `${String(i).padStart(String(n).length)}/${n} ${what}`;
|
||||
55
cli/lib/money.ts
Normal file
55
cli/lib/money.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// Price helpers shared by the Play and App Store product commands. Pure.
|
||||
import type { PriceOverride } from './config';
|
||||
|
||||
export interface Money { currencyCode: string; units: string; nanos?: number }
|
||||
|
||||
/** 2.99 -> { units: "2", nanos: 990000000 } without float noise (works in cents). */
|
||||
export function toMoney(currencyCode: string, value: number): Money {
|
||||
if (!(value >= 0)) throw new Error(`bad price ${value}`);
|
||||
const cents = Math.round(value * 100);
|
||||
return { currencyCode, units: String(Math.floor(cents / 100)), nanos: (cents % 100) * 10_000_000 };
|
||||
}
|
||||
|
||||
export const fromMoney = (m: Money): number => Number(m.units) + (m.nanos ?? 0) / 1e9;
|
||||
|
||||
export interface RegionConfig { regionCode: string; availability: 'AVAILABLE'; price: Money }
|
||||
|
||||
/**
|
||||
* Play: take convertRegionPrices' result (every region Play sells in, rounded to local price points) and replace the
|
||||
* regions you set explicitly. Throws when an override names a region Play does not offer.
|
||||
*/
|
||||
export function playRegionConfigs(converted: Record<string, { regionCode: string; price: Money }>, overrides: PriceOverride[] = []): RegionConfig[] {
|
||||
const byRegion = new Map(Object.values(converted).map(r => [r.regionCode, r.price] as const));
|
||||
for (const o of overrides) if (!byRegion.has(o.region)) throw new Error(`Play does not sell in region ${o.region}`);
|
||||
const ov = new Map(overrides.map(o => [o.region, toMoney(o.currency, o.price)] as const));
|
||||
return [...byRegion.entries()].sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([regionCode, price]) => ({ regionCode, availability: 'AVAILABLE' as const, price: ov.get(regionCode) ?? price }));
|
||||
}
|
||||
|
||||
/** Apple price points carry customerPrice as a string ("2.99", "30.0"); compare as cents. */
|
||||
export const samePrice = (customerPrice: string | number, want: number): boolean =>
|
||||
Math.round(Number(customerPrice) * 100) === Math.round(want * 100);
|
||||
|
||||
/** Nearest few price points, for a helpful error. */
|
||||
export function nearestPrices(have: number[], want: number, n = 3): number[] {
|
||||
return [...have].sort((a, b) => Math.abs(a - want) - Math.abs(b - want)).slice(0, n);
|
||||
}
|
||||
|
||||
// ISO 3166 alpha-2 -> alpha-3 for the App Store territories (the 175 storefronts). Unknown: set `territory` yourself.
|
||||
const A3 = `AE ARE AF AFG AG ATG AI AIA AL ALB AM ARM AO AGO AR ARG AT AUT AU AUS AZ AZE BA BIH BB BRB BE BEL BF BFA BG BGR
|
||||
BH BHR BJ BEN BM BMU BN BRN BO BOL BR BRA BS BHS BT BTN BW BWA BY BLR BZ BLZ CA CAN CD COD CG COG CH CHE CI CIV CL CHL CM CMR
|
||||
CN CHN CO COL CR CRI CV CPV CY CYP CZ CZE DE DEU DK DNK DM DMA DO DOM DZ DZA EC ECU EE EST EG EGY ES ESP FI FIN FJ FJI FM FSM
|
||||
FR FRA GA GAB GB GBR GD GRD GE GEO GH GHA GM GMB GR GRC GT GTM GW GNB GY GUY HK HKG HN HND HR HRV HU HUN ID IDN IE IRL IL ISR
|
||||
IN IND IQ IRQ IS ISL IT ITA JM JAM JO JOR JP JPN KE KEN KG KGZ KH KHM KN KNA KR KOR KW KWT KY CYM KZ KAZ LA LAO LB LBN LC LCA
|
||||
LK LKA LR LBR LT LTU LU LUX LV LVA LY LBY MA MAR MD MDA ME MNE MG MDG MK MKD ML MLI MM MMR MN MNG MO MAC MR MRT MS MSR MT MLT
|
||||
MU MUS MV MDV MW MWI MX MEX MY MYS MZ MOZ NA NAM NE NER NG NGA NI NIC NL NLD NO NOR NP NPL NR NRU NZ NZL OM OMN PA PAN PE PER
|
||||
PG PNG PH PHL PK PAK PL POL PT PRT PW PLW PY PRY QA QAT RO ROU RS SRB RU RUS RW RWA SA SAU SB SLB SC SYC SE SWE SG SGP SI SVN
|
||||
SK SVK SL SLE SN SEN SR SUR ST STP SV SLV SZ SWZ TC TCA TD TCD TH THA TJ TJK TM TKM TN TUN TO TON TR TUR TT TTO TW TWN TZ TZA
|
||||
UA UKR UG UGA US USA UY URY UZ UZB VC VCT VE VEN VG VGB VN VNM VU VUT XK XKS YE YEM ZA ZAF ZM ZMB ZW ZWE`.split(/\s+/);
|
||||
export const ALPHA3: Record<string, string> = Object.fromEntries(Array.from({ length: A3.length / 2 }, (_, i) => [A3[2 * i]!, A3[2 * i + 1]!]));
|
||||
|
||||
export function appleTerritory(o: PriceOverride): string {
|
||||
const t = o.territory ?? ALPHA3[o.region];
|
||||
if (!t) throw new Error(`no App Store territory known for region ${o.region}; set "territory" (alpha-3) on the override`);
|
||||
return t;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue