@metricraven/cli 0.0.0-stage → 0.1.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 +65 -2
- package/dist/api.js +76 -0
- package/dist/args.js +119 -0
- package/dist/commands.js +702 -0
- package/dist/completion.js +63 -0
- package/dist/config.js +48 -0
- package/dist/format.js +67 -0
- package/dist/index.js +113 -0
- package/dist/prompt.js +48 -0
- package/dist/range.js +117 -0
- package/package.json +30 -4
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { UsageError } from "./args.js";
|
|
2
|
+
/** Shell completion scripts for `metricraven completion bash|zsh|fish`. */
|
|
3
|
+
const COMMANDS = ["login", "logout", "whoami", "use", "websites", "analytics", "realtime", "visitors", "funnels", "notes", "mentions", "alerts", "members", "completion"];
|
|
4
|
+
const SUB = {
|
|
5
|
+
websites: ["list", "create"],
|
|
6
|
+
analytics: ["traffic", "breakdown", "revenue", "conversions", "goal", "insights", "search", "crawlers"],
|
|
7
|
+
visitors: ["list", "get"],
|
|
8
|
+
funnels: ["list"],
|
|
9
|
+
notes: ["list", "add"],
|
|
10
|
+
mentions: ["list"],
|
|
11
|
+
alerts: ["list", "get", "create", "update", "delete", "history"],
|
|
12
|
+
members: ["list", "invite", "role", "remove", "revoke"],
|
|
13
|
+
completion: ["bash", "zsh", "fish"],
|
|
14
|
+
};
|
|
15
|
+
const FLAGS = ["--json", "--site", "--token", "--verbose", "--help", "--version", "--period", "--from", "--to", "--timezone", "--filter", "--sort", "--limit", "--offset", "--q", "--payment", "--name", "--domain", "--date", "--text", "--goal", "--trigger", "--subject", "--message", "--notify", "--enabled", "--disabled", "--yes", "--alert", "--platform", "--role"];
|
|
16
|
+
export function completionScript(shell) {
|
|
17
|
+
if (shell === "bash") {
|
|
18
|
+
const cases = Object.entries(SUB)
|
|
19
|
+
.map(([cmd, subs]) => ` ${cmd}) COMPREPLY=($(compgen -W "${subs.join(" ")} ${FLAGS.join(" ")}" -- "$cur")) ;;`)
|
|
20
|
+
.join("\n");
|
|
21
|
+
return `# metricraven bash completion. Add to ~/.bashrc: eval "$(metricraven completion bash)"
|
|
22
|
+
_metricraven() {
|
|
23
|
+
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
24
|
+
if [ "$COMP_CWORD" -eq 1 ]; then
|
|
25
|
+
COMPREPLY=($(compgen -W "${COMMANDS.join(" ")} ${FLAGS.join(" ")}" -- "$cur")); return
|
|
26
|
+
fi
|
|
27
|
+
case "\${COMP_WORDS[1]}" in
|
|
28
|
+
${cases}
|
|
29
|
+
*) COMPREPLY=($(compgen -W "${FLAGS.join(" ")}" -- "$cur")) ;;
|
|
30
|
+
esac
|
|
31
|
+
}
|
|
32
|
+
complete -F _metricraven metricraven`;
|
|
33
|
+
}
|
|
34
|
+
if (shell === "zsh") {
|
|
35
|
+
const cases = Object.entries(SUB)
|
|
36
|
+
.map(([cmd, subs]) => ` ${cmd}) compadd -- ${subs.join(" ")} ${FLAGS.join(" ")} ;;`)
|
|
37
|
+
.join("\n");
|
|
38
|
+
return `#compdef metricraven
|
|
39
|
+
# metricraven zsh completion. Add to ~/.zshrc: eval "$(metricraven completion zsh)"
|
|
40
|
+
_metricraven() {
|
|
41
|
+
if (( CURRENT == 2 )); then
|
|
42
|
+
compadd -- ${COMMANDS.join(" ")} ${FLAGS.join(" ")}
|
|
43
|
+
else
|
|
44
|
+
case "\${words[2]}" in
|
|
45
|
+
${cases}
|
|
46
|
+
*) compadd -- ${FLAGS.join(" ")} ;;
|
|
47
|
+
esac
|
|
48
|
+
fi
|
|
49
|
+
}
|
|
50
|
+
compdef _metricraven metricraven`;
|
|
51
|
+
}
|
|
52
|
+
if (shell === "fish") {
|
|
53
|
+
const lines = [
|
|
54
|
+
"# metricraven fish completion. Save to ~/.config/fish/completions/metricraven.fish",
|
|
55
|
+
"complete -c metricraven -f",
|
|
56
|
+
`complete -c metricraven -n "__fish_use_subcommand" -a "${COMMANDS.join(" ")}"`,
|
|
57
|
+
...Object.entries(SUB).map(([cmd, subs]) => `complete -c metricraven -n "__fish_seen_subcommand_from ${cmd}" -a "${subs.join(" ")}"`),
|
|
58
|
+
...FLAGS.map((f) => `complete -c metricraven -l ${f.slice(2)}`),
|
|
59
|
+
];
|
|
60
|
+
return lines.join("\n");
|
|
61
|
+
}
|
|
62
|
+
throw new UsageError("Use: metricraven completion bash|zsh|fish");
|
|
63
|
+
}
|
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,113 @@
|
|
|
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
|
+
|
|
14
|
+
Websites
|
|
15
|
+
websites list Websites this token can use (* = default)
|
|
16
|
+
websites create --name --domain
|
|
17
|
+
Add a website; prints its ID, secret key and script
|
|
18
|
+
use <website_id> Set the default website
|
|
19
|
+
|
|
20
|
+
Reports (default: last 30 days)
|
|
21
|
+
analytics traffic Visitors, pageviews, revenue, conversion, top sources
|
|
22
|
+
analytics breakdown <dim> Full table for a dimension: channel, referrer, page,
|
|
23
|
+
entryPage, utmSource, utmCampaign, country, city,
|
|
24
|
+
browser, os, device, hostname, outbound, …
|
|
25
|
+
analytics revenue Payments, renewals, refunds, LTV, revenue by channel
|
|
26
|
+
analytics conversions Goals and funnel steps
|
|
27
|
+
analytics goal <name> One goal in detail
|
|
28
|
+
analytics insights What converts: sources, countries, time to purchase
|
|
29
|
+
analytics search Google Search Console queries
|
|
30
|
+
analytics crawlers AI crawlers and bots
|
|
31
|
+
realtime Visitors online now
|
|
32
|
+
visitors list Visitors in the period (needs visitor details access)
|
|
33
|
+
visitors get <visitor_id> One visitor's journey (needs visitor details access)
|
|
34
|
+
funnels list Saved funnels
|
|
35
|
+
notes list Chart notes in the period
|
|
36
|
+
notes add --text [--date] Add a chart note (needs write access)
|
|
37
|
+
mentions X and Reddit posts mentioning the website (Growth);
|
|
38
|
+
--platform x|reddit, --q, -n/--limit, --offset
|
|
39
|
+
|
|
40
|
+
Alerts (email when a goal, payment or new customer happens)
|
|
41
|
+
alerts list Alerts on the website
|
|
42
|
+
alerts get <alert_id> One alert with its counts
|
|
43
|
+
alerts create --goal <name> New goal alert; or --trigger payment|new_customer
|
|
44
|
+
[--name] [--subject] [--message] [--notify me|members]
|
|
45
|
+
[--disabled] (needs write access)
|
|
46
|
+
alerts update <alert_id> [--name] [--goal] [--enabled | --disabled]
|
|
47
|
+
alerts delete <alert_id> Delete an alert (asks first; --yes to skip)
|
|
48
|
+
alerts history [--alert <id>] Emails the alerts sent, newest first
|
|
49
|
+
|
|
50
|
+
Team
|
|
51
|
+
members list Members, roles and (admins) pending invitations
|
|
52
|
+
members invite <email> --role admin|viewer
|
|
53
|
+
Email an invitation (needs write access, admin)
|
|
54
|
+
members role <user_id> --role admin|viewer
|
|
55
|
+
members remove <user_id> Remove a member (asks first; --yes to skip)
|
|
56
|
+
members revoke <invite_id> Revoke a pending invitation
|
|
57
|
+
completion bash|zsh|fish Print a shell completion script
|
|
58
|
+
|
|
59
|
+
Period and filters
|
|
60
|
+
-p, --period <p> today, yesterday, 24h, 7d, 30d, 90d, 6m, 1y, wtd, mtd, all
|
|
61
|
+
--from, --to <date> Custom days, YYYY-MM-DD (inclusive)
|
|
62
|
+
-z, --timezone <zone> IANA zone for day boundaries, e.g. Europe/Madrid (default UTC)
|
|
63
|
+
-f, --filter <dim:op:value> Repeatable. Ops: is, is_not, contains, not_contains
|
|
64
|
+
e.g. -f country:is:US -f page:contains:/blog
|
|
65
|
+
|
|
66
|
+
List options
|
|
67
|
+
--sort, -n/--limit, --offset, --q (search), --payment all|paid|unpaid
|
|
68
|
+
|
|
69
|
+
Global
|
|
70
|
+
--site <id> Website for this command (or METRICRAVEN_SITE, or \`use\`)
|
|
71
|
+
--json Raw API JSON (compact), for scripts and AI agents
|
|
72
|
+
-v, --verbose Print request URLs and status codes to stderr
|
|
73
|
+
--token <token> Use this token (prefer METRICRAVEN_TOKEN: flags end up in shell history)
|
|
74
|
+
-h, --help Show help
|
|
75
|
+
--version Show the version
|
|
76
|
+
|
|
77
|
+
Environment
|
|
78
|
+
METRICRAVEN_TOKEN Access token (overrides the saved one)
|
|
79
|
+
METRICRAVEN_SITE Default website ID
|
|
80
|
+
METRICRAVEN_API_BASE API origin (default https://metricraven.com)
|
|
81
|
+
|
|
82
|
+
Docs: https://metricraven.com/docs/cli`;
|
|
83
|
+
function version() {
|
|
84
|
+
try {
|
|
85
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
86
|
+
return pkg.version;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return "unknown";
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function main() {
|
|
93
|
+
const { command, flags } = parseCli(process.argv.slice(2));
|
|
94
|
+
if (flags.version) {
|
|
95
|
+
process.stdout.write(`${version()}\n`);
|
|
96
|
+
return 0;
|
|
97
|
+
}
|
|
98
|
+
if (flags.help || command.length === 0 || command[0] === "help") {
|
|
99
|
+
process.stdout.write(`${HELP}\n`);
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
102
|
+
if (flags.token && command[0] !== "login")
|
|
103
|
+
process.stderr.write("Warning: --token can end up in your shell history. Prefer METRICRAVEN_TOKEN or `metricraven login`.\n");
|
|
104
|
+
return run(command, flags);
|
|
105
|
+
}
|
|
106
|
+
main().then((code) => {
|
|
107
|
+
process.exitCode = code;
|
|
108
|
+
}, (error) => {
|
|
109
|
+
process.stderr.write(`${errorMessage(error)}\n`);
|
|
110
|
+
if (error instanceof UsageError && /^Unknown|must look like/.test(error.message))
|
|
111
|
+
process.stderr.write("Run `metricraven --help` for usage.\n");
|
|
112
|
+
process.exitCode = 1;
|
|
113
|
+
});
|
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,117 @@
|
|
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metricraven/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.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
|
+
}
|