|
| 1 | +/** |
| 2 | + * Unique-visitor counter shared by the course sites. |
| 3 | + * |
| 4 | + * The number lives only on the counter service; this module never adds an |
| 5 | + * offset, floor or fallback figure. A browser is counted once, ever: a |
| 6 | + * per-course localStorage flag decides between `hit` (count this browser) and |
| 7 | + * `get` (read only). The cached number is a first-paint placeholder and is |
| 8 | + * always replaced by the server value. |
| 9 | + */ |
| 10 | + |
| 11 | +export const COUNTER_API = 'https://abacus.jasoncameron.dev'; |
| 12 | +export const COUNTER_NAMESPACE = 'alisadeghiaghili.github.io'; |
| 13 | +export const COURSE_SLUG = 'learn-python'; |
| 14 | +export const COUNTER_KEY = `${COURSE_SLUG}-unique-visitors`; |
| 15 | +export const COUNTED_FLAG_KEY = `${COURSE_SLUG}:visitor-counted:v1`; |
| 16 | +export const COUNT_CACHE_KEY = `${COURSE_SLUG}:visitor-count:v2`; |
| 17 | +export const REQUEST_TIMEOUT_MS = 5000; |
| 18 | + |
| 19 | +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>; |
| 20 | +type StorageLike = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>; |
| 21 | + |
| 22 | +export interface VisitorCounterDeps { |
| 23 | + fetch?: FetchLike; |
| 24 | + /** `null` means storage is unavailable; omit to use the browser's localStorage. */ |
| 25 | + storage?: StorageLike | null; |
| 26 | + timeoutMs?: number; |
| 27 | + now?: () => Date; |
| 28 | +} |
| 29 | + |
| 30 | +function defaultStorage(): StorageLike | null { |
| 31 | + try { |
| 32 | + return typeof localStorage === 'undefined' ? null : localStorage; |
| 33 | + } catch { |
| 34 | + return null; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +function isCount(value: unknown): value is number { |
| 39 | + return typeof value === 'number' && Number.isInteger(value) && value >= 0; |
| 40 | +} |
| 41 | + |
| 42 | +/** Call the counter service. Resolves to the count; a 404 on `get` means 0. */ |
| 43 | +async function request( |
| 44 | + action: 'get' | 'hit', |
| 45 | + deps: VisitorCounterDeps, |
| 46 | +): Promise<number> { |
| 47 | + const doFetch = deps.fetch ?? ((input, init) => fetch(input, init)); |
| 48 | + const url = `${COUNTER_API}/${action}/${COUNTER_NAMESPACE}/${COUNTER_KEY}`; |
| 49 | + const controller = new AbortController(); |
| 50 | + const timer = setTimeout(() => controller.abort(), deps.timeoutMs ?? REQUEST_TIMEOUT_MS); |
| 51 | + try { |
| 52 | + const res = await doFetch(url, { cache: 'no-store', signal: controller.signal }); |
| 53 | + if (action === 'get' && res.status === 404) return 0; |
| 54 | + if (!res.ok) throw new Error(`counter ${action} failed: ${res.status}`); |
| 55 | + const body: unknown = await res.json(); |
| 56 | + const value = (body as { value?: unknown } | null)?.value; |
| 57 | + if (!isCount(value)) throw new Error('counter returned an invalid value'); |
| 58 | + return value; |
| 59 | + } finally { |
| 60 | + clearTimeout(timer); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Count this browser if it has not been counted yet, then return the server |
| 66 | + * value, or `null` when the service cannot be reached. |
| 67 | + */ |
| 68 | +export async function resolveVisitorCount(deps: VisitorCounterDeps = {}): Promise<number | null> { |
| 69 | + const storage = deps.storage === undefined ? defaultStorage() : deps.storage; |
| 70 | + const now = deps.now ?? (() => new Date()); |
| 71 | + |
| 72 | + let shouldHit = false; |
| 73 | + if (storage) { |
| 74 | + try { |
| 75 | + if (storage.getItem(COUNTED_FLAG_KEY) === null) { |
| 76 | + storage.setItem(COUNTED_FLAG_KEY, now().toISOString()); |
| 77 | + shouldHit = true; |
| 78 | + } |
| 79 | + } catch { |
| 80 | + shouldHit = false; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + if (shouldHit) { |
| 85 | + try { |
| 86 | + return await request('hit', deps); |
| 87 | + } catch { |
| 88 | + try { |
| 89 | + storage?.removeItem(COUNTED_FLAG_KEY); |
| 90 | + } catch { |
| 91 | + // storage became unavailable; nothing to undo |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + try { |
| 97 | + return await request('get', deps); |
| 98 | + } catch { |
| 99 | + return null; |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +/** The last server value, for the first paint only. */ |
| 104 | +export function readCachedCount(storage: StorageLike | null = defaultStorage()): number | null { |
| 105 | + if (!storage) return null; |
| 106 | + try { |
| 107 | + const raw = storage.getItem(COUNT_CACHE_KEY); |
| 108 | + if (!raw) return null; |
| 109 | + const count = (JSON.parse(raw) as { count?: unknown } | null)?.count; |
| 110 | + return isCount(count) ? count : null; |
| 111 | + } catch { |
| 112 | + return null; |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +function writeCachedCount(storage: StorageLike | null, count: number, now: Date): void { |
| 117 | + if (!storage) return; |
| 118 | + try { |
| 119 | + storage.setItem(COUNT_CACHE_KEY, JSON.stringify({ count, at: now.toISOString() })); |
| 120 | + } catch { |
| 121 | + // cache is optional |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * Show the cached number immediately (if any), then replace it with the server |
| 127 | + * value whenever it arrives, even when that value is lower. |
| 128 | + */ |
| 129 | +export async function startVisitorCounter( |
| 130 | + render: (count: number) => void, |
| 131 | + deps: VisitorCounterDeps = {}, |
| 132 | +): Promise<void> { |
| 133 | + const storage = deps.storage === undefined ? defaultStorage() : deps.storage; |
| 134 | + const cached = readCachedCount(storage); |
| 135 | + if (cached !== null) render(cached); |
| 136 | + |
| 137 | + const count = await resolveVisitorCount({ ...deps, storage }); |
| 138 | + if (count === null) return; |
| 139 | + writeCachedCount(storage, count, (deps.now ?? (() => new Date()))()); |
| 140 | + render(count); |
| 141 | +} |
| 142 | + |
| 143 | +export function formatVisitorCount(count: number, locale = 'en-US'): string { |
| 144 | + return count.toLocaleString(locale); |
| 145 | +} |
0 commit comments