/** 사람 방문 비콘 — 쿠키·식별자를 남기지 않는다. 방문자 구분은 서버가 IP·UA·월로 해시해 한다. */ const ENDPOINT = '/v1/track/view'; /** 운영자가 자기 방문을 빼고 싶을 때 콘솔에서 `localStorage.setItem('web4ai.stats.disabled', '1')`. */ const OPT_OUT_KEY = 'web4ai.stats.disabled'; type Loc = {pathname: string; search: string; hash?: string}; type Store = {getItem(key: string): string | null}; export type VisitPayload = {path: string; referrer: string; utm_source: string}; export function buildVisitPayload(loc: Loc, referrer: string): VisitPayload | null { // 발행 페이지(/s/…)만 센다 — 같은 번들이 /preview 에서도 돈다. if (!loc.pathname.startsWith('/s/')) return null; // 하위 페이지는 HTML 이 따로 없고 해시 탭(#/stay)이다(layouts/*/Frame.tsx). 탭을 빼면 "많이 본 페이지" 가 // 첫 화면 한 줄로 뭉친다. #/ 는 홈, #/ 로 시작하지 않는 해시는 문서 안 앵커라 경로가 아니다. const hash = loc.hash ?? ''; const tab = hash.startsWith('#/') && hash !== '#/' ? hash : ''; const utm = new URLSearchParams(loc.search).get('utm_source') ?? ''; return {path: loc.pathname + tab, referrer, utm_source: utm}; } export function isOptedOut(store: Store | undefined): boolean { try { return store?.getItem(OPT_OUT_KEY) === '1'; } catch { // 사파리 비공개 창 등에서 저장소 접근이 막히면 그냥 센다 — 통계 때문에 페이지가 깨지면 안 된다. return false; } } /** 페이지가 열릴 때, 그리고 탭(#/…)을 옮길 때마다. 실패해도 조용히 지나간다 — 통계가 손님 화면을 막으면 안 된다. */ export function sendVisit(): void { if (typeof window === 'undefined') return; let store: Store | undefined; try { store = window.localStorage; } catch { store = undefined; } if (isOptedOut(store)) return; sendOnce(); window.addEventListener('hashchange', sendOnce); } function sendOnce(): void { const payload = buildVisitPayload(window.location, document.referrer); if (!payload) return; const body = JSON.stringify(payload); // text/plain — sendBeacon 이 프리플라이트 없이 보낼 수 있는 형식이다. const blob = new Blob([body], {type: 'text/plain;charset=UTF-8'}); if (navigator.sendBeacon?.(ENDPOINT, blob)) return; // 전송 실패는 손님에게 보일 일이 아니다 — 결과를 버린다. void fetch(ENDPOINT, {method: 'POST', body, keepalive: true, headers: {'Content-Type': 'text/plain'}}).catch( () => undefined, ); }