File size: 2,025 Bytes
2f8496d
aaa634c
2f8496d
aaa634c
60290e5
 
 
 
 
 
 
 
2f8496d
a95fdd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60290e5
 
 
 
 
 
 
 
 
 
2f8496d
60290e5
2f8496d
 
e366a46
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
import { createClient, SupabaseClient } from '@supabase/supabase-js';

let supabaseInstance: SupabaseClient | null = null;

export function initializeSupabase(url: string, key: string) {
  if (url && key) {
    supabaseInstance = createClient(url, key);
  }
}

// Proxy wrapper that delegates all calls to the dynamically initialized instance
export const supabase = new Proxy({} as any, {
  get(_target, prop) {
    if (prop === 'auth' && localStorage.getItem('algospaced_sandbox_mode') === 'true') {
      const mockSession = {
        access_token: 'sandbox',
        user: {
          id: 'sandbox-user-id',
          email: 'sandbox@algospaced.io',
          email_confirmed_at: new Date().toISOString(),
          last_sign_in_at: new Date().toISOString(),
          role: 'authenticated',
          aud: 'authenticated',
        }
      };
      return {
        getSession: async () => ({ data: { session: mockSession }, error: null }),
        getUser: async () => ({ data: { user: mockSession.user }, error: null }),
        onAuthStateChange: (callback: any) => {
          setTimeout(() => callback('SIGNED_IN', mockSession), 0);
          return {
            data: {
              subscription: {
                unsubscribe: () => {}
              }
            }
          };
        },
        signOut: async () => {
          localStorage.removeItem('algospaced_sandbox_mode');
          window.location.reload();
          return { error: null };
        }
      };
    }

    if (!supabaseInstance) {
      // Fallback: try loading from build-time environment if not initialized yet
      const url = import.meta.env.VITE_SUPABASE_URL || '';
      const key = import.meta.env.VITE_SUPABASE_ANON_KEY || '';
      if (url && key) {
        supabaseInstance = createClient(url, key);
      } else {
        throw new Error("Supabase client is not initialized. Please call initializeSupabase(url, key) first.");
      }
    }
    return (supabaseInstance as any)[prop];
  }
}) as unknown as SupabaseClient;