← Files JuicyLucy AdsARCHIVED FILE

skills/media-use/scripts/lib/telemetry.mjs

6.32 KB · Oct 4, 2026 · 12:34 UTC

↓ Download file

// Usage tracking shares the CLI and Studio identity. Properties stay coarse and
// never carry intent text, file names, or paths.

import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";

const POSTHOG_API_KEY = "phc_zjjbX0PnWxERXrMHhkEJWj9A9BhGVLRReICgsfTMmpx";
const POSTHOG_HOST = "https://us.i.posthog.com";
const TIMEOUT_MS = 1500;
let identifiedAccount = false;
let warnedNonDefaultHost = false;

function isTestOrCiContext() {
  return (
    process.env.CI === "true" ||
    process.env.CI === "1" ||
    process.env.NODE_ENV === "test" ||
    process.env.NODE_ENV === "development"
  );
}

function posthogHost() {
  const override = process.env.MEDIA_USE_TELEMETRY_HOST;
  if (override && !warnedNonDefaultHost && !isTestOrCiContext()) {
    warnedNonDefaultHost = true;
    console.error(
      `media-use: telemetry is redirected to a non-default host via MEDIA_USE_TELEMETRY_HOST (${override}) — unset it unless this is intentional.`,
    );
  }
  return override || POSTHOG_HOST;
}

/** True when telemetry must NOT be sent (opt-out envs, CI, dev). */
export function optedOut() {
  return (
    process.env.HYPERFRAMES_NO_TELEMETRY === "1" ||
    process.env.DO_NOT_TRACK === "1" ||
    process.env.CI === "true" ||
    process.env.CI === "1" ||
    process.env.NODE_ENV === "development"
  );
}

// Read and write the shared config so media-use keeps one identity per install.
function sharedConfigPath() {
  return join(homedir(), ".hyperframes", "config.json");
}

function readSharedConfig() {
  try {
    const file = sharedConfigPath();
    if (existsSync(file)) {
      const parsed = JSON.parse(readFileSync(file, "utf8"));
      if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
    }
  } catch {
    // unreadable config → treat as empty; never throw
  }
  return {};
}

function writeSharedConfig(config) {
  const dir = join(homedir(), ".hyperframes");
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
  writeFileSync(join(dir, "config.json"), JSON.stringify(config, null, 2) + "\n");
}

// Adopt a pre-existing media-use-only id (~/.media/anon-id from before this
// change) so upgraders keep their PostHog persona instead of resetting to a new
// one — otherwise cross-surface continuity would start over on upgrade.
function legacyMediaAnonId() {
  try {
    const file = join(homedir(), ".media", "anon-id");
    if (existsSync(file)) {
      const id = readFileSync(file, "utf8").trim();
      if (id) return id;
    }
  } catch {
    // ignore
  }
  return null;
}

// Stable per-machine id from the shared config; seeds it (adopting a legacy
// media-use id when present) if absent.
function anonymousId() {
  try {
    const config = readSharedConfig();
    if (typeof config.anonymousId === "string" && config.anonymousId.trim()) {
      return config.anonymousId.trim();
    }
    const id = legacyMediaAnonId() || randomUUID();
    writeSharedConfig({ ...config, anonymousId: id });
    return id;
  } catch {
    return "anon"; // best-effort; a shared bucket is fine if the fs is read-only
  }
}

function heygenAccountDistinctId() {
  const file = join(process.env.HEYGEN_CONFIG_DIR || join(homedir(), ".heygen"), "credentials");
  try {
    if (!existsSync(file)) return null;
    const raw = readFileSync(file, "utf8").trim();
    if (!raw.startsWith("{")) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
    const user = parsed.user;
    if (!user || typeof user !== "object" || Array.isArray(user)) return null;
    const id = typeof user.email === "string" && user.email.trim() ? user.email : user.username;
    // Lowercased so this joins with the CLI's own identify call regardless of
    // the account's stored email casing — two different-case distinct ids
    // would otherwise split one person across two PostHog profiles.
    return typeof id === "string" && id.trim() ? id.trim().toLowerCase() : null;
  } catch {
    return null;
  }
}

function showTelemetryNotice() {
  if (optedOut()) return;
  try {
    const config = readSharedConfig();
    // Shared with the CLI (config.telemetryNoticeShown): shown once per person
    // across surfaces, not once per tool.
    if (config.telemetryNoticeShown === true) return;
    console.error(
      [
        "media-use sends usage telemetry: media type, resolution source, and provider; never intent text, file names, or paths.",
        "If you sign in to HeyGen, usage links to your account email or username. Opt out with HYPERFRAMES_NO_TELEMETRY=1 or DO_NOT_TRACK=1.",
      ].join("\n"),
    );
    writeSharedConfig({ ...config, telemetryNoticeShown: true });
  } catch {
    // notice is best-effort; never surface into the command
  }
}

async function postBatch(batch) {
  try {
    await fetch(`${posthogHost()}/batch/`, {
      method: "POST",
      headers: { "Content-Type": "application/json", Connection: "close" },
      body: JSON.stringify({ api_key: POSTHOG_API_KEY, batch }),
      signal: AbortSignal.timeout(TIMEOUT_MS),
    });
  } catch {
    // telemetry is best-effort; never surface into the command
  }
}

async function postEvent(event, properties, distinctId) {
  await postBatch([
    {
      event,
      properties: { ...properties, surface: "media-use", $ip: null },
      distinct_id: distinctId,
      timestamp: new Date().toISOString(),
    },
  ]);
}

async function identifyAccount(anonId) {
  if (optedOut() || identifiedAccount) return;
  const distinctId = heygenAccountDistinctId();
  if (!distinctId) return;
  identifiedAccount = true;
  await postEvent("$identify", { $anon_distinct_id: anonId }, distinctId);
}

/**
 * Fire-and-forget a single event to PostHog. Best-effort: awaited with a short
 * timeout so a short-lived script flushes before exit, but any failure (offline,
 * opted out) is swallowed. `properties` must be non-PII (no intent/paths).
 */
export async function track(event, properties = {}) {
  if (optedOut()) return;
  showTelemetryNotice();
  const anonId = anonymousId();
  await identifyAccount(anonId);
  await postEvent(event, properties, anonId);
}

export function __anonymousIdForTest() {
  return anonymousId();
}

export function __resetTelemetryForTest() {
  identifiedAccount = false;
  warnedNonDefaultHost = false;
}

SHA-256: c6bbfb6586f7533547e77802cf5e54e5dd0b00f8c313fb0f5cc8aa0c14092a05