"use client"; import { clientApiBase } from "./api"; const KEY = "ws_owner"; const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; /** Anonymous owner token for watchlists/alerts (phase 1, no accounts). Generated once per browser. */ export function ownerToken(): string { if (typeof window === "undefined") return ""; let t = window.localStorage.getItem(KEY); if (!t || !/^[A-Za-z0-9_-]{16,80}$/.test(t)) { const bytes = new Uint8Array(32); window.crypto.getRandomValues(bytes); t = Array.from(bytes, (b) => ALPHABET[b % ALPHABET.length]).join(""); window.localStorage.setItem(KEY, t); } return t; } export async function ownerFetch(path: string, init: RequestInit = {}): Promise { const res = await fetch(`${clientApiBase()}${path}`, { ...init, headers: { "content-type": "application/json", accept: "application/json", "x-websensor-owner": ownerToken(), ...(init.headers ?? {}) }, }); if (!res.ok) { const body = (await res.json().catch(() => ({}))) as { error?: string }; throw new Error(body.error ?? `HTTP ${res.status}`); } return (await res.json()) as T; } export async function publicFetch(path: string): Promise { const res = await fetch(`${clientApiBase()}${path}`, { headers: { accept: "application/json" } }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return (await res.json()) as T; }