@anaella/cli 0.1.1 → 0.2.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.
Files changed (2) hide show
  1. package/dist/index.js +143 -50
  2. package/package.json +24 -7
package/dist/index.js CHANGED
@@ -1,11 +1,109 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { readFileSync as readFileSync2 } from "fs";
4
+ import { readFileSync as readFileSync3 } from "fs";
5
5
  import { AnaellaClient } from "@anaella/client";
6
6
  import { Command } from "commander";
7
7
 
8
+ // src/browser-login.ts
9
+ import { spawn } from "child_process";
10
+ import crypto from "crypto";
11
+ import http from "http";
12
+ var CLIENT_ID = "anaella-cli";
13
+ var DEFAULT_TIMEOUT_MS = 3e5;
14
+ function pkce() {
15
+ const verifier = crypto.randomBytes(32).toString("base64url");
16
+ const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
17
+ return { verifier, challenge };
18
+ }
19
+ function defaultOpen(url) {
20
+ const child = process.platform === "darwin" ? spawn("open", [url], { stdio: "ignore", detached: true }) : process.platform === "win32" ? spawn("cmd", ["/c", "start", "", url], { stdio: "ignore", detached: true }) : spawn("xdg-open", [url], { stdio: "ignore", detached: true });
21
+ child.on("error", () => {
22
+ process.stderr.write("Couldn't open a browser automatically \u2014 open the URL above manually.\n");
23
+ });
24
+ child.unref();
25
+ }
26
+ async function browserLogin(opts) {
27
+ const { verifier, challenge } = pkce();
28
+ const state = crypto.randomBytes(16).toString("base64url");
29
+ const open = opts.openBrowser ?? defaultOpen;
30
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
31
+ return new Promise((resolve, reject) => {
32
+ const server = http.createServer(async (req, res) => {
33
+ const url = new URL(req.url ?? "", "http://127.0.0.1");
34
+ if (url.pathname !== "/callback") {
35
+ res.writeHead(404);
36
+ res.end();
37
+ return;
38
+ }
39
+ const returnedState = url.searchParams.get("state");
40
+ const code = url.searchParams.get("code");
41
+ const err = url.searchParams.get("error");
42
+ const port = server.address().port;
43
+ res.writeHead(200, { "content-type": "text/html" });
44
+ res.end("<html><body>You can close this tab and return to the terminal.</body></html>");
45
+ server.close();
46
+ clearTimeout(timer);
47
+ if (err) return reject(new Error(`Authorization denied: ${err}`));
48
+ if (!code || returnedState !== state)
49
+ return reject(new Error("Invalid authorization response"));
50
+ try {
51
+ const tokenRes = await fetch(`${opts.apiUrl}/oauth/token`, {
52
+ method: "POST",
53
+ headers: { "content-type": "application/json" },
54
+ body: JSON.stringify({
55
+ grant_type: "authorization_code",
56
+ code,
57
+ code_verifier: verifier,
58
+ client_id: CLIENT_ID,
59
+ redirect_uri: `http://127.0.0.1:${port}/callback`
60
+ })
61
+ });
62
+ if (!tokenRes.ok) return reject(new Error(`Token exchange failed: HTTP ${tokenRes.status}`));
63
+ const json = await tokenRes.json();
64
+ resolve(json.access_token);
65
+ } catch (e) {
66
+ reject(e);
67
+ }
68
+ });
69
+ const timer = setTimeout(() => {
70
+ server.close();
71
+ reject(
72
+ new Error(
73
+ "Timed out waiting for the browser sign-in. Make sure you're signed in at anaella.com, then run 'anaella login' again."
74
+ )
75
+ );
76
+ }, timeoutMs);
77
+ server.listen(0, "127.0.0.1", () => {
78
+ const port = server.address().port;
79
+ const authorizeUrl = new URL("/oauth/authorize", opts.apiUrl);
80
+ authorizeUrl.searchParams.set("response_type", "code");
81
+ authorizeUrl.searchParams.set("client_id", CLIENT_ID);
82
+ authorizeUrl.searchParams.set("redirect_uri", `http://127.0.0.1:${port}/callback`);
83
+ authorizeUrl.searchParams.set("code_challenge", challenge);
84
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
85
+ authorizeUrl.searchParams.set("state", state);
86
+ process.stdout.write(`Opening your browser\u2026 if it doesn't open, visit:
87
+ ${authorizeUrl}
88
+ `);
89
+ void open(authorizeUrl.toString());
90
+ });
91
+ });
92
+ }
93
+
8
94
  // src/commands.ts
95
+ import { readFileSync } from "fs";
96
+ import { basename, extname } from "path";
97
+ var EXT_MIME = {
98
+ ".mp4": "video/mp4",
99
+ ".mov": "video/quicktime",
100
+ ".webm": "video/webm",
101
+ ".jpg": "image/jpeg",
102
+ ".jpeg": "image/jpeg",
103
+ ".png": "image/png",
104
+ ".gif": "image/gif",
105
+ ".webp": "image/webp"
106
+ };
9
107
  var cmdChannels = (client) => client.listChannels();
10
108
  function cmdPost(client, o) {
11
109
  return client.createPost({
@@ -23,9 +121,26 @@ var cmdPosts = (client, o) => client.listPosts({
23
121
  });
24
122
  var cmdGet = (client, id) => client.getPost(id);
25
123
  var cmdDelete = (client, id) => client.deletePost(id);
124
+ var cmdAnalytics = (client, o) => o.post ? client.getPostAnalytics(o.post, { period: o.period }) : client.getAnalytics({ period: o.period });
125
+ function cmdUpload(client, o) {
126
+ const urls = o.url ?? [];
127
+ const files = o.files ?? [];
128
+ if (urls.length && files.length) {
129
+ throw new Error("Pass either local file path(s) or --url, not both.");
130
+ }
131
+ if (urls.length) return client.uploadUrls(urls);
132
+ if (!files.length) throw new Error("Provide file path(s) to upload, or --url <url> to register.");
133
+ return client.uploadFiles(
134
+ files.map((p) => ({
135
+ filename: basename(p),
136
+ data: readFileSync(p),
137
+ contentType: EXT_MIME[extname(p).toLowerCase()]
138
+ }))
139
+ );
140
+ }
26
141
 
27
142
  // src/config.ts
28
- import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
143
+ import { chmodSync, existsSync, mkdirSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "fs";
29
144
  import { homedir } from "os";
30
145
  import { dirname, join } from "path";
31
146
  var DEFAULT_API_URL = "https://api.anaella.com";
@@ -37,7 +152,7 @@ function readConfigFile(env) {
37
152
  const path = configPath(env);
38
153
  if (!existsSync(path)) return {};
39
154
  try {
40
- return JSON.parse(readFileSync(path, "utf8"));
155
+ return JSON.parse(readFileSync2(path, "utf8"));
41
156
  } catch {
42
157
  process.stderr.write(`[anaella] warning: could not parse ${path}; ignoring.
43
158
  `);
@@ -114,45 +229,6 @@ ${err.details.map((d) => ` - ${d.field}: ${d.message}`).join("\n")}` : "";
114
229
  `);
115
230
  }
116
231
 
117
- // src/prompt.ts
118
- function promptSecret(question) {
119
- return new Promise((resolve) => {
120
- const stdin = process.stdin;
121
- process.stdout.write(question);
122
- stdin.setRawMode?.(true);
123
- stdin.resume();
124
- stdin.setEncoding("utf8");
125
- let value = "";
126
- const onData = (chunk) => {
127
- for (const ch of chunk) {
128
- const code = ch.charCodeAt(0);
129
- if (code === 10 || code === 13 || code === 4) {
130
- stdin.setRawMode?.(false);
131
- stdin.pause();
132
- stdin.removeListener("data", onData);
133
- process.stdout.write("\n");
134
- resolve(value);
135
- return;
136
- }
137
- if (code === 3) {
138
- process.stdout.write("\n");
139
- process.exit(130);
140
- }
141
- if (code === 127 || code === 8) {
142
- if (value.length > 0) {
143
- value = value.slice(0, -1);
144
- process.stdout.write("\b \b");
145
- }
146
- continue;
147
- }
148
- value += ch;
149
- process.stdout.write("*");
150
- }
151
- };
152
- stdin.on("data", onData);
153
- });
154
- }
155
-
156
232
  // src/index.ts
157
233
  var collect = (val, acc) => {
158
234
  acc.push(val);
@@ -178,18 +254,31 @@ async function withClient(command, fn, columns) {
178
254
  process.exitCode = 1;
179
255
  }
180
256
  }
181
- program.command("login").description("Save an API key (verified against the API) to ~/.config/anaella/config.json").option("--api-key <key>", "the key (else read from stdin)").action(async (opts, command) => {
257
+ program.command("login").description("Sign in via the browser (or pass --api-key for headless).").option("--api-key <key>", "skip the browser and save this key directly").action(async (opts, command) => {
182
258
  const globals = command.optsWithGlobals();
259
+ const apiUrl = resolveConfig({ apiUrl: globals.apiUrl }, process.env).apiUrl;
183
260
  let key = opts.apiKey;
184
261
  if (!key) {
185
- key = process.stdin.isTTY ? (await promptSecret("Enter your ana_ API key: ")).trim() : readFileSync2(0, "utf8").trim();
186
- }
187
- if (!key) {
188
- process.stderr.write("No key provided (pass --api-key, pipe it on stdin, or type it).\n");
189
- process.exitCode = 1;
190
- return;
262
+ if (!process.stdin.isTTY) {
263
+ key = readFileSync3(0, "utf8").trim();
264
+ if (!key) {
265
+ process.stderr.write(
266
+ "No key provided (pass --api-key, pipe it on stdin, or run 'anaella login' in an interactive terminal).\n"
267
+ );
268
+ process.exitCode = 1;
269
+ return;
270
+ }
271
+ } else {
272
+ try {
273
+ key = await browserLogin({ apiUrl });
274
+ } catch (err) {
275
+ process.stderr.write("Browser login failed:\n");
276
+ printError(err, false);
277
+ process.exitCode = 1;
278
+ return;
279
+ }
280
+ }
191
281
  }
192
- const apiUrl = resolveConfig({ apiUrl: globals.apiUrl }, process.env).apiUrl;
193
282
  try {
194
283
  await new AnaellaClient({ apiKey: key, baseUrl: apiUrl }).listChannels();
195
284
  } catch (err) {
@@ -214,4 +303,8 @@ program.command("posts").description("List recent posts").option("--limit <n>",
214
303
  );
215
304
  program.command("get <id>").description("Get one post by id").action((id, _opts, command) => withClient(command, (c) => cmdGet(c, id)));
216
305
  program.command("delete <id>").description("Delete a draft or cancel a scheduled post").action((id, _opts, command) => withClient(command, (c) => cmdDelete(c, id)));
306
+ program.command("analytics").description("Organization analytics, or one post with --post").option("--post <id>", "post id (omit for org-wide analytics)").option("--period <p>", "24h | 7d | 30d | 90d | 1y").action((opts, command) => withClient(command, (c) => cmdAnalytics(c, opts)));
307
+ program.command("upload [files...]").description("Upload local media files, or register public URLs with --url").option("--url <url>", "public media URL to register (repeatable)", collect, []).action(
308
+ (files, opts, command) => withClient(command, (c) => cmdUpload(c, { files, url: opts.url }), ["id", "url", "type"])
309
+ );
217
310
  program.parseAsync(process.argv);
package/package.json CHANGED
@@ -1,12 +1,29 @@
1
1
  {
2
2
  "name": "@anaella/cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Command-line tool for anaella.com — schedule and publish social posts.",
5
5
  "type": "module",
6
- "bin": { "anaella": "dist/index.js" },
7
- "files": ["dist"],
8
- "publishConfig": { "access": "public" },
9
- "scripts": { "build": "tsup", "prepublishOnly": "npm run build", "test": "bun test" },
10
- "dependencies": { "@anaella/client": "^0.1.0", "commander": "^12.0.0" },
11
- "devDependencies": { "tsup": "^8.0.0", "typescript": "^5", "bun-types": "^1.1.0" }
6
+ "bin": {
7
+ "anaella": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "scripts": {
16
+ "build": "tsup",
17
+ "prepublishOnly": "npm run build",
18
+ "test": "bun test"
19
+ },
20
+ "dependencies": {
21
+ "@anaella/client": "^0.1.6",
22
+ "commander": "^12.0.0"
23
+ },
24
+ "devDependencies": {
25
+ "tsup": "^8.0.0",
26
+ "typescript": "^5",
27
+ "@types/node": "^22"
28
+ }
12
29
  }