@zilfu/cli 1.0.2 → 1.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 (4) hide show
  1. package/dist/cli.js +1738 -1646
  2. package/dist/cli.js.map +1 -1
  3. package/package.json +10 -12
  4. package/README.md +0 -61
package/dist/cli.js CHANGED
@@ -1,221 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from 'citty';
3
- import { createZilfuClient, ZilfuApiError } from '@zilfu/sdk';
3
+ import { DEFAULT_API_BASE_URL, createZilfuClient, ZilfuApiError } from '@zilfu/sdk';
4
+ import { existsSync, rmSync, mkdirSync, writeFileSync, chmodSync, readFileSync } from 'fs';
4
5
  import { hostname, homedir } from 'os';
5
6
  import { basename, join } from 'path';
6
- import { existsSync, rmSync, mkdirSync, writeFileSync, chmodSync, readFileSync } from 'fs';
7
7
  import 'buffer';
8
- import { createServer } from 'http';
9
- import { randomBytes, createHash } from 'crypto';
10
8
  import { spawn } from 'child_process';
9
+ import { randomBytes, createHash } from 'crypto';
10
+ import { createServer } from 'http';
11
11
  import { readFile } from 'fs/promises';
12
12
 
13
13
  // package.json
14
- var version = "1.0.2";
15
- function configDir() {
16
- if (process.platform === "win32") {
17
- const appData = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
18
- return join(appData, "zilfu");
19
- }
20
- const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
21
- return join(base, "zilfu");
22
- }
23
- function configPath() {
24
- return join(configDir(), "config.json");
25
- }
26
- function readConfig() {
27
- try {
28
- const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
29
- if (parsed && typeof parsed === "object") {
30
- return parsed;
31
- }
32
- } catch {
33
- }
34
- return {};
35
- }
36
- function writeConfig(config) {
37
- mkdirSync(configDir(), { recursive: true });
38
- const path = configPath();
39
- writeFileSync(path, `${JSON.stringify(config, null, 2)}
40
- `, { mode: 384 });
41
- chmodSync(path, 384);
42
- return path;
43
- }
44
- function clearConfig() {
45
- const path = configPath();
46
- if (existsSync(path)) {
47
- rmSync(path);
48
- return true;
49
- }
50
- return false;
51
- }
52
- var CTRL_C = String.fromCharCode(3);
53
- var CTRL_D = String.fromCharCode(4);
54
- var DEL = String.fromCharCode(127);
55
- var BACKSPACE = String.fromCharCode(8);
56
- var SUBMIT = /* @__PURE__ */ new Set(["\r", "\n", CTRL_D]);
57
- var DELETE = /* @__PURE__ */ new Set([DEL, BACKSPACE]);
58
- function promptSecret(label) {
59
- return new Promise((resolve) => {
60
- const { stdin, stdout } = process;
61
- stdout.write(label);
62
- stdin.setRawMode(true);
63
- stdin.resume();
64
- let input = "";
65
- const finish = () => {
66
- stdin.setRawMode(false);
67
- stdin.pause();
68
- stdin.removeListener("data", onData);
69
- stdout.write("\n");
70
- };
71
- const onData = (chunk) => {
72
- for (const char of chunk.toString("utf8")) {
73
- if (char === CTRL_C) {
74
- finish();
75
- process.exit(130);
76
- }
77
- if (SUBMIT.has(char)) {
78
- finish();
79
- resolve(input);
80
- return;
81
- }
82
- if (DELETE.has(char)) {
83
- input = input.slice(0, -1);
84
- continue;
85
- }
86
- if (char >= " ") {
87
- input += char;
88
- }
89
- }
90
- };
91
- stdin.on("data", onData);
92
- });
93
- }
94
- var TIMEOUT_MS = 5 * 60 * 1e3;
95
- function base64url(buffer) {
96
- return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
97
- }
98
- function createPkce() {
99
- const verifier = base64url(randomBytes(32));
100
- const challenge = base64url(createHash("sha256").update(verifier).digest());
101
- return { verifier, challenge };
102
- }
103
- function webOrigin(baseUrl) {
104
- const url = new URL(baseUrl);
105
- url.pathname = url.pathname.replace(/\/api\/?$/, "/");
106
- return url.toString().replace(/\/$/, "");
107
- }
108
- function openBrowser(url) {
109
- const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
110
- try {
111
- const child = spawn(command, args, { stdio: "ignore", detached: true });
112
- child.on("error", () => {
113
- });
114
- child.unref();
115
- } catch {
116
- }
117
- }
118
- var DONE_PAGE = '<!doctype html><meta charset=utf-8><title>Zilfu CLI</title><body style="font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0"><p>Authorization complete. You can close this tab and return to your terminal.</p>';
119
- function loginViaBrowser(baseUrl) {
120
- const origin = webOrigin(baseUrl);
121
- const { verifier, challenge } = createPkce();
122
- const state = randomBytes(16).toString("hex");
123
- return new Promise((resolve, reject) => {
124
- const server = createServer((req, res) => {
125
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
126
- if (url.pathname !== "/callback") {
127
- res.writeHead(204).end();
128
- return;
129
- }
130
- res.writeHead(200, { "content-type": "text/html" }).end(DONE_PAGE);
131
- const error = url.searchParams.get("error");
132
- if (error) {
133
- settle(reject, new Error(`Authorization was denied (${error}).`));
134
- return;
135
- }
136
- if (url.searchParams.get("state") !== state) {
137
- settle(reject, new Error("State mismatch \u2014 aborting for safety."));
138
- return;
139
- }
140
- const code = url.searchParams.get("code");
141
- if (!code) {
142
- settle(reject, new Error("No authorization code received."));
143
- return;
144
- }
145
- exchange(origin, code, verifier).then(
146
- (token) => settle(resolve, token),
147
- (err) => settle(reject, err)
148
- );
149
- });
150
- const timer = setTimeout(() => {
151
- settle(reject, new Error("Timed out waiting for browser authorization."));
152
- }, TIMEOUT_MS);
153
- function settle(fn, value) {
154
- clearTimeout(timer);
155
- server.close();
156
- fn(value);
157
- }
158
- server.on("error", (err) => settle(reject, err));
159
- server.listen(0, "127.0.0.1", () => {
160
- const { port } = server.address();
161
- const redirectUri = `http://127.0.0.1:${port}/callback`;
162
- const authorizeUrl = `${origin}/cli/authorize?${new URLSearchParams({
163
- redirect_uri: redirectUri,
164
- state,
165
- code_challenge: challenge,
166
- name: `zilfu-cli (${hostname()})`
167
- }).toString()}`;
168
- process.stdout.write(
169
- `Opening your browser to authorize access:
170
- ${authorizeUrl}
171
-
172
- Waiting for authorization\u2026
173
- `
174
- );
175
- openBrowser(authorizeUrl);
176
- });
177
- });
178
- }
179
- async function exchange(origin, code, verifier) {
180
- const res = await fetch(`${origin}/cli/token`, {
181
- method: "POST",
182
- headers: { "content-type": "application/json", accept: "application/json" },
183
- body: JSON.stringify({ code, code_verifier: verifier })
184
- });
185
- if (!res.ok) {
186
- throw new Error(`Token exchange failed (HTTP ${res.status}).`);
187
- }
188
- const body = await res.json();
189
- if (!body.token) {
190
- throw new Error("Token exchange returned no token.");
191
- }
192
- return body.token;
193
- }
194
- var MissingTokenError = class extends Error {
195
- constructor() {
196
- super(
197
- "No API token found.\nRun `zilfu login`, set ZILFU_TOKEN, or pass --token <token>.\nCopy your API key from Settings \u2192 AI & API."
198
- );
199
- this.name = "MissingTokenError";
200
- }
201
- };
202
- function resolveToken(flags) {
203
- return flags.token ?? process.env.ZILFU_TOKEN ?? readConfig().token;
204
- }
205
- function resolveBaseUrl(flags) {
206
- return flags.baseUrl ?? process.env.ZILFU_BASE_URL ?? readConfig().baseUrl;
207
- }
208
- function resolveClient(flags, opts = {}) {
209
- const token = resolveToken(flags);
210
- if (!token && opts.requireToken !== false) {
211
- throw new MissingTokenError();
212
- }
213
- return createZilfuClient({
214
- token: token ?? "",
215
- baseUrl: resolveBaseUrl(flags),
216
- headers: { "X-Zilfu-Client": "cli" }
217
- });
218
- }
14
+ var version = "1.2.0";
219
15
  function formatCell(value) {
220
16
  if (value === null || value === void 0) {
221
17
  return "";
@@ -238,15 +34,36 @@ function printTable(rows, columns) {
238
34
  return;
239
35
  }
240
36
  const cols = columns ?? inferColumns(rows);
241
- const widths = cols.map(
242
- (col) => Math.max(col.length, ...rows.map((row) => formatCell(row[col]).length))
243
- );
244
- const line = (cells) => `${cells.map((cell, i) => cell.padEnd(widths[i])).join(" ").replace(/\s+$/, "")}
37
+ const widths = cols.map((col) => {
38
+ return Math.max(
39
+ col.length,
40
+ ...rows.map((row) => {
41
+ return formatCell(row[col]).length;
42
+ })
43
+ );
44
+ });
45
+ const line = (cells) => {
46
+ return `${cells.map((cell, i) => {
47
+ return cell.padEnd(widths[i]);
48
+ }).join(" ").replace(/\s+$/, "")}
245
49
  `;
50
+ };
246
51
  process.stdout.write(line(cols));
247
- process.stdout.write(line(cols.map((_, i) => "-".repeat(widths[i]))));
52
+ process.stdout.write(
53
+ line(
54
+ cols.map((_, i) => {
55
+ return "-".repeat(widths[i]);
56
+ })
57
+ )
58
+ );
248
59
  for (const row of rows) {
249
- process.stdout.write(line(cols.map((col) => formatCell(row[col]))));
60
+ process.stdout.write(
61
+ line(
62
+ cols.map((col) => {
63
+ return formatCell(row[col]);
64
+ })
65
+ )
66
+ );
250
67
  }
251
68
  }
252
69
  function printRecord(record) {
@@ -255,7 +72,11 @@ function printRecord(record) {
255
72
  process.stdout.write("(empty)\n");
256
73
  return;
257
74
  }
258
- const width = Math.max(...keys.map((key) => key.length));
75
+ const width = Math.max(
76
+ ...keys.map((key) => {
77
+ return key.length;
78
+ })
79
+ );
259
80
  for (const key of keys) {
260
81
  process.stdout.write(`${key.padEnd(width)} ${formatCell(record[key])}
261
82
  `);
@@ -299,40 +120,104 @@ function printError(error) {
299
120
  }
300
121
  return process.exit(1);
301
122
  }
302
-
303
- // src/commands/_shared.ts
304
- var globalArgs = {
305
- token: {
306
- type: "string",
307
- description: "API token (overrides ZILFU_TOKEN and stored config)"
308
- },
309
- "base-url": {
310
- type: "string",
311
- description: "API base URL (overrides ZILFU_BASE_URL and stored config)"
312
- },
313
- json: {
314
- type: "boolean",
315
- description: "Output raw JSON instead of a table"
123
+ function configDir() {
124
+ if (process.platform === "win32") {
125
+ const appData = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
126
+ return join(appData, "zilfu");
316
127
  }
317
- };
318
- function readString(value) {
319
- return typeof value === "string" && value.length > 0 ? value : void 0;
320
- }
321
- function clientFor(args, opts) {
322
- return resolveClient(
323
- { token: readString(args["token"]), baseUrl: readString(args["base-url"]) },
324
- opts
325
- );
128
+ const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
129
+ return join(base, "zilfu");
326
130
  }
327
- function wantsJson(args) {
328
- return args["json"] === true;
131
+ function configPath() {
132
+ return join(configDir(), "config.json");
329
133
  }
330
- function toId(value, label) {
331
- const id = Number(value);
332
- if (!Number.isInteger(id) || id <= 0) {
333
- throw new Error(`Invalid ${label} id: ${String(value)}`);
334
- }
335
- return id;
134
+ function readConfig() {
135
+ try {
136
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
137
+ if (parsed && typeof parsed === "object") {
138
+ return parsed;
139
+ }
140
+ } catch {
141
+ }
142
+ return {};
143
+ }
144
+ function writeConfig(config) {
145
+ mkdirSync(configDir(), { recursive: true });
146
+ const path = configPath();
147
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}
148
+ `, { mode: 384 });
149
+ chmodSync(path, 384);
150
+ return path;
151
+ }
152
+ function clearConfig() {
153
+ const path = configPath();
154
+ if (existsSync(path)) {
155
+ rmSync(path);
156
+ return true;
157
+ }
158
+ return false;
159
+ }
160
+
161
+ // src/client.ts
162
+ var MissingTokenError = class extends Error {
163
+ constructor() {
164
+ super(
165
+ "No API token found.\nRun `zilfu login`, set ZILFU_TOKEN, or pass --token <token>.\nCopy your API key from Settings \u2192 AI & API."
166
+ );
167
+ this.name = "MissingTokenError";
168
+ }
169
+ };
170
+ function resolveToken(flags) {
171
+ return flags.token ?? process.env.ZILFU_TOKEN ?? readConfig().token;
172
+ }
173
+ function resolveBaseUrl(flags) {
174
+ return flags.baseUrl ?? process.env.ZILFU_BASE_URL ?? readConfig().baseUrl;
175
+ }
176
+ function resolveClient(flags, opts = {}) {
177
+ const token = resolveToken(flags);
178
+ if (!token && opts.requireToken !== false) {
179
+ throw new MissingTokenError();
180
+ }
181
+ return createZilfuClient({
182
+ token: token ?? "",
183
+ baseUrl: resolveBaseUrl(flags),
184
+ headers: { "X-Zilfu-Client": "cli" }
185
+ });
186
+ }
187
+
188
+ // src/commands/_shared.ts
189
+ var globalArgs = {
190
+ token: {
191
+ type: "string",
192
+ description: "API token (overrides ZILFU_TOKEN and stored config)"
193
+ },
194
+ "base-url": {
195
+ type: "string",
196
+ description: "API base URL (overrides ZILFU_BASE_URL and stored config)"
197
+ },
198
+ json: {
199
+ type: "boolean",
200
+ description: "Output raw JSON instead of a table"
201
+ }
202
+ };
203
+ function readString(value) {
204
+ return typeof value === "string" && value.length > 0 ? value : void 0;
205
+ }
206
+ function clientFor(args, opts) {
207
+ return resolveClient(
208
+ { token: readString(args["token"]), baseUrl: readString(args["base-url"]) },
209
+ opts
210
+ );
211
+ }
212
+ function wantsJson(args) {
213
+ return args["json"] === true;
214
+ }
215
+ function toId(value, label) {
216
+ const id = Number(value);
217
+ if (!Number.isInteger(id) || id <= 0) {
218
+ throw new Error(`Invalid ${label} id: ${String(value)}`);
219
+ }
220
+ return id;
336
221
  }
337
222
  function toSpaceId(value) {
338
223
  return toId(value, "space");
@@ -342,7 +227,11 @@ function toList(value) {
342
227
  return [];
343
228
  }
344
229
  const values = Array.isArray(value) ? value : [value];
345
- return values.map((entry) => String(entry)).filter((entry) => entry.length > 0);
230
+ return values.map((entry) => {
231
+ return String(entry);
232
+ }).filter((entry) => {
233
+ return entry.length > 0;
234
+ });
346
235
  }
347
236
  function toEpochMs(value) {
348
237
  const raw = String(value);
@@ -361,10 +250,8 @@ Pass epoch milliseconds or an ISO 8601 timestamp, e.g. 2026-08-14T18:00:00Z.`
361
250
  function toDate(value, flag) {
362
251
  const raw = String(value);
363
252
  if (Number.isNaN(Date.parse(raw))) {
364
- throw new Error(
365
- `Invalid --${flag} value: ${raw}
366
- Pass a date, for example 2026-07-01.`
367
- );
253
+ throw new Error(`Invalid --${flag} value: ${raw}
254
+ Pass a date, for example 2026-07-01.`);
368
255
  }
369
256
  return raw;
370
257
  }
@@ -378,7 +265,9 @@ var DAY_NUMBERS = {
378
265
  sun: 7
379
266
  };
380
267
  function toDaysOfWeek(value) {
381
- const tokens = toList(value).flatMap((entry) => entry.split(","));
268
+ const tokens = toList(value).flatMap((entry) => {
269
+ return entry.split(",");
270
+ });
382
271
  const days = /* @__PURE__ */ new Set();
383
272
  for (const token of tokens) {
384
273
  const raw = token.trim().toLowerCase();
@@ -397,12 +286,14 @@ Use 1-7 (1 = Monday, 7 = Sunday) or names like mon,wed,fri.`
397
286
  if (days.size === 0) {
398
287
  throw new Error("Pass at least one day via --days.");
399
288
  }
400
- return [...days].sort((a, b) => a - b);
289
+ return [...days].toSorted((a, b) => {
290
+ return a - b;
291
+ });
401
292
  }
402
293
  function toOptionalBool(args, name, rawArgs) {
403
- const mentioned = rawArgs.some(
404
- (arg) => arg === `--${name}` || arg === `--no-${name}` || arg.startsWith(`--${name}=`)
405
- );
294
+ const mentioned = rawArgs.some((arg) => {
295
+ return arg === `--${name}` || arg === `--no-${name}` || arg.startsWith(`--${name}=`);
296
+ });
406
297
  return mentioned ? args[name] === true : void 0;
407
298
  }
408
299
  async function guard(fn) {
@@ -413,1575 +304,1776 @@ async function guard(fn) {
413
304
  }
414
305
  }
415
306
 
416
- // src/commands/login.ts
417
- var login = defineCommand({
418
- meta: { name: "login", description: "Authenticate and store your API token" },
419
- args: {
420
- web: {
421
- type: "boolean",
422
- description: "Authorize in the browser instead of pasting a token"
423
- },
424
- token: {
425
- type: "string",
426
- description: "API token (skips the interactive prompt)"
427
- },
428
- "base-url": {
429
- type: "string",
430
- description: "API base URL to store (defaults to the production API)"
431
- }
432
- },
433
- run: ({ args }) => guard(async () => {
434
- const baseUrl = typeof args["base-url"] === "string" && args["base-url"] ? args["base-url"] : process.env.ZILFU_BASE_URL;
435
- const token = args["web"] === true ? await loginViaBrowser(baseUrl ?? "https://zilfu.app/api") : await promptToken(typeof args["token"] === "string" ? args["token"] : "");
436
- const api = createZilfuClient({ token, baseUrl });
437
- const res = await api.session.get();
438
- const user = res.data?.data;
439
- const path = writeConfig({ token, ...baseUrl ? { baseUrl } : {} });
440
- process.stdout.write(
441
- `Logged in as ${user?.name ?? "?"} <${user?.email ?? "?"}>.
442
- Credentials stored at ${path}
443
- `
444
- );
445
- })
446
- });
447
- async function promptToken(flagToken) {
448
- let token = flagToken;
449
- if (!token) {
450
- if (!process.stdin.isTTY) {
451
- throw new Error(
452
- "No token provided. Pass --token <token>, use --web, or run in an interactive terminal."
453
- );
454
- }
455
- process.stdout.write("Copy your API key from Settings -> AI & API.\n");
456
- token = await promptSecret("Zilfu API key: ");
457
- }
458
- token = token.trim();
459
- if (!token) {
460
- throw new Error("A token is required.");
461
- }
462
- return token;
463
- }
464
- var logout = defineCommand({
465
- meta: { name: "logout", description: "Remove stored credentials" },
466
- run: () => guard(() => {
467
- const removed = clearConfig();
468
- process.stdout.write(
469
- removed ? "Logged out.\n" : "No stored credentials found.\n"
470
- );
471
- })
472
- });
473
- var whoami = defineCommand({
474
- meta: { name: "whoami", description: "Show the authenticated user" },
475
- args: { ...globalArgs },
476
- run: ({ args }) => guard(async () => {
477
- const api = clientFor(args);
478
- const res = await api.session.get();
479
- print(res.data?.data ?? {}, { json: wantsJson(args) });
480
- })
481
- });
482
- var health = defineCommand({
483
- meta: { name: "health", description: "Check the Zilfu API health" },
484
- args: { ...globalArgs },
485
- run: ({ args }) => guard(async () => {
486
- const api = clientFor(args, { requireToken: false });
487
- const res = await api.health.check();
488
- print(res.data ?? {}, { json: wantsJson(args) });
489
- })
490
- });
307
+ // src/commands/accounts.ts
491
308
  var list = defineCommand({
492
- meta: { name: "list", description: "List spaces you can access" },
493
- args: { ...globalArgs },
494
- run: ({ args }) => guard(async () => {
495
- const api = clientFor(args);
496
- const res = await api.spaces.list();
497
- print(res.data?.data ?? [], {
498
- json: wantsJson(args),
499
- columns: ["id", "name", "timezone"]
500
- });
501
- })
502
- });
503
- var spaces = defineCommand({
504
- meta: { name: "spaces", description: "Manage spaces" },
505
- subCommands: { list }
506
- });
507
- var list2 = defineCommand({
508
309
  meta: { name: "list", description: "List connected accounts in a space" },
509
310
  args: {
510
311
  ...globalArgs,
511
312
  space: { type: "string", required: true, description: "The space id" }
512
313
  },
513
- run: ({ args }) => guard(async () => {
514
- const space = toSpaceId(args["space"]);
515
- const api = clientFor(args);
516
- const res = await api.accounts.list({ path: { space } });
517
- print(res.data?.data ?? [], {
518
- json: wantsJson(args),
519
- columns: ["id", "social", "display_name", "handler", "is_active"]
314
+ run: ({ args }) => {
315
+ return guard(async () => {
316
+ const space = toSpaceId(args["space"]);
317
+ const api = clientFor(args);
318
+ const res = await api.accounts.list({ path: { space } });
319
+ print(res.data?.data ?? [], {
320
+ json: wantsJson(args),
321
+ columns: ["id", "social", "display_name", "handler", "is_active"]
322
+ });
520
323
  });
521
- })
324
+ }
522
325
  });
523
326
  var accounts = defineCommand({
524
327
  meta: { name: "accounts", description: "Manage connected accounts" },
525
- subCommands: { list: list2 }
328
+ subCommands: { list }
526
329
  });
527
-
528
- // src/mime.ts
529
- var MIME_BY_EXTENSION = {
530
- jpg: "image/jpeg",
531
- jpeg: "image/jpeg",
532
- png: "image/png",
533
- webp: "image/webp",
534
- mp4: "video/mp4",
535
- mov: "video/quicktime"
536
- };
537
- function extensionOf(value) {
538
- const withoutQuery = value.split(/[?#]/)[0] ?? "";
539
- const lastDot = withoutQuery.lastIndexOf(".");
540
- return lastDot === -1 ? "" : withoutQuery.slice(lastDot + 1).toLowerCase();
330
+ var MIN_PER_PAGE = 10;
331
+ var MAX_PER_PAGE = 100;
332
+ var NUMBER = new Intl.NumberFormat("en-US");
333
+ function formatValue(value) {
334
+ return value === null || value === void 0 ? "-" : NUMBER.format(value);
541
335
  }
542
- function mimeForPath(path) {
543
- const mime = MIME_BY_EXTENSION[extensionOf(path)];
544
- if (!mime) {
545
- throw new Error(
546
- `Unsupported file type: ${path}
547
- Zilfu accepts ${Object.keys(MIME_BY_EXTENSION).join(", ")}.`
548
- );
336
+ function formatDelta(value) {
337
+ if (value === null || value === void 0) {
338
+ return "-";
549
339
  }
550
- return mime;
551
- }
552
- function mediaTypeForMime(mime) {
553
- return mime.startsWith("video/") ? "video" : "image";
340
+ return `${value > 0 ? "+" : ""}${NUMBER.format(value)}`;
554
341
  }
555
- function mediaTypeForUrl(url) {
556
- const mime = MIME_BY_EXTENSION[extensionOf(url)];
557
- if (!mime) {
558
- throw new Error(
559
- `Cannot tell whether this is an image or a video: ${url}
560
- Use a URL ending in ${Object.keys(MIME_BY_EXTENSION).join(", ")}, or upload the file with \`zilfu media upload\` first.`
561
- );
342
+ function formatChange(value, unit) {
343
+ if (value === null) {
344
+ return "-";
562
345
  }
563
- return mediaTypeForMime(mime);
346
+ const sign = value > 0 ? "+" : "";
347
+ if (unit === "percent") {
348
+ return `${sign}${value}%`;
349
+ }
350
+ if (unit === "percentage_points") {
351
+ return `${sign}${value} pp`;
352
+ }
353
+ return `${sign}${value} ${unit}`;
564
354
  }
565
-
566
- // src/commands/posts.ts
567
- var STATUS_LABELS = {
568
- 0: "scheduled",
569
- 1: "published",
570
- 2: "error",
571
- 3: "draft",
572
- 4: "processing",
573
- 5: "pending_approval"
574
- };
575
- var CONTENT_LIMITS = {
576
- threads: 500,
577
- x: 280,
578
- instagram: 2200,
579
- linkedin: 3e3,
580
- tiktok: 2200,
581
- facebook: 63206,
582
- pinterest: 500
583
- };
584
- var COMMENT_LIMITS = {
585
- threads: 500,
586
- instagram: 2200,
587
- facebook: 8e3,
588
- linkedin: 1250
589
- };
590
- var COMMENT_FALLBACK_LIMIT = 500;
591
- var REPLY_ENABLED = /* @__PURE__ */ new Set(["threads", "instagram", "facebook"]);
592
- var REPLY_CAPABLE = /* @__PURE__ */ new Set([...REPLY_ENABLED, "linkedin"]);
593
- var MEDIA_REQUIRED = /* @__PURE__ */ new Set(["instagram", "tiktok", "pinterest"]);
594
- var PRIVACY_LEVELS = [
595
- "PUBLIC_TO_EVERYONE",
596
- "MUTUAL_FOLLOW_FRIENDS",
597
- "FOLLOWER_OF_CREATOR",
598
- "SELF_ONLY"
599
- ];
600
- var MAX_COMMENT_DELAY = 10080;
601
- var PIN_TITLE_MAX = 100;
602
- var MAX_PER_PAGE = 200;
603
- function statusLabel(status) {
604
- return STATUS_LABELS[status] ?? String(status);
355
+ function formatRate(value) {
356
+ return value === null ? "-" : `${value}%`;
605
357
  }
606
- function charCount(value) {
607
- return [...value].length;
358
+ function formatStatus(status, reason) {
359
+ return reason ? `${status} (${reason})` : status;
608
360
  }
609
- function readString2(value) {
610
- if (value === void 0 || value === null) {
611
- return void 0;
612
- }
613
- const raw = String(value);
614
- return raw.length > 0 ? raw : void 0;
361
+ function formatCollection(collection) {
362
+ return formatStatus(collection.state, collection.reason);
615
363
  }
616
- function readUrl(value, flag) {
617
- const raw = readString2(value);
618
- if (raw !== void 0 && !/^https?:\/\//i.test(raw)) {
619
- throw new Error(`--${flag} must be an http(s) URL: ${raw}`);
364
+ function describeCollection(collection) {
365
+ const parts = [
366
+ formatCollection(collection),
367
+ `last collected ${collection.last_collected_at ?? "never"}`,
368
+ `every ${collection.cadence_hours}h over ${collection.polling_window_days} days`
369
+ ];
370
+ if (collection.remedy) {
371
+ parts.push(`remedy: ${collection.remedy}`);
620
372
  }
621
- return raw;
373
+ return parts.join(", ");
622
374
  }
623
- function camelize(name) {
624
- return name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
375
+ function formatAccount(account2) {
376
+ const handle = account2.handler ? ` @${account2.handler}` : "";
377
+ return `${account2.display_name}${handle} (${account2.social}, id ${account2.id})`;
625
378
  }
626
- function repeatedValues(args, rawArgs, name) {
627
- const names = /* @__PURE__ */ new Set([name, camelize(name)]);
628
- const values = [];
629
- for (let index = 0; index < rawArgs.length; index += 1) {
630
- const token = rawArgs[index];
631
- if (token === "--") {
632
- break;
633
- }
634
- if (!token.startsWith("--")) {
635
- continue;
636
- }
637
- const separator = token.indexOf("=");
638
- const flag = separator === -1 ? token.slice(2) : token.slice(2, separator);
639
- if (!names.has(flag)) {
640
- continue;
641
- }
642
- if (separator !== -1) {
643
- values.push(token.slice(separator + 1));
644
- continue;
645
- }
646
- const next = rawArgs[index + 1];
647
- if (next !== void 0 && !next.startsWith("--")) {
648
- values.push(next);
649
- index += 1;
650
- }
379
+ function formatRange(range) {
380
+ return `${range.from} to ${range.to} (${range.days} days, ${range.timezone})`;
381
+ }
382
+ function oneLine(text, max) {
383
+ const flat = text.replace(/\s+/g, " ").trim();
384
+ return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
385
+ }
386
+ function heading(title) {
387
+ process.stdout.write(`
388
+ ${title}
389
+
390
+ `);
391
+ }
392
+ function windowQuery(args) {
393
+ const query = {};
394
+ if (args["from"] !== void 0) {
395
+ query.from = toDate(args["from"], "from");
396
+ }
397
+ if (args["to"] !== void 0) {
398
+ query.to = toDate(args["to"], "to");
651
399
  }
652
- return values.length > 1 ? values.filter((value) => value.length > 0) : toList(args[name]);
400
+ return query;
653
401
  }
654
- function parsePairs(entries, flag, example) {
655
- return entries.map((entry) => {
656
- const separator = entry.indexOf("=");
657
- if (separator <= 0) {
658
- throw new Error(
659
- `Invalid --${flag} value: ${entry}
660
- Use --${flag} <key>=<value>, for example ${example}`
661
- );
662
- }
663
- return [entry.slice(0, separator), entry.slice(separator + 1)];
664
- });
402
+ function describeWindow(query) {
403
+ if (query.from && query.to) {
404
+ return `${query.from} to ${query.to} (requested)`;
405
+ }
406
+ if (query.from) {
407
+ return `from ${query.from} (requested)`;
408
+ }
409
+ if (query.to) {
410
+ return `up to ${query.to} (requested)`;
411
+ }
412
+ return "last 7 days in the organization timezone (API default)";
665
413
  }
666
- function toStatus(value) {
667
- const raw = value.trim().toLowerCase().replace(/-/g, "_");
668
- const match = Object.entries(STATUS_LABELS).find(
669
- ([number, label]) => label === raw || number === raw
670
- );
671
- if (!match) {
672
- throw new Error(
673
- `Invalid --status value: ${value}
674
- Use one of: ${Object.entries(STATUS_LABELS).map(([number, label]) => `${label} (${number})`).join(", ")}.`
675
- );
414
+ function toDir(value) {
415
+ const dir = String(value).toLowerCase();
416
+ if (dir !== "asc" && dir !== "desc") {
417
+ throw new Error(`Invalid --dir value: ${String(value)}
418
+ Use asc or desc.`);
676
419
  }
677
- return Number(match[0]);
420
+ return dir;
678
421
  }
679
- function toCount(value, flag, max) {
680
- const count = Number(value);
681
- if (!Number.isInteger(count) || count < 1 || max !== void 0 && count > max) {
422
+ function toPerPage(value) {
423
+ const perPage = Number(value);
424
+ if (!Number.isInteger(perPage) || perPage < MIN_PER_PAGE || perPage > MAX_PER_PAGE) {
682
425
  throw new Error(
683
- `Invalid --${flag} value: ${String(value)}
684
- Pass a whole number ${max === void 0 ? "of 1 or more" : `between 1 and ${max}`}.`
426
+ `Invalid --per-page value: ${String(value)}
427
+ Use a whole number between ${MIN_PER_PAGE} and ${MAX_PER_PAGE}.`
685
428
  );
686
429
  }
687
- return count;
430
+ return perPage;
688
431
  }
689
- var list3 = defineCommand({
690
- meta: { name: "list", description: "List posts in a space" },
432
+ function toPage(value) {
433
+ const page = Number(value);
434
+ if (!Number.isInteger(page) || page < 1) {
435
+ throw new Error(`Invalid --page value: ${String(value)}
436
+ Pages start at 1.`);
437
+ }
438
+ return page;
439
+ }
440
+ var windowArgs = {
441
+ from: {
442
+ type: "string",
443
+ description: "Window start, e.g. 2026-07-01 (default: 6 days ago)"
444
+ },
445
+ to: {
446
+ type: "string",
447
+ description: "Window end, e.g. 2026-07-31 (default: today, organization timezone)"
448
+ }
449
+ };
450
+ var overview = defineCommand({
451
+ meta: {
452
+ name: "overview",
453
+ description: "One analytics summary row per account in a space"
454
+ },
691
455
  args: {
692
456
  ...globalArgs,
693
457
  space: { type: "string", required: true, description: "The space id" },
694
- status: {
695
- type: "string",
696
- description: "Filter by status \u2014 name or number (scheduled, published, error, draft, processing, pending_approval). Repeat to match any of several"
697
- },
698
- account: {
699
- type: "string",
700
- description: "Filter by account id (repeat to match any of several)"
701
- },
702
- from: {
703
- type: "string",
704
- description: "Only posts scheduled or published on/after this date"
705
- },
706
- to: {
707
- type: "string",
708
- description: "Only posts scheduled or published on/before this date"
709
- },
710
- "per-page": {
711
- type: "string",
712
- description: `Results per page, 1-${MAX_PER_PAGE} (default 15)`
713
- },
714
- page: {
715
- type: "string",
716
- description: "Page of results to fetch (default 1)"
717
- }
458
+ ...windowArgs
718
459
  },
719
- run: ({ args, rawArgs }) => guard(async () => {
720
- const space = toSpaceId(args["space"]);
721
- const statuses = repeatedValues(args, rawArgs, "status").map(toStatus);
722
- const accountIds = repeatedValues(args, rawArgs, "account").map(
723
- (id) => toId(id, "account")
724
- );
725
- const query = {};
726
- if (statuses.length === 1) {
727
- query.status = statuses[0];
728
- } else if (statuses.length > 1) {
729
- query["statuses[]"] = statuses;
730
- }
731
- if (accountIds.length === 1) {
732
- query.account_id = accountIds[0];
733
- } else if (accountIds.length > 1) {
734
- query["account_ids[]"] = accountIds;
735
- }
736
- if (args["from"] !== void 0) {
737
- query.from = toDate(args["from"], "from");
738
- }
739
- if (args["to"] !== void 0) {
740
- query.to = toDate(args["to"], "to");
741
- }
742
- if (args["per-page"] !== void 0) {
743
- query.per_page = toCount(args["per-page"], "per-page", MAX_PER_PAGE);
744
- }
745
- if (args["page"] !== void 0) {
746
- query.page = toCount(args["page"], "page");
747
- }
748
- const api = clientFor(args);
749
- const res = await api.posts.list({ path: { space }, query });
750
- const posts3 = res.data?.data ?? [];
751
- if (wantsJson(args)) {
752
- print(res.data ?? { data: [] }, { json: true });
753
- return;
754
- }
755
- const rows = posts3.map((post) => ({
756
- id: post.id,
757
- account_id: post.account_id,
758
- status: statusLabel(post.status),
759
- scheduled_at: post.scheduled_at,
760
- published_at: post.published_at
761
- }));
762
- print(rows, {
763
- columns: [
764
- "id",
765
- "account_id",
766
- "status",
767
- "scheduled_at",
768
- "published_at"
769
- ]
770
- });
771
- const meta = res.data?.meta;
772
- if (meta && meta.total > 0) {
773
- const shown = meta.from !== null && meta.to !== null ? `${meta.from}-${meta.to}` : String(posts3.length);
774
- const more = meta.current_page < meta.last_page ? `. Pass --page ${meta.current_page + 1} for the next page` : "";
775
- process.stdout.write(`Showing ${shown} of ${meta.total}${more}.
460
+ run: ({ args }) => {
461
+ return guard(async () => {
462
+ const space = toSpaceId(args["space"]);
463
+ const query = windowQuery(args);
464
+ const api = clientFor(args);
465
+ const res = await api.analytics.list({ path: { space }, query });
466
+ const summaries = res.data?.data ?? [];
467
+ if (wantsJson(args)) {
468
+ print(summaries, { json: true });
469
+ return;
470
+ }
471
+ process.stdout.write(`Window ${describeWindow(query)}
472
+
776
473
  `);
777
- }
778
- })
779
- });
780
- async function resolveAccounts(api, space, accountIds) {
781
- const res = await api.accounts.list({ path: { space } });
782
- const accounts2 = res.data?.data ?? [];
783
- const accountById = new Map(accounts2.map((a) => [a.id, a]));
784
- for (const accountId of accountIds) {
785
- if (!accountById.has(accountId)) {
786
- const known = accounts2.map((a) => a.id).join(", ");
787
- throw new Error(
788
- `Account ${accountId} is not in space ${space}.
789
- ` + (known ? `Accounts in this space: ${known}` : "This space has no connected accounts.")
474
+ if (summaries.length === 0) {
475
+ process.stdout.write("No accounts in this space.\n");
476
+ return;
477
+ }
478
+ print(
479
+ summaries.map((row) => {
480
+ return {
481
+ id: row.account.id,
482
+ account: row.account.display_name,
483
+ social: row.account.social,
484
+ collection: formatCollection(row.collection),
485
+ posts: formatValue(row.coverage?.posts_in_range),
486
+ interactions: formatValue(row.interactions?.value),
487
+ remedy: row.collection.remedy ?? ""
488
+ };
489
+ }),
490
+ {
491
+ columns: ["id", "account", "social", "collection", "posts", "interactions", "remedy"]
492
+ }
790
493
  );
791
- }
494
+ const totals = summaries.flatMap((row) => {
495
+ return row.totals.map((total) => {
496
+ return {
497
+ account: row.account.display_name,
498
+ metric: total.label,
499
+ unit: total.unit,
500
+ value: formatValue(total.value),
501
+ previous: formatValue(total.previous),
502
+ change: formatChange(total.change_pct, total.change_unit),
503
+ note: total.reason ?? ""
504
+ };
505
+ });
506
+ });
507
+ if (totals.length > 0) {
508
+ heading("Totals");
509
+ print(totals, {
510
+ columns: ["account", "metric", "unit", "value", "previous", "change", "note"]
511
+ });
512
+ }
513
+ const rates = summaries.flatMap((row) => {
514
+ return row.rates.map((rate) => {
515
+ return {
516
+ account: row.account.display_name,
517
+ rate: rate.label,
518
+ value: formatRate(rate.value),
519
+ per_post: formatRate(rate.per_post_mean),
520
+ previous: formatRate(rate.previous),
521
+ change: formatChange(rate.change_pp, rate.change_unit),
522
+ note: rate.reason ?? ""
523
+ };
524
+ });
525
+ });
526
+ if (rates.length > 0) {
527
+ heading("Rates");
528
+ print(rates, {
529
+ columns: ["account", "rate", "value", "per_post", "previous", "change", "note"]
530
+ });
531
+ }
532
+ });
792
533
  }
793
- const stale = accountIds.map((id) => accountById.get(id)).filter((a) => !a.is_active || Boolean(a.disconnected_at));
794
- if (stale.length > 0) {
795
- const many = stale.length > 1;
796
- process.stderr.write(
797
- `Note: account${many ? "s" : ""} ${stale.map((a) => `${a.id} (${a.social})`).join(", ")} ${many ? "are" : "is"} disconnected; publishing will fail until reconnected.
798
- `
534
+ });
535
+ function printReport(report) {
536
+ const header = {
537
+ account: formatAccount(report.account),
538
+ range: formatRange(report.range),
539
+ previous: `${report.range.previous_from} to ${report.range.previous_to}`,
540
+ collection: describeCollection(report.collection),
541
+ coverage: report.coverage ? `${report.coverage.posts_in_range} posts (${report.coverage.posts_imported} imported) on ${report.coverage.days_with_posts} of ${report.coverage.days_in_range} days` : "-",
542
+ contract: report.contract
543
+ };
544
+ if (report.basis) {
545
+ header["basis"] = report.basis.comparison_immature ? `${report.basis.values} (comparison window is still maturing)` : report.basis.values;
546
+ header["note"] = report.basis.note;
547
+ }
548
+ print(header);
549
+ if (report.metrics.length === 0) {
550
+ process.stdout.write(
551
+ "\nThis platform has no analytics driver, so there is nothing to report.\n"
799
552
  );
553
+ return;
800
554
  }
801
- return accountById;
802
- }
803
- function parseAccountTexts(entries, accountIds) {
804
- const texts = /* @__PURE__ */ new Map();
805
- for (const [rawId, text] of parsePairs(
806
- entries,
807
- "account-text",
808
- '--account-text 7="Shorter copy for X"'
809
- )) {
810
- const accountId = toId(rawId, "account");
811
- if (!accountIds.includes(accountId)) {
812
- throw new Error(
813
- `--account-text targets account ${accountId}, which was not passed with --account.
814
- Accounts in this call: ${accountIds.join(", ")}`
815
- );
816
- }
817
- if (texts.has(accountId)) {
818
- throw new Error(`--account-text was given twice for account ${accountId}.`);
819
- }
820
- if (text.length === 0) {
821
- throw new Error(`--account-text for account ${accountId} is empty.`);
822
- }
823
- texts.set(accountId, text);
555
+ if (report.totals.length > 0) {
556
+ heading("Totals");
557
+ print(
558
+ report.totals.map((total) => {
559
+ return {
560
+ // The platform's own wording, printed verbatim: Facebook's "Like
561
+ // reactions" and LinkedIn's "Reactions" count different things under
562
+ // the same `likes` key, and only the label says so.
563
+ metric: total.label,
564
+ unit: total.unit,
565
+ value: formatValue(total.value),
566
+ previous: formatValue(total.previous),
567
+ change: formatChange(total.change_pct, total.change_unit),
568
+ note: total.reason ?? ""
569
+ };
570
+ }),
571
+ {
572
+ columns: ["metric", "unit", "value", "previous", "change", "note"]
573
+ }
574
+ );
824
575
  }
825
- return texts;
826
- }
827
- function parseReplyMedia(entries, replyCount) {
828
- const byReply = /* @__PURE__ */ new Map();
829
- for (const [rawIndex, url] of parsePairs(
830
- entries,
831
- "reply-media",
832
- "--reply-media 1=https://\u2026/clip.mp4"
833
- )) {
834
- const index = Number(rawIndex);
835
- if (!Number.isInteger(index) || index < 1 || index > replyCount) {
836
- throw new Error(
837
- `--reply-media ${rawIndex}=\u2026 does not match a reply.
838
- ` + (replyCount === 0 ? "Pass --reply first \u2014 --reply-media attaches media to a reply by its 1-based position." : `Use 1-${replyCount}: the position of the --reply this media belongs to.`)
839
- );
576
+ const interactions = report.interactions;
577
+ if (interactions) {
578
+ heading(interactions.label);
579
+ print({
580
+ value: formatValue(interactions.value),
581
+ previous: formatValue(interactions.previous),
582
+ change: formatChange(interactions.change_pct, interactions.change_unit),
583
+ // At report scope `components` is a list of keys, not key/value pairs,
584
+ // and on a `mixed` source it is a union — adding it up double-counts.
585
+ source: `${interactions.source}${interactions.native ? ", reported natively" : ""}`,
586
+ components: interactions.components.join(", "),
587
+ status: formatStatus(interactions.status, interactions.reason),
588
+ definition: interactions.definition
589
+ });
590
+ }
591
+ if (report.rates.length > 0) {
592
+ heading("Rates");
593
+ print(
594
+ report.rates.map((rate) => {
595
+ return {
596
+ rate: rate.label,
597
+ value: formatRate(rate.value),
598
+ per_post: formatRate(rate.per_post_mean),
599
+ previous: formatRate(rate.previous),
600
+ change: formatChange(rate.change_pp, rate.change_unit),
601
+ over: rate.denominator_label ?? rate.denominator_key,
602
+ note: rate.reason ?? ""
603
+ };
604
+ }),
605
+ {
606
+ columns: ["rate", "value", "per_post", "previous", "change", "over", "note"]
607
+ }
608
+ );
609
+ }
610
+ heading("Metrics");
611
+ print(
612
+ report.metrics.map((metric) => {
613
+ return {
614
+ key: metric.key,
615
+ scope: metric.scope,
616
+ label: metric.label,
617
+ unit: metric.unit,
618
+ role: metric.role,
619
+ window: metric.window_days ?? "",
620
+ status: metric.status,
621
+ note: metric.reason ?? ""
622
+ };
623
+ }),
624
+ {
625
+ columns: ["key", "scope", "label", "unit", "role", "window", "status", "note"]
840
626
  }
841
- const media2 = byReply.get(index) ?? [];
842
- media2.push({ url, type: mediaTypeForUrl(url) });
843
- byReply.set(index, media2);
627
+ );
628
+ const audience = report.audience;
629
+ const latest = audience.latest;
630
+ if (audience.supported && latest) {
631
+ heading(`Audience (as of ${latest.date})`);
632
+ print(
633
+ audience.metrics.map((key) => {
634
+ return {
635
+ metric: audience.labels?.[key] ?? key,
636
+ value: formatValue(latest.values[key]),
637
+ // latest minus the first point in the window, so an absolute delta.
638
+ change: formatDelta(audience.change?.[key])
639
+ };
640
+ }),
641
+ { columns: ["metric", "value", "change"] }
642
+ );
643
+ }
644
+ const notes = {};
645
+ const series = report.series;
646
+ if (series) {
647
+ const first = series.points.at(0);
648
+ const last = series.points.at(-1);
649
+ const span = first && last ? `, ${first.date} to ${last.date}` : "";
650
+ notes["series"] = `${series.points.length} daily points${span}, values ${series.values} (${series.metrics.join(", ")}). Full series in --json.`;
651
+ }
652
+ if (Object.keys(notes).length > 0) {
653
+ heading("Insights");
654
+ print(notes);
844
655
  }
845
- return byReply;
846
656
  }
847
- var BOOLEAN_METADATA = [
848
- ["allow-comments", "allow_comments"],
849
- ["allow-duet", "allow_duet"],
850
- ["allow-stitch", "allow_stitch"],
851
- ["branded-content", "branded_content"],
852
- ["brand-organic", "brand_organic"]
853
- ];
854
- function buildMetadata(args, rawArgs) {
855
- const metadata = {};
856
- const topicTag = readString2(args["topic-tag"]);
857
- if (topicTag !== void 0) {
858
- metadata.topic_tag = topicTag;
657
+ var account = defineCommand({
658
+ meta: {
659
+ name: "account",
660
+ description: "The full analytics report for one connected account"
661
+ },
662
+ args: {
663
+ ...globalArgs,
664
+ space: { type: "string", required: true, description: "The space id" },
665
+ account: { type: "string", required: true, description: "The account id" },
666
+ ...windowArgs
667
+ },
668
+ run: ({ args }) => {
669
+ return guard(async () => {
670
+ const space = toSpaceId(args["space"]);
671
+ const accountId = toId(args["account"], "account");
672
+ const query = windowQuery(args);
673
+ const api = clientFor(args);
674
+ const res = await api.analytics.get({
675
+ path: { space, account: accountId },
676
+ query
677
+ });
678
+ const report = res.data?.data;
679
+ if (!report) {
680
+ throw new Error("The API returned no report.");
681
+ }
682
+ if (wantsJson(args)) {
683
+ print(report, { json: true });
684
+ return;
685
+ }
686
+ printReport(report);
687
+ });
859
688
  }
860
- const postType = readString2(args["post-type"]);
861
- if (postType !== void 0) {
862
- metadata.post_type = postType;
689
+ });
690
+ function postColumnHeaders(columns, taken) {
691
+ const used = new Set(taken);
692
+ return columns.map((column) => {
693
+ let header = column.label;
694
+ if (used.has(header)) {
695
+ header = `${column.label} (${column.key})`;
696
+ }
697
+ if (used.has(header)) {
698
+ header = column.key;
699
+ }
700
+ used.add(header);
701
+ return header;
702
+ });
703
+ }
704
+ function printPosts(payload) {
705
+ print({
706
+ account: formatAccount(payload.account),
707
+ range: formatRange(payload.range),
708
+ collection: describeCollection(payload.collection),
709
+ sort: `${payload.sort.key} ${payload.sort.direction}`,
710
+ page: `${payload.meta.current_page} of ${payload.meta.last_page} (${payload.meta.per_page} per page, ${payload.meta.total} posts in range)`,
711
+ contract: payload.contract
712
+ });
713
+ const fixed = ["post_id", "published_at", "excerpt", "interactions"];
714
+ const headers = postColumnHeaders(payload.columns, fixed);
715
+ heading("Posts");
716
+ print(
717
+ payload.data.map((post) => {
718
+ const row = {
719
+ post_id: post.post_id,
720
+ // Published timestamps are ISO instants while `range` dates are
721
+ // Y-m-d — two formats on purpose, so neither is reformatted here.
722
+ published_at: post.published_at ?? "-",
723
+ excerpt: oneLine(post.excerpt, 48),
724
+ interactions: formatValue(post.interactions.total)
725
+ };
726
+ payload.columns.forEach((column, index) => {
727
+ row[headers[index] ?? column.key] = formatValue(post.metrics[column.key]?.value);
728
+ });
729
+ return row;
730
+ }),
731
+ { columns: [...fixed, ...headers] }
732
+ );
733
+ if (payload.columns.length === 0) {
734
+ process.stdout.write(
735
+ "\nThis platform has no analytics driver, so it declares no metric columns.\n"
736
+ );
863
737
  }
864
- const link = readUrl(args["link"], "link");
865
- if (link !== void 0) {
866
- metadata.link = link;
738
+ const unavailable = payload.columns.map((column, index) => {
739
+ return { column, header: headers[index] ?? column.key };
740
+ }).filter(({ column }) => {
741
+ return column.status !== "ok";
742
+ });
743
+ if (unavailable.length > 0) {
744
+ process.stdout.write("\n");
745
+ for (const { column, header } of unavailable) {
746
+ process.stdout.write(`${header}: ${formatStatus(column.status, column.reason)}
747
+ `);
748
+ }
867
749
  }
868
- const boardId = readString2(args["board-id"]);
869
- if (boardId !== void 0) {
870
- metadata.board_id = boardId;
750
+ const sortable = payload.sort.options.filter((option) => {
751
+ return option.sortable;
752
+ });
753
+ const unhealthy = payload.sort.options.filter((option) => {
754
+ return !option.sortable;
755
+ });
756
+ process.stdout.write(
757
+ `
758
+ Sort keys: ${sortable.map((option) => {
759
+ return option.key;
760
+ }).join(", ")}
761
+ `
762
+ );
763
+ if (unhealthy.length > 0) {
764
+ process.stdout.write(
765
+ `Accepted but currently unmeasured: ${unhealthy.map((option) => {
766
+ return option.key;
767
+ }).join(", ")}
768
+ `
769
+ );
871
770
  }
872
- const title = readString2(args["title"]);
873
- if (title !== void 0) {
874
- if (charCount(title) > PIN_TITLE_MAX) {
875
- throw new Error(
876
- `--title is ${charCount(title)} characters; the limit is ${PIN_TITLE_MAX}.`
771
+ }
772
+ var posts = defineCommand({
773
+ meta: {
774
+ name: "posts",
775
+ description: "One row per published post, with this platform's metrics"
776
+ },
777
+ args: {
778
+ ...globalArgs,
779
+ space: { type: "string", required: true, description: "The space id" },
780
+ account: { type: "string", required: true, description: "The account id" },
781
+ ...windowArgs,
782
+ sort: {
783
+ type: "string",
784
+ description: "Order by published_at, interactions or any metric key this account declares"
785
+ },
786
+ dir: { type: "string", description: "asc or desc (default: desc)" },
787
+ "per-page": {
788
+ type: "string",
789
+ description: `Rows per page, ${MIN_PER_PAGE}-${MAX_PER_PAGE} (default: 20)`
790
+ },
791
+ page: { type: "string", description: "Page number (default: 1)" }
792
+ },
793
+ run: ({ args }) => {
794
+ return guard(async () => {
795
+ const space = toSpaceId(args["space"]);
796
+ const accountId = toId(args["account"], "account");
797
+ const query = windowQuery(args);
798
+ if (args["sort"] !== void 0) {
799
+ query.sort = String(args["sort"]);
800
+ }
801
+ if (args["dir"] !== void 0) {
802
+ query.dir = toDir(args["dir"]);
803
+ }
804
+ if (args["per-page"] !== void 0) {
805
+ query.per_page = toPerPage(args["per-page"]);
806
+ }
807
+ if (args["page"] !== void 0) {
808
+ query.page = toPage(args["page"]);
809
+ }
810
+ const api = clientFor(args);
811
+ const res = await api.analytics.posts({
812
+ path: { space, account: accountId },
813
+ query
814
+ });
815
+ const payload = res.data;
816
+ if (!payload) {
817
+ throw new Error("The API returned no posts payload.");
818
+ }
819
+ if (wantsJson(args)) {
820
+ print(payload, { json: true });
821
+ return;
822
+ }
823
+ printPosts(payload);
824
+ });
825
+ }
826
+ });
827
+ var analytics = defineCommand({
828
+ meta: { name: "analytics", description: "Read analytics reports" },
829
+ subCommands: { overview, account, posts }
830
+ });
831
+ var health = defineCommand({
832
+ meta: { name: "health", description: "Check the Zilfu API health" },
833
+ args: { ...globalArgs },
834
+ run: ({ args }) => {
835
+ return guard(async () => {
836
+ const api = clientFor(args, { requireToken: false });
837
+ const res = await api.health.check();
838
+ print(res.data ?? {}, { json: wantsJson(args) });
839
+ });
840
+ }
841
+ });
842
+ var CTRL_C = String.fromCharCode(3);
843
+ var CTRL_D = String.fromCharCode(4);
844
+ var DEL = String.fromCharCode(127);
845
+ var BACKSPACE = String.fromCharCode(8);
846
+ var SUBMIT = /* @__PURE__ */ new Set(["\r", "\n", CTRL_D]);
847
+ var DELETE = /* @__PURE__ */ new Set([DEL, BACKSPACE]);
848
+ function promptSecret(label) {
849
+ return new Promise((resolve) => {
850
+ const { stdin, stdout } = process;
851
+ stdout.write(label);
852
+ stdin.setRawMode(true);
853
+ stdin.resume();
854
+ let input = "";
855
+ const finish = () => {
856
+ stdin.setRawMode(false);
857
+ stdin.pause();
858
+ stdin.removeListener("data", onData);
859
+ stdout.write("\n");
860
+ };
861
+ const onData = (chunk) => {
862
+ for (const char of chunk.toString("utf8")) {
863
+ if (char === CTRL_C) {
864
+ finish();
865
+ process.exit(130);
866
+ }
867
+ if (SUBMIT.has(char)) {
868
+ finish();
869
+ resolve(input);
870
+ return;
871
+ }
872
+ if (DELETE.has(char)) {
873
+ input = input.slice(0, -1);
874
+ continue;
875
+ }
876
+ if (char >= " ") {
877
+ input += char;
878
+ }
879
+ }
880
+ };
881
+ stdin.on("data", onData);
882
+ });
883
+ }
884
+ var TIMEOUT_MS = 5 * 60 * 1e3;
885
+ function base64url(buffer) {
886
+ return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
887
+ }
888
+ function createPkce() {
889
+ const verifier = base64url(randomBytes(32));
890
+ const challenge = base64url(createHash("sha256").update(verifier).digest());
891
+ return { verifier, challenge };
892
+ }
893
+ function webOrigin(baseUrl) {
894
+ const url = new URL(baseUrl);
895
+ url.pathname = url.pathname.replace(/\/api\/?$/, "/");
896
+ return url.toString().replace(/\/$/, "");
897
+ }
898
+ function openBrowser(url) {
899
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
900
+ try {
901
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
902
+ child.on("error", () => {
903
+ });
904
+ child.unref();
905
+ } catch {
906
+ }
907
+ }
908
+ var DONE_PAGE = '<!doctype html><meta charset=utf-8><title>Zilfu CLI</title><body style="font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0"><p>Authorization complete. You can close this tab and return to your terminal.</p>';
909
+ function loginViaBrowser(baseUrl) {
910
+ const origin = webOrigin(baseUrl);
911
+ const { verifier, challenge } = createPkce();
912
+ const state = randomBytes(16).toString("hex");
913
+ return new Promise((resolve, reject) => {
914
+ const server = createServer((req, res) => {
915
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
916
+ if (url.pathname !== "/callback") {
917
+ res.writeHead(204).end();
918
+ return;
919
+ }
920
+ res.writeHead(200, { "content-type": "text/html" }).end(DONE_PAGE);
921
+ const error = url.searchParams.get("error");
922
+ if (error) {
923
+ settle(reject, new Error(`Authorization was denied (${error}).`));
924
+ return;
925
+ }
926
+ if (url.searchParams.get("state") !== state) {
927
+ settle(reject, new Error("State mismatch \u2014 aborting for safety."));
928
+ return;
929
+ }
930
+ const code = url.searchParams.get("code");
931
+ if (!code) {
932
+ settle(reject, new Error("No authorization code received."));
933
+ return;
934
+ }
935
+ exchange(origin, code, verifier).then(
936
+ (token) => {
937
+ return settle(resolve, token);
938
+ },
939
+ (err) => {
940
+ return settle(reject, err);
941
+ }
942
+ );
943
+ });
944
+ const timer = setTimeout(() => {
945
+ settle(reject, new Error("Timed out waiting for browser authorization."));
946
+ }, TIMEOUT_MS);
947
+ function settle(fn, value) {
948
+ clearTimeout(timer);
949
+ server.close();
950
+ fn(value);
951
+ }
952
+ server.on("error", (err) => {
953
+ return settle(reject, err);
954
+ });
955
+ server.listen(0, "127.0.0.1", () => {
956
+ const { port } = server.address();
957
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
958
+ const authorizeUrl = `${origin}/cli/authorize?${new URLSearchParams({
959
+ redirect_uri: redirectUri,
960
+ state,
961
+ code_challenge: challenge,
962
+ name: `zilfu-cli (${hostname()})`
963
+ }).toString()}`;
964
+ process.stdout.write(
965
+ `Opening your browser to authorize access:
966
+ ${authorizeUrl}
967
+
968
+ Waiting for authorization\u2026
969
+ `
877
970
  );
971
+ openBrowser(authorizeUrl);
972
+ });
973
+ });
974
+ }
975
+ async function exchange(origin, code, verifier) {
976
+ const res = await fetch(`${origin}/cli/token`, {
977
+ method: "POST",
978
+ headers: { "content-type": "application/json", accept: "application/json" },
979
+ body: JSON.stringify({ code, code_verifier: verifier })
980
+ });
981
+ if (!res.ok) {
982
+ throw new Error(`Token exchange failed (HTTP ${res.status}).`);
983
+ }
984
+ const body = await res.json();
985
+ if (!body.token) {
986
+ throw new Error("Token exchange returned no token.");
987
+ }
988
+ return body.token;
989
+ }
990
+
991
+ // src/commands/login.ts
992
+ var login = defineCommand({
993
+ meta: { name: "login", description: "Authenticate and store your API token" },
994
+ args: {
995
+ web: {
996
+ type: "boolean",
997
+ description: "Authorize in the browser instead of pasting a token"
998
+ },
999
+ token: {
1000
+ type: "string",
1001
+ description: "API token (skips the interactive prompt)"
1002
+ },
1003
+ "base-url": {
1004
+ type: "string",
1005
+ description: "API base URL to store (defaults to the production API)"
878
1006
  }
879
- metadata.title = title;
880
- }
881
- const coverImageUrl = readUrl(args["cover-image-url"], "cover-image-url");
882
- if (coverImageUrl !== void 0) {
883
- metadata.cover_image_url = coverImageUrl;
1007
+ },
1008
+ run: ({ args }) => {
1009
+ return guard(async () => {
1010
+ const baseUrl = typeof args["base-url"] === "string" && args["base-url"] ? args["base-url"] : process.env.ZILFU_BASE_URL;
1011
+ const token = args["web"] === true ? await loginViaBrowser(baseUrl ?? DEFAULT_API_BASE_URL) : await promptToken(typeof args["token"] === "string" ? args["token"] : "");
1012
+ const api = createZilfuClient({ token, baseUrl });
1013
+ const res = await api.session.get();
1014
+ const user = res.data?.data;
1015
+ const path = writeConfig({ token, ...baseUrl ? { baseUrl } : {} });
1016
+ process.stdout.write(
1017
+ `Logged in as ${user?.name ?? "?"} <${user?.email ?? "?"}>.
1018
+ Credentials stored at ${path}
1019
+ `
1020
+ );
1021
+ });
884
1022
  }
885
- const privacyLevel = readString2(args["privacy-level"]);
886
- if (privacyLevel !== void 0) {
887
- const normalised = privacyLevel.trim().toUpperCase().replace(/-/g, "_");
888
- const match = PRIVACY_LEVELS.find((level) => level === normalised);
889
- if (!match) {
1023
+ });
1024
+ async function promptToken(flagToken) {
1025
+ let token = flagToken;
1026
+ if (!token) {
1027
+ if (!process.stdin.isTTY) {
890
1028
  throw new Error(
891
- `Invalid --privacy-level value: ${privacyLevel}
892
- Use one of: ${PRIVACY_LEVELS.join(", ")}.`
1029
+ "No token provided. Pass --token <token>, use --web, or run in an interactive terminal."
893
1030
  );
894
1031
  }
895
- metadata.privacy_level = match;
1032
+ process.stdout.write("Copy your API key from Settings -> AI & API.\n");
1033
+ token = await promptSecret("Zilfu API key: ");
896
1034
  }
897
- for (const [flag, key] of BOOLEAN_METADATA) {
898
- const value = toOptionalBool(args, flag, rawArgs);
899
- if (value !== void 0) {
900
- metadata[key] = value;
901
- }
1035
+ token = token.trim();
1036
+ if (!token) {
1037
+ throw new Error("A token is required.");
902
1038
  }
903
- return Object.keys(metadata).length > 0 ? metadata : void 0;
1039
+ return token;
904
1040
  }
905
- function buildComment(args) {
906
- const content = readString2(args["comment"]);
907
- const rawDelay = args["comment-delay"];
908
- if (content === void 0) {
909
- if (rawDelay !== void 0) {
910
- throw new Error(
911
- "--comment-delay was passed without --comment. Add --comment <text>, or drop the delay."
912
- );
913
- }
914
- return void 0;
915
- }
916
- if (rawDelay === void 0) {
917
- throw new Error(
918
- `--comment needs --comment-delay <minutes>: how long after publishing to post it.
919
- Pass a whole number between 1 and ${MAX_COMMENT_DELAY} (7 days).`
920
- );
1041
+ var logout = defineCommand({
1042
+ meta: { name: "logout", description: "Remove stored credentials" },
1043
+ run: () => {
1044
+ return guard(() => {
1045
+ const removed = clearConfig();
1046
+ process.stdout.write(removed ? "Logged out.\n" : "No stored credentials found.\n");
1047
+ });
921
1048
  }
922
- const delayMinutes = Number(rawDelay);
923
- if (!Number.isInteger(delayMinutes) || delayMinutes < 1 || delayMinutes > MAX_COMMENT_DELAY) {
1049
+ });
1050
+
1051
+ // src/mime.ts
1052
+ var MIME_BY_EXTENSION = {
1053
+ jpg: "image/jpeg",
1054
+ jpeg: "image/jpeg",
1055
+ png: "image/png",
1056
+ webp: "image/webp",
1057
+ mp4: "video/mp4",
1058
+ mov: "video/quicktime"
1059
+ };
1060
+ function extensionOf(value) {
1061
+ const withoutQuery = value.split(/[?#]/)[0] ?? "";
1062
+ const lastDot = withoutQuery.lastIndexOf(".");
1063
+ return lastDot === -1 ? "" : withoutQuery.slice(lastDot + 1).toLowerCase();
1064
+ }
1065
+ function mimeForPath(path) {
1066
+ const mime = MIME_BY_EXTENSION[extensionOf(path)];
1067
+ if (!mime) {
924
1068
  throw new Error(
925
- `Invalid --comment-delay value: ${String(rawDelay)}
926
- Pass a whole number of minutes between 1 and ${MAX_COMMENT_DELAY} (7 days).`
1069
+ `Unsupported file type: ${path}
1070
+ Zilfu accepts ${Object.keys(MIME_BY_EXTENSION).join(", ")}.`
927
1071
  );
928
1072
  }
929
- return { content, delay_minutes: delayMinutes };
1073
+ return mime;
930
1074
  }
931
- function commentLimitAcross(socials) {
932
- const limits = socials.map((social) => COMMENT_LIMITS[social]).filter((limit) => limit !== void 0);
933
- return limits.length > 0 ? Math.min(...limits) : COMMENT_FALLBACK_LIMIT;
1075
+ function mediaTypeForMime(mime) {
1076
+ return mime.startsWith("video/") ? "video" : "image";
934
1077
  }
935
- function preflight(accountId, social, content, children, media2, metadata) {
936
- const limit = CONTENT_LIMITS[social];
937
- if (limit !== void 0) {
938
- const length = charCount(content);
939
- if (length > limit) {
940
- throw new Error(
941
- `Content for account ${accountId} (${social}) is ${length} characters; ${social} allows ${limit}.
942
- Use --account-text ${accountId}=<text> to tailor the copy for this account.`
943
- );
944
- }
945
- for (const [index, child] of children.entries()) {
946
- const replyLength = charCount(child.content);
947
- if (replyLength > limit) {
948
- throw new Error(
949
- `Reply ${index + 1} for account ${accountId} (${social}) is ${replyLength} characters; ${social} allows ${limit}.`
950
- );
951
- }
952
- }
953
- }
954
- if (MEDIA_REQUIRED.has(social) && media2.length === 0) {
955
- throw new Error(
956
- `Account ${accountId} (${social}) cannot publish a text-only post. Attach a file with --media.`
957
- );
958
- }
959
- if (social === "linkedin" && media2.length > 1 && !media2.some((item) => item.type === "image")) {
1078
+ function mediaTypeForUrl(url) {
1079
+ const mime = MIME_BY_EXTENSION[extensionOf(url)];
1080
+ if (!mime) {
960
1081
  throw new Error(
961
- `Account ${accountId} (linkedin) has ${media2.length} media files and no image; LinkedIn only takes several files as a multi-image post.
962
- Attach a single video with --media, or include at least one image.`
1082
+ `Cannot tell whether this is an image or a video: ${url}
1083
+ Use a URL ending in ${Object.keys(MIME_BY_EXTENSION).join(", ")}, or upload the file with \`zilfu media upload\` first.`
963
1084
  );
964
1085
  }
965
- if (social === "pinterest") {
966
- if (!metadata?.board_id) {
967
- throw new Error(
968
- `Account ${accountId} (pinterest) needs --board-id: the board the pin is created on.`
969
- );
970
- }
971
- const hasVideo = media2.some((item) => item.type === "video");
972
- const hasImage = media2.some((item) => item.type === "image");
973
- if (hasVideo && !hasImage && !metadata.cover_image_url) {
974
- throw new Error(
975
- `Account ${accountId} (pinterest) is publishing a video pin, which needs a cover image.
976
- Add an image with --media, or point --cover-image-url at one.`
977
- );
978
- }
979
- }
980
- if (social === "tiktok") {
981
- const privacyLevel = metadata?.privacy_level;
982
- if (!privacyLevel) {
983
- throw new Error(
984
- `Account ${accountId} (tiktok) needs --privacy-level; TikTok defaults to SELF_ONLY (visible only to you).
985
- Use one of: ${PRIVACY_LEVELS.join(", ")}.`
986
- );
987
- }
988
- if (metadata?.branded_content === true && privacyLevel === "SELF_ONLY") {
989
- throw new Error(
990
- `Account ${accountId} (tiktok) cannot combine --branded-content with --privacy-level SELF_ONLY; TikTok rejects branded content on a private post.`
991
- );
992
- }
993
- }
1086
+ return mediaTypeForMime(mime);
994
1087
  }
995
- var create = defineCommand({
1088
+
1089
+ // src/commands/media.ts
1090
+ var upload = defineCommand({
996
1091
  meta: {
997
- name: "create",
998
- description: "Create a post \u2014 scheduled, draft, or published now"
1092
+ name: "upload",
1093
+ description: "Upload a local file and print a URL you can attach to a post"
999
1094
  },
1000
1095
  args: {
1001
1096
  ...globalArgs,
1002
- space: { type: "string", required: true, description: "The space id" },
1003
- account: {
1004
- type: "string",
1005
- required: true,
1006
- description: "Account id to post to (repeat for multiple accounts)"
1007
- },
1008
- text: {
1009
- type: "string",
1010
- description: "The post content, shared by every account. Optional when every account has --account-text"
1011
- },
1012
- "account-text": {
1013
- type: "string",
1014
- description: "Per-account copy as <accountId>=<text>, overriding --text for that account (repeat per account)"
1015
- },
1016
- at: {
1017
- type: "string",
1018
- description: "When to publish \u2014 ISO 8601 or epoch ms. Omit to publish immediately"
1019
- },
1020
- draft: { type: "boolean", description: "Save as a draft instead" },
1021
- media: {
1022
- type: "string",
1023
- description: "Media URL to attach (repeat for multiple)"
1024
- },
1025
- reply: {
1026
- type: "string",
1027
- description: "Threaded reply content (repeat for a longer thread)"
1028
- },
1029
- "reply-media": {
1030
- type: "string",
1031
- description: "Media for a threaded reply as <n>=<url>, where <n> is the 1-based position of the --reply it belongs to (1 = first --reply). Repeat with the same <n> for several files"
1032
- },
1033
- comment: {
1034
- type: "string",
1035
- description: "First comment to post after publishing (threads, instagram and facebook only). Requires --comment-delay"
1036
- },
1037
- "comment-delay": {
1038
- type: "string",
1039
- description: `Minutes to wait after publishing before posting --comment, 1-${MAX_COMMENT_DELAY} (7 days)`
1040
- },
1041
- "topic-tag": {
1042
- type: "string",
1043
- description: "Threads: topic tag for the post"
1044
- },
1045
- "board-id": {
1046
- type: "string",
1047
- description: "Pinterest: board the pin is created on (required)"
1048
- },
1049
- title: {
1050
- type: "string",
1051
- description: `Pinterest: pin title, max ${PIN_TITLE_MAX} characters`
1052
- },
1053
- link: {
1054
- type: "string",
1055
- description: "Pinterest: destination URL the pin links to"
1056
- },
1057
- "cover-image-url": {
1058
- type: "string",
1059
- description: "Pinterest: cover image for a video pin, used when --media has no image"
1060
- },
1061
- "privacy-level": {
1062
- type: "string",
1063
- description: `TikTok: who can see the post \u2014 ${PRIVACY_LEVELS.join(" | ")} (required for TikTok; TikTok itself defaults to SELF_ONLY)`
1064
- },
1065
- "allow-comments": {
1066
- type: "boolean",
1067
- description: "TikTok: allow comments (--no-allow-comments to disable; unset leaves TikTok's default)"
1068
- },
1069
- "allow-duet": {
1070
- type: "boolean",
1071
- description: "TikTok video: allow duets (--no-allow-duet to disable; ignored on photo posts)"
1072
- },
1073
- "allow-stitch": {
1074
- type: "boolean",
1075
- description: "TikTok video: allow stitches (--no-allow-stitch to disable; ignored on photo posts)"
1076
- },
1077
- "branded-content": {
1078
- type: "boolean",
1079
- description: "TikTok: mark as branded content (paid partnership); not allowed with --privacy-level SELF_ONLY"
1080
- },
1081
- "brand-organic": {
1082
- type: "boolean",
1083
- description: "TikTok: mark as promoting your own brand"
1084
- },
1085
- "post-type": {
1097
+ file: { type: "string", required: true, description: "Path to the file" },
1098
+ space: {
1086
1099
  type: "string",
1087
- description: "Stored on the post as metadata but not read by any platform \u2014 set it only if your own tooling reads it back"
1100
+ description: "Also add the upload to this space's media library"
1088
1101
  }
1089
1102
  },
1090
- run: ({ args, rawArgs }) => guard(async () => {
1091
- const space = toSpaceId(args["space"]);
1092
- const accountIds = [
1093
- ...new Set(
1094
- repeatedValues(args, rawArgs, "account").map(
1095
- (id) => toId(id, "account")
1096
- )
1097
- )
1098
- ];
1099
- if (accountIds.length === 0) {
1100
- throw new Error("Pass at least one --account.");
1101
- }
1102
- const isDraft = args["draft"] === true;
1103
- const rawAt = args["at"];
1104
- if (isDraft && rawAt !== void 0) {
1105
- throw new Error("--draft and --at are mutually exclusive.");
1106
- }
1107
- const at = rawAt === void 0 ? null : toEpochMs(rawAt);
1108
- if (at !== null) {
1109
- const raw = String(rawAt);
1110
- if (/^\d+$/.test(raw) && at < 1e12) {
1111
- throw new Error(
1112
- `--at ${raw} looks like epoch seconds; the API reads epoch milliseconds, so this would schedule for ${new Date(at).toISOString()}.
1113
- Multiply by 1000, or pass an ISO 8601 timestamp like 2026-08-14T18:00:00Z.`
1114
- );
1115
- }
1116
- if (at <= Date.now()) {
1117
- throw new Error(
1118
- `--at ${new Date(at).toISOString()} is in the past; the scheduler never picks up a post whose time has already passed.
1119
- Omit --at to publish immediately, or pass a future timestamp.`
1120
- );
1121
- }
1122
- }
1123
- const sharedText = readString2(args["text"]);
1124
- const accountTexts = parseAccountTexts(
1125
- repeatedValues(args, rawArgs, "account-text"),
1126
- accountIds
1127
- );
1128
- if (sharedText === void 0) {
1129
- const missing = accountIds.filter((id) => !accountTexts.has(id));
1130
- if (missing.length > 0) {
1131
- throw new Error(
1132
- `No content for account${missing.length > 1 ? "s" : ""} ${missing.join(", ")}.
1133
- Pass --text for copy shared by every account, or --account-text <accountId>=<text> for each one.`
1134
- );
1103
+ run: ({ args }) => {
1104
+ return guard(async () => {
1105
+ const path = String(args["file"]);
1106
+ const mime = mimeForPath(path);
1107
+ const body = await readFile(path);
1108
+ const api = clientFor(args);
1109
+ const signed = await api.media.sign({ body: { mime } });
1110
+ if (!signed.data) {
1111
+ throw new Error("The API returned no upload URL.");
1135
1112
  }
1136
- }
1137
- const media2 = repeatedValues(args, rawArgs, "media").map((url) => ({
1138
- url,
1139
- type: mediaTypeForUrl(url)
1140
- }));
1141
- const replies = repeatedValues(args, rawArgs, "reply");
1142
- const replyMedia = parseReplyMedia(
1143
- repeatedValues(args, rawArgs, "reply-media"),
1144
- replies.length
1145
- );
1146
- const children = replies.map((content, index) => {
1147
- const attached = replyMedia.get(index + 1);
1148
- return attached ? { content, media: attached } : { content };
1149
- });
1150
- const metadata = buildMetadata(args, rawArgs);
1151
- const comment = buildComment(args);
1152
- const api = clientFor(args);
1153
- const accountById = await resolveAccounts(api, space, accountIds);
1154
- const items = accountIds.map((accountId) => {
1155
- const social = accountById.get(accountId).social;
1156
- const content = accountTexts.get(accountId) ?? sharedText;
1157
- preflight(accountId, social, content, children, media2, metadata);
1158
- return {
1159
- account_id: accountId,
1160
- social,
1161
- main: { content, media: media2.length > 0 ? media2 : null },
1162
- ...children.length > 0 ? { children } : {},
1163
- ...metadata ? { metadata } : {}
1164
- };
1165
- });
1166
- if (comment) {
1167
- const socials = accountIds.map((id) => accountById.get(id).social);
1168
- const limit = commentLimitAcross(socials);
1169
- const length = charCount(comment.content);
1170
- if (length > limit) {
1113
+ const { upload_url: uploadUrl, url } = signed.data;
1114
+ const res = await fetch(uploadUrl, {
1115
+ method: "PUT",
1116
+ headers: { "Content-Type": mime },
1117
+ body: new Uint8Array(body)
1118
+ });
1119
+ if (!res.ok) {
1171
1120
  throw new Error(
1172
- `--comment is ${length} characters; ${limit} is the cap for this set of accounts (the strictest comment-capable platform in the call wins).`
1173
- );
1174
- }
1175
- const unsupported = [
1176
- ...new Set(socials.filter((social) => !REPLY_CAPABLE.has(social)))
1177
- ];
1178
- if (unsupported.length > 0) {
1179
- process.stderr.write(
1180
- `Note: ${unsupported.join(", ")} cannot post a scheduled comment; --comment applies to the other accounts only.
1181
- `
1182
- );
1183
- }
1184
- const gated = [
1185
- ...new Set(
1186
- socials.filter(
1187
- (social) => REPLY_CAPABLE.has(social) && !REPLY_ENABLED.has(social)
1188
- )
1189
- )
1190
- ];
1191
- if (gated.length > 0) {
1192
- process.stderr.write(
1193
- `Note: ${gated.join(", ")} is not on the follow-up comment rollout, so --comment is usually dropped for those accounts.
1194
- `
1121
+ `Upload failed: ${res.status} ${res.statusText}
1122
+ The signed URL expires 15 minutes after it is issued.`
1195
1123
  );
1196
1124
  }
1197
- }
1198
- const res = await api.posts.create({
1199
- path: { space: String(space) },
1200
- body: {
1201
- space_id: space,
1202
- at,
1203
- is_draft: isDraft,
1204
- items,
1205
- ...comment ? { comment } : {}
1125
+ const type = mediaTypeForMime(mime);
1126
+ if (args["space"] !== void 0) {
1127
+ const space = toSpaceId(args["space"]);
1128
+ await api.media.create({
1129
+ path: { space },
1130
+ body: { url, type, mime, name: basename(path) }
1131
+ });
1206
1132
  }
1133
+ print({ url, type, mime }, { json: wantsJson(args) });
1207
1134
  });
1208
- const created = res.data?.data ?? [];
1209
- if (wantsJson(args)) {
1210
- print(created, { json: true });
1211
- return;
1212
- }
1213
- const rows = created.map((post) => ({
1214
- id: post.id,
1215
- account_id: post.account_id,
1216
- status: statusLabel(post.status),
1217
- scheduled_at: post.scheduled_at
1218
- }));
1219
- print(rows, {
1220
- columns: ["id", "account_id", "status", "scheduled_at"]
1221
- });
1222
- })
1223
- });
1224
- var del = defineCommand({
1225
- meta: {
1226
- name: "delete",
1227
- description: "Delete a post. The API answers 204 No Content, so --json prints a CLI-made acknowledgement rather than a server payload"
1228
- },
1229
- args: {
1230
- ...globalArgs,
1231
- space: { type: "string", required: true, description: "The space id" },
1232
- post: { type: "string", required: true, description: "The post id" }
1233
- },
1234
- run: ({ args }) => guard(async () => {
1235
- const space = toSpaceId(args["space"]);
1236
- const post = toId(args["post"], "post");
1237
- const api = clientFor(args);
1238
- await api.posts.delete({ path: { space, post } });
1239
- if (wantsJson(args)) {
1240
- print({ deleted: true, id: post }, { json: true });
1241
- return;
1242
- }
1243
- process.stdout.write(`Deleted post ${post}.
1244
- `);
1245
- })
1135
+ }
1246
1136
  });
1247
- var posts = defineCommand({
1248
- meta: { name: "posts", description: "Manage posts" },
1249
- subCommands: { list: list3, create, delete: del }
1137
+ var media = defineCommand({
1138
+ meta: { name: "media", description: "Upload and manage media" },
1139
+ subCommands: { upload }
1250
1140
  });
1251
- var DAY_LABELS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
1252
- var DAY_NAMES = /* @__PURE__ */ new Set([
1253
- "mon",
1254
- "monday",
1255
- "tue",
1256
- "tuesday",
1257
- "wed",
1258
- "wednesday",
1259
- "thu",
1260
- "thursday",
1261
- "fri",
1262
- "friday",
1263
- "sat",
1264
- "saturday",
1265
- "sun",
1266
- "sunday"
1267
- ]);
1268
- function dayLabel(day) {
1269
- return DAY_LABELS[day - 1] ?? String(day);
1141
+ var STATUS_LABELS = {
1142
+ 0: "scheduled",
1143
+ 1: "published",
1144
+ 2: "error",
1145
+ 3: "draft",
1146
+ 4: "processing",
1147
+ 5: "pending_approval"
1148
+ };
1149
+ var CONTENT_LIMITS = {
1150
+ threads: 500,
1151
+ x: 280,
1152
+ instagram: 2200,
1153
+ linkedin: 3e3,
1154
+ tiktok: 2200,
1155
+ facebook: 63206,
1156
+ pinterest: 500
1157
+ };
1158
+ var COMMENT_LIMITS = {
1159
+ threads: 500,
1160
+ instagram: 2200,
1161
+ facebook: 8e3,
1162
+ linkedin: 1250
1163
+ };
1164
+ var COMMENT_FALLBACK_LIMIT = 500;
1165
+ var REPLY_ENABLED = /* @__PURE__ */ new Set(["threads", "instagram", "facebook"]);
1166
+ var REPLY_CAPABLE = /* @__PURE__ */ new Set([...REPLY_ENABLED, "linkedin"]);
1167
+ var MEDIA_REQUIRED = /* @__PURE__ */ new Set(["instagram", "tiktok", "pinterest"]);
1168
+ var PRIVACY_LEVELS = [
1169
+ "PUBLIC_TO_EVERYONE",
1170
+ "MUTUAL_FOLLOW_FRIENDS",
1171
+ "FOLLOWER_OF_CREATOR",
1172
+ "SELF_ONLY"
1173
+ ];
1174
+ var MAX_COMMENT_DELAY = 10080;
1175
+ var PIN_TITLE_MAX = 100;
1176
+ var MAX_PER_PAGE2 = 200;
1177
+ function statusLabel(status) {
1178
+ return STATUS_LABELS[status] ?? String(status);
1270
1179
  }
1271
- function collectRepeated(name, rawArgs, fallback) {
1272
- const flag = `--${name}`;
1273
- const inline = `${flag}=`;
1180
+ function charCount(value) {
1181
+ return [...value].length;
1182
+ }
1183
+ function readString2(value) {
1184
+ if (value === void 0 || value === null) {
1185
+ return void 0;
1186
+ }
1187
+ const raw = String(value);
1188
+ return raw.length > 0 ? raw : void 0;
1189
+ }
1190
+ function readUrl(value, flag) {
1191
+ const raw = readString2(value);
1192
+ if (raw !== void 0 && !/^https?:\/\//i.test(raw)) {
1193
+ throw new Error(`--${flag} must be an http(s) URL: ${raw}`);
1194
+ }
1195
+ return raw;
1196
+ }
1197
+ function camelize(name) {
1198
+ return name.replace(/-([a-z])/g, (_, letter) => {
1199
+ return letter.toUpperCase();
1200
+ });
1201
+ }
1202
+ function repeatedValues(args, rawArgs, name) {
1203
+ const names = /* @__PURE__ */ new Set([name, camelize(name)]);
1274
1204
  const values = [];
1275
- for (let i = 0; i < rawArgs.length; i += 1) {
1276
- const arg = rawArgs[i];
1277
- if (arg === "--") {
1205
+ for (let index = 0; index < rawArgs.length; index += 1) {
1206
+ const token = rawArgs[index];
1207
+ if (token === "--") {
1278
1208
  break;
1279
1209
  }
1280
- if (arg === flag) {
1281
- const next = rawArgs[i + 1];
1282
- if (next !== void 0 && !next.startsWith("-")) {
1283
- values.push(next);
1284
- i += 1;
1285
- }
1210
+ if (!token.startsWith("--")) {
1286
1211
  continue;
1287
1212
  }
1288
- if (arg.startsWith(inline)) {
1289
- values.push(arg.slice(inline.length));
1213
+ const separator = token.indexOf("=");
1214
+ const flag = separator === -1 ? token.slice(2) : token.slice(2, separator);
1215
+ if (!names.has(flag)) {
1216
+ continue;
1217
+ }
1218
+ if (separator !== -1) {
1219
+ values.push(token.slice(separator + 1));
1220
+ continue;
1221
+ }
1222
+ const next = rawArgs[index + 1];
1223
+ if (next !== void 0 && !next.startsWith("--")) {
1224
+ values.push(next);
1225
+ index += 1;
1290
1226
  }
1291
1227
  }
1292
- return values.length > 0 ? values : fallback;
1228
+ return values.length > 1 ? values.filter((value) => {
1229
+ return value.length > 0;
1230
+ }) : toList(args[name]);
1293
1231
  }
1294
- function toDayNumbers(value) {
1295
- const tokens = toList(value).flatMap((entry) => entry.split(",")).map((token) => token.trim()).filter((token) => token.length > 0);
1296
- for (const token of tokens) {
1297
- const raw = token.toLowerCase();
1298
- if (!/^\d+$/.test(raw) && !DAY_NAMES.has(raw)) {
1232
+ function parsePairs(entries, flag, example) {
1233
+ return entries.map((entry) => {
1234
+ const separator = entry.indexOf("=");
1235
+ if (separator <= 0) {
1299
1236
  throw new Error(
1300
- `Invalid day: ${token}
1301
- Use 1-7 (1 = Monday, 7 = Sunday) or names like mon,wed,fri.`
1237
+ `Invalid --${flag} value: ${entry}
1238
+ Use --${flag} <key>=<value>, for example ${example}`
1302
1239
  );
1303
1240
  }
1304
- }
1305
- return toDaysOfWeek(tokens);
1241
+ return [entry.slice(0, separator), entry.slice(separator + 1)];
1242
+ });
1306
1243
  }
1307
- function toTime(value) {
1308
- const raw = String(value ?? "").trim();
1309
- const match = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(raw);
1310
- const hour = Number(match?.[1]);
1311
- const minute = Number(match?.[2]);
1312
- if (!match || match[3] !== void 0 && match[3] !== "00" || hour > 23 || minute > 59) {
1244
+ function toStatus(value) {
1245
+ const raw = value.trim().toLowerCase().replace(/-/g, "_");
1246
+ const match = Object.entries(STATUS_LABELS).find(([number, label]) => {
1247
+ return label === raw || number === raw;
1248
+ });
1249
+ if (!match) {
1313
1250
  throw new Error(
1314
- `Invalid --time value: ${raw}
1315
- Pass a 24-hour time as HH:MM, for example 09:00 or 17:30.`
1251
+ `Invalid --status value: ${value}
1252
+ Use one of: ${Object.entries(STATUS_LABELS).map(([number, label]) => {
1253
+ return `${label} (${number})`;
1254
+ }).join(", ")}.`
1316
1255
  );
1317
1256
  }
1318
- return `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
1257
+ return Number(match[0]);
1319
1258
  }
1320
- function rethrowWithSlotHint(error) {
1321
- if (error instanceof ZilfuApiError && error.status === 403) {
1322
- const hint = /^you have read-only access/i.test(error.message) ? "Hint: this token has read-only access to the workspace, and slot changes additionally require space ownership." : "Hint: adding or removing slots requires space ownership \u2014 members cannot change the schedule, whatever their permissions.";
1323
- process.stderr.write(`${hint}
1324
- `);
1259
+ function toCount(value, flag, max) {
1260
+ const count = Number(value);
1261
+ if (!Number.isInteger(count) || count < 1 || max !== void 0 && count > max) {
1262
+ throw new Error(
1263
+ `Invalid --${flag} value: ${String(value)}
1264
+ Pass a whole number ${max === void 0 ? "of 1 or more" : `between 1 and ${max}`}.`
1265
+ );
1325
1266
  }
1326
- throw error;
1327
- }
1328
- function slotRows(slots2) {
1329
- return slots2.map((slot) => ({
1330
- id: slot.id,
1331
- day: dayLabel(slot.day_of_week),
1332
- time: slot.time
1333
- }));
1267
+ return count;
1334
1268
  }
1335
- var SLOT_COLUMNS = ["id", "day", "time"];
1336
- var list4 = defineCommand({
1337
- meta: { name: "list", description: "List the posting slots in a space" },
1338
- args: {
1339
- ...globalArgs,
1340
- space: { type: "string", required: true, description: "The space id" }
1341
- },
1342
- run: ({ args }) => guard(async () => {
1343
- const space = toSpaceId(args["space"]);
1344
- const api = clientFor(args);
1345
- const res = await api.slots.list({ path: { space } });
1346
- const slots2 = res.data?.data ?? [];
1347
- if (wantsJson(args)) {
1348
- print(slots2, { json: true });
1349
- return;
1350
- }
1351
- print(slotRows(slots2), { columns: SLOT_COLUMNS });
1352
- })
1353
- });
1354
- var create2 = defineCommand({
1355
- meta: {
1356
- name: "create",
1357
- description: "Add a posting slot at one time on one or more days (an existing day is a no-op)"
1358
- },
1269
+ var list2 = defineCommand({
1270
+ meta: { name: "list", description: "List posts in a space" },
1359
1271
  args: {
1360
1272
  ...globalArgs,
1361
1273
  space: { type: "string", required: true, description: "The space id" },
1362
- days: {
1274
+ status: {
1363
1275
  type: "string",
1364
- required: true,
1365
- description: "Days for this slot \u2014 mon,wed,fri or 1,3,5 (1 = Monday, 7 = Sunday); comma-separated or repeatable"
1276
+ description: "Filter by status \u2014 name or number (scheduled, published, error, draft, processing, pending_approval). Repeat to match any of several"
1366
1277
  },
1367
- time: {
1278
+ account: {
1368
1279
  type: "string",
1369
- required: true,
1370
- description: "Time of day in the organization's timezone, as HH:MM (e.g. 09:00)"
1371
- }
1372
- },
1373
- run: ({ args, rawArgs }) => guard(async () => {
1374
- const space = toSpaceId(args["space"]);
1375
- const days_of_week = toDayNumbers(
1376
- collectRepeated("days", rawArgs, args["days"])
1377
- );
1378
- const time = toTime(args["time"]);
1379
- const api = clientFor(args);
1380
- const res = await api.slots.create({ path: { space }, body: { days_of_week, time } }).catch(rethrowWithSlotHint);
1381
- const slots2 = res.data?.data ?? [];
1382
- if (wantsJson(args)) {
1383
- print(slots2, { json: true });
1384
- return;
1280
+ description: "Filter by account id (repeat to match any of several)"
1281
+ },
1282
+ from: {
1283
+ type: "string",
1284
+ description: "Only posts scheduled or published on/after this date"
1285
+ },
1286
+ to: {
1287
+ type: "string",
1288
+ description: "Only posts scheduled or published on/before this date"
1289
+ },
1290
+ "per-page": {
1291
+ type: "string",
1292
+ description: `Results per page, 1-${MAX_PER_PAGE2} (default 15)`
1293
+ },
1294
+ page: {
1295
+ type: "string",
1296
+ description: "Page of results to fetch (default 1)"
1385
1297
  }
1386
- print(slotRows(slots2), { columns: SLOT_COLUMNS });
1387
- })
1388
- });
1389
- var del2 = defineCommand({
1390
- meta: {
1391
- name: "delete",
1392
- description: "Remove a posting slot (ids come from `slots list`)"
1393
1298
  },
1394
- args: {
1395
- ...globalArgs,
1396
- space: { type: "string", required: true, description: "The space id" },
1397
- slot: { type: "string", required: true, description: "The slot id" }
1398
- },
1399
- run: ({ args }) => guard(async () => {
1400
- const space = toSpaceId(args["space"]);
1401
- const slot = toId(args["slot"], "slot");
1402
- const api = clientFor(args);
1403
- await api.slots.delete({ path: { space, slot } }).catch(rethrowWithSlotHint);
1404
- if (wantsJson(args)) {
1405
- print({ deleted: true, id: slot }, { json: true });
1406
- return;
1407
- }
1408
- process.stdout.write(`Deleted slot ${slot}.
1299
+ run: ({ args, rawArgs }) => {
1300
+ return guard(async () => {
1301
+ const space = toSpaceId(args["space"]);
1302
+ const statuses = repeatedValues(args, rawArgs, "status").map(toStatus);
1303
+ const accountIds = repeatedValues(args, rawArgs, "account").map((id) => {
1304
+ return toId(id, "account");
1305
+ });
1306
+ const query = {};
1307
+ if (statuses.length === 1) {
1308
+ query.status = statuses[0];
1309
+ } else if (statuses.length > 1) {
1310
+ query["statuses[]"] = statuses;
1311
+ }
1312
+ if (accountIds.length === 1) {
1313
+ query.account_id = accountIds[0];
1314
+ } else if (accountIds.length > 1) {
1315
+ query["account_ids[]"] = accountIds;
1316
+ }
1317
+ if (args["from"] !== void 0) {
1318
+ query.from = toDate(args["from"], "from");
1319
+ }
1320
+ if (args["to"] !== void 0) {
1321
+ query.to = toDate(args["to"], "to");
1322
+ }
1323
+ if (args["per-page"] !== void 0) {
1324
+ query.per_page = toCount(args["per-page"], "per-page", MAX_PER_PAGE2);
1325
+ }
1326
+ if (args["page"] !== void 0) {
1327
+ query.page = toCount(args["page"], "page");
1328
+ }
1329
+ const api = clientFor(args);
1330
+ const res = await api.posts.list({ path: { space }, query });
1331
+ const posts3 = res.data?.data ?? [];
1332
+ if (wantsJson(args)) {
1333
+ print(res.data ?? { data: [] }, { json: true });
1334
+ return;
1335
+ }
1336
+ const rows = posts3.map((post) => {
1337
+ return {
1338
+ id: post.id,
1339
+ account_id: post.account_id,
1340
+ status: statusLabel(post.status),
1341
+ scheduled_at: post.scheduled_at,
1342
+ published_at: post.published_at
1343
+ };
1344
+ });
1345
+ print(rows, {
1346
+ columns: ["id", "account_id", "status", "scheduled_at", "published_at"]
1347
+ });
1348
+ const meta = res.data?.meta;
1349
+ if (meta && meta.total > 0) {
1350
+ const shown = meta.from !== null && meta.to !== null ? `${meta.from}-${meta.to}` : String(posts3.length);
1351
+ const more = meta.current_page < meta.last_page ? `. Pass --page ${meta.current_page + 1} for the next page` : "";
1352
+ process.stdout.write(`Showing ${shown} of ${meta.total}${more}.
1409
1353
  `);
1410
- })
1411
- });
1412
- var slots = defineCommand({
1413
- meta: {
1414
- name: "slots",
1415
- description: "Manage a space's recurring posting schedule"
1416
- },
1417
- subCommands: { list: list4, create: create2, delete: del2 }
1354
+ }
1355
+ });
1356
+ }
1418
1357
  });
1419
- var MIN_PER_PAGE = 10;
1420
- var MAX_PER_PAGE2 = 100;
1421
- var NUMBER = new Intl.NumberFormat("en-US");
1422
- function formatValue(value) {
1423
- return value === null || value === void 0 ? "-" : NUMBER.format(value);
1358
+ async function resolveAccounts(api, space, accountIds) {
1359
+ const res = await api.accounts.list({ path: { space } });
1360
+ const accounts2 = res.data?.data ?? [];
1361
+ const accountById = new Map(
1362
+ accounts2.map((a) => {
1363
+ return [a.id, a];
1364
+ })
1365
+ );
1366
+ for (const accountId of accountIds) {
1367
+ if (!accountById.has(accountId)) {
1368
+ const known = accounts2.map((a) => {
1369
+ return a.id;
1370
+ }).join(", ");
1371
+ throw new Error(
1372
+ `Account ${accountId} is not in space ${space}.
1373
+ ` + (known ? `Accounts in this space: ${known}` : "This space has no connected accounts.")
1374
+ );
1375
+ }
1376
+ }
1377
+ const stale = accountIds.map((id) => {
1378
+ return accountById.get(id);
1379
+ }).filter((a) => {
1380
+ return !a.is_active || Boolean(a.disconnected_at);
1381
+ });
1382
+ if (stale.length > 0) {
1383
+ const many = stale.length > 1;
1384
+ process.stderr.write(
1385
+ `Note: account${many ? "s" : ""} ${stale.map((a) => {
1386
+ return `${a.id} (${a.social})`;
1387
+ }).join(
1388
+ ", "
1389
+ )} ${many ? "are" : "is"} disconnected; publishing will fail until reconnected.
1390
+ `
1391
+ );
1392
+ }
1393
+ return accountById;
1424
1394
  }
1425
- function formatDelta(value) {
1426
- if (value === null || value === void 0) {
1427
- return "-";
1395
+ function parseAccountTexts(entries, accountIds) {
1396
+ const texts = /* @__PURE__ */ new Map();
1397
+ for (const [rawId, text] of parsePairs(
1398
+ entries,
1399
+ "account-text",
1400
+ '--account-text 7="Shorter copy for X"'
1401
+ )) {
1402
+ const accountId = toId(rawId, "account");
1403
+ if (!accountIds.includes(accountId)) {
1404
+ throw new Error(
1405
+ `--account-text targets account ${accountId}, which was not passed with --account.
1406
+ Accounts in this call: ${accountIds.join(", ")}`
1407
+ );
1408
+ }
1409
+ if (texts.has(accountId)) {
1410
+ throw new Error(`--account-text was given twice for account ${accountId}.`);
1411
+ }
1412
+ if (text.length === 0) {
1413
+ throw new Error(`--account-text for account ${accountId} is empty.`);
1414
+ }
1415
+ texts.set(accountId, text);
1428
1416
  }
1429
- return `${value > 0 ? "+" : ""}${NUMBER.format(value)}`;
1417
+ return texts;
1430
1418
  }
1431
- function formatChange(value, unit) {
1432
- if (value === null) {
1433
- return "-";
1419
+ function parseReplyMedia(entries, replyCount) {
1420
+ const byReply = /* @__PURE__ */ new Map();
1421
+ for (const [rawIndex, url] of parsePairs(
1422
+ entries,
1423
+ "reply-media",
1424
+ "--reply-media 1=https://\u2026/clip.mp4"
1425
+ )) {
1426
+ const index = Number(rawIndex);
1427
+ if (!Number.isInteger(index) || index < 1 || index > replyCount) {
1428
+ throw new Error(
1429
+ `--reply-media ${rawIndex}=\u2026 does not match a reply.
1430
+ ` + (replyCount === 0 ? "Pass --reply first \u2014 --reply-media attaches media to a reply by its 1-based position." : `Use 1-${replyCount}: the position of the --reply this media belongs to.`)
1431
+ );
1432
+ }
1433
+ const media2 = byReply.get(index) ?? [];
1434
+ media2.push({ url, type: mediaTypeForUrl(url) });
1435
+ byReply.set(index, media2);
1434
1436
  }
1435
- const sign = value > 0 ? "+" : "";
1436
- if (unit === "percent") {
1437
- return `${sign}${value}%`;
1437
+ return byReply;
1438
+ }
1439
+ var BOOLEAN_METADATA = [
1440
+ ["allow-comments", "allow_comments"],
1441
+ ["allow-duet", "allow_duet"],
1442
+ ["allow-stitch", "allow_stitch"],
1443
+ ["branded-content", "branded_content"],
1444
+ ["brand-organic", "brand_organic"]
1445
+ ];
1446
+ function buildMetadata(args, rawArgs) {
1447
+ const metadata = {};
1448
+ const topicTag = readString2(args["topic-tag"]);
1449
+ if (topicTag !== void 0) {
1450
+ metadata.topic_tag = topicTag;
1438
1451
  }
1439
- if (unit === "percentage_points") {
1440
- return `${sign}${value} pp`;
1452
+ const postType = readString2(args["post-type"]);
1453
+ if (postType !== void 0) {
1454
+ metadata.post_type = postType;
1441
1455
  }
1442
- return `${sign}${value} ${unit}`;
1443
- }
1444
- function formatRate(value) {
1445
- return value === null ? "-" : `${value}%`;
1446
- }
1447
- function formatStatus(status, reason) {
1448
- return reason ? `${status} (${reason})` : status;
1449
- }
1450
- function formatCollection(collection) {
1451
- return formatStatus(collection.state, collection.reason);
1452
- }
1453
- function describeCollection(collection) {
1454
- const parts = [
1455
- formatCollection(collection),
1456
- `last collected ${collection.last_collected_at ?? "never"}`,
1457
- `every ${collection.cadence_hours}h over ${collection.polling_window_days} days`
1458
- ];
1459
- if (collection.remedy) {
1460
- parts.push(`remedy: ${collection.remedy}`);
1456
+ const link = readUrl(args["link"], "link");
1457
+ if (link !== void 0) {
1458
+ metadata.link = link;
1461
1459
  }
1462
- return parts.join(", ");
1463
- }
1464
- function formatAccount(account2) {
1465
- const handle = account2.handler ? ` @${account2.handler}` : "";
1466
- return `${account2.display_name}${handle} (${account2.social}, id ${account2.id})`;
1467
- }
1468
- function formatRange(range) {
1469
- return `${range.from} to ${range.to} (${range.days} days, ${range.timezone})`;
1470
- }
1471
- function oneLine(text, max) {
1472
- const flat = text.replace(/\s+/g, " ").trim();
1473
- return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
1474
- }
1475
- function heading(title) {
1476
- process.stdout.write(`
1477
- ${title}
1478
-
1479
- `);
1480
- }
1481
- function windowQuery(args) {
1482
- const query = {};
1483
- if (args["from"] !== void 0) {
1484
- query.from = toDate(args["from"], "from");
1460
+ const boardId = readString2(args["board-id"]);
1461
+ if (boardId !== void 0) {
1462
+ metadata.board_id = boardId;
1485
1463
  }
1486
- if (args["to"] !== void 0) {
1487
- query.to = toDate(args["to"], "to");
1464
+ const title = readString2(args["title"]);
1465
+ if (title !== void 0) {
1466
+ if (charCount(title) > PIN_TITLE_MAX) {
1467
+ throw new Error(`--title is ${charCount(title)} characters; the limit is ${PIN_TITLE_MAX}.`);
1468
+ }
1469
+ metadata.title = title;
1488
1470
  }
1489
- return query;
1490
- }
1491
- function describeWindow(query) {
1492
- if (query.from && query.to) {
1493
- return `${query.from} to ${query.to} (requested)`;
1471
+ const coverImageUrl = readUrl(args["cover-image-url"], "cover-image-url");
1472
+ if (coverImageUrl !== void 0) {
1473
+ metadata.cover_image_url = coverImageUrl;
1494
1474
  }
1495
- if (query.from) {
1496
- return `from ${query.from} (requested)`;
1475
+ const privacyLevel = readString2(args["privacy-level"]);
1476
+ if (privacyLevel !== void 0) {
1477
+ const normalised = privacyLevel.trim().toUpperCase().replace(/-/g, "_");
1478
+ const match = PRIVACY_LEVELS.find((level) => {
1479
+ return level === normalised;
1480
+ });
1481
+ if (!match) {
1482
+ throw new Error(
1483
+ `Invalid --privacy-level value: ${privacyLevel}
1484
+ Use one of: ${PRIVACY_LEVELS.join(", ")}.`
1485
+ );
1486
+ }
1487
+ metadata.privacy_level = match;
1497
1488
  }
1498
- if (query.to) {
1499
- return `up to ${query.to} (requested)`;
1489
+ for (const [flag, key] of BOOLEAN_METADATA) {
1490
+ const value = toOptionalBool(args, flag, rawArgs);
1491
+ if (value !== void 0) {
1492
+ metadata[key] = value;
1493
+ }
1500
1494
  }
1501
- return "last 7 days in the organization timezone (API default)";
1495
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
1502
1496
  }
1503
- function toDir(value) {
1504
- const dir = String(value).toLowerCase();
1505
- if (dir !== "asc" && dir !== "desc") {
1497
+ function buildComment(args) {
1498
+ const content = readString2(args["comment"]);
1499
+ const rawDelay = args["comment-delay"];
1500
+ if (content === void 0) {
1501
+ if (rawDelay !== void 0) {
1502
+ throw new Error(
1503
+ "--comment-delay was passed without --comment. Add --comment <text>, or drop the delay."
1504
+ );
1505
+ }
1506
+ return void 0;
1507
+ }
1508
+ if (rawDelay === void 0) {
1509
+ throw new Error(
1510
+ `--comment needs --comment-delay <minutes>: how long after publishing to post it.
1511
+ Pass a whole number between 1 and ${MAX_COMMENT_DELAY} (7 days).`
1512
+ );
1513
+ }
1514
+ const delayMinutes = Number(rawDelay);
1515
+ if (!Number.isInteger(delayMinutes) || delayMinutes < 1 || delayMinutes > MAX_COMMENT_DELAY) {
1506
1516
  throw new Error(
1507
- `Invalid --dir value: ${String(value)}
1508
- Use asc or desc.`
1517
+ `Invalid --comment-delay value: ${String(rawDelay)}
1518
+ Pass a whole number of minutes between 1 and ${MAX_COMMENT_DELAY} (7 days).`
1509
1519
  );
1510
1520
  }
1511
- return dir;
1512
- }
1513
- function toPerPage(value) {
1514
- const perPage = Number(value);
1515
- if (!Number.isInteger(perPage) || perPage < MIN_PER_PAGE || perPage > MAX_PER_PAGE2) {
1521
+ return { content, delay_minutes: delayMinutes };
1522
+ }
1523
+ function commentLimitAcross(socials) {
1524
+ const limits = socials.map((social) => {
1525
+ return COMMENT_LIMITS[social];
1526
+ }).filter((limit) => {
1527
+ return limit !== void 0;
1528
+ });
1529
+ return limits.length > 0 ? Math.min(...limits) : COMMENT_FALLBACK_LIMIT;
1530
+ }
1531
+ function preflight(accountId, social, content, children, media2, metadata) {
1532
+ const limit = CONTENT_LIMITS[social];
1533
+ if (limit !== void 0) {
1534
+ const length = charCount(content);
1535
+ if (length > limit) {
1536
+ throw new Error(
1537
+ `Content for account ${accountId} (${social}) is ${length} characters; ${social} allows ${limit}.
1538
+ Use --account-text ${accountId}=<text> to tailor the copy for this account.`
1539
+ );
1540
+ }
1541
+ for (const [index, child] of children.entries()) {
1542
+ const replyLength = charCount(child.content);
1543
+ if (replyLength > limit) {
1544
+ throw new Error(
1545
+ `Reply ${index + 1} for account ${accountId} (${social}) is ${replyLength} characters; ${social} allows ${limit}.`
1546
+ );
1547
+ }
1548
+ }
1549
+ }
1550
+ if (MEDIA_REQUIRED.has(social) && media2.length === 0) {
1516
1551
  throw new Error(
1517
- `Invalid --per-page value: ${String(value)}
1518
- Use a whole number between ${MIN_PER_PAGE} and ${MAX_PER_PAGE2}.`
1552
+ `Account ${accountId} (${social}) cannot publish a text-only post. Attach a file with --media.`
1519
1553
  );
1520
1554
  }
1521
- return perPage;
1522
- }
1523
- function toPage(value) {
1524
- const page = Number(value);
1525
- if (!Number.isInteger(page) || page < 1) {
1555
+ if (social === "linkedin" && media2.length > 1 && !media2.some((item) => {
1556
+ return item.type === "image";
1557
+ })) {
1526
1558
  throw new Error(
1527
- `Invalid --page value: ${String(value)}
1528
- Pages start at 1.`
1559
+ `Account ${accountId} (linkedin) has ${media2.length} media files and no image; LinkedIn only takes several files as a multi-image post.
1560
+ Attach a single video with --media, or include at least one image.`
1529
1561
  );
1530
1562
  }
1531
- return page;
1532
- }
1533
- var windowArgs = {
1534
- from: {
1535
- type: "string",
1536
- description: "Window start, e.g. 2026-07-01 (default: 6 days ago)"
1537
- },
1538
- to: {
1539
- type: "string",
1540
- description: "Window end, e.g. 2026-07-31 (default: today, organization timezone)"
1563
+ if (social === "pinterest") {
1564
+ if (!metadata?.board_id) {
1565
+ throw new Error(
1566
+ `Account ${accountId} (pinterest) needs --board-id: the board the pin is created on.`
1567
+ );
1568
+ }
1569
+ const hasVideo = media2.some((item) => {
1570
+ return item.type === "video";
1571
+ });
1572
+ const hasImage = media2.some((item) => {
1573
+ return item.type === "image";
1574
+ });
1575
+ if (hasVideo && !hasImage && !metadata.cover_image_url) {
1576
+ throw new Error(
1577
+ `Account ${accountId} (pinterest) is publishing a video pin, which needs a cover image.
1578
+ Add an image with --media, or point --cover-image-url at one.`
1579
+ );
1580
+ }
1541
1581
  }
1542
- };
1543
- var overview = defineCommand({
1582
+ if (social === "tiktok") {
1583
+ const privacyLevel = metadata?.privacy_level;
1584
+ if (!privacyLevel) {
1585
+ throw new Error(
1586
+ `Account ${accountId} (tiktok) needs --privacy-level; TikTok defaults to SELF_ONLY (visible only to you).
1587
+ Use one of: ${PRIVACY_LEVELS.join(", ")}.`
1588
+ );
1589
+ }
1590
+ if (metadata?.branded_content === true && privacyLevel === "SELF_ONLY") {
1591
+ throw new Error(
1592
+ `Account ${accountId} (tiktok) cannot combine --branded-content with --privacy-level SELF_ONLY; TikTok rejects branded content on a private post.`
1593
+ );
1594
+ }
1595
+ }
1596
+ }
1597
+ var create = defineCommand({
1544
1598
  meta: {
1545
- name: "overview",
1546
- description: "One analytics summary row per account in a space"
1599
+ name: "create",
1600
+ description: "Create a post \u2014 scheduled, draft, or published now"
1547
1601
  },
1548
1602
  args: {
1549
1603
  ...globalArgs,
1550
1604
  space: { type: "string", required: true, description: "The space id" },
1551
- ...windowArgs
1552
- },
1553
- run: ({ args }) => guard(async () => {
1554
- const space = toSpaceId(args["space"]);
1555
- const query = windowQuery(args);
1556
- const api = clientFor(args);
1557
- const res = await api.analytics.list({ path: { space }, query });
1558
- const summaries = res.data?.data ?? [];
1559
- if (wantsJson(args)) {
1560
- print(summaries, { json: true });
1561
- return;
1562
- }
1563
- process.stdout.write(`Window ${describeWindow(query)}
1564
-
1565
- `);
1566
- if (summaries.length === 0) {
1567
- process.stdout.write("No accounts in this space.\n");
1568
- return;
1605
+ account: {
1606
+ type: "string",
1607
+ required: true,
1608
+ description: "Account id to post to (repeat for multiple accounts)"
1609
+ },
1610
+ text: {
1611
+ type: "string",
1612
+ description: "The post content, shared by every account. Optional when every account has --account-text"
1613
+ },
1614
+ "account-text": {
1615
+ type: "string",
1616
+ description: "Per-account copy as <accountId>=<text>, overriding --text for that account (repeat per account)"
1617
+ },
1618
+ at: {
1619
+ type: "string",
1620
+ description: "When to publish \u2014 ISO 8601 or epoch ms. Omit to publish immediately"
1621
+ },
1622
+ draft: { type: "boolean", description: "Save as a draft instead" },
1623
+ media: {
1624
+ type: "string",
1625
+ description: "Media URL to attach (repeat for multiple)"
1626
+ },
1627
+ reply: {
1628
+ type: "string",
1629
+ description: "Threaded reply content (repeat for a longer thread)"
1630
+ },
1631
+ "reply-media": {
1632
+ type: "string",
1633
+ description: "Media for a threaded reply as <n>=<url>, where <n> is the 1-based position of the --reply it belongs to (1 = first --reply). Repeat with the same <n> for several files"
1634
+ },
1635
+ comment: {
1636
+ type: "string",
1637
+ description: "First comment to post after publishing (threads, instagram and facebook only). Requires --comment-delay"
1638
+ },
1639
+ "comment-delay": {
1640
+ type: "string",
1641
+ description: `Minutes to wait after publishing before posting --comment, 1-${MAX_COMMENT_DELAY} (7 days)`
1642
+ },
1643
+ "topic-tag": {
1644
+ type: "string",
1645
+ description: "Threads: topic tag for the post"
1646
+ },
1647
+ "board-id": {
1648
+ type: "string",
1649
+ description: "Pinterest: board the pin is created on (required)"
1650
+ },
1651
+ title: {
1652
+ type: "string",
1653
+ description: `Pinterest: pin title, max ${PIN_TITLE_MAX} characters`
1654
+ },
1655
+ link: {
1656
+ type: "string",
1657
+ description: "Pinterest: destination URL the pin links to"
1658
+ },
1659
+ "cover-image-url": {
1660
+ type: "string",
1661
+ description: "Pinterest: cover image for a video pin, used when --media has no image"
1662
+ },
1663
+ "privacy-level": {
1664
+ type: "string",
1665
+ description: `TikTok: who can see the post \u2014 ${PRIVACY_LEVELS.join(" | ")} (required for TikTok; TikTok itself defaults to SELF_ONLY)`
1666
+ },
1667
+ "allow-comments": {
1668
+ type: "boolean",
1669
+ description: "TikTok: allow comments (--no-allow-comments to disable; unset leaves TikTok's default)"
1670
+ },
1671
+ "allow-duet": {
1672
+ type: "boolean",
1673
+ description: "TikTok video: allow duets (--no-allow-duet to disable; ignored on photo posts)"
1674
+ },
1675
+ "allow-stitch": {
1676
+ type: "boolean",
1677
+ description: "TikTok video: allow stitches (--no-allow-stitch to disable; ignored on photo posts)"
1678
+ },
1679
+ "branded-content": {
1680
+ type: "boolean",
1681
+ description: "TikTok: mark as branded content (paid partnership); not allowed with --privacy-level SELF_ONLY"
1682
+ },
1683
+ "brand-organic": {
1684
+ type: "boolean",
1685
+ description: "TikTok: mark as promoting your own brand"
1686
+ },
1687
+ "post-type": {
1688
+ type: "string",
1689
+ description: "Stored on the post as metadata but not read by any platform \u2014 set it only if your own tooling reads it back"
1569
1690
  }
1570
- print(
1571
- summaries.map((row) => ({
1572
- id: row.account.id,
1573
- account: row.account.display_name,
1574
- social: row.account.social,
1575
- collection: formatCollection(row.collection),
1576
- posts: formatValue(row.coverage?.posts_in_range),
1577
- interactions: formatValue(row.interactions?.value),
1578
- remedy: row.collection.remedy ?? ""
1579
- })),
1580
- {
1581
- columns: [
1582
- "id",
1583
- "account",
1584
- "social",
1585
- "collection",
1586
- "posts",
1587
- "interactions",
1588
- "remedy"
1589
- ]
1691
+ },
1692
+ run: ({ args, rawArgs }) => {
1693
+ return guard(async () => {
1694
+ const space = toSpaceId(args["space"]);
1695
+ const accountIds = [
1696
+ ...new Set(
1697
+ repeatedValues(args, rawArgs, "account").map((id) => {
1698
+ return toId(id, "account");
1699
+ })
1700
+ )
1701
+ ];
1702
+ if (accountIds.length === 0) {
1703
+ throw new Error("Pass at least one --account.");
1590
1704
  }
1591
- );
1592
- const totals = summaries.flatMap(
1593
- (row) => row.totals.map((total) => ({
1594
- account: row.account.display_name,
1595
- metric: total.label,
1596
- unit: total.unit,
1597
- value: formatValue(total.value),
1598
- previous: formatValue(total.previous),
1599
- change: formatChange(total.change_pct, total.change_unit),
1600
- note: total.reason ?? ""
1601
- }))
1602
- );
1603
- if (totals.length > 0) {
1604
- heading("Totals");
1605
- print(totals, {
1606
- columns: [
1607
- "account",
1608
- "metric",
1609
- "unit",
1610
- "value",
1611
- "previous",
1612
- "change",
1613
- "note"
1614
- ]
1615
- });
1616
- }
1617
- const rates = summaries.flatMap(
1618
- (row) => row.rates.map((rate) => ({
1619
- account: row.account.display_name,
1620
- rate: rate.label,
1621
- value: formatRate(rate.value),
1622
- per_post: formatRate(rate.per_post_mean),
1623
- previous: formatRate(rate.previous),
1624
- change: formatChange(rate.change_pp, rate.change_unit),
1625
- note: rate.reason ?? ""
1626
- }))
1627
- );
1628
- if (rates.length > 0) {
1629
- heading("Rates");
1630
- print(rates, {
1631
- columns: [
1632
- "account",
1633
- "rate",
1634
- "value",
1635
- "per_post",
1636
- "previous",
1637
- "change",
1638
- "note"
1639
- ]
1640
- });
1641
- }
1642
- })
1643
- });
1644
- function printReport(report) {
1645
- const header = {
1646
- account: formatAccount(report.account),
1647
- range: formatRange(report.range),
1648
- previous: `${report.range.previous_from} to ${report.range.previous_to}`,
1649
- collection: describeCollection(report.collection),
1650
- coverage: report.coverage ? `${report.coverage.posts_in_range} posts (${report.coverage.posts_imported} imported) on ${report.coverage.days_with_posts} of ${report.coverage.days_in_range} days` : "-",
1651
- contract: report.contract
1652
- };
1653
- if (report.basis) {
1654
- header["basis"] = report.basis.comparison_immature ? `${report.basis.values} (comparison window is still maturing)` : report.basis.values;
1655
- header["note"] = report.basis.note;
1656
- }
1657
- print(header);
1658
- if (report.metrics.length === 0) {
1659
- process.stdout.write(
1660
- "\nThis platform has no analytics driver, so there is nothing to report.\n"
1661
- );
1662
- return;
1663
- }
1664
- if (report.totals.length > 0) {
1665
- heading("Totals");
1666
- print(
1667
- report.totals.map((total) => ({
1668
- // The platform's own wording, printed verbatim: Facebook's "Like
1669
- // reactions" and LinkedIn's "Reactions" count different things under
1670
- // the same `likes` key, and only the label says so.
1671
- metric: total.label,
1672
- unit: total.unit,
1673
- value: formatValue(total.value),
1674
- previous: formatValue(total.previous),
1675
- change: formatChange(total.change_pct, total.change_unit),
1676
- note: total.reason ?? ""
1677
- })),
1678
- {
1679
- columns: ["metric", "unit", "value", "previous", "change", "note"]
1705
+ const isDraft = args["draft"] === true;
1706
+ const rawAt = args["at"];
1707
+ if (isDraft && rawAt !== void 0) {
1708
+ throw new Error("--draft and --at are mutually exclusive.");
1680
1709
  }
1681
- );
1682
- }
1683
- const interactions = report.interactions;
1684
- if (interactions) {
1685
- heading(interactions.label);
1686
- print({
1687
- value: formatValue(interactions.value),
1688
- previous: formatValue(interactions.previous),
1689
- change: formatChange(interactions.change_pct, interactions.change_unit),
1690
- // At report scope `components` is a list of keys, not key/value pairs,
1691
- // and on a `mixed` source it is a union — adding it up double-counts.
1692
- source: `${interactions.source}${interactions.native ? ", reported natively" : ""}`,
1693
- components: interactions.components.join(", "),
1694
- status: formatStatus(interactions.status, interactions.reason),
1695
- definition: interactions.definition
1696
- });
1697
- }
1698
- if (report.rates.length > 0) {
1699
- heading("Rates");
1700
- print(
1701
- report.rates.map((rate) => ({
1702
- rate: rate.label,
1703
- value: formatRate(rate.value),
1704
- per_post: formatRate(rate.per_post_mean),
1705
- previous: formatRate(rate.previous),
1706
- change: formatChange(rate.change_pp, rate.change_unit),
1707
- over: rate.denominator_label ?? rate.denominator_key,
1708
- note: rate.reason ?? ""
1709
- })),
1710
- {
1711
- columns: [
1712
- "rate",
1713
- "value",
1714
- "per_post",
1715
- "previous",
1716
- "change",
1717
- "over",
1718
- "note"
1719
- ]
1710
+ const at = rawAt === void 0 ? null : toEpochMs(rawAt);
1711
+ if (at !== null) {
1712
+ const raw = String(rawAt);
1713
+ if (/^\d+$/.test(raw) && at < 1e12) {
1714
+ throw new Error(
1715
+ `--at ${raw} looks like epoch seconds; the API reads epoch milliseconds, so this would schedule for ${new Date(at).toISOString()}.
1716
+ Multiply by 1000, or pass an ISO 8601 timestamp like 2026-08-14T18:00:00Z.`
1717
+ );
1718
+ }
1719
+ if (at <= Date.now()) {
1720
+ throw new Error(
1721
+ `--at ${new Date(at).toISOString()} is in the past; the scheduler never picks up a post whose time has already passed.
1722
+ Omit --at to publish immediately, or pass a future timestamp.`
1723
+ );
1724
+ }
1720
1725
  }
1721
- );
1722
- }
1723
- heading("Metrics");
1724
- print(
1725
- report.metrics.map((metric) => ({
1726
- key: metric.key,
1727
- scope: metric.scope,
1728
- label: metric.label,
1729
- unit: metric.unit,
1730
- role: metric.role,
1731
- window: metric.window_days ?? "",
1732
- status: metric.status,
1733
- note: metric.reason ?? ""
1734
- })),
1735
- {
1736
- columns: [
1737
- "key",
1738
- "scope",
1739
- "label",
1740
- "unit",
1741
- "role",
1742
- "window",
1743
- "status",
1744
- "note"
1745
- ]
1746
- }
1747
- );
1748
- const audience = report.audience;
1749
- const latest = audience.latest;
1750
- if (audience.supported && latest) {
1751
- heading(`Audience (as of ${latest.date})`);
1752
- print(
1753
- audience.metrics.map((key) => ({
1754
- metric: audience.labels?.[key] ?? key,
1755
- value: formatValue(latest.values[key]),
1756
- // latest minus the first point in the window, so an absolute delta.
1757
- change: formatDelta(audience.change?.[key])
1758
- })),
1759
- { columns: ["metric", "value", "change"] }
1760
- );
1761
- }
1762
- const notes = {};
1763
- const series = report.series;
1764
- if (series) {
1765
- const first = series.points.at(0);
1766
- const last = series.points.at(-1);
1767
- const span = first && last ? `, ${first.date} to ${last.date}` : "";
1768
- notes["series"] = `${series.points.length} daily points${span}, values ${series.values} (${series.metrics.join(", ")}). Full series in --json.`;
1769
- }
1770
- if (Object.keys(notes).length > 0) {
1771
- heading("Insights");
1772
- print(notes);
1726
+ const sharedText = readString2(args["text"]);
1727
+ const accountTexts = parseAccountTexts(
1728
+ repeatedValues(args, rawArgs, "account-text"),
1729
+ accountIds
1730
+ );
1731
+ if (sharedText === void 0) {
1732
+ const missing = accountIds.filter((id) => {
1733
+ return !accountTexts.has(id);
1734
+ });
1735
+ if (missing.length > 0) {
1736
+ throw new Error(
1737
+ `No content for account${missing.length > 1 ? "s" : ""} ${missing.join(", ")}.
1738
+ Pass --text for copy shared by every account, or --account-text <accountId>=<text> for each one.`
1739
+ );
1740
+ }
1741
+ }
1742
+ const media2 = repeatedValues(args, rawArgs, "media").map((url) => {
1743
+ return {
1744
+ url,
1745
+ type: mediaTypeForUrl(url)
1746
+ };
1747
+ });
1748
+ const replies = repeatedValues(args, rawArgs, "reply");
1749
+ const replyMedia = parseReplyMedia(
1750
+ repeatedValues(args, rawArgs, "reply-media"),
1751
+ replies.length
1752
+ );
1753
+ const children = replies.map((content, index) => {
1754
+ const attached = replyMedia.get(index + 1);
1755
+ return attached ? { content, media: attached } : { content };
1756
+ });
1757
+ const metadata = buildMetadata(args, rawArgs);
1758
+ const comment = buildComment(args);
1759
+ const api = clientFor(args);
1760
+ const accountById = await resolveAccounts(api, space, accountIds);
1761
+ const items = accountIds.map((accountId) => {
1762
+ const social = accountById.get(accountId).social;
1763
+ const content = accountTexts.get(accountId) ?? sharedText;
1764
+ preflight(accountId, social, content, children, media2, metadata);
1765
+ return {
1766
+ account_id: accountId,
1767
+ social,
1768
+ main: { content, media: media2.length > 0 ? media2 : null },
1769
+ ...children.length > 0 ? { children } : {},
1770
+ ...metadata ? { metadata } : {}
1771
+ };
1772
+ });
1773
+ if (comment) {
1774
+ const socials = accountIds.map((id) => {
1775
+ return accountById.get(id).social;
1776
+ });
1777
+ const limit = commentLimitAcross(socials);
1778
+ const length = charCount(comment.content);
1779
+ if (length > limit) {
1780
+ throw new Error(
1781
+ `--comment is ${length} characters; ${limit} is the cap for this set of accounts (the strictest comment-capable platform in the call wins).`
1782
+ );
1783
+ }
1784
+ const unsupported = [
1785
+ ...new Set(
1786
+ socials.filter((social) => {
1787
+ return !REPLY_CAPABLE.has(social);
1788
+ })
1789
+ )
1790
+ ];
1791
+ if (unsupported.length > 0) {
1792
+ process.stderr.write(
1793
+ `Note: ${unsupported.join(", ")} cannot post a scheduled comment; --comment applies to the other accounts only.
1794
+ `
1795
+ );
1796
+ }
1797
+ const gated = [
1798
+ ...new Set(
1799
+ socials.filter((social) => {
1800
+ return REPLY_CAPABLE.has(social) && !REPLY_ENABLED.has(social);
1801
+ })
1802
+ )
1803
+ ];
1804
+ if (gated.length > 0) {
1805
+ process.stderr.write(
1806
+ `Note: ${gated.join(", ")} is not on the follow-up comment rollout, so --comment is usually dropped for those accounts.
1807
+ `
1808
+ );
1809
+ }
1810
+ }
1811
+ const res = await api.posts.create({
1812
+ path: { space: String(space) },
1813
+ body: {
1814
+ space_id: space,
1815
+ at,
1816
+ is_draft: isDraft,
1817
+ items,
1818
+ ...comment ? { comment } : {}
1819
+ }
1820
+ });
1821
+ const created = res.data?.data ?? [];
1822
+ if (wantsJson(args)) {
1823
+ print(created, { json: true });
1824
+ return;
1825
+ }
1826
+ const rows = created.map((post) => {
1827
+ return {
1828
+ id: post.id,
1829
+ account_id: post.account_id,
1830
+ status: statusLabel(post.status),
1831
+ scheduled_at: post.scheduled_at
1832
+ };
1833
+ });
1834
+ print(rows, {
1835
+ columns: ["id", "account_id", "status", "scheduled_at"]
1836
+ });
1837
+ });
1773
1838
  }
1774
- }
1775
- var account = defineCommand({
1839
+ });
1840
+ var del = defineCommand({
1776
1841
  meta: {
1777
- name: "account",
1778
- description: "The full analytics report for one connected account"
1842
+ name: "delete",
1843
+ description: "Delete a post. The API answers 204 No Content, so --json prints a CLI-made acknowledgement rather than a server payload"
1779
1844
  },
1780
1845
  args: {
1781
1846
  ...globalArgs,
1782
1847
  space: { type: "string", required: true, description: "The space id" },
1783
- account: { type: "string", required: true, description: "The account id" },
1784
- ...windowArgs
1848
+ post: { type: "string", required: true, description: "The post id" }
1785
1849
  },
1786
- run: ({ args }) => guard(async () => {
1787
- const space = toSpaceId(args["space"]);
1788
- const accountId = toId(args["account"], "account");
1789
- const query = windowQuery(args);
1790
- const api = clientFor(args);
1791
- const res = await api.analytics.get({
1792
- path: { space, account: accountId },
1793
- query
1850
+ run: ({ args }) => {
1851
+ return guard(async () => {
1852
+ const space = toSpaceId(args["space"]);
1853
+ const post = toId(args["post"], "post");
1854
+ const api = clientFor(args);
1855
+ await api.posts.delete({ path: { space, post } });
1856
+ if (wantsJson(args)) {
1857
+ print({ deleted: true, id: post }, { json: true });
1858
+ return;
1859
+ }
1860
+ process.stdout.write(`Deleted post ${post}.
1861
+ `);
1794
1862
  });
1795
- const report = res.data?.data;
1796
- if (!report) {
1797
- throw new Error("The API returned no report.");
1798
- }
1799
- if (wantsJson(args)) {
1800
- print(report, { json: true });
1801
- return;
1802
- }
1803
- printReport(report);
1804
- })
1863
+ }
1805
1864
  });
1806
- function postColumnHeaders(columns, taken) {
1807
- const used = new Set(taken);
1808
- return columns.map((column) => {
1809
- let header = column.label;
1810
- if (used.has(header)) {
1811
- header = `${column.label} (${column.key})`;
1865
+ var posts2 = defineCommand({
1866
+ meta: { name: "posts", description: "Manage posts" },
1867
+ subCommands: { list: list2, create, delete: del }
1868
+ });
1869
+ var DAY_LABELS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
1870
+ var DAY_NAMES = /* @__PURE__ */ new Set([
1871
+ "mon",
1872
+ "monday",
1873
+ "tue",
1874
+ "tuesday",
1875
+ "wed",
1876
+ "wednesday",
1877
+ "thu",
1878
+ "thursday",
1879
+ "fri",
1880
+ "friday",
1881
+ "sat",
1882
+ "saturday",
1883
+ "sun",
1884
+ "sunday"
1885
+ ]);
1886
+ function dayLabel(day) {
1887
+ return DAY_LABELS[day - 1] ?? String(day);
1888
+ }
1889
+ function collectRepeated(name, rawArgs, fallback) {
1890
+ const flag = `--${name}`;
1891
+ const inline = `${flag}=`;
1892
+ const values = [];
1893
+ for (let i = 0; i < rawArgs.length; i += 1) {
1894
+ const arg = rawArgs[i];
1895
+ if (arg === "--") {
1896
+ break;
1812
1897
  }
1813
- if (used.has(header)) {
1814
- header = column.key;
1898
+ if (arg === flag) {
1899
+ const next = rawArgs[i + 1];
1900
+ if (next !== void 0 && !next.startsWith("-")) {
1901
+ values.push(next);
1902
+ i += 1;
1903
+ }
1904
+ continue;
1815
1905
  }
1816
- used.add(header);
1817
- return header;
1818
- });
1906
+ if (arg.startsWith(inline)) {
1907
+ values.push(arg.slice(inline.length));
1908
+ }
1909
+ }
1910
+ return values.length > 0 ? values : fallback;
1819
1911
  }
1820
- function printPosts(payload) {
1821
- print({
1822
- account: formatAccount(payload.account),
1823
- range: formatRange(payload.range),
1824
- collection: describeCollection(payload.collection),
1825
- sort: `${payload.sort.key} ${payload.sort.direction}`,
1826
- page: `${payload.meta.current_page} of ${payload.meta.last_page} (${payload.meta.per_page} per page, ${payload.meta.total} posts in range)`,
1827
- contract: payload.contract
1912
+ function toDayNumbers(value) {
1913
+ const tokens = toList(value).flatMap((entry) => {
1914
+ return entry.split(",");
1915
+ }).map((token) => {
1916
+ return token.trim();
1917
+ }).filter((token) => {
1918
+ return token.length > 0;
1828
1919
  });
1829
- const fixed = ["post_id", "published_at", "excerpt", "interactions"];
1830
- const headers = postColumnHeaders(payload.columns, fixed);
1831
- heading("Posts");
1832
- print(
1833
- payload.data.map((post) => {
1834
- const row = {
1835
- post_id: post.post_id,
1836
- // Published timestamps are ISO instants while `range` dates are
1837
- // Y-m-d — two formats on purpose, so neither is reformatted here.
1838
- published_at: post.published_at ?? "-",
1839
- excerpt: oneLine(post.excerpt, 48),
1840
- interactions: formatValue(post.interactions.total)
1841
- };
1842
- payload.columns.forEach((column, index) => {
1843
- row[headers[index] ?? column.key] = formatValue(
1844
- post.metrics[column.key]?.value
1845
- );
1846
- });
1847
- return row;
1848
- }),
1849
- { columns: [...fixed, ...headers] }
1850
- );
1851
- if (payload.columns.length === 0) {
1852
- process.stdout.write(
1853
- "\nThis platform has no analytics driver, so it declares no metric columns.\n"
1854
- );
1855
- }
1856
- const unavailable = payload.columns.map((column, index) => ({ column, header: headers[index] ?? column.key })).filter(({ column }) => column.status !== "ok");
1857
- if (unavailable.length > 0) {
1858
- process.stdout.write("\n");
1859
- for (const { column, header } of unavailable) {
1860
- process.stdout.write(
1861
- `${header}: ${formatStatus(column.status, column.reason)}
1862
- `
1920
+ for (const token of tokens) {
1921
+ const raw = token.toLowerCase();
1922
+ if (!/^\d+$/.test(raw) && !DAY_NAMES.has(raw)) {
1923
+ throw new Error(
1924
+ `Invalid day: ${token}
1925
+ Use 1-7 (1 = Monday, 7 = Sunday) or names like mon,wed,fri.`
1863
1926
  );
1864
1927
  }
1865
1928
  }
1866
- const sortable = payload.sort.options.filter((option) => option.sortable);
1867
- const unhealthy = payload.sort.options.filter((option) => !option.sortable);
1868
- process.stdout.write(
1869
- `
1870
- Sort keys: ${sortable.map((option) => option.key).join(", ")}
1871
- `
1872
- );
1873
- if (unhealthy.length > 0) {
1874
- process.stdout.write(
1875
- `Accepted but currently unmeasured: ${unhealthy.map((option) => option.key).join(", ")}
1876
- `
1929
+ return toDaysOfWeek(tokens);
1930
+ }
1931
+ function toTime(value) {
1932
+ const raw = String(value ?? "").trim();
1933
+ const match = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(raw);
1934
+ const hour = Number(match?.[1]);
1935
+ const minute = Number(match?.[2]);
1936
+ if (!match || match[3] !== void 0 && match[3] !== "00" || hour > 23 || minute > 59) {
1937
+ throw new Error(
1938
+ `Invalid --time value: ${raw}
1939
+ Pass a 24-hour time as HH:MM, for example 09:00 or 17:30.`
1877
1940
  );
1878
1941
  }
1942
+ return `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
1879
1943
  }
1880
- var posts2 = defineCommand({
1944
+ function rethrowWithSlotHint(error) {
1945
+ if (error instanceof ZilfuApiError && error.status === 403) {
1946
+ const hint = /^you have read-only access/i.test(error.message) ? "Hint: this token has read-only access to the workspace, and slot changes additionally require space ownership." : "Hint: adding or removing slots requires space ownership \u2014 members cannot change the schedule, whatever their permissions.";
1947
+ process.stderr.write(`${hint}
1948
+ `);
1949
+ }
1950
+ throw error;
1951
+ }
1952
+ function slotRows(slots2) {
1953
+ return slots2.map((slot) => {
1954
+ return {
1955
+ id: slot.id,
1956
+ day: dayLabel(slot.day_of_week),
1957
+ time: slot.time
1958
+ };
1959
+ });
1960
+ }
1961
+ var SLOT_COLUMNS = ["id", "day", "time"];
1962
+ var list3 = defineCommand({
1963
+ meta: { name: "list", description: "List the posting slots in a space" },
1964
+ args: {
1965
+ ...globalArgs,
1966
+ space: { type: "string", required: true, description: "The space id" }
1967
+ },
1968
+ run: ({ args }) => {
1969
+ return guard(async () => {
1970
+ const space = toSpaceId(args["space"]);
1971
+ const api = clientFor(args);
1972
+ const res = await api.slots.list({ path: { space } });
1973
+ const slots2 = res.data?.data ?? [];
1974
+ if (wantsJson(args)) {
1975
+ print(slots2, { json: true });
1976
+ return;
1977
+ }
1978
+ print(slotRows(slots2), { columns: SLOT_COLUMNS });
1979
+ });
1980
+ }
1981
+ });
1982
+ var create2 = defineCommand({
1881
1983
  meta: {
1882
- name: "posts",
1883
- description: "One row per published post, with this platform's metrics"
1984
+ name: "create",
1985
+ description: "Add a posting slot at one time on one or more days (an existing day is a no-op)"
1884
1986
  },
1885
1987
  args: {
1886
1988
  ...globalArgs,
1887
1989
  space: { type: "string", required: true, description: "The space id" },
1888
- account: { type: "string", required: true, description: "The account id" },
1889
- ...windowArgs,
1890
- sort: {
1990
+ days: {
1891
1991
  type: "string",
1892
- description: "Order by published_at, interactions or any metric key this account declares"
1992
+ required: true,
1993
+ description: "Days for this slot \u2014 mon,wed,fri or 1,3,5 (1 = Monday, 7 = Sunday); comma-separated or repeatable"
1893
1994
  },
1894
- dir: { type: "string", description: "asc or desc (default: desc)" },
1895
- "per-page": {
1995
+ time: {
1896
1996
  type: "string",
1897
- description: `Rows per page, ${MIN_PER_PAGE}-${MAX_PER_PAGE2} (default: 20)`
1898
- },
1899
- page: { type: "string", description: "Page number (default: 1)" }
1900
- },
1901
- run: ({ args }) => guard(async () => {
1902
- const space = toSpaceId(args["space"]);
1903
- const accountId = toId(args["account"], "account");
1904
- const query = windowQuery(args);
1905
- if (args["sort"] !== void 0) {
1906
- query.sort = String(args["sort"]);
1907
- }
1908
- if (args["dir"] !== void 0) {
1909
- query.dir = toDir(args["dir"]);
1910
- }
1911
- if (args["per-page"] !== void 0) {
1912
- query.per_page = toPerPage(args["per-page"]);
1913
- }
1914
- if (args["page"] !== void 0) {
1915
- query.page = toPage(args["page"]);
1997
+ required: true,
1998
+ description: "Time of day in the organization's timezone, as HH:MM (e.g. 09:00)"
1916
1999
  }
1917
- const api = clientFor(args);
1918
- const res = await api.analytics.posts({
1919
- path: { space, account: accountId },
1920
- query
2000
+ },
2001
+ run: ({ args, rawArgs }) => {
2002
+ return guard(async () => {
2003
+ const space = toSpaceId(args["space"]);
2004
+ const days_of_week = toDayNumbers(collectRepeated("days", rawArgs, args["days"]));
2005
+ const time = toTime(args["time"]);
2006
+ const api = clientFor(args);
2007
+ const res = await api.slots.create({ path: { space }, body: { days_of_week, time } }).catch(rethrowWithSlotHint);
2008
+ const slots2 = res.data?.data ?? [];
2009
+ if (wantsJson(args)) {
2010
+ print(slots2, { json: true });
2011
+ return;
2012
+ }
2013
+ print(slotRows(slots2), { columns: SLOT_COLUMNS });
1921
2014
  });
1922
- const payload = res.data;
1923
- if (!payload) {
1924
- throw new Error("The API returned no posts payload.");
1925
- }
1926
- if (wantsJson(args)) {
1927
- print(payload, { json: true });
1928
- return;
1929
- }
1930
- printPosts(payload);
1931
- })
1932
- });
1933
- var analytics = defineCommand({
1934
- meta: { name: "analytics", description: "Read analytics reports" },
1935
- subCommands: { overview, account, posts: posts2 }
2015
+ }
1936
2016
  });
1937
- var upload = defineCommand({
2017
+ var del2 = defineCommand({
1938
2018
  meta: {
1939
- name: "upload",
1940
- description: "Upload a local file and print a URL you can attach to a post"
2019
+ name: "delete",
2020
+ description: "Remove a posting slot (ids come from `slots list`)"
1941
2021
  },
1942
2022
  args: {
1943
2023
  ...globalArgs,
1944
- file: { type: "string", required: true, description: "Path to the file" },
1945
- space: {
1946
- type: "string",
1947
- description: "Also add the upload to this space's media library"
1948
- }
2024
+ space: { type: "string", required: true, description: "The space id" },
2025
+ slot: { type: "string", required: true, description: "The slot id" }
1949
2026
  },
1950
- run: ({ args }) => guard(async () => {
1951
- const path = String(args["file"]);
1952
- const mime = mimeForPath(path);
1953
- const body = await readFile(path);
1954
- const api = clientFor(args);
1955
- const signed = await api.media.sign({ body: { mime } });
1956
- if (!signed.data) {
1957
- throw new Error("The API returned no upload URL.");
1958
- }
1959
- const { upload_url: uploadUrl, url } = signed.data;
1960
- const res = await fetch(uploadUrl, {
1961
- method: "PUT",
1962
- headers: { "Content-Type": mime },
1963
- body: new Uint8Array(body)
1964
- });
1965
- if (!res.ok) {
1966
- throw new Error(
1967
- `Upload failed: ${res.status} ${res.statusText}
1968
- The signed URL expires 15 minutes after it is issued.`
1969
- );
1970
- }
1971
- const type = mediaTypeForMime(mime);
1972
- if (args["space"] !== void 0) {
2027
+ run: ({ args }) => {
2028
+ return guard(async () => {
1973
2029
  const space = toSpaceId(args["space"]);
1974
- await api.media.create({
1975
- path: { space },
1976
- body: { url, type, mime, name: basename(path) }
2030
+ const slot = toId(args["slot"], "slot");
2031
+ const api = clientFor(args);
2032
+ await api.slots.delete({ path: { space, slot } }).catch(rethrowWithSlotHint);
2033
+ if (wantsJson(args)) {
2034
+ print({ deleted: true, id: slot }, { json: true });
2035
+ return;
2036
+ }
2037
+ process.stdout.write(`Deleted slot ${slot}.
2038
+ `);
2039
+ });
2040
+ }
2041
+ });
2042
+ var slots = defineCommand({
2043
+ meta: {
2044
+ name: "slots",
2045
+ description: "Manage a space's recurring posting schedule"
2046
+ },
2047
+ subCommands: { list: list3, create: create2, delete: del2 }
2048
+ });
2049
+ var list4 = defineCommand({
2050
+ meta: { name: "list", description: "List spaces you can access" },
2051
+ args: { ...globalArgs },
2052
+ run: ({ args }) => {
2053
+ return guard(async () => {
2054
+ const api = clientFor(args);
2055
+ const res = await api.spaces.list();
2056
+ print(res.data?.data ?? [], {
2057
+ json: wantsJson(args),
2058
+ columns: ["id", "name", "timezone"]
1977
2059
  });
1978
- }
1979
- print({ url, type, mime }, { json: wantsJson(args) });
1980
- })
2060
+ });
2061
+ }
1981
2062
  });
1982
- var media = defineCommand({
1983
- meta: { name: "media", description: "Upload and manage media" },
1984
- subCommands: { upload }
2063
+ var spaces = defineCommand({
2064
+ meta: { name: "spaces", description: "Manage spaces" },
2065
+ subCommands: { list: list4 }
2066
+ });
2067
+ var whoami = defineCommand({
2068
+ meta: { name: "whoami", description: "Show the authenticated user" },
2069
+ args: { ...globalArgs },
2070
+ run: ({ args }) => {
2071
+ return guard(async () => {
2072
+ const api = clientFor(args);
2073
+ const res = await api.session.get();
2074
+ print(res.data?.data ?? {}, { json: wantsJson(args) });
2075
+ });
2076
+ }
1985
2077
  });
1986
2078
 
1987
2079
  // src/cli.ts
@@ -1998,7 +2090,7 @@ var main = defineCommand({
1998
2090
  health,
1999
2091
  spaces,
2000
2092
  accounts,
2001
- posts,
2093
+ posts: posts2,
2002
2094
  slots,
2003
2095
  analytics,
2004
2096
  media