Spaces:
Sleeping
Sleeping
File size: 5,439 Bytes
bf8b26e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
import { atom } from 'nanostores';
import type { SupabaseUser, SupabaseStats, SupabaseApiKey, SupabaseCredentials } from '~/types/supabase';
export interface SupabaseProject {
id: string;
name: string;
region: string;
organization_id: string;
status: string;
database?: {
host: string;
version: string;
postgres_engine: string;
release_channel: string;
};
created_at: string;
}
export interface SupabaseConnectionState {
user: SupabaseUser | null;
token: string;
stats?: SupabaseStats;
selectedProjectId?: string;
isConnected?: boolean;
project?: SupabaseProject;
credentials?: SupabaseCredentials;
}
const savedConnection = typeof localStorage !== 'undefined' ? localStorage.getItem('supabase_connection') : null;
const savedCredentials = typeof localStorage !== 'undefined' ? localStorage.getItem('supabaseCredentials') : null;
const initialState: SupabaseConnectionState = savedConnection
? JSON.parse(savedConnection)
: {
user: null,
token: '',
stats: undefined,
selectedProjectId: undefined,
isConnected: false,
project: undefined,
};
if (savedCredentials && !initialState.credentials) {
try {
initialState.credentials = JSON.parse(savedCredentials);
} catch (e) {
console.error('Failed to parse saved credentials:', e);
}
}
export const supabaseConnection = atom<SupabaseConnectionState>(initialState);
if (initialState.token && !initialState.stats) {
fetchSupabaseStats(initialState.token).catch(console.error);
}
export const isConnecting = atom(false);
export const isFetchingStats = atom(false);
export const isFetchingApiKeys = atom(false);
export function updateSupabaseConnection(connection: Partial<SupabaseConnectionState>) {
const currentState = supabaseConnection.get();
if (connection.user !== undefined || connection.token !== undefined) {
const newUser = connection.user !== undefined ? connection.user : currentState.user;
const newToken = connection.token !== undefined ? connection.token : currentState.token;
connection.isConnected = !!(newUser && newToken);
}
if (connection.selectedProjectId !== undefined) {
if (connection.selectedProjectId && currentState.stats?.projects) {
const selectedProject = currentState.stats.projects.find(
(project) => project.id === connection.selectedProjectId,
);
if (selectedProject) {
connection.project = selectedProject;
} else {
connection.project = {
id: connection.selectedProjectId,
name: `Project ${connection.selectedProjectId.substring(0, 8)}...`,
region: 'unknown',
organization_id: '',
status: 'active',
created_at: new Date().toISOString(),
};
}
} else if (connection.selectedProjectId === '') {
connection.project = undefined;
connection.credentials = undefined;
}
}
const newState = { ...currentState, ...connection };
supabaseConnection.set(newState);
/*
* Always save the connection state to localStorage to persist across chats
*/
if (connection.user || connection.token || connection.selectedProjectId !== undefined || connection.credentials) {
localStorage.setItem('supabase_connection', JSON.stringify(newState));
if (newState.credentials) {
localStorage.setItem('supabaseCredentials', JSON.stringify(newState.credentials));
} else {
localStorage.removeItem('supabaseCredentials');
}
} else {
localStorage.removeItem('supabase_connection');
localStorage.removeItem('supabaseCredentials');
}
}
export async function fetchSupabaseStats(token: string) {
isFetchingStats.set(true);
try {
// Use the internal API route instead of direct Supabase API call
const response = await fetch('/api/supabase', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
token,
}),
});
if (!response.ok) {
throw new Error('Failed to fetch projects');
}
const data = (await response.json()) as any;
updateSupabaseConnection({
user: data.user,
stats: data.stats,
});
} catch (error) {
console.error('Failed to fetch Supabase stats:', error);
throw error;
} finally {
isFetchingStats.set(false);
}
}
export async function fetchProjectApiKeys(projectId: string, token: string) {
isFetchingApiKeys.set(true);
try {
const response = await fetch('/api/supabase/variables', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
projectId,
token,
}),
});
if (!response.ok) {
throw new Error('Failed to fetch API keys');
}
const data = (await response.json()) as any;
const apiKeys = data.apiKeys;
const anonKey = apiKeys.find((key: SupabaseApiKey) => key.name === 'anon' || key.name === 'public');
if (anonKey) {
const supabaseUrl = `https://${projectId}.supabase.co`;
updateSupabaseConnection({
credentials: {
anonKey: anonKey.api_key,
supabaseUrl,
},
});
return { anonKey: anonKey.api_key, supabaseUrl };
}
return null;
} catch (error) {
console.error('Failed to fetch project API keys:', error);
throw error;
} finally {
isFetchingApiKeys.set(false);
}
}
|