Merge remote-tracking branch 'origin/main' into play-app-record
# Conflicts: # CHANGELOG.md # docs/pitfalls.md # skills/store-pitfalls/SKILL.md # tests/console-fill.test.ts
This commit is contained in:
commit
ebc45c8c1a
70 changed files with 3729 additions and 290 deletions
|
|
@ -60,6 +60,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
|
|||
'appStoreVersions_build_getToOneRelated': 'apple/listing validate',
|
||||
'appStoreVersions_build_updateToOneRelationship': 'apple/listing',
|
||||
'appStoreVersions_createInstance': 'apple/listing',
|
||||
'appStoreVersions_getInstance': 'apple/listing',
|
||||
'appStoreVersions_updateInstance': 'apple/listing',
|
||||
'apps_analyticsReportRequests_getToManyRelated': 'analytics',
|
||||
'apps_appAvailabilityV2_getToOneRelated': 'apple/appinfo apple/preorder validate',
|
||||
|
|
|
|||
|
|
@ -16,12 +16,13 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|||
import { type AppleCopy, parseAppStoreListing } from '../lib/copy';
|
||||
import { compactDiff } from '../lib/diff';
|
||||
import { mergeAppleListing, overLimits } from '../lib/listing-pull';
|
||||
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
|
||||
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
|
||||
import { createOnce, findOrCreate, getById } from '../lib/upsert';
|
||||
import { appleName } from '../lib/config';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { ascClient, EDITABLE, type J } from './asc';
|
||||
|
||||
export function readAppleCopy(ctx: Ctx) {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
|
|
@ -156,15 +157,21 @@ export function listingPlanLines(p: AppleListingPlan): string[] {
|
|||
return out;
|
||||
}
|
||||
|
||||
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, plan: ItemPlan[]): Promise<void> {
|
||||
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, listPath: string, plan: ItemPlan[]): Promise<void> {
|
||||
const patch = async (key: string, id: string, changes: ItemPlan['changes']) => {
|
||||
await c.asc('PATCH', `/v1/${type}/${id}`, { data: { type, id, attributes: Object.fromEntries(changes.map(ch => [ch.field, ch.to ?? ''])) } });
|
||||
log('apple', `${type} ${key}: updated ${changes.map(ch => ch.field).join(', ')}`);
|
||||
};
|
||||
for (const l of plan) {
|
||||
if (l.action === 'create') {
|
||||
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
|
||||
log('apple', `${type} ${l.key}: created`);
|
||||
} else if (l.action === 'update') {
|
||||
await c.asc('PATCH', `/v1/${type}/${l.id}`, { data: { type, id: l.id, attributes: Object.fromEntries(l.changes.map(ch => [ch.field, ch.to ?? ''])) } });
|
||||
log('apple', `${type} ${l.key}: updated ${l.changes.map(ch => ch.field).join(', ')}`);
|
||||
}
|
||||
// a locale is unique per parent: a 409 (or a lost answer) finds the existing one, which is then updated, never created twice
|
||||
const made = await createOnce<J>({ what: `${type} ${l.key}`, tag: 'apple', unique: true,
|
||||
find: async () => (await c.all(`${listPath}?limit=200`)).find((x: J) => x.attributes.locale === l.key) ?? null,
|
||||
create: async () => (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } })).data });
|
||||
if (made.created) { log('apple', `${type} ${l.key}: created`); continue; }
|
||||
const again = planItem(l.key, { id: made.value.id, attributes: made.value.attributes ?? {} }, l.attributes);
|
||||
if (again.action === 'update') await patch(l.key, made.value.id, again.changes);
|
||||
} else if (l.action === 'update') await patch(l.key, l.id!, l.changes);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -189,9 +196,21 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const vp = p.versionPlan;
|
||||
let versionId = vp.id;
|
||||
if (vp.action === 'create') {
|
||||
versionId = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
|
||||
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
|
||||
log('apple', `version ${version} created`);
|
||||
// look again right before the create (another run, or a lost answer), then the journal for the list lag
|
||||
const made = await findOrCreate<J>({ what: `App Store version ${version}`, tag: 'apple', unique: true,
|
||||
find: async () => (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`))
|
||||
.find((x: J) => x.attributes.versionString === version && EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState)) ?? null,
|
||||
journal: { root, key: `apple:${appId}:version:IOS:${version}`, byId: id => getById(c.asc, `/v1/appStoreVersions/${id}`) as Promise<J | null>, idOf: v => v.id },
|
||||
create: async () => (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
|
||||
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data });
|
||||
versionId = made.value.id;
|
||||
if (made.created) log('apple', `version ${version} created`);
|
||||
else {
|
||||
const { platform: _p, ...want } = vp.attributes;
|
||||
const again = planItem(version, { id: versionId!, attributes: made.value.attributes ?? {} }, want);
|
||||
if (again.action === 'update') await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(again.changes.map(ch => [ch.field, ch.to])) } });
|
||||
log('apple', `version ${version} exists already (an earlier run made it): using it${again.action === 'update' ? `, updated ${again.changes.map(ch => ch.field).join(', ')}` : ''}`);
|
||||
}
|
||||
} else if (vp.action === 'update') {
|
||||
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(vp.changes.map(ch => [ch.field, ch.to])) } });
|
||||
log('apple', `version: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`);
|
||||
|
|
@ -200,8 +219,9 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } });
|
||||
log('apple', `build ${version} (${p.build.number}) attached`);
|
||||
}
|
||||
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, p.appInfo.locales);
|
||||
const vl = p.versionLocales ?? planLocales(await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=200`), p.wanted);
|
||||
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vl);
|
||||
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, `/v1/appInfos/${p.appInfo.id}/appInfoLocalizations`, p.appInfo.locales);
|
||||
const vlPath = `/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations`;
|
||||
const vl = p.versionLocales ?? planLocales(await c.all(`${vlPath}?limit=200`), p.wanted);
|
||||
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vlPath, vl);
|
||||
done('apple', 'listing done');
|
||||
}
|
||||
|
|
|
|||
234
cli/aso.ts
234
cli/aso.ts
|
|
@ -1,32 +1,86 @@
|
|||
// App Store keyword rank check through Apple's public iTunes Search API (no account, no scraping).
|
||||
// App Store keyword work from official / public data only (no scraping, no third-party ASO services).
|
||||
// storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--only-keywords] [--competitors 3] [--limit 200]
|
||||
// [--delay 3500] [--dry] [--json]
|
||||
// Keywords: the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless
|
||||
// storebound aso competitors [--term <kw>]... [--storefront us,tr] [--only-terms] [--top 10] [--delay 3500] [--no-save] [--dry] [--json]
|
||||
// storebound aso suggest [--locale en-US,tr] [--fresh] [--offline] [--write] [--json]
|
||||
// storebound aso audit [--storefront US] [--json]
|
||||
// rank: keywords = the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless
|
||||
// "us=en-GB"), plus --keywords (--only-keywords: just those). One request per keyword and storefront, at most one
|
||||
// every 3.5 s (Apple allows about 20 a minute); a 403 / 429 stops the run with what was read. Rank = position of the
|
||||
// app (apple.appId, else the bundle id) in the first --limit results, "-" when not there; plus the first competitors
|
||||
// (title, developer, rating). Subtitles are not in the public API and are not shown. Writes
|
||||
// .storebound/aso/<date>.json (and compares with the previous one) unless --dry. Pure parts: cli/lib/aso-rank.ts.
|
||||
// (title, developer, rating). Writes .storebound/aso/<date>.json (and compares with the previous one) unless --dry.
|
||||
// competitors: the same queries and rate limit; per term the top N other apps (name, developer, rating count, first
|
||||
// release, last update, genre) and the words in their names that our name / subtitle / keywords do not cover. Saves
|
||||
// .storebound/aso/competitors/<date>.json unless --dry / --no-save; names the apps new in a term's top N since the
|
||||
// previous snapshot. Competitor subtitles are not in any public API and are not shown.
|
||||
// suggest: keyword candidates per App Store locale from our own name / subtitle / description, the latest competitor
|
||||
// snapshot, the localized category names (from the Search API's genres) and, when Apple Ads credentials exist (and
|
||||
// not --offline), Apple Ads keyword suggestions with their relative popularity (0-100). Prints the ranked candidates
|
||||
// and a 100-byte keyword field per locale as a diff against store/appstore.md; --write puts it there with a draft
|
||||
// line above it (review, then delete the line). Never invents a popularity.
|
||||
// audit: one offline report (cli/lib/aso-audit.ts) with experiment ideas and the next 3 actions. Never writes.
|
||||
// Pure parts: cli/lib/aso-rank.ts, cli/lib/aso-intel.ts, cli/lib/aso-audit.ts.
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { adsClient } from './ads/client';
|
||||
import type { Snapshot } from './lib/analytics';
|
||||
import { mergeSeries } from './lib/analytics';
|
||||
import { auditAso } from './lib/aso';
|
||||
import { auditText, buildAudit, type RankSnap } from './lib/aso-audit';
|
||||
import {
|
||||
ADS_KEYWORD_SUGGESTIONS, type AdsSuggestion, candidates, categoryNames, competitorRow, type CompetitorRow, type CompetitorSnapshot, coverageGaps, draftLocales,
|
||||
draftMark, fitKeywordField, keywordSuggestionBody, newEntrants, parseKeywordSuggestions, setKeywords, storefrontOf, tokens,
|
||||
} from './lib/aso-intel';
|
||||
import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank';
|
||||
import { appleName } from './lib/config';
|
||||
import { parseAppStoreListing, parsePlayListing } from './lib/copy';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { done, log, printJson, warn } from './lib/log';
|
||||
import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank';
|
||||
import { appleSections } from './lib/project-files';
|
||||
import { textTable } from './lib/table';
|
||||
|
||||
const TAG = 'aso';
|
||||
const SUBS = ['rank', 'competitors', 'suggest', 'audit'];
|
||||
const SNAP_RE = /^\d{4}-\d{2}-\d{2}\.json$/;
|
||||
const today = () => new Date().toISOString().slice(0, 10);
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
function listingOf(ctx: Ctx): { file: string; md: string; sections: Map<string, Record<string, string | undefined>> } {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const file = resolve(config.apple?.listing ?? 'store/appstore.md');
|
||||
const md = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
||||
return { file, md, sections: appleSections(md) };
|
||||
}
|
||||
|
||||
const primaryLocale = (ctx: Ctx): string => ctx.loaded.config.apple?.primaryLocale ?? ctx.loaded.config.languages.find(l => l.apple)?.apple ?? 'en-US';
|
||||
|
||||
function snapshots<T>(dir: string): { file: string; data: T }[] {
|
||||
if (!existsSync(dir)) return [];
|
||||
return readdirSync(dir).filter(f => SNAP_RE.test(f)).sort().map(f => {
|
||||
try { return { file: f, data: JSON.parse(readFileSync(join(dir, f), 'utf8')) as T }; } catch { return null; }
|
||||
}).filter((x): x is { file: string; data: T } => x !== null);
|
||||
}
|
||||
|
||||
/** One Search API call per item, one every `delay` ms; stops on 403 / 429 with what was read. */
|
||||
async function searchAll<P extends { storefront: string; keyword: string }>(plan: P[], limit: number, delay: number, each: (p: P, results: SearchApp[], i: number) => void): Promise<number> {
|
||||
let read = 0;
|
||||
for (const [i, p] of plan.entries()) {
|
||||
if (i) await Bun.sleep(delay);
|
||||
const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } });
|
||||
if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${read} of ${plan.length}; try later or with a larger --delay`); break; }
|
||||
if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; }
|
||||
each(p, ((await r.json()) as { results?: SearchApp[] }).results ?? [], i);
|
||||
read++;
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
async function rank(ctx: Ctx): Promise<void> {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
if (a._[0] !== 'rank') throw new Error('usage: storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--dry] [--json]');
|
||||
if (!config.apple) throw new Error('aso rank checks App Store search: the config has no apple section');
|
||||
const primary = config.apple.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US';
|
||||
const listingFile = resolve(config.apple.listing ?? 'store/appstore.md');
|
||||
const listing = existsSync(listingFile) ? appleSections(readFileSync(listingFile, 'utf8')) : new Map<string, Record<string, string | undefined>>();
|
||||
const { file: listingFile, sections: listing } = listingOf(ctx);
|
||||
const extra = a.list('keywords');
|
||||
const fronts = parseStorefronts(a.list('storefronts'), primary);
|
||||
const fronts = parseStorefronts(a.list('storefronts'), primaryLocale(ctx));
|
||||
const n = a.num('competitors', 3);
|
||||
const limit = a.num('limit', 200);
|
||||
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
|
||||
|
|
@ -40,21 +94,16 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
return;
|
||||
}
|
||||
const rows: RankRow[] = [];
|
||||
for (const [i, p] of plan.entries()) {
|
||||
if (i) await Bun.sleep(delay);
|
||||
const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } });
|
||||
if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${rows.length} of ${plan.length}; try later or with a larger --delay`); break; }
|
||||
if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; }
|
||||
const results = ((await r.json()) as { results?: SearchApp[] }).results ?? [];
|
||||
await searchAll(plan, limit, delay, (p, results, i) => {
|
||||
const row: RankRow = { storefront: p.storefront, locale: p.locale, keyword: p.keyword, rank: rankOf(results, app), results: results.length, competitors: competitors(results, app, n) };
|
||||
rows.push(row);
|
||||
log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${row.rank ?? `not in the first ${results.length}`}`);
|
||||
}
|
||||
});
|
||||
const dir = resolve('.storebound/aso');
|
||||
const prevFile = existsSync(dir) ? readdirSync(dir).filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).sort().at(-1) : undefined;
|
||||
const prevFile = snapshots<unknown>(dir).at(-1)?.file;
|
||||
const prev = prevFile ? (JSON.parse(readFileSync(join(dir, prevFile), 'utf8')) as { rows?: RankRow[] }).rows : undefined;
|
||||
const delta = rankDelta(rows, prev);
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
const date = today();
|
||||
if (a.has('json')) printJson({ date, previous: prevFile ?? null, rows: rows.map(r => ({ ...r, change: delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`) ?? null })) });
|
||||
else console.log(textTable(['store', 'keyword', 'rank', 'change', 'top competitors'], rows.map(r => {
|
||||
const d = delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`);
|
||||
|
|
@ -64,3 +113,148 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
writeFileSync(join(dir, `${date}.json`), JSON.stringify({ date, app: { appId: app.appId ?? null, bundleId: app.bundleId }, rows }, null, 2) + '\n');
|
||||
done(TAG, `${rows.length} rank(s) saved to ${join(dir, `${date}.json`)}${prevFile ? ` (change vs ${prevFile})` : ''}; Search API order is close to App Store search, read it as a trend`);
|
||||
}
|
||||
|
||||
async function competitorsCmd(ctx: Ctx): Promise<void> {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
if (!config.apple) throw new Error('aso competitors reads App Store search: the config has no apple section');
|
||||
const { file, sections } = listingOf(ctx);
|
||||
const terms = a.many('term').flatMap(t => t.split(',')).map(t => t.trim()).filter(Boolean);
|
||||
const fronts = parseStorefronts([...a.list('storefront'), ...a.list('storefronts')], primaryLocale(ctx));
|
||||
const top = Math.max(1, Math.min(50, a.num('top', 10)));
|
||||
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
|
||||
const app = { appId: config.apple.appId, bundleId: config.apple.bundleId };
|
||||
const plan = fronts.flatMap(f => keywordList(a.has('only-terms') ? '' : sections.get(f.locale)?.keywords, terms).map(k => ({ ...f, keyword: k })));
|
||||
if (!plan.length) throw new Error(`no terms: ${file} has no keywords for ${fronts.map(f => f.locale).join(', ')}; pass --term <keyword>`);
|
||||
const limit = top + 1;
|
||||
const save = !a.has('dry') && !a.has('no-save');
|
||||
if (!a.has('json')) log(TAG, `${plan.length} quer${plan.length === 1 ? 'y' : 'ies'} (${fronts.map(f => f.storefront).join(', ')}), top ${top} each, one every ${delay / 1000}s: about ${Math.ceil(plan.length * delay / 60_000)} min`);
|
||||
if (a.has('dry')) {
|
||||
if (a.has('json')) printJson({ dryRun: true, top, queries: plan.map(p => ({ storefront: p.storefront, locale: p.locale, term: p.keyword, url: searchUrl(p.keyword, p.storefront, limit) })) });
|
||||
else for (const p of plan) log(TAG, `would GET ${searchUrl(p.keyword, p.storefront, limit)}`);
|
||||
return;
|
||||
}
|
||||
const rows: CompetitorRow[] = [];
|
||||
await searchAll(plan, limit, delay, (p, results, i) => {
|
||||
rows.push(competitorRow(results, app, { storefront: p.storefront, locale: p.locale, term: p.keyword }, top));
|
||||
if (!a.has('json')) log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${results.length} result(s)`);
|
||||
});
|
||||
const dir = resolve('.storebound/aso/competitors');
|
||||
const prev = snapshots<CompetitorSnapshot>(dir).filter(s => s.file !== `${today()}.json`).at(-1);
|
||||
const fresh = newEntrants(rows, prev?.data.rows);
|
||||
const gaps = fronts.map(f => {
|
||||
const s = sections.get(f.locale) ?? {};
|
||||
const covered = [...tokens(s.name ?? appleName(config), f.locale), ...tokens(s.subtitle ?? '', f.locale), ...(s.keywords ?? '').split(',').flatMap(t => tokens(t, f.locale))];
|
||||
return { storefront: f.storefront, locale: f.locale, gaps: coverageGaps(rows.filter(r => r.storefront === f.storefront && r.locale === f.locale), covered, f.locale) };
|
||||
});
|
||||
const snap: CompetitorSnapshot = { date: today(), app: { appId: app.appId ?? null, bundleId: app.bundleId }, top, rows };
|
||||
if (a.has('json')) printJson({ ...snap, previous: prev?.file ?? null, newEntrants: Object.fromEntries(fresh), gaps, saved: save,
|
||||
notes: ['Search API order is close to, not equal to, App Store search', 'competitor subtitles are not in any public API'] });
|
||||
else {
|
||||
for (const r of rows) {
|
||||
console.log(`\n${r.storefront} "${r.term}"${r.ourRank ? ` (you: #${r.ourRank})` : ''}`);
|
||||
console.log(textTable(['#', 'app', 'developer', 'ratings', 'released', 'updated', 'genre'],
|
||||
r.apps.map(x => [x.rank, x.name.slice(0, 40), x.developer.slice(0, 24), x.ratings, x.released ?? '-', x.updated ?? '-', x.genres[0]?.name || x.genre])));
|
||||
const n = fresh.get(`${r.storefront}|${r.term.toLowerCase()}`);
|
||||
if (n?.length) log(TAG, `new in the top ${top} since ${prev!.data.date}: ${n.join(', ')}`);
|
||||
}
|
||||
for (const g of gaps) console.log(`\n${g.storefront} ${g.locale}: words in competitors' names you do not cover: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} developers)`).join(', ') : 'none'}`);
|
||||
log(TAG, 'subtitles are not in any public API, so they are not shown; words one developer uses are left out (likely a brand); never put other apps\' names into your keywords');
|
||||
}
|
||||
if (save) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(join(dir, `${snap.date}.json`), JSON.stringify(snap, null, 2) + '\n');
|
||||
if (!a.has('json')) done(TAG, `${rows.length} term(s) saved to ${join(dir, `${snap.date}.json`)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function suggest(ctx: Ctx): Promise<void> {
|
||||
const { config, resolve, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const json = a.has('json');
|
||||
if (!config.apple) throw new Error('aso suggest proposes App Store keyword fields: the config has no apple section');
|
||||
const { file, md } = listingOf(ctx);
|
||||
if (!md) throw new Error(`${file} not found`);
|
||||
const listing = parseAppStoreListing(md);
|
||||
const locales = a.list('locale').length ? a.list('locale') : Object.keys(listing);
|
||||
for (const l of locales) if (!listing[l]) throw new Error(`--locale ${l}: no "## ${l}" section in ${file}`);
|
||||
const comp = snapshots<CompetitorSnapshot>(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null;
|
||||
const cats = Object.values(config.apple.info?.categories ?? {}).filter((x): x is string => typeof x === 'string');
|
||||
// Apple Ads keyword suggestions: only with the owner's credentials and an Apple ID; never estimated without them
|
||||
let ads: ReturnType<typeof adsClient> | null = null;
|
||||
let adsNote = '';
|
||||
if (a.has('offline')) adsNote = '--offline: Apple Ads not asked; popularity unknown';
|
||||
else if (!config.apple.appId) adsNote = 'no apple.appId in the config: Apple Ads suggestions need the app\'s Apple ID; popularity unknown';
|
||||
else {
|
||||
try { ads = adsClient(root); if (!ads.accountId) { ads = null; adsNote = 'APPLE_ADS_ACCOUNT_ID is not set: popularity unknown'; } } catch (e) { adsNote = `no Apple Ads credentials (${(e as Error).message.split(';')[0]}): popularity unknown`; }
|
||||
}
|
||||
const results: { locale: string; storefront: string; ads: string; competitors: string | null; candidates: ReturnType<typeof candidates>; proposal: ReturnType<typeof fitKeywordField> }[] = [];
|
||||
for (const locale of locales) {
|
||||
const c = listing[locale]!;
|
||||
const sf = storefrontOf(locale);
|
||||
const rows = (comp?.rows ?? []).filter(r => r.locale === locale);
|
||||
const name = c.name ?? appleName(config);
|
||||
let sugg: AdsSuggestion[] = [];
|
||||
let adsState = adsNote;
|
||||
if (ads) {
|
||||
const seeds = [...new Set([...tokens(name, locale), ...tokens(c.subtitle ?? '', locale), ...(c.keywords ?? '').split(',').map(t => t.trim()).filter(Boolean)])].slice(0, 20);
|
||||
try {
|
||||
sugg = parseKeywordSuggestions(await ads.post(ADS_KEYWORD_SUGGESTIONS, keywordSuggestionBody(config.apple.appId!, seeds, [sf])));
|
||||
adsState = `Apple Ads keyword suggestions (${sf.toUpperCase()}): ${sugg.length}; popularity is Apple's relative 0-100 score, not a search volume`;
|
||||
} catch (e) { adsState = `Apple Ads keyword suggestions failed (${(e as Error).message.slice(0, 160)}): popularity unknown`; }
|
||||
}
|
||||
const cands = candidates({ locale, name, subtitle: c.subtitle ?? '', keywords: c.keywords ?? '', description: c.description ?? '', competitors: rows, categories: categoryNames(rows, cats), ads: sugg });
|
||||
const proposal = fitKeywordField({ locale, current: c.keywords ?? '', name, subtitle: c.subtitle ?? '', ranked: cands, fresh: a.has('fresh') });
|
||||
results.push({ locale, storefront: sf, ads: adsState, competitors: rows.length ? `${comp!.date}: ${rows.length} term(s)` : null, candidates: cands, proposal });
|
||||
}
|
||||
const write = a.has('write') && !a.has('dry');
|
||||
const changed = results.filter(r => r.proposal.after !== r.proposal.before);
|
||||
if (json) printJson({ file, written: write && changed.length > 0, results: results.map(r => ({ ...r, candidates: r.candidates.slice(0, 60) })) });
|
||||
else {
|
||||
for (const r of results) {
|
||||
console.log(`\n== ${r.locale} (storefront ${r.storefront}) · competitors: ${r.competitors ?? 'no snapshot (storebound aso competitors)'} · ${r.ads}`);
|
||||
const shown = r.candidates.filter(c => c.status === 'candidate').slice(0, 25);
|
||||
console.log(textTable(['candidate', 'from', 'relevance', 'in names', 'popularity'], shown.map(c => [c.term, c.sources.join('+'), `${c.relevance}/2`, `${c.inNames}/${c.ofApps}`,
|
||||
c.popularity === null ? 'unknown' : `${c.popularity}${c.popularityFrom === 'phrase' ? ' (phrase)' : ''}`])));
|
||||
const skipped = r.candidates.filter(c => c.status !== 'candidate' && c.kind === 'word').slice(0, 12);
|
||||
if (skipped.length) log(TAG, `left out: ${skipped.map(c => `${c.term} (${c.why})`).join(', ')}`);
|
||||
const p = r.proposal;
|
||||
if (p.after === p.before) { log(TAG, `${r.locale}: keyword field unchanged (${p.bytes}/100 bytes)`); continue; }
|
||||
console.log(`--- ${r.locale} keywords (store/appstore.md)\n- ${p.before || '(empty)'}\n+ ${p.after}\n ${p.bytes}/100 bytes · kept ${p.kept.length} · added ${p.added.join(', ') || 'none'}${p.dropped.length ? ` · dropped ${p.dropped.map(d => `${d.term} (${d.why})`).join(', ')}` : ''}`);
|
||||
}
|
||||
log(TAG, 'relevance: in your own text (+1) and in competitors\' names (+1); "in names": top apps that already have the word in their name; popularity only from Apple Ads, never estimated');
|
||||
}
|
||||
if (!changed.length) return;
|
||||
if (!write) { if (!json) log(TAG, `dry run: nothing written; --write puts the ${changed.length} proposal(s) into ${file} as drafts for review`); return; }
|
||||
let next = md;
|
||||
for (const r of changed) next = setKeywords(next, r.locale, r.proposal.after, draftMark(today()));
|
||||
writeFileSync(file, next);
|
||||
if (!json) done(TAG, `wrote ${changed.length} draft keyword field(s) to ${file}: review them, delete the draft lines, then storebound check --aso`);
|
||||
}
|
||||
|
||||
function audit(ctx: Ctx): void {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const storefront = (a.get('storefront') ?? 'US').toUpperCase();
|
||||
const { file, md } = listingOf(ctx);
|
||||
const apple = config.apple && md ? parseAppStoreListing(md) : undefined;
|
||||
const playFile = resolve(config.play?.listing ?? 'store/listing.md');
|
||||
const play = config.play && existsSync(playFile) ? parsePlayListing(readFileSync(playFile, 'utf8'), config.app.name) : undefined;
|
||||
const findings = auditAso({ apple, play, appName: appleName(config), storefront });
|
||||
const ranks = snapshots<RankSnap>(resolve('.storebound/aso')).map(s => ({ date: s.data.date, rows: s.data.rows ?? [] }));
|
||||
const comp = snapshots<CompetitorSnapshot>(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null;
|
||||
const analytics = mergeSeries(snapshots<Snapshot>(resolve('.storebound/analytics')).map(s => s.data)).apple;
|
||||
const r = buildAudit({ today: today(), storefront, findings, drafts: md ? draftLocales(md) : [], apple, appName: appleName(config), play, ranks, competitors: comp, analytics,
|
||||
variants: Object.keys(config.shots?.variants ?? {}) });
|
||||
if (a.has('json')) return printJson({ ...r, files: { appstore: apple ? file : null, play: play ? playFile : null } });
|
||||
console.log(auditText(r));
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const sub = ctx.args._[0];
|
||||
if (!sub || !SUBS.includes(sub)) throw new Error('usage: storebound aso rank | competitors | suggest | audit (see the aso-basics skill)');
|
||||
if (sub === 'rank') return rank(ctx);
|
||||
if (sub === 'competitors') return competitorsCmd(ctx);
|
||||
if (sub === 'suggest') return suggest(ctx);
|
||||
return audit(ctx);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { existsSync, readFileSync } from 'node:fs';
|
|||
import { relative } from 'node:path';
|
||||
import { appPrivacyMismatches } from './lib/app-privacy';
|
||||
import { type AsoFinding, auditAso } from './lib/aso';
|
||||
import { draftLocales } from './lib/aso-intel';
|
||||
import { appleName, playCodes } from './lib/config';
|
||||
import { APPLE_IAP_LIMITS, appleNameIssues, len, parseAppStoreListing, parsePlayListing } from './lib/copy';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
|
|
@ -22,9 +23,11 @@ import { type CopyFile, validateCopy } from './shots/lib';
|
|||
|
||||
function aso(ctx: Ctx): void {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined;
|
||||
const appleMd = config.apple ? readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8') : '';
|
||||
const apple = config.apple ? parseAppStoreListing(appleMd) : undefined;
|
||||
const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined;
|
||||
const f: AsoFinding[] = auditAso({ apple, play, appName: appleName(config), storefront: ctx.args.get('storefront') ?? 'US' });
|
||||
for (const l of draftLocales(appleMd)) f.push({ level: 'warn', where: `apple ${l}`, msg: 'keywords: draft from `aso suggest`, not reviewed yet (review, then delete the storebound-aso draft line)' });
|
||||
if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; }
|
||||
const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const;
|
||||
for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`);
|
||||
|
|
|
|||
|
|
@ -168,6 +168,8 @@ export interface OpenOpts {
|
|||
hosts?: string[];
|
||||
headless?: boolean;
|
||||
platform?: string;
|
||||
/** Tests: Playwright's launch timeout for modes (b) and (c) (default: Playwright's 30 s). */
|
||||
launchTimeoutMs?: number;
|
||||
say: (m: string) => void;
|
||||
}
|
||||
|
||||
|
|
@ -233,7 +235,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
|
|||
copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) });
|
||||
const c = await chromiumFor(root);
|
||||
const context = await c.launchPersistentContext(copy.dir, {
|
||||
channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS,
|
||||
channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}),
|
||||
// Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read
|
||||
ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'],
|
||||
});
|
||||
|
|
@ -251,7 +253,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
|
|||
}
|
||||
// (c) storebound's persistent profile, the owner signs in there
|
||||
mkdirSync(o.profileDir, { recursive: true });
|
||||
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS });
|
||||
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}) });
|
||||
o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`);
|
||||
const page = await ownTab(context);
|
||||
return wrapContext('profile', context, page, () => { /* kept on purpose */ });
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
|||
'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches | pull [--write]: store texts of IAPs + subscriptions as a config proposal'],
|
||||
'reports': [() => import('./reports'), 'apple-sales | apple-finance --month | play-earnings --month | play-sales --month: download to .storebound/reports/, summary table + CSV; read-only'],
|
||||
'triage': [() => import('./triage'), 'TestFlight crash / screenshot feedback and Play error reports grouped by signature, device, OS version, build; read-only, --json'],
|
||||
'aso': [() => import('./aso'), 'rank [--storefronts us,de] [--keywords a,b]: App Store rank per keyword and storefront + competitors from the public iTunes Search API (rate limited) -> .storebound/aso/'],
|
||||
'aso': [() => import('./aso'), 'rank | competitors | suggest | audit: App Store ranks, top apps per keyword, keyword field proposals (Apple Ads popularity with credentials) and one ASO report, from the public iTunes Search API -> .storebound/aso/'],
|
||||
'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes) | ppp --base <USD> (purchasing power price sheet, snapped to store price points)'],
|
||||
'ads apple': [() => import('./ads/apple'), 'Apple Ads (Search Ads): status | campaigns | report (spend, taps, installs, CPA per campaign / keyword, --csv); bid | budget | pause (dry run, asks first; never via MCP)'],
|
||||
'web': [() => import('./web'), 'init (apple-app-site-association, assetlinks.json, Smart App Banner tag, optional landing page) | check <domain> (live files: content type, no redirects, ids match)'],
|
||||
|
|
@ -49,7 +49,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
|||
'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'],
|
||||
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language; pull [--write]: live listings back into the listing file (diff first)'],
|
||||
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'],
|
||||
'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'],
|
||||
'play data-safety': [() => import('./play/data-safety'), '[--force] Data safety form (CSV import through the API; skipped when unchanged since the last upload)'],
|
||||
'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'],
|
||||
'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'],
|
||||
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],
|
||||
|
|
|
|||
221
cli/lib/aso-audit.ts
Normal file
221
cli/lib/aso-audit.ts
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
// `aso audit`: one offline report over everything storebound already keeps, as pure parts. Inputs: the `check --aso`
|
||||
// findings and the cross-locale free-keyword-room hint (cli/lib/aso.ts), the rank snapshots of `aso rank`
|
||||
// (.storebound/aso/<date>.json, trend arrows), the latest competitor snapshot of `aso competitors`
|
||||
// (.storebound/aso/competitors/<date>.json, coverage gaps), the Play listing (keyword density, short description use),
|
||||
// the App Store analytics snapshots (.storebound/analytics, impressions / downloads / conversion) and the screenshot
|
||||
// variants of the config. Output: the report, experiment ideas (suggestions only: nothing is started) and the next 3
|
||||
// concrete actions. No network, no writes.
|
||||
import type { AppleDay } from './analytics';
|
||||
import type { AsoFinding } from './aso';
|
||||
import { words } from './aso';
|
||||
import { type CompetitorSnapshot, coverageGaps, type Gap, isStop, tokens } from './aso-intel';
|
||||
import type { RankRow } from './aso-rank';
|
||||
import type { AppleCopy, PlayCopy } from './copy';
|
||||
import { len } from './copy';
|
||||
import { textTable } from './table';
|
||||
|
||||
export interface RankSnap { date: string; rows: RankRow[] }
|
||||
export type Arrow = '↑' | '↓' | '→' | 'new' | 'lost' | '·';
|
||||
export interface TrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: Arrow; best: number | null; snapshots: number }
|
||||
|
||||
const k = (r: { storefront: string; keyword: string }) => `${r.storefront}|${r.keyword.toLowerCase()}`;
|
||||
|
||||
/** Latest rank per storefront + keyword against the snapshot before it (positive change = moved up). Pure. */
|
||||
export function rankTrend(snaps: RankSnap[]): { rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] } {
|
||||
const sorted = [...snaps].sort((a, b) => a.date.localeCompare(b.date));
|
||||
const dates = sorted.map(s => s.date);
|
||||
const hist = new Map<string, { storefront: string; keyword: string; ranks: (number | null | undefined)[] }>();
|
||||
sorted.forEach((s, i) => {
|
||||
for (const r of s.rows) {
|
||||
const h = hist.get(k(r)) ?? { storefront: r.storefront, keyword: r.keyword, ranks: Array(sorted.length).fill(undefined) };
|
||||
h.ranks[i] = r.rank;
|
||||
hist.set(k(r), h);
|
||||
}
|
||||
});
|
||||
const rows: TrendRow[] = [];
|
||||
for (const h of hist.values()) {
|
||||
const seen = h.ranks.map((v, i) => ({ v, i })).filter(x => x.v !== undefined) as { v: number | null; i: number }[];
|
||||
const last = seen.at(-1)!, prev = seen.at(-2);
|
||||
const rank = last.v, previous = prev ? prev.v : null;
|
||||
const arrow: Arrow = !prev ? (rank === null ? '·' : 'new') : rank === null ? (previous === null ? '·' : 'lost') : previous === null ? 'new'
|
||||
: rank < previous ? '↑' : rank > previous ? '↓' : '→';
|
||||
const known = seen.map(x => x.v).filter((v): v is number => v !== null);
|
||||
rows.push({ storefront: h.storefront, keyword: h.keyword, rank, previous, change: rank !== null && previous !== null ? previous - rank : null, arrow,
|
||||
best: known.length ? Math.min(...known) : null, snapshots: seen.length });
|
||||
}
|
||||
rows.sort((a, b) => a.storefront.localeCompare(b.storefront) || (a.rank ?? 999) - (b.rank ?? 999) || a.keyword.localeCompare(b.keyword));
|
||||
const series = [...hist.values()].map(h => ({ storefront: h.storefront, keyword: h.keyword, ranks: h.ranks.map(v => v ?? null) }));
|
||||
return { rows, dates, series };
|
||||
}
|
||||
|
||||
export interface PlayUse { lang: string; title: string; shortChars: number; shortRoom: number; titleWordsInShort: boolean; shortWordsInOpening: boolean; top: { word: string; count: number; density: number }[]; stuffed: string[] }
|
||||
|
||||
/** Play: how the short description is used and which words the full description leans on (density). Pure. */
|
||||
export function playUse(c: PlayCopy): PlayUse {
|
||||
const L = c.lang;
|
||||
const full = words(c.full, L);
|
||||
const counts = new Map<string, number>();
|
||||
for (const w of full) if (w.length > 3 && !isStop(w, L)) counts.set(w, (counts.get(w) ?? 0) + 1);
|
||||
const top = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 5)
|
||||
.map(([word, count]) => ({ word, count, density: full.length ? count / full.length : 0 }));
|
||||
const titleWords = tokens(c.title, L).filter(w => w.length > 2);
|
||||
const shortWords = new Set(tokens(c.short, L));
|
||||
const opening = new Set(words(c.full.split('\n').slice(0, 3).join(' '), L));
|
||||
return {
|
||||
lang: L, title: c.title, shortChars: len(c.short), shortRoom: 80 - len(c.short),
|
||||
titleWordsInShort: titleWords.some(w => shortWords.has(w)),
|
||||
shortWordsInOpening: [...shortWords].some(w => w.length > 3 && opening.has(w)),
|
||||
top, stuffed: top.filter(t => full.length >= 80 && t.count >= 6 && t.density > 0.03).map(t => t.word),
|
||||
};
|
||||
}
|
||||
|
||||
export interface Experiment { store: 'apple' | 'play'; what: string; why: string; how: string }
|
||||
export interface Action { what: string; why: string; command?: string }
|
||||
|
||||
export interface AuditInput {
|
||||
today: string;
|
||||
storefront: string;
|
||||
findings: AsoFinding[];
|
||||
drafts: string[];
|
||||
apple?: Record<string, AppleCopy>;
|
||||
appName: string;
|
||||
play?: PlayCopy[];
|
||||
ranks: RankSnap[];
|
||||
competitors: CompetitorSnapshot | null;
|
||||
analytics: AppleDay[];
|
||||
variants: string[];
|
||||
}
|
||||
|
||||
export interface AsoAudit {
|
||||
generated: string; storefront: string;
|
||||
keywordField: { errors: number; warnings: number; hints: number; findings: AsoFinding[] };
|
||||
crossLocale: string | null;
|
||||
drafts: string[];
|
||||
ranks: { snapshots: number; latest: string | null; rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] };
|
||||
competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: Gap[] }[] };
|
||||
play: PlayUse[];
|
||||
/** check --aso findings of the Play listing (stuffing, claims, caps, emoji, short description room). */
|
||||
playFindings: AsoFinding[];
|
||||
analytics: { days: number; start: string; end: string; impressions: number; pageViews: number; downloads: number; conversion: number | null } | null;
|
||||
experiments: Experiment[];
|
||||
next: Action[];
|
||||
}
|
||||
|
||||
const daysBetween = (a: string, b: string) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
|
||||
|
||||
/** The whole audit. Pure. */
|
||||
export function buildAudit(i: AuditInput): AsoAudit {
|
||||
const kwFindings = i.findings.filter(f => f.where.startsWith('apple ') && !/storefront$/.test(f.where));
|
||||
const playFindings = i.findings.filter(f => f.where.startsWith('play '));
|
||||
const cross = i.findings.find(f => /storefront$/.test(f.where))?.msg ?? null;
|
||||
const trend = rankTrend(i.ranks);
|
||||
const gaps: AsoAudit['competitors']['gaps'] = [];
|
||||
if (i.competitors) {
|
||||
const groups = new Map<string, CompetitorSnapshot['rows']>();
|
||||
for (const r of i.competitors.rows) groups.set(`${r.storefront}|${r.locale}`, [...(groups.get(`${r.storefront}|${r.locale}`) ?? []), r]);
|
||||
for (const [g, rows] of groups) {
|
||||
const [storefront, locale] = g.split('|') as [string, string];
|
||||
const c = i.apple?.[locale];
|
||||
const covered = [...words(c?.name ?? i.appName, locale), ...words(c?.subtitle ?? '', locale), ...(c?.keywords ?? '').split(',').flatMap(t => words(t, locale))];
|
||||
gaps.push({ storefront, locale, gaps: coverageGaps(rows, covered, locale, 8) });
|
||||
}
|
||||
}
|
||||
const play = (i.play ?? []).map(playUse);
|
||||
const last = i.analytics.slice(-28);
|
||||
const sum = (f: (d: AppleDay) => number) => last.reduce((n, d) => n + f(d), 0);
|
||||
const analytics = last.length ? { days: last.length, start: last[0]!.date, end: last.at(-1)!.date, impressions: sum(d => d.uniqueImpressions || d.impressions),
|
||||
pageViews: sum(d => d.uniquePageViews || d.pageViews), downloads: sum(d => d.firstTimeDownloads || d.downloads), conversion: null as number | null } : null;
|
||||
if (analytics) analytics.conversion = analytics.impressions ? analytics.downloads / analytics.impressions : null;
|
||||
const a: AsoAudit = {
|
||||
generated: i.today, storefront: i.storefront,
|
||||
keywordField: { errors: kwFindings.filter(f => f.level === 'error').length, warnings: kwFindings.filter(f => f.level === 'warn').length, hints: kwFindings.filter(f => f.level === 'info').length, findings: kwFindings },
|
||||
crossLocale: cross, drafts: i.drafts,
|
||||
ranks: { snapshots: i.ranks.length, latest: trend.dates.at(-1) ?? null, rows: trend.rows, dates: trend.dates, series: trend.series },
|
||||
competitors: { date: i.competitors?.date ?? null, gaps },
|
||||
play, playFindings, analytics, experiments: [], next: [],
|
||||
};
|
||||
a.experiments = experimentIdeas(a, i);
|
||||
a.next = nextActions(a, i);
|
||||
return a;
|
||||
}
|
||||
|
||||
/** Product Page Optimization (Apple) and store listing experiment (Play) ideas from the audit. Suggestions only. Pure. */
|
||||
export function experimentIdeas(a: AsoAudit, i: AuditInput): Experiment[] {
|
||||
const out: Experiment[] = [];
|
||||
if (i.apple) {
|
||||
const v = i.variants[0];
|
||||
out.push({ store: 'apple', what: 'first screenshot caption: lead with the search phrase people use for the app\'s main job',
|
||||
why: a.analytics?.conversion !== null && a.analytics ? `App Store conversion (first-time downloads / unique impressions, last ${a.analytics.days} days) is ${(a.analytics.conversion! * 100).toFixed(1)}%: the first screenshot is what search results show` : 'the first screenshot is what search results show; PPO measures it against the original',
|
||||
how: v ? `variant "${v}" exists: storebound shots render --variant ${v}, then storebound apple ppo create --variant ${v} --dry and apple ppo upload --variant ${v} --dry (starting the test is the owner's step: apple ppo start)`
|
||||
: 'add a shots.variants entry with the new caption, storebound shots render --variant b, then storebound apple ppo create --variant b --dry (starting the test is the owner\'s step: apple ppo start)' });
|
||||
out.push({ store: 'apple', what: 'subtitle variant',
|
||||
why: 'PPO tests only icons, screenshots and app previews: the subtitle cannot be A/B tested on the App Store',
|
||||
how: 'change it with the next version and compare before / after with storebound analytics compare (one change at a time)' });
|
||||
}
|
||||
for (const p of a.play.slice(0, 1)) {
|
||||
out.push({ store: 'play', what: `short description variant (${p.lang})`,
|
||||
why: p.shortRoom > 30 ? `the short description uses ${p.shortChars}/80 characters` : !p.titleWordsInShort ? 'the short description shares no word with the title' : 'the short description is the first text on the listing',
|
||||
how: 'Play Console > Grow users > Store listing experiments (no API: storebound only prepares the text; the store-screenshots skill has the steps)' });
|
||||
if (i.variants.length) out.push({ store: 'play', what: `screenshot variant "${i.variants[0]}"`, why: 'graphics experiments need no new version',
|
||||
how: `storebound shots render --variant ${i.variants[0]} --size play, then upload it as the experiment's variant in Play Console` });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The next 3 concrete actions, most important first. Pure. */
|
||||
export function nextActions(a: AsoAudit, i: AuditInput): Action[] {
|
||||
const out: Action[] = [];
|
||||
const f = a.keywordField.findings;
|
||||
const err = f.find(x => x.level === 'error');
|
||||
if (err) out.push({ what: `fix ${err.where}: ${err.msg}`, why: 'App Store Connect refuses the keyword field as it is', command: 'storebound check --aso' });
|
||||
if (a.drafts.length) out.push({ what: `review the draft keywords of ${a.drafts.join(', ')} in store/appstore.md and delete the draft line`, why: 'they were proposed by aso suggest, not reviewed yet' });
|
||||
const room = f.find(x => /bytes used; fill/.test(x.msg));
|
||||
if (room) out.push({ what: `fill the keyword field of ${room.where.replace('apple ', '')} (${room.msg.replace(/^keywords: /, '')})`, why: 'unused bytes are unused search reach', command: `storebound aso suggest --locale ${room.where.replace('apple ', '')}` });
|
||||
const rep = f.find(x => /repeat words from the name/.test(x.msg));
|
||||
if (rep) out.push({ what: `${rep.where}: replace the words the name / subtitle already index (${rep.msg.split(': ').at(-1)})`, why: 'they take bytes without adding reach', command: `storebound aso suggest --locale ${rep.where.replace('apple ', '')}` });
|
||||
const gap = a.competitors.gaps.find(g => g.gaps.length);
|
||||
if (gap) out.push({ what: `consider "${gap.gaps.slice(0, 3).map(g => g.word).join('", "')}" for ${gap.locale} (in the names of ${gap.gaps[0]!.developers} developers' top apps, not in your name / subtitle / keywords)`, why: 'words the top apps lead with; only if they describe your app', command: `storebound aso suggest --locale ${gap.locale}` });
|
||||
const lost = a.ranks.rows.filter(r => r.arrow === '↓' || r.arrow === 'lost');
|
||||
if (lost.length) out.push({ what: `look at the keywords that dropped: ${lost.slice(0, 3).map(r => `${r.storefront} "${r.keyword}" ${r.previous ?? '-'} -> ${r.rank ?? '-'}`).join(', ')}`, why: 'a drop after a listing change is the signal to revert or adjust it' });
|
||||
if (!a.ranks.latest) out.push({ what: 'take a first rank snapshot', why: 'trends need a baseline before the next listing change', command: 'storebound aso rank --dry, then storebound aso rank' });
|
||||
else if (daysBetween(a.ranks.latest, i.today) > 14) out.push({ what: `take a new rank snapshot (the last is from ${a.ranks.latest})`, why: 'trend arrows compare the last two snapshots', command: 'storebound aso rank' });
|
||||
if (!a.competitors.date) out.push({ what: 'read the competitors for your keywords', why: 'coverage gaps and suggest need the top apps per term', command: 'storebound aso competitors --dry, then storebound aso competitors' });
|
||||
for (const p of a.play) {
|
||||
if (p.stuffed.length) out.push({ what: `Play ${p.lang}: use "${p.stuffed.join('", "')}" less often in the full description`, why: 'reads as keyword stuffing (Play metadata policy)' });
|
||||
else if (p.shortRoom > 30) out.push({ what: `Play ${p.lang}: put the core phrase into the short description (${p.shortChars}/80 used)`, why: 'Play indexes the short description' });
|
||||
}
|
||||
if (!a.analytics) out.push({ what: 'start App Store analytics snapshots', why: 'conversion before / after each listing change is the real measure', command: 'storebound analytics setup --dry, then storebound analytics snapshot' });
|
||||
return out.slice(0, 3);
|
||||
}
|
||||
|
||||
const signed = (n: number | null) => (n === null ? '' : n > 0 ? `+${n}` : String(n));
|
||||
|
||||
/** The report as text. Pure. */
|
||||
export function auditText(a: AsoAudit): string {
|
||||
const o: string[] = [];
|
||||
const kf = a.keywordField;
|
||||
o.push(`ASO audit ${a.generated} (offline: listing files, .storebound/aso snapshots, .storebound/analytics)`, '');
|
||||
o.push(`1. Keyword field (check --aso): ${kf.errors} errors, ${kf.warnings} warnings, ${kf.hints} hints`);
|
||||
for (const f of kf.findings.filter(x => x.level !== 'info').slice(0, 8)) o.push(` ${f.level === 'error' ? 'ERROR' : 'warn '} [${f.where}] ${f.msg}`);
|
||||
if (a.drafts.length) o.push(` draft keywords (from aso suggest, not reviewed): ${a.drafts.join(', ')}`);
|
||||
if (a.crossLocale) o.push(` ${a.storefront} storefront: ${a.crossLocale}`);
|
||||
o.push('', `2. Ranks (aso rank, iTunes Search API order; a trend, not App Store search itself): ${a.ranks.snapshots} snapshot(s)${a.ranks.latest ? `, latest ${a.ranks.latest}` : ''}`);
|
||||
if (a.ranks.rows.length) o.push(indent(textTable(['store', 'keyword', 'rank', '', 'change', 'best'], a.ranks.rows.map(r => [r.storefront, r.keyword, r.rank ?? '-', r.arrow, signed(r.change), r.best ?? '-']))));
|
||||
else o.push(' none yet: storebound aso rank');
|
||||
o.push('', `3. Competitor coverage (aso competitors${a.competitors.date ? `, ${a.competitors.date}` : ''}): words in the top apps' names you do not cover`);
|
||||
if (!a.competitors.date) o.push(' no snapshot yet: storebound aso competitors');
|
||||
for (const g of a.competitors.gaps) o.push(` ${g.storefront} ${g.locale}: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} devs)`).join(', ') : 'none'}`);
|
||||
o.push('', '4. Google Play listing');
|
||||
if (!a.play.length) o.push(' no Play listing');
|
||||
for (const f of a.playFindings.filter(x => x.level !== 'info')) o.push(` warn [${f.where}] ${f.msg}`);
|
||||
for (const p of a.play) o.push(` ${p.lang}: short ${p.shortChars}/80${p.titleWordsInShort ? '' : ', no title word in it'}${p.shortWordsInOpening ? '' : ', opening lines share no word with it'}; top words ${p.top.map(t => `${t.word} ${t.count}x (${(t.density * 100).toFixed(1)}%)`).join(', ') || '-'}${p.stuffed.length ? `; STUFFING: ${p.stuffed.join(', ')}` : ''}`);
|
||||
o.push('', '5. App Store analytics (analytics snapshot)');
|
||||
o.push(a.analytics ? ` ${a.analytics.start} .. ${a.analytics.end} (${a.analytics.days} days): ${a.analytics.impressions} unique impressions, ${a.analytics.pageViews} product page views, ${a.analytics.downloads} first-time downloads, conversion ${a.analytics.conversion === null ? 'n/a' : `${(a.analytics.conversion * 100).toFixed(2)}%`}` : ' no snapshots: storebound analytics snapshot');
|
||||
o.push('', '6. Experiment ideas (suggestions only; nothing is started)');
|
||||
for (const e of a.experiments) o.push(` [${e.store === 'apple' ? 'App Store PPO' : 'Play experiment'}] ${e.what}`, ` why: ${e.why}`, ` how: ${e.how}`);
|
||||
o.push('', 'Next 3 actions');
|
||||
a.next.forEach((x, n) => o.push(` ${n + 1}. ${x.what}`, ` why: ${x.why}${x.command ? `; run: ${x.command}` : ''}`));
|
||||
return o.join('\n');
|
||||
}
|
||||
|
||||
const indent = (s: string) => s.split('\n').map(l => ` ${l}`).join('\n');
|
||||
366
cli/lib/aso-intel.ts
Normal file
366
cli/lib/aso-intel.ts
Normal file
|
|
@ -0,0 +1,366 @@
|
|||
// ASO keyword research from official and public data only, as pure parts. The commands are in cli/aso.ts
|
||||
// (`aso competitors`, `aso suggest`); the audit report is cli/lib/aso-audit.ts.
|
||||
//
|
||||
// Data sources and what each number is (and is not):
|
||||
// - iTunes Search API (public, no account; https://performance-partners.apple.com/search-api): the top N apps for a
|
||||
// term in one storefront, with name (trackName), developer, rating count, first release date, last update, genre
|
||||
// and the genre names localized to that storefront ("genres": "Produktivität" for country=de). Its order is close
|
||||
// to, not equal to, App Store search. It has no subtitle field, so competitor subtitles are never shown.
|
||||
// - Apple Ads Platform API, POST /v1/suggestions/keywords/query (only with the owner's Apple Ads credentials):
|
||||
// keyword suggestions for the app (promotedObjectId = Apple ID, promotedObjectType APPSTORE_APP), seeded with
|
||||
// `terms` and scoped with `countriesOrRegions`; each KeywordSuggestion is { text, popularity } where popularity is
|
||||
// "a relative popularity score (not an absolute volume)" on a 0-100 scale. That is the only popularity signal
|
||||
// storebound shows; without credentials popularity stays "unknown" (never estimated).
|
||||
// https://developer.apple.com/documentation/apple-ads-platform-api/query-keyword-suggestions
|
||||
// https://developer.apple.com/documentation/apple-ads-platform-api/keywordsuggestion
|
||||
// https://developer.apple.com/documentation/apple-ads-platform-api/recommendationqueryrequest (pageSize 1..1000)
|
||||
// (The Recommendations endpoints are budget / target CPA only; Insights has search term popularity 1-5 by genre,
|
||||
// not used here.)
|
||||
// - The app's own listing (store/appstore.md): name, subtitle, keyword field and description.
|
||||
// Nothing here scrapes a store web page or calls a third-party ASO service.
|
||||
import { FILLER, words } from './aso';
|
||||
import type { SearchApp } from './aso-rank';
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// Words
|
||||
|
||||
/** Function words that never make a keyword (a few languages; extend as needed). FILLER (app, game, free ...) too. */
|
||||
const STOP: Record<string, string[]> = {
|
||||
en: ['to', 'in', 'on', 'at', 'by', 'or', 'is', 'it', 'its', 'you', 'your', 'our', 'we', 'my', 'me', 'all', 'one', 'new', 'more', 'from', 'that', 'this', 'are', 'be', 'can', 'get', 'up', 'out', 'as', 'so', 'no', 'not', 'any', 'every', 'each', 'just', 'into', 'than', 'then', 'also', 'will', 'has', 'have', 'only', 'when', 'what', 'who', 'how', 'way', 'like', 'use', 'make', 'keep', 'see'],
|
||||
de: ['der', 'die', 'das', 'und', 'mit', 'für', 'von', 'zu', 'ein', 'eine', 'ist', 'im', 'in', 'auf', 'den', 'dem', 'des', 'sie', 'du', 'dein', 'deine', 'alle', 'oder', 'auch'],
|
||||
fr: ['le', 'la', 'les', 'et', 'de', 'des', 'du', 'un', 'une', 'pour', 'avec', 'en', 'au', 'aux', 'vos', 'votre', 'est', 'dans', 'sur', 'ou', 'tout', 'tous'],
|
||||
es: ['el', 'la', 'los', 'las', 'y', 'de', 'del', 'un', 'una', 'para', 'con', 'en', 'tu', 'tus', 'es', 'por', 'o', 'que', 'todo', 'todos'],
|
||||
pt: ['o', 'a', 'os', 'as', 'e', 'de', 'do', 'da', 'um', 'uma', 'para', 'com', 'em', 'seu', 'sua', 'no', 'na', 'ou', 'que', 'todo', 'todos'],
|
||||
it: ['il', 'lo', 'la', 'le', 'gli', 'e', 'di', 'del', 'un', 'una', 'per', 'con', 'in', 'tuo', 'tua', 'che', 'tutti'],
|
||||
tr: ['ve', 'ile', 'için', 'göre', 'kadar', 'sonra', 'önce', 'olan', 'olarak', 'bir', 'bu', 'şu', 'da', 'de', 'mi', 'en', 'çok', 'her', 'tüm', 'gibi', 'daha', 'sen', 'senin'],
|
||||
};
|
||||
/** Words of listing boilerplate (account, settings, privacy ...): they describe the store page, not the app's job. */
|
||||
const BOILER = new Set(['account', 'accounts', 'settings', 'sign', 'signin', 'login', 'delete', 'privacy', 'policy', 'terms', 'support', 'contact', 'feature', 'features',
|
||||
'update', 'updates', 'version', 'subscription', 'purchase', 'purchases', 'time', 'any', 'back', 'between', 'off', 'next', 'keeps', 'keep', 'item', 'items',
|
||||
'change', 'changes', 'show', 'shows', 'work', 'works', 'people', 'phone', 'phones', 'here', 'there', 'about', 'want', 'need', 'help', 'day', 'days', 'even', 'much', 'many']);
|
||||
const lang = (locale: string): string => locale.split('-')[0]!.toLowerCase();
|
||||
export const isStop = (w: string, locale: string): boolean => FILLER.has(w) || BOILER.has(w) || (STOP[lang(locale)] ?? []).includes(w) || STOP.en!.includes(w) || /^\d+$/.test(w);
|
||||
/** "Ayarlar'dan" -> "Ayarlar", "it's" -> "it": the suffix after an apostrophe is not a word of its own. */
|
||||
const unApostrophe = (s: string): string => s.replace(/['’]\p{L}+/gu, '');
|
||||
|
||||
/** Content words of a text (lowercased for the locale, function words, boilerplate and numbers left out). Pure. */
|
||||
export const tokens = (s: string, locale: string): string[] => words(unApostrophe(s), locale).filter(w => !isStop(w, locale));
|
||||
|
||||
/** Two-word phrases of content words that stand next to each other in the text. Pure. */
|
||||
export function bigrams(s: string, locale: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const seg of unApostrophe(s).split(/[.!?\n:;,()"“”«»•·|/–—-]+/)) {
|
||||
const ws = words(seg, locale);
|
||||
for (let i = 0; i + 1 < ws.length; i++) if (!isStop(ws[i]!, locale) && !isStop(ws[i + 1]!, locale)) out.push(`${ws[i]} ${ws[i + 1]}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Plural-insensitive key: languages whose plural is mostly "-s" fold "lists" and "list" together. Pure. */
|
||||
export function stem(w: string, locale: string): string {
|
||||
const l = lang(locale);
|
||||
if (l === 'en' && w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y'; // groceries -> grocery
|
||||
return ['en', 'fr', 'es', 'pt'].includes(l) && w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w;
|
||||
}
|
||||
|
||||
/** Languages that add suffixes to a word ("listeler", "listelerini"): one word starts with the other. */
|
||||
const SUFFIXING = new Set(['tr', 'fi', 'hu', 'et', 'az', 'kk', 'uz']);
|
||||
/** The same keyword for search: plural-insensitive, and in suffixing languages a word that only adds a short suffix
|
||||
* (up to 5 letters) to a word of at least 4. A heuristic: it errs on the side of not repeating a word. Pure. */
|
||||
export function sameWord(a: string, b: string, locale: string): boolean {
|
||||
const x = stem(a, locale), y = stem(b, locale);
|
||||
if (x === y) return true;
|
||||
if (!SUFFIXING.has(lang(locale))) return false;
|
||||
const [s, l] = x.length <= y.length ? [x, y] : [y, x];
|
||||
return s.length >= 4 && l.startsWith(s) && l.length - s.length <= 5;
|
||||
}
|
||||
const coveredBy = (w: string, set: Iterable<string>, locale: string): boolean => { for (const s of set) if (sameWord(w, s, locale)) return true; return false; };
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// Competitors (iTunes Search API)
|
||||
|
||||
/** App Store Connect category id -> iTunes genre id (the "genreIds" of Search API results). Apple's genre ids. */
|
||||
export const GENRE_IDS: Record<string, string> = {
|
||||
BOOKS: '6018', BUSINESS: '6000', DEVELOPER_TOOLS: '6026', EDUCATION: '6017', ENTERTAINMENT: '6016', FINANCE: '6015', FOOD_AND_DRINK: '6023', GAMES: '6014',
|
||||
GRAPHICS_AND_DESIGN: '6027', HEALTH_AND_FITNESS: '6013', LIFESTYLE: '6012', MAGAZINES_AND_NEWSPAPERS: '6021', MEDICAL: '6020', MUSIC: '6011', NAVIGATION: '6010',
|
||||
NEWS: '6009', PHOTO_AND_VIDEO: '6008', PRODUCTIVITY: '6007', REFERENCE: '6006', SHOPPING: '6024', SOCIAL_NETWORKING: '6005', SPORTS: '6004', STICKERS: '6025',
|
||||
TRAVEL: '6003', UTILITIES: '6002', WEATHER: '6001',
|
||||
GAMES_ACTION: '7001', GAMES_ADVENTURE: '7002', GAMES_CASUAL: '7003', GAMES_BOARD: '7004', GAMES_CARD: '7005', GAMES_CASINO: '7006', GAMES_FAMILY: '7009',
|
||||
GAMES_MUSIC: '7011', GAMES_PUZZLE: '7012', GAMES_RACING: '7013', GAMES_ROLE_PLAYING: '7014', GAMES_SIMULATION: '7015', GAMES_SPORTS: '7016',
|
||||
GAMES_STRATEGY: '7017', GAMES_TRIVIA: '7018', GAMES_WORD: '7019',
|
||||
};
|
||||
|
||||
export interface CompetitorApp {
|
||||
rank: number; id: string; name: string; developer: string; ratings: number; rating: number | null;
|
||||
/** First release (releaseDate) and the current version's release (currentVersionReleaseDate), YYYY-MM-DD. */
|
||||
released: string | null; updated: string | null;
|
||||
genre: string;
|
||||
/** Genre ids with their names localized to the storefront. */
|
||||
genres: { id: string; name: string }[];
|
||||
}
|
||||
export interface CompetitorRow { storefront: string; locale: string; term: string; results: number; ourRank: number | null; apps: CompetitorApp[] }
|
||||
export interface CompetitorSnapshot { date: string; app: { appId: string | null; bundleId: string }; top: number; rows: CompetitorRow[] }
|
||||
|
||||
const isUs = (r: SearchApp, app: { appId?: string; bundleId?: string }) => !!((app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId));
|
||||
|
||||
/** One term's Search API results -> the top n other apps (and our own position among the results read). Pure. */
|
||||
export function competitorRow(results: SearchApp[], app: { appId?: string; bundleId?: string }, q: { storefront: string; locale: string; term: string }, n: number): CompetitorRow {
|
||||
const i = results.findIndex(r => isUs(r, app));
|
||||
const apps = results.map((r, k) => ({ r, k })).filter(({ r }) => !isUs(r, app)).slice(0, n).map(({ r, k }): CompetitorApp => ({
|
||||
rank: k + 1, id: String(r.trackId), name: r.trackName, developer: r.sellerName ?? '', ratings: r.userRatingCount ?? 0, rating: r.averageUserRating ?? null,
|
||||
released: r.releaseDate?.slice(0, 10) ?? null, updated: r.currentVersionReleaseDate?.slice(0, 10) ?? null, genre: r.primaryGenreName ?? '',
|
||||
genres: (r.genreIds ?? []).map((id, j) => ({ id: String(id), name: r.genres?.[j] ?? '' })).filter(g => g.name),
|
||||
}));
|
||||
return { ...q, results: results.length, ourRank: i >= 0 ? i + 1 : null, apps };
|
||||
}
|
||||
|
||||
/** Distinct apps of the rows (one storefront / locale), first seen first. Pure. */
|
||||
export function distinctApps(rows: CompetitorRow[]): CompetitorApp[] {
|
||||
const seen = new Map<string, CompetitorApp>();
|
||||
for (const r of rows) for (const a of r.apps) if (!seen.has(a.id)) seen.set(a.id, a);
|
||||
return [...seen.values()];
|
||||
}
|
||||
|
||||
export interface Gap { word: string; apps: number; developers: number; terms: string[]; examples: string[] }
|
||||
|
||||
/**
|
||||
* Words in competitors' names that our name, subtitle and keyword field do not cover. A word only counts when apps of at
|
||||
* least two different developers use it: a word one developer uses is most likely a brand (and other apps' names and
|
||||
* trademarks must never go into a keyword field). Pure.
|
||||
*/
|
||||
export function coverageGaps(rows: CompetitorRow[], covered: Iterable<string>, locale: string, max = 15): Gap[] {
|
||||
const have = [...covered];
|
||||
const by = new Map<string, { apps: Set<string>; devs: Set<string>; terms: Set<string>; examples: string[] }>();
|
||||
for (const r of rows) for (const a of r.apps) for (const w of new Set(tokens(a.name, locale))) {
|
||||
if (w.length < 3 || coveredBy(w, have, locale)) continue;
|
||||
const k = stem(w, locale);
|
||||
const g = by.get(k) ?? { apps: new Set(), devs: new Set(), terms: new Set(), examples: [] };
|
||||
if (!g.apps.has(a.id) && g.examples.length < 3) g.examples.push(a.name);
|
||||
g.apps.add(a.id); g.devs.add(a.developer.toLowerCase()); g.terms.add(r.term);
|
||||
by.set(k, g);
|
||||
}
|
||||
return [...by.entries()].filter(([, g]) => g.devs.size >= 2)
|
||||
.map(([word, g]) => ({ word, apps: g.apps.size, developers: g.devs.size, terms: [...g.terms], examples: g.examples }))
|
||||
.sort((a, b) => b.developers - a.developers || b.apps - a.apps || a.word.localeCompare(b.word)).slice(0, max);
|
||||
}
|
||||
|
||||
/** Apps in the top N now that were not there in the previous snapshot, per storefront + term. Pure. */
|
||||
export function newEntrants(now: CompetitorRow[], before: CompetitorRow[] | undefined): Map<string, string[]> {
|
||||
const out = new Map<string, string[]>();
|
||||
if (!before) return out;
|
||||
const prev = new Map(before.map(r => [`${r.storefront}|${r.term.toLowerCase()}`, new Set(r.apps.map(a => a.id))] as const));
|
||||
for (const r of now) {
|
||||
const p = prev.get(`${r.storefront}|${r.term.toLowerCase()}`);
|
||||
if (p) out.set(`${r.storefront}|${r.term.toLowerCase()}`, r.apps.filter(a => !p.has(a.id)).map(a => a.name));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The category names of the app in one storefront's language, read from the Search API results' localized genres. Pure. */
|
||||
export function categoryNames(rows: CompetitorRow[], categoryIds: string[]): string[] {
|
||||
const ids = new Set(categoryIds.map(c => GENRE_IDS[c]).filter(Boolean));
|
||||
const names = new Set<string>();
|
||||
for (const a of distinctApps(rows)) for (const g of a.genres) if (ids.has(g.id)) names.add(g.name);
|
||||
return [...names];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// Apple Ads keyword suggestions
|
||||
|
||||
export const ADS_KEYWORD_SUGGESTIONS = '/suggestions/keywords/query';
|
||||
|
||||
/** RecommendationQueryRequest for keyword suggestions: the two required filters, seed terms, countries. Pure. */
|
||||
export function keywordSuggestionBody(adamId: string, terms: string[], countries: string[], pageSize = 200): Record<string, unknown> {
|
||||
const filters: Record<string, unknown>[] = [
|
||||
{ field: 'promotedObjectId', operator: 'EQUALS', value: [adamId] },
|
||||
{ field: 'promotedObjectType', operator: 'EQUALS', value: ['APPSTORE_APP'] },
|
||||
];
|
||||
if (terms.length) filters.push({ field: 'terms', operator: 'IN', value: terms });
|
||||
if (countries.length) filters.push({ field: 'countriesOrRegions', operator: 'IN', value: countries.map(c => c.toUpperCase()) });
|
||||
return { filters, sorting: [{ field: 'popularity', order: 'DESC' }], pagination: { offset: 0, pageSize: Math.min(1000, Math.max(1, pageSize)) } };
|
||||
}
|
||||
|
||||
export interface AdsSuggestion { text: string; popularity: number }
|
||||
/** `result` of the keyword suggestions answer -> { text, popularity } (0-100), invalid rows left out. Pure. */
|
||||
export function parseKeywordSuggestions(res: unknown): AdsSuggestion[] {
|
||||
const rows = (res as { result?: unknown })?.result;
|
||||
if (!Array.isArray(rows)) return [];
|
||||
return rows.filter((r): r is { text: string; popularity: number } => typeof r?.text === 'string' && typeof r?.popularity === 'number')
|
||||
.map(r => ({ text: r.text.trim(), popularity: Math.max(0, Math.min(100, Math.round(r.popularity))) })).filter(r => r.text);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// Candidates and scoring
|
||||
|
||||
export type CandSource = 'name' | 'subtitle' | 'keywords' | 'description' | 'competitors' | 'category' | 'apple-ads';
|
||||
export type CandStatus = 'candidate' | 'indexed' | 'category' | 'filler';
|
||||
export interface Candidate {
|
||||
term: string;
|
||||
kind: 'word' | 'phrase';
|
||||
sources: CandSource[];
|
||||
/** Times in our own name / subtitle / description. */
|
||||
ours: number;
|
||||
/** relevance 0-2: +1 in our own text (name, subtitle, description, keywords), +1 in competitor names (the top apps). */
|
||||
relevance: number;
|
||||
/** Competition: how many of the distinct top apps already have it in their name, of how many read. */
|
||||
inNames: number; ofApps: number;
|
||||
/** Apple Ads relative popularity 0-100, null = unknown (no credentials, or Apple returned nothing for it). */
|
||||
popularity: number | null;
|
||||
/** exact: Apple Ads suggested this exact word; phrase: the highest score of a suggested phrase that contains it. */
|
||||
popularityFrom: 'exact' | 'phrase' | null;
|
||||
status: CandStatus;
|
||||
why?: string;
|
||||
}
|
||||
|
||||
export interface CandidateInput {
|
||||
locale: string;
|
||||
name: string; subtitle: string; keywords: string; description: string;
|
||||
/** The competitor rows of this locale's storefront (latest `aso competitors` snapshot), may be empty. */
|
||||
competitors: CompetitorRow[];
|
||||
/** Category names in this language (categoryNames); matched by Apple anyway, so never put into the field. */
|
||||
categories: string[];
|
||||
ads: AdsSuggestion[];
|
||||
}
|
||||
|
||||
/** Every keyword candidate of one locale with its signals. Sorted: candidates first, by relevance, popularity (known
|
||||
* first), lower competition, then how often our own text uses it. Pure. */
|
||||
export function candidates(i: CandidateInput): Candidate[] {
|
||||
const L = i.locale;
|
||||
const m = new Map<string, Candidate>();
|
||||
const key = (t: string) => t.split(' ').map(w => stem(w, L)).join(' ');
|
||||
const add = (term: string, kind: Candidate['kind'], src: CandSource, n = 1) => {
|
||||
const k = key(term);
|
||||
const c = m.get(k) ?? { term, kind, sources: [], ours: 0, relevance: 0, inNames: 0, ofApps: 0, popularity: null, popularityFrom: null, status: 'candidate' as CandStatus };
|
||||
if (!c.sources.includes(src)) c.sources.push(src);
|
||||
if (src === 'name' || src === 'subtitle' || src === 'description') c.ours += n;
|
||||
m.set(k, c);
|
||||
};
|
||||
for (const [src, text] of [['name', i.name], ['subtitle', i.subtitle], ['description', i.description]] as const) for (const w of tokens(text, L)) if (w.length > 2) add(w, 'word', src);
|
||||
for (const w of i.keywords.split(',').flatMap(t => tokens(t, L))) if (w.length > 1) add(w, 'word', 'keywords');
|
||||
// phrases: only the ones our own text uses at least twice, or that stand in the name / subtitle
|
||||
const phraseCount = new Map<string, number>();
|
||||
for (const b of [...bigrams(i.name, L), ...bigrams(i.subtitle, L), ...bigrams(i.subtitle, L), ...bigrams(i.description, L)]) phraseCount.set(b, (phraseCount.get(b) ?? 0) + 1);
|
||||
for (const [b, n] of phraseCount) if (n >= 2) add(b, 'phrase', 'description', n);
|
||||
const apps = distinctApps(i.competitors);
|
||||
const nameWords = apps.map(a => new Set(tokens(a.name, L).map(w => stem(w, L))));
|
||||
for (const g of coverageGaps(i.competitors, [], L, 200)) add(g.word, 'word', 'competitors');
|
||||
const catWords = [...new Set(i.categories.flatMap(c => words(c, L)))];
|
||||
const cats = new Set(catWords.map(w => stem(w, L)));
|
||||
for (const c of catWords) add(c, 'word', 'category');
|
||||
for (const s of i.ads) {
|
||||
const ws = tokens(s.text, L);
|
||||
if (ws.length === 1) add(ws[0]!, 'word', 'apple-ads');
|
||||
}
|
||||
const indexed = [...tokens(i.name, L), ...tokens(i.subtitle, L)];
|
||||
for (const c of m.values()) {
|
||||
const ws = c.term.split(' ').map(w => stem(w, L));
|
||||
const inOurs = c.ours > 0 || c.sources.includes('keywords');
|
||||
c.inNames = nameWords.filter(n => ws.every(w => n.has(w))).length;
|
||||
c.ofApps = apps.length;
|
||||
c.relevance = (inOurs ? 1 : 0) + (c.inNames > 0 ? 1 : 0);
|
||||
const exact = i.ads.find(s => key(s.text.toLocaleLowerCase(L)) === key(c.term));
|
||||
const phrases = i.ads.filter(s => ws.every(w => tokens(s.text, L).map(x => stem(x, L)).includes(w)));
|
||||
if (exact) { c.popularity = exact.popularity; c.popularityFrom = 'exact'; }
|
||||
else if (phrases.length) { c.popularity = Math.max(...phrases.map(s => s.popularity)); c.popularityFrom = 'phrase'; }
|
||||
if (ws.some(w => cats.has(w)) && ws.length === 1) { c.status = 'category'; c.why = 'category name: matched by Apple anyway'; }
|
||||
else if (ws.every(w => coveredBy(w, indexed, L))) { c.status = 'indexed'; c.why = 'already in the name / subtitle (indexed)'; }
|
||||
else if (ws.some(w => FILLER.has(w))) { c.status = 'filler'; c.why = 'filler word'; }
|
||||
}
|
||||
const order = (c: Candidate) => (c.status === 'candidate' ? 0 : 1);
|
||||
// a word only the description uses once is noise, unless competitors or Apple Ads bring it up too
|
||||
const weak = (c: Candidate) => c.sources.length === 1 && c.sources[0] === 'description' && c.ours < 2;
|
||||
return [...m.values()].filter(c => !weak(c)).sort((a, b) => order(a) - order(b) || b.relevance - a.relevance || (b.popularity ?? -1) - (a.popularity ?? -1)
|
||||
|| a.inNames - b.inNames || b.ours - a.ours || a.term.localeCompare(b.term));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// The 100-byte keyword field
|
||||
|
||||
export interface FieldProposal { locale: string; before: string; after: string; bytes: number; kept: string[]; added: string[]; dropped: { term: string; why: string }[] }
|
||||
|
||||
const bytes = (s: string) => Buffer.byteLength(s, 'utf8');
|
||||
|
||||
/**
|
||||
* A keyword field for one locale that fits 100 bytes (UTF-8) with the existing rules: commas without spaces, no
|
||||
* duplicates (plural-insensitive), no words of the name / subtitle, no filler or category words, single words. Current
|
||||
* terms that are still valid are kept first (change a few terms per release, not all), unless `fresh`; then the best
|
||||
* candidates fill the room. Pure.
|
||||
*/
|
||||
export function fitKeywordField(o: { locale: string; current: string; name: string; subtitle: string; ranked: Candidate[]; fresh?: boolean; limit?: number }): FieldProposal {
|
||||
const L = o.locale, limit = o.limit ?? 100;
|
||||
const indexed = [...tokens(o.name, L), ...tokens(o.subtitle, L)];
|
||||
const blocked = new Map(o.ranked.filter(c => c.status !== 'candidate' && c.kind === 'word').map(c => [stem(c.term, L), c.why ?? c.status] as const));
|
||||
const out: string[] = [], kept: string[] = [], added: string[] = [], dropped: { term: string; why: string }[] = [];
|
||||
const seen: string[] = [];
|
||||
const fits = (t: string) => bytes([...out, t].join(',')) <= limit;
|
||||
const tryAdd = (t: string, into: string[]): string | null => {
|
||||
const ws = words(t, L);
|
||||
if (!ws.length) return 'empty';
|
||||
if (ws.every(w => coveredBy(w, indexed, L))) return 'already in the name / subtitle (indexed)';
|
||||
if (ws.some(w => FILLER.has(w))) return 'filler word';
|
||||
if (ws.length === 1 ? coveredBy(ws[0]!, seen, L) : seen.includes(ws.join(' '))) return 'duplicate';
|
||||
const b = ws.length === 1 ? blocked.get(stem(ws[0]!, L)) : undefined;
|
||||
if (b) return b;
|
||||
if (!fits(t)) return 'no room in 100 bytes';
|
||||
seen.push(ws.length === 1 ? ws[0]! : ws.join(' ')); out.push(t); into.push(t);
|
||||
return null;
|
||||
};
|
||||
if (!o.fresh) for (const t of o.current.split(',').map(s => s.trim().toLocaleLowerCase(L)).filter(Boolean)) {
|
||||
// keep a current phrase as the words it is made of: single words combine on their own and save bytes
|
||||
const parts = /\s/.test(t) ? tokens(t, L) : [t];
|
||||
for (const p of parts) { const why = tryAdd(p, kept); if (why && why !== 'duplicate') dropped.push({ term: p, why }); }
|
||||
}
|
||||
for (const c of o.ranked) {
|
||||
if (c.status !== 'candidate' || c.kind !== 'word') continue;
|
||||
tryAdd(c.term, added);
|
||||
}
|
||||
const after = out.join(',');
|
||||
return { locale: L, before: o.current, after, bytes: bytes(after), kept, added, dropped };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// Writing the proposal into store/appstore.md (only with --write; marked as a draft for review)
|
||||
|
||||
export const DRAFT_RE = /^<!--\s*storebound-aso:\s*draft\b[^>]*-->\s*$/m;
|
||||
export const draftMark = (date: string): string => `<!-- storebound-aso: draft keywords from \`aso suggest\` ${date}; review them, then delete this line -->`;
|
||||
|
||||
/** Locales of store/appstore.md whose keywords carry the draft line. Pure. */
|
||||
export function draftLocales(md: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const sec of md.split(/^(?=## )/m)) {
|
||||
if (!sec.startsWith('## ')) continue;
|
||||
const kw = sec.split(/^(?=### )/m).find(p => /^### keywords\s*$/m.test(p.split('\n')[0]!));
|
||||
if (kw && DRAFT_RE.test(kw)) out.push(sec.slice(3).split(/[\s·]/)[0]!.trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** store/appstore.md with the keywords block of `locale` set to `value` and the draft line above it. Pure. */
|
||||
export function setKeywords(md: string, locale: string, value: string, mark: string): string {
|
||||
const secs = md.split(/^(?=## )/m);
|
||||
const i = secs.findIndex(s => s.startsWith('## ') && s.slice(3).split(/[\s·]/)[0]!.trim() === locale);
|
||||
if (i < 0) throw new Error(`no "## ${locale}" section in the App Store listing`);
|
||||
const parts = secs[i]!.split(/^(?=### )/m);
|
||||
const block = `### keywords\n${mark}\n\`\`\`\n${value}\n\`\`\`\n`;
|
||||
const k = parts.findIndex(p => /^### keywords\s*$/.test(p.split('\n')[0]!));
|
||||
if (k >= 0) {
|
||||
const old = parts[k]!;
|
||||
const fence = /^```[^\n]*\n[\s\S]*?\n```[^\n]*\n?/m.exec(old);
|
||||
const tail = fence ? old.slice(fence.index + fence[0].length) : old.split('\n').slice(1).join('\n');
|
||||
parts[k] = block + tail.replace(DRAFT_RE, '').replace(/^\n+/, '\n');
|
||||
if (!/\n$/.test(parts[k]!)) parts[k] += '\n';
|
||||
} else {
|
||||
const last = parts.length - 1;
|
||||
parts[last] = parts[last]!.replace(/\n*$/, '\n\n') + block + (i < secs.length - 1 ? '\n' : '');
|
||||
}
|
||||
secs[i] = parts.join('');
|
||||
return secs.join('');
|
||||
}
|
||||
|
||||
/** "us" for en-US, "tr" for tr, "jp" for ja ... : the storefront a locale is most likely meant for. Pure. */
|
||||
export function storefrontOf(locale: string): string {
|
||||
const [l, r] = locale.split('-');
|
||||
if (r && /^[A-Za-z]{2}$/.test(r)) return r.toLowerCase();
|
||||
const map: Record<string, string> = { ja: 'jp', ko: 'kr', zh: locale === 'zh-Hant' ? 'tw' : 'cn', el: 'gr', he: 'il', hi: 'in', uk: 'ua', vi: 'vn', cs: 'cz', da: 'dk', sv: 'se', nb: 'no', ms: 'my', ca: 'es', en: 'us', ar: 'sa' };
|
||||
return map[l!.toLowerCase()] ?? l!.toLowerCase();
|
||||
}
|
||||
|
|
@ -8,14 +8,18 @@
|
|||
// title (trackName), developer (sellerName), bundleId, rating and description, but no subtitle: competitor subtitles
|
||||
// are not available through a public API, so they are not shown (storebound scrapes nothing).
|
||||
// Result fields used (as the API returns them; Apple's table lists only the general ones): trackId, trackName,
|
||||
// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName.
|
||||
// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName; `aso competitors` also releaseDate,
|
||||
// currentVersionReleaseDate, genres (localized to the storefront, e.g. "Produktivität" for country=de) and genreIds.
|
||||
|
||||
export const SEARCH_API = 'https://itunes.apple.com/search';
|
||||
/** Apple: about 20 calls per minute. One call every 3.5 s stays below it with room for retries. */
|
||||
export const MIN_DELAY_MS = 3_500;
|
||||
export const MAX_RESULTS = 200;
|
||||
|
||||
export interface SearchApp { trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string }
|
||||
export interface SearchApp {
|
||||
trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string;
|
||||
releaseDate?: string; currentVersionReleaseDate?: string; genres?: string[]; genreIds?: string[]; primaryGenreId?: number;
|
||||
}
|
||||
|
||||
export function searchUrl(term: string, country: string, limit = MAX_RESULTS): string {
|
||||
if (!/^[a-z]{2}$/i.test(country)) throw new Error(`storefront "${country}": a two-letter country code (us, de, tr)`);
|
||||
|
|
|
|||
|
|
@ -16,9 +16,9 @@ export const CROSS_LOCALES: Record<string, string[]> = {
|
|||
};
|
||||
|
||||
/** Words that add nothing in the keyword field (Apple: the category name and "app" are matched anyway). */
|
||||
const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']);
|
||||
export const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']);
|
||||
|
||||
const words = (s: string, locale: string): string[] =>
|
||||
export const words = (s: string, locale: string): string[] =>
|
||||
s.toLocaleLowerCase(locale).split(/[^\p{L}\p{N}]+/u).filter(w => w.length > 1);
|
||||
|
||||
/** One locale of the App Store listing: keyword field rules. */
|
||||
|
|
|
|||
|
|
@ -101,6 +101,12 @@ export interface ShotFrame { src: string; x?: number; dy?: number; scale?: numbe
|
|||
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 }
|
||||
|
||||
/** A local font file for shots.fonts. license: 'OFL-1.1', 'proprietary' or a short note (shown by `shots fonts`;
|
||||
* `shots check` warns without one). weight / style: the @font-face descriptors (default: all weights, normal). */
|
||||
export interface LocalFontSpec { family?: string; file: string; weight?: number | string; style?: 'normal' | 'italic'; license?: string }
|
||||
/** A Google Fonts family name, a local font path (relative to the config) or a LocalFontSpec. */
|
||||
export type FontSpec = string | LocalFontSpec;
|
||||
|
||||
export interface ShotsConfig {
|
||||
/** Look of the rendered screenshots: game (sunburst, sparkles, badges, bold outlined titles) or app (calm gradient,
|
||||
* device frame, headline + subline, no sparkles or badges). Default: app for the app / subscription-app profiles,
|
||||
|
|
@ -114,11 +120,12 @@ export interface ShotsConfig {
|
|||
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`). Default: game Paytone One +
|
||||
* Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: Noto families you accept for
|
||||
* characters the title / body font lacks (e.g. ['Noto Sans Display']); without it a render that needs an automatic
|
||||
* fallback is an ERROR in `shots check`. */
|
||||
fonts?: { title?: string; body?: string; fallback?: string[] };
|
||||
/** Fonts for titles / body text: a Google Fonts family (downloaded and subset by `shots fonts`), or your own font file
|
||||
* (a path relative to the config, TTF / OTF / WOFF / WOFF2, or { family, file, weight?, style?, license? }).
|
||||
* Default: game Paytone One + Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: fonts you
|
||||
* accept for characters the title / body font lacks, tried in order before the automatic Noto fallbacks (e.g.
|
||||
* ['Noto Sans Display'] or a local file); a render that needs an automatic fallback is an ERROR in `shots check`. */
|
||||
fonts?: { title?: FontSpec; body?: FontSpec; fallback?: FontSpec[] };
|
||||
scenes: ShotScene[];
|
||||
feature?: { frame: string; palette?: string | Palette };
|
||||
/** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar).
|
||||
|
|
@ -866,6 +873,19 @@ export function validateConfig(c: unknown): string[] {
|
|||
for (const k of ['copy', 'frames', 'out'] as const) if (!s[k]) e.push(`shots.${k}: missing`);
|
||||
if (s.style !== undefined && s.style !== 'game' && s.style !== 'app') e.push('shots.style: game | app');
|
||||
if (!s.scenes?.length) e.push('shots.scenes: at least one scene');
|
||||
const fontKeys: [string, unknown][] = [['title', s.fonts?.title], ['body', s.fonts?.body], ...(Array.isArray(s.fonts?.fallback) ? s.fonts!.fallback! : s.fonts?.fallback !== undefined ? [s.fonts.fallback] : []).map((f, i) => [`fallback[${i}]`, f] as [string, unknown])];
|
||||
if (s.fonts?.fallback !== undefined && !Array.isArray(s.fonts.fallback)) e.push('shots.fonts.fallback: a list');
|
||||
for (const [k, f] of fontKeys) {
|
||||
if (f === undefined) continue;
|
||||
if (typeof f === 'string') { if (!f.trim()) e.push(`shots.fonts.${k}: empty`); else if (/[\\/]|\.[a-z0-9]{2,5}$/i.test(f) && !/\.(ttf|otf|woff2?)$/i.test(f)) e.push(`shots.fonts.${k}: ${f}: a font file must be TTF, OTF, WOFF or WOFF2`); continue; }
|
||||
const o = f as Partial<LocalFontSpec>;
|
||||
if (!o || typeof o !== 'object' || typeof o.file !== 'string') { e.push(`shots.fonts.${k}: a Google Fonts family, a font file path or { family, file, weight?, style?, license? }`); continue; }
|
||||
if (!/\.(ttf|otf|woff2?)$/i.test(o.file)) e.push(`shots.fonts.${k}.file: ${o.file}: TTF, OTF, WOFF or WOFF2`);
|
||||
if (o.family !== undefined && (typeof o.family !== 'string' || !o.family.trim())) e.push(`shots.fonts.${k}.family: a name`);
|
||||
if (o.style !== undefined && o.style !== 'normal' && o.style !== 'italic') e.push(`shots.fonts.${k}.style: normal | italic`);
|
||||
if (o.weight !== undefined && !/^\d{3}( \d{3})?$/.test(String(o.weight))) e.push(`shots.fonts.${k}.weight: e.g. 400, 800 or "100 900"`);
|
||||
if (o.license !== undefined && typeof o.license !== 'string') e.push(`shots.fonts.${k}.license: text ('OFL-1.1', 'proprietary', ...)`);
|
||||
}
|
||||
for (const sc of s.scenes ?? []) if (!sc.frames?.length) e.push(`shots.scenes[${sc.id}].frames: at least one frame`);
|
||||
e.push(...validateCapture(s.capture));
|
||||
const sceneIds = new Set((s.scenes ?? []).map(x => x.id));
|
||||
|
|
|
|||
|
|
@ -322,6 +322,17 @@ export interface AnalyticsCompare {
|
|||
/** Per store with no days in any snapshot: why the newest snapshot has none (no report request yet, no bucket). */
|
||||
errors?: { apple?: string; play?: string };
|
||||
}
|
||||
/** aso.audit (`aso audit --json`, offline, cli/lib/aso-audit.ts AsoAudit): the parts the Growth tab's ASO card shows. */
|
||||
export interface AsoTrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: '↑' | '↓' | '→' | 'new' | 'lost' | '·'; best: number | null; snapshots: number }
|
||||
export interface AsoAuditView {
|
||||
generated: string;
|
||||
keywordField: { errors: number; warnings: number; hints: number; findings: { level: 'error' | 'warn' | 'info'; where: string; msg: string }[] };
|
||||
drafts: string[];
|
||||
ranks: { snapshots: number; latest: string | null; rows: AsoTrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] };
|
||||
competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: { word: string; apps: number; developers: number }[] }[] };
|
||||
experiments: { store: 'apple' | 'play'; what: string; why: string; how: string }[];
|
||||
next: { what: string; why: string; command?: string }[];
|
||||
}
|
||||
/** console.fill (`console fill <form> --json`, cli/console/fill.ts): the answers it types into one console form. The
|
||||
* dry run has the answers only; the real run (it ends when the owner closes the browser) adds what happened. */
|
||||
export type ConsoleForm = 'apple-app-record' | 'apple-age-rating' | 'apple-app-privacy' | 'play-app-record' | 'play-content-rating' | 'play-target-audience';
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -116,7 +116,10 @@ const COMPETITORS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat',
|
|||
'amazon', 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run',
|
||||
'angry birds', 'tetris', 'wordle', 'duolingo', 'zoom', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'notion', 'evernote', 'photoshop', 'canva', 'capcut', 'iphone', 'ipad', 'apple'];
|
||||
const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/;
|
||||
const PLACEHOLDER = /lorem ipsum|\bTODO\b|\bTBD\b|\bFIXME\b|\bplaceholder\b|\bXXX\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
|
||||
// Developer markers count only in capitals ("TODO:", "FIXME"): "todo" is a real word and keyword (a to-do app).
|
||||
const PLACEHOLDER_MARKERS = /\bTODO\b|\bTBD\b|\bFIXME\b|\bXXX\b/;
|
||||
const PLACEHOLDER_TEXT = /lorem ipsum|\bplaceholder\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
|
||||
const PLACEHOLDER = { test: (l: string) => PLACEHOLDER_MARKERS.test(l) || PLACEHOLDER_TEXT.test(l) } as RegExp;
|
||||
const FGS_PERMISSION: Record<string, string> = {
|
||||
camera: 'CAMERA', connectedDevice: 'CONNECTED_DEVICE', dataSync: 'DATA_SYNC', health: 'HEALTH', location: 'LOCATION', mediaPlayback: 'MEDIA_PLAYBACK',
|
||||
mediaProjection: 'MEDIA_PROJECTION', microphone: 'MICROPHONE', phoneCall: 'PHONE_CALL', remoteMessaging: 'REMOTE_MESSAGING', specialUse: 'SPECIAL_USE',
|
||||
|
|
|
|||
|
|
@ -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`);
|
||||
|
|
|
|||
|
|
@ -163,7 +163,8 @@ export const TOOLS: ToolDef[] = [
|
|||
props: { only, csv: { type: 'string', description: 'Prices CSV with rows for subscription ids' } },
|
||||
args: i => [...opt('only', i.only), ...opt('csv', i.csv)] },
|
||||
{ name: 'play_data_safety', title: 'Push Play Data safety', command: ['play', 'data-safety'], write: true, destructive: true, network: true, idempotent: true,
|
||||
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). dry_run prints the CSV.' },
|
||||
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). Skipped when the CSV equals the last upload of this project (hash in .storebound/; force: true sends it anyway). dry_run prints the CSV.',
|
||||
props: { force: { type: 'boolean', default: false, description: 'Upload even when the CSV equals the last upload (after a manual change in Play Console)' } }, args: i => flag('force', i.force) },
|
||||
{ name: 'play_release_testing', title: 'Release to a Play testing track', command: ['play', 'release'], write: true, network: true,
|
||||
description: 'Upload an AAB (or reuse a versionCode) to a TESTING track (internal, alpha, beta) with release notes. Production is not available here.',
|
||||
props: { aab: { type: 'string', description: 'Path to the .aab' }, version_code: { type: 'integer', minimum: 1 },
|
||||
|
|
@ -356,6 +357,20 @@ export const TOOLS: ToolDef[] = [
|
|||
props: { storefronts: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,de=de-DE (default us)' }, keywords: { type: 'string', description: 'Extra keywords, comma-separated' },
|
||||
competitors: { type: 'integer', minimum: 0, maximum: 10, default: 3 } },
|
||||
args: i => [...opt('storefronts', i.storefronts), ...opt('keywords', i.keywords), ...opt('competitors', i.competitors), '--json'] },
|
||||
{ name: 'aso_competitors', title: 'App Store competitors per keyword', command: ['aso', 'competitors'], write: false, network: true,
|
||||
description: 'Read-only: for each keyword of the locale\'s keyword field (plus terms) and storefront, the top apps in Apple\'s public iTunes Search API (name, developer, rating count, first release, last update, localized genre) and the words in their names that your name / subtitle / keywords do not cover (only words of at least two developers: a one-developer word is likely a brand). One request every 3.5 s. Saves no snapshot (the terminal run `storebound aso competitors` does). Search API order is close to, not equal to, App Store search; competitor subtitles are not in any public API.',
|
||||
props: { storefront: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,tr (default us)' },
|
||||
terms: { type: 'string', description: 'Extra terms, comma-separated' }, top: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
|
||||
args: i => [...opt('storefront', i.storefront), ...opt('term', i.terms), ...opt('top', i.top), '--no-save', '--json'] },
|
||||
{ name: 'aso_suggest', title: 'Keyword field proposal', command: ['aso', 'suggest'], write: false, network: true,
|
||||
description: 'Read-only proposal: keyword candidates per App Store locale from your own name / subtitle / description, the latest `aso competitors` snapshot, the localized category names and, when Apple Ads credentials exist, Apple Ads keyword suggestions (relative popularity 0-100; without credentials popularity is "unknown", never estimated). Scores relevance (own text, competitor names) and competition (top apps with the word in their name) and returns a 100-byte keyword field per locale as old -> new. Never writes: the owner runs `storebound aso suggest --write` in a terminal, which marks the result as a draft for review.',
|
||||
props: { locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale of store/appstore.md)' },
|
||||
fresh: { type: 'boolean', default: false, description: 'Do not keep the current keywords first' }, offline: { type: 'boolean', default: false, description: 'Skip Apple Ads' } },
|
||||
args: i => [...opt('locale', i.locale), ...flag('fresh', i.fresh), ...flag('offline', i.offline), '--json'] },
|
||||
{ name: 'aso_audit', title: 'ASO audit', command: ['aso', 'audit'], write: false, network: false,
|
||||
description: 'Offline ASO report: keyword field findings (check --aso), cross-locale free keyword room, rank trend from the `aso rank` snapshots, competitor coverage gaps, Play short description use and keyword density, App Store analytics conversion from the snapshots, Product Page Optimization / Play experiment ideas (suggestions only) and the next 3 actions.',
|
||||
props: { storefront: { type: 'string', description: 'App Store storefront for the cross-locale hint', default: 'US' } },
|
||||
args: i => [...opt('storefront', i.storefront), '--json'] },
|
||||
{ name: 'ads_scan', title: 'AdAttributionKit scan', command: ['ads', 'scan'], write: false, network: false,
|
||||
description: 'Local scan of an iOS project for AdAttributionKit and SKAdNetwork: ad network ids (SKAdNetworkItems, AdNetworkIdentifiers, lowercase), postback copy endpoints (AttributionCopyEndpoint, re-engagement copies, NSAdvertisingAttributionReportEndpoint), attribution windows and cooldown, conversion value updates in code, ad SDKs without ids.',
|
||||
props: { ios: { type: 'string', description: 'Path of the iOS project folder, e.g. ios/App' } }, required: ['ios'], args: i => [...opt('ios', i.ios), '--json'] },
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
// Play Data safety form through applications.dataSafety (CSV import; replaces every earlier answer).
|
||||
// storebound play data-safety [--csv out.csv] [--dry]
|
||||
// storebound play data-safety [--csv out.csv] [--dry] [--force]
|
||||
// Answers come from `dataSafety` in storebound.config.ts. --dry only writes / prints the CSV.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
// Play cannot read the form back, so a run compares with what this project uploaded last: the sha256 of that CSV
|
||||
// (per package) is kept in .storebound/data-safety.sha256 (gitignored). The same CSV is not sent again; --force sends it
|
||||
// anyway (e.g. after the form was changed in Play Console by hand).
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
|
|
@ -10,6 +13,27 @@ import { DATA_SAFETY_UPLOADED } from '../lib/declarations';
|
|||
import { done, log } from '../lib/log';
|
||||
import { playClient } from './client';
|
||||
|
||||
export const DATA_SAFETY_HASH = '.storebound/data-safety.sha256';
|
||||
|
||||
/** sha256 of the CSV for one package. Pure. */
|
||||
export const dataSafetyHash = (pkg: string, csv: string): string => new Bun.CryptoHasher('sha256').update(`${pkg}\n${csv}`).digest('hex');
|
||||
|
||||
/** The hash of the last upload of this package, null when none is recorded. */
|
||||
export function lastUpload(root: string, pkg: string): { sha256: string; at: string } | null {
|
||||
const f = join(root, DATA_SAFETY_HASH);
|
||||
if (!existsSync(f)) return null;
|
||||
try { return (JSON.parse(readFileSync(f, 'utf8')) as Record<string, { sha256: string; at: string }>)[pkg] ?? null; } catch { return null; }
|
||||
}
|
||||
|
||||
function rememberUpload(root: string, pkg: string, sha256: string): void {
|
||||
const f = join(root, DATA_SAFETY_HASH);
|
||||
let all: Record<string, { sha256: string; at: string }> = {};
|
||||
try { if (existsSync(f)) all = JSON.parse(readFileSync(f, 'utf8')); } catch { all = {}; }
|
||||
all[pkg] = { sha256, at: new Date().toISOString() };
|
||||
mkdirSync(join(root, '.storebound'), { recursive: true });
|
||||
writeFileSync(f, JSON.stringify(all, null, 2) + '\n');
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const csv = dataSafetyCsv(need(config.dataSafety, 'dataSafety'));
|
||||
|
|
@ -17,10 +41,25 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
if (out) { writeFileSync(resolve(out), csv); log('play', `wrote ${out}`); }
|
||||
const types = Object.keys(config.dataSafety!.data);
|
||||
log('play', `data safety: ${types.length} data types declared (${types.join(', ') || 'none'})`);
|
||||
if (ctx.args.has('dry')) { if (!out) process.stdout.write(csv); return; }
|
||||
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
|
||||
const pkg = need(config.play?.packageName, 'play.packageName');
|
||||
const hash = dataSafetyHash(pkg, csv);
|
||||
const last = lastUpload(root, pkg);
|
||||
const same = last?.sha256 === hash;
|
||||
if (ctx.args.has('dry')) {
|
||||
if (!out) process.stdout.write(csv);
|
||||
log('play', same ? `the same CSV was uploaded ${last!.at.slice(0, 16).replace('T', ' ')} UTC: a real run sends nothing (--force sends it again)` : 'a real run uploads it (it differs from the last upload, or none is recorded)');
|
||||
return;
|
||||
}
|
||||
if (same && !ctx.args.has('force')) {
|
||||
done('play', `data safety unchanged since the upload of ${last!.at.slice(0, 16).replace('T', ' ')} UTC: nothing sent (--force sends it again, e.g. after a change in Play Console)`);
|
||||
return;
|
||||
}
|
||||
const play = await playClient(root, pkg);
|
||||
await play.call('POST', `${play.API}/dataSafety`, { safetyLabels: csv });
|
||||
// Play cannot read the form back: keep what went up, so the desktop app can show what changed since (gitignored).
|
||||
try { mkdirSync(join(root, '.storebound'), { recursive: true }); writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv); } catch { /* the upload itself worked */ }
|
||||
// keep what went up: the hash skips the next identical upload, the CSV lets the desktop app show what changed since
|
||||
try {
|
||||
rememberUpload(root, pkg, hash);
|
||||
writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv);
|
||||
} catch { /* the upload itself worked */ }
|
||||
done('play', `data safety updated (${csv.split('\n').length - 2} rows)`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -140,16 +140,24 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
if (dry) { done('play', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
|
||||
if (!p.changes) { done('play', 'listing already up to date'); return; }
|
||||
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to Google Play (one edit, committed)?`))) { warn('play', 'nothing written'); return; }
|
||||
const todo = p.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
|
||||
await play.edit(async id => {
|
||||
if (p.details.action !== 'same') {
|
||||
// The edit compares again with what it holds (a Console save or another run since the plan): only differing details
|
||||
// and languages are PUT; nothing left to change = the edit is deleted, not committed. Commit only after every PUT worked.
|
||||
let sent = 0;
|
||||
await play.edit(async (id, ctl) => {
|
||||
const cur = await play.call<Record<string, string>>('GET', `${play.API}/edits/${id}/details`);
|
||||
const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? [];
|
||||
const q = playPlan(cur, details, now, bodies, { only: a.has('only') });
|
||||
const todo = q.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
|
||||
sent = q.changes;
|
||||
if (!q.changes) { ctl.unchanged(); return; }
|
||||
if (q.details.action !== 'same') {
|
||||
await play.call('PUT', `${play.API}/edits/${id}/details`, details);
|
||||
log('play', `details: ${p.details.changes.map(ch => ch.field).join(', ')}`);
|
||||
log('play', `details: ${q.details.changes.map(ch => ch.field).join(', ')}`);
|
||||
}
|
||||
for (const [i, b] of todo.entries()) {
|
||||
await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b);
|
||||
log('play', step(i + 1, todo.length, b.language!));
|
||||
}
|
||||
});
|
||||
done('play', 'listing done');
|
||||
done('play', sent ? 'listing done' : 'listing already up to date (the edit was deleted, nothing committed)');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_r
|
|||
export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i;
|
||||
|
||||
/** Read tools whose command prints a structured result with --json. */
|
||||
export const JSON_TOOLS = new Set(['check', 'check_aso', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
||||
export const JSON_TOOLS = new Set(['check', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
||||
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff',
|
||||
'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']);
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@
|
|||
// Per set: Play 2-8 phone screenshots, Apple 1-10 per display type, 13" iPad set when apple.ipad, feature graphic.
|
||||
// Per app preview: 886x1920 / 1200x1600, H.264, <= 30 fps, 15-30 s, stereo AAC track, <= 500 MB, <= 3 per set.
|
||||
// Text overflow flags come from the last `shots render` (report.json). Frames: with capture.source "folder" every frame
|
||||
// the scenes use must exist with the right aspect. Exit 1 on any error (warnings do not fail).
|
||||
// the scenes use must exist with the right aspect. Local font files (shots.fonts paths) without a license note: warn.
|
||||
// Exit 1 on any error (warnings do not fail).
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { ShipConfig } from '../lib/config';
|
||||
|
|
@ -17,6 +18,8 @@ import { defaultSizes, frameDims, SIZES } from './lib';
|
|||
import type { LocalIssue, RendersCheck } from '../lib/validate-rules';
|
||||
import { allIssues, requiredSets, type RendersScan, scanRenders, storeOf } from './report';
|
||||
import { imageInfo } from './spec';
|
||||
import { fontsDirOf, readManifest } from './fonts';
|
||||
import { localFontIssues } from './local-fonts';
|
||||
|
||||
/** Frame files the scenes (and the feature graphic) use, per language and device class. */
|
||||
export function framesNeeded(config: ShipConfig, langs: string[]): { lang: string; device: 'phone' | 'tablet'; name: string }[] {
|
||||
|
|
@ -58,9 +61,9 @@ export function rendersCheck(config: ShipConfig, dir: string): Record<'apple' |
|
|||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const { config, resolve, root } = ctx.loaded;
|
||||
const scan = scanProject(ctx);
|
||||
const issues = allIssues(scan);
|
||||
const issues = [...allIssues(scan), ...localFontIssues(readManifest(fontsDirOf(root))).map(issue => ({ where: '.storebound/fonts/fonts.json', issue }))];
|
||||
const cap = config.shots?.capture;
|
||||
const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : [];
|
||||
if (ctx.args.has('json')) {
|
||||
|
|
|
|||
|
|
@ -8,20 +8,25 @@ const tag = (d: DataView, o: number): string => String.fromCharCode(d.getUint8(o
|
|||
const view = (b: Uint8Array): DataView => new DataView(b.buffer, b.byteOffset, b.byteLength);
|
||||
|
||||
/** The raw cmap table of a font file (any of the formats above). Throws on anything else. */
|
||||
export function cmapTable(file: Uint8Array): Uint8Array {
|
||||
export const cmapTable = (file: Uint8Array): Uint8Array => fontTable(file, 'cmap');
|
||||
|
||||
/** One raw (untransformed) table of a font file, e.g. 'cmap' or 'name'. Throws when the file is not a font or the
|
||||
* table is missing. */
|
||||
export function fontTable(file: Uint8Array, want: string): Uint8Array {
|
||||
const d = view(file);
|
||||
if (file.byteLength < 12) throw new Error('not a font file (too short)');
|
||||
const sig = tag(d, 0);
|
||||
if (sig === 'wOF2') return woff2Cmap(file);
|
||||
if (sig === 'wOF2') return woff2Table(file, want);
|
||||
if (sig === 'wOFF') {
|
||||
const n = d.getUint16(12);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const o = 44 + i * 20;
|
||||
if (tag(d, o) !== 'cmap') continue;
|
||||
if (tag(d, o) !== want) continue;
|
||||
const off = d.getUint32(o + 4), comp = d.getUint32(o + 8), orig = d.getUint32(o + 12);
|
||||
const raw = file.subarray(off, off + comp);
|
||||
return comp < orig ? new Uint8Array(inflateSync(raw)) : raw;
|
||||
}
|
||||
throw new Error('woff: no cmap table');
|
||||
throw new Error(`woff: no ${want} table`);
|
||||
}
|
||||
let base = 0;
|
||||
if (sig === 'ttcf') base = d.getUint32(12);
|
||||
|
|
@ -29,9 +34,9 @@ export function cmapTable(file: Uint8Array): Uint8Array {
|
|||
const n = d.getUint16(base + 4);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const o = base + 12 + i * 16;
|
||||
if (tag(d, o) === 'cmap') { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); }
|
||||
if (tag(d, o) === want) { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); }
|
||||
}
|
||||
throw new Error('sfnt: no cmap table');
|
||||
throw new Error(`sfnt: no ${want} table`);
|
||||
}
|
||||
|
||||
const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG',
|
||||
|
|
@ -39,7 +44,7 @@ const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'pos
|
|||
'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar',
|
||||
'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill'];
|
||||
|
||||
function woff2Cmap(file: Uint8Array): Uint8Array {
|
||||
function woff2Table(file: Uint8Array, want: string): Uint8Array {
|
||||
const d = view(file);
|
||||
const n = d.getUint16(12), compLen = d.getUint32(20);
|
||||
let p = 48;
|
||||
|
|
@ -56,10 +61,10 @@ function woff2Cmap(file: Uint8Array): Uint8Array {
|
|||
const version = (flags >> 6) & 3;
|
||||
const transformed = t === 'glyf' || t === 'loca' ? version === 0 : version !== 0;
|
||||
const len = transformed ? base128() : orig;
|
||||
if (t === 'cmap') found = [off, orig];
|
||||
if (t === want) found = [off, orig];
|
||||
off += len;
|
||||
}
|
||||
if (!found) throw new Error('woff2: no cmap table');
|
||||
if (!found) throw new Error(`woff2: no ${want} table`);
|
||||
if (tag(d, 4) === 'ttcf') { // collection directory: skip it (version, numFonts 255UInt16, per font numTables + indices)
|
||||
p += 4;
|
||||
const u16 = (): number => { const c = d.getUint8(p++); return c === 253 ? (p += 2, d.getUint16(p - 2)) : c === 255 ? 253 + d.getUint8(p++) : c === 254 ? 506 + d.getUint8(p++) : c; };
|
||||
|
|
@ -110,6 +115,28 @@ function readSub(d: DataView, o: number, out: Set<number>): void {
|
|||
}
|
||||
}
|
||||
|
||||
/** Family name from the name table (typographic family 16, else family 1; Windows Unicode, else Mac Roman), or null. */
|
||||
export function fontFamilyName(file: Uint8Array): string | null {
|
||||
let t: Uint8Array;
|
||||
try { t = fontTable(file, 'name'); } catch { return null; }
|
||||
const d = view(t);
|
||||
const count = d.getUint16(2), strings = d.getUint16(4);
|
||||
const recs: { pid: number; lang: number; id: number; text: string }[] = [];
|
||||
for (let i = 0; i < count && 6 + i * 12 + 12 <= t.byteLength; i++) {
|
||||
const o = 6 + i * 12;
|
||||
const pid = d.getUint16(o), lang = d.getUint16(o + 4), id = d.getUint16(o + 6), len = d.getUint16(o + 8), off = strings + d.getUint16(o + 10);
|
||||
if ((id !== 1 && id !== 16) || off + len > t.byteLength) continue;
|
||||
const raw = t.subarray(off, off + len);
|
||||
let text = '';
|
||||
if (pid === 3 || pid === 0) for (let k = 0; k + 1 < raw.length; k += 2) text += String.fromCharCode((raw[k]! << 8) | raw[k + 1]!);
|
||||
else if (pid === 1) text = String.fromCharCode(...raw);
|
||||
else continue;
|
||||
recs.push({ pid, lang, id, text: text.trim() });
|
||||
}
|
||||
const score = (r: { pid: number; lang: number; id: number }): number => (r.id === 16 ? 10 : 0) + (r.pid === 3 ? 4 : r.pid === 0 ? 3 : 1) + (r.lang === 0x409 || r.lang === 0 ? 1 : 0);
|
||||
return recs.filter(r => r.text).sort((a, b) => score(b) - score(a))[0]?.text ?? null;
|
||||
}
|
||||
|
||||
/** Code points a font file covers. */
|
||||
export const fontCodepoints = (file: Uint8Array): Set<number> => cmapCodepoints(cmapTable(file));
|
||||
|
||||
|
|
|
|||
|
|
@ -8,14 +8,16 @@
|
|||
// character no fallback covers fails with the language and the characters.
|
||||
// storebound shots fonts [--json] (re-run after editing the copy or the fonts)
|
||||
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css + fonts.json (faces and the per-language stacks, read by render).
|
||||
// All of these fonts are SIL Open Font License 1.1.
|
||||
// The Google fonts are SIL Open Font License 1.1. A local font file in shots.fonts (local-fonts.ts) gets the same cmap
|
||||
// check, is read in place (never copied) and recorded with its path, sha256 and license note.
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { shotsStyle } from '../lib/config';
|
||||
import { type CopyFile, shotFonts } from './lib';
|
||||
import type { CopyFile } from './lib';
|
||||
import { localByFamily, resolveShotFonts } from './local-fonts';
|
||||
import { fontCodepoints } from './cmap';
|
||||
import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs';
|
||||
|
||||
|
|
@ -54,14 +56,24 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const dir = fontsDirOf(root);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const style = shotsStyle(config);
|
||||
const { title, body, titleVariable } = shotFonts(shots, style);
|
||||
const sf = resolveShotFonts(shots, style, resolve, root);
|
||||
const { titleVariable } = sf;
|
||||
const title = sf.title.family, body = sf.body.family;
|
||||
const local = localByFamily([sf.title, sf.body, ...sf.fallback]);
|
||||
const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name);
|
||||
|
||||
const sizes: string[] = [];
|
||||
const manifest = await planFonts({
|
||||
langs: texts, title, body, titleAxis: titleVariable ? 'wght@100..900' : null, bodyAxis: 'wght@100..900',
|
||||
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: shots.fonts?.fallback, base: ASCII,
|
||||
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: sf.fallback.map(f => f.family), base: ASCII, local,
|
||||
}, async (job: FaceJob) => {
|
||||
if (job.local) { // read in place: the whole file's cmap
|
||||
const bin = new Uint8Array(readFileSync(join(root, job.local.path)));
|
||||
const cps = fontCodepoints(bin);
|
||||
const line = `${job.local.path} ${job.family}, ${(bin.byteLength / 1024).toFixed(1)} KB, ${cps.size} in the cmap, sha256 ${job.local.hash}, license: ${job.local.license ?? 'none noted (add license to the shots.fonts entry)'}`;
|
||||
if (!sizes.includes(line)) sizes.push(line);
|
||||
return cps;
|
||||
}
|
||||
let bin: Uint8Array;
|
||||
try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) {
|
||||
if (job.kind !== 'fallback') throw e;
|
||||
|
|
@ -77,12 +89,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
writeFileSync(join(dir, 'fonts.json'), JSON.stringify(manifest, null, 1) + '\n');
|
||||
if (ctx.args.has('json')) return printJson(manifest);
|
||||
for (const s of sizes) log('shots', s);
|
||||
for (const f of Object.values(local)) if (!f.license) warn('shots', `local font ${f.path} has no license note: add license ('OFL-1.1', 'proprietary', ...) to its shots.fonts entry`);
|
||||
let auto = 0;
|
||||
for (const [lang, l] of Object.entries(manifest.langs)) for (const f of l.fallbacks) {
|
||||
const ok = manifest.faces[f.face]?.chosen;
|
||||
if (!ok) auto++;
|
||||
const base = f.role === 'title' ? title : body;
|
||||
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}`);
|
||||
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}${manifest.faces[f.face]?.local ? ' (local file)' : ''}`);
|
||||
}
|
||||
if (auto) warn('shots', `${auto} automatic fallbacks: renders that use them fail \`shots check\`. Pick title / body fonts that cover them${style === 'game' ? ' (titles: e.g. Paytone One, Baloo 2, Rowdies)' : ''} or accept the fallback with shots.fonts.fallback: ['<family>']`);
|
||||
done('shots', 'fonts done');
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@
|
|||
import type { SceneCopy } from './lib';
|
||||
import { scriptFont } from './lib';
|
||||
import { needsGlyph } from './cmap';
|
||||
import { type LocalFontInfo, localFile, slug } from './local-fonts';
|
||||
|
||||
export type Role = 'title' | 'body';
|
||||
export interface RoleTexts { title: string; body: string }
|
||||
|
|
@ -61,16 +62,16 @@ export function fallbackFamilies(ch: string, lang: string, role: Role): string[]
|
|||
export const FALLBACK_ORDER = ['Noto Sans Display', 'Noto Sans', 'Noto Sans KR', 'Noto Sans JP', 'Noto Sans SC', 'Noto Sans TC',
|
||||
...NOTO_SCRIPTS.map(s => `Noto Sans ${s}`), ...SYMBOLS];
|
||||
|
||||
const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
|
||||
export type FaceKind = 'title' | 'body' | 'script' | 'fallback';
|
||||
/** One downloaded face: `face` is the @font-face family name the templates use. axis: css2 axis spec ("wght@800",
|
||||
* "wght@100..900") or null for the font's default instance. */
|
||||
export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string }
|
||||
export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string; local?: LocalFontInfo }
|
||||
export interface LangFonts { title: string[]; body: string[]; fallbacks: { role: Role; face: string; family: string; chars: string }[] }
|
||||
export interface FontManifest {
|
||||
v: 1;
|
||||
faces: Record<string, { family: string; file: string; kind: FaceKind; role?: Role; chosen: boolean }>;
|
||||
/** local: a local font file (shots.fonts entry with a path), read in place, never copied; file = its served path. */
|
||||
faces: Record<string, { family: string; file: string; kind: FaceKind; role?: Role; chosen: boolean; local?: LocalFontInfo }>;
|
||||
langs: Record<string, LangFonts>;
|
||||
}
|
||||
|
||||
|
|
@ -81,8 +82,11 @@ export interface PlanInput {
|
|||
titleAxis: string | null; bodyAxis: string | null;
|
||||
/** Weight axis for automatic title fallbacks (game titles are heavy display faces: "wght@800"). */
|
||||
fallbackTitleAxis: string | null;
|
||||
/** shots.fonts.fallback: families the owner accepts as fallbacks. */
|
||||
/** shots.fonts.fallback: families the owner accepts as fallbacks, in order. Families that are not one of the automatic
|
||||
* Noto fallbacks (another Google family, a local file) are tried first, for every character the stack lacks. */
|
||||
chosen?: string[];
|
||||
/** Local font files by family (title, body or fallback). */
|
||||
local?: Record<string, LocalFontInfo>;
|
||||
/** Extra characters for the title / body downloads (ASCII, so later copy edits rarely need a new download). */
|
||||
base?: string;
|
||||
}
|
||||
|
|
@ -100,6 +104,11 @@ export class GlyphError extends Error {
|
|||
* and returns the code points its cmap covers. Throws GlyphError when no fallback covers a character. */
|
||||
export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise<Set<number>>): Promise<FontManifest> {
|
||||
const chosen = new Set((input.chosen ?? []).map(s => s.toLowerCase()));
|
||||
const local = input.local ?? {};
|
||||
const extra = [...new Set(input.chosen ?? [])].filter(f => !FALLBACK_ORDER.some(n => n.toLowerCase() === f.toLowerCase()));
|
||||
const order = [...extra, ...FALLBACK_ORDER];
|
||||
const fileOf = (family: string, google: string): string => local[family] ? localFile(family, local[family]!) : google;
|
||||
const loc = (family: string): { local?: LocalFontInfo } => (local[family] ? { local: local[family] } : {});
|
||||
const base = input.base ?? '';
|
||||
const scripts = new Map<string, { family: string; chars: Set<string> }>();
|
||||
const langScript = new Map<string, string | null>();
|
||||
|
|
@ -121,13 +130,13 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
|
|||
const add = async (job: FaceJob, isChosen: boolean): Promise<void> => {
|
||||
cps.set(job.face, await get(job));
|
||||
if (job.kind === 'fallback' && ![...job.chars].some(ch => cps.get(job.face)!.has(ch.codePointAt(0)!))) return; // covers none: not a face
|
||||
faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen };
|
||||
faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen, ...(job.local ? { local: job.local } : {}) };
|
||||
};
|
||||
await add({ face: input.title, family: input.title, file: 'title.woff2', kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title) }, true);
|
||||
if (input.body !== input.title) await add({ face: input.body, family: input.body, file: 'body.woff2', kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body) }, true);
|
||||
await add({ face: input.title, family: input.title, file: fileOf(input.title, 'title.woff2'), kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title), ...loc(input.title) }, true);
|
||||
if (input.body !== input.title) await add({ face: input.body, family: input.body, file: fileOf(input.body, 'body.woff2'), kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body), ...loc(input.body) }, true);
|
||||
else { // same family: one download (title axis) with both roles' characters
|
||||
const t = faces[input.title]!;
|
||||
cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]) }));
|
||||
cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]), ...loc(input.title) }));
|
||||
}
|
||||
for (const [s, v] of scripts) await add({ face: `Store ${s}`, family: v.family, file: `${s}.woff2`, kind: 'script', axis: 'wght@100..900', chars: sorted(v.chars) }, true);
|
||||
|
||||
|
|
@ -139,17 +148,17 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
|
|||
langs[lang] = { title: [...(x ? [x] : []), input.title], body: [...(x ? [x] : []), input.body], fallbacks: [] };
|
||||
for (const role of ['title', 'body'] as const) {
|
||||
const stack = langs[lang]![role].map(f => cps.get(f)!);
|
||||
for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: fallbackFamilies(ch, lang, role) });
|
||||
for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: [...extra, ...fallbackFamilies(ch, lang, role)] });
|
||||
}
|
||||
}
|
||||
const gaps = new Map<string, { lang: string; role: Role; chars: string[]; tried: string[] }>();
|
||||
const hits = new Map<string, Map<string, Set<string>>>(); // lang|role -> face -> chars
|
||||
for (const role of ['title', 'body'] as const) for (const family of FALLBACK_ORDER) {
|
||||
for (const role of ['title', 'body'] as const) for (const family of order) {
|
||||
const want = pending.filter(p => p.role === role && p.tries.includes(family));
|
||||
if (!want.length) continue;
|
||||
const face = `Store fb ${slug(family)} ${role}`;
|
||||
const axis = family === 'Noto Color Emoji' ? null : role === 'title' ? input.fallbackTitleAxis : 'wght@100..900';
|
||||
await add({ face, family, file: `fb-${slug(family)}-${role}.woff2`, kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)) }, chosen.has(family.toLowerCase()));
|
||||
await add({ face, family, file: fileOf(family, `fb-${slug(family)}-${role}.woff2`), kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)), ...loc(family) }, chosen.has(family.toLowerCase()));
|
||||
const got = cps.get(face)!;
|
||||
for (const p of want) {
|
||||
p.tries = p.tries.filter(f => f !== family);
|
||||
|
|
@ -165,14 +174,14 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
|
|||
for (const p of pending) {
|
||||
if ((p as { done?: boolean }).done) continue;
|
||||
const k = `${p.lang}|${p.role}`;
|
||||
const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...fallbackFamilies(p.ch, p.lang, p.role)] };
|
||||
const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...extra, ...fallbackFamilies(p.ch, p.lang, p.role)] };
|
||||
g.chars.push(p.ch);
|
||||
gaps.set(k, g);
|
||||
}
|
||||
if (gaps.size) throw new GlyphError([...gaps.values()]);
|
||||
for (const [k, m] of hits) {
|
||||
const [lang, role] = k.split('|') as [string, Role];
|
||||
for (const face of [...m.keys()].sort((a, b) => FALLBACK_ORDER.indexOf(faces[a]!.family) - FALLBACK_ORDER.indexOf(faces[b]!.family))) {
|
||||
for (const face of [...m.keys()].sort((a, b) => order.indexOf(faces[a]!.family) - order.indexOf(faces[b]!.family))) {
|
||||
langs[lang]![role].push(face);
|
||||
langs[lang]!.fallbacks.push({ role, face, family: faces[face]!.family, chars: [...m.get(face)!].join('') });
|
||||
}
|
||||
|
|
@ -187,6 +196,12 @@ export function fontsCss(m: FontManifest): string {
|
|||
for (const [face, f] of Object.entries(m.faces)) {
|
||||
if (seen.has(face)) continue;
|
||||
seen.add(face);
|
||||
if (f.local) { // the project's own font file, served in place; ?v= changes with its content
|
||||
const l = f.local;
|
||||
css += `/* ${f.family}: local file ${l.path} (${l.license ? 'license: ' + l.license.replace(/\*\//g, '') : 'no license note'}) */\n`;
|
||||
css += `@font-face { font-family: '${face}'; font-weight: ${l.weight ?? '100 900'}; font-style: ${l.style ?? 'normal'}; font-synthesis: none; src: url(${f.file}?v=${l.hash}) format('${l.format}'); }\n`;
|
||||
continue;
|
||||
}
|
||||
css += `@font-face { font-family: '${face}'; font-weight: 100 900; font-synthesis: none; src: url(${f.file}) format('woff2'); }\n`;
|
||||
}
|
||||
return css;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
// Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data.
|
||||
import { specFamily } from './local-fonts';
|
||||
import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config';
|
||||
|
||||
/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), iphone-medium = 6.3" iPhone with
|
||||
|
|
@ -54,7 +55,8 @@ export const palette = (p: string | Palette | undefined, style: 'game' | 'app' =
|
|||
* Cyrillic. The app title is a variable font (bold headline weights). Per-script stack: glyphs.ts. */
|
||||
export function shotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app'): { title: string; body: string; titleVariable: boolean } {
|
||||
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
|
||||
return { title: shots?.fonts?.title ?? d.title, body: shots?.fonts?.body ?? d.body, titleVariable: style === 'app' };
|
||||
// local files: the family given in the config, else the file name (resolveShotFonts reads the real name table)
|
||||
return { title: specFamily(shots?.fonts?.title ?? d.title), body: specFamily(shots?.fonts?.body ?? d.body), titleVariable: style === 'app' };
|
||||
}
|
||||
|
||||
export interface SceneCopy { eyebrow?: string; title: [string, string]; sub?: string; badges?: [string, string?][] }
|
||||
|
|
|
|||
130
cli/shots/local-fonts.ts
Normal file
130
cli/shots/local-fonts.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// A game's or app's own brand font as a local file, next to the Google Fonts families:
|
||||
// shots.fonts.title / body / fallback[] = 'Paytone One' (Google Fonts family)
|
||||
// | 'assets/fonts/er-display.woff2' (local file, family from its name table)
|
||||
// | { family, file, weight?, style?, license? }
|
||||
// Paths are relative to the config. TTF / OTF / WOFF / WOFF2 (checked by extension and signature). The file is never
|
||||
// copied: `shots fonts` reads its cmap and records it in fonts.json (path relative to the project, sha256, license),
|
||||
// fonts.css points at /fonts/local/<slug>.<ext>?v=<hash> and the render / video servers serve that route from the
|
||||
// original file. A changed file changes fonts.css (capture cache) and fails render until `shots fonts` runs again.
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { basename, join, relative } from 'node:path';
|
||||
import { fontFamilyName } from './cmap';
|
||||
import type { FontManifest } from './glyphs';
|
||||
|
||||
import type { FontSpec, LocalFontSpec, ShotsConfig } from '../lib/config';
|
||||
export type { FontSpec, LocalFontSpec };
|
||||
export type FontFormat = 'truetype' | 'opentype' | 'woff' | 'woff2';
|
||||
|
||||
/** A local font as fonts.json records it. path: relative to the project root. */
|
||||
export interface LocalFontInfo { path: string; format: FontFormat; hash: string; bytes: number; weight?: string; style?: string; license?: string }
|
||||
/** A resolved font of shots.fonts: the family name the templates use, plus the file for a local font. */
|
||||
export interface FontRef { family: string; local?: LocalFontInfo & { abs: string } }
|
||||
|
||||
const EXT: Record<string, FontFormat> = { ttf: 'truetype', otf: 'opentype', woff: 'woff', woff2: 'woff2' };
|
||||
|
||||
/** A string spec is a local file when it ends in a font extension or contains a path separator. */
|
||||
export const isLocalSpec = (s: FontSpec): boolean => typeof s !== 'string' || /\.(ttf|otf|woff2?)$/i.test(s) || /[\\/]/.test(s);
|
||||
|
||||
/** Format from the file signature (null = not a font file storebound reads). */
|
||||
export function sniffFormat(bin: Uint8Array): FontFormat | null {
|
||||
if (bin.byteLength < 12) return null;
|
||||
const sig = String.fromCharCode(bin[0]!, bin[1]!, bin[2]!, bin[3]!);
|
||||
if (sig === 'wOF2') return 'woff2';
|
||||
if (sig === 'wOFF') return 'woff';
|
||||
if (sig === 'OTTO') return 'opentype';
|
||||
if (sig === 'true' || (bin[0] === 0 && bin[1] === 1 && bin[2] === 0 && bin[3] === 0)) return 'truetype';
|
||||
return null;
|
||||
}
|
||||
|
||||
export const fileHash = (bin: Uint8Array): string => createHash('sha256').update(bin).digest('hex').slice(0, 16);
|
||||
|
||||
/** Resolves and validates one local font spec (file exists, TTF / OTF / WOFF / WOFF2). Throws with the config key. */
|
||||
export function loadLocalFont(spec: FontSpec, key: string, resolve: (p: string) => string, root: string): FontRef {
|
||||
const o: LocalFontSpec = typeof spec === 'string' ? { file: spec } : spec;
|
||||
if (!o.file || typeof o.file !== 'string') throw new Error(`${key}: { family, file } needs a file path (relative to the config)`);
|
||||
const ext = o.file.split('.').pop()!.toLowerCase();
|
||||
if (!EXT[ext]) throw new Error(`${key}: ${o.file}: not a font file (TTF, OTF, WOFF or WOFF2)`);
|
||||
const abs = resolve(o.file);
|
||||
if (!existsSync(abs) || !statSync(abs).isFile()) throw new Error(`${key}: ${o.file} not found (paths are relative to the config: ${abs})`);
|
||||
const bin = new Uint8Array(readFileSync(abs));
|
||||
const format = sniffFormat(bin);
|
||||
if (!format) throw new Error(`${key}: ${o.file} is not a TTF / OTF / WOFF / WOFF2 font (unknown signature)`);
|
||||
const sfnt = (f: FontFormat): boolean => f === 'truetype' || f === 'opentype';
|
||||
if (format !== EXT[ext] && !(sfnt(format) && sfnt(EXT[ext]!))) throw new Error(`${key}: ${o.file} is ${format.toUpperCase()} inside, but named .${ext}: rename it`);
|
||||
const family = (o.family ?? fontFamilyName(bin) ?? basename(o.file).replace(/\.[^.]+$/, '')).trim();
|
||||
if (!family) throw new Error(`${key}: ${o.file}: no family name (give { family, file })`);
|
||||
return { family, local: { abs, path: relative(root, abs), format, hash: fileHash(bin), bytes: bin.byteLength,
|
||||
...(o.weight !== undefined ? { weight: String(o.weight) } : {}), ...(o.style ? { style: o.style } : {}), ...(o.license ? { license: o.license } : {}) } };
|
||||
}
|
||||
|
||||
/** shots.fonts resolved: Google families as names, local files loaded and validated (throws on a bad file). */
|
||||
export function resolveShotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app', resolve: (p: string) => string, root: string): { title: FontRef; body: FontRef; fallback: FontRef[]; titleVariable: boolean } {
|
||||
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
|
||||
const ref = (s: FontSpec, key: string): FontRef => isLocalSpec(s) ? loadLocalFont(s, key, resolve, root) : { family: s as string };
|
||||
const fallback = (shots?.fonts?.fallback ?? []).map((f, i) => ref(f, `shots.fonts.fallback[${i}]`));
|
||||
return { title: ref(shots?.fonts?.title ?? d.title, 'shots.fonts.title'), body: ref(shots?.fonts?.body ?? d.body, 'shots.fonts.body'), fallback, titleVariable: style === 'app' };
|
||||
}
|
||||
|
||||
/** Local files by family for planFonts (one family, one file). */
|
||||
export function localByFamily(refs: FontRef[]): Record<string, LocalFontInfo> {
|
||||
const out: Record<string, LocalFontInfo> = {};
|
||||
for (const r of refs) if (r.local) {
|
||||
const { abs: _abs, ...info } = r.local;
|
||||
if (out[r.family] && out[r.family]!.hash !== info.hash) throw new Error(`shots.fonts: two different files for the family "${r.family}" (give each a distinct family)`);
|
||||
out[r.family] = info;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Family name of a spec without reading files (Google family, { family }, else the file name). For callers that only
|
||||
* need a name and never a local file's name table. */
|
||||
export const specFamily = (s: FontSpec): string => typeof s !== 'string' ? s.family ?? basename(s.file).replace(/\.[^.]+$/, '')
|
||||
: isLocalSpec(s) ? basename(s).replace(/\.[^.]+$/, '') : s;
|
||||
|
||||
export const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
|
||||
/** fonts.json file name of a local face: served at /fonts/local/<slug>.<ext>. */
|
||||
export const localFile = (family: string, l: Pick<LocalFontInfo, 'format'>): string =>
|
||||
`local/${slug(family)}.${l.format === 'truetype' ? 'ttf' : l.format === 'opentype' ? 'otf' : l.format}`;
|
||||
|
||||
/** Absolute file of a face: the downloaded subset in .storebound/fonts, or the local font file itself. */
|
||||
export function faceFilePath(fontsDir: string, root: string, f: FontManifest['faces'][string]): string {
|
||||
return f.local ? join(root, f.local.path) : join(fontsDir, f.file);
|
||||
}
|
||||
|
||||
/** File for a /fonts/<rel> request of the render / video page (null = not ours). */
|
||||
export function fontsRoute(rel: string, fontsDir: string, root: string, m: FontManifest | null): string | null {
|
||||
rel = rel.split('?')[0]!;
|
||||
if (rel.includes('..')) return null;
|
||||
if (rel.startsWith('local/')) {
|
||||
const f = Object.values(m?.faces ?? {}).find(x => x.local && x.file === rel);
|
||||
return f ? faceFilePath(fontsDir, root, f) : null;
|
||||
}
|
||||
return join(fontsDir, rel);
|
||||
}
|
||||
|
||||
export const FONT_TYPES: Record<string, string> = { woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css' };
|
||||
|
||||
/** Local faces whose file changed (or vanished) since `shots fonts`. */
|
||||
export function staleLocalFonts(m: FontManifest, root: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const f of new Map(Object.values(m.faces).filter(x => x.local).map(x => [x.local!.path, x] as const)).values()) {
|
||||
const abs = join(root, f.local!.path);
|
||||
if (!existsSync(abs)) out.push(`${f.family}: ${f.local!.path} is gone`);
|
||||
else if (fileHash(new Uint8Array(readFileSync(abs))) !== f.local!.hash) out.push(`${f.family}: ${f.local!.path} changed`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `shots check` warnings for local fonts without a license note. */
|
||||
export function localFontIssues(m: FontManifest | null): { level: 'warn'; code: 'font-license'; msg: string }[] {
|
||||
const seen = new Set<string>();
|
||||
const out: { level: 'warn'; code: 'font-license'; msg: string }[] = [];
|
||||
for (const f of Object.values(m?.faces ?? {})) {
|
||||
if (!f.local || f.local.license || seen.has(f.local.path)) continue;
|
||||
seen.add(f.local.path);
|
||||
out.push({ level: 'warn', code: 'font-license', msg: `local font ${f.family} (${f.local.path}) has no license note: add license ('OFL-1.1', 'proprietary', or a short note) to its shots.fonts entry, and make sure you may embed it in store graphics` });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -8,7 +8,8 @@
|
|||
// Fonts: the per-language stacks from .storebound/fonts/fonts.json (`shots fonts`). Before rendering, every character
|
||||
// of the copy is checked against the cmaps of the downloaded faces (stale fonts fail with the language and the
|
||||
// characters); while rendering, the page measures which face drew every character, and report.json records it per
|
||||
// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`.
|
||||
// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`. Local font files (shots.fonts
|
||||
// paths) are served from where they are at /fonts/local/... (local-fonts.ts); a file changed since `shots fonts` fails.
|
||||
// Style: shotsStyle() = shots.style, else app for the app / subscription-app profiles (template-app.html,
|
||||
// feature-app.html: calm gradient, device frame, headline + subline), else game (template.html, feature.html).
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
||||
|
|
@ -22,11 +23,12 @@ import { done, log, warn } from '../lib/log';
|
|||
import { launch } from './browser';
|
||||
import { defaultConcurrency, pool, progressLine } from './capture-web';
|
||||
import { shotsStyle } from '../lib/config';
|
||||
import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, shotFonts, validateCopy, variantScenes } from './lib';
|
||||
import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib';
|
||||
import { faceFilePath, fontsRoute, resolveShotFonts, staleLocalFonts } from './local-fonts';
|
||||
import { type RenderReport, mergeReport, readReport } from './report';
|
||||
|
||||
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
|
||||
webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' };
|
||||
webp: 'image/webp', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css', svg: 'image/svg+xml' };
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
|
|
@ -62,7 +64,8 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const { phone, tablet } = frameDims(config);
|
||||
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
|
||||
const style = shotsStyle(config);
|
||||
const sf = shotFonts(shots, style);
|
||||
const rf = resolveShotFonts(shots, style, resolve, root);
|
||||
const sf = { title: rf.title.family, body: rf.body.family };
|
||||
const fonts = { title: sf.title, body: sf.body };
|
||||
const manifest = existsSync(join(fontsDir, 'fonts.css')) ? readManifest(fontsDir) : null;
|
||||
if (existsSync(join(fontsDir, 'fonts.css')) && !manifest) warn('shots', 'fonts from an older storebound (no fonts.json): run `storebound shots fonts` again for the glyph coverage check');
|
||||
|
|
@ -79,10 +82,14 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const x = stacks(lang, job.copy).script;
|
||||
if (x) faces[x] = { family: x, file: '', kind: 'script', chosen: true };
|
||||
}
|
||||
if (manifest) {
|
||||
const stale = staleLocalFonts(manifest, root);
|
||||
if (stale.length) throw new Error(`shots render: local font files changed since \`shots fonts\`: run \`storebound shots fonts\`\n ${stale.join('\n ')}`);
|
||||
}
|
||||
if (manifest) { // glyph coverage of the local font files, before rendering anything
|
||||
const cmaps = new Map<string, Set<number>>();
|
||||
const cps = (face: string): Set<number> => {
|
||||
if (!cmaps.has(face)) { const f = manifest.faces[face]; cmaps.set(face, f && existsSync(join(fontsDir, f.file)) ? fontCodepoints(readFileSync(join(fontsDir, f.file))) : new Set()); }
|
||||
if (!cmaps.has(face)) { const f = manifest.faces[face]; const file = f && faceFilePath(fontsDir, root, f); cmaps.set(face, file && existsSync(file) ? fontCodepoints(readFileSync(file)) : new Set()); }
|
||||
return cmaps.get(face)!;
|
||||
};
|
||||
const gaps: string[] = [];
|
||||
|
|
@ -121,7 +128,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
let file = '';
|
||||
if (p === '/logo' && shots.logo) file = resolve(shots.logo);
|
||||
else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8));
|
||||
else if (p.startsWith('/fonts/')) file = join(fontsDir, p.slice(7));
|
||||
else if (p.startsWith('/fonts/')) file = fontsRoute(p.slice(7), fontsDir, root, manifest) ?? '';
|
||||
else if (p.startsWith('/out/')) file = join(outDir, p.slice(5));
|
||||
else if (/^\/(template|feature)(-app)?\.html$/.test(p)) file = join(tpl, p.slice(1));
|
||||
if (!file || file.includes('..')) return new Response('no', { status: 404 });
|
||||
|
|
|
|||
|
|
@ -17,7 +17,8 @@ import { done, log, warn } from '../lib/log';
|
|||
import { launch } from './browser';
|
||||
import { shotsStyle } from '../lib/config';
|
||||
import { readManifest } from './fonts';
|
||||
import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont, shotFonts } from './lib';
|
||||
import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont } from './lib';
|
||||
import { FONT_TYPES, fontsRoute, resolveShotFonts } from './local-fonts';
|
||||
import { ffprobe } from './report';
|
||||
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec';
|
||||
|
||||
|
|
@ -159,12 +160,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const style = shotsStyle(ctx.loaded.config);
|
||||
const pal = palette(shots.scenes[0]?.palette, style);
|
||||
return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: style === 'app' ? '#111827' : pal.ink, rtl: rtl.get(lang),
|
||||
fonts: { title: shotFonts(shots, style).title, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } });
|
||||
fonts: { title: resolveShotFonts(shots, style, ctx.loaded.resolve, root).title.family, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } });
|
||||
}
|
||||
if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
||||
if (url.pathname.startsWith('/fonts/') && !url.pathname.includes('..')) {
|
||||
const f = Bun.file(join(fontsDir, url.pathname.slice(7)));
|
||||
if (await f.exists()) return new Response(f, { headers: { 'content-type': url.pathname.endsWith('.css') ? 'text/css' : 'font/woff2' } });
|
||||
if (url.pathname.startsWith('/fonts/')) {
|
||||
const file = fontsRoute(decodeURIComponent(url.pathname.slice(7)), fontsDir, root, readManifest(fontsDir));
|
||||
const f = file ? Bun.file(file) : null;
|
||||
if (f && await f.exists()) return new Response(f, { headers: { 'content-type': FONT_TYPES[file!.split('.').pop()!.toLowerCase()] ?? 'font/woff2' } });
|
||||
}
|
||||
return new Response('no', { status: 404 });
|
||||
} });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue