@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.
@@ -0,0 +1,69 @@
1
+ import { UsageError } from "./args.js";
2
+ /** Shell completion scripts for `metricraven completion bash|zsh|fish`. */
3
+ 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
+ const SUB = {
5
+ websites: ["list", "create", "get", "update", "delete", "keys"],
6
+ account: ["get", "update"],
7
+ tokens: ["list", "create", "delete"],
8
+ payments: ["delete"],
9
+ analytics: ["traffic", "breakdown", "revenue", "conversions", "goal", "insights", "search", "crawlers", "ads", "meta-ads"],
10
+ visitors: ["list", "get"],
11
+ funnels: ["list"],
12
+ goals: ["list", "set", "reset", "colors", "delete-events"],
13
+ notes: ["list", "add"],
14
+ mentions: ["list"],
15
+ alerts: ["list", "get", "create", "update", "delete", "history"],
16
+ members: ["list", "invite", "role", "remove", "revoke"],
17
+ bots: ["settings", "usage", "exclude", "include", "require-token"],
18
+ proxy: ["status", "enable", "check", "remove"],
19
+ completion: ["bash", "zsh", "fish"],
20
+ };
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"];
22
+ export function completionScript(shell) {
23
+ if (shell === "bash") {
24
+ const cases = Object.entries(SUB)
25
+ .map(([cmd, subs]) => ` ${cmd}) COMPREPLY=($(compgen -W "${subs.join(" ")} ${FLAGS.join(" ")}" -- "$cur")) ;;`)
26
+ .join("\n");
27
+ return `# metricraven bash completion. Add to ~/.bashrc: eval "$(metricraven completion bash)"
28
+ _metricraven() {
29
+ local cur="\${COMP_WORDS[COMP_CWORD]}"
30
+ if [ "$COMP_CWORD" -eq 1 ]; then
31
+ COMPREPLY=($(compgen -W "${COMMANDS.join(" ")} ${FLAGS.join(" ")}" -- "$cur")); return
32
+ fi
33
+ case "\${COMP_WORDS[1]}" in
34
+ ${cases}
35
+ *) COMPREPLY=($(compgen -W "${FLAGS.join(" ")}" -- "$cur")) ;;
36
+ esac
37
+ }
38
+ complete -F _metricraven metricraven`;
39
+ }
40
+ if (shell === "zsh") {
41
+ const cases = Object.entries(SUB)
42
+ .map(([cmd, subs]) => ` ${cmd}) compadd -- ${subs.join(" ")} ${FLAGS.join(" ")} ;;`)
43
+ .join("\n");
44
+ return `#compdef metricraven
45
+ # metricraven zsh completion. Add to ~/.zshrc: eval "$(metricraven completion zsh)"
46
+ _metricraven() {
47
+ if (( CURRENT == 2 )); then
48
+ compadd -- ${COMMANDS.join(" ")} ${FLAGS.join(" ")}
49
+ else
50
+ case "\${words[2]}" in
51
+ ${cases}
52
+ *) compadd -- ${FLAGS.join(" ")} ;;
53
+ esac
54
+ fi
55
+ }
56
+ compdef _metricraven metricraven`;
57
+ }
58
+ if (shell === "fish") {
59
+ const lines = [
60
+ "# metricraven fish completion. Save to ~/.config/fish/completions/metricraven.fish",
61
+ "complete -c metricraven -f",
62
+ `complete -c metricraven -n "__fish_use_subcommand" -a "${COMMANDS.join(" ")}"`,
63
+ ...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)}`),
65
+ ];
66
+ return lines.join("\n");
67
+ }
68
+ throw new UsageError("Use: metricraven completion bash|zsh|fish");
69
+ }
package/dist/config.js ADDED
@@ -0,0 +1,48 @@
1
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ export const DEFAULT_API_BASE = "https://metricraven.com";
5
+ export function configPath(env = process.env) {
6
+ const base = env.XDG_CONFIG_HOME?.trim() || join(homedir(), ".config");
7
+ return join(base, "metricraven", "config.json");
8
+ }
9
+ export async function readConfig(path = configPath()) {
10
+ try {
11
+ const data = JSON.parse(await readFile(path, "utf8"));
12
+ return data && typeof data === "object" ? data : {};
13
+ }
14
+ catch {
15
+ return {};
16
+ }
17
+ }
18
+ /** Writes the config readable only by the current user (dir 0700, file 0600). */
19
+ export async function writeConfig(config, path = configPath()) {
20
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
21
+ await chmod(dirname(path), 0o700);
22
+ await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
23
+ await chmod(path, 0o600);
24
+ }
25
+ export async function updateConfig(patch, path = configPath()) {
26
+ const next = { ...(await readConfig(path)), ...patch };
27
+ for (const key of Object.keys(next))
28
+ if (next[key] === undefined)
29
+ delete next[key];
30
+ await writeConfig(next, path);
31
+ return next;
32
+ }
33
+ export async function deleteConfigToken(path = configPath()) {
34
+ const config = await readConfig(path);
35
+ delete config.token;
36
+ if (Object.keys(config).length)
37
+ await writeConfig(config, path);
38
+ else
39
+ await rm(path, { force: true });
40
+ }
41
+ /** Flags beat environment variables, which beat the saved config. */
42
+ export function resolveSettings(flags, env, config) {
43
+ return {
44
+ token: flags.token || env.METRICRAVEN_TOKEN || config.token || undefined,
45
+ site: flags.site || env.METRICRAVEN_SITE || config.site || undefined,
46
+ apiBase: (env.METRICRAVEN_API_BASE || config.apiBase || DEFAULT_API_BASE).replace(/\/+$/, ""),
47
+ };
48
+ }
package/dist/format.js ADDED
@@ -0,0 +1,67 @@
1
+ /** Plain-text output helpers: aligned tables, numbers, money and changes. */
2
+ const color = process.stdout.isTTY && !process.env.NO_COLOR;
3
+ export const bold = (s) => (color ? `\x1b[1m${s}\x1b[22m` : s);
4
+ export const dim = (s) => (color ? `\x1b[2m${s}\x1b[22m` : s);
5
+ const green = (s) => (color ? `\x1b[32m${s}\x1b[39m` : s);
6
+ const red = (s) => (color ? `\x1b[31m${s}\x1b[39m` : s);
7
+ const visibleLength = (s) => s.replace(/\x1b\[[0-9;]*m/g, "").length;
8
+ export function num(n, digits = 0) {
9
+ if (n === null || n === undefined || !Number.isFinite(n))
10
+ return "–";
11
+ return n.toLocaleString("en-US", { maximumFractionDigits: digits, minimumFractionDigits: 0 });
12
+ }
13
+ export function money(n, currency = "USD") {
14
+ if (n === null || n === undefined || !Number.isFinite(n))
15
+ return "–";
16
+ try {
17
+ return n.toLocaleString("en-US", { style: "currency", currency, maximumFractionDigits: Math.abs(n) >= 100 ? 0 : 2, minimumFractionDigits: 0 });
18
+ }
19
+ catch {
20
+ return `${num(n, 2)} ${currency}`;
21
+ }
22
+ }
23
+ export function pct(n, digits = 1) {
24
+ return n === null || n === undefined || !Number.isFinite(n) ? "–" : `${num(n, digits)}%`;
25
+ }
26
+ export function duration(seconds) {
27
+ if (seconds === null || seconds === undefined || !Number.isFinite(seconds))
28
+ return "–";
29
+ const s = Math.round(seconds);
30
+ if (s < 60)
31
+ return `${s}s`;
32
+ const m = Math.floor(s / 60);
33
+ if (m < 60)
34
+ return `${m}m ${String(s % 60).padStart(2, "0")}s`;
35
+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
36
+ }
37
+ /** Relative change in percent; for rates use `points`. Lower-is-better metrics flip the colour. */
38
+ export function change(value, opts = {}) {
39
+ if (value === null || value === undefined || !Number.isFinite(value))
40
+ return dim("–");
41
+ const text = `${value > 0 ? "+" : ""}${num(value, 1)}%`;
42
+ if (value === 0)
43
+ return dim(text);
44
+ return (value > 0) !== Boolean(opts.lowerIsBetter) ? green(text) : red(text);
45
+ }
46
+ export function date(iso) {
47
+ if (!iso)
48
+ return "–";
49
+ const d = new Date(iso);
50
+ return Number.isFinite(d.getTime()) ? d.toISOString().replace("T", " ").slice(0, 16) : iso;
51
+ }
52
+ /** An aligned table; numeric columns are right-aligned. */
53
+ export function table(head, rows, align = []) {
54
+ const widths = head.map((h, i) => Math.max(visibleLength(h), ...rows.map((r) => visibleLength(r[i] ?? ""))));
55
+ const cell = (s, i) => {
56
+ const pad = " ".repeat(Math.max(0, widths[i] - visibleLength(s)));
57
+ return align[i] === "right" ? pad + s : s + pad;
58
+ };
59
+ const line = (r) => r.map(cell).join(" ").trimEnd();
60
+ return [bold(line(head)), ...rows.map(line)].join("\n");
61
+ }
62
+ export function truncate(s, max = 48) {
63
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
64
+ }
65
+ export function section(title, body) {
66
+ return `\n${bold(title)}\n${body}`;
67
+ }
package/dist/index.js ADDED
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { UsageError, parseCli } from "./args.js";
4
+ import { errorMessage, run } from "./commands.js";
5
+ const HELP = `MetricRaven CLI: your analytics from the terminal.
6
+
7
+ Usage: metricraven <command> [options]
8
+
9
+ Account
10
+ login Save an access token (from https://metricraven.com/app/api)
11
+ logout Remove the saved token
12
+ whoami Show the token's account, access and websites
13
+ account update --name <name> Change your display name ("" clears it; needs write)
14
+ tokens list Access tokens on the account (* = this one)
15
+ tokens create --name <label> [--scopes read,visitors,write] [--sites <id,id>|all];
16
+ never more access than the token you use; shown once
17
+ tokens delete <token_id> Delete a token (asks first; --yes to skip)
18
+
19
+ Websites
20
+ websites list Websites this token can use (* = default)
21
+ websites create --name --domain
22
+ Add a website; prints its ID, secret key and script
23
+ websites get [<website_id>] Name, domains, app IDs and your role
24
+ websites update [<website_id>] [--name <name>] [--domain a.com,b.com]
25
+ Rename or replace domains (needs write, admin)
26
+ websites delete <website_id> Delete a website and all its data (owner; you type its
27
+ domain, or pass --domain <domain> without a terminal)
28
+ websites keys list Secret keys (default and named): last used, IDs
29
+ websites keys create --name Add a named secret key (shown once)
30
+ websites keys rename <id> --name
31
+ websites keys revoke <id> Revoke a named key (asks first; --yes to skip)
32
+ websites keys roll <id> New value for a key ("default" for the default key);
33
+ --grace none|24h|7d keeps the old one working
34
+ (keys need write access, admin)
35
+ use <website_id> Set the default website
36
+
37
+ Reports (default: last 30 days)
38
+ analytics traffic Visitors, pageviews, revenue, conversion, top sources
39
+ analytics breakdown <dim> Full table for a dimension: channel, referrer, page,
40
+ entryPage, utmSource, utmCampaign, country, city,
41
+ browser, os, device, hostname, outbound, …
42
+ analytics revenue Payments, renewals, refunds, LTV, revenue by channel
43
+ analytics conversions Goals and funnel steps
44
+ analytics goal <name> One goal in detail
45
+ analytics insights What converts: sources, countries, time to purchase
46
+ analytics search Google Search Console queries
47
+ analytics crawlers AI crawlers and bots
48
+ analytics ads [level] Ad spend, revenue and ROAS for every connected network
49
+ (campaign, adgroup or ad; --provider all|meta|google)
50
+ analytics meta-ads [level] Meta Ads spend, revenue and ROAS by campaign, adset or ad
51
+ realtime Visitors online now
52
+ visitors list Visitors in the period (needs visitor details access);
53
+ search: --page, --page-contains, --goal, --referrer,
54
+ --channel, --source, --utm-source, --utm-medium,
55
+ --utm-campaign, --country, --device, --browser, --os,
56
+ --visits-gt <n>, --visits-lt <n> (visits in the period)
57
+ visitors get <visitor_id> One visitor's journey (needs visitor details access)
58
+ funnels list Saved funnels
59
+ goals list Goal display settings (name, colour, hidden)
60
+ goals set <goal> [--name <label>] [--color <hex|name>] [--description]
61
+ [--hidden | --visible] (needs write access, admin);
62
+ pass "" to clear a text field or colour
63
+ goals reset <goal> Back to the raw name, default colour, visible
64
+ goals colors Colours you can use
65
+ goals delete-events Delete goal events: --goal <name>, --visitor <id>,
66
+ --user <id>, --from/--to <day> (counts, then asks;
67
+ --yes to skip, --dry-run to only count; needs write)
68
+ payments delete Delete payments: --transaction <id>, --visitor <id>,
69
+ --user <id>, --from/--to <day> (same confirmation)
70
+ notes list Chart notes in the period
71
+ notes add --text [--date] Add a chart note (needs write access)
72
+ mentions X and Reddit posts mentioning the website (Growth);
73
+ --platform x|reddit, --q, -n/--limit, --offset
74
+ ai-visibility What AI assistants answer to your tracked prompts
75
+ (Growth): scores, per-assistant results, brands named;
76
+ --period (default 90d) for the trend
77
+
78
+ Alerts (email when a goal, payment or new customer happens)
79
+ alerts list Alerts on the website
80
+ alerts get <alert_id> One alert with its counts
81
+ alerts create --goal <name> New goal alert; or --trigger payment|new_customer
82
+ [--name] [--subject] [--message] [--notify me|members]
83
+ [--disabled] (needs write access)
84
+ alerts update <alert_id> [--name] [--goal] [--enabled | --disabled]
85
+ alerts delete <alert_id> Delete an alert (asks first; --yes to skip)
86
+ alerts history [--alert <id>] Emails the alerts sent, newest first
87
+
88
+ Team
89
+ members list Members, roles and (admins) pending invitations
90
+ members invite <email> --role admin|viewer
91
+ Email an invitation (needs write access, admin)
92
+ members role <user_id> --role admin|viewer
93
+ members remove <user_id> Remove a member (asks first; --yes to skip)
94
+ members revoke <invite_id> Revoke a pending invitation
95
+
96
+ Bot traffic
97
+ bots settings Excluded crawler companies and agents, bot token status
98
+ bots usage AI and bot requests used this cycle and the allowance
99
+ bots exclude <name…> Stop recording these agents (--company for companies)
100
+ bots include <name…> Record excluded agents again (--company for companies)
101
+ bots require-token on|off Refuse crawl events sent without the bot token
102
+ (changes need write access, admin)
103
+
104
+ Managed proxy (serve the script from your own subdomain)
105
+ proxy status Hostname, DNS record to add and status
106
+ proxy enable <subdomain> Set it up, e.g. a.example.com (needs write access, admin)
107
+ proxy check Look for the DNS record now
108
+ proxy remove Remove it (asks first; --yes to skip)
109
+ completion bash|zsh|fish Print a shell completion script
110
+
111
+ Period and filters
112
+ -p, --period <p> today, yesterday, 24h, 7d, 30d, 90d, 6m, 1y, wtd, mtd, all
113
+ --from, --to <date> Custom days, YYYY-MM-DD (inclusive)
114
+ -z, --timezone <zone> IANA zone for day boundaries, e.g. Europe/Madrid (default UTC)
115
+ --compare <c> Change figures against: previous (default), year
116
+ (same period last year) or a YYYY-MM-DD start
117
+ -f, --filter <dim:op:value> Repeatable. Ops: is, is_not, contains, not_contains;
118
+ gt, lt for visits. e.g. -f country:is:US
119
+ -f page:contains:/blog -f visits:gt:2
120
+ Revenue also takes plan, currency, paymentType
121
+ (new|renewal), refund (none|partial|refunded) and
122
+ provider: -f plan:is:Pro -f paymentType:is:renewal
123
+ ai-visibility takes model, prompt, group, competitor,
124
+ mention (mentioned|not_mentioned|cited) and citedDomain
125
+ with is or is_not: -f model:is:claude
126
+
127
+ List options
128
+ --sort, -n/--limit, --offset, --q (search), --payment all|paid|unpaid
129
+
130
+ Global
131
+ --site <id> Website for this command (or METRICRAVEN_SITE, or \`use\`)
132
+ --json Raw API JSON (compact), for scripts and AI agents
133
+ --fields <paths> Only these parts of the answer, as JSON (analytics,
134
+ realtime, visitors list): comma-separated dot paths,
135
+ e.g. --fields overview.current,series.date,series.visitors
136
+ -v, --verbose Print request URLs and status codes to stderr
137
+ --token <token> Use this token (prefer METRICRAVEN_TOKEN: flags end up in shell history)
138
+ -h, --help Show help
139
+ --version Show the version
140
+
141
+ Environment
142
+ METRICRAVEN_TOKEN Access token (overrides the saved one)
143
+ METRICRAVEN_SITE Default website ID
144
+ METRICRAVEN_API_BASE API origin (default https://metricraven.com)
145
+
146
+ Docs: https://metricraven.com/docs/cli`;
147
+ function version() {
148
+ try {
149
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
150
+ return pkg.version;
151
+ }
152
+ catch {
153
+ return "unknown";
154
+ }
155
+ }
156
+ async function main() {
157
+ const { command, flags } = parseCli(process.argv.slice(2));
158
+ if (flags.version) {
159
+ process.stdout.write(`${version()}\n`);
160
+ return 0;
161
+ }
162
+ if (flags.help || command.length === 0 || command[0] === "help") {
163
+ process.stdout.write(`${HELP}\n`);
164
+ return 0;
165
+ }
166
+ if (flags.token && command[0] !== "login")
167
+ process.stderr.write("Warning: --token can end up in your shell history. Prefer METRICRAVEN_TOKEN or `metricraven login`.\n");
168
+ return run(command, flags);
169
+ }
170
+ main().then((code) => {
171
+ process.exitCode = code;
172
+ }, (error) => {
173
+ process.stderr.write(`${errorMessage(error)}\n`);
174
+ if (error instanceof UsageError && /^Unknown|must look like/.test(error.message))
175
+ process.stderr.write("Run `metricraven --help` for usage.\n");
176
+ process.exitCode = 1;
177
+ });
package/dist/prompt.js ADDED
@@ -0,0 +1,48 @@
1
+ import { createInterface } from "node:readline";
2
+ /** Reads all of stdin (for `echo $TOKEN | metricraven login`). */
3
+ export async function readStdin() {
4
+ const chunks = [];
5
+ for await (const chunk of process.stdin)
6
+ chunks.push(Buffer.from(chunk));
7
+ return Buffer.concat(chunks).toString("utf8").trim();
8
+ }
9
+ /** Prompts without echoing what is typed (tokens). */
10
+ export function promptHidden(question) {
11
+ return new Promise((resolve, reject) => {
12
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
13
+ const output = rl;
14
+ let asked = false;
15
+ output._writeToOutput = (s) => {
16
+ if (!asked) {
17
+ process.stdout.write(s);
18
+ asked = true;
19
+ }
20
+ else if (s.includes("\n") || s.includes("\r"))
21
+ process.stdout.write("\n");
22
+ };
23
+ rl.question(question, (answer) => {
24
+ rl.close();
25
+ resolve(answer.trim());
26
+ });
27
+ rl.on("SIGINT", () => {
28
+ rl.close();
29
+ process.stdout.write("\n");
30
+ reject(new Error("canceled"));
31
+ });
32
+ });
33
+ }
34
+ export function prompt(question) {
35
+ return new Promise((resolve, reject) => {
36
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
37
+ rl.question(question, (answer) => {
38
+ rl.close();
39
+ resolve(answer.trim());
40
+ });
41
+ rl.on("SIGINT", () => {
42
+ rl.close();
43
+ process.stdout.write("\n");
44
+ reject(new Error("canceled"));
45
+ });
46
+ });
47
+ }
48
+ export const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
package/dist/range.js ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Report periods, matching @metricraven/core/report-range (the dashboard's presets) without the
3
+ * Temporal polyfill: calendar math runs on UTC dates, zone offsets come from Intl.
4
+ */
5
+ export const PERIODS = ["today", "yesterday", "24h", "7d", "30d", "90d", "6m", "1y", "wtd", "mtd", "all"];
6
+ const DAY = 86_400_000;
7
+ /** Same cap as the API (core MAX_REPORT_DAYS). */
8
+ export const MAX_REPORT_DAYS = 36_600;
9
+ const formatters = new Map();
10
+ function formatter(timeZone) {
11
+ let f = formatters.get(timeZone);
12
+ if (!f) {
13
+ f = new Intl.DateTimeFormat("en-US", {
14
+ timeZone,
15
+ hourCycle: "h23",
16
+ year: "numeric",
17
+ month: "2-digit",
18
+ day: "2-digit",
19
+ hour: "2-digit",
20
+ minute: "2-digit",
21
+ second: "2-digit",
22
+ });
23
+ formatters.set(timeZone, f);
24
+ }
25
+ return f;
26
+ }
27
+ /** Accepts named IANA zones (like the API) and returns the canonical name, or null. */
28
+ export function validTimeZone(value) {
29
+ if (!value)
30
+ return "UTC";
31
+ if (value.length > 100 || !/^[A-Za-z_]+(?:\/[A-Za-z0-9_+.-]+)*$/.test(value))
32
+ return null;
33
+ try {
34
+ return new Intl.DateTimeFormat("en", { timeZone: value }).resolvedOptions().timeZone;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ /** Wall-clock fields of an instant in a zone. */
41
+ function wall(ms, timeZone) {
42
+ const parts = {};
43
+ for (const p of formatter(timeZone).formatToParts(new Date(ms)))
44
+ if (p.type !== "literal")
45
+ parts[p.type] = Number(p.value);
46
+ return { y: parts.year, m: parts.month, d: parts.day, h: parts.hour, min: parts.minute, s: parts.second };
47
+ }
48
+ /** Offset of the zone at an instant, in ms (local − UTC). */
49
+ function offsetAt(ms, timeZone) {
50
+ const w = wall(ms, timeZone);
51
+ const asUtc = Date.UTC(w.y, w.m - 1, w.d, w.h, w.min, w.s);
52
+ return asUtc - Math.floor(ms / 1000) * 1000;
53
+ }
54
+ /**
55
+ * Midnight at the start of `date` in `timeZone`, with Temporal's "compatible" disambiguation:
56
+ * an ambiguous midnight takes the earlier instant, a skipped one moves forward past the gap.
57
+ */
58
+ export function startOfDate(date, timeZone) {
59
+ const local = Date.UTC(date.y, date.m - 1, date.d);
60
+ const before = offsetAt(local - DAY, timeZone);
61
+ const after = offsetAt(local + DAY, timeZone);
62
+ const candidates = [local - before, local - after].filter((t, i, all) => all.indexOf(t) === i);
63
+ const valid = candidates.filter((t) => t + offsetAt(t, timeZone) === local);
64
+ if (valid.length)
65
+ return new Date(Math.min(...valid));
66
+ return new Date(local - before);
67
+ }
68
+ function toPlain(ms) {
69
+ const d = new Date(ms);
70
+ return { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate() };
71
+ }
72
+ const epoch = (p) => Date.UTC(p.y, p.m - 1, p.d);
73
+ const addDays = (p, days) => toPlain(epoch(p) + days * DAY);
74
+ /** ISO weekday, Monday = 1 … Sunday = 7. */
75
+ const dayOfWeek = (p) => ((new Date(epoch(p)).getUTCDay() + 6) % 7) + 1;
76
+ export function parseDate(value) {
77
+ if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value))
78
+ return null;
79
+ const ms = Date.parse(`${value}T00:00:00.000Z`);
80
+ if (!Number.isFinite(ms) || new Date(ms).toISOString().slice(0, 10) !== value)
81
+ return null;
82
+ return toPlain(ms);
83
+ }
84
+ /** Inclusive calendar dates in the zone → exact instants with an exclusive end (core customRange). */
85
+ export function customRange(from, to, timeZone = "UTC") {
86
+ const start = parseDate(from);
87
+ const end = parseDate(to);
88
+ if (!start || !end || epoch(start) > epoch(end) || epoch(end) - epoch(start) >= MAX_REPORT_DAYS * DAY)
89
+ return null;
90
+ const result = { from: startOfDate(start, timeZone), to: startOfDate(addDays(end, 1), timeZone) };
91
+ return result.from < result.to ? result : null;
92
+ }
93
+ /** A preset (today, 7d, mtd, …) as UTC instants; same results as core resolveRange with offset 0. */
94
+ export function presetRange(preset, timeZone = "UTC", now = new Date()) {
95
+ const w = wall(now.getTime(), timeZone);
96
+ const today = { y: w.y, m: w.m, d: w.d };
97
+ const instant = (p) => startOfDate(p, timeZone);
98
+ switch (preset) {
99
+ case "today":
100
+ return { from: instant(today), to: now };
101
+ case "yesterday":
102
+ return { from: instant(addDays(today, -1)), to: instant(today) };
103
+ case "wtd":
104
+ return { from: instant(addDays(today, -(dayOfWeek(today) - 1))), to: now };
105
+ case "mtd":
106
+ return { from: instant({ ...today, d: 1 }), to: now };
107
+ default: {
108
+ const days = { "24h": 1, "7d": 7, "30d": 30, "90d": 90, "6m": 182, "1y": 365 }[preset] ?? 30;
109
+ return { from: new Date(now.getTime() - days * DAY), to: now };
110
+ }
111
+ }
112
+ }
113
+ /** Calendar date (YYYY-MM-DD) of an instant in a zone. */
114
+ export function calendarDate(date, timeZone = "UTC") {
115
+ const w = wall(date.getTime(), timeZone);
116
+ return `${w.y}-${String(w.m).padStart(2, "0")}-${String(w.d).padStart(2, "0")}`;
117
+ }
118
+ /**
119
+ * Start of the comparison window (`--compare`), matching @metricraven/core/compare: "year" is the
120
+ * same calendar day a year earlier (29 Feb → 28 Feb), a YYYY-MM-DD is that day; both keep the
121
+ * range's time of day. "previous" (the default) and "off" return null. Undefined for bad input.
122
+ */
123
+ export function compareStartFor(value, from, timeZone = "UTC") {
124
+ if (value === "previous" || value === "off")
125
+ return null;
126
+ const day = calendarDate(from, timeZone);
127
+ const [y, m, d] = day.split("-").map(Number);
128
+ let target;
129
+ if (value === "year")
130
+ target = { y: y - 1, m, d: Math.min(d, new Date(Date.UTC(y - 1, m, 0)).getUTCDate()) };
131
+ else
132
+ target = parseDate(value);
133
+ if (!target)
134
+ return undefined;
135
+ const intoDay = from.getTime() - startOfDate({ y, m, d }, timeZone).getTime();
136
+ const start = new Date(startOfDate(target, timeZone).getTime() + intoDay);
137
+ return start < from ? start : undefined;
138
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@metricraven/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "MetricRaven from your terminal: traffic, revenue, goals, visitors and websites. Built for people and AI agents.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://metricraven.com/docs/cli",
8
+ "keywords": [
9
+ "analytics",
10
+ "metricraven",
11
+ "cli",
12
+ "web-analytics",
13
+ "revenue"
14
+ ],
15
+ "bin": {
16
+ "metricraven": "dist/index.js"
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json && chmod +x dist/index.js",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit",
30
+ "prepublishOnly": "npm run build"
31
+ }
32
+ }