/** * Anonymous usage analytics (ADR 0016): when nothing is sent, the anonymous id, * and the events a command collects while it runs. `BaseCommand` sends them * when the command ends, through `clients/analytics.ts`. */ import { randomUUID } from "node:crypto"; import { existsSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { type AnalyticsEvent, sendEvents } from "./clients/analytics.js"; import { configFilePath, DEFAULT_MANAGEMENT_URL, ENV, type Env, isOn, nonEmpty, writeSecretFile, } from "./config.js"; import { isRecord, writeNotice } from "./errors.js"; import { credentialsFilePath, readCredentialsFile } from "./session.js"; const NOTICE = "meili sends anonymous usage data to Meilisearch, to improve the CLI. What is sent, and how to turn it off: https://github.com/meilisearch/cli#analytics"; const collected: Array> = []; /** Adds an event to the ones the command sends when it ends. */ export function track(event: string, properties: Record): void { collected.push({ event, properties, timestamp: new Date().toISOString() }); } /** * Off when the human asks, in CI, and against a Cloud other than Meilisearch * Cloud, whose users do not belong in its PostHog project. */ function enabled(env: Env): boolean { const managementUrl = nonEmpty(env[ENV.MANAGEMENT_URL]); return !( isOn(env[ENV.NO_ANALYTICS]) || isOn(env.DO_NOT_TRACK) || env.CI !== undefined || (managementUrl !== undefined && managementUrl !== DEFAULT_MANAGEMENT_URL) ); } const analyticsFilePath = (env: Env): string => join(dirname(configFilePath(env)), "analytics.json"); /** * The id of `analytics.json`, next to the config file. The first time, the * file is written and the notice shown. When the file cannot be written, each * process has its own id, and the notice is not repeated on every command. */ function anonymousId(env: Env): string { const path = analyticsFilePath(env); try { const parsed: unknown = JSON.parse(readFileSync(path, "utf8")); if (isRecord(parsed) && typeof parsed.anonymousId === "string") return parsed.anonymousId; } catch { // No file yet, or not ours: a new id replaces it. } const id = randomUUID(); try { writeSecretFile(path, { anonymousId: id }); writeNotice(NOTICE); } catch { // A read-only mount, for example. } return id; } /** The Cloud user of the session of `auth login`, if any. */ function sessionUserId(env: Env): string | undefined { try { return readCredentialsFile(credentialsFilePath(env), () => {})?.userId; } catch { // A malformed file: the next management command says so. return undefined; } } /** * For a session of Meilisearch Cloud, when usage data is sent: the id of the * Cloud user, to store in the session, and one `$identify` that joins the * anonymous id to it. Undefined when nothing is sent, the session belongs to * another Cloud, or `fetchUserId` fails: the CLI stays anonymous. */ export async function identify( env: Env, managementUrl: string, fetchUserId: () => Promise, ): Promise { if (!enabled(env) || managementUrl !== DEFAULT_MANAGEMENT_URL) return undefined; let userId: string; try { userId = await fetchUserId(); } catch { return undefined; } track("$identify", { $anon_distinct_id: anonymousId(env) }); return userId; } /** After a logout: a new anonymous id, so the next person on the machine is not joined to the previous one. */ export function resetAnonymousId(env: Env): void { if (!enabled(env)) return; try { writeSecretFile(analyticsFilePath(env), { anonymousId: randomUUID() }); } catch { // A read-only mount, for example. } } /** * The agents of `@vercel/detect-agent` 1.2.7, in its order: the first that the * environment names runs the CLI. An empty variable names none. */ const AGENTS: Array<[string, (env: Env) => unknown]> = [ ["cursor", (env) => env.CURSOR_TRACE_ID], ["cursor-cli", (env) => env.CURSOR_AGENT || env.CURSOR_EXTENSION_HOST_ROLE === "agent-exec"], ["gemini", (env) => env.GEMINI_CLI], ["codex", (env) => env.CODEX_SANDBOX || env.CODEX_CI || env.CODEX_THREAD_ID], ["antigravity", (env) => env.ANTIGRAVITY_AGENT], ["augment", (env) => env.AUGMENT_AGENT], ["opencode", (env) => env.OPENCODE === "1" || env.OPENCODE_CLIENT], ["claude-code", (env) => env.CLAUDECODE || env.CLAUDE_CODE], ["replit", (env) => env.REPL_ID], [ "github-copilot", (env) => env.COPILOT_MODEL || env.COPILOT_ALLOW_ALL || env.COPILOT_GITHUB_TOKEN, ], ["devin", () => existsSync("/opt/.devin")], ]; /** * The coding agent that runs the CLI, by one of the ids above. `AI_AGENT`, a * name any agent can set, comes first: `claude-code_2-1-309_agent` is the * name, its version and its mode. A name not in the list is `other`, so that * free text is never sent. */ export function agentOf(env: Env): string | undefined { const named = nonEmpty(env.AI_AGENT)?.trim().split("_")[0]; if (named !== undefined) { if (named === "github-copilot-cli") return "github-copilot"; return AGENTS.some(([id]) => id === named) ? named : "other"; } return AGENTS.find(([, detect]) => detect(env))?.[0]; } /** How the CLI at `root`, oclif's `config.root`, was installed (ADR 0017). */ export function installMethod(root: string): string { // An archive brings its own Node, inside the CLI's folder. if (process.execPath.startsWith(join(root, "/"))) return "archive"; const path = root.replaceAll("\\", "/"); if (path.includes("/Cellar/")) return "brew"; if (path.includes("/_npx/")) return "npx"; if (path.includes("/dlx/")) return "pnpm"; if (path.endsWith("/node_modules/@meilisearch/cli")) return "npm"; return "other"; } /** The kind of Meilisearch instance a URL names, never the URL. */ export function targetOf(url: string): "local" | "cloud" | "other" { const host = new URL(url).hostname.replace(/^\[(.*)\]$/, "$1"); if (host === "meilisearch.io" || host.endsWith(".meilisearch.io")) return "cloud"; const local = host === "localhost" || host.endsWith(".localhost") || host.startsWith("127.") || host === "::1" || host === "0.0.0.0" || host === "host.docker.internal"; return local ? "local" : "other"; } /** Sends the events the command collected, each with `common`, then forgets them. */ export async function sendAnalytics(env: Env, common: Record): Promise { const events = collected.splice(0); if (events.length === 0 || !enabled(env)) return; const userId = sessionUserId(env); const distinctId = userId ?? anonymousId(env); const properties = { ...common, site: "cli", os: process.platform, arch: process.arch, node_version: process.versions.node, tty: process.stdin.isTTY === true && process.stderr.isTTY === true, agent: agentOf(env), $lib: "meili-cli", ...(userId === undefined && { $process_person_profile: false }), }; await sendEvents( events.map((event) => ({ ...event, distinct_id: distinctId, properties: { ...properties, ...event.properties }, })), ); } /** * The names of the flags on the command line, never their values. Only the * names the command declares: an argument that only looks like a flag is a value. */ export function flagNames( argv: readonly string[], flags: Record, ): string[] { const known = new Map(); for (const [name, flag] of Object.entries(flags)) { known.set(`--${name}`, name); if (flag.char !== undefined) known.set(`-${flag.char}`, name); if (flag.allowNo === true) known.set(`--no-${name}`, `no-${name}`); } const names = argv.flatMap((arg) => known.get(arg.split("=")[0] ?? "") ?? []); return [...new Set(names)]; }