ampost-cli 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amlabs Artur Muszyński (Ampost)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,215 @@
1
- # Temporary Holding Version
1
+ # Ampost CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `ampost` posts to Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky, Telegram and Discord
4
+ from your terminal, a shell script or an AI agent, through the [Ampost API](https://ampost.io/docs?ref=github).
5
+
6
+ - Publish now, schedule, add to a posting queue or save a draft, with local images and videos
7
+ - List, publish, retry, discard, unpublish and edit published posts; check or disconnect accounts; import a CSV of posts; read analytics; manage webhooks
8
+ - `--json` on every command, one JSON document on stdout, and documented exit codes
9
+ - Built on the [Node SDK](https://github.com/ampost-io/ampost-node), Node 18+
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npx ampost-cli --help # run it without installing
15
+ npm install -g ampost-cli # or install the `ampost` command
16
+ ```
17
+
18
+ ## Quick start
19
+
20
+ Create an API key in [Settings, API keys](https://ampost.io/app/settings/api-keys?ref=github) and
21
+ connect Bluesky and Threads in the [dashboard](https://ampost.io/app?ref=github). Then:
22
+
23
+ ```sh
24
+ ampost login # paste the key; it is checked, then saved
25
+ ampost accounts list
26
+ ampost post "Hello from the Ampost CLI 👋" -p bluesky,threads
27
+ ```
28
+
29
+ ```
30
+ Post: 0b6c1e8a-4f0e-4d39-9a51-2b6f0c7d9e21 (created)
31
+ Status: posting
32
+ Created: 2026-11-22 10:00 UTC
33
+ Text: Hello from the Ampost CLI 👋
34
+
35
+ PLATFORM STATUS URL OR ERROR ACCOUNT
36
+ bluesky publishing 5d2f...
37
+ threads publishing 9a1c...
38
+ ```
39
+
40
+ Add `--wait` to wait until every platform has published and print the links.
41
+
42
+ `ampost help` lists every command, and `ampost <command> --help` shows its options and examples.
43
+
44
+ ## Authentication
45
+
46
+ `ampost login` reads the key from a hidden prompt, or from stdin when stdin is not a terminal, checks
47
+ it against the API and saves it, readable by you only, in `config.json` in your config directory:
48
+
49
+ | OS | Directory |
50
+ | --- | --- |
51
+ | Linux | `$XDG_CONFIG_HOME/ampost` or `~/.config/ampost` |
52
+ | macOS | `~/Library/Application Support/ampost` |
53
+ | Windows | `%APPDATA%\ampost` |
54
+
55
+ `AMPOST_CONFIG_DIR` changes the directory. `AMPOST_API_KEY`, when set, is used instead of the saved key,
56
+ which is the simplest setup for CI and agents. `ampost status` shows which key is in use and
57
+ `ampost logout` deletes the saved one. There is no `--api-key` flag, so keys stay out of shell history.
58
+
59
+ A key has [scopes](https://ampost.io/docs?ref=github#scopes): a Read only key can list but not post.
60
+
61
+ ## Posting
62
+
63
+ ```sh
64
+ # Publish now (the default)
65
+ ampost post "We just shipped dark mode" -p bluesky,threads
66
+
67
+ # Schedule (ISO 8601 with a time; Z or an offset, else your machine's time zone)
68
+ ampost post "Webinar starts in one hour" -p threads --schedule 2026-12-01T09:00:00Z
69
+
70
+ # Next free slot of the platform set's posting queue, or a draft to finish in the dashboard
71
+ ampost post "Tip of the week" -p bluesky --queue
72
+ ampost post "Draft idea" -p threads --draft
73
+
74
+ # Local files are uploaded first; https URLs are passed as they are
75
+ ampost post "New office" -p bluesky,threads -m ./office.jpg -m ./team.jpg --alt-text "Our office" --alt-text "The team"
76
+
77
+ # A link and a first comment (a reply on Bluesky, Threads and X)
78
+ ampost post "Our pricing changed" -p bluesky --link https://example.com/pricing --first-comment "Questions? Ask below"
79
+
80
+ # Long text from a file or stdin
81
+ ampost post --text-file release-notes.md -p threads
82
+ git log -1 --format=%s | ampost post - -p bluesky
83
+
84
+ # Check without creating anything (local media is still uploaded, to check it)
85
+ ampost post "Does this fit?" -p bluesky,threads --dry-run
86
+
87
+ # Wait until every platform has finished, and fail if any did not publish
88
+ ampost post "Launch day" -p bluesky,threads --wait
89
+ ```
90
+
91
+ `-p` takes `instagram`, `facebook`, `threads`, `twitter` (or `x`), `youtube`, `pinterest`, `bluesky`,
92
+ `telegram`, `discord`, `linkedin` and `tiktok`, from your default platform set. Use `--platform-set <id>`
93
+ (repeatable) for other sets; `ampost platform-sets list` shows them.
94
+
95
+ ## Managing posts
96
+
97
+ ```sh
98
+ ampost posts list --status failed
99
+ ampost posts list --platform threads --search "launch" --all
100
+ ampost posts get <post-id>
101
+ ampost posts publish <post-id> --wait # publish a draft or scheduled post now
102
+ ampost posts retry <post-id> --wait # retry the failed platforms
103
+ ampost posts delete <post-id> # discard a draft, scheduled, queued or failed post
104
+ ampost posts unpublish <post-id> # delete a published post from the platforms
105
+ ampost posts edit-published <post-id> --text "Fixed" # replace a published post's text on the platforms
106
+ ampost import-csv week.csv --dry-run && ampost import-csv week.csv --idempotency-key week-48
107
+ ampost accounts get <account-id> # can it post, and why not
108
+ ampost accounts disconnect <account-id> # revoke Ampost's access; reconnect in the dashboard
109
+ ```
110
+
111
+ Lists show 20 items; use `--limit`, `--offset` or `--all`. The CSV columns are those of the
112
+ dashboard's export ([reference](https://ampost.io/docs?ref=github#posts)).
113
+
114
+ ## Analytics and webhooks
115
+
116
+ ```sh
117
+ ampost analytics --from 2026-11-01 --to 2026-11-30
118
+ ampost analytics posts --platform bluesky
119
+ ampost analytics followers
120
+
121
+ ampost webhooks create --url https://example.com/hooks/ampost -e post.published,post.failed
122
+ ampost webhooks list
123
+ ampost webhooks test <webhook-id>
124
+ ampost webhooks deliveries <webhook-id>
125
+ ampost webhooks update <webhook-id> --disable
126
+ ```
127
+
128
+ `webhooks create` prints the signing secret once. Payloads and signature checks are in the
129
+ [webhook docs](https://ampost.io/docs?ref=github#webhooks).
130
+
131
+ ## Scripts and agents
132
+
133
+ With `--json` (anywhere on the command line) every command prints exactly one JSON document on stdout:
134
+ the API's response, or an error. Progress goes to stderr, and no command but `ampost login` on a
135
+ terminal asks for input.
136
+
137
+ ```json
138
+ { "error": { "code": "VALIDATION_FAILED", "message": "...", "status": 400, "details": { ... }, "requestId": "req_...", "exitCode": 6 } }
139
+ ```
140
+
141
+ The exit code tells what happened without parsing anything:
142
+
143
+ | Code | Meaning |
144
+ | --- | --- |
145
+ | 0 | Done |
146
+ | 1 | Unexpected error, or `--wait` gave up while the post was still publishing |
147
+ | 2 | Wrong command, option or argument; nothing was sent |
148
+ | 3 | No API key, or the key was refused (401) |
149
+ | 4 | The key lacks a scope or platform set, or the plan lacks the feature (403) |
150
+ | 5 | Not found (404) |
151
+ | 6 | Invalid request or content (400, 413, 422), a failed `--dry-run`, or a CSV row with errors |
152
+ | 7 | The post's state does not allow it (409), for example deleting a published post |
153
+ | 8 | Rate limit or plan quota (429), after automatic retries |
154
+ | 9 | Ampost or the network is unavailable (5xx, timeout); retry later |
155
+ | 10 | `--wait`: the post failed or published only partly. `posts unpublish`: an account still has it (Instagram and TikTok have no delete API, or the platform refused). `posts edit-published`: an account kept its old text (Instagram, Threads, TikTok, Bluesky and X have no edit API, or the platform refused) |
156
+
157
+ A shell script that posts the day's release notes and stops on any failure:
158
+
159
+ ```sh
160
+ #!/bin/sh
161
+ set -eu
162
+ export AMPOST_API_KEY="$AMPOST_KEY_FROM_YOUR_SECRET_STORE"
163
+
164
+ post=$(ampost post --text-file notes.md -p bluesky,threads --wait --json \
165
+ --idempotency-key "notes-$(date +%F)")
166
+ echo "$post" | jq -r '.platformPosts[] | "\(.platform): \(.publishedUrl)"'
167
+ ```
168
+
169
+ `--idempotency-key` makes a rerun of the same command safe: the API returns the first post instead
170
+ of creating a second one. Without it, each run creates a new post.
171
+
172
+ Branching on the outcome:
173
+
174
+ ```sh
175
+ ampost post "$TEXT" -p bluesky --dry-run --json > check.json
176
+ case $? in
177
+ 0) ampost post "$TEXT" -p bluesky ;;
178
+ 6) jq -r '(.errors[], .targets[].errors[]) | .message' check.json ;; # post-wide, then per platform
179
+ 3) echo "Set AMPOST_API_KEY" >&2 ;;
180
+ esac
181
+ ```
182
+
183
+ For AI agents (Claude Code, Codex, Cursor and others), give the agent a key in `AMPOST_API_KEY` and
184
+ tell it to use `ampost <command> --json` and `ampost <command> --help`. The help text has examples,
185
+ and errors name the field that failed. Agents that speak MCP can use the hosted
186
+ [MCP server](https://ampost.io/docs/mcp?ref=github) instead.
187
+
188
+ ## Environment
189
+
190
+ | Variable | Use |
191
+ | --- | --- |
192
+ | `AMPOST_API_KEY` | API key; overrides the one saved by `ampost login` |
193
+ | `AMPOST_BASE_URL` | API host, default `https://api.ampost.io` |
194
+ | `AMPOST_CONFIG_DIR` | Where `ampost login` saves the key |
195
+
196
+ ## Development
197
+
198
+ ```sh
199
+ (cd ../ampost-node && npm ci && npm run build) # while the SDK is a local dependency
200
+ npm ci
201
+ npm run typecheck && npm test && npm run build
202
+ AMPOST_API_KEY=amp_... npm run test:smoke # reads and validates only
203
+ node dist/bin.js --help
204
+ ```
205
+
206
+ ## Links
207
+
208
+ - [API docs](https://ampost.io/docs?ref=github) and [llms.txt](https://ampost.io/llms.txt?ref=github)
209
+ - [Node SDK](https://github.com/ampost-io/ampost-node) and [Python SDK](https://github.com/ampost-io/ampost-python)
210
+ - [MCP server](https://ampost.io/docs/mcp?ref=github)
211
+ - [Pricing](https://ampost.io/pricing?ref=github)
212
+
213
+ ## License
214
+
215
+ MIT
package/dist/bin.js ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "./cli.js";
3
+ import { nodeIo } from "./io.js";
4
+ const code = await run(process.argv.slice(2), {
5
+ env: process.env,
6
+ io: nodeIo(),
7
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
8
+ });
9
+ process.exitCode = code;
package/dist/cli.js ADDED
@@ -0,0 +1,214 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { parseArgs } from "node:util";
3
+ import { Ampost, VERSION as SDK_VERSION } from "ampost";
4
+ import { COMMANDS, GROUPS } from "./commands/index.js";
5
+ import { resolveCredentials } from "./config.js";
6
+ import { CliError, errorJson, errorText, EXIT, UsageError } from "./errors.js";
7
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
8
+ const GLOBAL_OPTIONS = {
9
+ json: { type: "boolean", help: "Print JSON: the API's response, or { \"error\": {...} } on failure. Always one document on stdout" },
10
+ help: { type: "boolean", short: "h", help: "Show help" },
11
+ };
12
+ /** Runs one command line and returns the exit code. Never throws. */
13
+ export async function run(argv, deps) {
14
+ let json = argv.includes("--json");
15
+ try {
16
+ const { command, rest, help, version } = route(argv);
17
+ if (version)
18
+ return print(deps, json, { version: VERSION, sdkVersion: SDK_VERSION }, VERSION);
19
+ if (!command)
20
+ return print(deps, json, null, help ?? mainHelp(), EXIT.OK);
21
+ const input = parse(command, rest);
22
+ json = input.values.json === true;
23
+ if (input.values.help)
24
+ return print(deps, false, null, commandHelp(command), EXIT.OK);
25
+ const output = await command.run(context(deps, json), input);
26
+ return print(deps, json, output.data, output.text, output.exitCode ?? EXIT.OK);
27
+ }
28
+ catch (error) {
29
+ const code = exitCodeOf(error);
30
+ if (json)
31
+ deps.io.stdout(`${JSON.stringify(errorJson(error), null, 2)}\n`);
32
+ else
33
+ deps.io.stderr(`${errorText(error)}\n`);
34
+ return code;
35
+ }
36
+ }
37
+ function exitCodeOf(error) {
38
+ return errorJson(error).error.exitCode;
39
+ }
40
+ function print(deps, json, data, text, exitCode = EXIT.OK) {
41
+ if (json)
42
+ deps.io.stdout(`${JSON.stringify(data, null, 2)}\n`);
43
+ else if (text)
44
+ deps.io.stdout(text.endsWith("\n") ? text : `${text}\n`);
45
+ return exitCode;
46
+ }
47
+ function context(deps, json) {
48
+ let client;
49
+ return {
50
+ deps,
51
+ json,
52
+ async client() {
53
+ if (client)
54
+ return client;
55
+ const credentials = await resolveCredentials(deps.env);
56
+ if (!credentials) {
57
+ throw new CliError("No API key. Run `ampost login`, or set AMPOST_API_KEY. Create a key at https://ampost.io/app/settings/api-keys?ref=cli", EXIT.AUTH, "MISSING_API_KEY");
58
+ }
59
+ client = new Ampost({
60
+ apiKey: credentials.apiKey,
61
+ ...(credentials.baseUrl && { baseUrl: credentials.baseUrl }),
62
+ ...(deps.fetch && { fetch: deps.fetch }),
63
+ defaultHeaders: { "User-Agent": `ampost-cli/${VERSION} ampost-node/${SDK_VERSION}` },
64
+ });
65
+ return client;
66
+ },
67
+ progress(message) {
68
+ if (!json)
69
+ deps.io.stderr(`${message}\n`);
70
+ },
71
+ };
72
+ }
73
+ /**
74
+ * Finds the command. `--json`, `--help` and `--version` may come before it; the command's own options come
75
+ * after it. Returns help text instead of a command for `ampost`, `ampost help ...` and `ampost <group>`.
76
+ */
77
+ function route(argv) {
78
+ let i = 0;
79
+ for (; i < argv.length && argv[i].startsWith("-"); i++) {
80
+ const flag = argv[i];
81
+ if (flag === "--version" || flag === "-v")
82
+ return { rest: [], version: true };
83
+ if (!["--json", "--help", "-h"].includes(flag))
84
+ throw new UsageError(`Unknown option ${flag} before the command`);
85
+ }
86
+ const words = argv.slice(i);
87
+ if (words[0] === "help") {
88
+ const target = words.slice(1).filter((word) => !word.startsWith("-"));
89
+ if (target.length === 0)
90
+ return { rest: [], help: mainHelp() };
91
+ return helpFor(target);
92
+ }
93
+ if (words.length === 0)
94
+ return { rest: [], help: mainHelp() };
95
+ if (argv.slice(0, i).some((flag) => flag === "--help" || flag === "-h") && !match(words))
96
+ return helpFor(words);
97
+ const found = match(words);
98
+ if (!found) {
99
+ if (GROUPS[words[0]]) {
100
+ if (words.length === 1 || words[1].startsWith("-"))
101
+ return { rest: [], help: groupHelp(words[0]) };
102
+ throw new UsageError(`Unknown command \`ampost ${words[0]} ${words[1]}\`. ${groupCommands(words[0])}`);
103
+ }
104
+ throw new UsageError(`Unknown command \`${words[0]}\``);
105
+ }
106
+ // Global options given before the command are parsed with the command's own.
107
+ const rest = [...argv.slice(0, i), ...words.slice(found.length)];
108
+ return { command: found.command, rest };
109
+ }
110
+ function match(words) {
111
+ for (const length of [2, 1]) {
112
+ const name = words.slice(0, length).join(" ");
113
+ const command = COMMANDS.find((c) => c.name === name || c.aliases?.includes(name));
114
+ if (command && words.length >= length)
115
+ return { command, length };
116
+ }
117
+ return undefined;
118
+ }
119
+ function helpFor(target) {
120
+ const found = match(target);
121
+ if (found)
122
+ return { rest: [], help: commandHelp(found.command) };
123
+ if (GROUPS[target[0]])
124
+ return { rest: [], help: groupHelp(target[0]) };
125
+ throw new UsageError(`Unknown command \`${target.join(" ")}\``);
126
+ }
127
+ function parse(command, args) {
128
+ const options = { ...command.options, ...GLOBAL_OPTIONS };
129
+ let parsed;
130
+ try {
131
+ parsed = parseArgs({
132
+ args,
133
+ options: Object.fromEntries(Object.entries(options).map(([name, spec]) => [
134
+ name,
135
+ { type: spec.type, ...(spec.multiple && { multiple: true }), ...(spec.short && { short: spec.short }) },
136
+ ])),
137
+ allowPositionals: true,
138
+ strict: true,
139
+ });
140
+ }
141
+ catch (error) {
142
+ throw new UsageError(`${error.message.replace(/\. To specify a positional argument.*$/s, "")} (ampost ${command.name} --help)`);
143
+ }
144
+ const { positionals } = parsed;
145
+ const values = parsed.values;
146
+ if (values.help)
147
+ return { positionals, values };
148
+ const { min, max } = command.positionals ?? { min: 0, max: 0 };
149
+ if (positionals.length < min)
150
+ throw new UsageError(`Missing ${command.args ?? "argument"}: ampost ${command.name} ${command.args ?? ""}`.trim());
151
+ if (positionals.length > max) {
152
+ throw new UsageError(max === 0
153
+ ? `\`ampost ${command.name}\` takes no arguments, got ${JSON.stringify(positionals[0])}`
154
+ : `Too many arguments for \`ampost ${command.name}\`: ${JSON.stringify(positionals.slice(max))}. Quote text with spaces`);
155
+ }
156
+ return { positionals, values };
157
+ }
158
+ export function mainHelp() {
159
+ const width = Math.max(...COMMANDS.map((c) => c.name.length)) + 2;
160
+ return [
161
+ "ampost: publish and schedule posts on Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky,",
162
+ "Telegram and Discord from your shell. Docs: https://ampost.io/docs?ref=cli",
163
+ "",
164
+ "Usage: ampost <command> [options] [--json]",
165
+ "",
166
+ "Commands:",
167
+ ...COMMANDS.map((c) => ` ${c.name.padEnd(width)}${c.summary}`),
168
+ "",
169
+ "Global options:",
170
+ " --json Print JSON on stdout (errors too, as { \"error\": {...} }); for scripts and agents",
171
+ " -h, --help Help for any command: ampost post --help",
172
+ " -v, --version Print the version",
173
+ "",
174
+ "Authentication: `ampost login`, or the AMPOST_API_KEY environment variable (it wins over the login).",
175
+ "",
176
+ exitCodesHelp(),
177
+ ].join("\n");
178
+ }
179
+ export function exitCodesHelp() {
180
+ return [
181
+ "Exit codes:",
182
+ " 0 ok 1 error 2 usage 3 no or bad API key 4 forbidden (scope, plan) 5 not found",
183
+ " 6 invalid request, failed dry run or CSV rows 7 conflict 8 rate limited 9 API unavailable",
184
+ " 10 post failed or partial (--wait), or a platform kept the post (unpublish) or its text (edit-published)",
185
+ ].join("\n");
186
+ }
187
+ function groupCommands(group) {
188
+ return `Commands: ${COMMANDS.filter((c) => c.name.startsWith(`${group} `)).map((c) => c.name.split(" ")[1]).join(", ")}`;
189
+ }
190
+ function groupHelp(group) {
191
+ const commands = COMMANDS.filter((c) => c.name === group || c.name.startsWith(`${group} `));
192
+ const width = Math.max(...commands.map((c) => c.name.length)) + 2;
193
+ return [
194
+ `ampost ${group}: ${GROUPS[group]}`,
195
+ "",
196
+ ...commands.map((c) => ` ampost ${c.name.padEnd(width)}${c.summary}`),
197
+ "",
198
+ `Help for one: ampost ${commands[0].name} --help`,
199
+ ].join("\n");
200
+ }
201
+ export function commandHelp(command) {
202
+ const options = Object.entries({ ...command.options, json: GLOBAL_OPTIONS.json });
203
+ const label = ([name, spec]) => `${spec.short ? `-${spec.short}, ` : " "}--${name}${spec.type === "string" ? ` ${spec.value ?? "VALUE"}` : ""}`;
204
+ const width = Math.max(...options.map((o) => label(o).length)) + 2;
205
+ return [
206
+ `ampost ${command.name}: ${command.summary}`,
207
+ "",
208
+ `Usage: ampost ${command.name}${command.args ? ` ${command.args}` : ""}${options.length > 1 ? " [options]" : ""}`,
209
+ "",
210
+ "Options:",
211
+ ...options.map((o) => ` ${label(o).padEnd(width)}${o[1].help}${o[1].multiple ? " (repeatable)" : ""}`),
212
+ ...(command.help ? ["", command.help.trimEnd()] : []),
213
+ ].join("\n");
214
+ }
@@ -0,0 +1,92 @@
1
+ import { fields, pageNote, table } from "../format.js";
2
+ import { fetchList, id, LIST_OPTIONS, oneOf, pageQuery, platform, string } from "./shared.js";
3
+ function accountText(a, heading) {
4
+ const head = fields([
5
+ ["Account", heading ? `${a.id} (${heading})` : a.id],
6
+ ["Platform", a.platform],
7
+ ["Username", a.username ?? undefined],
8
+ ["Status", a.status],
9
+ ["Token", a.tokenHealth],
10
+ ["Platform set", a.platformSetId ?? undefined],
11
+ ["Can post", a.health.canPost ? "yes" : "no"],
12
+ ["Reconnect", a.health.needsReconnect ? "needed: https://ampost.io/app?ref=cli" : undefined],
13
+ ]);
14
+ const issues = a.health.issues.map((i) => ` ${i.severity}: ${i.message} (${i.code})`);
15
+ return issues.length ? `${head}\n\nIssues:\n${issues.join("\n")}` : head;
16
+ }
17
+ export const accountsGet = {
18
+ name: "accounts get",
19
+ summary: "Show an account and whether it can post",
20
+ args: "<account-id>",
21
+ positionals: { min: 1, max: 1 },
22
+ async run(ctx, input) {
23
+ const client = await ctx.client();
24
+ const a = await client.accounts.get(id(input.positionals[0], "The account id"));
25
+ return { data: a, text: accountText(a) };
26
+ },
27
+ };
28
+ export const accountsDisconnect = {
29
+ name: "accounts disconnect",
30
+ summary: "Disconnect an account: revoke Ampost's access and delete its tokens",
31
+ args: "<account-id>",
32
+ positionals: { min: 1, max: 1 },
33
+ help: `The account becomes \`revoked\` and its scheduled posts will fail. It keeps its id: reconnect it in
34
+ the dashboard. Ampost revokes its access at the platform where the platform allows it; Instagram and
35
+ Threads have no revoke API, so remove Ampost in their settings (the output says where).
36
+
37
+ Example:
38
+ ampost accounts disconnect <account-id>`,
39
+ async run(ctx, input) {
40
+ const client = await ctx.client();
41
+ const a = await client.accounts.disconnect(id(input.positionals[0], "The account id"));
42
+ const revoke = a.providerRevoked
43
+ ? "The platform confirmed the revoke."
44
+ : `The platform did not confirm a revoke.${a.providerAccessSettings ? ` Remove Ampost at ${a.providerAccessSettings}` : ""}`;
45
+ return { data: a, text: `${accountText(a, "disconnected")}\n\n${revoke}` };
46
+ },
47
+ };
48
+ export const accountsList = {
49
+ name: "accounts list",
50
+ summary: "List connected social accounts",
51
+ options: {
52
+ platform: { type: "string", value: "NAME", help: "Only this platform (bluesky, threads, instagram, ...)" },
53
+ "platform-set": { type: "string", value: "ID", help: "Only accounts in this platform set" },
54
+ status: { type: "string", value: "STATUS", help: "active (default), revoked or all" },
55
+ ...LIST_OPTIONS,
56
+ },
57
+ help: "Connect accounts in the dashboard: https://ampost.io/app?ref=cli",
58
+ async run(ctx, input) {
59
+ const setId = string(input, "platform-set");
60
+ const query = {
61
+ ...pageQuery(input),
62
+ platform: platform(input),
63
+ status: oneOf(input, "status", ["active", "revoked", "all"]),
64
+ platformSetId: setId === undefined ? undefined : id(setId, "--platform-set"),
65
+ };
66
+ const client = await ctx.client();
67
+ const result = await fetchList(client.accounts.list(query), input);
68
+ if (result.data.length === 0)
69
+ return { data: result, text: "No accounts. Connect one at https://ampost.io/app?ref=cli" };
70
+ const rows = result.data.map((a) => [a.id, a.platform, a.username, a.status, a.tokenHealth, a.platformSetId]);
71
+ return {
72
+ data: result,
73
+ text: `${table(["id", "platform", "username", "status", "token", "platform set"], rows)}\n\n${pageNote(result.pagination, result.data.length, "account")}`,
74
+ };
75
+ },
76
+ };
77
+ export const platformSetsList = {
78
+ name: "platform-sets list",
79
+ summary: "List platform sets (one account per platform each; use with --platform-set)",
80
+ options: { ...LIST_OPTIONS },
81
+ async run(ctx, input) {
82
+ const client = await ctx.client();
83
+ const result = await fetchList(client.platformSets.list(pageQuery(input)), input);
84
+ if (result.data.length === 0)
85
+ return { data: result, text: "No platform sets." };
86
+ const rows = result.data.map((s) => [s.id, s.name, s.isDefault ? "yes" : "", s.accountCount]);
87
+ return {
88
+ data: result,
89
+ text: `${table(["id", "name", "default", "accounts"], rows)}\n\n${pageNote(result.pagination, result.data.length, "platform set")}`,
90
+ };
91
+ },
92
+ };
@@ -0,0 +1,110 @@
1
+ import { UsageError } from "../errors.js";
2
+ import { date, number, oneLine, pageNote, signed, table } from "../format.js";
3
+ import { day, fetchList, id, LIST_OPTIONS, pageQuery, platform, string } from "./shared.js";
4
+ const FILTERS = {
5
+ platform: { type: "string", value: "NAME", help: "Only accounts on this platform" },
6
+ "platform-set": { type: "string", value: "ID", help: "Only accounts in this platform set" },
7
+ account: { type: "string", value: "ID", help: "Only this account" },
8
+ };
9
+ const RANGE = {
10
+ from: { type: "string", value: "YYYY-MM-DD", help: "First day, UTC (default: 29 days before --to; at most 90 days)" },
11
+ to: { type: "string", value: "YYYY-MM-DD", help: "Last day, UTC, included (default: today)" },
12
+ };
13
+ function filters(input) {
14
+ const setId = string(input, "platform-set");
15
+ const accountId = string(input, "account");
16
+ return {
17
+ platform: platform(input),
18
+ platformSetId: setId === undefined ? undefined : id(setId, "--platform-set"),
19
+ accountId: accountId === undefined ? undefined : id(accountId, "--account"),
20
+ };
21
+ }
22
+ function range(input) {
23
+ const from = day(input, "from");
24
+ const to = day(input, "to");
25
+ if (from && to && from > to)
26
+ throw new UsageError("--from is after --to");
27
+ return { from, to };
28
+ }
29
+ function metricCells(m) {
30
+ return [number(m.views), number(m.likes), number(m.comments), number(m.shares)];
31
+ }
32
+ export const analyticsOverview = {
33
+ name: "analytics overview",
34
+ aliases: ["analytics"],
35
+ summary: "Totals per account for a date range: posts, followers, views, likes, ...",
36
+ options: { ...RANGE, ...FILTERS },
37
+ help: `Examples:
38
+ ampost analytics
39
+ ampost analytics --from 2026-11-01 --to 2026-11-30 --platform instagram
40
+ ampost analytics --json | jq '.totals.metrics'
41
+
42
+ Metrics a platform does not report are shown as - (null in JSON). Discord has no analytics.`,
43
+ async run(ctx, input) {
44
+ const client = await ctx.client();
45
+ const result = await client.analytics.getOverview({ ...range(input), ...filters(input) });
46
+ const t = result.totals;
47
+ const lines = [
48
+ `${result.from} to ${result.to}: ${number(t.posts)} posts, ${number(t.followers)} followers (${signed(t.followersChange)}), ` +
49
+ `${number(t.metrics.views)} views, ${number(t.metrics.likes)} likes, ${number(t.metrics.comments)} comments`,
50
+ ];
51
+ if (result.accounts.length) {
52
+ const rows = result.accounts.map((a) => [
53
+ a.platform,
54
+ a.username,
55
+ number(a.posts),
56
+ number(a.followers),
57
+ signed(a.followersChange),
58
+ ...metricCells(a.metrics),
59
+ a.syncState,
60
+ ]);
61
+ lines.push("", table(["platform", "account", "posts", "followers", "change", "views", "likes", "comments", "shares", "sync"], rows));
62
+ }
63
+ if (result.unavailableAccounts.length) {
64
+ lines.push("", `No analytics for: ${result.unavailableAccounts.map((a) => `${a.platform} (${a.reason})`).join(", ")}`);
65
+ }
66
+ return { data: result, text: lines.join("\n") };
67
+ },
68
+ };
69
+ export const analyticsPosts = {
70
+ name: "analytics posts",
71
+ summary: "Metrics of each published post, per platform",
72
+ options: {
73
+ post: { type: "string", value: "ID", help: "Only this post" },
74
+ ...FILTERS,
75
+ ...LIST_OPTIONS,
76
+ },
77
+ async run(ctx, input) {
78
+ const postId = string(input, "post");
79
+ const client = await ctx.client();
80
+ const query = { ...pageQuery(input), ...filters(input), postId: postId === undefined ? undefined : id(postId, "--post") };
81
+ const result = await fetchList(client.analytics.listPosts(query), input);
82
+ if (result.data.length === 0)
83
+ return { data: result, text: "No published posts with analytics." };
84
+ const rows = result.data.flatMap((p) => p.platformPosts.map((pp) => [p.postId, pp.platform, date(pp.publishedAt), ...metricCells(pp.metrics), oneLine(p.text, 30)]));
85
+ return {
86
+ data: result,
87
+ text: `${table(["post", "platform", "published", "views", "likes", "comments", "shares", "text"], rows)}\n\n${pageNote(result.pagination, result.data.length, "post")}`,
88
+ };
89
+ },
90
+ };
91
+ export const analyticsFollowers = {
92
+ name: "analytics followers",
93
+ summary: "Follower counts per account, with daily history in --json",
94
+ options: { ...RANGE, ...FILTERS, ...LIST_OPTIONS },
95
+ async run(ctx, input) {
96
+ const client = await ctx.client();
97
+ const result = await fetchList(client.analytics.listFollowers({ ...pageQuery(input), ...range(input), ...filters(input) }), input);
98
+ if (result.data.length === 0)
99
+ return { data: result, text: "No accounts with follower counts." };
100
+ const rows = result.data.map((a) => {
101
+ const first = a.history[0]?.followers;
102
+ const change = first === undefined || first === null || a.followers === null ? null : a.followers - first;
103
+ return [a.platform, a.username, number(a.followers), signed(change), date(a.syncedAt)];
104
+ });
105
+ return {
106
+ data: result,
107
+ text: `${table(["platform", "account", "followers", "change in range", "synced"], rows)}\n\n${pageNote(result.pagination, result.data.length, "account")}`,
108
+ };
109
+ },
110
+ };