feat: add frontend analytics wrapper and consent store

This commit is contained in:
ashim-hq
2026-04-22 19:07:50 +08:00
parent a3f707a361
commit 544f81c48d
4 changed files with 528 additions and 0 deletions
+113
View File
@@ -0,0 +1,113 @@
import type { AnalyticsConfig } from "@ashim/shared";
import * as Sentry from "@sentry/react";
import posthogJs from "posthog-js";
let posthog: import("posthog-js").PostHog | null = null;
let initialized = false;
let consentGranted = false;
const FILE_EXT_PATTERN =
/\.(jpe?g|png|pdf|webp|gif|tiff?|bmp|svg|he[ic]f?|avif|raw|cr2|nef|arw|dng|psd|tga|exr|hdr)\b/gi;
const FILE_PATH_PATTERN = /\/(tmp\/workspace|data\/files|data\/ai|Users|home)\//g;
function scrubString(str: string): string {
return str.replace(FILE_EXT_PATTERN, ".[REDACTED]").replace(FILE_PATH_PATTERN, "/[REDACTED]/");
}
export function initAnalytics(config: AnalyticsConfig): void {
if (initialized || !config.enabled) return;
initialized = true;
try {
posthog =
posthogJs.init(config.posthogApiKey, {
api_host: config.posthogHost,
autocapture: false,
capture_pageview: true,
disable_session_recording: true,
session_recording: {
captureCanvas: { recordCanvas: false },
maskAllInputs: true,
maskTextSelector: ".file-name, .file-path, [data-file-name]",
blockSelector: "[data-user-content]",
},
ip: false,
persistence: "localStorage",
}) ?? null;
} catch {
// SDK blocked or unavailable — use null provider
}
try {
if (config.sentryDsn) {
Sentry.init({
dsn: config.sentryDsn,
sendDefaultPii: false,
beforeSend(event) {
if (!consentGranted) return null;
startErrorReplay();
if (event.user) {
delete event.user.email;
delete event.user.username;
}
if (event.exception?.values) {
for (const ex of event.exception.values) {
if (ex.value) ex.value = scrubString(ex.value);
if (ex.stacktrace?.frames) {
for (const frame of ex.stacktrace.frames) {
if (frame.filename) frame.filename = scrubString(frame.filename);
if (frame.abs_path) frame.abs_path = scrubString(frame.abs_path);
}
}
}
}
return event;
},
beforeBreadcrumb(breadcrumb) {
if (!consentGranted) return null;
if (breadcrumb.category === "ui.click") return null;
if (breadcrumb.category === "fetch" && breadcrumb.data?.url) {
if (FILE_EXT_PATTERN.test(breadcrumb.data.url as string)) return null;
}
if (breadcrumb.message) {
breadcrumb.message = scrubString(breadcrumb.message);
}
return breadcrumb;
},
});
}
} catch {
// Sentry blocked or unavailable
}
}
export function setAnalyticsConsent(enabled: boolean): void {
consentGranted = enabled;
}
export function identify(instanceId: string, properties: Record<string, unknown>): void {
if (!posthog || !consentGranted) return;
try {
posthog.identify(instanceId, properties);
} catch {
// never throw
}
}
export function track(event: string, properties?: Record<string, unknown>): void {
if (!posthog || !consentGranted) return;
try {
posthog.capture(event, properties);
} catch {
// never throw
}
}
export function startErrorReplay(): void {
if (!posthog || !consentGranted) return;
try {
posthog.startSessionRecording();
} catch {
// never throw
}
}
+102
View File
@@ -0,0 +1,102 @@
import type { AnalyticsConfig, ConsentState } from "@ashim/shared";
import { create } from "zustand";
import { setAnalyticsConsent } from "@/lib/analytics";
import { apiPut } from "@/lib/api";
interface AnalyticsState {
config: AnalyticsConfig | null;
consent: ConsentState;
configLoaded: boolean;
fetchConfig: () => Promise<void>;
setConsent: (consent: ConsentState) => void;
acceptAnalytics: () => Promise<void>;
declineAnalytics: () => Promise<void>;
remindLater: () => Promise<void>;
toggleAnalytics: (enabled: boolean) => Promise<void>;
}
export const useAnalyticsStore = create<AnalyticsState>((set, get) => ({
config: null,
consent: {
analyticsEnabled: null,
analyticsConsentShownAt: null,
analyticsConsentRemindAt: null,
},
configLoaded: false,
fetchConfig: async () => {
if (get().configLoaded) return;
try {
const res = await fetch("/api/v1/config/analytics");
const config: AnalyticsConfig = await res.json();
set({ config, configLoaded: true });
} catch {
set({ configLoaded: true });
}
},
setConsent: (consent: ConsentState) => {
set({ consent });
setAnalyticsConsent(consent.analyticsEnabled === true);
},
acceptAnalytics: async () => {
try {
await apiPut("/v1/user/analytics", { enabled: true });
} catch {
localStorage.setItem("ashim-analytics-consent", "true");
}
const now = Date.now();
const consent: ConsentState = {
analyticsEnabled: true,
analyticsConsentShownAt: now,
analyticsConsentRemindAt: null,
};
set({ consent });
setAnalyticsConsent(true);
},
declineAnalytics: async () => {
try {
await apiPut("/v1/user/analytics", { enabled: false });
} catch {
localStorage.setItem("ashim-analytics-consent", "false");
}
const now = Date.now();
const consent: ConsentState = {
analyticsEnabled: false,
analyticsConsentShownAt: now,
analyticsConsentRemindAt: null,
};
set({ consent });
setAnalyticsConsent(false);
},
remindLater: async () => {
try {
await apiPut("/v1/user/analytics", { remindLater: true });
} catch {
localStorage.setItem("ashim-analytics-consent", "remind");
}
const now = Date.now();
const consent: ConsentState = {
analyticsEnabled: null,
analyticsConsentShownAt: now,
analyticsConsentRemindAt: now + 7 * 24 * 60 * 60 * 1000,
};
set({ consent });
setAnalyticsConsent(false);
},
toggleAnalytics: async (enabled: boolean) => {
try {
await apiPut("/v1/user/analytics", { enabled });
} catch {
localStorage.setItem("ashim-analytics-consent", enabled ? "true" : "false");
}
set((state) => ({
consent: { ...state.consent, analyticsEnabled: enabled },
}));
setAnalyticsConsent(enabled);
},
}));