import { useCallback, useEffect, useState } from 'react'; const USER_STORAGE_KEY = 'mcp-webcam-user-id'; const VALID_USER_RE = /^[a-zA-Z0-9._-]{1,48}$/; /** * Extract and sanitize `?user=` from a query string. */ export function getUserFromSearch(search: string): string | null { const params = new URLSearchParams(search); const raw = params.get('user')?.trim(); if (!raw || !VALID_USER_RE.test(raw)) return null; return raw; } /** * Sanitize an arbitrary user/room input string. */ export function sanitizeUserId(input: string): string { const cleaned = input.trim().replace(/[^a-zA-Z0-9._-]/g, '-').slice(0, 48); return cleaned || 'default'; } /** * Generate a short memorable room/user slug (e.g. "room-k4m9ab"). */ export function generateUserId(randomFn: () => number = Math.random): string { const alphabet = 'abcdefghjkmnpqrstuvwxyz23456789'; let suffix = ''; for (let i = 0; i < 6; i++) { suffix += alphabet[Math.floor(randomFn() * alphabet.length)]; } return `room-${suffix}`; } /** * Resolve the active user ID given URL search, stored value, and whether multi-user mode is active. */ export function resolveUserId(opts: { search: string; stored?: string | null; multiUser: boolean; randomFn?: () => number; }): string { const fromUrl = getUserFromSearch(opts.search); if (fromUrl) return fromUrl; if (!opts.multiUser) return 'default'; if (opts.stored && VALID_USER_RE.test(opts.stored) && opts.stored !== 'default') { return opts.stored; } return generateUserId(opts.randomFn); } /** * Build a URL string with `?user=` set (or removed when `user === 'default'`). */ export function buildUserUrl(currentHref: string, user: string): string { const url = new URL(currentHref); if (url.pathname === '/') { url.pathname = '/mcp'; } if (!user || user === 'default') { url.searchParams.delete('user'); } else { url.searchParams.set('user', user); } return url.toString(); } export function useUserId(multiUser: boolean) { const [explicitUser, setExplicitUser] = useState(() => { if (typeof window === 'undefined') return null; return getUserFromSearch(window.location.search); }); const [fallbackMultiUser] = useState(() => { if (typeof window === 'undefined') return generateUserId(); const stored = window.sessionStorage.getItem(USER_STORAGE_KEY); if (stored && VALID_USER_RE.test(stored) && stored !== 'default') { return stored; } return generateUserId(); }); const user = explicitUser ?? (multiUser ? fallbackMultiUser : 'default'); useEffect(() => { if (typeof window === 'undefined') return; try { window.sessionStorage.setItem(USER_STORAGE_KEY, user); } catch { // ignore storage quota errors } if (multiUser || user !== 'default' || window.location.pathname === '/') { const nextUrl = buildUserUrl(window.location.href, user); if (nextUrl !== window.location.href) { window.history.replaceState(null, '', nextUrl); } } }, [user, multiUser]); const setUser = useCallback((nextRaw: string) => { setExplicitUser(sanitizeUserId(nextRaw)); }, []); return { user, setUser }; }