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 +21 -0
- package/README.md +214 -2
- package/dist/bin.js +9 -0
- package/dist/cli.js +214 -0
- package/dist/commands/accounts.js +92 -0
- package/dist/commands/analytics.js +110 -0
- package/dist/commands/auth.js +106 -0
- package/dist/commands/import-csv.js +67 -0
- package/dist/commands/index.js +43 -0
- package/dist/commands/posts.js +432 -0
- package/dist/commands/shared.js +104 -0
- package/dist/commands/webhooks.js +201 -0
- package/dist/config.js +76 -0
- package/dist/errors.js +144 -0
- package/dist/format.js +78 -0
- package/dist/io.js +50 -0
- package/package.json +55 -4
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { UsageError } from "../errors.js";
|
|
2
|
+
export const PLATFORMS = [
|
|
3
|
+
"instagram",
|
|
4
|
+
"facebook",
|
|
5
|
+
"linkedin",
|
|
6
|
+
"tiktok",
|
|
7
|
+
"threads",
|
|
8
|
+
"twitter",
|
|
9
|
+
"discord",
|
|
10
|
+
"telegram",
|
|
11
|
+
"bluesky",
|
|
12
|
+
"youtube",
|
|
13
|
+
"pinterest",
|
|
14
|
+
];
|
|
15
|
+
export function string(input, name) {
|
|
16
|
+
const value = input.values[name];
|
|
17
|
+
return typeof value === "string" ? value : undefined;
|
|
18
|
+
}
|
|
19
|
+
export function flag(input, name) {
|
|
20
|
+
return input.values[name] === true;
|
|
21
|
+
}
|
|
22
|
+
/** A repeatable option whose values may also be comma-separated: `-p bluesky,threads -p x`. */
|
|
23
|
+
export function list(input, name) {
|
|
24
|
+
const value = input.values[name];
|
|
25
|
+
const values = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
|
|
26
|
+
return values.flatMap((v) => v.split(",")).map((v) => v.trim()).filter(Boolean);
|
|
27
|
+
}
|
|
28
|
+
/** A repeatable option taken as is (text may contain commas). */
|
|
29
|
+
export function repeated(input, name) {
|
|
30
|
+
const value = input.values[name];
|
|
31
|
+
return Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
|
|
32
|
+
}
|
|
33
|
+
export function integer(input, name, min, max) {
|
|
34
|
+
const value = string(input, name);
|
|
35
|
+
if (value === undefined)
|
|
36
|
+
return undefined;
|
|
37
|
+
if (!/^\d+$/.test(value) || Number(value) < min || Number(value) > max) {
|
|
38
|
+
throw new UsageError(`--${name} must be a whole number from ${min} to ${max}, got ${JSON.stringify(value)}`);
|
|
39
|
+
}
|
|
40
|
+
return Number(value);
|
|
41
|
+
}
|
|
42
|
+
export function platform(input, name = "platform") {
|
|
43
|
+
const value = string(input, name);
|
|
44
|
+
if (value === undefined)
|
|
45
|
+
return undefined;
|
|
46
|
+
return checkPlatform(value);
|
|
47
|
+
}
|
|
48
|
+
export function checkPlatform(value) {
|
|
49
|
+
const normalized = value.toLowerCase() === "x" ? "twitter" : value.toLowerCase();
|
|
50
|
+
if (!PLATFORMS.includes(normalized)) {
|
|
51
|
+
throw new UsageError(`Unknown platform ${JSON.stringify(value)}. Platforms: ${PLATFORMS.join(", ")}`);
|
|
52
|
+
}
|
|
53
|
+
return normalized;
|
|
54
|
+
}
|
|
55
|
+
/** `YYYY-MM-DD`, as the analytics endpoints take it. */
|
|
56
|
+
export function day(input, name) {
|
|
57
|
+
const value = string(input, name);
|
|
58
|
+
if (value === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(`${value}T00:00:00Z`))) {
|
|
61
|
+
throw new UsageError(`--${name} must be a date as YYYY-MM-DD, got ${JSON.stringify(value)}`);
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
export function oneOf(input, name, allowed) {
|
|
66
|
+
const value = string(input, name);
|
|
67
|
+
if (value === undefined)
|
|
68
|
+
return undefined;
|
|
69
|
+
if (!allowed.includes(value)) {
|
|
70
|
+
throw new UsageError(`--${name} must be one of ${allowed.join(", ")}, got ${JSON.stringify(value)}`);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
export const LIST_OPTIONS = {
|
|
75
|
+
limit: { type: "string", value: "N", help: "Items per page, 1-100 (default 20)" },
|
|
76
|
+
offset: { type: "string", value: "N", help: "Items to skip (default 0)" },
|
|
77
|
+
all: { type: "boolean", help: "Fetch every page" },
|
|
78
|
+
};
|
|
79
|
+
/** `limit`/`offset` for the query; with `--all`, pages of 100. */
|
|
80
|
+
export function pageQuery(input) {
|
|
81
|
+
const all = flag(input, "all");
|
|
82
|
+
const limit = integer(input, "limit", 1, 100);
|
|
83
|
+
const offset = integer(input, "offset", 0, Number.MAX_SAFE_INTEGER);
|
|
84
|
+
if (all && offset !== undefined)
|
|
85
|
+
throw new UsageError("--all starts at the first item: leave out --offset");
|
|
86
|
+
return { ...((limit !== undefined || all) && { limit: limit ?? 100 }), ...(offset !== undefined && { offset }) };
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* One page as the API returns it, or with `--all` every item in the same shape:
|
|
90
|
+
* `{ data, pagination: { limit, offset: 0, total, hasMore: false } }`.
|
|
91
|
+
*/
|
|
92
|
+
export async function fetchList(page, input) {
|
|
93
|
+
if (!flag(input, "all"))
|
|
94
|
+
return await page;
|
|
95
|
+
const data = await page.toArray();
|
|
96
|
+
return { data, pagination: { limit: data.length, offset: 0, total: data.length, hasMore: false } };
|
|
97
|
+
}
|
|
98
|
+
export const ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
99
|
+
/** Ids are UUIDs; catching a typo here gives a clearer message than the API's 400. */
|
|
100
|
+
export function id(value, what) {
|
|
101
|
+
if (!value || !ID_PATTERN.test(value))
|
|
102
|
+
throw new UsageError(`${what} must be a UUID, got ${JSON.stringify(value ?? "")}`);
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { UsageError } from "../errors.js";
|
|
2
|
+
import { date, fields, pageNote, table } from "../format.js";
|
|
3
|
+
import { fetchList, flag, id, LIST_OPTIONS, list, pageQuery, string } from "./shared.js";
|
|
4
|
+
export const WEBHOOK_EVENTS = [
|
|
5
|
+
"post.scheduled",
|
|
6
|
+
"post.unscheduled",
|
|
7
|
+
"post.discarded",
|
|
8
|
+
"post.published",
|
|
9
|
+
"post.partial",
|
|
10
|
+
"post.failed",
|
|
11
|
+
"post.platform.published",
|
|
12
|
+
"post.platform.failed",
|
|
13
|
+
"post.platform.deleted",
|
|
14
|
+
"post.platform.edited",
|
|
15
|
+
"account.connected",
|
|
16
|
+
"account.disconnected",
|
|
17
|
+
"account.needs_reconnect",
|
|
18
|
+
"analytics.synced",
|
|
19
|
+
];
|
|
20
|
+
function events(input) {
|
|
21
|
+
const values = list(input, "events");
|
|
22
|
+
if (values.length === 0)
|
|
23
|
+
return undefined;
|
|
24
|
+
const expanded = values.flatMap((value) => {
|
|
25
|
+
// `post.*` takes every post event, `*` every event.
|
|
26
|
+
if (value === "*")
|
|
27
|
+
return [...WEBHOOK_EVENTS];
|
|
28
|
+
if (value.endsWith(".*")) {
|
|
29
|
+
const prefix = value.slice(0, -1);
|
|
30
|
+
const matched = WEBHOOK_EVENTS.filter((e) => e.startsWith(prefix));
|
|
31
|
+
if (matched.length)
|
|
32
|
+
return matched;
|
|
33
|
+
}
|
|
34
|
+
if (WEBHOOK_EVENTS.includes(value))
|
|
35
|
+
return [value];
|
|
36
|
+
throw new UsageError(`Unknown event ${JSON.stringify(value)}. Events: ${WEBHOOK_EVENTS.join(", ")}`);
|
|
37
|
+
});
|
|
38
|
+
return [...new Set(expanded)];
|
|
39
|
+
}
|
|
40
|
+
function url(input) {
|
|
41
|
+
const value = string(input, "url");
|
|
42
|
+
if (value !== undefined && !/^https:\/\//i.test(value))
|
|
43
|
+
throw new UsageError("--url must be a public https URL");
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
function webhookText(w, heading) {
|
|
47
|
+
return fields([
|
|
48
|
+
["Webhook", heading ? `${w.id} (${heading})` : w.id],
|
|
49
|
+
["URL", w.url],
|
|
50
|
+
["Events", w.events.join(", ")],
|
|
51
|
+
["Enabled", w.enabled ? "yes" : `no${w.disabledReason ? ` (${w.disabledReason})` : ""}`],
|
|
52
|
+
["Description", w.description],
|
|
53
|
+
["Secret", w.secret ? `${w.secret} (shown once: store it now to verify signatures)` : w.secretPreview],
|
|
54
|
+
["Last delivery", w.lastDeliveryAt ? date(w.lastDeliveryAt) : undefined],
|
|
55
|
+
["Failures", w.consecutiveFailures || undefined],
|
|
56
|
+
]);
|
|
57
|
+
}
|
|
58
|
+
const EVENTS_HELP = `Events, comma-separated: ${WEBHOOK_EVENTS.join(", ")}.
|
|
59
|
+
post.* or account.* takes a whole group, * every event. Payloads and signature checks:
|
|
60
|
+
https://ampost.io/docs?ref=cli#webhooks`;
|
|
61
|
+
export const webhooksList = {
|
|
62
|
+
name: "webhooks list",
|
|
63
|
+
summary: "List webhook endpoints",
|
|
64
|
+
options: { ...LIST_OPTIONS },
|
|
65
|
+
async run(ctx, input) {
|
|
66
|
+
const client = await ctx.client();
|
|
67
|
+
const result = await fetchList(client.webhooks.list(pageQuery(input)), input);
|
|
68
|
+
if (result.data.length === 0)
|
|
69
|
+
return { data: result, text: "No webhooks." };
|
|
70
|
+
const rows = result.data.map((w) => [w.id, w.url, w.enabled ? "yes" : "no", w.events.length, date(w.lastDeliveryAt)]);
|
|
71
|
+
return {
|
|
72
|
+
data: result,
|
|
73
|
+
text: `${table(["id", "url", "enabled", "events", "last delivery"], rows)}\n\n${pageNote(result.pagination, result.data.length, "webhook")}`,
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
export const webhooksGet = {
|
|
78
|
+
name: "webhooks get",
|
|
79
|
+
summary: "Show a webhook endpoint",
|
|
80
|
+
args: "<webhook-id>",
|
|
81
|
+
positionals: { min: 1, max: 1 },
|
|
82
|
+
async run(ctx, input) {
|
|
83
|
+
const client = await ctx.client();
|
|
84
|
+
const w = await client.webhooks.get(id(input.positionals[0], "The webhook id"));
|
|
85
|
+
return { data: w, text: webhookText(w) };
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
export const webhooksCreate = {
|
|
89
|
+
name: "webhooks create",
|
|
90
|
+
summary: "Send events to a URL (prints the signing secret once)",
|
|
91
|
+
options: {
|
|
92
|
+
url: { type: "string", value: "URL", help: "Public https URL that receives the events (required)" },
|
|
93
|
+
events: { type: "string", short: "e", multiple: true, value: "LIST", help: "Events to send (required), e.g. post.published,post.failed" },
|
|
94
|
+
description: { type: "string", value: "TEXT", help: "Your note, at most 200 characters" },
|
|
95
|
+
"idempotency-key": { type: "string", value: "KEY", help: "Repeat the command safely with the same key" },
|
|
96
|
+
},
|
|
97
|
+
help: `${EVENTS_HELP}
|
|
98
|
+
|
|
99
|
+
Example:
|
|
100
|
+
ampost webhooks create --url https://example.com/hooks/ampost -e post.published,post.failed`,
|
|
101
|
+
async run(ctx, input) {
|
|
102
|
+
const target = url(input);
|
|
103
|
+
const chosen = events(input);
|
|
104
|
+
if (!target)
|
|
105
|
+
throw new UsageError("--url is required");
|
|
106
|
+
if (!chosen)
|
|
107
|
+
throw new UsageError("--events is required, e.g. -e post.published,post.failed");
|
|
108
|
+
const description = string(input, "description");
|
|
109
|
+
const body = { url: target, events: chosen, ...(description !== undefined && { description }) };
|
|
110
|
+
const client = await ctx.client();
|
|
111
|
+
const key = string(input, "idempotency-key");
|
|
112
|
+
const w = await client.webhooks.create(body, key ? { idempotencyKey: key } : {});
|
|
113
|
+
return { data: w, text: webhookText(w, "created") };
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
export const webhooksUpdate = {
|
|
117
|
+
name: "webhooks update",
|
|
118
|
+
summary: "Change a webhook's URL, events, description or state; rotate its secret",
|
|
119
|
+
args: "<webhook-id>",
|
|
120
|
+
positionals: { min: 1, max: 1 },
|
|
121
|
+
options: {
|
|
122
|
+
url: { type: "string", value: "URL", help: "New https URL" },
|
|
123
|
+
events: { type: "string", short: "e", multiple: true, value: "LIST", help: "New event list (replaces the old one)" },
|
|
124
|
+
description: { type: "string", value: "TEXT", help: "New note; \"\" clears it" },
|
|
125
|
+
enable: { type: "boolean", help: "Turn it on (clears the failure count)" },
|
|
126
|
+
disable: { type: "boolean", help: "Turn it off" },
|
|
127
|
+
"rotate-secret": { type: "boolean", help: "Replace the signing secret; the old one stops working at once" },
|
|
128
|
+
},
|
|
129
|
+
help: EVENTS_HELP,
|
|
130
|
+
async run(ctx, input) {
|
|
131
|
+
const webhookId = id(input.positionals[0], "The webhook id");
|
|
132
|
+
if (flag(input, "enable") && flag(input, "disable"))
|
|
133
|
+
throw new UsageError("Use --enable or --disable, not both");
|
|
134
|
+
const target = url(input);
|
|
135
|
+
const chosen = events(input);
|
|
136
|
+
const description = string(input, "description");
|
|
137
|
+
const body = {
|
|
138
|
+
...(target !== undefined && { url: target }),
|
|
139
|
+
...(chosen && { events: chosen }),
|
|
140
|
+
...(description !== undefined && { description: description === "" ? null : description }),
|
|
141
|
+
...(flag(input, "enable") && { enabled: true }),
|
|
142
|
+
...(flag(input, "disable") && { enabled: false }),
|
|
143
|
+
...(flag(input, "rotate-secret") && { rotateSecret: true }),
|
|
144
|
+
};
|
|
145
|
+
if (Object.keys(body).length === 0)
|
|
146
|
+
throw new UsageError("Nothing to change: give --url, --events, --description, --enable, --disable or --rotate-secret");
|
|
147
|
+
const client = await ctx.client();
|
|
148
|
+
const w = await client.webhooks.update(webhookId, body);
|
|
149
|
+
return { data: w, text: webhookText(w, "updated") };
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
export const webhooksDelete = {
|
|
153
|
+
name: "webhooks delete",
|
|
154
|
+
summary: "Delete a webhook endpoint",
|
|
155
|
+
args: "<webhook-id>",
|
|
156
|
+
positionals: { min: 1, max: 1 },
|
|
157
|
+
async run(ctx, input) {
|
|
158
|
+
const client = await ctx.client();
|
|
159
|
+
const result = await client.webhooks.delete(id(input.positionals[0], "The webhook id"));
|
|
160
|
+
return { data: result, text: `Deleted webhook ${result.id}` };
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
export const webhooksTest = {
|
|
164
|
+
name: "webhooks test",
|
|
165
|
+
summary: "Send a test event to a webhook now",
|
|
166
|
+
args: "<webhook-id>",
|
|
167
|
+
positionals: { min: 1, max: 1 },
|
|
168
|
+
async run(ctx, input) {
|
|
169
|
+
const client = await ctx.client();
|
|
170
|
+
const d = await client.webhooks.test(id(input.positionals[0], "The webhook id"));
|
|
171
|
+
return {
|
|
172
|
+
data: d,
|
|
173
|
+
text: fields([
|
|
174
|
+
["Delivery", d.id],
|
|
175
|
+
["Status", d.status],
|
|
176
|
+
["HTTP status", d.responseStatus],
|
|
177
|
+
["Took", d.durationMs === null ? undefined : `${d.durationMs} ms`],
|
|
178
|
+
["Error", d.error],
|
|
179
|
+
]),
|
|
180
|
+
};
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
export const webhooksDeliveries = {
|
|
184
|
+
name: "webhooks deliveries",
|
|
185
|
+
summary: "Recent deliveries of a webhook, with their HTTP status",
|
|
186
|
+
args: "<webhook-id>",
|
|
187
|
+
positionals: { min: 1, max: 1 },
|
|
188
|
+
options: { ...LIST_OPTIONS },
|
|
189
|
+
async run(ctx, input) {
|
|
190
|
+
const client = await ctx.client();
|
|
191
|
+
const webhookId = id(input.positionals[0], "The webhook id");
|
|
192
|
+
const result = await fetchList(client.webhooks.listDeliveries(webhookId, pageQuery(input)), input);
|
|
193
|
+
if (result.data.length === 0)
|
|
194
|
+
return { data: result, text: "No deliveries yet." };
|
|
195
|
+
const rows = result.data.map((d) => [d.id, d.eventType, d.status, d.responseStatus, d.attempts, date(d.createdAt)]);
|
|
196
|
+
return {
|
|
197
|
+
data: result,
|
|
198
|
+
text: `${table(["id", "event", "status", "http", "attempts", "created"], rows)}\n\n${pageNote(result.pagination, result.data.length, "delivery", "deliveries")}`,
|
|
199
|
+
};
|
|
200
|
+
},
|
|
201
|
+
};
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
/**
|
|
5
|
+
* The OS config directory: `AMPOST_CONFIG_DIR` if set, else `%APPDATA%\ampost` on Windows,
|
|
6
|
+
* `~/Library/Application Support/ampost` on macOS, `$XDG_CONFIG_HOME/ampost` or `~/.config/ampost` elsewhere.
|
|
7
|
+
*/
|
|
8
|
+
export function configDir(env, platform = process.platform, home = homedir()) {
|
|
9
|
+
if (env.AMPOST_CONFIG_DIR)
|
|
10
|
+
return env.AMPOST_CONFIG_DIR;
|
|
11
|
+
if (platform === "win32")
|
|
12
|
+
return join(env.APPDATA || join(home, "AppData", "Roaming"), "ampost");
|
|
13
|
+
if (platform === "darwin")
|
|
14
|
+
return join(home, "Library", "Application Support", "ampost");
|
|
15
|
+
return join(env.XDG_CONFIG_HOME || join(home, ".config"), "ampost");
|
|
16
|
+
}
|
|
17
|
+
export function configPath(env) {
|
|
18
|
+
return join(configDir(env), "config.json");
|
|
19
|
+
}
|
|
20
|
+
export async function readConfig(env) {
|
|
21
|
+
let text;
|
|
22
|
+
try {
|
|
23
|
+
text = await readFile(configPath(env), "utf8");
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code === "ENOENT")
|
|
27
|
+
return {};
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(text);
|
|
32
|
+
if (!parsed || typeof parsed !== "object")
|
|
33
|
+
return {};
|
|
34
|
+
const { apiKey, baseUrl } = parsed;
|
|
35
|
+
return {
|
|
36
|
+
...(typeof apiKey === "string" && apiKey && { apiKey }),
|
|
37
|
+
...(typeof baseUrl === "string" && baseUrl && { baseUrl }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new Error(`${configPath(env)} is not valid JSON: fix or delete it, or run \`ampost logout\``);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Writes the config readable by the user only (0600 in a 0700 directory; Windows ignores the modes). */
|
|
45
|
+
export async function writeConfig(env, config) {
|
|
46
|
+
const dir = configDir(env);
|
|
47
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
48
|
+
const path = configPath(env);
|
|
49
|
+
await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
50
|
+
// writeFile keeps the mode of an existing file.
|
|
51
|
+
await chmod(path, 0o600);
|
|
52
|
+
return path;
|
|
53
|
+
}
|
|
54
|
+
/** Deletes the stored key. Returns false when there was none. */
|
|
55
|
+
export async function deleteConfig(env) {
|
|
56
|
+
const config = await readConfig(env);
|
|
57
|
+
if (!config.apiKey)
|
|
58
|
+
return false;
|
|
59
|
+
await rm(configPath(env), { force: true });
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
/** AMPOST_API_KEY wins over the stored key, so a script or an agent can override a login. */
|
|
63
|
+
export async function resolveCredentials(env) {
|
|
64
|
+
if (env.AMPOST_API_KEY)
|
|
65
|
+
return { apiKey: env.AMPOST_API_KEY, baseUrl: env.AMPOST_BASE_URL || undefined, source: "env" };
|
|
66
|
+
const config = await readConfig(env);
|
|
67
|
+
if (!config.apiKey)
|
|
68
|
+
return undefined;
|
|
69
|
+
return { apiKey: config.apiKey, baseUrl: env.AMPOST_BASE_URL || config.baseUrl, source: "config" };
|
|
70
|
+
}
|
|
71
|
+
/** `amp_live_abc…wxyz`: enough to tell keys apart, never the whole key. */
|
|
72
|
+
export function maskKey(key) {
|
|
73
|
+
if (key.length < 24)
|
|
74
|
+
return `${key.slice(0, 4)}…`;
|
|
75
|
+
return `${key.slice(0, 12)}…${key.slice(-4)}`;
|
|
76
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { AmpostError, APIConnectionError, APIError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, MediaUploadError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, } from "ampost";
|
|
2
|
+
/**
|
|
3
|
+
* Exit codes. Scripts and agents can branch on them; `--json` also prints the reason as
|
|
4
|
+
* `{ "error": { "code", ... } }`. They are part of the CLI's public contract: add codes, never renumber.
|
|
5
|
+
*/
|
|
6
|
+
export const EXIT = {
|
|
7
|
+
/** Done. */
|
|
8
|
+
OK: 0,
|
|
9
|
+
/** Anything else: an unexpected error, or `--wait` gave up while the post was still publishing. */
|
|
10
|
+
ERROR: 1,
|
|
11
|
+
/** Wrong command, option or argument. Nothing was sent to the API. */
|
|
12
|
+
USAGE: 2,
|
|
13
|
+
/** No API key, or the API refused it (401). Run `ampost login` or set AMPOST_API_KEY. */
|
|
14
|
+
AUTH: 3,
|
|
15
|
+
/** The key lacks a scope or platform set, or the plan lacks the feature (403). */
|
|
16
|
+
FORBIDDEN: 4,
|
|
17
|
+
/** No such post, account or webhook (404). */
|
|
18
|
+
NOT_FOUND: 5,
|
|
19
|
+
/** The request or its content is invalid (400, 413, 422), a `--dry-run` found errors, or a CSV row failed. */
|
|
20
|
+
INVALID: 6,
|
|
21
|
+
/** The resource's state does not allow it (409), for example deleting a published post. */
|
|
22
|
+
CONFLICT: 7,
|
|
23
|
+
/** Rate limit or plan quota (429), after the SDK's own retries. */
|
|
24
|
+
RATE_LIMITED: 8,
|
|
25
|
+
/** Ampost or the network failed (5xx, timeout, no connection). Safe to retry later. */
|
|
26
|
+
UNAVAILABLE: 9,
|
|
27
|
+
/** With `--wait`: the post failed on every platform or on some of them (`failed`, `partial`).
|
|
28
|
+
* `posts unpublish`: an account still has the post (no delete API, or the platform refused).
|
|
29
|
+
* `posts edit-published`: an account did not take the new text. */
|
|
30
|
+
POST_FAILED: 10,
|
|
31
|
+
};
|
|
32
|
+
/** A mistake in the command line. Exits with EXIT.USAGE. */
|
|
33
|
+
export class UsageError extends Error {
|
|
34
|
+
name = "UsageError";
|
|
35
|
+
}
|
|
36
|
+
/** An error the CLI itself raises, with its exit code and a stable code for `--json`. */
|
|
37
|
+
export class CliError extends Error {
|
|
38
|
+
exitCode;
|
|
39
|
+
code;
|
|
40
|
+
details;
|
|
41
|
+
name = "CliError";
|
|
42
|
+
constructor(message, exitCode, code, details) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.exitCode = exitCode;
|
|
45
|
+
this.code = code;
|
|
46
|
+
this.details = details;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function exitCodeFor(error) {
|
|
50
|
+
if (error instanceof UsageError)
|
|
51
|
+
return EXIT.USAGE;
|
|
52
|
+
if (error instanceof CliError)
|
|
53
|
+
return error.exitCode;
|
|
54
|
+
if (error instanceof AuthenticationError)
|
|
55
|
+
return EXIT.AUTH;
|
|
56
|
+
if (error instanceof PermissionDeniedError)
|
|
57
|
+
return EXIT.FORBIDDEN;
|
|
58
|
+
if (error instanceof NotFoundError)
|
|
59
|
+
return EXIT.NOT_FOUND;
|
|
60
|
+
if (error instanceof BadRequestError || error instanceof PayloadTooLargeError || error instanceof UnprocessableEntityError) {
|
|
61
|
+
return EXIT.INVALID;
|
|
62
|
+
}
|
|
63
|
+
if (error instanceof ConflictError)
|
|
64
|
+
return EXIT.CONFLICT;
|
|
65
|
+
if (error instanceof RateLimitError)
|
|
66
|
+
return EXIT.RATE_LIMITED;
|
|
67
|
+
if (error instanceof InternalServerError || error instanceof APIConnectionError)
|
|
68
|
+
return EXIT.UNAVAILABLE;
|
|
69
|
+
if (error instanceof MediaUploadError)
|
|
70
|
+
return error.reason === "timeout" ? EXIT.UNAVAILABLE : EXIT.INVALID;
|
|
71
|
+
if (error instanceof APIError)
|
|
72
|
+
return error.status >= 500 ? EXIT.UNAVAILABLE : EXIT.ERROR;
|
|
73
|
+
// The SDK throws a plain AmpostError for a missing key.
|
|
74
|
+
if (error instanceof AmpostError && /API key/.test(error.message))
|
|
75
|
+
return EXIT.AUTH;
|
|
76
|
+
return EXIT.ERROR;
|
|
77
|
+
}
|
|
78
|
+
/** The `{ error }` document `--json` prints on failure. API errors keep the API's own code. */
|
|
79
|
+
export function errorJson(error) {
|
|
80
|
+
const exitCode = exitCodeFor(error);
|
|
81
|
+
if (error instanceof APIError) {
|
|
82
|
+
return {
|
|
83
|
+
error: {
|
|
84
|
+
code: error.code,
|
|
85
|
+
message: messageOf(error),
|
|
86
|
+
status: error.status,
|
|
87
|
+
details: error.details ?? null,
|
|
88
|
+
requestId: error.requestId ?? null,
|
|
89
|
+
exitCode,
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
if (error instanceof CliError) {
|
|
94
|
+
return { error: { code: error.code, message: error.message, details: error.details ?? null, exitCode } };
|
|
95
|
+
}
|
|
96
|
+
if (error instanceof MediaUploadError) {
|
|
97
|
+
return { error: { code: "MEDIA_UPLOAD_FAILED", message: error.message, details: { reason: error.reason, uploadId: error.uploadId }, exitCode } };
|
|
98
|
+
}
|
|
99
|
+
const code = error instanceof UsageError
|
|
100
|
+
? "USAGE"
|
|
101
|
+
: exitCode === EXIT.AUTH
|
|
102
|
+
? "MISSING_API_KEY"
|
|
103
|
+
: error instanceof APIConnectionError
|
|
104
|
+
? "CONNECTION_ERROR"
|
|
105
|
+
: "ERROR";
|
|
106
|
+
return { error: { code, message: error instanceof Error ? error.message : String(error), details: null, exitCode } };
|
|
107
|
+
}
|
|
108
|
+
/** The API's message without the SDK's `400 CODE: ` prefix. */
|
|
109
|
+
function messageOf(error) {
|
|
110
|
+
const prefix = `${error.status} ${error.code}: `;
|
|
111
|
+
return error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message;
|
|
112
|
+
}
|
|
113
|
+
/** Human-readable lines for stderr. */
|
|
114
|
+
export function errorText(error) {
|
|
115
|
+
if (error instanceof APIError) {
|
|
116
|
+
const lines = [`Error: ${messageOf(error)} (${error.code}, HTTP ${error.status})`];
|
|
117
|
+
const issues = error.details?.issues;
|
|
118
|
+
if (Array.isArray(issues)) {
|
|
119
|
+
for (const issue of issues.slice(0, 20))
|
|
120
|
+
lines.push(` - ${issueText(issue)}`);
|
|
121
|
+
if (issues.length > 20)
|
|
122
|
+
lines.push(` ... and ${issues.length - 20} more (use --json for all)`);
|
|
123
|
+
}
|
|
124
|
+
if (error instanceof AuthenticationError)
|
|
125
|
+
lines.push("Run `ampost login` or set AMPOST_API_KEY.");
|
|
126
|
+
if (error instanceof RateLimitError && error.retryAfterSeconds !== undefined) {
|
|
127
|
+
lines.push(`Try again in ${error.retryAfterSeconds} s.`);
|
|
128
|
+
}
|
|
129
|
+
if (error.requestId)
|
|
130
|
+
lines.push(`Request id: ${error.requestId}`);
|
|
131
|
+
return lines.join("\n");
|
|
132
|
+
}
|
|
133
|
+
if (error instanceof UsageError)
|
|
134
|
+
return `Error: ${error.message}\nRun \`ampost --help\` for usage.`;
|
|
135
|
+
return `Error: ${error instanceof Error ? error.message : String(error)}`;
|
|
136
|
+
}
|
|
137
|
+
function issueText(issue) {
|
|
138
|
+
if (!issue || typeof issue !== "object")
|
|
139
|
+
return String(issue);
|
|
140
|
+
const { path, message, code } = issue;
|
|
141
|
+
// The API sends `media[0].url`; accept a path array too.
|
|
142
|
+
const where = Array.isArray(path) ? (path.length ? `${path.join(".")}: ` : "") : typeof path === "string" && path ? `${path}: ` : "";
|
|
143
|
+
return `${where}${typeof message === "string" ? message : JSON.stringify(issue)}${typeof code === "string" ? ` (${code})` : ""}`;
|
|
144
|
+
}
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** Plain-text output for people. Scripts should use `--json`: this format may change between versions. */
|
|
2
|
+
/** Left-aligned columns separated by two spaces, with an upper-case header row. */
|
|
3
|
+
export function table(headers, rows) {
|
|
4
|
+
const text = [headers.map((h) => h.toUpperCase()), ...rows.map((row) => row.map(cell))];
|
|
5
|
+
const widths = headers.map((_, i) => Math.max(...text.map((row) => width(row[i] ?? ""))));
|
|
6
|
+
return text
|
|
7
|
+
.map((row) => row
|
|
8
|
+
.map((value, i) => (i === row.length - 1 ? value : value + " ".repeat(widths[i] - width(value))))
|
|
9
|
+
.join(" ")
|
|
10
|
+
.trimEnd())
|
|
11
|
+
.join("\n");
|
|
12
|
+
}
|
|
13
|
+
/** `key: value` lines with the keys aligned. Empty values are left out. */
|
|
14
|
+
export function fields(entries) {
|
|
15
|
+
const shown = entries.filter(([, value]) => value !== undefined && value !== null && value !== "");
|
|
16
|
+
const pad = Math.max(0, ...shown.map(([key]) => key.length)) + 1;
|
|
17
|
+
return shown.map(([key, value]) => `${`${key}:`.padEnd(pad + 1)}${cell(value)}`).join("\n");
|
|
18
|
+
}
|
|
19
|
+
export function cell(value) {
|
|
20
|
+
if (value === null || value === undefined || value === "")
|
|
21
|
+
return "-";
|
|
22
|
+
if (typeof value === "boolean")
|
|
23
|
+
return value ? "yes" : "no";
|
|
24
|
+
return String(value);
|
|
25
|
+
}
|
|
26
|
+
/** One line of at most `max` characters, for a text column. */
|
|
27
|
+
export function oneLine(text, max = 48) {
|
|
28
|
+
const flat = (text ?? "").replace(/\s+/g, " ").trim();
|
|
29
|
+
const chars = Array.from(flat);
|
|
30
|
+
return chars.length > max ? `${chars.slice(0, max - 1).join("")}…` : flat;
|
|
31
|
+
}
|
|
32
|
+
/** `2026-12-01 09:00 UTC`. Dates stay UTC so output does not depend on the machine's time zone. */
|
|
33
|
+
export function date(iso) {
|
|
34
|
+
if (!iso)
|
|
35
|
+
return "-";
|
|
36
|
+
const parsed = new Date(iso);
|
|
37
|
+
if (Number.isNaN(parsed.getTime()))
|
|
38
|
+
return iso;
|
|
39
|
+
return `${parsed.toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
40
|
+
}
|
|
41
|
+
export function number(value) {
|
|
42
|
+
if (value === null || value === undefined)
|
|
43
|
+
return "-";
|
|
44
|
+
return value.toLocaleString("en-US");
|
|
45
|
+
}
|
|
46
|
+
export function signed(value) {
|
|
47
|
+
if (value === null || value === undefined)
|
|
48
|
+
return "-";
|
|
49
|
+
return `${value > 0 ? "+" : ""}${value.toLocaleString("en-US")}`;
|
|
50
|
+
}
|
|
51
|
+
/** Footer for one page of a list. */
|
|
52
|
+
export function pageNote(pagination, shown, noun, plural = `${noun}s`) {
|
|
53
|
+
if (!pagination.hasMore)
|
|
54
|
+
return shown === 1 ? `1 ${noun}` : `${shown} ${plural}`;
|
|
55
|
+
const from = pagination.offset + 1;
|
|
56
|
+
const to = pagination.offset + shown;
|
|
57
|
+
return `${from}-${to} of ${pagination.total} ${plural}. Next page: --offset ${to}, or --all for every one`;
|
|
58
|
+
}
|
|
59
|
+
/** Display width: wide characters (CJK, most emoji) take two columns. */
|
|
60
|
+
const WIDE_RANGES = [
|
|
61
|
+
[0x1100, 0x115f], // Hangul Jamo
|
|
62
|
+
[0x2e80, 0xa4cf], // CJK radicals to Yi
|
|
63
|
+
[0xac00, 0xd7a3], // Hangul syllables
|
|
64
|
+
[0xf900, 0xfaff], // CJK compatibility ideographs
|
|
65
|
+
[0xfe30, 0xfe4f], // CJK compatibility forms
|
|
66
|
+
[0xff00, 0xff60], // full-width forms
|
|
67
|
+
[0xffe0, 0xffe6],
|
|
68
|
+
[0x20000, 0x3fffd], // CJK extensions
|
|
69
|
+
];
|
|
70
|
+
const EMOJI = /\p{Extended_Pictographic}/u;
|
|
71
|
+
function width(text) {
|
|
72
|
+
let total = 0;
|
|
73
|
+
for (const char of text) {
|
|
74
|
+
const code = char.codePointAt(0);
|
|
75
|
+
total += EMOJI.test(char) || WIDE_RANGES.some(([from, to]) => code >= from && code <= to) ? 2 : 1;
|
|
76
|
+
}
|
|
77
|
+
return total;
|
|
78
|
+
}
|
package/dist/io.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** The real terminal. */
|
|
2
|
+
export function nodeIo() {
|
|
3
|
+
return {
|
|
4
|
+
stdout: (text) => void process.stdout.write(text),
|
|
5
|
+
stderr: (text) => void process.stderr.write(text),
|
|
6
|
+
stdinIsTTY: Boolean(process.stdin.isTTY),
|
|
7
|
+
readStdin,
|
|
8
|
+
promptSecret,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
async function readStdin() {
|
|
12
|
+
const chunks = [];
|
|
13
|
+
for await (const chunk of process.stdin)
|
|
14
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
15
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
16
|
+
}
|
|
17
|
+
/** Reads one line from the terminal without echoing it. Ctrl+C cancels. */
|
|
18
|
+
function promptSecret(question) {
|
|
19
|
+
const { stdin, stderr } = process;
|
|
20
|
+
stderr.write(question);
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
let answer = "";
|
|
23
|
+
stdin.setRawMode(true);
|
|
24
|
+
stdin.resume();
|
|
25
|
+
stdin.setEncoding("utf8");
|
|
26
|
+
const done = (error) => {
|
|
27
|
+
stdin.setRawMode(false);
|
|
28
|
+
stdin.pause();
|
|
29
|
+
stdin.off("data", onData);
|
|
30
|
+
stderr.write("\n");
|
|
31
|
+
if (error)
|
|
32
|
+
reject(error);
|
|
33
|
+
else
|
|
34
|
+
resolve(answer);
|
|
35
|
+
};
|
|
36
|
+
const onData = (data) => {
|
|
37
|
+
for (const char of data) {
|
|
38
|
+
if (char === "\r" || char === "\n" || char === "\u0004")
|
|
39
|
+
return done();
|
|
40
|
+
if (char === "\u0003")
|
|
41
|
+
return done(new Error("Cancelled"));
|
|
42
|
+
if (char === "\u007f" || char === "\b")
|
|
43
|
+
answer = answer.slice(0, -1);
|
|
44
|
+
else if (char >= " ")
|
|
45
|
+
answer += char;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
stdin.on("data", onData);
|
|
49
|
+
});
|
|
50
|
+
}
|