@metricraven/cli 0.5.0 → 0.6.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
@@ -70,7 +70,8 @@ The token is saved to `~/.config/metricraven/config.json` (or `$XDG_CONFIG_HOME/
70
70
  | `notes list`, `notes add --text [--date]` | Chart notes (adding needs write access) |
71
71
  | `mentions [--platform x\|reddit] [--q text]` | X and Reddit posts mentioning the website (Growth plan) |
72
72
  | `ai-visibility` | What AI assistants answer to your tracked prompts (Growth plan); `--period` for the trend (default 90d) |
73
- | `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) |
73
+ | `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, `--channel <id,id>` also posts to alert channels (changes need write access) |
74
+ | `alerts channels list\|get <id>`, `alerts channels add slack\|discord\|webhook --url <URL> [--spikes] [--weekly] [--monthly]`, `alerts channels add telegram`, `alerts channels update\|test\|rotate-secret\|reconnect\|remove <id>` | Alert channels: Slack, Discord, Telegram (prints the connect links) and signed webhooks (prints the signing secret once). Destinations are shown masked; remove and rotate-secret ask first (`--yes`). Changes need write access, admin |
74
75
  | `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) |
75
76
  | `bots settings\|usage`, `bots settings --verified-only on\|off`, `bots settings --datacenter on\|off`, `bots exclude\|include <name…> [--company]`, `bots require-token on\|off` | Bot traffic settings (`--verified-only on` records only IP-verified crawlers; `--datacenter on`, the default, doesn't count tracker hits from cloud and hosting networks) and the bot request allowance |
76
77
  | `proxy status\|enable <subdomain>\|check\|remove` | The managed proxy subdomain that serves the script |
package/dist/args.js CHANGED
@@ -110,6 +110,12 @@ const OPTIONS = {
110
110
  disabled: { type: "boolean" },
111
111
  yes: { type: "boolean", short: "y" },
112
112
  alert: { type: "string" },
113
+ // alerts channels add|update: the webhook URL and the site-wide notifications it gets
114
+ url: { type: "string" },
115
+ spikes: { type: "boolean" },
116
+ weekly: { type: "boolean" },
117
+ monthly: { type: "boolean" },
118
+ events: { type: "string" },
113
119
  role: { type: "string" },
114
120
  color: { type: "string" },
115
121
  description: { type: "string" },
package/dist/commands.js CHANGED
@@ -722,12 +722,20 @@ const RENDER = {
722
722
  // Hidden goals (Settings → Goals) stay out of the table, like the dashboard; --json has them all.
723
723
  const shown = d.goals.filter((g) => !g.hidden);
724
724
  const hidden = d.goals.length - shown.length;
725
+ const auto = (d.automaticEvents ?? []).filter((g) => !g.hidden);
725
726
  return [
726
727
  periodLine(d.period),
727
728
  section("Goals", shown.length
728
729
  ? table(["Goal", "Visitors", "Completions", "Rate"], shown.map((g) => [truncate(goalText(g)), num(g.visitors), num(g.events), pct(g.rate, 2)]), ["left", "right", "right", "right"])
729
730
  : dim("No goals in this period.")),
730
731
  hidden ? dim(`${num(hidden)} hidden goal${hidden === 1 ? "" : "s"} not shown (see --json or \`metricraven goals list\`).`) : "",
732
+ // Button clicks, form submissions and downloads: event counts here, people with `analytics goal <name>`.
733
+ auto.length
734
+ ? section("Automatic events", [
735
+ table(["Event", "Completions"], auto.map((g) => [truncate(goalText(g)), num(g.events)]), ["left", "right"]),
736
+ dim(`Visitors and revenue: metricraven analytics goal ${auto[0].name}`),
737
+ ].join("\n"))
738
+ : "",
731
739
  d.funnel?.length
732
740
  ? section("Funnel", table(["Step", "Visitors", "From start", "Median after previous"], d.funnel.map((s) => [s.displayName || s.step, num(s.visitors), pct(s.fromStart, 0), duration(s.medianSecondsFromPrevious)]), ["left", "right", "right", "right"]))
733
741
  : "",
@@ -1450,6 +1458,31 @@ function recipientsFlag(flags) {
1450
1458
  throw new UsageError("--recipients needs member emails or user IDs, comma-separated, or all.");
1451
1459
  return list.length === 1 && list[0].toLowerCase() === "all" ? { notify: "members" } : { recipients: list };
1452
1460
  }
1461
+ /**
1462
+ * `--channel <id,id>`: the alert channels it posts to (replaces the list), or `none` to stop
1463
+ * posting to channels. IDs come from `metricraven alerts channels list`.
1464
+ */
1465
+ function channelsFlag(flags) {
1466
+ if (flags.channel === undefined)
1467
+ return {};
1468
+ const list = flags.channel.split(",").map((c) => c.trim()).filter(Boolean);
1469
+ if (list.length === 1 && list[0].toLowerCase() === "none")
1470
+ return { channels: [] };
1471
+ if (!list.length)
1472
+ throw new UsageError("--channel needs channel IDs, comma-separated (from `metricraven alerts channels list`), or none.");
1473
+ return { channels: list };
1474
+ }
1475
+ const channelCount = (a) => a.channelIds?.length ?? 0;
1476
+ /** Who an alert reaches: its recipients' emails and how many channels. */
1477
+ function audience(a) {
1478
+ const emails = a.recipients.map((r) => r.email).join(", ");
1479
+ const channels = channelCount(a) ? `${num(channelCount(a))} ${plural("channels", channelCount(a))}` : "";
1480
+ if (emails && channels)
1481
+ return `emailing ${emails} and posting to ${channels}`;
1482
+ if (channels)
1483
+ return `posting to ${channels}`;
1484
+ return `emailing ${emails || "nobody yet"}`;
1485
+ }
1453
1486
  const triggerText = (t) => (t.type === "goal" ? `goal ${t.goalName}` : t.type === "payment" ? "any payment" : "new customer");
1454
1487
  /** `metricraven alerts …`: conversion alerts on the website (list/get/create/update/delete/history). */
1455
1488
  async function alerts(ctx, sub, rest) {
@@ -1461,6 +1494,8 @@ async function alerts(ctx, sub, rest) {
1461
1494
  throw new UsageError(`Use: metricraven alerts ${sub} <alert_id> (IDs from \`metricraven alerts list\`).`);
1462
1495
  return `/alerts/${encodeURIComponent(id)}`;
1463
1496
  };
1497
+ if (sub === "channels")
1498
+ return alertChannels(ctx, site, rest[0], rest.slice(1));
1464
1499
  switch (sub ?? "list") {
1465
1500
  case "list": {
1466
1501
  const d = await client.get("/alerts", params());
@@ -1472,7 +1507,7 @@ async function alerts(ctx, sub, rest) {
1472
1507
  out(dim(`Tracked goals: ${d.goals.slice(0, 12).join(", ")}`));
1473
1508
  return 0;
1474
1509
  }
1475
- out(table(["Alert", "Trigger", "On", "Recipients", "Today", "Total", "ID"], d.data.map((a) => [a.name, triggerText(a.trigger), a.isEnabled ? "yes" : "no", String(a.recipients.length), num(a.dailyCount), num(a.triggerCount), a.id])));
1510
+ out(table(["Alert", "Trigger", "On", "Recipients", "Channels", "Today", "Total", "ID"], d.data.map((a) => [a.name, triggerText(a.trigger), a.isEnabled ? "yes" : "no", String(a.recipients.length), String(channelCount(a)), num(a.dailyCount), num(a.triggerCount), a.id])));
1476
1511
  return 0;
1477
1512
  }
1478
1513
  case "get": {
@@ -1483,6 +1518,8 @@ async function alerts(ctx, sub, rest) {
1483
1518
  out(bold(a.name));
1484
1519
  out(`Trigger: ${triggerText(a.trigger)} · ${a.isEnabled ? "enabled" : "disabled"}`);
1485
1520
  out(`Recipients: ${a.recipients.map((r) => r.email).join(", ") || "none"}`);
1521
+ if (channelCount(a))
1522
+ out(`Channels: ${a.channelIds.join(", ")}`);
1486
1523
  if (a.optedOut?.length)
1487
1524
  out(`Unsubscribed: ${a.optedOut.map((r) => r.email).join(", ")}`);
1488
1525
  if (a.template.subject)
@@ -1511,13 +1548,14 @@ async function alerts(ctx, sub, rest) {
1511
1548
  trigger: type === "goal" ? { type, goalName: goal } : { type },
1512
1549
  template: flags.subject || flags.message ? { subject: flags.subject, message: flags.message } : undefined,
1513
1550
  ...recipientsFlag(flags),
1551
+ ...channelsFlag(flags),
1514
1552
  isEnabled: flags.disabled ? false : undefined,
1515
1553
  };
1516
1554
  const d = await needs("write", client.post("/alerts", body, params()));
1517
1555
  if (flags.json)
1518
1556
  return printJson(d), 0;
1519
1557
  const a = d.data[0];
1520
- out(`Created "${a.name}" (${triggerText(a.trigger)}), ${a.isEnabled ? "enabled" : "disabled"}, emailing ${a.recipients.map((r) => r.email).join(", ") || "nobody yet"}. ID ${a.id}`);
1558
+ out(`Created "${a.name}" (${triggerText(a.trigger)}), ${a.isEnabled ? "enabled" : "disabled"}, ${audience(a)}. ID ${a.id}`);
1521
1559
  return 0;
1522
1560
  }
1523
1561
  case "update": {
@@ -1528,14 +1566,15 @@ async function alerts(ctx, sub, rest) {
1528
1566
  trigger: flags.goal ? { type: "goal", goalName: flags.goal } : undefined,
1529
1567
  isEnabled: flags.enabled ? true : flags.disabled ? false : undefined,
1530
1568
  ...recipientsFlag(flags),
1569
+ ...channelsFlag(flags),
1531
1570
  };
1532
1571
  if (Object.values(body).every((v) => v === undefined))
1533
- throw new UsageError("Nothing to change. Use --name, --goal, --enabled, --disabled or --recipients.");
1572
+ throw new UsageError("Nothing to change. Use --name, --goal, --enabled, --disabled, --recipients or --channel.");
1534
1573
  const d = await needs("write", client.patch(alertPath(rest[0]), body, params()));
1535
1574
  if (flags.json)
1536
1575
  return printJson(d), 0;
1537
1576
  const a = d.data[0];
1538
- out(`Updated "${a.name}" (${triggerText(a.trigger)}), ${a.isEnabled ? "enabled" : "disabled"}.`);
1577
+ out(`Updated "${a.name}" (${triggerText(a.trigger)}), ${a.isEnabled ? "enabled" : "disabled"}, ${audience(a)}.`);
1539
1578
  return 0;
1540
1579
  }
1541
1580
  case "delete": {
@@ -1570,7 +1609,210 @@ async function alerts(ctx, sub, rest) {
1570
1609
  return 0;
1571
1610
  }
1572
1611
  }
1573
- throw new UsageError(`Unknown command "alerts ${sub}". Use list, get, create, update, delete or history.`);
1612
+ throw new UsageError(`Unknown command "alerts ${sub}". Use list, get, create, update, delete, history or channels.`);
1613
+ }
1614
+ const CHANNEL_TYPES = ["slack", "discord", "telegram", "webhook"];
1615
+ const CHANNEL_LABEL = { slack: "Slack", discord: "Discord", telegram: "Telegram", webhook: "Webhook" };
1616
+ const EVENT_NAMES = { spikes: "spike", weekly: "weeklyReport", monthly: "monthlyReport" };
1617
+ const eventsText = (e) => Object.entries(EVENT_NAMES)
1618
+ .filter(([, key]) => e[key])
1619
+ .map(([name]) => name)
1620
+ .join(", ") || "–";
1621
+ const channelLabel = (t) => CHANNEL_LABEL[t] ?? t;
1622
+ const destination = (c) => (c.status === "pending" ? "waiting for a chat" : c.target);
1623
+ /**
1624
+ * Spike alerts and weekly/monthly reports for a channel: --spikes, --weekly and --monthly switch
1625
+ * them on; --events spikes,weekly|none sets the whole list (on update, the others go off).
1626
+ */
1627
+ function channelEvents(flags) {
1628
+ const picked = { spike: flags.spikes, weeklyReport: flags.weekly, monthlyReport: flags.monthly };
1629
+ const on = Object.entries(picked).filter(([, value]) => value);
1630
+ if (flags.events === undefined)
1631
+ return on.length ? Object.fromEntries(on.map(([key]) => [key, true])) : undefined;
1632
+ if (on.length)
1633
+ throw new UsageError("Use --events, or --spikes/--weekly/--monthly, not both.");
1634
+ const names = flags.events.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
1635
+ const none = names.length === 1 && names[0] === "none";
1636
+ if (!names.length || (!none && names.some((n) => !EVENT_NAMES[n])))
1637
+ throw new UsageError("--events takes spikes, weekly and monthly, comma-separated, or none.");
1638
+ return { spike: names.includes("spikes"), weeklyReport: names.includes("weekly"), monthlyReport: names.includes("monthly") };
1639
+ }
1640
+ /** --timezone on a channel: the zone its weekly and monthly reports use. */
1641
+ function channelTimeZone(flags) {
1642
+ if (flags.timezone === undefined)
1643
+ return {};
1644
+ const zone = validTimeZone(flags.timezone);
1645
+ if (!zone)
1646
+ throw new UsageError(`Unknown timezone "${flags.timezone}". Use an IANA name like America/New_York.`);
1647
+ return { timeZone: zone };
1648
+ }
1649
+ /** Writes need write access; a 503 channel_unavailable means this server can't add that type. */
1650
+ async function channelWrite(request) {
1651
+ try {
1652
+ return await needs("write", request);
1653
+ }
1654
+ catch (error) {
1655
+ if (error instanceof ApiError && error.code === "channel_unavailable")
1656
+ throw new ApiError("This server can't add that kind of channel right now. `metricraven alerts channels list` shows the types it can add.", error.status, error.code);
1657
+ throw error;
1658
+ }
1659
+ }
1660
+ /**
1661
+ * `metricraven alerts channels …`: where alerts go besides email (Slack, Discord, Telegram, signed
1662
+ * webhooks). Destinations are never printed in full: the API only returns a masked target.
1663
+ */
1664
+ async function alertChannels(ctx, site, sub, rest) {
1665
+ const { flags, client } = ctx;
1666
+ const params = () => new URLSearchParams({ site });
1667
+ const channelPath = (id, suffix = "") => {
1668
+ if (!id)
1669
+ throw new UsageError(`Use: metricraven alerts channels ${sub} <channel_id> (IDs from \`metricraven alerts channels list\`).`);
1670
+ return `/alerts/channels/${encodeURIComponent(id)}${suffix}`;
1671
+ };
1672
+ const confirm = async (question) => {
1673
+ if (flags.yes)
1674
+ return true;
1675
+ if (!interactive() || flags.json)
1676
+ throw new UsageError("Add --yes to do this without a prompt.");
1677
+ return /^y(es)?$/i.test(await prompt(`${question} [y/N] `));
1678
+ };
1679
+ const describe = (c) => `${channelLabel(c.type)} channel "${c.name}" (${destination(c)})`;
1680
+ const showLinks = (c, s) => {
1681
+ out("Open a link in Telegram and press Start to connect a chat:");
1682
+ out(` Private chat: ${s.connectUrl}`);
1683
+ if (s.groupConnectUrl)
1684
+ out(` Group: ${s.groupConnectUrl}`);
1685
+ out(dim(`${c.connectExpiresAt ? `The links stop working ${date(c.connectExpiresAt)}. ` : ""}New links: metricraven alerts channels reconnect ${c.id}`));
1686
+ };
1687
+ const showSecret = (c, secret) => {
1688
+ out(`Signing secret for "${c.name}" (${c.id}): ${secret}`);
1689
+ out(dim("Shown once. Check the X-MetricRaven-Signature header with it: https://metricraven.com/docs/webhooks"));
1690
+ };
1691
+ switch (sub ?? "list") {
1692
+ case "list": {
1693
+ const d = await client.get("/alerts/channels", params());
1694
+ if (flags.json)
1695
+ return printJson(d), 0;
1696
+ if (!d.data.length)
1697
+ out(dim("No alert channels yet. Add one with `metricraven alerts channels add slack --url <webhook URL>`."));
1698
+ else
1699
+ out(table(["Channel", "Type", "Destination", "Also gets", "Alerts", "Last sent", "ID"], d.data.map((c) => [
1700
+ c.lastError ? `${c.name} (failing)` : c.name,
1701
+ channelLabel(c.type),
1702
+ destination(c),
1703
+ eventsText(c.events),
1704
+ num(c.alertCount),
1705
+ c.lastDeliveredAt ? date(c.lastDeliveredAt) : "never",
1706
+ c.id,
1707
+ ])));
1708
+ const missing = CHANNEL_TYPES.filter((t) => !d.available.includes(t));
1709
+ const note = !d.available.length ? " This server can't add channels right now." : missing.length ? ` This server can't add ${missing.map(channelLabel).join(" or ")} channels.` : "";
1710
+ out(dim(`${num(d.data.length)} of ${num(d.limit)} channels.${note}`));
1711
+ return 0;
1712
+ }
1713
+ case "get": {
1714
+ const d = await client.get(channelPath(rest[0]), params());
1715
+ if (flags.json)
1716
+ return printJson(d), 0;
1717
+ const c = d.data[0];
1718
+ out(bold(c.name));
1719
+ out(`Type: ${channelLabel(c.type)} · ${c.status === "pending" ? "waiting for a chat" : "active"}`);
1720
+ if (c.status === "active")
1721
+ out(`Destination: ${c.target}${c.chatType ? ` (${c.chatType})` : ""}`);
1722
+ out(`Also gets: ${eventsText(c.events)} · reports in ${c.timeZone}`);
1723
+ out(`Used by ${num(c.alertCount)} ${plural("alerts", c.alertCount)}`);
1724
+ out(dim(c.lastDeliveredAt ? `Last sent ${date(c.lastDeliveredAt)}` : "Nothing sent yet"));
1725
+ if (c.lastError)
1726
+ out(`Last error: ${c.lastError}`);
1727
+ return 0;
1728
+ }
1729
+ case "add":
1730
+ case "create": {
1731
+ const type = (rest[0] ?? flags.type)?.toLowerCase();
1732
+ if (!type || !CHANNEL_TYPES.includes(type))
1733
+ throw new UsageError("Use: metricraven alerts channels add slack|discord|webhook --url <URL>, or add telegram.");
1734
+ let url = flags.url?.trim();
1735
+ if (type === "telegram") {
1736
+ if (url)
1737
+ throw new UsageError("Telegram channels connect with a link, not a URL. Leave out --url.");
1738
+ }
1739
+ else if (!url) {
1740
+ if (!interactive() || flags.json)
1741
+ throw new UsageError(`Use: metricraven alerts channels add ${type} --url <URL>`);
1742
+ url = (await promptHidden(`${channelLabel(type)} webhook URL: `)).trim();
1743
+ if (!url)
1744
+ throw new UsageError("No URL given.");
1745
+ }
1746
+ const body = { type, name: flags.name, url, events: channelEvents(flags), ...channelTimeZone(flags) };
1747
+ const d = await channelWrite(client.post("/alerts/channels", body, params()));
1748
+ if (flags.json)
1749
+ return printJson(d), 0;
1750
+ const c = d.data[0];
1751
+ out(`Added ${describe(c)}. ID ${c.id}`);
1752
+ if (d.signingSecret)
1753
+ showSecret(c, d.signingSecret);
1754
+ if (d.connectUrl)
1755
+ showLinks(c, d);
1756
+ if (c.status === "active")
1757
+ out(dim(`Send a test: metricraven alerts channels test ${c.id} · Post an alert there: metricraven alerts update <alert_id> --channel ${c.id}`));
1758
+ return 0;
1759
+ }
1760
+ case "update": {
1761
+ const path = channelPath(rest[0]);
1762
+ const body = { name: flags.name, url: flags.url?.trim() || undefined, events: channelEvents(flags), ...channelTimeZone(flags) };
1763
+ if (Object.values(body).every((v) => v === undefined))
1764
+ throw new UsageError("Nothing to change. Use --name, --url, --events (or --spikes, --weekly, --monthly) or --timezone.");
1765
+ const d = await channelWrite(client.patch(path, body, params()));
1766
+ if (flags.json)
1767
+ return printJson(d), 0;
1768
+ const c = d.data[0];
1769
+ out(`Updated ${describe(c)}. Also gets: ${eventsText(c.events)}.`);
1770
+ return 0;
1771
+ }
1772
+ case "test": {
1773
+ const d = await needs("write", client.post(channelPath(rest[0], "/test"), {}, params()));
1774
+ if (flags.json)
1775
+ return printJson(d), d.data.sent ? 0 : 1;
1776
+ const name = d.channel ? `"${d.channel.name}"` : rest[0];
1777
+ if (d.data.sent)
1778
+ return out(`Sent a test message to ${name}.`), 0;
1779
+ out(`The test message to ${name} failed: ${d.data.error ?? "unknown error"}`);
1780
+ return 1;
1781
+ }
1782
+ case "rotate-secret": {
1783
+ const path = channelPath(rest[0]);
1784
+ if (!(await confirm(`Rotate the signing secret of channel ${rest[0]}? The current secret stops working at once.`)))
1785
+ return out("Kept."), 0;
1786
+ const d = await needs("write", client.patch(path, { rotateSecret: true }, params()));
1787
+ if (flags.json)
1788
+ return printJson(d), 0;
1789
+ if (!d.signingSecret)
1790
+ throw new UsageError("Only webhook channels have a signing secret.");
1791
+ showSecret(d.data[0], d.signingSecret);
1792
+ return 0;
1793
+ }
1794
+ case "reconnect": {
1795
+ const d = await channelWrite(client.patch(channelPath(rest[0]), { reconnect: true }, params()));
1796
+ if (flags.json)
1797
+ return printJson(d), 0;
1798
+ if (!d.connectUrl)
1799
+ throw new UsageError("Only Telegram channels connect with a link.");
1800
+ showLinks(d.data[0], d);
1801
+ return 0;
1802
+ }
1803
+ case "remove":
1804
+ case "delete": {
1805
+ const path = channelPath(rest[0]);
1806
+ if (!(await confirm(`Remove channel ${rest[0]}? Alerts stop posting there; past deliveries stay in the history.`)))
1807
+ return out("Kept."), 0;
1808
+ const d = await needs("write", client.del(path, params()));
1809
+ if (flags.json)
1810
+ return printJson(d), 0;
1811
+ out(`Removed channel ${d.data.id}.`);
1812
+ return 0;
1813
+ }
1814
+ }
1815
+ throw new UsageError(`Unknown command "alerts channels ${sub}". Use list, get, add, update, test, rotate-secret, reconnect or remove.`);
1574
1816
  }
1575
1817
  /** `metricraven members …`: the website's team (list/invite/role/remove/revoke). Ownership transfer stays in the dashboard. */
1576
1818
  async function members(ctx, sub, rest) {
@@ -17,13 +17,18 @@ const SUB = {
17
17
  goals: ["list", "set", "reset", "colors", "definitions", "preview", "define", "undefine", "delete-events"],
18
18
  notes: ["list", "add"],
19
19
  mentions: ["list"],
20
- alerts: ["list", "get", "create", "update", "delete", "history"],
20
+ alerts: ["list", "get", "create", "update", "delete", "history", "channels"],
21
21
  members: ["list", "invite", "role", "remove", "revoke"],
22
22
  bots: ["settings", "usage", "exclude", "include", "require-token"],
23
23
  proxy: ["status", "enable", "check", "remove"],
24
24
  completion: ["bash", "zsh", "fish"],
25
25
  };
26
- const FLAGS = ["--json", "--fields", "--site", "--token", "--verbose", "--help", "--version", "--period", "--from", "--to", "--timezone", "--filter", "--compare", "--sort", "--limit", "--offset", "--q", "--param", "--attribution", "--group", "--folder", "--include", "--drop-step", "--path", "--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", "--link", "--link-path", "--click", "--form", "--download", "--referrer", "--channel", "--source", "--utm-source", "--utm-medium", "--utm-campaign", "--country", "--device", "--browser", "--os", "--visits-gt", "--visits-lt", "--trait", "--key", "--visit-source", "--visit-channel", "--visit-campaign", "--visit-referrer", "--visit-entry-page", "--visit-page", "--visit-page-contains", "--visit-goal", "--visit", "--grace", "--provider", "--account", "--order", "--verified-only", "--datacenter", "--type", "--cursor", "--all", "--csv", "--step", "--continued", "--funnel", "--steps", "--start", "--end", "--who"];
26
+ /** Commands with their own subcommands, completed after the second word. */
27
+ const NESTED = {
28
+ "alerts channels": ["list", "get", "add", "update", "test", "rotate-secret", "reconnect", "remove"],
29
+ "websites keys": ["list", "create", "rename", "revoke", "roll"],
30
+ };
31
+ const FLAGS = ["--json", "--fields", "--site", "--token", "--verbose", "--help", "--version", "--period", "--from", "--to", "--timezone", "--filter", "--compare", "--sort", "--limit", "--offset", "--q", "--param", "--attribution", "--group", "--folder", "--include", "--drop-step", "--path", "--payment", "--name", "--domain", "--date", "--text", "--goal", "--trigger", "--subject", "--message", "--notify", "--recipients", "--enabled", "--disabled", "--yes", "--alert", "--url", "--spikes", "--weekly", "--monthly", "--events", "--platform", "--role", "--color", "--description", "--hidden", "--visible", "--company", "--scopes", "--sites", "--transaction", "--visitor", "--user", "--dry-run", "--page", "--page-contains", "--link", "--link-path", "--click", "--form", "--download", "--referrer", "--channel", "--source", "--utm-source", "--utm-medium", "--utm-campaign", "--country", "--device", "--browser", "--os", "--visits-gt", "--visits-lt", "--trait", "--key", "--visit-source", "--visit-channel", "--visit-campaign", "--visit-referrer", "--visit-entry-page", "--visit-page", "--visit-page-contains", "--visit-goal", "--visit", "--grace", "--provider", "--account", "--order", "--verified-only", "--datacenter", "--type", "--cursor", "--all", "--csv", "--step", "--continued", "--funnel", "--steps", "--start", "--end", "--who"];
27
32
  /** Flags with a fixed set of values; completion offers them after the flag. */
28
33
  export const FLAG_VALUES = {
29
34
  "--provider": AD_PROVIDER_VALUES,
@@ -35,6 +40,7 @@ export const FLAG_VALUES = {
35
40
  "--include": ["speed", "errors", "speed,errors"],
36
41
  "--verified-only": ["on", "off"],
37
42
  "--datacenter": ["on", "off"],
43
+ "--events": ["spikes", "weekly", "monthly", "spikes,weekly,monthly", "none"],
38
44
  };
39
45
  export function completionScript(shell) {
40
46
  if (shell === "bash") {
@@ -44,12 +50,20 @@ export function completionScript(shell) {
44
50
  const cases = Object.entries(SUB)
45
51
  .map(([cmd, subs]) => ` ${cmd}) COMPREPLY=($(compgen -W "${subs.join(" ")} ${FLAGS.join(" ")}" -- "$cur")) ;;`)
46
52
  .join("\n");
53
+ const nested = Object.entries(NESTED)
54
+ .map(([cmd, subs]) => ` "${cmd}") COMPREPLY=($(compgen -W "${subs.join(" ")} ${FLAGS.join(" ")}" -- "$cur")); return ;;`)
55
+ .join("\n");
47
56
  return `# metricraven bash completion. Add to ~/.bashrc: eval "$(metricraven completion bash)"
48
57
  _metricraven() {
49
58
  local cur="\${COMP_WORDS[COMP_CWORD]}"
50
59
  case "\${COMP_WORDS[COMP_CWORD-1]}" in
51
60
  ${values}
52
61
  esac
62
+ if [ "$COMP_CWORD" -ge 3 ]; then
63
+ case "\${COMP_WORDS[1]} \${COMP_WORDS[2]}" in
64
+ ${nested}
65
+ esac
66
+ fi
53
67
  if [ "$COMP_CWORD" -eq 1 ]; then
54
68
  COMPREPLY=($(compgen -W "${COMMANDS.join(" ")} ${FLAGS.join(" ")}" -- "$cur")); return
55
69
  fi
@@ -67,12 +81,20 @@ complete -F _metricraven metricraven`;
67
81
  const cases = Object.entries(SUB)
68
82
  .map(([cmd, subs]) => ` ${cmd}) compadd -- ${subs.join(" ")} ${FLAGS.join(" ")} ;;`)
69
83
  .join("\n");
84
+ const nested = Object.entries(NESTED)
85
+ .map(([cmd, subs]) => ` "${cmd}") compadd -- ${subs.join(" ")} ${FLAGS.join(" ")}; return ;;`)
86
+ .join("\n");
70
87
  return `#compdef metricraven
71
88
  # metricraven zsh completion. Add to ~/.zshrc: eval "$(metricraven completion zsh)"
72
89
  _metricraven() {
73
90
  case "\${words[CURRENT-1]}" in
74
91
  ${values}
75
92
  esac
93
+ if (( CURRENT >= 4 )); then
94
+ case "\${words[2]} \${words[3]}" in
95
+ ${nested}
96
+ esac
97
+ fi
76
98
  if (( CURRENT == 2 )); then
77
99
  compadd -- ${COMMANDS.join(" ")} ${FLAGS.join(" ")}
78
100
  else
@@ -90,6 +112,10 @@ compdef _metricraven metricraven`;
90
112
  "complete -c metricraven -f",
91
113
  `complete -c metricraven -n "__fish_use_subcommand" -a "${COMMANDS.join(" ")}"`,
92
114
  ...Object.entries(SUB).map(([cmd, subs]) => `complete -c metricraven -n "__fish_seen_subcommand_from ${cmd}" -a "${subs.join(" ")}"`),
115
+ ...Object.entries(NESTED).map(([cmd, subs]) => {
116
+ const [group, sub] = cmd.split(" ");
117
+ return `complete -c metricraven -n "__fish_seen_subcommand_from ${group}; and __fish_seen_subcommand_from ${sub}" -a "${subs.join(" ")}"`;
118
+ }),
93
119
  ...FLAGS.map((f) => FLAG_VALUES[f]
94
120
  ? `complete -c metricraven -l ${f.slice(2)} -x -a "${FLAG_VALUES[f].join(" ")}"`
95
121
  : `complete -c metricraven -l ${f.slice(2)}`),
package/dist/index.js CHANGED
@@ -143,18 +143,45 @@ Reports (default: last 30 days)
143
143
  (Growth): scores, per-assistant results, brands named;
144
144
  --period (default 90d) for the trend
145
145
 
146
- Alerts (email when a goal, payment or new customer happens)
146
+ Alerts (email, Slack, Discord, Telegram or a webhook when a goal, payment or new
147
+ customer happens)
147
148
  alerts list Alerts on the website
148
149
  alerts get <alert_id> One alert with its counts
149
150
  alerts create --goal <name> New goal alert; or --trigger payment|new_customer
150
151
  [--name] [--subject] [--message]
151
152
  [--recipients <email,email|all>] (default: you)
153
+ [--channel <channel_id,channel_id>] (also post there)
152
154
  [--disabled] (needs write access, admin)
153
155
  alerts update <alert_id> [--name] [--goal] [--enabled | --disabled]
154
156
  [--recipients <email,email|all>]
157
+ [--channel <channel_id,…|none>] (replaces the list)
155
158
  alerts delete <alert_id> Delete an alert (asks first; --yes to skip)
156
159
  alerts history [--alert <id>] Emails the alerts sent, newest first
157
160
 
161
+ Alert channels (where alerts post besides email; changes need write access, admin)
162
+ alerts channels list Channels with their masked destination, what else they
163
+ get, how many alerts use them and the last delivery
164
+ alerts channels get <channel_id>
165
+ alerts channels add slack|discord|webhook --url <URL>
166
+ [--name] [--spikes] [--weekly] [--monthly]
167
+ [--timezone <zone>] (report weeks and months); asks for
168
+ the URL when --url is left out. A webhook prints its
169
+ signing secret once
170
+ alerts channels add telegram Prints the t.me links that connect a chat or group
171
+ alerts channels update <channel_id>
172
+ [--name] [--url] [--events spikes,weekly,monthly|none]
173
+ [--timezone <zone>]
174
+ alerts channels test <channel_id>
175
+ Post a test message now (exit code 1 when it fails)
176
+ alerts channels rotate-secret <channel_id>
177
+ New webhook signing secret, printed once; the old one
178
+ stops working at once (asks first; --yes to skip)
179
+ alerts channels reconnect <channel_id>
180
+ New Telegram connect links
181
+ alerts channels remove <channel_id>
182
+ Remove a channel and take it off every alert (asks
183
+ first; --yes to skip)
184
+
158
185
  Team
159
186
  members list Members, roles and (admins) pending invitations
160
187
  members invite <email> --role admin|viewer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metricraven/cli",
3
- "version": "0.5.0",
3
+ "version": "0.6.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",