@metricraven/cli 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,7 +13,7 @@ Node.js 20 or later.
13
13
 
14
14
  ## Log in
15
15
 
16
- Create an access token in **Settings → API & MCP** (https://metricraven.com/app/api), then:
16
+ Create an access token on the **API & MCP** page (https://metricraven.com/app/api), then:
17
17
 
18
18
  ```bash
19
19
  metricraven login # paste the token (hidden)
@@ -38,12 +38,14 @@ The token is saved to `~/.config/metricraven/config.json` (or `$XDG_CONFIG_HOME/
38
38
  | `analytics traffic` | Visitors, pageviews, revenue, conversion rate and top sources |
39
39
  | `analytics breakdown <dimension>` | Full table for `channel`, `referrer`, `page`, `utmSource`, `country`, `device`, … |
40
40
  | `analytics revenue` | Payments, renewals, refunds, LTV, revenue by channel |
41
+ | `analytics mrr [day\|week\|month]` | MRR over time: new, expansion, contraction, churn |
41
42
  | `analytics conversions` | Goals and funnel steps |
42
43
  | `analytics goal <name>` | One goal with its sources and properties |
43
44
  | `analytics insights` | What converts and how long buyers take |
44
45
  | `analytics search` | Google Search Console queries |
45
46
  | `analytics crawlers` | AI crawlers and bots |
46
- | `analytics meta-ads [campaign\|adset\|ad]` | Meta Ads spend, attributed revenue, ROAS and cost per customer |
47
+ | `analytics ads [campaign\|adgroup\|ad] [--provider all\|meta\|google\|tiktok] [--account <id>]` | Ad spend from every connected network, attributed and assisted revenue, ROAS and cost per customer, with each network's own reported value (Meta-reported, Google-reported) for comparison. `--account` reports one chosen ad account alone (the IDs are listed when several are combined; Google IDs with or without dashes, Meta without `act_`) |
48
+ | `analytics meta-ads [campaign\|adset\|ad] [--account <id>]` | Meta Ads spend, attributed revenue, ROAS and cost per customer |
47
49
  | `realtime` | Visitors online now |
48
50
  | `visitors list`, `visitors get <id>` | Visitors and journeys (token needs visitor details access) |
49
51
  | `visitors list --page /pricing --goal signup --visits-gt 2` | Search visitors by visited page (`--page`, `--page-contains`), completed goal, `--referrer`, `--channel`, `--source`, `--utm-source/medium/campaign`, `--country`, `--device`, `--browser`, `--os` and visits in the period (`--visits-gt`, `--visits-lt`) |
@@ -53,13 +55,19 @@ The token is saved to `~/.config/metricraven/config.json` (or `$XDG_CONFIG_HOME/
53
55
  | `goals set <goal> [--name] [--color] [--description] [--hidden\|--visible]`, `goals reset <goal>` | Change how a goal is shown (needs write access, admin) |
54
56
  | `notes list`, `notes add --text [--date]` | Chart notes (adding needs write access) |
55
57
  | `mentions [--platform x\|reddit] [--q text]` | X and Reddit posts mentioning the website (Growth plan) |
58
+ | `ai-visibility` | What AI assistants answer to your tracked prompts (Growth plan); `--period` for the trend (default 90d) |
59
+ | `alerts list\|get <id>\|history`, `alerts create --goal <name>` (or `--trigger payment\|new_customer`), `alerts update <id>`, `alerts delete <id>` | Conversion alerts; `--recipients a@x.com,b@x.com\|all` picks who gets them (changes need write access) |
60
+ | `members list`, `members invite <email> --role admin\|viewer`, `members role <user_id> --role …`, `members remove <user_id>`, `members revoke <invite_id>` | The website's team (changes need write access, admin) |
61
+ | `bots settings\|usage`, `bots settings --verified-only on\|off`, `bots exclude\|include <name…> [--company]`, `bots require-token on\|off` | Bot traffic settings (`--verified-only on` records only IP-verified crawlers) and the bot request allowance |
62
+ | `proxy status\|enable <subdomain>\|check\|remove` | The managed proxy subdomain that serves the script |
56
63
  | `completion bash\|zsh\|fish` | Shell completion script |
57
64
 
58
- Reports cover the last 30 days by default. Use `--period today|yesterday|24h|7d|30d|90d|6m|1y|wtd|mtd|all`, or `--from 2026-10-01 --to 2026-10-31`, with `--timezone Europe/Madrid` for day boundaries. `--compare year` (or a `YYYY-MM-DD` start) changes what the change figures compare against; the default is the previous period of equal length. Filter with `--filter dimension:operator:value` (repeatable; operators `is`, `is_not`, `contains`, `not_contains`, and `gt`/`lt` for `visits`, e.g. `-f visits:gt:2`).
65
+ Reports cover the last 30 days by default. Use `--period today|yesterday|24h|7d|30d|90d|6m|1y|wtd|mtd|all`, or `--from 2026-10-01 --to 2026-10-31`, with `--timezone Europe/Madrid` for day boundaries. `--compare year` (or a `YYYY-MM-DD` start) changes what the change figures compare against; the default is the previous period of equal length. `--compare off` shows no comparison: no change column, and the comparison fields are left out of `--json`. Filter with `--filter dimension:operator:value` (repeatable; operators `is`, `is_not`, `contains`, `not_contains`, and `gt`/`lt` for `visits`, e.g. `-f visits:gt:2`).
59
66
 
60
67
  ```bash
61
68
  metricraven analytics traffic --period 7d
62
69
  metricraven analytics breakdown referrer --sort revenue --limit 20
70
+ metricraven analytics breakdown page --sort visitors --order asc # least-visited pages first
63
71
  metricraven analytics traffic -f country:is:US -f device:is:mobile --json | jq .overview
64
72
  ```
65
73
 
@@ -78,6 +86,6 @@ metricraven analytics traffic -p 7d --fields overview.current,series.date,series
78
86
  metricraven analytics breakdown country --fields rows.name,rows.revenue
79
87
  ```
80
88
 
81
- Global flags: `--site <id>`, `--json`, `--verbose` (request URLs and status codes on stderr), `--help`, `--version`.
89
+ Global flags: `--site <id>`, `--json`, `--fields`, `--verbose` (request URLs and status codes on stderr), `--help`, `--version`.
82
90
 
83
91
  Full documentation: https://metricraven.com/docs/cli
package/dist/args.js CHANGED
@@ -17,6 +17,8 @@ const OPTIONS = {
17
17
  filter: { type: "string", short: "f", multiple: true },
18
18
  compare: { type: "string" },
19
19
  sort: { type: "string" },
20
+ // analytics breakdown: asc or desc (by --sort)
21
+ order: { type: "string" },
20
22
  limit: { type: "string", short: "n" },
21
23
  offset: { type: "string" },
22
24
  q: { type: "string" },
@@ -31,6 +33,7 @@ const OPTIONS = {
31
33
  subject: { type: "string" },
32
34
  message: { type: "string" },
33
35
  notify: { type: "string" },
36
+ recipients: { type: "string" },
34
37
  enabled: { type: "boolean" },
35
38
  disabled: { type: "boolean" },
36
39
  yes: { type: "boolean", short: "y" },
@@ -43,6 +46,7 @@ const OPTIONS = {
43
46
  company: { type: "boolean" },
44
47
  // analytics ads
45
48
  provider: { type: "string" },
49
+ account: { type: "string" },
46
50
  // tokens create
47
51
  scopes: { type: "string" },
48
52
  sites: { type: "string" },
@@ -67,6 +71,8 @@ const OPTIONS = {
67
71
  "visits-gt": { type: "string" },
68
72
  "visits-lt": { type: "string" },
69
73
  grace: { type: "string" },
74
+ // bots settings
75
+ "verified-only": { type: "string" },
70
76
  };
71
77
  export class UsageError extends Error {
72
78
  }
package/dist/commands.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ApiError, createClient } from "./api.js";
2
2
  import { UsageError, buildFilters, positiveInt, rangeParams } from "./args.js";
3
3
  import { customRange, validTimeZone } from "./range.js";
4
- import { completionScript } from "./completion.js";
4
+ import { AD_PROVIDER_VALUES, completionScript } from "./completion.js";
5
5
  import { configPath, deleteConfigToken, readConfig, resolveSettings, updateConfig } from "./config.js";
6
6
  import { bold, change, date, dim, duration, money, num, pct, section, table, terminalSafe, truncate } from "./format.js";
7
7
  import { interactive, prompt, promptHidden, readStdin } from "./prompt.js";
@@ -124,7 +124,7 @@ async function login(flags) {
124
124
  let token = flags.token?.trim();
125
125
  if (!token) {
126
126
  if (process.stdin.isTTY) {
127
- out(`Create an access token at ${bold(TOKENS_URL)} (Settings → API & MCP), then paste it here.`);
127
+ out(`Create an access token at ${bold(TOKENS_URL)} (API & MCP), then paste it here.`);
128
128
  token = await promptHidden("Token: ");
129
129
  }
130
130
  else
@@ -220,7 +220,7 @@ async function useSite({ flags, client }, id) {
220
220
  out(`Default website: ${bold(site.name)} (${id}).`);
221
221
  return 0;
222
222
  }
223
- const REPORTS = ["traffic", "revenue", "conversions", "insights", "search", "crawlers", "ads", "meta-ads"];
223
+ const REPORTS = ["traffic", "revenue", "mrr", "conversions", "insights", "search", "crawlers", "ads", "meta-ads"];
224
224
  async function analytics(ctx, sub, rest) {
225
225
  const { flags, client } = ctx;
226
226
  if (!sub)
@@ -233,6 +233,11 @@ async function analytics(ctx, sub, rest) {
233
233
  params.set("dimension", dimension);
234
234
  if (flags.sort)
235
235
  params.set("sort", flags.sort);
236
+ if (flags.order) {
237
+ if (flags.order !== "asc" && flags.order !== "desc")
238
+ throw new UsageError("Use --order asc or desc (by the --sort column, visitors by default).");
239
+ params.set("order", flags.order);
240
+ }
236
241
  if (flags.q)
237
242
  params.set("q", flags.q);
238
243
  const limit = positiveInt(flags.limit, "limit", 100);
@@ -247,36 +252,68 @@ async function analytics(ctx, sub, rest) {
247
252
  throw new UsageError("Use: metricraven analytics goal <name>");
248
253
  params.set("name", rest[0]);
249
254
  }
250
- else if (sub === "meta-ads" && rest[0]) {
251
- if (!["campaign", "adset", "ad"].includes(rest[0]))
252
- throw new UsageError("Use: metricraven analytics meta-ads [campaign|adset|ad]");
253
- params.set("level", rest[0]);
255
+ else if (sub === "meta-ads" && (rest[0] || flags.account)) {
256
+ if (rest[0] && !["campaign", "adset", "ad"].includes(rest[0]))
257
+ throw new UsageError("Use: metricraven analytics meta-ads [campaign|adset|ad] [--account <id>]");
258
+ if (rest[0])
259
+ params.set("level", rest[0]);
260
+ if (flags.account)
261
+ params.set("account", adAccountId(flags.account));
262
+ }
263
+ else if (sub === "mrr") {
264
+ if (rest[0] && !["day", "week", "month"].includes(rest[0]))
265
+ throw new UsageError("Use: metricraven analytics mrr [day|week|month]");
266
+ if (rest[0])
267
+ params.set("granularity", rest[0]);
254
268
  }
255
269
  else if (sub === "ads") {
256
270
  if (rest[0] && !["campaign", "adgroup", "adset", "ad"].includes(rest[0]))
257
- throw new UsageError("Use: metricraven analytics ads [campaign|adgroup|ad] [--provider all|meta|google]");
271
+ throw new UsageError(`Use: metricraven analytics ads [campaign|adgroup|ad] [--provider ${AD_PROVIDER_VALUES.join("|")}] [--account <id>]`);
258
272
  if (rest[0])
259
273
  params.set("level", rest[0]);
260
274
  if (flags.provider) {
261
- if (!["all", "meta", "google", "tiktok"].includes(flags.provider))
262
- throw new UsageError("Use --provider all, meta or google.");
275
+ if (!AD_PROVIDER_VALUES.includes(flags.provider))
276
+ throw new UsageError("Use --provider all, meta, google or tiktok (TikTok Ads can't be connected yet).");
263
277
  params.set("provider", flags.provider);
264
278
  }
279
+ if (flags.account)
280
+ params.set("account", adAccountId(flags.account));
265
281
  }
266
282
  else if (!REPORTS.includes(sub)) {
267
283
  throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal"].join(", ")}.`);
268
284
  }
269
285
  params.set("site", await ctx.site());
270
286
  const selected = selectFields(flags, params);
271
- const path = sub === "breakdown" ? "/stats/breakdown" : sub === "goal" ? "/stats/goal" : `/stats/${sub}`;
272
- const data = await client.get(path, params);
287
+ const path = sub === "breakdown" ? "/stats/breakdown" : sub === "goal" ? "/stats/goal" : sub === "mrr" ? "/stats/mrr-history" : `/stats/${sub}`;
288
+ const fetched = await client.get(path, params);
289
+ const data = flags.compare === "off" ? withoutComparison(fetched) : fetched;
273
290
  if (flags.json || selected)
274
291
  return printJson(data), 0;
292
+ if ((sub === "ads" || sub === "meta-ads") && flags.account && data.configured === false) {
293
+ out(`Ad account ${params.get("account")} is not one of this website's chosen ad accounts${params.get("provider") && params.get("provider") !== "all" ? ` on ${NETWORKS[params.get("provider")] ?? params.get("provider")}` : ""}. Run the report without --account to list them.`);
294
+ return 0;
295
+ }
275
296
  const render = RENDER[sub];
276
297
  out(render ? render(data) : JSON.stringify(data, null, 2));
277
298
  return 0;
278
299
  }
300
+ /**
301
+ * --account: one chosen ad account alone (GET /stats/ads ?account=). The ID as the dashboard
302
+ * shows it: Meta without "act_", Google with or without dashes (123-456-7890).
303
+ */
304
+ export function adAccountId(v) {
305
+ const id = v.trim().replace(/^act_/, "");
306
+ const google = /^\d{3}-\d{3}-\d{4}$/.test(id) ? id.replace(/-/g, "") : id;
307
+ if (!/^[A-Za-z0-9_-]{1,40}$/.test(google))
308
+ throw new UsageError("Use --account <ad account ID> (letters, digits, - and _; see adAccounts[] in --json).");
309
+ return google;
310
+ }
279
311
  const NETWORKS = { meta: "Meta Ads", google: "Google Ads", tiktok: "TikTok Ads" };
312
+ /** What each network's own reported value is called (never part of revenue or ROAS). */
313
+ const REPORTED = {
314
+ meta: { label: "Meta-reported purchase value", count: "purchases" },
315
+ google: { label: "Google-reported conversion value", count: "conversions" },
316
+ };
280
317
  /** analytics ads and analytics meta-ads (the same response shape). */
281
318
  function renderAds(d) {
282
319
  if (!d.configured)
@@ -291,6 +328,16 @@ function renderAds(d) {
291
328
  return [
292
329
  ...(d.accounts ?? []).map((a) => dim(`${NETWORKS[a.provider] ?? a.provider}: ${a.name}${d.sample ? " · sample data" : ""} · days ${a.days.from} → ${a.days.to} (${a.timeZone})`)),
293
330
  `${combined ? "All networks: s" : "S"}pend ${money(t.spend, cur)} · revenue ${money(t.revenue, cur)} · ROAS ${roas(t.roas)} · ${num(t.customers)} customers · cost per customer ${t.costPerCustomer === null ? "–" : money(t.costPerCustomer, cur)} · assisted ${money(t.assistedRevenue ?? 0, cur)}`,
331
+ ...(d.accounts ?? []).map((a) => {
332
+ const r = REPORTED[a.provider];
333
+ if (!r || a.totals?.reportedValue === undefined)
334
+ return "";
335
+ return dim(`${r.label}: ${money(a.totals.reportedValue, cur)} (${num(a.totals.reportedPurchases ?? 0, 2)} ${r.count}, ${roas(a.totals.reportedRoas)} by its own count). Not in revenue or ROAS.`);
336
+ }),
337
+ // Several chosen accounts: name them with their IDs for --account.
338
+ (d.adAccounts?.length ?? 0) > 1
339
+ ? dim(`Ad accounts: ${d.adAccounts.map((a) => `${a.name} (${a.id}${combined || new Set(d.adAccounts.map((x) => x.provider)).size > 1 ? `, ${(NETWORKS[a.provider] ?? a.provider).replace(" Ads", "")}` : ""})${d.accountFilter === a.id ? " ← shown" : ""}`).join(", ")}${d.accountFilter ? "" : ". One alone: --account <id>"}`)
340
+ : "",
294
341
  ...(d.accounts ?? []).flatMap((a) => [
295
342
  a.sync.error ? dim(`${NETWORKS[a.provider] ?? a.provider} sync: ${a.sync.error}`) : "",
296
343
  a.unconvertedSpend ? dim(`${money(a.unconvertedSpend, a.currency)} of ${NETWORKS[a.provider] ?? a.provider} spend has no exchange rate yet and is left out.`) : "",
@@ -325,15 +372,42 @@ function periodLine(p) {
325
372
  const rowsTable = (rows, label, currency, limit = 5) => rows?.length
326
373
  ? table([label, "Visitors", "Revenue"], rows.slice(0, limit).map((r) => [truncate(r.name), num(r.visitors), r.revenue === undefined ? "–" : money(r.revenue, currency)]), ["left", "right", "right"])
327
374
  : dim("No data.");
375
+ const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
376
+ /**
377
+ * --compare off: reports always come with a comparison (the API compares with the previous period
378
+ * unless told otherwise), so the CLI leaves those parts out: the overview's previous figures and
379
+ * change percentages, previous-period series, insights' source changes and the subscription
380
+ * events' changes.
381
+ */
382
+ export function withoutComparison(data) {
383
+ const { previous: _p, previousSeries: _s, previousPeriod: _pp, sourceChanges: _c, ...rest } = data;
384
+ const out = { ...rest };
385
+ if (isObject(rest.overview)) {
386
+ const { previous: _op, change: _oc, ...overview } = rest.overview;
387
+ out.overview = overview;
388
+ }
389
+ if (isObject(rest.lifecycle) && Array.isArray(rest.lifecycle.goals))
390
+ out.lifecycle = {
391
+ ...rest.lifecycle,
392
+ goals: rest.lifecycle.goals.map((g) => {
393
+ if (!isObject(g))
394
+ return g;
395
+ const { previous: _gp, change: _gc, ...goal } = g;
396
+ return goal;
397
+ }),
398
+ };
399
+ return out;
400
+ }
328
401
  const RENDER = {
329
402
  traffic(d) {
330
403
  const c = d.overview.current;
331
404
  const ch = d.overview.change;
332
405
  const cur = d.period.currency ?? "USD";
333
- const metric = (label, value, key, lowerIsBetter = false) => [label, value, change(ch[key], { lowerIsBetter })];
406
+ // No change column with --compare off (the report then has no overview.change).
407
+ const metric = (label, value, key, lowerIsBetter = false) => ch ? [label, value, change(ch[key], { lowerIsBetter })] : [label, value];
334
408
  return [
335
409
  periodLine(d.period),
336
- table(["Metric", "Value", "vs previous"], [
410
+ table(ch ? ["Metric", "Value", "vs previous"] : ["Metric", "Value"], [
337
411
  metric("Visitors", num(c.visitors), "visitors"),
338
412
  metric("Pageviews", num(c.pageviews), "pageviews"),
339
413
  metric("Visits", num(c.sessions), "sessions"),
@@ -342,7 +416,7 @@ const RENDER = {
342
416
  metric("Revenue", money(c.revenue, cur), "revenue"),
343
417
  metric("Conversion rate", pct(c.conversionRate, 2), "conversionRate"),
344
418
  metric("Revenue / visitor", money(c.revenuePerVisitor, cur), "revenuePerVisitor"),
345
- ], ["left", "right", "right"]),
419
+ ], ch ? ["left", "right", "right"] : ["left", "right"]),
346
420
  section("Top channels", rowsTable(d.channels, "Channel", cur)),
347
421
  section("Top pages", rowsTable(d.pages, "Page", cur)),
348
422
  section("Top countries", rowsTable(d.countries, "Country", cur)),
@@ -360,23 +434,53 @@ const RENDER = {
360
434
  const c = d.overview.current;
361
435
  const ch = d.overview.change;
362
436
  const cur = d.period.currency ?? "USD";
437
+ const rows = [
438
+ ["Revenue", money(c.revenue, cur), change(ch?.revenue)],
439
+ ["New revenue", money(c.newRevenue, cur), change(ch?.newRevenue)],
440
+ ["Renewal revenue", money(c.renewalRevenue, cur), change(ch?.renewalRevenue)],
441
+ ["New payments", num(c.newPayments), change(ch?.newPayments)],
442
+ ["Renewals", num(c.renewals), change(ch?.renewals)],
443
+ ["Paying customers", num(c.payingCustomers), change(ch?.payingCustomers)],
444
+ ["Refunds", `${num(c.refunds)} (${money(c.refundedAmount, cur)})`, ""],
445
+ ];
363
446
  return [
364
447
  periodLine(d.period),
365
- table(["Metric", "Value", "vs previous"], [
366
- ["Revenue", money(c.revenue, cur), change(ch.revenue)],
367
- ["New revenue", money(c.newRevenue, cur), change(ch.newRevenue)],
368
- ["Renewal revenue", money(c.renewalRevenue, cur), change(ch.renewalRevenue)],
369
- ["New payments", num(c.newPayments), change(ch.newPayments)],
370
- ["Renewals", num(c.renewals), change(ch.renewals)],
371
- ["Paying customers", num(c.payingCustomers), change(ch.payingCustomers)],
372
- ["Refunds", `${num(c.refunds)} (${money(c.refundedAmount, cur)})`, ""],
373
- ], ["left", "right", "right"]),
448
+ // No change column with --compare off (the report then has no overview.change).
449
+ ch
450
+ ? table(["Metric", "Value", "vs previous"], rows, ["left", "right", "right"])
451
+ : table(["Metric", "Value"], rows.map(([label, value]) => [label, value]), ["left", "right"]),
374
452
  section("Revenue by channel (first touch)", d.byChannel?.length
375
453
  ? table(["Channel", "Revenue", "New", "Renewals"], d.byChannel.slice(0, 8).map((r) => [r.name, money(r.revenue, cur), num(r.newPayments), num(r.renewals)]), ["left", "right", "right", "right"])
376
454
  : dim("No payments.")),
377
455
  d.ltv ? section("Lifetime value", `${num(d.ltv.customers)} customers · average ${money(d.ltv.average, cur)}`) : "",
378
456
  ].join("\n");
379
457
  },
458
+ mrr(d) {
459
+ if (!d.available || !d.series || !d.summary)
460
+ return dim(d.reason ?? "No MRR history yet.");
461
+ const cur = d.currency;
462
+ const s = d.summary;
463
+ const m = (n) => (n === null ? "–" : money(n, cur));
464
+ const points = d.series.filter((p) => p.mrr !== null);
465
+ return [
466
+ periodLine(d.period),
467
+ table(["Metric", "Value"], [
468
+ ["MRR at end", `${m(s.endMrr)}${s.change !== null ? ` (${s.change > 0 ? "+" : ""}${s.change}% in period)` : ""}`],
469
+ ["MRR at start", m(s.startMrr)],
470
+ ["New", `${m(s.newMrr)} · ${num(s.newSubscriptions)} started paying`],
471
+ ["Expansion", m(s.expansionMrr)],
472
+ ["Contraction", m(s.contractionMrr)],
473
+ ["Churned", `${m(s.churnedMrr)} · ${num(s.churned)} stopped paying`],
474
+ ["Net new", m(s.netNewMrr)],
475
+ ], ["left", "right"]),
476
+ section(`MRR by ${d.period.granularity ?? "day"} (last 12)`, points.length
477
+ ? table(["Date", "MRR", "Active", "Net new", ""], points.slice(-12).map((p) => [p.date, m(p.mrr), num(p.active), m(p.netNewMrr), p.reconstructed ? dim("reconstructed") : ""]), ["left", "right", "right", "right", "left"])
478
+ : dim("No MRR recorded in this period.")),
479
+ d.demo ? dim("Sample history (demo).") : "",
480
+ ]
481
+ .filter(Boolean)
482
+ .join("\n");
483
+ },
380
484
  conversions(d) {
381
485
  // Hidden goals (Settings → Goals) stay out of the table, like the dashboard; --json has them all.
382
486
  const shown = d.goals.filter((g) => !g.hidden);
@@ -714,6 +818,22 @@ async function goals(ctx, sub, rest) {
714
818
  }
715
819
  throw new UsageError(`Unknown command "goals ${sub}". Use list, set, reset or colors.`);
716
820
  }
821
+ /**
822
+ * `--recipients a@x.com,b@x.com` (emails or user IDs), or `all` for every current member. The API
823
+ * checks each one is a member of the website.
824
+ */
825
+ function recipientsFlag(flags) {
826
+ if (flags.recipients !== undefined && flags.notify !== undefined)
827
+ throw new UsageError("Use --recipients or --notify, not both.");
828
+ if (flags.notify !== undefined)
829
+ return { notify: flags.notify };
830
+ if (flags.recipients === undefined)
831
+ return {};
832
+ const list = flags.recipients.split(",").map((r) => r.trim()).filter(Boolean);
833
+ if (!list.length)
834
+ throw new UsageError("--recipients needs member emails or user IDs, comma-separated, or all.");
835
+ return list.length === 1 && list[0].toLowerCase() === "all" ? { notify: "members" } : { recipients: list };
836
+ }
717
837
  const triggerText = (t) => (t.type === "goal" ? `goal ${t.goalName}` : t.type === "payment" ? "any payment" : "new customer");
718
838
  /** `metricraven alerts …`: conversion alerts on the website (list/get/create/update/delete/history). */
719
839
  async function alerts(ctx, sub, rest) {
@@ -747,6 +867,8 @@ async function alerts(ctx, sub, rest) {
747
867
  out(bold(a.name));
748
868
  out(`Trigger: ${triggerText(a.trigger)} · ${a.isEnabled ? "enabled" : "disabled"}`);
749
869
  out(`Recipients: ${a.recipients.map((r) => r.email).join(", ") || "none"}`);
870
+ if (a.optedOut?.length)
871
+ out(`Unsubscribed: ${a.optedOut.map((r) => r.email).join(", ")}`);
750
872
  if (a.template.subject)
751
873
  out(`Subject: ${a.template.subject}`);
752
874
  if (a.template.message)
@@ -772,7 +894,7 @@ async function alerts(ctx, sub, rest) {
772
894
  name: flags.name,
773
895
  trigger: type === "goal" ? { type, goalName: goal } : { type },
774
896
  template: flags.subject || flags.message ? { subject: flags.subject, message: flags.message } : undefined,
775
- notify: flags.notify,
897
+ ...recipientsFlag(flags),
776
898
  isEnabled: flags.disabled ? false : undefined,
777
899
  };
778
900
  const d = await needs("write", client.post("/alerts", body, params()));
@@ -789,9 +911,10 @@ async function alerts(ctx, sub, rest) {
789
911
  name: flags.name,
790
912
  trigger: flags.goal ? { type: "goal", goalName: flags.goal } : undefined,
791
913
  isEnabled: flags.enabled ? true : flags.disabled ? false : undefined,
914
+ ...recipientsFlag(flags),
792
915
  };
793
916
  if (Object.values(body).every((v) => v === undefined))
794
- throw new UsageError("Nothing to change. Use --name, --goal, --enabled or --disabled.");
917
+ throw new UsageError("Nothing to change. Use --name, --goal, --enabled, --disabled or --recipients.");
795
918
  const d = await needs("write", client.patch(alertPath(rest[0]), body, params()));
796
919
  if (flags.json)
797
920
  return printJson(d), 0;
@@ -915,6 +1038,7 @@ function printBotSettings(d) {
915
1038
  out(`Excluded agents: ${list(d.settings.excludedAgents)}`);
916
1039
  out(`Bot token: ${d.token.hasToken ? `${d.token.hint ?? "set"}${d.token.lastUsedAt ? `, last used ${date(d.token.lastUsedAt)}` : ", not used yet"}` : "none (create one in Settings → Tracking & install)"}`);
917
1040
  out(`Require bot token: ${d.settings.rejectWithoutToken ? "yes" : "no"}`);
1041
+ out(`Verified only: ${d.settings.verifiedOnly ? "yes (crawler events from outside the published IP ranges are dropped)" : "no"}`);
918
1042
  }
919
1043
  /** `metricraven bots …`: bot traffic settings (exclusions, token enforcement) and the bot request allowance. */
920
1044
  async function bots(ctx, sub, rest) {
@@ -923,6 +1047,18 @@ async function bots(ctx, sub, rest) {
923
1047
  const params = () => new URLSearchParams({ site });
924
1048
  switch (sub ?? "settings") {
925
1049
  case "settings": {
1050
+ const verifiedOnly = flags["verified-only"];
1051
+ if (verifiedOnly !== undefined) {
1052
+ if (verifiedOnly !== "on" && verifiedOnly !== "off")
1053
+ throw new UsageError("Use: metricraven bots settings --verified-only on|off");
1054
+ const d = await needs("write", client.patch("/bot-traffic/settings", { verifiedOnly: verifiedOnly === "on" }, params()));
1055
+ if (flags.json)
1056
+ return printJson(d), 0;
1057
+ out(verifiedOnly === "on"
1058
+ ? "Only IP-verified crawler events are recorded now; events from outside a crawler's published IP ranges are dropped."
1059
+ : "Crawler events are recorded whether or not their IP is verified.");
1060
+ return 0;
1061
+ }
926
1062
  const d = await client.get("/bot-traffic/settings", params());
927
1063
  if (flags.json)
928
1064
  return printJson(d), 0;
@@ -1,4 +1,6 @@
1
1
  import { UsageError } from "./args.js";
2
+ /** --provider values of `analytics ads`: what GET /stats/ads accepts (TikTok Ads can't be connected yet). */
3
+ export const AD_PROVIDER_VALUES = ["all", "meta", "google", "tiktok"];
2
4
  /** Shell completion scripts for `metricraven completion bash|zsh|fish`. */
3
5
  const COMMANDS = ["login", "logout", "whoami", "account", "tokens", "payments", "use", "websites", "analytics", "realtime", "visitors", "funnels", "goals", "notes", "mentions", "ai-visibility", "alerts", "members", "bots", "proxy", "completion"];
4
6
  const SUB = {
@@ -6,7 +8,7 @@ const SUB = {
6
8
  account: ["get", "update"],
7
9
  tokens: ["list", "create", "delete"],
8
10
  payments: ["delete"],
9
- analytics: ["traffic", "breakdown", "revenue", "conversions", "goal", "insights", "search", "crawlers", "ads", "meta-ads"],
11
+ analytics: ["traffic", "breakdown", "revenue", "mrr", "conversions", "goal", "insights", "search", "crawlers", "ads", "meta-ads"],
10
12
  visitors: ["list", "get"],
11
13
  funnels: ["list"],
12
14
  goals: ["list", "set", "reset", "colors", "delete-events"],
@@ -18,15 +20,28 @@ const SUB = {
18
20
  proxy: ["status", "enable", "check", "remove"],
19
21
  completion: ["bash", "zsh", "fish"],
20
22
  };
21
- const FLAGS = ["--json", "--fields", "--site", "--token", "--verbose", "--help", "--version", "--period", "--from", "--to", "--timezone", "--filter", "--compare", "--sort", "--limit", "--offset", "--q", "--payment", "--name", "--domain", "--date", "--text", "--goal", "--trigger", "--subject", "--message", "--notify", "--enabled", "--disabled", "--yes", "--alert", "--platform", "--role", "--color", "--description", "--hidden", "--visible", "--company", "--scopes", "--sites", "--transaction", "--visitor", "--user", "--dry-run", "--page", "--page-contains", "--referrer", "--channel", "--source", "--utm-source", "--utm-medium", "--utm-campaign", "--country", "--device", "--browser", "--os", "--visits-gt", "--visits-lt", "--grace", "--provider"];
23
+ const FLAGS = ["--json", "--fields", "--site", "--token", "--verbose", "--help", "--version", "--period", "--from", "--to", "--timezone", "--filter", "--compare", "--sort", "--limit", "--offset", "--q", "--payment", "--name", "--domain", "--date", "--text", "--goal", "--trigger", "--subject", "--message", "--notify", "--recipients", "--enabled", "--disabled", "--yes", "--alert", "--platform", "--role", "--color", "--description", "--hidden", "--visible", "--company", "--scopes", "--sites", "--transaction", "--visitor", "--user", "--dry-run", "--page", "--page-contains", "--referrer", "--channel", "--source", "--utm-source", "--utm-medium", "--utm-campaign", "--country", "--device", "--browser", "--os", "--visits-gt", "--visits-lt", "--grace", "--provider", "--account", "--order", "--verified-only"];
24
+ /** Flags with a fixed set of values; completion offers them after the flag. */
25
+ export const FLAG_VALUES = {
26
+ "--provider": AD_PROVIDER_VALUES,
27
+ "--compare": ["previous", "year", "off"],
28
+ "--order": ["asc", "desc"],
29
+ "--verified-only": ["on", "off"],
30
+ };
22
31
  export function completionScript(shell) {
23
32
  if (shell === "bash") {
33
+ const values = Object.entries(FLAG_VALUES)
34
+ .map(([flag, list]) => ` ${flag}) COMPREPLY=($(compgen -W "${list.join(" ")}" -- "$cur")); return ;;`)
35
+ .join("\n");
24
36
  const cases = Object.entries(SUB)
25
37
  .map(([cmd, subs]) => ` ${cmd}) COMPREPLY=($(compgen -W "${subs.join(" ")} ${FLAGS.join(" ")}" -- "$cur")) ;;`)
26
38
  .join("\n");
27
39
  return `# metricraven bash completion. Add to ~/.bashrc: eval "$(metricraven completion bash)"
28
40
  _metricraven() {
29
41
  local cur="\${COMP_WORDS[COMP_CWORD]}"
42
+ case "\${COMP_WORDS[COMP_CWORD-1]}" in
43
+ ${values}
44
+ esac
30
45
  if [ "$COMP_CWORD" -eq 1 ]; then
31
46
  COMPREPLY=($(compgen -W "${COMMANDS.join(" ")} ${FLAGS.join(" ")}" -- "$cur")); return
32
47
  fi
@@ -38,12 +53,18 @@ ${cases}
38
53
  complete -F _metricraven metricraven`;
39
54
  }
40
55
  if (shell === "zsh") {
56
+ const values = Object.entries(FLAG_VALUES)
57
+ .map(([flag, list]) => ` ${flag}) compadd -- ${list.join(" ")}; return ;;`)
58
+ .join("\n");
41
59
  const cases = Object.entries(SUB)
42
60
  .map(([cmd, subs]) => ` ${cmd}) compadd -- ${subs.join(" ")} ${FLAGS.join(" ")} ;;`)
43
61
  .join("\n");
44
62
  return `#compdef metricraven
45
63
  # metricraven zsh completion. Add to ~/.zshrc: eval "$(metricraven completion zsh)"
46
64
  _metricraven() {
65
+ case "\${words[CURRENT-1]}" in
66
+ ${values}
67
+ esac
47
68
  if (( CURRENT == 2 )); then
48
69
  compadd -- ${COMMANDS.join(" ")} ${FLAGS.join(" ")}
49
70
  else
@@ -61,7 +82,9 @@ compdef _metricraven metricraven`;
61
82
  "complete -c metricraven -f",
62
83
  `complete -c metricraven -n "__fish_use_subcommand" -a "${COMMANDS.join(" ")}"`,
63
84
  ...Object.entries(SUB).map(([cmd, subs]) => `complete -c metricraven -n "__fish_seen_subcommand_from ${cmd}" -a "${subs.join(" ")}"`),
64
- ...FLAGS.map((f) => `complete -c metricraven -l ${f.slice(2)}`),
85
+ ...FLAGS.map((f) => FLAG_VALUES[f]
86
+ ? `complete -c metricraven -l ${f.slice(2)} -x -a "${FLAG_VALUES[f].join(" ")}"`
87
+ : `complete -c metricraven -l ${f.slice(2)}`),
65
88
  ];
66
89
  return lines.join("\n");
67
90
  }
package/dist/index.js CHANGED
@@ -39,15 +39,20 @@ Reports (default: last 30 days)
39
39
  analytics breakdown <dim> Full table for a dimension: channel, referrer, page,
40
40
  entryPage, utmSource, utmCampaign, country, city,
41
41
  browser, os, device, hostname, outbound, …
42
+ --sort visitors|pageviews|revenue|name, --order desc|asc
42
43
  analytics revenue Payments, renewals, refunds, LTV, revenue by channel
44
+ analytics mrr [unit] MRR over time: new, expansion, contraction, churn
45
+ (unit: day, week or month)
43
46
  analytics conversions Goals and funnel steps
44
47
  analytics goal <name> One goal in detail
45
48
  analytics insights What converts: sources, countries, time to purchase
46
49
  analytics search Google Search Console queries
47
50
  analytics crawlers AI crawlers and bots
48
51
  analytics ads [level] Ad spend, revenue and ROAS for every connected network
49
- (campaign, adgroup or ad; --provider all|meta|google)
52
+ (campaign, adgroup or ad; --provider all|meta|google|tiktok;
53
+ --account <id>: one chosen ad account alone)
50
54
  analytics meta-ads [level] Meta Ads spend, revenue and ROAS by campaign, adset or ad
55
+ (--account <id>: one ad account alone)
51
56
  realtime Visitors online now
52
57
  visitors list Visitors in the period (needs visitor details access);
53
58
  search: --page, --page-contains, --goal, --referrer,
@@ -79,9 +84,11 @@ Alerts (email when a goal, payment or new customer happens)
79
84
  alerts list Alerts on the website
80
85
  alerts get <alert_id> One alert with its counts
81
86
  alerts create --goal <name> New goal alert; or --trigger payment|new_customer
82
- [--name] [--subject] [--message] [--notify me|members]
83
- [--disabled] (needs write access)
87
+ [--name] [--subject] [--message]
88
+ [--recipients <email,email|all>] (default: you)
89
+ [--disabled] (needs write access, admin)
84
90
  alerts update <alert_id> [--name] [--goal] [--enabled | --disabled]
91
+ [--recipients <email,email|all>]
85
92
  alerts delete <alert_id> Delete an alert (asks first; --yes to skip)
86
93
  alerts history [--alert <id>] Emails the alerts sent, newest first
87
94
 
@@ -94,7 +101,8 @@ Team
94
101
  members revoke <invite_id> Revoke a pending invitation
95
102
 
96
103
  Bot traffic
97
- bots settings Excluded crawler companies and agents, bot token status
104
+ bots settings Excluded crawler companies and agents, bot token status;
105
+ --verified-only on|off records only IP-verified crawlers
98
106
  bots usage AI and bot requests used this cycle and the allowance
99
107
  bots exclude <name…> Stop recording these agents (--company for companies)
100
108
  bots include <name…> Record excluded agents again (--company for companies)
@@ -113,7 +121,8 @@ Period and filters
113
121
  --from, --to <date> Custom days, YYYY-MM-DD (inclusive)
114
122
  -z, --timezone <zone> IANA zone for day boundaries, e.g. Europe/Madrid (default UTC)
115
123
  --compare <c> Change figures against: previous (default), year
116
- (same period last year) or a YYYY-MM-DD start
124
+ (same period last year), a YYYY-MM-DD start, or
125
+ off (no comparison: no change column, none in --json)
117
126
  -f, --filter <dim:op:value> Repeatable. Ops: is, is_not, contains, not_contains;
118
127
  gt, lt for visits. e.g. -f country:is:US
119
128
  -f page:contains:/blog -f visits:gt:2
@@ -125,7 +134,8 @@ Period and filters
125
134
  with is or is_not: -f model:is:claude
126
135
 
127
136
  List options
128
- --sort, -n/--limit, --offset, --q (search), --payment all|paid|unpaid
137
+ --sort, --order asc|desc (breakdown), -n/--limit, --offset, --q (search),
138
+ --payment all|paid|unpaid
129
139
 
130
140
  Global
131
141
  --site <id> Website for this command (or METRICRAVEN_SITE, or \`use\`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metricraven/cli",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "MetricRaven from your terminal: traffic, revenue, goals, visitors and websites. Built for people and AI agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",