User: You are an expert code reviewer. Your task is to analyze the provided code files and provide a comprehensive code review. For each file, consider:

1. Code Quality: Assess readability, maintainability, and adherence to best practices
2. Potential Issues: Identify bugs, security vulnerabilities, or performance concerns
3. Suggestions: Provide specific recommendations for improvements

Format your review as follows:
1. Start with a brief overview of all files
2. For each file, provide:
   - A summary of the file's purpose
   - Key findings (both positive and negative)
   - Specific recommendations
3. End with any overall suggestions for the codebase

Your review should be detailed but concise, focusing on the most important aspects of the code.

Files to review:

File: ./src/core/bypasses/vegax.ts
Content:
import { app } from "~/client.js";
import { bypassvip } from "~/core/bypasses/bypassvip.js";
import { stringify } from "querystring";
import { sleep } from "bun";
import { load } from "cheerio";
import { seconds } from "~/core/times.js";

export async function vegax(link: string, isRetry?: boolean) {
  const url = new URL(link);
  const hwid = url.searchParams.get("hwid") || url.searchParams.get("HWID");

  if (!hwid) {
    return {
      status: "error",
      message: "HWID not found in link.",
    };
  }

  let location: string | null = null;
  let retries = 0;
  const maxRetries = 3;

  while (retries < maxRetries) {
    try {
      location = await attemptProceed(hwid);
      break;
    } catch (error) {
      if (error instanceof Error && error.message.includes("Token mismatch")) {
        retries++;
        if (retries >= maxRetries) {
          if (isRetry) {
            return {
              status: "error",
              message: "Max retries reached. Unable to proceed.",
            };
          }
          return await vegax(link, true);
        }
      } else {
        if (isRetry) {
          return {
            status: "error",
            message: "Failed to proceed!",
          };
        }
        return await vegax(link, true);
      }
    }
  }

  if (!location) {
    if (isRetry) {
      return {
        status: "error",
        message: "Failed to get redirect location!",
      };
    }
    return await vegax(link, true);
  }

  let result = await bypassvip(location);

  const sessiontoken1 = new URL(result.result).searchParams.get("sessiontoken");
  if (!sessiontoken1) {
    if (isRetry) {
      return {
        status: "error",
        message: "Failed to get sessiontoken!",
      };
    }
    return await vegax(link, true);
  }

  const proceed: string | null = await attemptProceed(hwid, sessiontoken1);

  result = await bypassvip(proceed!);

  const now = Date.now();
  const clearance = await getClearance();
  const timeTaken = Date.now() - now;

  await sleep(Math.max(0, seconds(6.66) - timeTaken));
  const res = await fetch(result.result, {
    headers: {
      cookie: `cf_clearance=${clearance.clearance}`,
      "user-agent": clearance.userAgent,
    },
  });

  const text = await res.text();

  const $ = load(text);

  const key = $("textarea").text();
  if (key) {
    return {
      status: "success",
      key: key,
    };
  } else {
    if (isRetry) {
      console.log(text);
      return {
        status: "error",
        message: "Failed to scrape key!",
      };
    }
    return await vegax(link, true);
  }

  async function getClearance(isRetry?: boolean) {
    const { data, error } = await app.api.v1.scraper.post({
      url: "https://pandadevelopment.net/getkey?service=vegax&hwid=111",
      cache: true,
      delayBeforeClose: 1000,
      $headers: {
        authorization: `Bearer ${Bun.env.ADMIN_KEY}`,
      },
    });

    if (data?.status !== "success") {
      if (isRetry) {
        throw new Error(data?.error?.message || "Failed to get key");
      }
      return getClearance(true);
    }

    if (!data.result.metadata.cf_clearance) {
      if (isRetry) {
        throw new Error("Failed to bypass Cloudflare!");
      }
      return getClearance(true);
    }

    return {
      clearance: data.result.metadata.cf_clearance,
      userAgent: data.result.metadata.user_agent,
    };
  }
}

async function attemptProceed(hwid: string, sessionToken?: string) {
  const proceedData = {
    hwid,
    service: "vegax",
    mode: "REDIRECT",
    serviceCheckpoints: "2",
    title: "Vega X",
    tier_id: "2",
    numberOfTasks: "1",
    theme: "3",
    background: "",
    token: sessionToken ?? "",
    provider: "linkvertise",
  };

  const proceed = await fetch(
    "https://pandadevelopment.net/getkey/proceed?service=vegax",
    {
      method: "POST",
      headers: {
        "content-type": "application/x-www-form-urlencoded",
        Referer: sessionToken
          ? `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise&sessiontoken=${sessionToken}`
          : `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise`,
      },
      body: stringify(proceedData),
      redirect: "manual",
    }
  );
  const text = await proceed.text();

  if (
    text.includes(
      "Token mismatch, session invalidated!, please refresh this page to go back to main checkpoint"
    )
  ) {
    throw new Error("Token mismatch, session invalidated!");
  }

  const location = proceed.headers.get("location");
  return location;
}



AI: **Overview:**

The provided code consists of a single TypeScript file, `vegax.ts`, located in `./src/core/bypasses/`. This file contains an asynchronous function that processes a given link to bypass certain checkpoints and ultimately retrieve a key. The code involves making HTTP requests, handling retries, parsing HTML content, and managing tokens and session data.

---

**File: `./src/core/bypasses/vegax.ts`**

**Summary of the File's Purpose:**

The `vegax` function is designed to automate the process of navigating through a series of redirects and checkpoints to extract a key associated with the provided link. It interacts with external services, handles errors and retries, and parses responses to manage session tokens and clearance cookies. Helper functions `attemptProceed` and `getClearance` support the main function by handling specific steps in the process.

**Key Findings:**

*Positive Aspects:*

1. **Asynchronous Operations:**
   - The use of `async/await` provides clear and readable asynchronous code flow.
   - Proper management of asynchronous tasks enhances performance and responsiveness.

2. **Error Handling and Retries:**
   - Implementing retries for asynchronous operations improves resiliency against transient failures.
   - Conditional checks and error messages help in debugging and provide user feedback.

3. **Modular Code Structure:**
   - Separation of concerns through helper functions (`attemptProceed`, `getClearance`) enhances maintainability.
   - Encapsulation of specific functionalities allows for easier testing and reuse.

4. **Use of External Libraries:**
   - Libraries like `cheerio` simplify HTML parsing and DOM manipulation.
   - Utility imports like `sleep` and `seconds` improve code readability.

*Negative Aspects:*

1. **Recursive Retry Mechanism:**
   - The retry logic involves recursive calls to `vegax` with the `isRetry` flag, which can lead to a growing call stack and potential stack overflow in extreme cases.
   - Recursive retries can make the control flow complex and harder to debug.

2. **Hardcoded Values:**
   - Values such as `hwid=111` are hardcoded, reducing flexibility and making the code less adaptable to different environments or inputs.
   - Magic numbers (e.g., `seconds(6.66)`) are used without context or explanation.

3. **Inconsistent Error Handling:**
   - The code mixes returning error objects with throwing exceptions, which can lead to inconsistent error propagation.
   - Some errors are handled silently or retried without logging sufficient information.

4. **Deprecated API Usage:**
   - The `querystring.stringify` method is used, which is deprecated; the modern `URLSearchParams` API is preferred.
   - Using outdated methods can lead to compatibility issues and lack of support.

5. **Lack of Input Validation:**
   - Inputs such as `link` and `sessionToken` are used without thorough validation, potentially leading to unexpected errors or security vulnerabilities.
   - Environmental variables like `Bun.env.ADMIN_KEY` are used without checks for their existence.

6. **Console Logging in Production Code:**
   - Use of `console.log` for error output is not ideal for production environments.
   - Logging lacks context and might not be appropriately captured by logging systems.

7. **No Response Status Handling:**
   - HTTP responses are not checked for status codes before processing, risking the handling of unsuccessful requests as if they were successful.
   - Lack of response validation can lead to unhandled exceptions or incorrect data processing.

8. **Insufficient Comments and Documentation:**
   - The code lacks explanatory comments, making it harder for other developers to understand the purpose and flow.
   - Complex logic blocks are not documented, increasing the learning curve for maintenance.

**Specific Recommendations:**

1. **Refactor Retry Logic:**
   - Replace recursive calls with iterative loops or utilize a retry library to manage retries and backoff strategies.
   - Clearly define the maximum retry attempts and implement exponential backoff if necessary.

2. **Remove Hardcoded Values:**
   - Extract hardcoded values like `hwid=111` into configuration files or environment variables.
   - Use constants with descriptive names for magic numbers to provide context.

3. **Standardize Error Handling:**
   - Adopt a consistent error handling approach—either return error objects or throw exceptions, but not both.
   - Implement a global error handler or middleware to manage errors uniformly.

4. **Update to Modern APIs:**
   - Replace `querystring.stringify` with `URLSearchParams` for query parameter serialization.
   - This change enhances readability and aligns with current JavaScript standards.

5. **Implement Input Validation:**
   - Validate and sanitize all inputs, including query parameters and environment variables.
   - Check for the existence of `Bun.env.ADMIN_KEY` and handle cases where it is undefined.

6. **Enhance Logging Practices:**
   - Replace `console.log` with a proper logging library that supports log levels and outputs to appropriate destinations.
   - Include context in log messages to facilitate debugging.

7. **Handle HTTP Response Statuses:**
   - Check the `response.status` of all fetch requests before processing the response body.
   - Throw informative errors or handle specific status codes (e.g., 404, 500) appropriately.

8. **Add Comments and Documentation:**
   - Include comments explaining the purpose of functions, variables, and complex logic sections.
   - Use JSDoc annotations to describe function parameters, return types, and potential errors.

9. **Improve Security Measures:**
   - Ensure sensitive data like `ADMIN_KEY` is securely retrieved and not exposed.
   - Use HTTPS for all network requests to protect data in transit.
   - Implement rate limiting or other protective measures if the function is exposed externally.

10. **Externalize Configuration:**
    - Move URLs, headers, and other configuration data to external config files or environment variables.
    - This practice enhances maintainability and allows for easier updates without modifying code.

---

**Overall Suggestions for the Codebase:**

1. **Adopt Consistent Coding Standards:**
   - Use a linter (e.g., ESLint) with a defined style guide to maintain code consistency across the project.
   - Enforce code formatting with tools like Prettier.

2. **Implement Comprehensive Testing:**
   - Write unit tests for all functions, especially those handling network operations and retries.
   - Use mocking for external services to ensure tests are reliable and do not depend on network availability.

3. **Enhance Error Monitoring:**
   - Integrate an error tracking system (e.g., Sentry) to capture and monitor runtime exceptions.
   - Use structured logging to collect analytics and debug information.

4. **Modularize and Refactor Code:**
   - Break down large functions into smaller, reusable modules.
   - Follow the Single Responsibility Principle to ensure each function or module has a clear purpose.

5. **Stay Updated with Dependencies:**
   - Keep third-party libraries up to date to benefit from performance improvements and security patches.
   - Regularly audit dependencies for known vulnerabilities.

6. **Review Security Practices:**
   - Conduct security assessments or code reviews focused on identifying vulnerabilities.
   - Implement security best practices, such as input validation, output encoding, and secure storage of secrets.

7. **Documentation and Knowledge Sharing:**
   - Maintain updated documentation, including setup instructions, code architecture, and API references.
   - Encourage knowledge sharing among team members through code reviews and collaborative sessions.

8. **Optimize Performance:**
   - Analyze and optimize the performance of network requests.
   - Implement caching strategies where appropriate to reduce redundant network calls.

9. **Plan for Scalability:**
   - Design the codebase with scalability in mind, preparing for increased load or additional features.
   - Use asynchronous queuing or throttling to manage high volumes of requests if necessary.

10. **Continuous Integration and Deployment:**
    - Set up CI/CD pipelines to automate testing, building, and deploying code changes.
    - Ensure that code quality checks are part of the integration process.

---

By addressing these recommendations, the codebase will become more robust, maintainable, and secure. Improving code quality not only facilitates easier maintenance but also enhances the reliability and performance of the application.
User: You are an expert code reviewer. Your task is to analyze the provided code files and provide a comprehensive code review. For each file, consider:

1. Code Quality: Assess readability, maintainability, and adherence to best practices
2. Potential Issues: Identify bugs, security vulnerabilities, or performance concerns
3. Suggestions: Provide specific recommendations for improvements

Format your review as follows:
1. Start with a brief overview of all files
2. For each file, provide:
   - A summary of the file's purpose
   - Key findings (both positive and negative)
   - Specific recommendations
3. End with any overall suggestions for the codebase

Your review should be detailed but concise, focusing on the most important aspects of the code.

Files to review:

File: ./src/core/bypasses/vegax.ts
Content:
import { app } from "~/client.js";
import { bypassvip } from "~/core/bypasses/bypassvip.js";
import { sleep } from "bun";
import { load } from "cheerio";
import { seconds } from "~/core/times.js";
import { logger } from "~/core/logger.js";

export async function vegax(link: string, isRetry?: boolean) {
  try {
    const url = new URL(link);
    const hwid = url.searchParams.get("hwid") || url.searchParams.get("HWID");

    if (!hwid) {
      throw new Error("HWID not found in link.");
    }

    let location: string | null = null;
    let retries = 0;
    const maxRetries = 3;

    // Attempt to proceed with the bypass, retrying up to maxRetries times
    while (retries < maxRetries) {
      try {
        location = await attemptProceed(hwid);
        break;
      } catch (error) {
        if (
          error instanceof Error &&
          error.message.includes("Token mismatch")
        ) {
          retries++;
          if (retries >= maxRetries) {
            throw new Error("Max retries reached. Unable to proceed.");
          }
        } else {
          throw error;
        }
      }
    }

    if (!location) {
      throw new Error("Failed to get redirect location!");
    }

    // Bypass the first Linkvertise link
    let result = await bypassvip(location);

    // Extract the session token from the bypassed URL
    const sessiontoken1 = new URL(result.result).searchParams.get(
      "sessiontoken"
    );
    if (!sessiontoken1) {
      throw new Error("Failed to get sessiontoken!");
    }

    // Attempt to proceed with the new session token
    const proceed: string | null = await attemptProceed(hwid, sessiontoken1);
    if (!proceed) {
      throw new Error("Failed to proceed with session token!");
    }

    // Bypass the second Linkvertise link
    result = await bypassvip(proceed);

    // Get Cloudflare clearance and respect the rate limit
    const now = Date.now();
    const clearance = await getClearance();
    const timeTaken = Date.now() - now;

    // Wait to respect the rate limit (6.66 seconds)
    await sleep(Math.max(0, seconds(6.66) - timeTaken));

    // Fetch the final page with Cloudflare clearance
    const res = await fetch(result.result, {
      headers: {
        cookie: `cf_clearance=${clearance.clearance}`,
        "user-agent": clearance.userAgent,
      },
    });

    const text = await res.text();

    // Parse the HTML and extract the key
    const $ = load(text);

    const key = $("textarea").text();
    if (!key) {
      throw new Error("Failed to scrape key!");
    }

    return {
      status: "success",
      key: key,
    };
  } catch (error) {
    logger.error(
      `Error in vegax: ${
        error instanceof Error ? error.message : "Unknown error"
      }`
    );
    if (!isRetry) {
      return vegax(link, true);
    }
    return {
      status: "error",
      message:
        error instanceof Error ? error.message : "An unknown error occurred.",
    };
  }
}

async function getClearance(
  isRetry?: boolean
): Promise<{ clearance: string; userAgent: string }> {
  try {
    const { data, error } = await app.api.v1.scraper.post({
      url: "https://pandadevelopment.net/getkey?service=vegax&hwid=111",
      cache: true,
      delayBeforeClose: 1000,
      $headers: {
        authorization: `Bearer ${Bun.env.ADMIN_KEY}`,
      },
    });

    if (data?.status !== "success" || !data.result?.metadata?.cf_clearance) {
      throw new Error(
        data?.error?.message || "Failed to get Cloudflare clearance"
      );
    }

    return {
      clearance: data.result.metadata.cf_clearance,
      userAgent: data.result.metadata.user_agent,
    };
  } catch (error) {
    logger.error(
      `Error in getClearance: ${
        error instanceof Error ? error.message : "Unknown error"
      }`
    );
    if (!isRetry) {
      return getClearance(true);
    }
    throw error;
  }
}

async function attemptProceed(
  hwid: string,
  sessionToken?: string
): Promise<string> {
  const proceedData = new URLSearchParams({
    hwid,
    service: "vegax",
    mode: "REDIRECT",
    serviceCheckpoints: "2",
    title: "Vega X",
    tier_id: "2",
    numberOfTasks: "1",
    theme: "3",
    background: "",
    token: sessionToken ?? "",
    provider: "linkvertise",
  });

  const proceed = await fetch(
    "https://pandadevelopment.net/getkey/proceed?service=vegax",
    {
      method: "POST",
      headers: {
        "content-type": "application/x-www-form-urlencoded",
        Referer: sessionToken
          ? `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise&sessiontoken=${sessionToken}`
          : `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise`,
      },
      body: proceedData.toString(),
      redirect: "manual",
    }
  );
  const text = await proceed.text();

  if (text.includes("Token mismatch, session invalidated!")) {
    throw new Error("Token mismatch, session invalidated!");
  }

  const location = proceed.headers.get("location");
  if (!location) {
    throw new Error("Failed to get redirect location");
  }

  return location;
}



PROMPT: User: You are an expert code reviewer. Your task is to analyze the provided code files and provide a comprehensive code review. For each file, consider:

1. Code Quality: Assess readability, maintainability, and adherence to best practices
2. Potential Issues: Identify bugs, security vulnerabilities, or performance concerns
3. Suggestions: Provide specific recommendations for improvements

Format your review as follows:
1. Start with a brief overview of all files
2. For each file, provide:
   - A summary of the file's purpose
   - Key findings (both positive and negative)
   - Specific recommendations
3. End with any overall suggestions for the codebase

Your review should be detailed but concise, focusing on the most important aspects of the code.

Files to review:

File: ./src/core/bypasses/vegax.ts
Content:
import { app } from "~/client.js";
import { bypassvip } from "~/core/bypasses/bypassvip.js";
import { stringify } from "querystring";
import { sleep } from "bun";
import { load } from "cheerio";
import { seconds } from "~/core/times.js";

export async function vegax(link: string, isRetry?: boolean) {
  const url = new URL(link);
  const hwid = url.searchParams.get("hwid") || url.searchParams.get("HWID");

  if (!hwid) {
    return {
      status: "error",
      message: "HWID not found in link.",
    };
  }

  let location: string | null = null;
  let retries = 0;
  const maxRetries = 3;

  while (retries < maxRetries) {
    try {
      location = await attemptProceed(hwid);
      break;
    } catch (error) {
      if (error instanceof Error && error.message.includes("Token mismatch")) {
        retries++;
        if (retries >= maxRetries) {
          if (isRetry) {
            return {
              status: "error",
              message: "Max retries reached. Unable to proceed.",
            };
          }
          return await vegax(link, true);
        }
      } else {
        if (isRetry) {
          return {
            status: "error",
            message: "Failed to proceed!",
          };
        }
        return await vegax(link, true);
      }
    }
  }

  if (!location) {
    if (isRetry) {
      return {
        status: "error",
        message: "Failed to get redirect location!",
      };
    }
    return await vegax(link, true);
  }

  let result = await bypassvip(location);

  const sessiontoken1 = new URL(result.result).searchParams.get("sessiontoken");
  if (!sessiontoken1) {
    if (isRetry) {
      return {
        status: "error",
        message: "Failed to get sessiontoken!",
      };
    }
    return await vegax(link, true);
  }

  const proceed: string | null = await attemptProceed(hwid, sessiontoken1);

  result = await bypassvip(proceed!);

  const now = Date.now();
  const clearance = await getClearance();
  const timeTaken = Date.now() - now;

  await sleep(Math.max(0, seconds(6.66) - timeTaken));
  const res = await fetch(result.result, {
    headers: {
      cookie: `cf_clearance=${clearance.clearance}`,
      "user-agent": clearance.userAgent,
    },
  });

  const text = await res.text();

  const $ = load(text);

  const key = $("textarea").text();
  if (key) {
    return {
      status: "success",
      key: key,
    };
  } else {
    if (isRetry) {
      console.log(text);
      return {
        status: "error",
        message: "Failed to scrape key!",
      };
    }
    return await vegax(link, true);
  }

  async function getClearance(isRetry?: boolean) {
    const { data, error } = await app.api.v1.scraper.post({
      url: "https://pandadevelopment.net/getkey?service=vegax&hwid=111",
      cache: true,
      delayBeforeClose: 1000,
      $headers: {
        authorization: `Bearer ${Bun.env.ADMIN_KEY}`,
      },
    });

    if (data?.status !== "success") {
      if (isRetry) {
        throw new Error(data?.error?.message || "Failed to get key");
      }
      return getClearance(true);
    }

    if (!data.result.metadata.cf_clearance) {
      if (isRetry) {
        throw new Error("Failed to bypass Cloudflare!");
      }
      return getClearance(true);
    }

    return {
      clearance: data.result.metadata.cf_clearance,
      userAgent: data.result.metadata.user_agent,
    };
  }
}

async function attemptProceed(hwid: string, sessionToken?: string) {
  const proceedData = {
    hwid,
    service: "vegax",
    mode: "REDIRECT",
    serviceCheckpoints: "2",
    title: "Vega X",
    tier_id: "2",
    numberOfTasks: "1",
    theme: "3",
    background: "",
    token: sessionToken ?? "",
    provider: "linkvertise",
  };

  const proceed = await fetch(
    "https://pandadevelopment.net/getkey/proceed?service=vegax",
    {
      method: "POST",
      headers: {
        "content-type": "application/x-www-form-urlencoded",
        Referer: sessionToken
          ? `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise&sessiontoken=${sessionToken}`
          : `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise`,
      },
      body: stringify(proceedData),
      redirect: "manual",
    }
  );
  const text = await proceed.text();

  if (
    text.includes(
      "Token mismatch, session invalidated!, please refresh this page to go back to main checkpoint"
    )
  ) {
    throw new Error("Token mismatch, session invalidated!");
  }

  const location = proceed.headers.get("location");
  return location;
}



AI: **Overview:**

The provided code consists of a single TypeScript file, `vegax.ts`, located in `./src/core/bypasses/`. This file contains an asynchronous function that processes a given link to bypass certain checkpoints and ultimately retrieve a key. The code involves making HTTP requests, handling retries, parsing HTML content, and managing tokens and session data.

---

**File: `./src/core/bypasses/vegax.ts`**

**Summary of the File's Purpose:**

The `vegax` function is designed to automate the process of navigating through a series of redirects and checkpoints to extract a key associated with the provided link. It interacts with external services, handles errors and retries, and parses responses to manage session tokens and clearance cookies. Helper functions `attemptProceed` and `getClearance` support the main function by handling specific steps in the process.

**Key Findings:**

*Positive Aspects:*

1. **Asynchronous Operations:**
   - The use of `async/await` provides clear and readable asynchronous code flow.
   - Proper management of asynchronous tasks enhances performance and responsiveness.

2. **Error Handling and Retries:**
   - Implementing retries for asynchronous operations improves resiliency against transient failures.
   - Conditional checks and error messages help in debugging and provide user feedback.

3. **Modular Code Structure:**
   - Separation of concerns through helper functions (`attemptProceed`, `getClearance`) enhances maintainability.
   - Encapsulation of specific functionalities allows for easier testing and reuse.

4. **Use of External Libraries:**
   - Libraries like `cheerio` simplify HTML parsing and DOM manipulation.
   - Utility imports like `sleep` and `seconds` improve code readability.

*Negative Aspects:*

1. **Recursive Retry Mechanism:**
   - The retry logic involves recursive calls to `vegax` with the `isRetry` flag, which can lead to a growing call stack and potential stack overflow in extreme cases.
   - Recursive retries can make the control flow complex and harder to debug.

2. **Hardcoded Values:**
   - Values such as `hwid=111` are hardcoded, reducing flexibility and making the code less adaptable to different environments or inputs.
   - Magic numbers (e.g., `seconds(6.66)`) are used without context or explanation.

3. **Inconsistent Error Handling:**
   - The code mixes returning error objects with throwing exceptions, which can lead to inconsistent error propagation.
   - Some errors are handled silently or retried without logging sufficient information.

4. **Deprecated API Usage:**
   - The `querystring.stringify` method is used, which is deprecated; the modern `URLSearchParams` API is preferred.
   - Using outdated methods can lead to compatibility issues and lack of support.

5. **Lack of Input Validation:**
   - Inputs such as `link` and `sessionToken` are used without thorough validation, potentially leading to unexpected errors or security vulnerabilities.
   - Environmental variables like `Bun.env.ADMIN_KEY` are used without checks for their existence.

6. **Console Logging in Production Code:**
   - Use of `console.log` for error output is not ideal for production environments.
   - Logging lacks context and might not be appropriately captured by logging systems.

7. **No Response Status Handling:**
   - HTTP responses are not checked for status codes before processing, risking the handling of unsuccessful requests as if they were successful.
   - Lack of response validation can lead to unhandled exceptions or incorrect data processing.

8. **Insufficient Comments and Documentation:**
   - The code lacks explanatory comments, making it harder for other developers to understand the purpose and flow.
   - Complex logic blocks are not documented, increasing the learning curve for maintenance.

**Specific Recommendations:**

1. **Refactor Retry Logic:**
   - Replace recursive calls with iterative loops or utilize a retry library to manage retries and backoff strategies.
   - Clearly define the maximum retry attempts and implement exponential backoff if necessary.

2. **Remove Hardcoded Values:**
   - Extract hardcoded values like `hwid=111` into configuration files or environment variables.
   - Use constants with descriptive names for magic numbers to provide context.

3. **Standardize Error Handling:**
   - Adopt a consistent error handling approach—either return error objects or throw exceptions, but not both.
   - Implement a global error handler or middleware to manage errors uniformly.

4. **Update to Modern APIs:**
   - Replace `querystring.stringify` with `URLSearchParams` for query parameter serialization.
   - This change enhances readability and aligns with current JavaScript standards.

5. **Implement Input Validation:**
   - Validate and sanitize all inputs, including query parameters and environment variables.
   - Check for the existence of `Bun.env.ADMIN_KEY` and handle cases where it is undefined.

6. **Enhance Logging Practices:**
   - Replace `console.log` with a proper logging library that supports log levels and outputs to appropriate destinations.
   - Include context in log messages to facilitate debugging.

7. **Handle HTTP Response Statuses:**
   - Check the `response.status` of all fetch requests before processing the response body.
   - Throw informative errors or handle specific status codes (e.g., 404, 500) appropriately.

8. **Add Comments and Documentation:**
   - Include comments explaining the purpose of functions, variables, and complex logic sections.
   - Use JSDoc annotations to describe function parameters, return types, and potential errors.

9. **Improve Security Measures:**
   - Ensure sensitive data like `ADMIN_KEY` is securely retrieved and not exposed.
   - Use HTTPS for all network requests to protect data in transit.
   - Implement rate limiting or other protective measures if the function is exposed externally.

10. **Externalize Configuration:**
    - Move URLs, headers, and other configuration data to external config files or environment variables.
    - This practice enhances maintainability and allows for easier updates without modifying code.

---

**Overall Suggestions for the Codebase:**

1. **Adopt Consistent Coding Standards:**
   - Use a linter (e.g., ESLint) with a defined style guide to maintain code consistency across the project.
   - Enforce code formatting with tools like Prettier.

2. **Implement Comprehensive Testing:**
   - Write unit tests for all functions, especially those handling network operations and retries.
   - Use mocking for external services to ensure tests are reliable and do not depend on network availability.

3. **Enhance Error Monitoring:**
   - Integrate an error tracking system (e.g., Sentry) to capture and monitor runtime exceptions.
   - Use structured logging to collect analytics and debug information.

4. **Modularize and Refactor Code:**
   - Break down large functions into smaller, reusable modules.
   - Follow the Single Responsibility Principle to ensure each function or module has a clear purpose.

5. **Stay Updated with Dependencies:**
   - Keep third-party libraries up to date to benefit from performance improvements and security patches.
   - Regularly audit dependencies for known vulnerabilities.

6. **Review Security Practices:**
   - Conduct security assessments or code reviews focused on identifying vulnerabilities.
   - Implement security best practices, such as input validation, output encoding, and secure storage of secrets.

7. **Documentation and Knowledge Sharing:**
   - Maintain updated documentation, including setup instructions, code architecture, and API references.
   - Encourage knowledge sharing among team members through code reviews and collaborative sessions.

8. **Optimize Performance:**
   - Analyze and optimize the performance of network requests.
   - Implement caching strategies where appropriate to reduce redundant network calls.

9. **Plan for Scalability:**
   - Design the codebase with scalability in mind, preparing for increased load or additional features.
   - Use asynchronous queuing or throttling to manage high volumes of requests if necessary.

10. **Continuous Integration and Deployment:**
    - Set up CI/CD pipelines to automate testing, building, and deploying code changes.
    - Ensure that code quality checks are part of the integration process.

---

By addressing these recommendations, the codebase will become more robust, maintainable, and secure. Improving code quality not only facilitates easier maintenance but also enhances the reliability and performance of the application.
User: You are an expert code reviewer. Your task is to analyze the provided code files and provide a comprehensive code review. For each file, consider:

1. Code Quality: Assess readability, maintainability, and adherence to best practices
2. Potential Issues: Identify bugs, security vulnerabilities, or performance concerns
3. Suggestions: Provide specific recommendations for improvements

Format your review as follows:
1. Start with a brief overview of all files
2. For each file, provide:
   - A summary of the file's purpose
   - Key findings (both positive and negative)
   - Specific recommendations
3. End with any overall suggestions for the codebase

Your review should be detailed but concise, focusing on the most important aspects of the code.

Files to review:

File: ./src/core/bypasses/vegax.ts
Content:
import { app } from "~/client.js";
import { bypassvip } from "~/core/bypasses/bypassvip.js";
import { sleep } from "bun";
import { load } from "cheerio";
import { seconds } from "~/core/times.js";
import { logger } from "~/core/logger.js";

export async function vegax(link: string, isRetry?: boolean) {
  try {
    const url = new URL(link);
    const hwid = url.searchParams.get("hwid") || url.searchParams.get("HWID");

    if (!hwid) {
      throw new Error("HWID not found in link.");
    }

    let location: string | null = null;
    let retries = 0;
    const maxRetries = 3;

    // Attempt to proceed with the bypass, retrying up to maxRetries times
    while (retries < maxRetries) {
      try {
        location = await attemptProceed(hwid);
        break;
      } catch (error) {
        if (
          error instanceof Error &&
          error.message.includes("Token mismatch")
        ) {
          retries++;
          if (retries >= maxRetries) {
            throw new Error("Max retries reached. Unable to proceed.");
          }
        } else {
          throw error;
        }
      }
    }

    if (!location) {
      throw new Error("Failed to get redirect location!");
    }

    // Bypass the first Linkvertise link
    let result = await bypassvip(location);

    // Extract the session token from the bypassed URL
    const sessiontoken1 = new URL(result.result).searchParams.get(
      "sessiontoken"
    );
    if (!sessiontoken1) {
      throw new Error("Failed to get sessiontoken!");
    }

    // Attempt to proceed with the new session token
    const proceed: string | null = await attemptProceed(hwid, sessiontoken1);
    if (!proceed) {
      throw new Error("Failed to proceed with session token!");
    }

    // Bypass the second Linkvertise link
    result = await bypassvip(proceed);

    // Get Cloudflare clearance and respect the rate limit
    const now = Date.now();
    const clearance = await getClearance();
    const timeTaken = Date.now() - now;

    // Wait to respect the rate limit (6.66 seconds)
    await sleep(Math.max(0, seconds(6.66) - timeTaken));

    // Fetch the final page with Cloudflare clearance
    const res = await fetch(result.result, {
      headers: {
        cookie: `cf_clearance=${clearance.clearance}`,
        "user-agent": clearance.userAgent,
      },
    });

    const text = await res.text();

    // Parse the HTML and extract the key
    const $ = load(text);

    const key = $("textarea").text();
    if (!key) {
      throw new Error("Failed to scrape key!");
    }

    return {
      status: "success",
      key: key,
    };
  } catch (error) {
    logger.error(
      `Error in vegax: ${
        error instanceof Error ? error.message : "Unknown error"
      }`
    );
    if (!isRetry) {
      return vegax(link, true);
    }
    return {
      status: "error",
      message:
        error instanceof Error ? error.message : "An unknown error occurred.",
    };
  }
}

async function getClearance(
  isRetry?: boolean
): Promise<{ clearance: string; userAgent: string }> {
  try {
    const { data, error } = await app.api.v1.scraper.post({
      url: "https://pandadevelopment.net/getkey?service=vegax&hwid=111",
      cache: true,
      delayBeforeClose: 1000,
      $headers: {
        authorization: `Bearer ${Bun.env.ADMIN_KEY}`,
      },
    });

    if (data?.status !== "success" || !data.result?.metadata?.cf_clearance) {
      throw new Error(
        data?.error?.message || "Failed to get Cloudflare clearance"
      );
    }

    return {
      clearance: data.result.metadata.cf_clearance,
      userAgent: data.result.metadata.user_agent,
    };
  } catch (error) {
    logger.error(
      `Error in getClearance: ${
        error instanceof Error ? error.message : "Unknown error"
      }`
    );
    if (!isRetry) {
      return getClearance(true);
    }
    throw error;
  }
}

async function attemptProceed(
  hwid: string,
  sessionToken?: string
): Promise<string> {
  const proceedData = new URLSearchParams({
    hwid,
    service: "vegax",
    mode: "REDIRECT",
    serviceCheckpoints: "2",
    title: "Vega X",
    tier_id: "2",
    numberOfTasks: "1",
    theme: "3",
    background: "",
    token: sessionToken ?? "",
    provider: "linkvertise",
  });

  const proceed = await fetch(
    "https://pandadevelopment.net/getkey/proceed?service=vegax",
    {
      method: "POST",
      headers: {
        "content-type": "application/x-www-form-urlencoded",
        Referer: sessionToken
          ? `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise&sessiontoken=${sessionToken}`
          : `https://pandadevelopment.net/getkey?service=vegax&hwid=${hwid}&provider=linkvertise`,
      },
      body: proceedData.toString(),
      redirect: "manual",
    }
  );
  const text = await proceed.text();

  if (text.includes("Token mismatch, session invalidated!")) {
    throw new Error("Token mismatch, session invalidated!");
  }

  const location = proceed.headers.get("location");
  if (!location) {
    throw new Error("Failed to get redirect location");
  }

  return location;
}