import { env, waitUntil } from "cloudflare:workers";
import { scrubErrorMessage } from "~/lib/scrub-error";
import { first } from "./db";
import { isLoopbackUrl } from "./deployment";
/**
* Product analytics (PostHog), optional like Stripe: off unless POSTHOG_KEY (or the VITE_POSTHOG_PROJECT_TOKEN
* alias) is set. Server events carry no PII: distinct ids are opaque account ids, and properties are enums
* and counts only, never emails, names, private repository names or paths.
*/
export type AnalyticsConfig = { key: string; host: string };
const DEFAULT_HOST = "https://us.i.posthog.com";
const CAPTURE_TIMEOUT_MS = 3000;
/**
* Analytics runs only in production: never under `vite dev`/preview (GITFOR_LOCAL), never on a loopback
* PUBLIC_URL, and never when GITFOR_ENV names another environment (staging, test).
*/
function productionDeployment(): boolean {
if (env.GITFOR_LOCAL === "true" || isLoopbackUrl(env.PUBLIC_URL)) return false;
const name = (env.GITFOR_ENV ?? "").trim().toLowerCase();
return name === "" || name === "production";
}
export function analyticsConfig(): AnalyticsConfig | null {
if (!productionDeployment()) return null;
const key = (env.POSTHOG_KEY || env.VITE_POSTHOG_PROJECT_TOKEN || "").trim();
if (!/^phc_[A-Za-z0-9]+$/.test(key)) return null;
const raw = (env.POSTHOG_HOST || env.VITE_POSTHOG_HOST || DEFAULT_HOST).trim();
try {
const url = new URL(raw);
if (url.protocol !== "https:" || url.username || url.password) return null;
return { key, host: url.origin };
} catch {
return null;
}
}
/** What the browser needs to start PostHog; null when analytics is off. */