Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

All 1.3 #225

Open
wants to merge 487 commits into
base: main
Choose a base branch
from
Open

All 1.3 #225

wants to merge 487 commits into from

Conversation

gouravmore
Copy link
Member

@gouravmore gouravmore commented Dec 2, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new configuration file for code reviews and automated processes.
    • Added a comprehensive list of offensive words for language filtering.
    • New login page component for user authentication.
    • Implemented multiple new GitHub Actions workflows for automated deployment.
    • Introduced a custom hook for audio detection.
  • Improvements

    • Enhanced error handling and state management across various components.
    • Streamlined API calls using environment variables and centralized URL constants.
    • Improved user interface with new dialog components and responsive design.
  • Bug Fixes

    • Updated routing logic to enforce authentication on several routes.
    • Fixed issues with audio playback and state management in components.
  • Styling

    • Added new CSS styles for the login page and improved header styles.

gouravmore and others added 30 commits June 19, 2024 17:50
Task #217402 fix: Husky Implementation and Integration in React
Issue #219845: deployment automation for all
Issue #219845 fix: all automation for test-rig instances
Issue #219845 fix: branch update for test-rig prod
Issueid #221626 fix: Implement AuthGuard for Route Protection in React
IssueId #223082 feat: Create Log Out Button in Test-Rig [React]
IssueId #223082 feat: Create Log Out Button in Test-Rig [React]
ajinkyapandetekdi and others added 26 commits November 15, 2024 10:58
IssueId #0000 fix send message through queryparams to  iframe
Issueid #0000 feat: help video play button through iframe added
Issueid #231004 feat:play youtube help video in mylearning iframe
#0000 updated origin variable in yml file
Copy link

coderabbitai bot commented Dec 2, 2024

Walkthrough

This pull request introduces several significant changes, including the addition of a new configuration file .coderabbit.yaml for code reviews and automated processes, updates to environment variables in the .env file, and multiple new GitHub Actions workflow files for deployment processes. It also includes new components, updates to existing components for improved functionality, and the introduction of utility functions for bad word filtering. Additionally, various modifications are made to enhance the overall structure, maintainability, and user experience across the application.

Changes

File Path Change Summary
.coderabbit.yaml New configuration file for code reviews and automated processes, specifying settings and instructions.
.env Updated REACT_APP_LEARNER_AI_APP_HOST and added REACT_APP_LEARNER_AI_ORCHESTRATION_HOST.
.github/workflows/all-app-sandbox.yml New workflow for automating deployment on the test branch.
.github/workflows/all-dev-rig.yml New workflow for deployment triggered by pushes to the all-1.2 branch.
.github/workflows/all-dev-tn-new.yml New workflow for deployment on the all-1.3-tn-dev-hotfix branch.
.github/workflows/all-dev-tn.yml New workflow for deployment on the all-1.2-tn-dev branch.
.github/workflows/all-prod-rig.yml New workflow for production deployment on the test-rig-1.1-prod branch.
.github/workflows/all-prod-tn.yml New workflow for deployment on the all-1.3-tn-prod-hotfix branch.
.github/workflows/all-staging-tn.yml New workflow for deployment on the all-1.3-tn-staging-hotfix branch.
.gitignore Added entries to ignore environment variables, build artifacts, and cache directories.
.husky/.gitignore Added entry to ignore files matching _.
.husky/pre-commit New pre-commit hook script to run linting tasks.
.prettierrc New configuration file specifying formatting options for Prettier.
eslintrc.json New ESLint configuration file with rules and settings for JavaScript and React.
package.json Added dependencies and scripts for linting, formatting, and pre-commit hooks.
prettierignore.txt New file specifying files and directories to ignore during formatting.
src/App.js Modifications to manage state and side effects with hooks, improving clarity.
src/Badwords/badWords.json New JSON file containing a list of offensive words categorized by language.
src/components/Assesment/Assesment.jsx Significant updates including new imports, state management, and API calls.
src/components/AssesmentEnd/AssesmentEnd.jsx Updates to API calls and session ID management.
src/components/DiscoverEnd/DiscoverEnd.jsx Modifications to API endpoint management and navigation handling.
src/components/DiscoverSentance/DiscoverSentance.jsx Changes in state management and messaging logic.
src/components/Layouts.jsx/MainLayout.jsx Updates to props, audio playback logic, and rendering conditions.
src/components/Mechanism/WordsOrImage.jsx Added new props and state management features.
src/components/Practice/Mechanics1.jsx Removed unused imports while maintaining the overall structure.
src/components/Practice/Mechanics3.jsx Updates to props, state management, and rendering logic for improved interactivity.
src/components/Practice/Mechanics4.jsx Refined word handling logic and updated equality checks.
src/components/Practice/Mechanics5.jsx Comprehensive refactor to enhance functionality and interactivity.
src/components/Practice/Mechanics6.jsx New component for interactive audio and fill-in-the-blank exercises.
src/config/awsS3.js Changes to import formatting and export of S3Client.
src/index.css Modifications to CSS classes for success and failure headers.
src/routes/index.js Updates to route declarations and authentication requirements.
src/services/callTelemetryIntract.js Removal of unused React import.
src/services/telementryService.js Enhancements to telemetry logging and data structure.
src/services/telemetryService.js Updates to initialization and event handling logic.
src/services/utilService.js Removal of unused React import.
src/store/sagas/handlers/user.handler.js Streamlined OTP verification handling.
src/utils/AudioCompare.js Refactor from class to functional component for audio recording.
src/utils/Badwords.js New utility functions for detecting and filtering bad words.
src/utils/RecordVoiceVisualizer.jsx Changes to use className for compatibility with React.
src/utils/VoiceAnalyser.js Enhancements to audio playback management and error handling.
src/utils/constants.js Updates to comparison logic and addition of new utility functions.
src/utils/urlConstants.json New file containing API endpoint constants.
src/utils/useAudioDetection.jsx New custom hook for audio detection using the Web Audio API.
src/views/AppContent/AppContent.jsx Changes to how virtualId is retrieved and navigation logic.
src/views/HomePage/HomePage.jsx Removal of navigation logic related to useNavigate.
src/views/LoginPage/LoginPage.css New CSS file for styling the login page layout.
src/views/LoginPage/LoginPage.jsx New functional component for user login, including form handling and validation.
src/views/LoginPage/index.jsx Export statement for LoginPage component.
src/views/Practice/Practice.jsx Updates to state management and logic for handling user interactions.
src/views/PracticeRedirectPage/PracticeRedirectPage.jsx New component for redirecting to the practice route.
src/views/PracticeRedirectPage/index.js Export statement for PracticeRedirectPage component.
src/views/index.js Updates to export statements for new components.

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/App.js

Oops! Something went wrong! :(

ESLint: 7.32.0

ESLint couldn't find the config "react-app" to extend from. Please check that the name of the config is correct.

The config "react-app" was referenced from the config file in "/package.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

sonarcloud bot commented Dec 2, 2024

Quality Gate Failed Quality Gate failed

Failed conditions
2 Security Hotspots
D Security Rating on New Code (required ≥ A)
C Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

const handleProfileBack = () => {
try {
if (process.env.REACT_APP_IS_APP_IFRAME === "true") {
window.parent.postMessage({ type: "restore-iframe-content" }, "*");

Check failure

Code scanning / SonarCloud

Origins should be verified during cross-origin communications High

Specify a target origin for this message. See more on SonarQube Cloud
// go_to_result(voiceText);
setVoiceText("");
}
//eslint-disable-next-line
}, [voiceText]);

const send = (score) => {
if (process.env.REACT_APP_IS_APP_IFRAME === "true") {
window.parent.postMessage(

Check failure

Code scanning / SonarCloud

Origins should be verified during cross-origin communications High

Specify a target origin for this message. See more on SonarQube Cloud
// go_to_result(voiceText);
setVoiceText("");
}
//eslint-disable-next-line
}, [voiceText]);

const send = (score) => {
if (process.env.REACT_APP_IS_APP_IFRAME === "true") {
window.parent.postMessage(

Check failure

Code scanning / SonarCloud

Origins should be verified during cross-origin communications High

Specify a target origin for this message. See more on SonarQube Cloud
"mechanic_1")
? 500
: stringLengths[0];
window.parent.postMessage({ type: "stringLengths", length }, "*");

Check failure

Code scanning / SonarCloud

Origins should be verified during cross-origin communications High

Specify a target origin for this message. See more on SonarQube Cloud
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

🛑 Comments failed to post (83)
.github/workflows/all-app-sandbox.yml (5)

14-16: ⚠️ Potential issue

Update GitHub Actions to latest versions

The workflow uses outdated versions of GitHub Actions:

  • actions/checkout@v2 should be updated to @v4
  • actions/setup-node@v3 should be updated to @v4

Apply this diff to update the actions:

-        uses: actions/checkout@v2
+        uses: actions/checkout@v4

-        uses: actions/setup-node@v3
+        uses: actions/setup-node@v4

Also applies to: 17-20

🧰 Tools
🪛 actionlint (1.7.4)

15-15: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


78-79: ⚠️ Potential issue

Security: Remove AWS credentials from build environment

AWS credentials should not be exposed as build environment variables as they could potentially leak into build logs. These credentials are only needed for the deployment step.

Remove these lines and use AWS credentials only in the deployment steps where needed.


83-83: ⚠️ Potential issue

Address build warnings instead of disabling CI

Setting CI=false to bypass warnings is not recommended as it might hide potential issues.

Instead of disabling CI:

  1. Address the build warnings
  2. Remove the CI=false flag

89-94: ⚠️ Potential issue

Remove debug step printing sensitive information

The debug step could potentially leak sensitive information to the logs. If debugging is necessary, ensure sensitive values are masked.

Remove this step or modify it to only print non-sensitive information.


86-88: 🛠️ Refactor suggestion

Use environment variables for S3 bucket path

The S3 bucket path is hardcoded. This could cause issues when deploying to different environments.

Use environment variables instead:

-        run: aws s3 sync ./build s3://sb-all-appliance/all-automation/
+        run: aws s3 sync ./build s3://${{ vars.AWS_S3_BUCKET_PATH }}/
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Deploy to S3 Bucket
        run: aws s3 sync ./build s3://${{ vars.AWS_S3_BUCKET_PATH }}/
src/components/Mechanism/WordsOrImage.jsx (2)

76-78: ⚠️ Potential issue

Fix incorrect useEffect dependency

The useEffect hook calls updateStoredData() without parameters whenever handleNext changes, which will add undefined entries to storedData.

Remove this useEffect or update it with proper dependencies and conditions:

-useEffect(() => {
-  updateStoredData();
-}, [handleNext]);

327-334: 🛠️ Refactor suggestion

Improve PropTypes specificity

Several props are using PropTypes.any which defeats the purpose of type checking:

  • type should be an enum of possible values ('image', 'phonics', etc.)
  • words should be a string or array of strings
  • contentId should have a specific type
  • level should be a number or string

Example improvement:

-  type: PropTypes.any,
-  words: PropTypes.any,
+  type: PropTypes.oneOf(['image', 'phonics', 'text']).isRequired,
+  words: PropTypes.oneOfType([
+    PropTypes.string,
+    PropTypes.arrayOf(PropTypes.string)
+  ]),

Committable suggestion skipped: line range outside the PR's diff.

src/components/Practice/Mechanics4.jsx (1)

214-220: ⚠️ Potential issue

Add key prop to mapped elements

React requires a unique key prop for elements in an array to optimize rendering and maintain component state correctly.

 {selectedWords?.map((elem) => (
   <span
+    key={elem}
     onClick={() => handleWords(elem, true)}
     className={
       answer === "wrong"
         ? `audioSelectedWrongWord ${shake ? "shakeImage" : ""}`
         : ""
     }

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 214-251: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

src/App.js (2)

16-73: 💡 Codebase verification

⚠️ Potential issue

Add comprehensive error handling and secure storage for sensitive data

The verification reveals several security and reliability concerns:

  • Multiple instances of storing sensitive data (tokens, session IDs, user IDs) in localStorage without encryption
  • Lack of error handling when parsing JSON data from localStorage (e.g., fpDetails_v2, accessToken)
  • Inconsistent error handling across the codebase for localStorage operations

Key locations requiring attention:

  • src/store/sagas/handlers/user.handler.js: Unprotected JSON.parse of tokens
  • src/services/telementryService.js: Unhandled JWT token access
  • src/App.js: Device fingerprinting storage without encryption
  • src/components/Assesment/Assesment.jsx: Multiple unprotected localStorage operations
🔗 Analysis chain

Add error handling for fingerprinting and telemetry initialization

The initialization logic lacks proper error handling which could lead to silent failures. Consider implementing proper error boundaries and logging.

 useEffect(() => {
   const initService = async () => {
     var did;
-    if (localStorage.getItem("fpDetails_v2") !== null) {
-      let fpDetails_v2 = localStorage.getItem("fpDetails_v2");
-      did = fpDetails_v2.result;
-    } else {
-      did = localStorage.getItem("did");
+    try {
+      if (localStorage.getItem("fpDetails_v2") !== null) {
+        let fpDetails_v2 = JSON.parse(localStorage.getItem("fpDetails_v2"));
+        did = fpDetails_v2.result;
+      } else {
+        did = localStorage.getItem("did");
+      }
+    } catch (error) {
+      console.error("Error retrieving device ID:", error);
+      did = "anonymous";
     }

     await initialize({

Let's verify the usage of sensitive data storage:


Let me verify the usage of sensitive data storage by checking how the stored values are retrieved and used.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other instances of storing sensitive data in localStorage
rg "localStorage.setItem" -A 2

Length of output: 5039


Script:

#!/bin/bash
# Search for localStorage.getItem patterns to understand data usage
rg "localStorage.getItem" -A 2

# Search for error handling patterns around localStorage
rg "try.*catch.*localStorage" -A 5

Length of output: 11438


75-96: ⚠️ Potential issue

Enhance security for sensitive parameter handling

The current implementation stores sensitive data (token, virtualId) in localStorage without proper validation or secure storage methods.

  1. Add parameter validation
  2. Consider using sessionStorage for temporary tokens
  3. Implement secure storage methods
 useEffect(() => {
   let virtualId;
+  const validateParam = (param) => {
+    // Add appropriate validation logic
+    return param && param.length < 100 && /^[a-zA-Z0-9_-]+$/.test(param);
+  };

   if (getParameter("virtualId", window.location.search)) {
     virtualId = getParameter("virtualId", window.location.search);
+    if (!validateParam(virtualId)) {
+      console.error("Invalid virtualId parameter");
+      return;
+    }
   } else {
     virtualId = localStorage.getItem("virtualId");
   }
   localStorage.setItem("virtualId", virtualId);

   const contentSessionId = getParameter(
     "contentSessionId",
     window.location.search
   );
   if (contentSessionId) {
+    if (!validateParam(contentSessionId)) {
+      console.error("Invalid contentSessionId parameter");
+      return;
+    }
     localStorage.setItem("contentSessionId", contentSessionId);
   }
   const token = getParameter("token", window.location.search);
   if (token) {
+    if (!validateParam(token)) {
+      console.error("Invalid token parameter");
+      return;
+    }
-    localStorage.setItem("token", token);
+    sessionStorage.setItem("token", token);
   }
 }, []);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  useEffect(() => {
    let virtualId;
    const validateParam = (param) => {
      // Add appropriate validation logic
      return param && param.length < 100 && /^[a-zA-Z0-9_-]+$/.test(param);
    };

    if (getParameter("virtualId", window.location.search)) {
      virtualId = getParameter("virtualId", window.location.search);
      if (!validateParam(virtualId)) {
        console.error("Invalid virtualId parameter");
        return;
      }
    } else {
      virtualId = localStorage.getItem("virtualId");
    }
    localStorage.setItem("virtualId", virtualId);

    const contentSessionId = getParameter(
      "contentSessionId",
      window.location.search
    );
    if (contentSessionId) {
      if (!validateParam(contentSessionId)) {
        console.error("Invalid contentSessionId parameter");
        return;
      }
      localStorage.setItem("contentSessionId", contentSessionId);
    }
    const token = getParameter("token", window.location.search);
    if (token) {
      if (!validateParam(token)) {
        console.error("Invalid token parameter");
        return;
      }
      sessionStorage.setItem("token", token);
    }
  }, []);
.github/workflows/all-dev-rig.yml (7)

78-79: ⚠️ Potential issue

Remove AWS credentials from build environment.

AWS credentials should not be exposed as build environment variables. They should only be used during the deployment step.

Remove these lines as they pose a security risk and are redundant with the AWS credentials configuration step.


83-83: ⚠️ Potential issue

Avoid bypassing CI warnings.

Setting CI=false bypasses treating warnings as errors, which could hide potential issues. Instead, address the underlying warnings properly.

Remove this line and fix any build warnings that occur.


89-94: ⚠️ Potential issue

Remove debug statement exposing sensitive information.

The debug step could potentially expose sensitive information in the workflow logs.

Remove this debug step or ensure it only logs non-sensitive information.


14-15: 🛠️ Refactor suggestion

Update checkout action to latest version.

The checkout action version v2 is outdated. Update to the latest version for improved security and features.

-        uses: actions/checkout@v2
+        uses: actions/checkout@v4
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Checkout code
        uses: actions/checkout@v4
🧰 Tools
🪛 actionlint (1.7.4)

15-15: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


86-88: 🛠️ Refactor suggestion

Parameterize S3 bucket name.

The S3 bucket name is hardcoded. This should be parameterized using environment variables or secrets for better maintainability and security.

-        run: aws s3 sync ./build s3://sballappliance/
+        run: aws s3 sync ./build "s3://${{ vars.AWS_S3_BUCKET_NAME }}/"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Deploy to S3 Bucket
        run: aws s3 sync ./build "s3://${{ vars.AWS_S3_BUCKET_NAME }}/"


27-32: 🛠️ Refactor suggestion

Consider using official AWS credentials action.

Replace the manual AWS credentials configuration with the official aws-actions/configure-aws-credentials action for better security and maintainability.

-      - name: Configure AWS credentials
-        run: |
-          aws configure set aws_access_key_id ${{ secrets.AWS_ACCESS_KEY_ID }}
-          aws configure set aws_secret_access_key ${{ secrets.AWS_SECRET_ACCESS_KEY }}
-          aws configure set default.region ${{ secrets.AWS_REGION }}
+      - name: Configure AWS Credentials
+        uses: aws-actions/configure-aws-credentials@v4
+        with:
+          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
+          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+          aws-region: ${{ secrets.AWS_REGION }}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_REGION }}

33-39: ⚠️ Potential issue

Reconsider dependency management approach.

The current approach of removing package-lock.json and using --legacy-peer-deps could lead to inconsistent builds and potential issues:

  1. Removing package-lock.json loses the benefit of deterministic installations
  2. --legacy-peer-deps bypasses peer dependency checks which could mask compatibility issues

Consider:

  1. Keeping package-lock.json under version control
  2. Resolving peer dependency conflicts properly instead of bypassing them
  3. Using npm ci for more reliable builds
-      - name: Clean up node_modules and package-lock.json
-        run: |
-          rm -rf node_modules
-          rm -f package-lock.json
-
-      - name: Install Dependencies
-        run: npm install --legacy-peer-deps
+      - name: Clean Install Dependencies
+        run: npm ci
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Clean Install Dependencies
        run: npm ci
src/config/awsS3.js (3)

3-9: 🛠️ Refactor suggestion

Add error handling for S3Client initialization.

The S3Client initialization should be wrapped in a try-catch block to handle potential configuration errors gracefully.

Consider implementing error handling:

+try {
   export default new S3Client({
     region: process.env.REACT_APP_AWS_S3_REGION,
     credentials: {
       accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
       secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY,
     },
   });
+} catch (error) {
+  console.error('Failed to initialize S3 client:', error);
+  throw error;
+}

Committable suggestion skipped: line range outside the PR's diff.


3-9: ⚠️ Potential issue

Add environment variable validation to prevent runtime errors.

The S3Client configuration relies on environment variables without validation. Missing or undefined variables could cause runtime errors.

Consider adding validation before initializing the client:

+const validateConfig = () => {
+  const required = [
+    'REACT_APP_AWS_S3_REGION',
+    'REACT_APP_AWS_ACCESS_KEY_ID',
+    'REACT_APP_AWS_SECRET_ACCESS_KEY'
+  ];
+  const missing = required.filter(key => !process.env[key]);
+  if (missing.length) {
+    throw new Error(`Missing required AWS configuration: ${missing.join(', ')}`);
+  }
+};
+
+validateConfig();
+
 export default new S3Client({
   region: process.env.REACT_APP_AWS_S3_REGION,
   credentials: {
     accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
     secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY,
   },
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const validateConfig = () => {
  const required = [
    'REACT_APP_AWS_S3_REGION',
    'REACT_APP_AWS_ACCESS_KEY_ID',
    'REACT_APP_AWS_SECRET_ACCESS_KEY'
  ];
  const missing = required.filter(key => !process.env[key]);
  if (missing.length) {
    throw new Error(`Missing required AWS configuration: ${missing.join(', ')}`);
  }
};

validateConfig();

export default new S3Client({
  region: process.env.REACT_APP_AWS_S3_REGION,
  credentials: {
    accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY,
  },
});

3-9: 💡 Codebase verification

Based on the analysis of the codebase, I can now provide a final response:

AWS IAM role-based authentication recommendation remains valid and important

The codebase shows direct usage of AWS access keys in environment variables (REACT_APP_AWS_ACCESS_KEY_ID and REACT_APP_AWS_SECRET_ACCESS_KEY) for S3 operations. This is particularly concerning as:

  • The application performs S3 operations directly from the client-side (browser)
  • The code handles audio file uploads in VoiceAnalyser.js
  • There's no indication of temporary credentials or IAM role usage

For production environments, consider:

  • Moving S3 operations to a backend service
  • Using AWS Cognito for identity management
  • Implementing STS (Security Token Service) for temporary credentials
  • Setting up appropriate IAM roles with minimal required permissions
🔗 Analysis chain

Consider using AWS IAM role-based authentication.

Direct use of AWS access keys in the application configuration poses security risks. Consider using IAM roles and temporary credentials, especially for production environments.

Let's check if there are other instances of AWS credentials in the codebase:


Let me check the VoiceAnalyser.js file to understand the context better.


Let me check if there's any AWS configuration or environment setup documentation that might provide more context about the authentication strategy.


Let me check for any documentation files that might provide insights into the AWS setup.


Let me check the content of the README.md file for any deployment or configuration information.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential AWS credential patterns
rg -i '(aws.*key|aws.*secret|aws.*credential)' --type js

Length of output: 326


Script:

#!/bin/bash
# Check the content of VoiceAnalyser.js
cat src/utils/VoiceAnalyser.js

Length of output: 24512


Script:

#!/bin/bash
# Check for environment setup files and AWS configuration
fd -e env -e env.example -e config -e yaml -e yml

Length of output: 51


Script:

#!/bin/bash
# Look for README files or documentation
fd -e md -e txt

Length of output: 64


Script:

#!/bin/bash
cat README.md

Length of output: 2523

.github/workflows/all-prod-tn.yml (4)

44-82: 🛠️ Refactor suggestion

Refactor environment variables configuration

The current setup has a large number of inline environment variables. Consider:

  1. Moving these to GitHub Environment Secrets
  2. Using a configuration file to group related variables
  3. Adding validation for required variables

87-91: ⚠️ Potential issue

Remove debug environment output

The debug step potentially exposes sensitive configuration. Consider:

  1. Removing this step from production workflow
  2. Moving debug information to development workflows only

14-20: ⚠️ Potential issue

Update GitHub Actions to latest versions

The current action versions are outdated:

  • actions/checkout@v2actions/checkout@v4
  • actions/setup-node@v3actions/setup-node@v4

Apply this diff:

-        uses: actions/checkout@v2
+        uses: actions/checkout@v4
-        uses: actions/setup-node@v3
+        uses: actions/setup-node@v4
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'
🧰 Tools
🪛 actionlint (1.7.4)

15-15: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


18-18: the runner of "actions/setup-node@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


84-86: ⚠️ Potential issue

Use environment variables for S3 bucket path

The S3 bucket path is hardcoded. Consider:

  1. Moving the bucket name to an environment variable
  2. Adding path prefix as a configurable value

Apply this diff:

-        run: aws s3 sync ./build s3://sballtnlanglab/tn-prod-build/
+        run: aws s3 sync ./build s3://${{ vars.AWS_S3_BUCKET_NAME }}/${{ vars.AWS_S3_PATH_PREFIX }}/
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Deploy to S3 Bucket
        run: aws s3 sync ./build s3://${{ vars.AWS_S3_BUCKET_NAME }}/${{ vars.AWS_S3_PATH_PREFIX }}/

.github/workflows/all-dev-tn.yml (3)

15-15: ⚠️ Potential issue

Update GitHub Actions to latest versions

The workflow uses outdated versions of GitHub Actions. Update the following actions to their latest stable versions:

  • actions/checkout@v2actions/checkout@v4
  • actions/setup-node@v3actions/setup-node@v4
  • aws-actions/configure-aws-credentials@v2aws-actions/configure-aws-credentials@v4
-        uses: actions/checkout@v2
+        uses: actions/checkout@v4
-        uses: actions/setup-node@v3
+        uses: actions/setup-node@v4
-        uses: aws-actions/configure-aws-credentials@v2
+        uses: aws-actions/configure-aws-credentials@v4

Also applies to: 18-18, 23-23

🧰 Tools
🪛 actionlint (1.7.4)

15-15: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


79-79: ⚠️ Potential issue

Fix typos and remove debug statements

  1. The comment has a typo: "secrate" should be "secret"
  2. Debug statements exposing sensitive information should be removed from production workflows
-          echo "secrate": ${{ vars.REACT_APP_AWS_S3_BUCKET_NAME }}

Also applies to: 89-89


92-92: ⚠️ Potential issue

Avoid using @master tag for third-party actions

Using the @master tag for the CloudFront invalidation action is risky as it could break if the upstream repository makes breaking changes. Use a specific version tag instead.

-        uses: chetan/invalidate-cloudfront-action@master
+        uses: chetan/invalidate-cloudfront-action@v2
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        uses: chetan/invalidate-cloudfront-action@v2
.github/workflows/all-prod-rig.yml (1)

22-31: 🛠️ Refactor suggestion

Replace manual AWS CLI configuration with the official action

The workflow manually installs and configures AWS CLI. It's better to use the official aws-actions/configure-aws-credentials action for consistency and security.

-      - name: Install AWS CLI
-        run: |
-          sudo DEBIAN_FRONTEND=noninteractive apt-get update
-          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y awscli
-
-      - name: Configure AWS credentials
-        run: |
-          aws configure set aws_access_key_id ${{ secrets.AWS_ACCESS_KEY_ID }}
-          aws configure set aws_secret_access_key ${{ secrets.AWS_SECRET_ACCESS_KEY }}
-          aws configure set default.region ${{ secrets.AWS_REGION }}
+      - name: Configure AWS credentials
+        uses: aws-actions/configure-aws-credentials@v4
+        with:
+          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
+          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+          aws-region: ${{ secrets.AWS_REGION }}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_REGION }}
.github/workflows/all-staging-tn.yml (6)

15-15: ⚠️ Potential issue

Update GitHub Actions to latest versions

The following actions are using outdated versions:

  • actions/checkout@v2 → Update to @v4
  • actions/setup-node@v3 → Update to @v4

Using latest versions ensures you get security fixes and performance improvements.

-        uses: actions/checkout@v2
+        uses: actions/checkout@v4
-        uses: actions/setup-node@v3
+        uses: actions/setup-node@v4

Also applies to: 18-18

🧰 Tools
🪛 actionlint (1.7.4)

15-15: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


27-32: 🛠️ Refactor suggestion

Use OIDC for AWS authentication

Instead of storing long-lived AWS credentials as secrets, consider using OpenID Connect (OIDC) for secure, temporary AWS credentials. This is a more secure approach recommended by AWS.

Here's how to implement it:

- name: Configure AWS credentials
  uses: aws-actions/configure-aws-credentials@v4
  with:
    role-to-assume: arn:aws:iam::123456789012:role/my-github-actions-role
    aws-region: ${{ secrets.AWS_REGION }}

83-83: ⚠️ Potential issue

Reconsider disabling CI warnings

Setting CI=false prevents treating warnings as errors, which might hide potential issues. Consider addressing the warnings instead of disabling them.


78-79: ⚠️ Potential issue

Move AWS credentials to dedicated service connection

AWS credentials are exposed as environment variables to the build process. This is unnecessary and poses a security risk. These should be only available to the deployment step.

Remove these environment variables from the build step and use them only in the deployment step.


89-94: ⚠️ Potential issue

Remove debug step exposing sensitive information

The debug step could potentially expose sensitive information in the workflow logs. Remove this step or ensure it only logs non-sensitive information.


87-87: 🛠️ Refactor suggestion

Avoid hardcoding S3 bucket paths

The S3 bucket path s3://sballtnlanglab/assets/test-rig/ is hardcoded. Consider moving this to a variable for better maintainability and reusability.

-        run: aws s3 sync ./build s3://sballtnlanglab/assets/test-rig/
+        run: aws s3 sync ./build "s3://${{ vars.AWS_S3_BUCKET_PATH }}"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        run: aws s3 sync ./build "s3://${{ vars.AWS_S3_BUCKET_PATH }}"
src/utils/useAudioDetection.jsx (2)

23-25: 🛠️ Refactor suggestion

⚠️ Potential issue

Replace deprecated createScriptProcessor with AudioWorklet

The method audioContextRef.current.createScriptProcessor() is deprecated and may not be supported in future browser versions. It's recommended to use AudioWorklet for audio processing tasks.


20-21: 🛠️ Refactor suggestion

Properly stop and release the media stream

The media stream obtained from getUserMedia is not being stopped, which can keep the microphone active after stopping detection. It's recommended to store the stream and stop it in stopDetection to release the microphone and free resources.

Apply this diff to manage the media stream:

+  const streamRef = useRef(null);

In the startDetection function:

  // Get user media
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ streamRef.current = stream;
  microphoneRef.current = audioContextRef.current.createMediaStreamSource(stream);

In the stopDetection function:

  if (microphoneRef.current) {
    microphoneRef.current.disconnect();
  }
+ if (streamRef.current) {
+   streamRef.current.getTracks().forEach((track) => track.stop());
+   streamRef.current = null;
+ }
  if (audioContextRef.current) {
    audioContextRef.current.close();
    audioContextRef.current = null;
  }

Also applies to: 64-70

src/components/Practice/Mechanics6.jsx (4)

18-18: 🛠️ Refactor suggestion

Rename component to match the file name for consistency

The component is named Mechanics2, but the file is Mechanics6.jsx. For clarity and consistency, consider renaming the component to Mechanics6.

Apply this diff to rename the component:

-const Mechanics2 = ({
+const Mechanics6 = ({

...

-export default Mechanics2;
+export default Mechanics6;

Also applies to: 515-515


184-185: ⚠️ Potential issue

Fix typo in variable name currrentProgress

The variable currrentProgress is misspelled with an extra 'r'. It should be currentProgress.

Apply this diff to correct the variable name:

-      const [currrentProgress, setCurrrentProgress] = React.useState(0);
+      const [currentProgress, setCurrentProgress] = useState(0);

-      const progressBarWidth = isNaN(currrentProgress / duration)
+      const progressBarWidth = isNaN(currentProgress / duration)

...

-      setCurrrentProgress(e.currentTarget.currentTime);
+      setCurrentProgress(e.currentTarget.currentTime);

Also applies to: 257-258

🧰 Tools
🪛 Biome (1.9.4)

[error] 185-185: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


185-185: ⚠️ Potential issue

Use Number.isNaN instead of isNaN for safer type checking

The global isNaN function can lead to unexpected results due to type coercion. Use Number.isNaN to safely check if a value is NaN.

Apply this diff:

-      const progressBarWidth = isNaN(currentProgress / duration)
+      const progressBarWidth = Number.isNaN(currentProgress / duration)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  const progressBarWidth = Number.isNaN(currrentProgress / duration)
🧰 Tools
🪛 Biome (1.9.4)

[error] 185-185: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


108-111: ⚠️ Potential issue

Ensure homophones array has sufficient elements before accessing

Accessing homophones[6] and homophones[8] without checking the array length may lead to undefined values or runtime errors if the array is shorter than expected.

Consider adding checks before accessing these indices:

          const homophones = await finder.find(wordToSimilar);
+         if (homophones.length >= 9) {
            let wordsArr = [homophones[8], wordToSimilar, homophones[6]];
            setWords(randomizeArray(wordsArr));
+         } else {
+            // Handle the case where homophones array is too short
+            // Provide alternative words or notify the user
+         }

Committable suggestion skipped: line range outside the PR's diff.

src/components/Layouts.jsx/MainLayout.jsx (6)

919-921: 🛠️ Refactor suggestion

Use imported asset for turtle image

The turtle image is being loaded from a hard-coded URL. Since turtleImage is imported at the top of the file, you should use this local asset instead.

Apply this diff to fix the issue:

-<img
-  src="https://raw.githubusercontent.com/Sunbird-ALL/all-learner-ai-app/refs/heads/all-1.2-tn-dev/src/assets/turtle.svg"
-  alt="turtleImage"
-/>

+<img
+  src={turtleImage}
+  alt="turtleImage"
+/>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                                <img
                                  src={turtleImage}
                                  alt="turtleImage"
                                />

880-887: 🛠️ Refactor suggestion

Use imported assets instead of hard-coded URLs

The <img> tags are using hard-coded URLs pointing to GitHub. Since correctImage and wrongImage are already imported, it's better to use these local assets to avoid potential issues with external dependencies.

Apply this diff to fix the issue:

{elem?.correctAnswer === false ? (
  <img
-    src="https://raw.githubusercontent.com/Sunbird-ALL/all-learner-ai-app/refs/heads/all-1.2-tn-dev/src/assets/wrong.svg"
+    src={wrongImage}
    alt="wrongImage"
  />
) : (
  <img
-    src="https://raw.githubusercontent.com/Sunbird-ALL/all-learner-ai-app/refs/heads/all-1.2-tn-dev/src/assets/correct.svg"
+    src={correctImage}
    alt="correctImage"
  />
)}

Committable suggestion skipped: line range outside the PR's diff.


376-376: ⚠️ Potential issue

Add key prop to elements in list rendering

When rendering lists in React, each child in an array or iterator should have a unique key prop. The <Diamond /> component inside the .map() function lacks a key prop, which can lead to rendering issues.

Apply this diff to fix the issue:

{[...Array(Math.max(0, redLivesToShow) || 0).keys()]?.map(
  (elem, index) => (
-    <Diamond />
+    <Diamond key={index} />
  )
)}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                          <Diamond key={index} />
🧰 Tools
🪛 Biome (1.9.4)

[error] 376-376: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)


383-383: ⚠️ Potential issue

Add key prop to elements in list rendering

The <HeartBlack /> component inside the .map() function lacks a key prop. Providing a unique key prop helps React optimize rendering and identify elements correctly.

Apply this diff to fix the issue:

{[...Array(Math.max(0, blackLivesToShow) || 0).keys()]?.map(
  (elem, index) => (
-    <HeartBlack />
+    <HeartBlack key={index} />
  )
)}

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 383-383: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)


872-872: 🛠️ Refactor suggestion

Avoid assignments in expressions for better code clarity

Using assignments within expressions can be confusing and may lead to unintended side effects. The assignment in the ref prop should be refactored for clarity and maintainability.

Consider refactoring the code as follows:

-<audio
-  ref={(el) => (audioRefs.current[index] = el)}
-  src={elem?.audioUrl}
-/>

+const setAudioRef = (el, index) => {
+  audioRefs.current[index] = el;
+};

+// In your JSX:
+<audio
+  ref={(el) => setAudioRef(el, index)}
+  src={elem?.audioUrl}
+/>

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 872-872: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


1175-1194: ⚠️ Potential issue

Add missing PropTypes definitions for component props

Several props used in the MainLayout component are not defined in MainLayout.propTypes. Defining all props in propTypes ensures proper type checking and improves maintainability.

Add the following PropTypes definitions:

MainLayout.propTypes = {
  // Existing propTypes...
  pageName: PropTypes.string,
+ fluency: PropTypes.bool,
+ percentage: PropTypes.number,
+ progressData: PropTypes.shape({
+   currentPracticeStep: PropTypes.number,
+   currentPracticeProgress: PropTypes.number,
+ }),
+ livesData: PropTypes.shape({
+   blackLivesToShow: PropTypes.number,
+   redLivesToShow: PropTypes.number,
+   lives: PropTypes.number,
+ }),
+ gameOverData: PropTypes.shape({
+   userWon: PropTypes.bool,
+   link: PropTypes.string,
+ }),
+ level: PropTypes.number,
+ cardBackground: PropTypes.string,
+ backgroundImage: PropTypes.string,
+ steps: PropTypes.number,
+ currentStep: PropTypes.number,
+ stepsArr: PropTypes.array,
+ lang: PropTypes.string,
+ disableScreen: PropTypes.bool,
+ children: PropTypes.node,
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

MainLayout.propTypes = {
  contentType: PropTypes.string,
  handleBack: PropTypes.func,
  disableScreen: PropTypes.bool,
  isShowCase: PropTypes.bool,
  showProgress: PropTypes.bool,
  setOpenLangModal: PropTypes.func,
  points: PropTypes.number,
  handleNext: PropTypes.any,
  enableNext: PropTypes.bool,
  showNext: PropTypes.bool,
  showTimer: PropTypes.bool,
  nextLessonAndHome: PropTypes.bool,
  startShowCase: PropTypes.bool,
  setStartShowCase: PropTypes.func,
  loading: PropTypes.bool,
  storedData: PropTypes.array,
  resetStoredData: PropTypes.func,
  pageName: PropTypes.string,
  fluency: PropTypes.bool,
  percentage: PropTypes.number,
  progressData: PropTypes.shape({
    currentPracticeStep: PropTypes.number,
    currentPracticeProgress: PropTypes.number,
  }),
  livesData: PropTypes.shape({
    blackLivesToShow: PropTypes.number,
    redLivesToShow: PropTypes.number,
    lives: PropTypes.number,
  }),
  gameOverData: PropTypes.shape({
    userWon: PropTypes.bool,
    link: PropTypes.string,
  }),
  level: PropTypes.number,
  cardBackground: PropTypes.string,
  backgroundImage: PropTypes.string,
  steps: PropTypes.number,
  currentStep: PropTypes.number,
  stepsArr: PropTypes.array,
  lang: PropTypes.string,
  disableScreen: PropTypes.bool,
  children: PropTypes.node,
};
src/components/Practice/Mechanics5.jsx (3)

58-59: ⚠️ Potential issue

Handle cases where options may not be populated

The initialization of audiosRef assumes that options.length exists. If options is empty or undefined, this will throw an error. Ensure that options is an array and has a length before using it.

Since we've updated the default value of options to an empty array, this should prevent errors. Additionally, ensure that options.length is checked before usage if there's any possibility of it being empty.


17-17: ⚠️ Potential issue

Fix the default value of options prop to be an array

The options prop is expected to be an array throughout the component. However, its default value is currently set to an empty object {}, which will cause errors when accessing options.length or iterating over options.

Apply this diff to fix the default value:

-   options = {},
+   options = [],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  options = [],

389-391: ⚠️ Potential issue

Add null check when accessing .text after options.find()

If no option with isAns === true is found, options.find() will return undefined, and accessing .text will cause an error. Adding a null check will prevent a potential runtime error.

Apply this diff to add a null check:

       options &&
       options.length > 0 &&
-      options.find((option) => option.isAns === true).text
+      options.find((option) => option.isAns === true)?.text
         ? options.find((option) => option.isAns === true).text
         : parentWords

Committable suggestion skipped: line range outside the PR's diff.

src/utils/VoiceAnalyser.js (3)

121-122: 🛠️ Refactor suggestion

Replace alert with user-friendly error messaging

Using alert() for error notifications can be intrusive and may not align with the application's UI/UX standards. Consider using a non-blocking UI component such as setOpenMessageDialog to display error messages consistently.

Apply this diff to improve error handling:

// In playAudio function error handler
- alert("Failed to load the audio. Please try again.");
+ props.setOpenMessageDialog({
+   message: "Failed to load the audio. Please try again.",
+   isError: true,
+ });

// In playAudio function catch block
- alert("An unexpected error occurred while trying to play the audio.");
+ props.setOpenMessageDialog({
+   message: "An unexpected error occurred while trying to play the audio.",
+   isError: true,
+ });

// In playRecordedAudio function error handler
- alert("Failed to load the audio. Please try again.");
+ props.setOpenMessageDialog({
+   message: "Failed to load the audio. Please try again.",
+   isError: true,
+ });

Also applies to: 126-126, 148-149


559-560: ⚠️ Potential issue

Handle potential division by zero in percentage calculation

The variable totalSyllables might be zero, which would lead to a division by zero error when calculating percentage. Ensure that totalSyllables is greater than zero before performing the division to prevent runtime exceptions.

Apply this diff to fix the issue:

+ if (totalSyllables > 0) {
    percentage = Math.round((percentage / totalSyllables) * 100);
+ } else {
+   percentage = 0;
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        if (totalSyllables > 0) {
            percentage = Math.round((percentage / totalSyllables) * 100);
        } else {
            percentage = 0;
        }

746-766: ⚠️ Potential issue

Include setLivesData in PropTypes

The setLivesData function is destructured from props and used within the component but is not specified in PropTypes. Adding it to PropTypes ensures that its presence is validated, preventing potential bugs.

Apply this diff to update PropTypes:

VoiceAnalyser.propTypes = {
    ...
    livesData: PropTypes.object,
+   setLivesData: PropTypes.func.isRequired,
    ...
};

Committable suggestion skipped: line range outside the PR's diff.

src/views/Practice/Practice.jsx (2)

242-242: 🛠️ Refactor suggestion

Simplify boolean expression in is_mechanics assignment

The ternary operator mechanism && mechanism?.id ? true : false is unnecessary since the expression already evaluates to a boolean. You can assign it directly.

Apply this diff to simplify the expression:

-                is_mechanics: mechanism && mechanism?.id ? true : false,
+                is_mechanics: Boolean(mechanism && mechanism.id),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

              is_mechanics: Boolean(mechanism && mechanism.id),
🧰 Tools
🪛 Biome (1.9.4)

[error] 242-242: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


[error] 242-242: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


124-131: ⚠️ Potential issue

Specify target origin in postMessage for security

Using window.parent.postMessage with "*" as the target origin can introduce security risks. It's recommended to specify the exact origin to prevent unauthorized message recipients.

Apply this diff to fix the issue (replace 'https://trusted.origin' with the actual parent origin):

 const send = (score) => {
   if (process.env.REACT_APP_IS_APP_IFRAME === "true") {
     window.parent.postMessage(
       {
         score: score,
         message: "all-test-rig-score",
       },
-      "*"
+      "https://trusted.origin"
     );
   }
 };

Committable suggestion skipped: line range outside the PR's diff.

src/utils/AudioCompare.js (4)

81-84: ⚠️ Potential issue

Revoke object URL to prevent memory leaks

After creating an object URL with window.URL.createObjectURL(blob);, it's important to revoke it when it's no longer needed to prevent memory leaks.

Consider adding code to revoke the object URL when appropriate. For instance, you can store the URL in a ref and revoke it in a useEffect cleanup function or when the component unmounts.


6-7: ⚠️ Potential issue

Correct the import paths for assets

The paths to playButton and pauseButton images seem incorrect. Since you are in the src/utils/ directory, you should adjust the relative paths to correctly locate the assets.

Apply this diff to fix the import paths:

- import playButton from "../../src/assets/listen.png";
- import pauseButton from "../../src/assets/pause.png";
+ import playButton from "../assets/listen.png";
+ import pauseButton from "../assets/pause.png";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

import playButton from "../assets/listen.png";
import pauseButton from "../assets/pause.png";

125-126: ⚠️ Potential issue

Fix typo in state variable name

The state variable currrentProgress has a typo with an extra 'r'. It should be currentProgress.

Apply this diff to correct the variable name:

- const [currrentProgress, setCurrrentProgress] = React.useState(0);
+ const [currentProgress, setCurrentProgress] = React.useState(0);

Ensure you update all references to currrentProgress accordingly.

Committable suggestion skipped: line range outside the PR's diff.


89-195: 🛠️ Refactor suggestion

Refactor inline IIFE in render method

Using an immediately-invoked function expression (IIFE) inside JSX for conditional rendering is unnecessary and can impact readability. Consider refactoring the code to use simple conditional rendering without the IIFE.

Apply this diff to refactor the conditional rendering:

- {(() => {
-   if (status === "recording") {
-     return (
-       <div>...Recording UI...</div>
-     );
-   } else {
-     return (
-       <div>...Non-recording UI...</div>
-     );
-   }
- })()}
+ {status === "recording" ? (
+   <div>...Recording UI...</div>
+ ) : (
+   <div>...Non-recording UI...</div>
+ )}

Committable suggestion skipped: line range outside the PR's diff.

src/components/Assesment/Assesment.jsx (2)

46-46: ⚠️ Potential issue

Correct the import statement for jwt-decode

The import of jwtDecode is incorrect. The jwt-decode library exports a default function. Adjust the import statement accordingly.

Apply this diff to fix the import:

- import { jwtDecode } from "jwt-decode";
+ import jwtDecode from "jwt-decode";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

import jwtDecode from "jwt-decode";

550-553: 🛠️ Refactor suggestion

Add error handling for jwtDecode

Decoding a JWT can fail if the token is invalid or expired. Wrap the jwtDecode call in a try-catch block to handle potential errors gracefully.

Apply this diff to add error handling:

let jwtToken = localStorage.getItem("token");
- let userDetails = jwtDecode(jwtToken);
+ let userDetails;
+ try {
+   userDetails = jwtDecode(jwtToken);
+ } catch (error) {
+   console.error("Failed to decode JWT token:", error);
+   // Handle error, possibly redirect to login
+ }

Committable suggestion skipped: line range outside the PR's diff.

src/utils/RecordVoiceVisualizer.jsx (1)

75-75: ⚠️ Potential issue

Add key prop to elements in list rendering

When rendering lists using map, each element should have a unique key prop to help React optimize rendering and track element identity.

Apply this diff to add a key prop:

{Object.entries(renderType).map(([key, value]) => {
-   return <>{renderBar(key, value)}</>;
+   return <React.Fragment key={key}>{renderBar(key, value)}</React.Fragment>;
})}

Similarly, update the reversed map:

{Object.entries(renderType)
  .reverse()
  .map(([key, value]) => {
-     return <>{renderBar(key, value)}</>;
+     return <React.Fragment key={key}>{renderBar(key, value)}</React.Fragment>;
  })}

Also applies to: 86-86

🧰 Tools
🪛 Biome (1.9.4)

[error] 75-75: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

package.json (2)

92-92: ⚠️ Potential issue

Remove duplicate dependencies.

The following packages appear in both dependencies and devDependencies:

  • @mui/styles
  • react

This could lead to version conflicts and increased bundle size.

Remove these duplicates from devDependencies as they're already present in dependencies.

  "devDependencies": {
-   "@mui/styles": "^5.15.10",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^3.4.0",
    "husky": "^9.0.11",
    "lint-staged": "^11.0.0",
    "prettier": "^2.3.2",
-   "react": "^18.2.0"
  }

Also applies to: 99-99


101-110: ⚠️ Potential issue

Update Husky and lint-staged configurations.

  1. The Husky configuration uses deprecated hooks syntax. Since Husky v7, the preferred method is using individual hook files.

  2. The lint-staged configuration could be more comprehensive.

  3. Replace the Husky configuration with the new format:
    Create .husky/pre-commit:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
  1. Update lint-staged configuration:
  "lint-staged": {
    "src/**/*.{js,jsx}": [
      "npx eslint --fix",
      "npx prettier --write"
-   ]
+   ],
+   "*.{json,md,yml,yaml}": [
+     "npx prettier --write"
+   ]
  },
- "husky": {
-   "hooks": {
-     "pre-commit": "npx lint-staged"
-   }
- }
src/store/sagas/handlers/user.handler.js (1)

57-57: ⚠️ Potential issue

Configure retry mechanism parameters

The retry mechanism is currently configured with 0 attempts and 0 delay, which effectively disables it. Consider setting appropriate retry parameters for better error handling.

-yield retry(0, 0, verifyOtp, action.payload);
+yield retry(3, 1000, verifyOtp, action.payload);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        yield retry(3, 1000, verifyOtp, action.payload);
src/views/LoginPage/LoginPage.jsx (2)

39-78: 🛠️ Refactor suggestion

Improve form accessibility and user feedback

The form lacks proper accessibility attributes and user feedback elements.

 return (
     <Container className="container">
         <div className="loginBox">
+            {error && (
+                <Alert severity="error" onClose={() => setError(null)}>
+                    {error}
+                </Alert>
+            )}
             <Typography variant="h4" align="center" gutterBottom>
                 Login
             </Typography>
-            <form onSubmit={handleSubmit}>
+            <form onSubmit={handleSubmit} aria-label="login form">
                 <Grid container spacing={2}>
                     <Grid item xs={12}>
                         <TextField
                             className="textField"
                             label="Username"
                             variant="outlined"
                             fullWidth
+                            required
+                            inputProps={{
+                                'aria-label': 'Username',
+                                minLength: 3
+                            }}
                             value={username}
                             onChange={(e) => setUsername(e.target.value)}
                         />
                     </Grid>
                     <Button 
                         type="submit" 
                         variant="contained" 
                         color="primary" 
                         fullWidth
+                        disabled={isLoading}
                     >
-                        Login
+                        {isLoading ? 'Logging in...' : 'Login'}
                     </Button>

Committable suggestion skipped: line range outside the PR's diff.


21-36: ⚠️ Potential issue

Enhance security and user experience in authentication flow

Several security and UX improvements are needed:

  1. Password is collected but not used in the API call
  2. Generic error messages don't help users understand what went wrong
  3. No loading state during API call
  4. Basic input validation
  5. Clearing localStorage without warning could lead to data loss
 try {
+    setIsLoading(true);
+    if (!isValidUsername(username)) {
+        throw new Error('Username must be at least 3 characters long');
+    }
+    if (localStorage.length > 0) {
+        const shouldClear = window.confirm('This will clear your existing session. Continue?');
+        if (!shouldClear) return;
+    }
     localStorage.clear();
     const usernameDetails = await axios.post(
         `${process.env.REACT_APP_VIRTUAL_ID_HOST}/${config.URLS.GET_VIRTUAL_ID}?username=${username}`
     );
     if (usernameDetails?.data?.result?.virtualID) {
         localStorage.setItem("profileName", username);
         localStorage.setItem("virtualId", usernameDetails?.data?.result?.virtualID);
         navigate("/discover-start");
     } else {
-        alert("Enter correct username and password");
+        throw new Error('Invalid username or password');
     }
 } catch (error) {
     console.error("Error occurred:", error);
-    alert("An error occurred. Please try again later.");
+    setError(error.message || 'An unexpected error occurred');
 } finally {
+    setIsLoading(false);
 }

Committable suggestion skipped: line range outside the PR's diff.

src/components/DiscoverEnd/DiscoverEnd.jsx (1)

55-65: 🛠️ Refactor suggestion

Improve error handling in navigation function

The error handling in handleProfileBack is too broad and the error message isn't actionable.

 const handleProfileBack = () => {
     try {
         if (process.env.REACT_APP_IS_APP_IFRAME === 'true') {
             navigate("/")
         } else {
             navigate("/discover-start")
         }
     } catch (error) {
-        console.error("Error posting message:", error);
+        console.error("Navigation failed:", error);
+        // Provide fallback navigation or show user-friendly error
+        window.location.href = '/discover-start';
     }
 };

Committable suggestion skipped: line range outside the PR's diff.

src/services/telementryService.js (1)

232-238: ⚠️ Potential issue

Verify the presence of userDetails object

The code assumes userDetails object exists when accessing its properties. This could lead to runtime errors if userDetails is undefined.

                { id: localStorage.getItem("lang") || 'ta', type: 'language' },
-                { id: userDetails?.school_name, type: 'school_name' },
-                {
-                  id: userDetails?.class_studying_id,
-                  type: 'class_studying_id',
-                },
-                { id: userDetails?.udise_code, type: 'udise_code' },
+                ...(userDetails ? [
+                  { id: userDetails.school_name, type: 'school_name' },
+                  { id: userDetails.class_studying_id, type: 'class_studying_id' },
+                  { id: userDetails.udise_code, type: 'udise_code' }
+                ] : [])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                { id: localStorage.getItem("lang") || 'ta', type: 'language' },
                ...(userDetails ? [
                  { id: userDetails.school_name, type: 'school_name' },
                  { id: userDetails.class_studying_id, type: 'class_studying_id' },
                  { id: userDetails.udise_code, type: 'udise_code' }
                ] : [])
src/components/AssesmentEnd/AssesmentEnd.jsx (1)

42-46: 🛠️ Refactor suggestion

Improve session ID management

The session ID management could be moved to a dedicated service for better reusability and consistency.

+// src/services/sessionService.js
+export const getOrCreateSessionId = () => {
+  let sessionId = localStorage.getItem('sessionId');
+  if (!sessionId) {
+    sessionId = uniqueId();
+    localStorage.setItem('sessionId', sessionId);
+  }
+  return sessionId;
+};

// In AssesmentEnd.jsx
-      let sessionId = getLocalData("sessionId");
-      if (!sessionId){
-        sessionId = uniqueId();
-        localStorage.setItem("sessionId", sessionId)
-      }
+      const sessionId = getOrCreateSessionId();

Committable suggestion skipped: line range outside the PR's diff.

src/components/DiscoverSentance/DiscoverSentance.jsx (6)

36-36: ⚠️ Potential issue

Initialize openMessageDialog to null or an object for consistency

openMessageDialog is initialized to an empty string "", but later used as an object with properties. This could lead to runtime errors when accessing its properties.

Consider initializing openMessageDialog to null:

- const [openMessageDialog, setOpenMessageDialog] = useState("");
+ const [openMessageDialog, setOpenMessageDialog] = useState(null);

And update the conditional rendering:

- {!!openMessageDialog && (
+ {openMessageDialog && (

This ensures that openMessageDialog is either null or an object, avoiding potential property access errors.

Also applies to: 308-318


121-121: 🛠️ Refactor suggestion

Simplify the condition to check for null values

The condition if (!(localStorage.getItem("contentSessionId") !== null)) can be simplified for clarity.

Consider changing it to:

- if (!(localStorage.getItem("contentSessionId") !== null)) {
+ if (localStorage.getItem("contentSessionId") === null) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      if (localStorage.getItem("contentSessionId") === null) {

102-110: ⚠️ Potential issue

Specify targetOrigin in postMessage for security

Using window.parent.postMessage with targetOrigin set to "*" allows any domain to receive the message, which can pose security risks. Specify the expected origin of the parent window to enhance security.

Please update the postMessage call to include the specific origin. For example:

- window.parent.postMessage(
-   {
-     score: score,
-     message: "all-test-rig-score",
-   },
-   "*"
- );
+ const targetOrigin = "https://your-trusted-domain.com";
+ window.parent.postMessage(
+   {
+     score: score,
+     message: "all-test-rig-score",
+   },
+   targetOrigin
+ );

Replace https://your-trusted-domain.com with the actual trusted domain.

Committable suggestion skipped: line range outside the PR's diff.


66-66: 🛠️ Refactor suggestion

Simplify the condition to check for null values

The condition if (!(localStorage.getItem("contentSessionId") !== null)) is unnecessarily complex. It can be simplified for better readability.

Consider changing it to:

- if (!(localStorage.getItem("contentSessionId") !== null)) {
+ if (localStorage.getItem("contentSessionId") === null) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if (localStorage.getItem("contentSessionId") === null) {

14-16: ⚠️ Potential issue

Correct typos in import paths for 'Assessment' and 'Telemetry'

The import paths contain spelling errors:

  • 'Assesment' should be 'Assessment'.
  • 'telementryService' should be 'telemetryService'.

Apply the following diff to fix the typos:

- import { MessageDialog } from "../Assesment/Assesment";
+ import { MessageDialog } from "../Assessment/Assessment";

- import { Log } from "../../services/telementryService";
+ import { Log } from "../../services/telemetryService";

Committable suggestion skipped: line range outside the PR's diff.


51-61: ⚠️ Potential issue

Correct spelling of 'assessment' in variable names

The variables assesmentCount and initialAssesment are misspelled. The correct spelling is assessment. Consider renaming them for consistency and readability.

Apply the following diff to correct the spelling:

- const [assesmentCount, setAssesmentcount] = useState(0);
+ const [assessmentCount, setAssessmentCount] = useState(0);

- const [initialAssesment, setInitialAssesment] = useState(true);
+ const [initialAssessment, setInitialAssessment] = useState(true);

Update all usages accordingly:

- setAssesmentcount(assesmentCount + 1);
+ setAssessmentCount(assessmentCount + 1);

- if (questions?.length && !initialAssesment && currentQuestion === 0) {
+ if (questions?.length && !initialAssessment && currentQuestion === 0) {

- "You have successfully completed assessment " + assesmentCount
+ "You have successfully completed assessment " + assessmentCount

Committable suggestion skipped: line range outside the PR's diff.

src/utils/constants.js (4)

82-82: ⚠️ Potential issue

Fix the opacity assignment to avoid unintended false value.

The opacity property might receive a boolean false when props.disabled is not set, which could lead to unexpected rendering behavior. It's better to provide a default value when disabled is not true.

Adjust the opacity assignment as follows:

-    opacity={props?.disabled && 0.3}
+    opacity={props?.disabled ? 0.3 : 1}

This ensures that the opacity is 0.3 when the button is disabled, and 1 (fully opaque) when it's not.

Committable suggestion skipped: line range outside the PR's diff.


4310-4312: ⚠️ Potential issue

Add try-catch block to handle JSON parsing errors.

Parsing process.env.REACT_APP_LANGUAGES without error handling could cause the application to crash if the environment variable is not a valid JSON string.

Implement error handling:

-let appLanguages = process.env.REACT_APP_LANGUAGES
-  ? JSON.parse(process.env.REACT_APP_LANGUAGES)
-  : [];
+let appLanguages = [];
+if (process.env.REACT_APP_LANGUAGES) {
+  try {
+    appLanguages = JSON.parse(process.env.REACT_APP_LANGUAGES);
+  } catch (error) {
+    console.error("Failed to parse REACT_APP_LANGUAGES:", error);
+    appLanguages = [];
+  }
+}

This ensures that your application remains stable even if the environment variable is incorrectly formatted.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

let appLanguages = [];
if (process.env.REACT_APP_LANGUAGES) {
  try {
    appLanguages = JSON.parse(process.env.REACT_APP_LANGUAGES);
  } catch (error) {
    console.error("Failed to parse REACT_APP_LANGUAGES:", error);
    appLanguages = [];
  }
}

4238-4241: ⚠️ Potential issue

Initialize skew before using it in calculations.

The variable skew is declared but not initialized, leading to NaN values when used in Math.max(0.8, skew - 0.001). This will cause unexpected behavior in the confetti animation.

Initialize skew to a valid number:

-var skew;
+var skew = 1; // Start with a skew value of 1

 skew = Math.max(0.8, skew - 0.001);

Adjust the initial value of skew as needed for the desired animation effect.

Committable suggestion skipped: line range outside the PR's diff.


3151-3156: ⚠️ Potential issue

Ensure location is not undefined before using it in getParameter.

The function getParameter uses location without checking if it's provided. If location is undefined, URLSearchParams will throw an error.

Include a check for location:

 export function getParameter(key, location) {
   if (key && location) {
     const query = new URLSearchParams(location);
     return query.get(key);
+  } else {
+    return null;
   }
 }

This ensures the function returns null when location is not provided, preventing runtime errors.

Committable suggestion skipped: line range outside the PR's diff.

src/routes/index.js (2)

6-6: 🛠️ Refactor suggestion

Inconsistent variable naming: 'routData' should be 'routeData'

The variable routData appears to be misspelled. For clarity and consistency, consider renaming it to routeData.

Apply this diff to correct the variable name:

-const routData = [
+const routeData = [

Also, replace all instances of routData with routeData in the code:

-  routData.push(
+  routeData.push(

Also applies to: 75-83, 84-93


77-77: ⚠️ Potential issue

Duplicate route ID 'route-000'

The id property for the routes added in both the if and else blocks is set to 'route-000'. Route IDs should be unique to prevent conflicts and ensure proper identification.

Apply this diff to assign unique IDs to the routes:

   // In the 'if' block
-    id: "route-000",
+    id: "route-011",
   // In the 'else' block
-    id: "route-000",
+    id: "route-012",

Ensure that each route has a unique id.

Also applies to: 86-86

src/views/PracticeRedirectPage/PracticeRedirectPage.jsx (1)

8-11: 🛠️ Refactor suggestion

Avoid suppressing ESLint warnings; include navigate in the dependency array

Suppressing ESLint warnings can hide potential issues. Instead of disabling the rule, include navigate in the dependency array to comply with the react-hooks/exhaustive-deps rule.

Apply this diff:

 useEffect(() => {
   navigate("/practice");
-  // eslint-disable-next-line react-hooks/exhaustive-deps
-}, []);
+}, [navigate]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  useEffect(() => {
    navigate("/practice");
  }, [navigate]);
src/utils/Badwords.js (1)

19-23: ⚠️ Potential issue

Handle short words correctly when masking bad words

The current implementation assumes that words have at least three characters. For shorter words, using word[0] and word[word.length - 1] may not work as intended.

Modify the code to handle words of different lengths:

 if (checkBadWord(word)) {
-    return `${word[0]}*****${word[word.length-1]}`; // Replace bad words with *****
+    if (word.length > 2) {
+      return `${word[0]}*****${word[word.length - 1]}`;
+    } else if (word.length === 2) {
+      return `${word[0]}*`;
+    } else {
+      return '*';
+    }
 }

This ensures all bad words are appropriately masked, regardless of length.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if (checkBadWord(word)) {
      if (word.length > 2) {
        return `${word[0]}*****${word[word.length - 1]}`;
      } else if (word.length === 2) {
        return `${word[0]}*`;
      } else {
        return '*';
      }
    }
    return word;
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants