@appeeky/spec 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,7 +30,7 @@ npx @appeeky/spec verify # day 7 and day 14: did it work?
30
30
 
31
31
  `pnpm dlx`, `yarn dlx` and `bunx` work the same way. Node 20 or later.
32
32
 
33
- `init` with no options asks for the app's name, finds it on the App Store, checks the Google Play package, pulls every store it can reach, suggests five targets from what the app already ranks for, offers the GitHub workflows (`--ci`) and the agent skills, and ends on the first coverage table. With options (`--name`, `--app-store`, `--google-play`, `--pull`) it does the same without questions, for scripts. It also adds `.appeeky/` to `.gitignore`.
33
+ `init` with no options asks for the app's name, finds it on the App Store, checks the Google Play package, pulls every store it can reach, suggests five targets from what the app already ranks for, offers the GitHub workflows (`--ci`) and the agent skills, and ends on the first coverage table. With options (`--name`, `--app-store`, `--google-play`, `--pull`) it does the same without questions, for scripts: it writes the five suggested targets (or the ones in `--targets "a,b,c"`; `--no-targets` leaves them empty) and the Google Play category, and a store it cannot reach does not stop the other. It also adds `.appeeky/` to `.gitignore`.
34
34
 
35
35
  ## What it does
36
36
 
@@ -119,7 +119,8 @@ A field you leave out of a listing file is not managed by the spec: it is never
119
119
 
120
120
  | Command | What it does |
121
121
  | --- | --- |
122
- | `init` | Create `appeeky.spec.yaml` and `appeeky/`. `--pull` fetches the live listings right away. |
122
+ | `init` | Create `appeeky.spec.yaml` and `appeeky/`. `--pull` fetches the live listings right away, `--targets` sets the first targets. |
123
+ | `doctor` | What is set up and what is missing, with the fix for each. It calls the hosted gateways once to check that the key reaches the stores (`--offline` skips that). |
123
124
  | `pull` | Write the live listings into `appeeky/store/` (overwrites local files). |
124
125
  | `check` | Store limits, ASO rules and screenshot sizes. Exits 1 on errors (`--strict`: on warnings too). |
125
126
  | `coverage` | Which target keywords each storefront indexes, plus tips for storefronts that read a second locale (the US also reads Spanish (Mexico)). |
@@ -142,7 +143,7 @@ A field you leave out of a listing file is not managed by the spec: it is never
142
143
  | `experiment add\|list\|close` | Track growth experiments outside the listing (screenshots, UGC, ads, pricing) with one metric and a check date. |
143
144
  | `screenshots pull\|check` | Download the live App Store screenshots into `appeeky/screenshots/` and check their sizes. |
144
145
  | `report` | Markdown for a pull request: listing changes, check results and coverage against `--base`. |
145
- | `social pull\|check\|push` | Organic social media through the accounts connected in Appeeky (X, Instagram, TikTok, LinkedIn, Pinterest, Reddit, YouTube, Threads, Facebook, Bluesky): `pull` writes the accounts, recent posts (made through Appeeky and in each platform's app), how they did, comments and followers to `appeeky/social/`; `check` checks the drafts in `appeeky/social/drafts/`; `push` sends them. Needs `APPEEKY_API_KEY`. |
146
+ | `social pull\|check\|push\|connect` | Organic social media through the accounts connected in Appeeky (X, Instagram, TikTok, LinkedIn, Pinterest, Reddit, YouTube, Threads, Facebook, Bluesky): `pull` writes the accounts, recent posts (made through Appeeky and in each platform's app), how they did, comments and followers to `appeeky/social/`; `check` checks the drafts in `appeeky/social/drafts/`; `push` sends them; `connect <platform>` prints the sign-in link to connect or reconnect an account and waits until it works. Needs `APPEEKY_API_KEY`. |
146
147
  | `social comments\|reply\|hide\|like\|delete-comment` | Comments on your posts: `comments` lists them (`--unanswered`, `--account`, `--post`, `--limit`); `reply <id> "<message>"` answers from the account it is on, after checking the platform's reply limit; `hide <id>` (`--unhide`), `like <id>`; `delete-comment <id>` asks first, or needs `--yes` outside a terminal. Needs `APPEEKY_API_KEY`. |
147
148
  | `ugc pull\|generate` | UGC from your Appeeky creator personas: `pull` writes the personas and their clips to `appeeky/ugc/`; `generate` makes a clip from each brief in `appeeky/ugc/briefs/` (`--dry-run` shows the cost in media credits). Needs `APPEEKY_API_KEY`. |
148
149
  | `agents install` | Write the specialist subagents and the `/appeeky-cofounder` review into `.claude/` (`--for opencode` or `all` for `.opencode/`). Files you changed are kept unless `--force`. |
@@ -357,7 +358,7 @@ What each platform takes:
357
358
  | Reddit | up to 40,000 characters (the body); a subreddit in `reddit:` | optional |
358
359
  | Instagram, TikTok, Pinterest | 2,200, 2,200, 500 characters | at least one image or video |
359
360
 
360
- `social check` flags drafts that would fail: an account that is not connected, a platform name that matches several accounts, text over the platform's limit, a missing image or video, too many images or videos for the platform, images and a video mixed where the platform does not allow it, a time in the past, TikTok's rules (a disclosed post can't be `only_me` unless it is an inbox draft, at most 35 images, images and a video can't mix, a title over 90 characters) YouTube's (exactly one video, a title over 100 characters) and Reddit's (a subreddit, a title over 300 characters). Media types are read from the URL's file extension. `ugc generate --dry-run` shows what each brief costs in media credits without making anything. The push workflow written by `init --ci` (and the docker `push` routine) runs `social push --yes` and `ugc generate --yes` when a merged pull request adds drafts or briefs; each is marked `sent` or `generating` and committed, so it never goes out twice. Social media needs the Startup plan or above in Appeeky; a persona needs a look (reference images) before it can make clips.
361
+ `social check` flags drafts that would fail: an account that is not connected, a platform name that matches several accounts, text over the platform's limit, a missing image or video, too many images or videos for the platform, images and a video mixed where the platform does not allow it, a time in the past, TikTok's rules (a disclosed post can't be `only_me` unless it is an inbox draft, at most 35 images, images and a video can't mix, a title over 90 characters) YouTube's (exactly one video, a title over 100 characters) and Reddit's (a subreddit, a title over 300 characters). Media types are read from the URL's file extension. `ugc generate --dry-run` shows what each brief costs in media credits without making anything. The push workflow written by `init --ci` (and the docker `push` routine) runs `social push --yes` and `ugc generate --yes` when a merged pull request adds drafts or briefs; each is marked `sent` or `generating` and committed, so it never goes out twice. When a platform drops an account (a revoked permission, a changed password), Appeeky marks it `needsReconnect`: `social pull`, `doctor`, the `social-account` alert and `social check` say so, and `social connect <platform>` gives the sign-in link (and one for the phone) without the dashboard, then waits until the account works. Appeeky keeps the tokens and refreshes them; a sign-in is only needed when the platform refuses that. Social media needs the Startup plan or above in Appeeky; a persona needs a look (reference images) before it can make clips.
361
362
 
362
363
  ### Comments
363
364
 
@@ -518,6 +519,7 @@ The daily run writes the numbers; `alerts` tells you when one of them needs a pe
518
519
  | `visibility-drop` | `appeeky/visibility/changes.md` | in the last 3 days the assistants named the app less for an intent (critical when no longer at all) or stopped citing its site |
519
520
  | `search-drop` | `appeeky/seo/daily.csv` | Search Console clicks per day over the last 7 days fell 30% against the 7 days before (with 20+ clicks before); critical at 60% |
520
521
  | `late-check` | `appeeky/loops.md` (releases and experiments) | a check is 2+ days past its date with no result; critical at 7 |
522
+ | `social-account` | `appeeky/social/accounts.yaml` (from the last `social pull`, if under 7 days old) | an account needs reconnecting or was turned off (critical), or a `social.accounts` entry matches no connected account |
521
523
 
522
524
  ```bash
523
525
  npx @appeeky/spec alerts # a table
@@ -548,6 +550,7 @@ alerts:
548
550
  visibility-drop: { days: 3 }
549
551
  search-drop: { days: 7, drop: 0.3, min: 20 }
550
552
  late-check: { days: 2 }
553
+ social-account: { days: 7 } # how old the last social pull may be
551
554
  ```
552
555
 
553
556
  Target ranks are recorded at each push and on its day-7 and day-14 checks, so `rank-drop` speaks up around releases; between releases the category chart, reviews, competitors and Search Console carry the daily signal.
package/dist/alerts.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type ReleaseRecord } from "./history.js";
3
3
  import { type Loop } from "./loops.js";
4
4
  import { type Review } from "./reviews.js";
5
5
  import type { AlertKind, Project, SpecFile } from "./schema.js";
6
+ import { type SocialAccount } from "./social.js";
6
7
  export type AlertSeverity = "warn" | "critical";
7
8
  export interface Alert {
8
9
  /** Stable id: the same problem keeps the same key from one day to the next. */
@@ -63,6 +64,15 @@ export declare function searchDrops(rows: Array<{
63
64
  clicks: number;
64
65
  }>, cfg: Config["search-drop"], now: Date): Alert[];
65
66
  export declare function lateChecks(loops: Loop[], cfg: Config["late-check"], now: Date): Alert[];
67
+ /**
68
+ * Accounts from the last social pull that stopped working, and social.accounts entries no
69
+ * connected account matches. A broken account is critical: posts the repo approved do not go
70
+ * out on it, and its comments and followers stop coming in.
71
+ */
72
+ export declare function socialAccountAlerts(file: {
73
+ accounts: SocialAccount[];
74
+ checkedAt?: string;
75
+ }, only: string[] | undefined, cfg: Config["social-account"], now: Date): Alert[];
66
76
  /** Every alert the repo's files show today, critical first. Kinds under `alerts.off` are left out. */
67
77
  export declare function collectAlerts(project: Project, now?: Date): Promise<Alert[]>;
68
78
  export interface AlertState {
package/dist/alerts.js CHANGED
@@ -11,6 +11,7 @@ import { collectLoops } from "./loops.js";
11
11
  import { readReviews } from "./reviews.js";
12
12
  import { ALERT_KINDS } from "./schema.js";
13
13
  import { seoDir } from "./seo.js";
14
+ import { accountProblems, readAccountsFile } from "./social.js";
14
15
  import { normalize } from "./text.js";
15
16
  import { visibilityChangesFile } from "./visibility.js";
16
17
  const DAY = 86_400_000;
@@ -320,6 +321,29 @@ export function lateChecks(loops, cfg, now) {
320
321
  return out;
321
322
  }
322
323
  // ── All of them ─────────────────────────────────────────────────────────────
324
+ // ── Social accounts ─────────────────────────────────────────────────────────
325
+ /**
326
+ * Accounts from the last social pull that stopped working, and social.accounts entries no
327
+ * connected account matches. A broken account is critical: posts the repo approved do not go
328
+ * out on it, and its comments and followers stop coming in.
329
+ */
330
+ export function socialAccountAlerts(file, only, cfg, now) {
331
+ if (file.checkedAt && now.getTime() - Date.parse(file.checkedAt) > cfg.days * DAY)
332
+ return [];
333
+ if (!file.accounts.length && !only?.length)
334
+ return [];
335
+ // Without a time (a file from before 0.10), only the accounts' own state counts, not missing ones.
336
+ return accountProblems(file.accounts, file.checkedAt ? (only ?? []) : []).map((p) => ({
337
+ key: `social-account:${p.platform}:${p.account?.id ?? p.ref}`,
338
+ kind: "social-account",
339
+ severity: p.account ? "critical" : "warn",
340
+ title: p.account ? `${p.message.replace(/ \(.*\)$/, "")}` : p.message,
341
+ numbers: p.account?.lastError ? `Last error: ${p.account.lastError}` : p.account ? "No approved post goes out on it, and its comments and followers stop coming in." : "Nothing is read or posted for it.",
342
+ window: file.checkedAt ? `social pull on ${file.checkedAt.slice(0, 10)}` : "last social pull",
343
+ source: `${SPEC_DIR}/social/accounts.yaml`,
344
+ next: p.fix,
345
+ }));
346
+ }
323
347
  const SEVERITY_ORDER = { critical: 0, warn: 1 };
324
348
  /** Every alert the repo's files show today, critical first. Kinds under `alerts.off` are left out. */
325
349
  export async function collectAlerts(project, now = new Date()) {
@@ -336,6 +360,7 @@ export async function collectAlerts(project, now = new Date()) {
336
360
  ...(on("visibility-drop") ? visibilityDrops(await readVisibilityChanges(root), cfg["visibility-drop"], now) : []),
337
361
  ...(on("search-drop") ? searchDrops(await readSearchDaily(root), cfg["search-drop"], now) : []),
338
362
  ...(on("late-check") ? lateChecks(await collectLoops(root, now), cfg["late-check"], now) : []),
363
+ ...(on("social-account") ? socialAccountAlerts(await readAccountsFile(root), project.spec.social?.accounts, cfg["social-account"], now) : []),
339
364
  ];
340
365
  return out.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || ALERT_KINDS.indexOf(a.kind) - ALERT_KINDS.indexOf(b.kind));
341
366
  }
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
4
  import { combineSources, summarizeMeta, summarizeMetrics, summarizeTikTok, } from "./metrics.js";
5
+ import { explainAppeekyError } from "./transport.js";
5
6
  import { normalize } from "./text.js";
6
7
  export const APPEEKY_API_URL = "https://api.appeeky.com/v1";
7
8
  /** An error answer from the Appeeky API, with its HTTP status and error code, so callers can tell "not there" from "failed". */
@@ -9,7 +10,7 @@ export class AppeekyApiError extends Error {
9
10
  status;
10
11
  code;
11
12
  constructor(message, status, code) {
12
- super(message);
13
+ super(explainAppeekyError(message, status));
13
14
  this.status = status;
14
15
  this.code = code;
15
16
  this.name = "AppeekyApiError";
@@ -49,7 +49,9 @@ export interface CategoryPlan {
49
49
  /** Category name for people, e.g. "Health & Fitness". */
50
50
  name?: string;
51
51
  }
52
- /** Which charts to read: the configured category, or the App Store app's own genre. */
52
+ /** The Google Play category id (e.g. VIDEO_PLAYERS) from the app's public Play page, as the App Store genre comes from Apple's lookup. */
53
+ export declare function playCategory(packageName: string, fetcher?: typeof fetch): Promise<string | undefined>;
54
+ /** Which charts to read: the configured category, or the app's own category on each store. */
53
55
  export declare function categoryPlans(project: Project, fetcher?: typeof fetch): Promise<{
54
56
  plans: CategoryPlan[];
55
57
  notes: string[];
package/dist/category.js CHANGED
@@ -80,7 +80,15 @@ export async function appleAppInfo(appId, country, fetcher = fetch) {
80
80
  return null;
81
81
  return { genreId: String(app.primaryGenreId), genre: app.primaryGenreName ?? String(app.primaryGenreId), paid: (app.price ?? 0) > 0 };
82
82
  }
83
- /** Which charts to read: the configured category, or the App Store app's own genre. */
83
+ /** The Google Play category id (e.g. VIDEO_PLAYERS) from the app's public Play page, as the App Store genre comes from Apple's lookup. */
84
+ export async function playCategory(packageName, fetcher = fetch) {
85
+ const res = await fetcher(`https://play.google.com/store/apps/details?id=${encodeURIComponent(packageName)}&hl=en`, { headers: { "User-Agent": "Mozilla/5.0 appeeky-spec" } });
86
+ if (!res.ok)
87
+ return undefined;
88
+ const html = await res.text();
89
+ return /"applicationCategory"\s*:\s*"([A-Z_]+)"/.exec(html)?.[1];
90
+ }
91
+ /** Which charts to read: the configured category, or the app's own category on each store. */
84
92
  export async function categoryPlans(project, fetcher = fetch) {
85
93
  const cfg = project.spec.category ?? {};
86
94
  const ids = rankAppIds(project);
@@ -103,10 +111,14 @@ export async function categoryPlans(project, fetcher = fetch) {
103
111
  notes.push("App Store: category charts need the numeric appId in stores.appStore.");
104
112
  }
105
113
  if (ids["google-play"]) {
106
- if (cfg.googlePlay)
107
- plans.push({ store: "google-play", appId: ids["google-play"], category: cfg.googlePlay, chart: cfg.chart ?? "top-free", countries, name: cfg.googlePlay.toLowerCase().replace(/_/g, " ") });
114
+ const detected = cfg.googlePlay ? undefined : await playCategory(ids["google-play"], fetcher).catch(() => undefined);
115
+ const category = cfg.googlePlay ?? detected;
116
+ if (category)
117
+ plans.push({ store: "google-play", appId: ids["google-play"], category, chart: cfg.chart ?? "top-free", countries, name: category.toLowerCase().replace(/_/g, " ") });
108
118
  else
109
- notes.push("Google Play: set category.googlePlay in appeeky.spec.yaml (e.g. HEALTH_AND_FITNESS) to record its chart.");
119
+ notes.push("Google Play: could not read the app's category. Set category.googlePlay in appeeky.spec.yaml (e.g. HEALTH_AND_FITNESS) to record its chart.");
120
+ if (detected)
121
+ notes.push(`Google Play: category ${detected}, read from the Play page. Set category.googlePlay: ${detected} in appeeky.spec.yaml to pin it.`);
110
122
  }
111
123
  return { plans, notes };
112
124
  }
package/dist/cli.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  import { Command } from "commander";
2
+ /** This package's version, from package.json next to src/ and dist/ (never typed by hand). */
3
+ export declare const VERSION: string;
2
4
  export declare function buildProgram(): Command;
3
5
  export declare function run(argv?: string[]): Promise<void>;
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
@@ -10,10 +10,10 @@ import { COFOUNDER_COMMAND, installAgents, parseTargets, TARGET_DIRS } from "./a
10
10
  import { attributionClient, attributionClients, attributionMetricSource, createExperimentLink, hasClients, IOS_LINK_NOTE, iosOnlyLink, isClient, linkStore, linkValueReader } from "./attribution.js";
11
11
  import { alertsMarkdown, alertsText, collectAlerts, githubRepo, markNew, nextAlertState, postWebhook, readAlertState, syncIssue, writeAlertState } from "./alerts.js";
12
12
  import { pullCompetitors, similarApps } from "./competitors.js";
13
- import { commentPlatform, deleteComment, draftIssues, fetchSocial, hideComment, likeComment, listComments, readAccounts, readDrafts, replyToComment, resolveAccounts, saveSocial, sendDraft } from "./social.js";
13
+ import { accountLabel, accountMatches, accountProblems, connectLink, listAccountRows, toAccount, waitForConnection, commentPlatform, deleteComment, draftIssues, fetchSocial, hideComment, likeComment, listComments, readAccounts, readDrafts, replyToComment, resolveAccounts, saveSocial, sendDraft } from "./social.js";
14
14
  import { fetchUgc, findPersona, generateBrief, quoteBrief, readBriefs, readPersonas, saveUgc } from "./ugc.js";
15
15
  import { generateLocal, loadCore, planLocalClip, readAppeekyPersona, readLocalPersona } from "./ugc-local.js";
16
- import { categoryFile, categoryMetricSource, categoryPlans, chartSources, previousRank, readCategoryHistory, readCategoryRanks, saveCategoryRanks } from "./category.js";
16
+ import { categoryFile, categoryMetricSource, categoryPlans, playCategory, chartSources, previousRank, readCategoryHistory, readCategoryRanks, saveCategoryRanks } from "./category.js";
17
17
  import { applySync, bootstrapIntents, languageFor, overallLine, planSync, pullVisibility, readRemoteIntents, scanVisibility, visibilityMetricSource, visibilityTarget } from "./visibility.js";
18
18
  import { appContext, daysSinceLocalScan, KEY_NAMES, loadVisibilityCore, localVisibilityMetricSource, planLocalScan, scanLocal } from "./visibility-local.js";
19
19
  import { pullSearchAds, SearchAdsClient, searchAdsMetricSource, searchAdsSource } from "./search-ads.js";
@@ -36,7 +36,7 @@ import { invertChanges } from "./diff.js";
36
36
  import { loadProject, recordPull, SPEC_DIR, SPEC_FILE, writeListing, writeSpec } from "./files.js";
37
37
  import { readReleases, releaseId, releaseMarkdown, writeRelease } from "./history.js";
38
38
  import { freeStores, writeLoops } from "./loops.js";
39
- import { diagnose, findApps, playPackageExists, suggestTargets, targetCandidates, WORKFLOWS } from "./setup.js";
39
+ import { diagnose, findApps, probeConnections, probeSocial, playPackageExists, suggestTargets, targetCandidates, WORKFLOWS } from "./setup.js";
40
40
  import { hasErrors, lintProject } from "./lint.js";
41
41
  import { c, formatChanges, formatCoverage, formatIssues, printJson, storeLabel } from "./output.js";
42
42
  import { CODING_AGENTS, onPath, runQuiet, setupPrompt } from "./coding-agents.js";
@@ -48,7 +48,7 @@ function experimentPlaybookLine(e) {
48
48
  const value = e.result?.value !== undefined ? ` (${e.metric} ${round(e.baseline)} → ${round(e.result.value)})` : "";
49
49
  return `- ${e.startedAt.slice(0, 10)}, ${e.type}${e.persona ? `, ${e.persona}` : ""}: ${e.hypothesis} → ${e.status}${value}${e.result?.note ? `. ${e.result.note}` : ""}`;
50
50
  }
51
- import { STORE_CLIS } from "./transport.js";
51
+ import { npxPackage, STORE_CLIS } from "./transport.js";
52
52
  const PLAYBOOK = `# Playbook
53
53
 
54
54
  What worked and what did not for this app. Appeeky Spec and your agent read this
@@ -127,11 +127,22 @@ async function confirm(question) {
127
127
  function storeOption() {
128
128
  return new Option("-s, --store <store>", "Only this store").choices([...STORES]);
129
129
  }
130
+ /** This package's version, from package.json next to src/ and dist/ (never typed by hand). */
131
+ export const VERSION = (() => {
132
+ try {
133
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
134
+ }
135
+ catch {
136
+ return "unknown";
137
+ }
138
+ })();
139
+ /** Errors the CLI throws on purpose carry a message meant for the user; anything else is a bug worth reporting. */
140
+ const EXPECTED_ERRORS = new Set(["Error", "SpecError", "TransportError", "AppeekyApiError", "CommanderError", "ConnectUnavailableError"]);
130
141
  export function buildProgram() {
131
142
  const program = new Command()
132
143
  .name("appeeky-spec")
133
144
  .description("Your app's store listing as a spec: check it, measure keyword coverage, diff it with the live store and push it.")
134
- .version("0.1.0")
145
+ .version(VERSION)
135
146
  .option("-C, --cwd <dir>", "Run as if started in this folder", process.cwd())
136
147
  .option("--json", "Machine-readable output", false)
137
148
  .addOption(new Option("--via <mode>", "How to reach the stores (overrides the spec)").choices(["auto", "local", "hosted"]));
@@ -139,6 +150,34 @@ export function buildProgram() {
139
150
  const transportOverrides = () => (g().via ? { via: g().via } : {});
140
151
  const load = () => loadProject(g().cwd);
141
152
  const api = () => (process.env.APPEEKY_API_KEY ? new AppeekyApi(process.env.APPEEKY_API_KEY, { baseUrl: process.env.APPEEKY_API_URL }) : undefined);
153
+ /** Pull each store on its own: one that cannot be reached does not stop the other. */
154
+ const pullListings = async (project, only, locales) => {
155
+ const written = [];
156
+ const errors = [];
157
+ const stores = configuredStores(project, only);
158
+ for (const store of stores) {
159
+ try {
160
+ const handle = storeHandle(project, store, transportOverrides());
161
+ if (!g().json)
162
+ console.log(c.dim(`${storeLabel(store)}: pulling via ${handle.transport.label}…`));
163
+ const state = await handle.adapter.pull();
164
+ for (const [locale, listing] of Object.entries(state.listings)) {
165
+ if (locales && !locales.includes(locale))
166
+ continue;
167
+ written.push({ store, locale, file: await writeListing(project.root, store, locale, listing) });
168
+ }
169
+ await recordPull(project.root, store, state.target);
170
+ if (!g().json)
171
+ console.log(`${storeLabel(store)}: ${Object.keys(state.listings).length} locales from ${state.target}`);
172
+ }
173
+ catch (e) {
174
+ errors.push({ store, message: e.message });
175
+ if (!g().json)
176
+ console.error(c.red(`${storeLabel(store)}: ${e.message}`));
177
+ }
178
+ }
179
+ return { written, errors, stores };
180
+ };
142
181
  /** Appeeky API ranks when a key is set (both stores), Apple's public search otherwise (App Store only). */
143
182
  const rankSource = () => {
144
183
  const a = api();
@@ -153,6 +192,8 @@ export function buildProgram() {
153
192
  .option("--locale <locale>", "Primary locale", "en-US")
154
193
  .option("--country <cc>", "First storefront to add targets for", "us")
155
194
  .option("--pull", "Pull the live listings right away", false)
195
+ .option("--targets <searches>", "Comma-separated searches to win in --country (default: five suggested from the app's name and where it already ranks)")
196
+ .option("--no-targets", "Leave targets empty")
156
197
  .option("--ci", "Write the GitHub workflows (pull request check, push on merge, daily verify); works on an existing spec too", false)
157
198
  .action(async (opts) => {
158
199
  const root = resolve(g().cwd);
@@ -192,10 +233,45 @@ export function buildProgram() {
192
233
  if (!opts.appStore && !opts.googlePlay)
193
234
  console.log(c.dim("Add stores.appStore.appId or stores.googlePlay.packageName, then run `appeeky-spec pull`."));
194
235
  }
195
- if (opts.pull && (opts.appStore || opts.googlePlay))
196
- await program.parseAsync(["pull"], { from: "user" });
197
- else if (g().json)
198
- printJson({ root, created: [SPEC_FILE, `${SPEC_DIR}/`, ...workflows] });
236
+ // Pull failures are reported and do not stop init: the spec is there, `pull` can run again later.
237
+ const pulled = opts.pull && (opts.appStore || opts.googlePlay) ? await pullListings(await load()) : undefined;
238
+ if (pulled?.errors.length)
239
+ process.exitCode = 1;
240
+ // The Google Play category, so `category pull` records its chart from the first day.
241
+ if (opts.googlePlay) {
242
+ const detected = await playCategory(opts.googlePlay).catch(() => undefined);
243
+ if (detected) {
244
+ // Into the spec as written above, so the file keeps only what init chose (no schema defaults).
245
+ spec.category = { ...spec.category, googlePlay: detected };
246
+ await writeSpec(root, spec);
247
+ if (!g().json)
248
+ console.log(`${c.green("Category")} Google Play ${detected}`);
249
+ }
250
+ }
251
+ // Targets, as the guided setup does: the ones given, or five suggested from the listing (or the
252
+ // name) and where the app already ranks on the App Store. --no-targets leaves them empty.
253
+ const country = opts.country.toLowerCase();
254
+ let targets = [];
255
+ let suggested = false;
256
+ if (typeof opts.targets === "string")
257
+ targets = [...new Set(opts.targets.split(",").map((x) => x.trim().toLowerCase()).filter(Boolean))];
258
+ else if (opts.targets !== false && (opts.appStore || opts.googlePlay)) {
259
+ const project = await load();
260
+ const appStoreId = opts.appStore && /^\d+$/.test(opts.appStore) ? opts.appStore : undefined;
261
+ const ranked = await suggestTargets(targetCandidates(project, 14, opts.name), appStoreId, country, itunesRankSource()).catch(() => []);
262
+ targets = ranked.map((r) => r.keyword);
263
+ suggested = true;
264
+ }
265
+ if (targets.length) {
266
+ spec.targets = { ...spec.targets, [country]: targets };
267
+ await writeSpec(root, spec);
268
+ if (!g().json)
269
+ console.log(`${c.green(suggested ? "Suggested" : "Added")} ${targets.length} targets for ${country.toUpperCase()}: ${targets.join(", ")}${suggested ? c.dim("\n A first guess from the name and listing: check them, and re-rank with `appeeky-spec suggest` once APPEEKY_API_KEY is set.") : ""}`);
270
+ }
271
+ else if (!g().json && opts.targets !== false)
272
+ console.log(c.dim(`No targets yet: add the searches to win under targets.${country} in ${SPEC_FILE}, or run \`appeeky-spec suggest\`.`));
273
+ if (g().json)
274
+ printJson({ root, created: [SPEC_FILE, `${SPEC_DIR}/`, ...workflows], targets: { [country]: targets }, ...(pulled ? { pulled: { written: pulled.written, errors: pulled.errors } } : {}) });
199
275
  });
200
276
  /**
201
277
  * The guided setup: find the app, make its folder and write the spec, check that the stores
@@ -413,7 +489,7 @@ export function buildProgram() {
413
489
  }
414
490
  const s = p.spinner();
415
491
  s.start(`Saving the key with the ${cli.bin} CLI`);
416
- const result = await runQuiet("npx", ["-y", "-p", cli.npmPackage, cli.bin, ...args], process.cwd());
492
+ const result = await runQuiet("npx", ["-y", "-p", npxPackage(store), cli.bin, ...args], process.cwd());
417
493
  if (result.code === 0) {
418
494
  s.stop(`Saved as "${account}" in the ${cli.bin} CLI's config (not in this repo)`);
419
495
  return true;
@@ -465,17 +541,21 @@ export function buildProgram() {
465
541
  program
466
542
  .command("doctor")
467
543
  .description("What is set up for this repo, what is missing, and how to fix it")
468
- .action(async () => {
544
+ .option("--offline", "Only look at what is set up; do not call the hosted gateways to check the connection", false)
545
+ .action(async (opts) => {
469
546
  const root = resolve(g().cwd);
470
547
  const project = await load().catch(() => null);
471
- const checks = diagnose(project?.root ?? root, project);
548
+ let checks = diagnose(project?.root ?? root, project);
549
+ if (project && !opts.offline)
550
+ checks = await probeSocial(project, await probeConnections(project, checks));
472
551
  if (g().json)
473
552
  printJson({ checks });
474
553
  else {
475
554
  printChecks(checks);
476
555
  const fails = checks.filter((x) => x.status === "fail").length;
477
- const warns = checks.filter((x) => x.status === "warn").length;
478
- console.log(`\n${fails ? c.red(`${fails} to fix`) : c.green("Ready")}${warns ? c.dim(` · ${warns} optional`) : ""}`);
556
+ const look = checks.filter((x) => x.status === "warn" && x.attention).length;
557
+ const warns = checks.filter((x) => x.status === "warn" && !x.attention).length;
558
+ console.log(`\n${fails ? c.red(`${fails} to fix`) : c.green("Ready")}${look ? c.yellow(` · ${look} to look at`) : ""}${warns ? c.dim(` · ${warns} optional`) : ""}`);
479
559
  }
480
560
  if (checks.some((x) => x.status === "fail"))
481
561
  process.exitCode = 1;
@@ -486,24 +566,13 @@ export function buildProgram() {
486
566
  .addOption(storeOption())
487
567
  .option("--locale <locales...>", "Only these locales")
488
568
  .action(async (opts) => {
489
- const project = await load();
490
- const written = [];
491
- for (const store of configuredStores(project, opts.store)) {
492
- const handle = storeHandle(project, store, transportOverrides());
493
- if (!g().json)
494
- console.log(c.dim(`${storeLabel(store)}: pulling via ${handle.transport.label}…`));
495
- const state = await handle.adapter.pull();
496
- for (const [locale, listing] of Object.entries(state.listings)) {
497
- if (opts.locale && !opts.locale.includes(locale))
498
- continue;
499
- written.push({ store, locale, file: await writeListing(project.root, store, locale, listing) });
500
- }
501
- await recordPull(project.root, store, state.target);
502
- if (!g().json)
503
- console.log(`${storeLabel(store)}: ${Object.keys(state.listings).length} locales from ${state.target}`);
504
- }
569
+ const { written, errors, stores } = await pullListings(await load(), opts.store, opts.locale);
505
570
  if (g().json)
506
- printJson({ written });
571
+ printJson({ written, errors });
572
+ else if (errors.length && errors.length < stores.length)
573
+ console.error(c.dim(`Pulled ${stores.length - errors.length} of ${stores.length} stores; fix the one above and run \`appeeky-spec pull --store ${errors[0].store}\`.`));
574
+ if (errors.length)
575
+ process.exitCode = 1;
507
576
  });
508
577
  program
509
578
  .command("check")
@@ -956,10 +1025,13 @@ export function buildProgram() {
956
1025
  const a = api();
957
1026
  if (!a)
958
1027
  throw new Error("Set APPEEKY_API_KEY: posts come from the social accounts connected in Appeeky.");
959
- const data = await fetchSocial(a, { limit: Number(opts.limit) || 100 });
1028
+ const only = project.spec.social?.accounts;
1029
+ const data = await fetchSocial(a, { limit: Number(opts.limit) || 100, only });
1030
+ if (only?.length && !g().json)
1031
+ console.log(c.dim(`Only the accounts under social.accounts in ${SPEC_FILE}: ${only.join(", ")}`));
960
1032
  await saveSocial(project.root, data);
961
1033
  if (g().json) {
962
- printJson({ accounts: data.accounts.length, posts: data.posts.length, nativePosts: data.nativePosts?.length ?? null, comments: data.comments?.length ?? null, insights: data.insights?.length ?? null, warnings: data.warnings ?? [] });
1034
+ printJson({ accounts: data.accounts.length, posts: data.posts.length, nativePosts: data.nativePosts?.length ?? null, comments: data.comments?.length ?? null, insights: data.insights?.length ?? null, warnings: data.warnings ?? [], problems: accountProblems(data.accounts, only).map(({ account, ...p }) => ({ ...p, ...(account ? { account: account.id } : {}) })) });
963
1035
  return;
964
1036
  }
965
1037
  console.log(`${c.bold("Accounts")} ${data.accounts.map((x) => `${x.platform} (${x.name})`).join(", ") || c.dim("none connected")}`);
@@ -968,9 +1040,57 @@ export function buildProgram() {
968
1040
  console.log(`${c.bold("Comments")} ${data.comments.length}`);
969
1041
  for (const w of data.warnings ?? [])
970
1042
  console.log(`${c.yellow("warn ")} ${w}`);
1043
+ for (const p of accountProblems(data.accounts, only))
1044
+ console.log(`${c.red("fix ")} ${p.message}\n ${c.dim(p.fix)}`);
971
1045
  const files = ["accounts.yaml", "posts.jsonl", data.nativePosts && "native-posts.jsonl", data.comments && "comments.jsonl", data.insights && "insights.yaml", "summary.md"].filter(Boolean);
972
1046
  console.log(c.dim(`Written to appeeky/social/: ${files.join(", ")}.`));
973
1047
  });
1048
+ social
1049
+ .command("connect")
1050
+ .description("Connect a social account, or reconnect one that stopped working, without the Appeeky dashboard: prints the sign-in link and waits until it lands")
1051
+ .argument("<platform>", "tiktok, instagram, pinterest, youtube, twitter, linkedin, …")
1052
+ .option("--account <account>", "The account to reconnect when the platform has several: a handle (@saikoaiapp) or its id")
1053
+ .option("--no-wait", "Only print the link; do not wait for the sign-in")
1054
+ .option("--timeout <seconds>", "How long to wait for the sign-in", "600")
1055
+ .action(async (platform, opts) => {
1056
+ const a = api();
1057
+ if (!a)
1058
+ throw new Error("Set APPEEKY_API_KEY: the account is connected to your Appeeky account, which keeps its tokens and refreshes them.");
1059
+ const before = await listAccountRows(a);
1060
+ const onPlatform = before.map(toAccount).filter((x) => x.platform.toLowerCase() === platform.toLowerCase() || (platform.toLowerCase() === "x" && x.platform === "twitter"));
1061
+ let target = opts.account ? onPlatform.find((x) => accountMatches(x, [opts.account, `${x.platform}:${opts.account}`])) : undefined;
1062
+ if (opts.account && !target)
1063
+ throw new Error(`No ${platform} account ${opts.account} is connected (${onPlatform.map(accountLabel).join(", ") || "none"}). Leave out --account to connect a new one.`);
1064
+ // One broken account on the platform: that is the one to reconnect.
1065
+ if (!target && onPlatform.filter((x) => !x.active).length === 1)
1066
+ target = onPlatform.find((x) => !x.active);
1067
+ const link = await connectLink(a, platform, target?.id);
1068
+ if (g().json && !opts.wait) {
1069
+ printJson({ platform, account: target?.id ?? null, ...link });
1070
+ return;
1071
+ }
1072
+ if (!g().json) {
1073
+ console.log(`${c.bold(target ? `Reconnect ${platform} ${accountLabel(target)}` : `Connect ${platform}`)}${target?.problem ? c.dim(` (${target.problem})`) : ""}`);
1074
+ console.log(` Sign in: ${link.url}`);
1075
+ if (link.phoneUrl)
1076
+ console.log(` On your phone: ${link.phoneUrl}`);
1077
+ if (link.expiresAt)
1078
+ console.log(c.dim(` The link works until ${link.expiresAt}.`));
1079
+ }
1080
+ if (!opts.wait)
1081
+ return;
1082
+ if (!g().json)
1083
+ console.log(c.dim(`Waiting for the sign-in (up to ${opts.timeout}s; Ctrl+C to stop, the link still works)…`));
1084
+ const done = await waitForConnection(a, platform, before, { timeoutMs: (Number(opts.timeout) || 600) * 1000, accountId: target?.id });
1085
+ if (g().json)
1086
+ printJson({ platform, connected: done ? { id: done.id, name: done.name } : null, ...link });
1087
+ else if (done)
1088
+ console.log(c.green(`Connected: ${done.platform} ${accountLabel(done)}.`) + c.dim(" Run `appeeky-spec social pull` to write it to appeeky/social/."));
1089
+ else
1090
+ console.log(c.yellow("No sign-in yet. The link still works: run this again to wait, or `appeeky-spec doctor` to check later."));
1091
+ if (!done)
1092
+ process.exitCode = 1;
1093
+ });
974
1094
  social
975
1095
  .command("check")
976
1096
  .description("Check the drafts in appeeky/social/drafts/: which account each goes to, length, media, TikTok and YouTube options, time")
@@ -2222,11 +2342,21 @@ export async function run(argv = process.argv) {
2222
2342
  await program.parseAsync(argv);
2223
2343
  }
2224
2344
  catch (err) {
2225
- const message = err.message;
2345
+ const e = err;
2346
+ const debug = Boolean(process.env.APPEEKY_SPEC_DEBUG);
2347
+ // A TypeError and the like is a bug, not a message for the user: say so, with where it happened.
2348
+ const bug = !EXPECTED_ERRORS.has(e?.name ?? "Error");
2349
+ const frames = (e?.stack ?? "").split("\n").slice(1).map((l) => l.trim());
2350
+ const where = frames.find((l) => /appeeky-spec|@appeeky\/spec|\/src\/|\/dist\//.test(l)) ?? frames[0];
2226
2351
  if (program.opts().json)
2227
- printJson({ error: message });
2228
- else
2229
- console.error(c.red(message));
2352
+ printJson({ error: e?.message ?? String(err), ...(bug ? { bug: true, version: VERSION, where, ...(debug ? { stack: e?.stack } : {}) } : {}) });
2353
+ else {
2354
+ console.error(c.red(e?.message ?? String(err)));
2355
+ if (bug) {
2356
+ console.error(c.dim(`${e.name} in appeeky-spec ${VERSION}${where ? `, ${where}` : ""}.`));
2357
+ console.error(c.dim(debug ? (e.stack ?? "") : "This is a bug: run again with APPEEKY_SPEC_DEBUG=1 for the full stack, and report it with the command you ran."));
2358
+ }
2359
+ }
2230
2360
  process.exitCode = 1;
2231
2361
  }
2232
2362
  }
package/dist/data.d.ts CHANGED
@@ -8,7 +8,9 @@ import type { Project } from "./schema.js";
8
8
  *
9
9
  * They are private business data, so they go to .appeeky/data/ (gitignored) unless the
10
10
  * spec says `data: { commit: true }`, which writes them to appeeky/data/ instead.
11
- * Pulling again merges by date, so a scheduled pull keeps one growing file per source.
11
+ * Pulling again merges by date, so pulls in the same folder keep one growing file per source.
12
+ * The Docker routines start from a fresh clone, where .appeeky/ is empty: there a file grows
13
+ * only with `data: { commit: true }`, otherwise each run holds the last `--days`.
12
14
  */
13
15
  export declare function dataDir(project: Project): string;
14
16
  type Row = Record<string, string | number | null | undefined>;
package/dist/data.js CHANGED
@@ -10,7 +10,9 @@ import { rankAppIds } from "./verify.js";
10
10
  *
11
11
  * They are private business data, so they go to .appeeky/data/ (gitignored) unless the
12
12
  * spec says `data: { commit: true }`, which writes them to appeeky/data/ instead.
13
- * Pulling again merges by date, so a scheduled pull keeps one growing file per source.
13
+ * Pulling again merges by date, so pulls in the same folder keep one growing file per source.
14
+ * The Docker routines start from a fresh clone, where .appeeky/ is empty: there a file grows
15
+ * only with `data: { commit: true }`, otherwise each run holds the last `--days`.
14
16
  */
15
17
  export function dataDir(project) {
16
18
  return project.spec.data.commit ? join(project.root, SPEC_DIR, "data") : join(project.root, ".appeeky", "data");
package/dist/lint.d.ts CHANGED
@@ -9,6 +9,7 @@ export interface Issue {
9
9
  field?: string;
10
10
  message: string;
11
11
  }
12
+ export declare function functionWords(locale: string): Set<string>;
12
13
  export declare function lintLength(store: StoreId, locale: string, field: string, value: string | undefined): Issue[];
13
14
  export declare function lintAppStore(locale: string, listing: AppStoreListing): Issue[];
14
15
  export declare function lintGooglePlay(locale: string, listing: GooglePlayListing): Issue[];
package/dist/lint.js CHANGED
@@ -2,6 +2,25 @@ import { LIMITS } from "./limits.js";
2
2
  import { charLength, isEnglish, keywordEntries, singular, unique, words } from "./text.js";
3
3
  /** Words Apple already ignores or that buy nothing in the keyword field. */
4
4
  const APPLE_FILLER = new Set(["app", "apps", "the", "a", "an", "and", "or", "for", "with", "of", "iphone", "ipad"]);
5
+ /**
6
+ * Articles, prepositions and conjunctions per language. They carry no search on their own, so a
7
+ * name and subtitle that both need "de" or "and" to read naturally are not wasting index space.
8
+ */
9
+ const FUNCTION_WORDS = {
10
+ en: "a an the and or of for with to in on by at from",
11
+ es: "de del la el los las y o en con para por un una al a",
12
+ pt: "de do da dos das e o a os as em com para por um uma no na",
13
+ fr: "de du des la le les et ou en avec pour par un une au aux à l d",
14
+ it: "di del della dei delle e o il lo la i gli le in con per un una al a da",
15
+ de: "der die das und oder mit für von zu im in am an auf ein eine den dem des",
16
+ nl: "de het een en of met voor van in op",
17
+ tr: "ve ile için bir da de",
18
+ pl: "i w z na do dla o",
19
+ sv: "och med för av i på en ett",
20
+ };
21
+ export function functionWords(locale) {
22
+ return new Set((FUNCTION_WORDS[locale.split("-")[0].toLowerCase()] ?? "").split(" ").filter(Boolean));
23
+ }
5
24
  /** Google Play's metadata policy rejects these in the title. */
6
25
  const PLAY_TITLE_BANNED = [/\bbest\b/i, /#\s?1\b/, /\btop\b/i, /\bfree\b/i, /\bno\.?\s?1\b/i, /\bsale\b/i, /\bdiscount\b/i];
7
26
  export function lintLength(store, locale, field, value) {
@@ -30,7 +49,8 @@ export function lintAppStore(locale, listing) {
30
49
  }
31
50
  const nameWords = new Set(words(listing.name));
32
51
  const subtitleWords = words(listing.subtitle);
33
- const repeatedInSubtitle = unique(subtitleWords.filter((w) => nameWords.has(w)));
52
+ const stop = functionWords(locale);
53
+ const repeatedInSubtitle = unique(subtitleWords.filter((w) => nameWords.has(w) && !stop.has(w)));
34
54
  if (repeatedInSubtitle.length > 0) {
35
55
  at("warning", "subtitle/repeats-name", "subtitle", `Subtitle repeats ${quoteList(repeatedInSubtitle)} from the name. Each word is indexed once, so use the space for a new word.`);
36
56
  }
@@ -52,7 +72,7 @@ export function lintAppStore(locale, listing) {
52
72
  }
53
73
  const keywordWords = entries.flatMap((e) => words(e));
54
74
  const titled = new Set([...nameWords, ...subtitleWords]);
55
- const alreadyIndexed = unique(keywordWords.filter((w) => titled.has(w)));
75
+ const alreadyIndexed = unique(keywordWords.filter((w) => titled.has(w) && !stop.has(w)));
56
76
  if (alreadyIndexed.length > 0) {
57
77
  at("warning", "keywords/duplicate-of-name", "keywords", `${quoteList(alreadyIndexed)} already ${alreadyIndexed.length === 1 ? "appears" : "appear"} in the name or subtitle, so the keyword field does not need ${alreadyIndexed.length === 1 ? "it" : "them"}.`);
58
78
  }
@@ -60,11 +80,12 @@ export function lintAppStore(locale, listing) {
60
80
  if (repeatedWords.length > 0) {
61
81
  at("info", "keywords/repeated-word", "keywords", `${quoteList(repeatedWords)} ${repeatedWords.length === 1 ? "is" : "are"} written more than once. Single words combine with each other, so phrases rarely need repeating.`);
62
82
  }
83
+ // Filler in any language: the function words above, plus Apple's English ones.
84
+ const filler = unique(keywordWords.filter((w) => stop.has(w) || (isEnglish(locale) && APPLE_FILLER.has(w))));
85
+ if (filler.length > 0) {
86
+ at("info", "keywords/filler", "keywords", `${quoteList(filler)} add little in the keyword field.`);
87
+ }
63
88
  if (isEnglish(locale)) {
64
- const filler = unique(keywordWords.filter((w) => APPLE_FILLER.has(w)));
65
- if (filler.length > 0) {
66
- at("info", "keywords/filler", "keywords", `${quoteList(filler)} add little in the keyword field.`);
67
- }
68
89
  const all = unique([...titled, ...keywordWords]);
69
90
  const plurals = all.filter((w) => singular(w) !== w && all.includes(singular(w)));
70
91
  if (plurals.length > 0) {