@metricraven/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # MetricRaven CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Your [MetricRaven](https://metricraven.com) analytics from the terminal: traffic, revenue, goals, visitors and websites. Output is readable by default and raw JSON with `--json`, so it also works well for scripts and AI agents.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npx @metricraven/cli login # run without installing
9
+ npm install -g @metricraven/cli # or install the `metricraven` command
10
+ ```
11
+
12
+ Node.js 20 or later.
13
+
14
+ ## Log in
15
+
16
+ Create an access token in **Settings → API & MCP** (https://metricraven.com/app/api), then:
17
+
18
+ ```bash
19
+ metricraven login # paste the token (hidden)
20
+ echo "$TOKEN" | metricraven login # or pipe it, e.g. in CI
21
+ ```
22
+
23
+ The token is saved to `~/.config/metricraven/config.json` (or `$XDG_CONFIG_HOME/metricraven/config.json`), readable only by you. `metricraven logout` removes it.
24
+
25
+ ## Commands
26
+
27
+ | Command | What it does |
28
+ |---|---|
29
+ | `login`, `logout`, `whoami` | Save, remove or inspect the access token |
30
+ | `websites list` | Websites this token can use |
31
+ | `websites create --name --domain` | Add a website; prints its ID, secret key and tracking script |
32
+ | `websites get [id]`, `websites update [id] [--name] [--domain a.com,b.com]` | One website's settings; rename it or replace its domains (write access, admin) |
33
+ | `websites delete <id>` | Delete a website and all of its data (owner only; you type its domain, or pass `--domain <domain>` in scripts) |
34
+ | `account update --name <name>` | Change your display name (write access) |
35
+ | `tokens list`, `tokens create --name [--scopes read,visitors,write] [--sites id,id\|all]`, `tokens delete <id>` | Manage access tokens; a new token never gets more access than the one you use |
36
+ | `websites keys list\|create --name\|rename <id> --name\|revoke <id>\|roll <id> [--grace none\|24h\|7d]` | Site secret keys: the default key and named keys with last use; revoke and roll ask first (`--yes` to skip). Needs write access, admin |
37
+ | `use <website_id>` | Set the default website |
38
+ | `analytics traffic` | Visitors, pageviews, revenue, conversion rate and top sources |
39
+ | `analytics breakdown <dimension>` | Full table for `channel`, `referrer`, `page`, `utmSource`, `country`, `device`, … |
40
+ | `analytics revenue` | Payments, renewals, refunds, LTV, revenue by channel |
41
+ | `analytics conversions` | Goals and funnel steps |
42
+ | `analytics goal <name>` | One goal with its sources and properties |
43
+ | `analytics insights` | What converts and how long buyers take |
44
+ | `analytics search` | Google Search Console queries |
45
+ | `analytics crawlers` | AI crawlers and bots |
46
+ | `analytics meta-ads [campaign\|adset\|ad]` | Meta Ads spend, attributed revenue, ROAS and cost per customer |
47
+ | `realtime` | Visitors online now |
48
+ | `visitors list`, `visitors get <id>` | Visitors and journeys (token needs visitor details access) |
49
+ | `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`) |
50
+ | `payments delete`, `goals delete-events` | Delete payments (`--transaction`, `--visitor`, `--user`, `--from/--to`) or goal events (`--goal`, `--visitor`, `--user`, `--from/--to`); shows the count and asks first (`--yes`, `--dry-run`) |
51
+ | `funnels list` | Saved funnels |
52
+ | `goals list`, `goals colors` | Goal display settings (display name, colour, description, hidden) and the palette |
53
+ | `goals set <goal> [--name] [--color] [--description] [--hidden\|--visible]`, `goals reset <goal>` | Change how a goal is shown (needs write access, admin) |
54
+ | `notes list`, `notes add --text [--date]` | Chart notes (adding needs write access) |
55
+ | `mentions [--platform x\|reddit] [--q text]` | X and Reddit posts mentioning the website (Growth plan) |
56
+ | `completion bash\|zsh\|fish` | Shell completion script |
57
+
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`).
59
+
60
+ ```bash
61
+ metricraven analytics traffic --period 7d
62
+ metricraven analytics breakdown referrer --sort revenue --limit 20
63
+ metricraven analytics traffic -f country:is:US -f device:is:mobile --json | jq .overview
64
+ ```
65
+
66
+ ## Environment
67
+
68
+ | Variable | Meaning |
69
+ |---|---|
70
+ | `METRICRAVEN_TOKEN` | Access token (overrides the saved one) |
71
+ | `METRICRAVEN_SITE` | Default website ID |
72
+ | `METRICRAVEN_API_BASE` | API origin, default `https://metricraven.com` |
73
+
74
+ `--fields` on `analytics`, `realtime` and `visitors list` returns only part of the answer, as JSON (comma-separated dot paths; `period` is always kept):
75
+
76
+ ```sh
77
+ metricraven analytics traffic -p 7d --fields overview.current,series.date,series.visitors
78
+ metricraven analytics breakdown country --fields rows.name,rows.revenue
79
+ ```
80
+
81
+ Global flags: `--site <id>`, `--json`, `--verbose` (request URLs and status codes on stderr), `--help`, `--version`.
82
+
83
+ Full documentation: https://metricraven.com/docs/cli
package/dist/api.js ADDED
@@ -0,0 +1,77 @@
1
+ /** Thin client for MetricRaven's REST API with friendly errors. */
2
+ export class ApiError extends Error {
3
+ status;
4
+ code;
5
+ constructor(message, status, code) {
6
+ super(message);
7
+ this.status = status;
8
+ this.code = code;
9
+ }
10
+ }
11
+ export function createClient(opts) {
12
+ const fetchImpl = opts.fetchImpl ?? fetch;
13
+ async function request(method, path, params, body) {
14
+ const url = `${opts.apiBase}/api/v1${path}${params && [...params].length ? `?${params}` : ""}`;
15
+ let res;
16
+ try {
17
+ res = await fetchImpl(url, {
18
+ method,
19
+ headers: {
20
+ Authorization: `Bearer ${opts.token}`,
21
+ Accept: "application/json",
22
+ "User-Agent": "metricraven-cli",
23
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
24
+ },
25
+ body: body === undefined ? undefined : JSON.stringify(body),
26
+ signal: AbortSignal.timeout(60_000),
27
+ });
28
+ }
29
+ catch (error) {
30
+ if (opts.verbose)
31
+ process.stderr.write(`${method} ${url} → network error\n`);
32
+ const reason = error.name === "TimeoutError" ? "timed out" : "could not connect";
33
+ throw new ApiError(`Request ${reason} (${opts.apiBase}). Check your connection or METRICRAVEN_API_BASE.`, 0);
34
+ }
35
+ if (opts.verbose)
36
+ process.stderr.write(`${method} ${url} → ${res.status}\n`);
37
+ const text = await res.text();
38
+ let data = null;
39
+ try {
40
+ data = text ? JSON.parse(text) : null;
41
+ }
42
+ catch {
43
+ data = null;
44
+ }
45
+ if (!res.ok)
46
+ throw toError(res.status, data);
47
+ return data;
48
+ }
49
+ return {
50
+ get: (path, params) => request("GET", path, params),
51
+ post: (path, body, params) => request("POST", path, params, body),
52
+ patch: (path, body, params) => request("PATCH", path, params, body),
53
+ put: (path, body, params) => request("PUT", path, params, body),
54
+ del: (path, params) => request("DELETE", path, params),
55
+ };
56
+ }
57
+ export function toError(status, data) {
58
+ const body = (data && typeof data === "object" ? data : {});
59
+ const code = typeof body.error === "string" ? body.error : undefined;
60
+ const message = typeof body.message === "string" ? body.message : undefined;
61
+ switch (status) {
62
+ case 401:
63
+ return new ApiError("Not authorized. Your token may be invalid or deleted, or it lacks the access this command needs (visitor details or write), or it is limited to other websites. Run `metricraven login` with a token from https://metricraven.com/app/api.", 401, code);
64
+ case 403:
65
+ return new ApiError(message ?? "This token is not allowed to do that.", 403, code);
66
+ case 402:
67
+ return new ApiError(message ?? "Your plan doesn't allow this. Upgrade at https://metricraven.com/app/billing.", 402, code);
68
+ case 404:
69
+ return new ApiError(message ?? (code === "not_found" ? "Not found." : `Not found${code ? ` (${code})` : ""}.`), 404, code);
70
+ case 429:
71
+ return new ApiError("Rate limited. Wait a minute and try again.", 429, code);
72
+ default:
73
+ if (status >= 500)
74
+ return new ApiError(`MetricRaven had a problem (HTTP ${status}). Try again shortly.`, status, code);
75
+ return new ApiError(message ?? (code ? `Request failed: ${code.replace(/_/g, " ")}.` : `Request failed (HTTP ${status}).`), status, code);
76
+ }
77
+ }
package/dist/args.js ADDED
@@ -0,0 +1,160 @@
1
+ import { parseArgs } from "node:util";
2
+ import { PERIODS, compareStartFor, customRange, presetRange, validTimeZone } from "./range.js";
3
+ export const FILTER_OPERATORS = ["is", "is_not", "contains", "not_contains", "gt", "lt"];
4
+ /** Every flag the CLI understands; commands ignore the ones that don't apply. */
5
+ const OPTIONS = {
6
+ json: { type: "boolean" },
7
+ fields: { type: "string" },
8
+ site: { type: "string" },
9
+ token: { type: "string" },
10
+ verbose: { type: "boolean", short: "v" },
11
+ help: { type: "boolean", short: "h" },
12
+ version: { type: "boolean" },
13
+ period: { type: "string", short: "p" },
14
+ from: { type: "string" },
15
+ to: { type: "string" },
16
+ timezone: { type: "string", short: "z" },
17
+ filter: { type: "string", short: "f", multiple: true },
18
+ compare: { type: "string" },
19
+ sort: { type: "string" },
20
+ limit: { type: "string", short: "n" },
21
+ offset: { type: "string" },
22
+ q: { type: "string" },
23
+ payment: { type: "string" },
24
+ name: { type: "string" },
25
+ domain: { type: "string" },
26
+ date: { type: "string" },
27
+ text: { type: "string" },
28
+ platform: { type: "string" },
29
+ goal: { type: "string" },
30
+ trigger: { type: "string" },
31
+ subject: { type: "string" },
32
+ message: { type: "string" },
33
+ notify: { type: "string" },
34
+ enabled: { type: "boolean" },
35
+ disabled: { type: "boolean" },
36
+ yes: { type: "boolean", short: "y" },
37
+ alert: { type: "string" },
38
+ role: { type: "string" },
39
+ color: { type: "string" },
40
+ description: { type: "string" },
41
+ hidden: { type: "boolean" },
42
+ visible: { type: "boolean" },
43
+ company: { type: "boolean" },
44
+ // analytics ads
45
+ provider: { type: "string" },
46
+ // tokens create
47
+ scopes: { type: "string" },
48
+ sites: { type: "string" },
49
+ // payments delete, goals delete-events
50
+ transaction: { type: "string" },
51
+ visitor: { type: "string" },
52
+ user: { type: "string" },
53
+ "dry-run": { type: "boolean" },
54
+ // visitors list search filters
55
+ page: { type: "string" },
56
+ "page-contains": { type: "string" },
57
+ referrer: { type: "string" },
58
+ channel: { type: "string" },
59
+ source: { type: "string" },
60
+ "utm-source": { type: "string" },
61
+ "utm-medium": { type: "string" },
62
+ "utm-campaign": { type: "string" },
63
+ country: { type: "string" },
64
+ device: { type: "string" },
65
+ browser: { type: "string" },
66
+ os: { type: "string" },
67
+ "visits-gt": { type: "string" },
68
+ "visits-lt": { type: "string" },
69
+ grace: { type: "string" },
70
+ };
71
+ export class UsageError extends Error {
72
+ }
73
+ export function parseCli(argv) {
74
+ try {
75
+ const { values, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
76
+ return { command: positionals, flags: values };
77
+ }
78
+ catch (error) {
79
+ throw new UsageError(error.message.replace(/^TypeError \[[A-Z_]+\]: /, ""));
80
+ }
81
+ }
82
+ /**
83
+ * `--filter country:is:US` (repeatable). Values may contain colons (`page:contains:/a:b`); the
84
+ * same dimension and operator merge into one filter with several values (OR), like the dashboard.
85
+ */
86
+ export function buildFilters(raw) {
87
+ const filters = [];
88
+ for (const item of raw ?? []) {
89
+ const first = item.indexOf(":");
90
+ const second = first < 0 ? -1 : item.indexOf(":", first + 1);
91
+ if (first <= 0 || second < 0)
92
+ throw new UsageError(`Filter "${item}" must look like dimension:operator:value, e.g. country:is:US.`);
93
+ const dim = item.slice(0, first);
94
+ const op = item.slice(first + 1, second);
95
+ const value = item.slice(second + 1);
96
+ if (!FILTER_OPERATORS.includes(op))
97
+ throw new UsageError(`Unknown filter operator "${op}". Use ${FILTER_OPERATORS.join(", ")}.`);
98
+ if (!value)
99
+ throw new UsageError(`Filter "${item}" has no value.`);
100
+ const existing = filters.find((f) => f.dim === dim && f.op === op);
101
+ if (existing) {
102
+ if (!existing.values.includes(value))
103
+ existing.values.push(value);
104
+ }
105
+ else
106
+ filters.push({ dim, op, values: [value] });
107
+ }
108
+ if (filters.length > 6)
109
+ throw new UsageError("At most six filters.");
110
+ return filters;
111
+ }
112
+ /** from/to (or range=all), timezone and filters for a dated report. */
113
+ export function rangeParams(flags, now = new Date()) {
114
+ const params = new URLSearchParams();
115
+ const zone = validTimeZone(flags.timezone);
116
+ if (!zone)
117
+ throw new UsageError(`Unknown timezone "${flags.timezone}". Use an IANA name like America/New_York.`);
118
+ params.set("timezone", zone);
119
+ if (flags.from || flags.to) {
120
+ if (!flags.from || !flags.to)
121
+ throw new UsageError("Use --from and --to together (YYYY-MM-DD), or --period.");
122
+ const range = customRange(flags.from, flags.to, zone);
123
+ if (!range)
124
+ throw new UsageError("--from and --to must be real dates like 2026-10-01, with --from on or before --to.");
125
+ params.set("from", range.from.toISOString());
126
+ params.set("to", range.to.toISOString());
127
+ }
128
+ else {
129
+ const period = (flags.period ?? "30d");
130
+ if (!PERIODS.includes(period))
131
+ throw new UsageError(`Unknown period "${flags.period}". Use ${PERIODS.join(", ")}.`);
132
+ if (period === "all")
133
+ params.set("range", "all");
134
+ else {
135
+ const range = presetRange(period, zone, now);
136
+ params.set("from", range.from.toISOString());
137
+ params.set("to", range.to.toISOString());
138
+ }
139
+ }
140
+ const filters = buildFilters(flags.filter);
141
+ if (filters.length)
142
+ params.set("filters", JSON.stringify(filters));
143
+ if (flags.compare) {
144
+ const from = params.get("from");
145
+ const start = from ? compareStartFor(flags.compare, new Date(from), zone) : null;
146
+ if (start === undefined)
147
+ throw new UsageError(`--compare must be previous, year, off or a YYYY-MM-DD day before the period starts (got "${flags.compare}").`);
148
+ if (start)
149
+ params.set("compareStart", start.toISOString());
150
+ }
151
+ return params;
152
+ }
153
+ export function positiveInt(value, name, max) {
154
+ if (value === undefined)
155
+ return undefined;
156
+ const n = Number(value);
157
+ if (!Number.isInteger(n) || n < 0 || n > max)
158
+ throw new UsageError(`--${name} must be a whole number from 0 to ${max}.`);
159
+ return n;
160
+ }