@appeeky/spec 0.2.1 → 0.4.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/dist/social.js CHANGED
@@ -3,14 +3,18 @@ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import YAML from "yaml";
5
5
  import { z } from "zod";
6
+ import { AppeekyApiError } from "./appeeky-api.js";
6
7
  import { SPEC_DIR, SpecError } from "./files.js";
7
8
  /**
8
9
  * Organic social media in the repo, through the accounts connected in Appeeky (APPEEKY_API_KEY,
9
10
  * Startup plan or above):
10
11
  *
11
12
  * appeeky/social/accounts.yaml the connected accounts (platform, name, id)
12
- * appeeky/social/posts.jsonl recent posts, one per line, with each platform's result
13
- * appeeky/social/summary.md the last 30 days per platform, and the posts that did best
13
+ * appeeky/social/posts.jsonl recent posts made through Appeeky, one per line, with each platform's result
14
+ * appeeky/social/native-posts.jsonl posts made in the platform's own app, with their results
15
+ * appeeky/social/comments.jsonl recent comments on the accounts' posts
16
+ * appeeky/social/insights.yaml followers and growth per account
17
+ * appeeky/social/summary.md the last 30 days per account and platform, and the posts that did best
14
18
  * appeeky/social/drafts/<name>.yaml a post: drafted, reviewed in a pull request, then sent
15
19
  *
16
20
  * Sending creates the post in Appeeky, which publishes it right away, or at `when`.
@@ -38,12 +42,83 @@ export function toPost(r, analytics = []) {
38
42
  url: p.platform_post_url ?? undefined,
39
43
  publishedAt: p.published_at ?? undefined,
40
44
  error: p.error_message ?? undefined,
45
+ draft: p.is_draft ? true : undefined,
41
46
  metrics: Object.keys(metrics).length ? metrics : undefined,
42
47
  });
43
48
  }),
44
49
  });
45
50
  }
46
- /** Connected accounts and the latest posts, with analytics for the ones that went out. */
51
+ const numbers = (m, keys) => Object.fromEntries(keys.filter((k) => typeof m?.[k] === "number" && m[k] > 0).map((k) => [k, m[k]]));
52
+ export function toNativePost(r, accounts) {
53
+ const metrics = numbers(r.metrics, [...METRICS, "engagementRate"]);
54
+ return compact({
55
+ id: r.id,
56
+ account: accounts.find((a) => a.id === r.accountId)?.name ?? r.accountId,
57
+ platform: r.platform,
58
+ url: r.platformPostUrl ?? undefined,
59
+ text: r.content ?? "",
60
+ mediaType: r.mediaType ?? undefined,
61
+ publishedAt: r.publishedAt ?? undefined,
62
+ metrics: Object.keys(metrics).length ? metrics : undefined,
63
+ });
64
+ }
65
+ export function toComment(r, accounts) {
66
+ return compact({
67
+ id: r.id,
68
+ account: accounts.find((a) => a.id === r.accountId)?.name ?? r.accountId,
69
+ platform: r.platform,
70
+ postUrl: r.postPermalink ?? undefined,
71
+ postId: r.postId ?? undefined,
72
+ platformPostId: r.platformPostId ?? undefined,
73
+ text: r.text ?? "",
74
+ author: r.author?.username ?? r.author?.name ?? undefined,
75
+ own: r.isOwnAccount ? true : undefined,
76
+ reply: r.isReply ? true : undefined,
77
+ at: r.commentedAt ?? undefined,
78
+ });
79
+ }
80
+ export function toInsights(r, account) {
81
+ return compact({
82
+ account: account.name,
83
+ platform: r.platform ?? account.platform,
84
+ followers: r.followers ?? undefined,
85
+ growth: r.growth ?? undefined,
86
+ growthPercentage: r.growthPercentage ?? undefined,
87
+ stats: r.stats && Object.keys(r.stats).length ? r.stats : undefined,
88
+ history: r.history?.length ? r.history : undefined,
89
+ updatedAt: r.updatedAt ?? undefined,
90
+ });
91
+ }
92
+ /**
93
+ * One call per connected account to an endpoint the deployed Appeeky API may not have yet. A 404
94
+ * (or any other failure) becomes a warning and the pull goes on; a 404 on the first account skips
95
+ * the rest, since the endpoint is missing. `skip` lists error codes that only mean "not for this
96
+ * account" (insights on X or LinkedIn).
97
+ */
98
+ async function perAccount(accounts, what, warnings, fetchOne, map, skip = []) {
99
+ const out = [];
100
+ let ok = false;
101
+ for (const a of accounts) {
102
+ try {
103
+ out.push(...map(await fetchOne(a), a));
104
+ ok = true;
105
+ }
106
+ catch (e) {
107
+ if (e instanceof AppeekyApiError && e.code && skip.includes(e.code))
108
+ continue;
109
+ if (e instanceof AppeekyApiError && e.status === 404 && !ok) {
110
+ warnings.push(`${what}: not available on this Appeeky API yet, skipped (the file from the last pull is kept)`);
111
+ return undefined;
112
+ }
113
+ warnings.push(`${what} for ${a.platform} ${a.name}: ${e.message}`);
114
+ }
115
+ }
116
+ return ok || !warnings.some((w) => w.startsWith(`${what} for `)) ? out : undefined;
117
+ }
118
+ /**
119
+ * Connected accounts and the latest posts made through Appeeky, with analytics for the ones that
120
+ * went out; then, per account, the posts made in the platform's app, recent comments and followers.
121
+ */
47
122
  export async function fetchSocial(api, options = {}) {
48
123
  const accounts = ((await api.get("/connect/social/accounts")) ?? []).map(toAccount);
49
124
  const rows = (await api.get("/social/posts", { limit: String(options.limit ?? 100) })) ?? [];
@@ -53,21 +128,37 @@ export async function fetchSocial(api, options = {}) {
53
128
  const analytics = published ? ((await api.get(`/social/posts/${encodeURIComponent(row.id)}/analytics`).catch(() => null))?.analytics ?? []) : [];
54
129
  posts.push(toPost(row, analytics));
55
130
  }
56
- return { accounts, posts };
131
+ const warnings = [];
132
+ const active = accounts.filter((a) => a.active);
133
+ const nativePosts = await perAccount(active, "Native posts", warnings, (a) => api.get("/social/external-posts", { account_id: a.id, limit: "200" }), (rows) => (rows ?? []).map((r) => toNativePost(r, accounts)));
134
+ const comments = await perAccount(active, "Comments", warnings, (a) => api.get("/social/comments", { account_id: a.id, limit: "100" }), (rows) => (rows ?? []).map((r) => toComment(r, accounts)));
135
+ const insights = await perAccount(active, "Follower insights", warnings, (a) => api.get(`/connect/social/accounts/${encodeURIComponent(a.id)}/insights`), (row, a) => (row ? [toInsights(row, a)] : []), ["INSIGHTS_UNAVAILABLE"]);
136
+ const unique = (rows) => rows?.filter((r, i) => rows.findIndex((x) => x.id === r.id) === i);
137
+ return { accounts, posts, nativePosts: unique(nativePosts), comments: unique(comments), insights, warnings };
57
138
  }
58
139
  const total = (p, k) => p.metrics?.[k] ?? 0;
59
140
  /** The reach of a post on one platform: views when the platform reports them, else impressions or reach. */
60
141
  const seen = (p) => total(p, "views") || total(p, "impressions") || total(p, "reach");
61
- export function summaryMarkdown(accounts, posts, now = new Date()) {
142
+ const score = (p) => seen(p) + total(p, "likes") * 10;
143
+ const oneLine = (text, max) => {
144
+ const t = text.replace(/\s+/g, " ").trim();
145
+ return `${t.slice(0, max)}${t.length > max ? "…" : ""}`;
146
+ };
147
+ const signed = (n) => (n > 0 ? `+${n}` : String(n));
148
+ export function summaryMarkdown(accounts, posts, now = new Date(), more = {}) {
62
149
  const since = new Date(now.getTime() - 30 * 86_400_000).toISOString();
63
150
  const recent = posts.filter((p) => (p.platforms.find((x) => x.publishedAt)?.publishedAt ?? p.createdAt) >= since);
151
+ const native = (more.nativePosts ?? []).filter((p) => (p.publishedAt ?? "") >= since);
64
152
  const lines = [`# Social media`, "", `Updated ${now.toISOString().slice(0, 10)}. The last 30 days, from the accounts connected in Appeeky.`, ""];
65
153
  lines.push("## Accounts", "");
66
154
  if (!accounts.length)
67
155
  lines.push("None connected. Connect them in Appeeky (Social).");
68
- for (const a of accounts)
69
- lines.push(`- ${a.platform}: ${a.name}${a.active ? "" : " (needs reconnecting in Appeeky)"}`);
70
- lines.push("", "## By platform", "");
156
+ for (const a of accounts) {
157
+ const i = more.insights?.find((x) => x.account === a.name && x.platform === a.platform);
158
+ const followers = i?.followers !== undefined ? `, ${i.followers} followers${i.growth !== undefined ? ` (${signed(i.growth)}${i.growthPercentage !== undefined ? `, ${signed(Math.round(i.growthPercentage * 10) / 10)}%` : ""})` : ""}` : "";
159
+ lines.push(`- ${a.platform}: ${a.name}${followers}${a.active ? "" : " (needs reconnecting in Appeeky)"}`);
160
+ }
161
+ lines.push("", "## By platform, posts made through Appeeky", "");
71
162
  const platforms = [...new Set(recent.flatMap((p) => p.platforms.map((x) => x.platform)))].sort();
72
163
  if (!platforms.length)
73
164
  lines.push("No posts in the last 30 days.");
@@ -79,30 +170,72 @@ export function summaryMarkdown(accounts, posts, now = new Date()) {
79
170
  lines.push(`| ${platform} | ${results.filter((x) => x.publishedAt).length} | ${sum(seen)} | ${sum((x) => total(x, "likes"))} | ${sum((x) => total(x, "comments"))} | ${sum((x) => total(x, "shares") + total(x, "reposts"))} | ${results.filter((x) => x.error).length} |`);
80
171
  }
81
172
  }
82
- const best = recent
83
- .flatMap((p) => p.platforms.filter((x) => x.publishedAt).map((x) => ({ post: p, result: x })))
84
- .sort((a, b) => seen(b.result) + total(b.result, "likes") * 10 - (seen(a.result) + total(a.result, "likes") * 10))
85
- .slice(0, 5);
86
- if (best.length) {
87
- lines.push("", "## Did best", "");
88
- for (const { post, result } of best) {
89
- const text = post.text.replace(/\s+/g, " ").slice(0, 90);
90
- lines.push(`- ${result.platform}, ${result.publishedAt.slice(0, 10)}: ${seen(result)} seen, ${total(result, "likes")} likes. "${text}${post.text.length > 90 ? "…" : ""}"${result.url ? ` ${result.url}` : ""}`);
173
+ if (more.nativePosts) {
174
+ lines.push("", "## By account, posts made in the platform's app", "");
175
+ const byAccount = [...new Set(native.map((p) => `${p.platform} ${p.account}`))].sort();
176
+ if (!byAccount.length)
177
+ lines.push("No posts made in the platform apps in the last 30 days.");
178
+ else {
179
+ lines.push("| Account | Posts | Seen | Likes | Comments | Shares | Saves |", "| --- | --- | --- | --- | --- | --- | --- |");
180
+ for (const key of byAccount) {
181
+ const list = native.filter((p) => `${p.platform} ${p.account}` === key);
182
+ const sum = (f) => list.reduce((n, x) => n + f(x), 0);
183
+ lines.push(`| ${key} | ${list.length} | ${sum(seen)} | ${sum((x) => total(x, "likes"))} | ${sum((x) => total(x, "comments"))} | ${sum((x) => total(x, "shares") + total(x, "reposts"))} | ${sum((x) => total(x, "saves"))} |`);
184
+ }
91
185
  }
92
186
  }
187
+ const best = [
188
+ ...recent.flatMap((p) => p.platforms.filter((x) => x.publishedAt).map((x) => ({ where: x.platform, via: "through Appeeky", text: p.text, at: x.publishedAt, url: x.url, metrics: x.metrics }))),
189
+ ...native.map((p) => ({ where: `${p.platform} ${p.account}`, via: "in the app", text: p.text, at: p.publishedAt, url: p.url, metrics: p.metrics })),
190
+ ]
191
+ .sort((a, b) => score(b) - score(a))
192
+ .slice(0, 8);
193
+ if (best.length) {
194
+ lines.push("", "## Did best, all posts", "");
195
+ for (const b of best)
196
+ lines.push(`- ${b.where}, ${b.at.slice(0, 10)}, ${b.via}: ${seen(b)} seen, ${total(b, "likes")} likes. "${oneLine(b.text, 90)}"${b.url ? ` ${b.url}` : ""}`);
197
+ }
198
+ const inbox = posts.flatMap((p) => p.platforms.filter((x) => x.draft).map((x) => ({ post: p, result: x })));
199
+ if (inbox.length) {
200
+ lines.push("", "## In the TikTok inbox", "", "Uploaded as drafts: the creator finishes and posts them in the TikTok app.", "");
201
+ for (const { post } of inbox)
202
+ lines.push(`- ${post.createdAt.slice(0, 10)}: "${oneLine(post.text, 80)}"`);
203
+ }
204
+ const heard = (more.comments ?? []).filter((x) => !x.own).sort((a, b) => (b.at ?? "").localeCompare(a.at ?? ""));
205
+ if (heard.length) {
206
+ lines.push("", "## Latest comments", "", `${heard.length} in comments.jsonl. The latest:`, "");
207
+ for (const x of heard.slice(0, 5))
208
+ lines.push(`- ${x.platform} ${x.account}${x.at ? `, ${x.at.slice(0, 10)}` : ""}: "${oneLine(x.text, 120)}"`);
209
+ }
93
210
  const waiting = posts.filter((p) => p.status === "scheduled" || p.status === "pending");
94
211
  if (waiting.length) {
95
212
  lines.push("", "## Waiting to go out", "");
96
213
  for (const p of waiting)
97
- lines.push(`- ${p.scheduledFor?.slice(0, 16).replace("T", " ") ?? "now"} on ${p.platforms.map((x) => x.platform).join(", ")}: "${p.text.replace(/\s+/g, " ").slice(0, 80)}"`);
214
+ lines.push(`- ${p.scheduledFor?.slice(0, 16).replace("T", " ") ?? "now"} on ${p.platforms.map((x) => x.platform).join(", ")}: "${oneLine(p.text, 80)}"`);
98
215
  }
99
216
  return `${lines.join("\n")}\n`;
100
217
  }
218
+ const jsonl = (rows) => rows.map((r) => JSON.stringify(r)).join("\n") + (rows.length ? "\n" : "");
101
219
  export async function saveSocial(root, data, now = new Date()) {
102
- await mkdir(socialDir(root), { recursive: true });
103
- await writeFile(join(socialDir(root), "accounts.yaml"), YAML.stringify({ accounts: data.accounts }, { lineWidth: 0 }));
104
- await writeFile(join(socialDir(root), "posts.jsonl"), data.posts.map((p) => JSON.stringify(p)).join("\n") + (data.posts.length ? "\n" : ""));
105
- await writeFile(join(socialDir(root), "summary.md"), summaryMarkdown(data.accounts, data.posts, now));
220
+ const dir = socialDir(root);
221
+ await mkdir(dir, { recursive: true });
222
+ await writeFile(join(dir, "accounts.yaml"), YAML.stringify({ accounts: data.accounts }, { lineWidth: 0 }));
223
+ await writeFile(join(dir, "posts.jsonl"), jsonl(data.posts));
224
+ if (data.nativePosts)
225
+ await writeFile(join(dir, "native-posts.jsonl"), jsonl(data.nativePosts));
226
+ if (data.comments)
227
+ await writeFile(join(dir, "comments.jsonl"), jsonl(data.comments));
228
+ if (data.insights)
229
+ await writeFile(join(dir, "insights.yaml"), YAML.stringify({ accounts: data.insights }, { lineWidth: 0 }));
230
+ // A file the API could not fill this time is kept, and still counts in the summary.
231
+ const kept = async (file, rows) => {
232
+ if (rows || !existsSync(join(dir, file)))
233
+ return rows;
234
+ return (await readFile(join(dir, file), "utf8")).split("\n").filter(Boolean).map((l) => JSON.parse(l));
235
+ };
236
+ const insights = data.insights ?? (existsSync(join(dir, "insights.yaml")) ? (YAML.parse(await readFile(join(dir, "insights.yaml"), "utf8"))?.accounts ?? undefined) : undefined);
237
+ const more = { nativePosts: await kept("native-posts.jsonl", data.nativePosts), comments: await kept("comments.jsonl", data.comments), insights };
238
+ await writeFile(join(dir, "summary.md"), summaryMarkdown(data.accounts, data.posts, now, more));
106
239
  }
107
240
  export async function readAccounts(root) {
108
241
  const file = join(socialDir(root), "accounts.yaml");
@@ -111,15 +244,52 @@ export async function readAccounts(root) {
111
244
  return (YAML.parse(await readFile(file, "utf8"))?.accounts ?? []);
112
245
  }
113
246
  // ── Drafts ──────────────────────────────────────────────────────────────────
247
+ /** TikTok's posting options, in the words a draft uses; each maps to a key of `extra.tiktok` in the API. */
248
+ export const PRIVACY = { public: "PUBLIC_TO_EVERYONE", friends: "MUTUAL_FOLLOW_FRIENDS", followers: "FOLLOWER_OF_CREATOR", only_me: "SELF_ONLY" };
249
+ export const DISCLOSURE = { none: "none", own_brand: "brand_organic", paid_partnership: "brand_content" };
250
+ export const TIKTOK_MAX_PHOTOS = 35;
251
+ export const TIKTOK_TITLE_LIMIT = 90;
252
+ const tiktokSchema = z
253
+ .object({
254
+ /** Who can see it: public (default), friends, followers or only_me. */
255
+ privacy: z.enum(Object.keys(PRIVACY)).optional(),
256
+ /** Commercial content: none (default), own_brand (promotes your own app or business) or paid_partnership. */
257
+ disclosure: z.enum(Object.keys(DISCLOSURE)).optional(),
258
+ /** Upload to the creator's TikTok inbox instead of posting: they finish and post it in the app. */
259
+ inbox_draft: z.boolean().optional(),
260
+ /** Photo posts: let TikTok add music. */
261
+ auto_music: z.boolean().optional(),
262
+ /** Allow comments (default true). */
263
+ comments: z.boolean().optional(),
264
+ /** Photo posts: the title; the text becomes the description. */
265
+ title: z.string().min(1).optional(),
266
+ /** Photo posts: which image is the cover, from 0. */
267
+ cover_index: z.number().int().min(0).max(TIKTOK_MAX_PHOTOS - 1).optional(),
268
+ /** Video posts: the frame used as the cover, in milliseconds. */
269
+ cover_time_ms: z.number().int().min(0).optional(),
270
+ /** Video posts: an https image used as the cover. */
271
+ cover_image_url: z
272
+ .string()
273
+ .url()
274
+ .refine((u) => u.startsWith("https://"), "must be an https URL")
275
+ .optional(),
276
+ })
277
+ .strict();
114
278
  export const draftSchema = z
115
279
  .object({
116
- /** Platforms (twitter, instagram, tiktok, …) or account ids from accounts.yaml. */
280
+ /**
281
+ * Who it goes to: a platform with one connected account (`twitter`), every account on a
282
+ * platform (`tiktok:all`), a handle (`@sleepysounds`, `tiktok:@sleepysounds`, `u/name`) or an
283
+ * account id from accounts.yaml.
284
+ */
117
285
  accounts: z.array(z.string().min(1)).min(1),
118
286
  text: z.string().min(1),
119
287
  /** ISO time to schedule it; without it, the post goes out when it is sent. */
120
288
  when: z.string().optional(),
121
289
  /** Public image or video URLs. Instagram, TikTok and Pinterest need one. */
122
290
  media: z.array(z.string().url()).optional(),
291
+ /** TikTok's options for the TikTok accounts it goes to. */
292
+ tiktok: tiktokSchema.optional(),
123
293
  /** Why this post, for whoever reviews the pull request. */
124
294
  why: z.string().optional(),
125
295
  status: z.enum(["draft", "sent"]).default("draft"),
@@ -143,44 +313,136 @@ export async function readDrafts(root) {
143
313
  }
144
314
  return out;
145
315
  }
146
- /** The connected accounts a draft goes to: platform names match every active account on that platform. */
316
+ const platformKey = (p) => (p.toLowerCase() === "x" ? "twitter" : p.toLowerCase());
317
+ /** The handles an account answers to: its name, and any @handle or u/name inside it ("Appeeky (@appeeky)"). */
318
+ export function accountHandles(a) {
319
+ const name = a.name.toLowerCase();
320
+ return [...new Set([name, ...(name.match(/@[\w.]+|u\/[\w-]+/g) ?? [])])];
321
+ }
322
+ /** How an account is named in messages: its @handle or u/name when it has one. */
323
+ export const accountLabel = (a) => accountHandles(a).find((h) => h.startsWith("@") || h.startsWith("u/")) ?? a.name;
324
+ /**
325
+ * The connected accounts a draft goes to. A platform name is only enough when one account is
326
+ * connected on it; with several, the draft names one by handle or says `<platform>:all`.
327
+ */
147
328
  export function resolveAccounts(draft, accounts) {
148
329
  const found = [];
149
330
  const missing = [];
331
+ const ambiguous = [];
332
+ const active = accounts.filter((a) => a.active);
150
333
  for (const ref of draft.accounts) {
151
- const key = ref.toLowerCase() === "x" ? "twitter" : ref.toLowerCase();
152
- const match = accounts.filter((a) => a.active && (a.id === ref || a.platform.toLowerCase() === key));
334
+ const trimmed = ref.trim();
335
+ const colon = trimmed.indexOf(":");
336
+ const [platform, who] = colon > 0 ? [platformKey(trimmed.slice(0, colon)), trimmed.slice(colon + 1).trim().toLowerCase()] : [undefined, trimmed.toLowerCase()];
337
+ const onPlatform = (a) => !platform || platformKey(a.platform) === platform;
338
+ let match;
339
+ if (platform && who === "all")
340
+ match = active.filter(onPlatform);
341
+ else if (!platform && active.some((a) => a.id === trimmed))
342
+ match = active.filter((a) => a.id === trimmed);
343
+ else if (!platform && !who.startsWith("@") && !who.startsWith("u/") && active.some((a) => platformKey(a.platform) === platformKey(who))) {
344
+ match = active.filter((a) => platformKey(a.platform) === platformKey(who));
345
+ if (match.length > 1) {
346
+ ambiguous.push({ ref, platform: match[0].platform, choices: match.map(accountLabel) });
347
+ continue;
348
+ }
349
+ }
350
+ else {
351
+ match = active.filter((a) => onPlatform(a) && (a.id === trimmed.slice(colon + 1).trim() || accountHandles(a).includes(who)));
352
+ if (match.length > 1) {
353
+ ambiguous.push({ ref, platform: "", choices: match.map((a) => `${a.platform}:${accountLabel(a)}`) });
354
+ continue;
355
+ }
356
+ }
153
357
  if (match.length)
154
358
  found.push(...match.filter((a) => !found.includes(a)));
155
359
  else
156
360
  missing.push(ref);
157
361
  }
158
- return { accounts: found, missing };
362
+ return { accounts: found, missing, ambiguous };
363
+ }
364
+ const VIDEO = /\.(mp4|mov|m4v|webm)(\?|#|$)/i;
365
+ const IMAGE = /\.(jpe?g|png|webp|gif|heic)(\?|#|$)/i;
366
+ function tiktokIssues(draft, toTikTok) {
367
+ const t = draft.tiktok;
368
+ const media = draft.media ?? [];
369
+ const videos = media.filter((m) => VIDEO.test(m)).length;
370
+ const images = media.filter((m) => IMAGE.test(m)).length;
371
+ const issues = [];
372
+ if (toTikTok) {
373
+ if (videos && images)
374
+ issues.push("tiktok: a post is either images or one video, not both (media:)");
375
+ if (images > TIKTOK_MAX_PHOTOS)
376
+ issues.push(`tiktok: ${images} images, at most ${TIKTOK_MAX_PHOTOS}`);
377
+ }
378
+ if (!t)
379
+ return issues;
380
+ if (!toTikTok)
381
+ return [...issues, "tiktok: options set, but the draft goes to no TikTok account"];
382
+ const disclosed = t.disclosure && t.disclosure !== "none";
383
+ if (disclosed && t.privacy === "only_me" && !t.inbox_draft)
384
+ issues.push(`tiktok: disclosure ${t.disclosure} can't be privacy only_me; make it public, friends or followers, or set inbox_draft: true`);
385
+ if (t.title && t.title.length > TIKTOK_TITLE_LIMIT)
386
+ issues.push(`tiktok: title ${t.title.length}/${TIKTOK_TITLE_LIMIT} characters`);
387
+ const photo = ["title", "auto_music", "cover_index"].filter((k) => t[k] !== undefined);
388
+ const video = ["cover_time_ms", "cover_image_url"].filter((k) => t[k] !== undefined);
389
+ if (videos && photo.length)
390
+ issues.push(`tiktok: ${photo.join(", ")} only apply to photo posts, and media: is a video`);
391
+ if (images && !videos && video.length)
392
+ issues.push(`tiktok: ${video.join(", ")} only apply to video posts, and media: is images`);
393
+ if (t.cover_index !== undefined && images && t.cover_index >= images)
394
+ issues.push(`tiktok: cover_index ${t.cover_index} is past the last image (there are ${images}, counted from 0)`);
395
+ return issues;
159
396
  }
160
397
  export function draftIssues(draft, accounts, now = new Date()) {
161
398
  const issues = [];
162
- const { accounts: to, missing } = resolveAccounts(draft, accounts);
399
+ const { accounts: to, missing, ambiguous } = resolveAccounts(draft, accounts);
163
400
  if (missing.length)
164
401
  issues.push(`no connected account for ${missing.join(", ")}`);
165
- for (const a of to) {
166
- const limit = TEXT_LIMIT[a.platform.toLowerCase()];
402
+ for (const a of ambiguous) {
403
+ issues.push(a.platform
404
+ ? `${a.ref} matches ${a.choices.length} ${a.platform} accounts (${a.choices.join(", ")}): name the ones to post on, e.g. ${a.platform}:${a.choices[0]}, or write ${a.platform}:all to post on all ${a.choices.length}`
405
+ : `${a.ref} matches ${a.choices.length} accounts (${a.choices.join(", ")}): add the platform, e.g. ${a.choices[0]}`);
406
+ }
407
+ const platforms = [...new Set(to.map((a) => a.platform.toLowerCase()))];
408
+ for (const p of platforms) {
409
+ const limit = TEXT_LIMIT[p];
167
410
  if (limit && draft.text.length > limit)
168
- issues.push(`${a.platform}: ${draft.text.length}/${limit} characters`);
169
- if (NEEDS_MEDIA.has(a.platform.toLowerCase()) && !draft.media?.length)
170
- issues.push(`${a.platform} needs an image or video (media:)`);
411
+ issues.push(`${p}: ${draft.text.length}/${limit} characters`);
412
+ if (NEEDS_MEDIA.has(p) && !draft.media?.length)
413
+ issues.push(`${p} needs an image or video (media:)`);
171
414
  }
415
+ issues.push(...tiktokIssues(draft, platforms.includes("tiktok")));
172
416
  if (draft.when && !(new Date(draft.when) > now))
173
417
  issues.push(`when ${draft.when} is not in the future`);
174
418
  return issues;
175
419
  }
420
+ /** A draft's `tiktok:` block as the API's `extra.tiktok`. */
421
+ export function tiktokExtra(t) {
422
+ return compact({
423
+ privacyLevel: t.privacy ? PRIVACY[t.privacy] : undefined,
424
+ commercialContentType: t.disclosure ? DISCLOSURE[t.disclosure] : undefined,
425
+ draft: t.inbox_draft,
426
+ autoAddMusic: t.auto_music,
427
+ allowComment: t.comments,
428
+ title: t.title,
429
+ photoCoverIndex: t.cover_index,
430
+ videoCoverTimestampMs: t.cover_time_ms,
431
+ videoCoverImageUrl: t.cover_image_url,
432
+ });
433
+ }
176
434
  /** Create the post in Appeeky (it publishes now, or at `when`) and mark the draft sent. */
177
435
  export async function sendDraft(api, draft, accounts, now = new Date()) {
178
- const { accounts: to } = resolveAccounts(draft, accounts);
436
+ const { accounts: to, missing, ambiguous } = resolveAccounts(draft, accounts);
437
+ if (missing.length || ambiguous.length || !to.length)
438
+ throw new Error(draftIssues(draft, accounts, now).join("; ") || "no connected account to send to");
439
+ const tiktok = draft.tiktok && to.some((a) => a.platform.toLowerCase() === "tiktok") ? tiktokExtra(draft.tiktok) : {};
179
440
  const created = await api.post("/social/posts", {
180
441
  content: draft.text,
181
442
  account_ids: to.map((a) => a.id),
182
443
  ...(draft.when ? { scheduled_for: new Date(draft.when).toISOString() } : {}),
183
444
  ...(draft.media?.length ? { media_urls: draft.media } : {}),
445
+ ...(Object.keys(tiktok).length ? { extra: { tiktok } } : {}),
184
446
  });
185
447
  const { file, ...rest } = draft;
186
448
  await writeFile(file, YAML.stringify({ ...rest, status: "sent", postId: created.id, sentAt: now.toISOString() }, { lineWidth: 0 }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appeeky/spec",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Your app's store listing as a spec: lint it, check keyword coverage, diff it against the live store and push it to App Store Connect and Google Play.",
5
5
  "license": "FSL-1.1-MIT",
6
6
  "type": "module",
@@ -69,6 +69,7 @@
69
69
  "vendor:visibility": "node scripts/vendor-visibility-core.mjs"
70
70
  },
71
71
  "dependencies": {
72
+ "@clack/prompts": "1.8.1",
72
73
  "commander": "^13.1.0",
73
74
  "yaml": "^2.6.1",
74
75
  "zod": "^3.24.3"
@@ -79,8 +79,8 @@ npx @appeeky/spec experiment close <id> --value 3.1 --note "Hook B: 3.1 installs
79
79
 
80
80
  With accounts and creator personas set up in Appeeky (`APPEEKY_API_KEY`):
81
81
 
82
- - `social pull` writes the connected accounts, recent posts and how each did to `appeeky/social/` (read `summary.md`). `ugc pull` writes the personas (`ready` when they can make clips) and their clips to `appeeky/ugc/`.
83
- - To post: write `appeeky/social/drafts/<date>-<slug>.yaml` (`accounts`, `text`, `when`, `media`, `why`) and run `social check`. To make a video: write `appeeky/ugc/briefs/<date>-<slug>.yaml` (`persona`, `script`, `scene`, `caption`, `durationSec`, `aspectRatio`, `why`) and run `ugc generate --dry-run` for its cost.
82
+ - `social pull` writes the connected accounts, the posts made through Appeeky and in each platform's app, how each did, comments and followers to `appeeky/social/` (read `summary.md`). `ugc pull` writes the personas (`ready` when they can make clips) and their clips to `appeeky/ugc/`.
83
+ - To post: write `appeeky/social/drafts/<date>-<slug>.yaml` (`accounts`, `text`, `when`, `media`, `tiktok`, `why`) and run `social check`. Name accounts by handle (`tiktok:@handle`) when a platform has more than one. To make a video: write `appeeky/ugc/briefs/<date>-<slug>.yaml` (`persona`, `script`, `scene`, `caption`, `durationSec`, `aspectRatio`, `why`) and run `ugc generate --dry-run` for its cost.
84
84
  - Open a pull request. `social push` and `ugc generate` run after the merge (the push workflow does it). Never run them, or `ugc generate --yes`, unless the user asked: posts are public and clips use media credits.
85
85
  - Give each post or video its own smart link (`experiment add --link <channel>`) so `experiment close` can say what it brought.
86
86