/** * Payload API Client Singleton * Manages single instance of Payload client with proper error handling */ import type { PayloadConfig } from './types/config.js'; import { getPayloadConfig } from './types/config.js'; // We'll dynamically import the Payload SDK from the published package let payloadClient: any = null; export async function getPayloadClient() { if (payloadClient) { return payloadClient; } try { const config = getPayloadConfig(); // Dynamic import of PayloadAPI from published package const PayloadModule = await import('@mcp-forge/payload-api') as any; const PayloadAPI = PayloadModule.default || PayloadModule; payloadClient = new PayloadAPI({ baseURL: config.baseURL, apiToken: config.apiToken, timeout: config.timeout, maxRetries: config.maxRetries, }); return payloadClient; } catch (error: any) { throw new Error( `Failed to initialize Payload client: ${error.message}. ` + `Ensure PAYLOAD_API_URL and PAYLOAD_API_TOKEN are set in your environment.` ); } } export async function testConnection(): Promise { try { const client = await getPayloadClient(); // Simple test - try to get current user or list something await client.users.retrieveCurrent(); return true; } catch (error: any) { if (error.status === 401) { throw new Error( 'Authentication failed. Check that PAYLOAD_API_TOKEN is valid. ' + 'Token may have expired or been revoked.' ); } throw error; } }