Make it better, improve, enhance and optimise it further and ensure it can work perfectly in cloudflare worker  without any issue. Ensure it can handle any issues or errors or edge cases perfect and send the full improved code. -- // Main event listener
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

// Advanced configuration
const config = {
  allowedDomains: ['https://api.abhibhai.com', 'http://localhost:8080'],
  headers: { 'Content-Type': 'application/json' },
  timeout: 10000,
  allowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'],
  forwardHeaders: {
    'Authorization': true,
    'Content-Type': true,
    'User-Agent': true,
    'Accept-Language': true,
    'X-Requested-With': true,
    'If-Modified-Since': true,
    'Cache-Control': true,
  },
  bypassCors: false,
  cacheControl: {
    enabled: true,
    maxAge: 3600,
    staleWhileRevalidate: 86400,
  },
  transformResponse: false,
  logging: {
    level: 'info', // 'debug', 'info', 'warn', 'error'
    includeHeaders: false,
  },
};

const AUTHORIZATION_KEY = 'yuichi1234k';

// Custom error class for better error handling
class ProxyError extends Error {
  constructor(message, status) {
    super(message);
    this.name = 'ProxyError';
    this.status = status;
  }
}

// Main request handler
async function handleRequest(request) {
  const url = new URL(request.url);
  const origin = request.headers.get('Origin');

  try {
    if (request.method === 'OPTIONS') {
      return handlePreflightRequest(request, origin);
    }

    if (request.method === 'POST' && url.pathname === '/modify-config') {
      return handleModifyConfig(request);
    }

    if (request.method === 'GET' && url.pathname === '/config-status') {
      return getConfigStatus(request);
    }

    await validateRequest(request, origin);

    const response = await forwardRequest(request, url);
    return createCorsResponse(response, origin);
  } catch (error) {
    return handleError(error, origin);
  }
}

// Validate incoming request
async function validateRequest(request, origin) {
  if (!isAllowedOrigin(origin)) {
    throw new ProxyError('Unauthorized: Invalid Origin', 403);
  }

  if (!config.allowedMethods.includes(request.method)) {
    throw new ProxyError(`Method Not Allowed: ${request.method}`, 405);
  }
}

// Check if the origin is allowed
function isAllowedOrigin(origin) {
  if (!origin) return true; // Allow requests without origin (e.g., curl)
  return config.allowedDomains.some(domain => {
    if (domain.endsWith('*')) {
      return origin.startsWith(domain.slice(0, -1));
    }
    return origin === domain;
  });
}

// Forward the request to the target server
async function forwardRequest(request, url) {
  const targetUrl = url.pathname.slice(1); // Remove the leading '/' to get the target URL
  const init = {
    method: request.method,
    headers: new Headers(request.headers),
    redirect: 'follow',
  };

  // Remove headers that shouldn't be forwarded
  ['Host', 'CF-Connecting-IP', 'CF-IPCountry', 'CF-RAY', 'CF-Visitor', 'CF-Worker'].forEach(header => {
    init.headers.delete(header);
  });

  // Apply custom headers
  Object.entries(config.headers).forEach(([key, value]) => {
    init.headers.set(key, value);
  });

  // Handle request body
  if (!['GET', 'HEAD'].includes(request.method)) {
    init.body = await request.arrayBuffer();
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), config.timeout);

  try {
    const response = await fetch(targetUrl, { ...init, signal: controller.signal });
    clearTimeout(timeoutId);

    if (!response.ok) {
      throw new ProxyError(`Target server responded with status ${response.status}`, response.status);
    }

    return config.transformResponse ? transformResponse(response) : response;
  } catch (error) {
    if (error.name === 'AbortError') {
      throw new ProxyError('Request timed out', 504);
    }
    throw error;
  }
}

// Transform response if needed
async function transformResponse(response) {
  // Implement any response transformation logic here
  return response;
}

// Create CORS response
function createCorsResponse(response, origin) {
  const corsHeaders = new Headers(response.headers);
  
  if (isAllowedOrigin(origin)) {
    corsHeaders.set('Access-Control-Allow-Origin', origin);
    corsHeaders.set('Access-Control-Allow-Credentials', 'true');
  } else {
    corsHeaders.set('Access-Control-Allow-Origin', '*');
  }

  corsHeaders.set('Access-Control-Allow-Methods', config.allowedMethods.join(', '));
  corsHeaders.set('Access-Control-Allow-Headers', Object.keys(config.forwardHeaders).join(', '));
  corsHeaders.set('Access-Control-Expose-Headers', '*');

  if (config.cacheControl.enabled) {
    corsHeaders.set('Cache-Control', `max-age=${config.cacheControl.maxAge}, stale-while-revalidate=${config.cacheControl.staleWhileRevalidate}`);
  }

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: corsHeaders,
  });
}

// Handle preflight requests
function handlePreflightRequest(request, origin) {
  if (!isAllowedOrigin(origin)) {
    throw new ProxyError('Unauthorized: Invalid Origin', 403);
  }

  const requestHeaders = request.headers.get('Access-Control-Request-Headers');
  const requestMethod = request.headers.get('Access-Control-Request-Method');

  if (!config.allowedMethods.includes(requestMethod)) {
    throw new ProxyError(`Method Not Allowed: ${requestMethod}`, 405);
  }

  const headers = {
    'Access-Control-Allow-Origin': origin,
    'Access-Control-Allow-Methods': config.allowedMethods.join(', '),
    'Access-Control-Allow-Headers': requestHeaders || Object.keys(config.forwardHeaders).join(', '),
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Max-Age': '86400',
  };

  return new Response(null, {
    status: 204,
    headers: headers,
  });
}

// Handle config modification
async function handleModifyConfig(request) {
  const authKey = request.headers.get('Authorization');
  if (authKey !== AUTHORIZATION_KEY) {
    throw new ProxyError('Unauthorized: Invalid Authorization Key', 403);
  }

  const body = await request.json();
  updateConfig(body);
  return new Response(JSON.stringify({ success: true, fullConfig: getPublicConfig() }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
}

// Update configuration
function updateConfig(body) {
  Object.keys(config).forEach(key => {
    if (body.hasOwnProperty(key)) {
      if (typeof config[key] === 'object' && !Array.isArray(config[key])) {
        config[key] = { ...config[key], ...body[key] };
      } else {
        config[key] = body[key];
      }
    }
  });
}

// Get config status
function getConfigStatus(request) {
  const authKey = request.headers.get('Authorization');
  if (authKey !== AUTHORIZATION_KEY) {
    throw new ProxyError('Unauthorized: Invalid Authorization Key', 403);
  }

  return new Response(JSON.stringify(getPublicConfig()), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
}

// Get public config (excluding sensitive information)
function getPublicConfig() {
  const { headers, ...publicConfig } = config;
  return publicConfig;
}

// Handle errors
function handleError(error, origin) {
  const status = error instanceof ProxyError ? error.status : 500;
  const message = config.logging.level === 'debug' ? error.stack : error.message;

  logError(error);

  const headers = {
    'Content-Type': 'application/json',
  };

  if (isAllowedOrigin(origin)) {
    headers['Access-Control-Allow-Origin'] = origin;
    headers['Access-Control-Allow-Credentials'] = 'true';
  } else {
    headers['Access-Control-Allow-Origin'] = '*';
  }

  return new Response(JSON.stringify({ error: message }), {
    status: status,
    headers: headers,
  });
}

// Logging function
function logError(error) {
  const logLevel = config.logging.level;
  const logLevels = ['debug', 'info', 'warn', 'error'];
  
  if (logLevels.indexOf(logLevel) <= logLevels.indexOf('error')) {
    console.error('Proxy Error:', error.message);
    if (logLevel === 'debug') {
      console.error(error.stack);
    }
  }
}