import { createClient } from '@supabase/supabase-js'; import * as fs from 'fs'; import * as path from 'path'; import * as dotenv from 'dotenv'; import { fileURLToPath } from 'url'; // Get the equivalent of __dirname in ESM const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Load environment variables from .env.local in project root, not scripts directory const envLocalPath = path.resolve(process.cwd(), '..', '.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); // Try loading from root directory's .env const envPath = path.resolve(process.cwd(), '..', '.env'); if (fs.existsSync(envPath)) { console.log(`Loading environment from: ${envPath}`); dotenv.config({ path: envPath }); } else { dotenv.config(); // Try loading from default .env } } const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || ''; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || ''; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing Supabase environment variables. Please check your .env file.'); console.error(`NEXT_PUBLIC_SUPABASE_URL: ${supabaseUrl ? '[SET]' : '[MISSING]'}`); console.error(`SUPABASE_SERVICE_ROLE_KEY: ${supabaseServiceKey ? '[SET]' : '[MISSING]'}`); process.exit(1); } async function createAdminRpcFunction() { try { // Create a Supabase client with the service role key const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false, }, }); console.log('Creating RPC function for admin check...'); // Read the SQL file content const sqlFile = path.join(__dirname, 'create-admin-rpc.sql'); const sqlContent = fs.readFileSync(sqlFile, 'utf8'); // Execute the SQL to create the function const { error } = await supabase.rpc('exec_sql', { sql: sqlContent }); if (error) { // If exec_sql RPC doesn't exist, try using raw SQL query instead console.warn('exec_sql RPC not available, attempting direct SQL API...'); console.error('Error with RPC method:', error.message); // Try the REST API for executing SQL directly try { const response = await fetch(`${supabaseUrl}/rest/v1/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}`, 'Prefer': 'return=minimal' } as HeadersInit, body: JSON.stringify({ query: sqlContent }) }); if (!response.ok) { const errorData = await response.json(); throw new Error(`Failed to execute SQL directly: ${JSON.stringify(errorData)}`); } console.log('Successfully created RPC function via direct SQL API'); } catch (fetchError) { console.error('Direct SQL API failed:', fetchError); // As a last resort, output the SQL for manual execution console.log('\n--- SQL for manual execution in Supabase SQL Editor ---'); console.log(sqlContent); console.log('------------------------------------------------------\n'); console.log('Please copy the SQL above and execute it manually in your Supabase SQL Editor.'); } } else { console.log('Successfully created RPC function'); } } catch (error) { console.error('Error creating admin RPC function:', error); process.exit(1); } } // Run the script createAdminRpcFunction();