| import { createClient, type Session, type SupabaseClient } from "@supabase/supabase-js"; | |
| export type PlanCard = { | |
| id: string; | |
| name: string; | |
| daily_rewrites: number; | |
| max_words_per_request: number; | |
| daily_word_cap: number; | |
| price_inr_monthly: number; | |
| blurb?: string; | |
| }; | |
| export type AuthConfig = { | |
| enabled: boolean; | |
| supabase_url: string; | |
| supabase_anon_key: string; | |
| session_idle_minutes?: number; | |
| guest?: { | |
| daily_rewrites: number; | |
| max_words_per_request: number; | |
| daily_word_cap: number; | |
| }; | |
| plans?: PlanCard[]; | |
| }; | |
| let client: SupabaseClient | null = null; | |
| let cachedConfig: AuthConfig | null = null; | |
| export async function loadAuthConfig(): Promise<AuthConfig> { | |
| if (cachedConfig) return cachedConfig; | |
| const res = await fetch("/v1/auth/config"); | |
| if (!res.ok) { | |
| cachedConfig = { enabled: false, supabase_url: "", supabase_anon_key: "" }; | |
| return cachedConfig; | |
| } | |
| cachedConfig = (await res.json()) as AuthConfig; | |
| return cachedConfig; | |
| } | |
| export function getCachedAuthConfig(): AuthConfig | null { | |
| return cachedConfig; | |
| } | |
| export function getSupabase(): SupabaseClient | null { | |
| return client; | |
| } | |
| export async function initSupabase(): Promise<AuthConfig> { | |
| const config = await loadAuthConfig(); | |
| if (config.enabled && config.supabase_url && config.supabase_anon_key) { | |
| client = createClient(config.supabase_url, config.supabase_anon_key, { | |
| auth: { | |
| persistSession: true, | |
| autoRefreshToken: true, | |
| detectSessionInUrl: true, | |
| }, | |
| }); | |
| } else { | |
| client = null; | |
| } | |
| return config; | |
| } | |
| export async function getAccessToken(): Promise<string | null> { | |
| if (!client) return null; | |
| const { data } = await client.auth.getSession(); | |
| return data.session?.access_token ?? null; | |
| } | |
| export type { Session }; | |