Files
infiplot-web/lib/analytics.ts
T
yuanzonghao e095650944 refactor(web): enforce content-free Umami fields at compile time
Address the Copilot review on #26.

#1 The game_start / art_style_select payload fields were typed as bare
   `string`, so free text could still slip through despite the "content-free
   by construction" claim. Add lib/options.ts as the single source of truth
   for the selector option sets (`as const` → literal-union types), have the
   home OPTS render from those arrays, and type the analytics fields from the
   derived unions (gender/art_style/plot_style/pacing/style) plus a template
   type for `card`. Free text now fails to compile; no casts at call sites.

#2 The /play heartbeat scheduled its 30s interval unconditionally. Gate the
   effect on the same NEXT_PUBLIC_UMAMI_* env used for script injection, so
   nothing is scheduled when the tracker is off (visibility check kept — a
   hidden tab still never emits).

#3 choice_select no longer emits a -1 choice_index: skip the event when the
   index can't be resolved instead of polluting the index distribution.

Verified with tsc (exit 0) and a throwaway negative test: free text in any
of the six fields raises TS2322, valid enum/template values compile.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-04 10:59:31 +08:00

73 lines
2.8 KiB
TypeScript

// Privacy-first analytics. Sends only content-free, categorical events to
// Umami, and only when the tracker script is actually present (gated by the
// NEXT_PUBLIC_UMAMI_* env vars in components/Analytics.tsx). With no script
// loaded — local dev, forks, a non-matching data-domains host, or a visitor
// with Do Not Track — `window.umami` is undefined and every call here is a
// silent no-op: zero runtime impact, no errors.
//
// RULE: never pass free text (player prompts, custom world/style guides,
// uploaded images, vision output) or any per-user identifier. Only enums,
// indices, counts and booleans — that is what keeps these events as
// privacy-friendly as the cookieless page-view baseline.
import type { ArtStyle, Gender, Pacing, PlotStyle } from "./options";
declare global {
interface Window {
umami?: {
track: (event: string, data?: Record<string, unknown>) => void;
};
}
}
// Per-event payload schema. Fixing each event's allowed fields turns the RULE
// above into a compile-time guarantee: an event simply has no slot for a prompt,
// world/style guide or vision string, so free text can't be attached by mistake
// (a bare `Record<string, string>` would happily accept it). Every field is a
// literal union (shared with the selector UI via ./options), index, count or
// boolean — never a bare `string`. `never` marks events that carry no payload.
type AnalyticsEventData = {
game_start:
| {
source: "prompt";
gender: Gender;
art_style: ArtStyle;
plot_style: PlotStyle;
pacing: Pacing;
tts: boolean;
has_prompt: boolean;
has_style_ref: boolean;
}
| { source: "curated"; gender: Gender; tts: boolean; card: `${"m" | "f"}${number}` }
| { source: "custom" };
art_style_select: { style: ArtStyle };
style_image_upload: { ok: boolean };
scene_reached: { scene_index: number };
choice_select: {
scene_index: number;
choice_index: number;
kind: "advance-beat" | "change-scene";
};
vision_click: { result: "insert-beat" | "change-scene" };
tts_toggle: { muted: boolean };
fullscreen_toggle: { on: boolean };
play_heartbeat: never;
};
export type AnalyticsEvent = keyof AnalyticsEventData;
// Payload is required for events that define one and forbidden for those typed
// `never` (the conditional rest tuple collapses to `[]`), so `track("game_start")`
// without data and `track("play_heartbeat", {...})` with data are both errors.
export function track<E extends AnalyticsEvent>(
event: E,
...[data]: AnalyticsEventData[E] extends never ? [] : [AnalyticsEventData[E]]
): void {
if (typeof window === "undefined") return;
try {
window.umami?.track(event, data as Record<string, unknown> | undefined);
} catch {
// Analytics must never throw into the app.
}
}