import { existsSync, readFileSync } from 'fs';
import { resolve } from 'path';
// Simple .env file parser (since dotenv might not be available in bundled version)
function loadEnvFile() {
try {
const envPath = resolve('.env');
if (existsSync(envPath)) {
const envContent = readFileSync(envPath, 'utf8');
const lines = envContent.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#') && trimmed.includes('=')) {
const [key, ...valueParts] = trimmed.split('=');
const value = valueParts.join('=').trim();
if (key && value && !process.env[key]) {
process.env[key] = value;
}
}
}
}
} catch (error) {
// Silently ignore .env loading errors
}
}
// Load environment variables from .env file
loadEnvFile();
interface NangoCredentials {
credentials: {
access_token: string;
refresh_token?: string;
expires_at?: string;
};
connection_id: string;
provider_config_key: string;
[key: string]: any;
}
export function get_connection_credentials(): Promise<NangoCredentials> {
return new Promise((resolve, reject) => {
const connection_id = process.env.NANGO_CONNECTION_ID;
const integration_id = process.env.NANGO_INTEGRATION_ID;
const base_url = process.env.NANGO_BASE_URL;
const secret_key = process.env.NANGO_SECRET_KEY;
if (!connection_id || !integration_id || !base_url || !secret_key) {
reject(new Error('Missing required Nango environment variables: NANGO_CONNECTION_ID, NANGO_INTEGRATION_ID, NANGO_BASE_URL, NANGO_SECRET_KEY'));
return;
}
const url = `${base_url}/connection/${connection_id}`;
const params = new URLSearchParams({
provider_config_key: integration_id,
refresh_token: "true",
});
const headers = {
'Authorization': `Bearer ${secret_key}`,
'Content-Type': 'application/json'
};
fetch(`${url}?${params}`, {
method: 'GET',
headers
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
resolve(data as NangoCredentials);
})
.catch(error => {
reject(error);
});
});
}
export async function get_access_token(): Promise<string> {
const credentials = await get_connection_credentials();
const access_token = credentials.credentials?.access_token;
if (!access_token) {
throw new Error('Access token not found in credentials');
}
return access_token;
}