Thoroughly analyze it whole and improve the provided code to make it more robust, efficient, fast, reliable, advance, effective and compliant with Cloudflare Workers' environment limitations.
Make this into a state of art level code. Ensure it always works perfectly in any circumstances in cloudflare worker's environment. Remove any rate limit or unnecessary logging related codes. Send the fully enhanced and working full code.
---
// Configuration
const CONFIG = {
  ALLOWED_ORIGINS: new Set(['*']),
  ALLOWED_TARGET_DOMAINS: new Set(['*']),
  ALLOW_ALL_TARGETS: true,
  BLOCKED_TARGET_HOSTS: new Set(['blocked.example.com']),
  FORWARDED_HEADERS: new Set(['accept', 'accept-language', 'content-type', 'cache-control', 'pragma', 'expires', 'last-modified', 'if-modified-since', 'if-none-match', 'connection', 'keep-alive', 'upgrade-insecure-requests']),
  REMOVED_HEADERS: new Set(['cf-connecting-ip', 'x-forwarded-for', 'x-real-ip', 'forwarded', 'via', 'client-ip', 'true-client-ip', 'proxy-connection', 'proxy-authorization', 'proxy-authenticate', 'x-proxy-id', 'x-proxy-location', 'x-proxy-type', 'x-squid-error', 'x-request-id', 'x-correlation-id', 'te', 'trailers', 'transfer-encoding', 'upgrade', 'cookie', 'authorization', 'set-cookie', 'server']),
  SECURITY_HEADERS: {
    'X-Content-Type-Options': 'nosniff',
    'Referrer-Policy': 'no-referrer',
    'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
    'X-Frame-Options': 'DENY',
    'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'; base-uri 'none';"
  },
  CUSTOM_ERROR_RESPONSES: {
    400: { error: 'Bad Request' },
    403: { error: 'Forbidden' },
    404: { error: 'Not Found' },
    413: { error: 'Payload Too Large' },
    429: { error: 'Too Many Requests' },
    500: { error: 'Internal Server Error' },
    502: { error: 'Bad Gateway' },
    504: { error: 'Gateway Timeout' },
    508: { error: 'Too Many Redirects' }
  },
  CACHE_CONTROL: {
    DEFAULT_MAX_AGE: 0,
    CUSTOM_RULES: {}
  },
  MAX_REQUEST_BODY_SIZE: 5000000,
  TIMEOUT: 29000,
  MAX_REDIRECTS: 5,
  TARGET_URL_HEADER: 'x-target-url',
  TARGET_URL_QUERY_PARAM: 'target',
  RATE_LIMIT: {
    REQUESTS_PER_MINUTE: 60,
    BURST: 10
  }
};

class ProxyError extends Error {
  constructor(message, status) {
    super(message);
    this.name = 'ProxyError';
    this.status = status;
  }
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request, event));
});

async function handleRequest(request, event) {
  try {
    if (request.method === 'OPTIONS') {
      return handlePreflight(request);
    }

    const origin = request.headers.get('Origin');
    if (origin && !isAllowedOrigin(origin)) {
      throw new ProxyError('Forbidden: Origin not allowed', 403);
    }

    if (!await checkRateLimit(request)) {
      throw new ProxyError('Too Many Requests', 429);
    }

    const cacheKey = new URL(request.url);
    const cachedResponse = await caches.default.match(cacheKey);
    if (cachedResponse) {
      return modifyAndReturnResponse(cachedResponse, request);
    }

    return await forwardRequest(request, event, 0);
  } catch (error) {
    return handleError(error, request);
  }
}

function isAllowedOrigin(origin) {
  return CONFIG.ALLOWED_ORIGINS.has(origin.toLowerCase()) || CONFIG.ALLOWED_ORIGINS.has('*');
}

function generateCorsHeaders(request, isPreflight = false) {
  const headers = new Headers();
  const origin = request.headers.get('Origin');
  if (origin && isAllowedOrigin(origin)) {
    headers.set('Access-Control-Allow-Origin', origin);
    headers.set('Access-Control-Allow-Credentials', 'true');
    if (isPreflight) {
      const requestedMethod = request.headers.get('Access-Control-Request-Method') || 'GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH';
      const requestedHeaders = request.headers.get('Access-Control-Request-Headers') || 'Content-Type';
      headers.set('Access-Control-Allow-Methods', requestedMethod);
      headers.set('Access-Control-Allow-Headers', requestedHeaders);
      headers.set('Access-Control-Max-Age', '86400');
    }
    headers.set('Access-Control-Expose-Headers', '*');
    headers.append('Vary', 'Origin');
    if (isPreflight) {
      headers.append('Vary', 'Access-Control-Request-Headers');
      headers.append('Vary', 'Access-Control-Request-Method');
    }
  }
  return headers;
}

function handlePreflight(request) {
  const headers = generateCorsHeaders(request, true);
  return new Response(null, { status: 204, headers });
}

function filterAndForwardHeaders(headers) {
  const result = new Headers();
  for (const [key, value] of headers.entries()) {
    const lowerKey = key.toLowerCase();
    if (CONFIG.FORWARDED_HEADERS.has(lowerKey) && !CONFIG.REMOVED_HEADERS.has(lowerKey)) {
      result.set(key, value);
    }
  }
  return result;
}

function validateTargetUrl(url) {
  let parsedUrl;
  try {
    parsedUrl = new URL(url);
  } catch {
    throw new ProxyError('Bad Request: Invalid target URL', 400);
  }

  const protocol = parsedUrl.protocol.toLowerCase();
  if (!['http:', 'https:'].includes(protocol)) {
    throw new ProxyError('Forbidden: Unsupported protocol', 403);
  }

  const hostname = parsedUrl.hostname.toLowerCase();
  if (CONFIG.BLOCKED_TARGET_HOSTS.has(hostname)) {
    throw new ProxyError('Forbidden: Target host is blocked', 403);
  }

  if (!CONFIG.ALLOW_ALL_TARGETS && !CONFIG.ALLOWED_TARGET_DOMAINS.has(hostname)) {
    throw new ProxyError('Forbidden: Target domain not allowed', 403);
  }

  return parsedUrl;
}

function getTargetUrl(request) {
  const headerTarget = request.headers.get(CONFIG.TARGET_URL_HEADER);
  if (headerTarget) {
    return headerTarget;
  }

  const url = new URL(request.url);
  return url.searchParams.get(CONFIG.TARGET_URL_QUERY_PARAM);
}

async function cacheResponse(cacheKey, response) {
  const cache = caches.default;
  const clonedResponse = response.clone();
  const cacheControl = clonedResponse.headers.get('Cache-Control') || '';
  let maxAge = CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE;

  const responseUrl = new URL(clonedResponse.url);
  const customCacheRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[responseUrl.pathname];
  if (customCacheRule) {
    const matches = customCacheRule.match(/max-age=(\d+)/);
    if (matches && matches[1]) {
      maxAge = parseInt(matches[1], 10);
    }
  }

  if (maxAge > 0) {
    await cache.put(cacheKey, clonedResponse, { expirationTtl: maxAge });
  }
}

function modifyAndReturnResponse(response, request) {
  const corsHeaders = generateCorsHeaders(request);
  const newHeaders = new Headers(response.headers);

  CONFIG.REMOVED_HEADERS.forEach(header => {
    newHeaders.delete(header);
  });

  if (request.headers.get('Origin')) {
    for (const [key, value] of corsHeaders.entries()) {
      newHeaders.set(key, value);
    }
  }

  for (const [key, value] of Object.entries(CONFIG.SECURITY_HEADERS)) {
    newHeaders.set(key, value);
  }

  const responseUrl = new URL(response.url);
  const cacheRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[responseUrl.pathname];
  if (cacheRule) {
    newHeaders.set('Cache-Control', cacheRule);
  } else if (CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE > 0) {
    newHeaders.set('Cache-Control', `public, max-age=${CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE}`);
  } else {
    newHeaders.set('Cache-Control', 'no-store');
  }

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

function handleError(error, request) {
  const status = error instanceof ProxyError ? error.status : 500;
  const errorMessage = CONFIG.CUSTOM_ERROR_RESPONSES[status] ? CONFIG.CUSTOM_ERROR_RESPONSES[status].error : 'An unexpected error occurred';
  const corsHeaders = generateCorsHeaders(request);
  const headers = new Headers({
    'Content-Type': 'application/json',
    ...CONFIG.SECURITY_HEADERS
  });

  if (request.headers.get('Origin')) {
    for (const [key, value] of corsHeaders.entries()) {
      headers.set(key, value);
    }
  }

  const body = JSON.stringify({ error: errorMessage });
  return new Response(body, { status, headers });
}

async function forwardRequest(request, event, redirectCount) {
  if (redirectCount > CONFIG.MAX_REDIRECTS) {
    throw new ProxyError('Too Many Redirects', 508);
  }

  const targetUrl = getTargetUrl(request);
  if (!targetUrl) {
    throw new ProxyError('Bad Request: Missing target URL', 400);
  }

  const parsedTarget = validateTargetUrl(targetUrl);
  const proxiedHeaders = filterAndForwardHeaders(request.headers);
  proxiedHeaders.set('Host', parsedTarget.host);

  const fetchOptions = {
    method: request.method,
    headers: proxiedHeaders,
    redirect: 'manual',
    cf: { requestTimeout: CONFIG.TIMEOUT }
  };

  if (!['GET', 'HEAD'].includes(request.method)) {
    const contentLength = parseInt(request.headers.get('Content-Length') || '0', 10);
    if (isNaN(contentLength) || contentLength > CONFIG.MAX_REQUEST_BODY_SIZE) {
      throw new ProxyError('Payload Too Large', 413);
    }
    fetchOptions.body = request.body;
  }

  let response;
  try {
    response = await fetch(parsedTarget.toString(), fetchOptions);
  } catch (err) {
    if (err instanceof TypeError && err.message.includes('network')) {
      throw new ProxyError('Bad Gateway: Network Error', 502);
    }
    if (err.name === 'AbortError') {
      throw new ProxyError('Gateway Timeout', 504);
    }
    throw new ProxyError('Bad Gateway: Unknown Error', 502);
  }

  if (response.status >= 300 && response.status < 400 && response.headers.has('Location')) {
    const location = response.headers.get('Location');
    if (location) {
      let redirectUrl;
      try {
        redirectUrl = new URL(location, parsedTarget);
      } catch {
        throw new ProxyError('Bad Gateway: Invalid redirect URL', 502);
      }
      if (!isAllowedOrigin(redirectUrl.hostname)) {
        throw new ProxyError('Forbidden: Redirected domain not allowed', 403);
      }
      const newRequest = new Request(redirectUrl.toString(), request);
      return await forwardRequest(newRequest, event, redirectCount + 1);
    }
  }

  const modifiedResponse = modifyAndReturnResponse(response, request);

  if (request.method === 'GET') {
    const cacheKey = new URL(request.url);
    await cacheResponse(cacheKey, modifiedResponse);
  }

  return modifiedResponse;
}

async function checkRateLimit(request) {
  const clientIP = request.headers.get('CF-Connecting-IP');
  const key = `ratelimit:${clientIP}`;
  const { REQUESTS_PER_MINUTE, BURST } = CONFIG.RATE_LIMIT;

  const rateLimitData = await getRateLimitData(key);
  const now = Date.now();
  const windowStart = now - 60000; // 1 minute ago

  let { tokens, lastRequest } = rateLimitData;
  tokens = Math.min(tokens + (now - lastRequest) * (REQUESTS_PER_MINUTE / 60000), BURST);

  if (tokens < 1) {
    return false;
  }

  tokens -= 1;
  await setRateLimitData(key, { tokens, lastRequest: now });
  return true;
}

async function getRateLimitData(key) {
  // This is a placeholder implementation. In a real-world scenario, you would use
  // Cloudflare Workers KV or Durable Objects to store and retrieve rate limit data.
  return { tokens: CONFIG.RATE_LIMIT.BURST, lastRequest: Date.now() - 60000 };
}

async function setRateLimitData(key, data) {
  // This is a placeholder implementation. In a real-world scenario, you would use
  // Cloudflare Workers KV or Durable Objects to store rate limit data.
}