storebound/cli/lib/config.ts

252 lines
12 KiB
TypeScript

// Per-project config (storebound.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 = ['storebound.config.ts', 'storebound.config.js', 'storebound.config.json'];
/** Finds storebound.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 storebound.config.ts found (run `storebound 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]);