ronantakizawa/codereview-bench huggingface dataset:
Repository: freeCodeCamp/freeCodeCamp
File: client/tools/external-curriculum/build-external-curricula-data-v2.ts (TypeScript)

Code before:
      public: false,
      title: intros[SuperBlocks.FullStackDeveloperV9].title
    }
  ],

  [SuperBlockStage.English]: [
    {
      dashedName: SuperBlocks.A2English,
      public: true,
      title: intros[SuperBlocks.A2English].title
    },
    {
      dashedName: SuperBlocks.B1English,
      public: true,
      title: intros[SuperBlocks.B1English].title
    }
  ],

  [SuperBlockStage.Extra]: [
    {
      dashedName: SuperBlocks.TheOdinProject,
      public: true,
      title: intros[SuperBlocks.TheOdinProject].title
    },
    {
      dashedName: SuperBlocks.CodingInterviewPrep,
      public: false,
      title: intros[SuperBlocks.CodingInterviewPrep].title
    },
    {
      dashedName: SuperBlocks.ProjectEuler,
      public: false,
      title: intros[SuperBlocks.ProjectEuler].title
    },
    {
      dashedName: SuperBlocks.RosettaCode,
      public: false,
      title: intros[SuperBlocks.RosettaCode].title
    }
  ],

  [SuperBlockStage.Legacy]: [
    {
      dashedName: SuperBlocks.RespWebDesignNew,
      public: true,
      title: intros[SuperBlocks.RespWebDesignNew].title
    },
    {
      dashedName: SuperBlocks.JsAlgoDataStructNew,
      public: false,
      title: intros[SuperBlocks.JsAlgoDataStructNew].title

Review comment (suggestion):
I'm adding this stage in so the tests won't scream.

I believe this change is safe for mobile, since we render the stages from a constant, rather than pulling and rendering everything from the data: https://github.com/freeCodeCamp/mobile/blob/4ae53df06f6f9fd7b009ed39a25071314817b921/mobile-app/lib/ui/views/learn/landing/landing_viewmodel.dart#L226-L232.

Code after:
      dashedName: SuperBlocks.FullStackDeveloperV9,
      public: false,
      title: intros[SuperBlocks.FullStackDeveloperV9].title
    }
  ],

  [SuperBlockStage.English]: [
    {
      dashedName: SuperBlocks.A2English,
      public: true,
      title: intros[SuperBlocks.A2English].title
    },
    {
      dashedName: SuperBlocks.B1English,
      public: true,
      title: intros[SuperBlocks.B1English].title
    }
  ],

  [SuperBlockStage.Spanish]: [
    {
      dashedName: SuperBlocks.A1Spanish,
      public: false,
      title: intros[SuperBlocks.A1Spanish].title
    }
  ],

  [SuperBlockStage.Extra]: [
    {
      dashedName: SuperBlocks.TheOdinProject,
      public: true,
      title: intros[SuperBlocks.TheOdinProject].title
    },
    {
      dashedName: SuperBlocks.CodingInterviewPrep,
      public: false,
      title: intros[SuperBlocks.CodingInterviewPrep].title
    },
    {
      dashedName: SuperBlocks.ProjectEuler,
      public: false,
      title: intros[SuperBlocks.ProjectEuler].title
    },
    {
      dashedName: SuperBlocks.RosettaCode,
      public: false,
      title: intros[SuperBlocks.RosettaCode].title
    }
  ],

  [SuperBlockStage.Legacy]: [
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/protected/certificate.ts (TypeScript)

Code before:
import { isKnownCertSlug } from '../helpers/certificate-utils.js';

function isCertAllowed(certSlug: string): boolean {
  if (
    currentCertifications.includes(certSlug) ||
    legacyCertifications.includes(certSlug) ||
    legacyFullStackCertification.includes(certSlug)
  ) {
    return true;
  }
  if (SHOW_UPCOMING_CHANGES && upcomingCertifications.includes(certSlug)) {
    return true;
  }
  return false;
}

function renderCertifiedEmail({
  username,
  name
}: {
  username: string;
  name: string;
}) {
  const certifiedEmailTemplate = `Hi ${name || username},

Congratulations on completing the Certified Full Stack Developer Certification!

All of your certifications are now live at: https://www.freecodecamp.org/${username}

Please tell me a bit more about you and your near-term goals.

Also, check out https://contribute.freecodecamp.org/ for some fun and convenient ways you can contribute to the community.

Happy coding,

- Quincy Larson, teacher at freeCodeCamp
`;
  return certifiedEmailTemplate;
}

function hasCompletedTests(
  tests: { id: string }[],
  completedChallenges: CompletedChallenge[]
) {
  return tests.every(({ id }) =>
    completedChallenges.some(({ id: completedId }) => completedId === id)
  );
}

function assertTestsExist(
  tests: ReturnType<typeof getChallenges>[number]['tests']

Review comment (suggestion):
```suggestion
Congratulations on completing the Certified Full Stack Developer Curriculum!
```

Code after:
import { isKnownCertSlug } from '../helpers/certificate-utils.js';

function isCertAllowed(certSlug: string): boolean {
  if (
    currentCertifications.includes(certSlug) ||
    legacyCertifications.includes(certSlug) ||
    legacyFullStackCertification.includes(certSlug)
  ) {
    return true;
  }
  if (SHOW_UPCOMING_CHANGES && upcomingCertifications.includes(certSlug)) {
    return true;
  }
  return false;
}

function renderCertifiedEmail({
  username,
  name
}: {
  username: string;
  name: string;
}) {
  const certifiedEmailTemplate = `Hi ${name || username},

Congratulations on completing the Certified Full Stack Developer Curriculum!

All of your certifications are now live at: https://www.freecodecamp.org/${username}

Please tell me a bit more about you and your near-term goals.

Also, check out https://contribute.freecodecamp.org/ for some fun and convenient ways you can contribute to the community.

Happy coding,

- Quincy Larson, teacher at freeCodeCamp
`;
  return certifiedEmailTemplate;
}

function hasCompletedTests(
  tests: { id: string }[],
  completedChallenges: CompletedChallenge[]
) {
  return tests.every(({ id }) =>
    completedChallenges.some(({ id: completedId }) => completedId === id)
  );
}

function assertTestsExist(
  tests: ReturnType<typeof getChallenges>[number]['tests']
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/protected/settings.ts (TypeScript)

Code before:
        });

        return reply.send({
          message: 'flash.username-updated',
          type: 'success',
          variables: { username: newUsernameDisplay }
        });
      } catch (err) {
        logger.error(err);
        fastify.Sentry.captureException(err);
        void reply.code(500);
        await reply.send({ message: 'flash.wrong-updating', type: 'danger' });
      }
    }
  );

  fastify.put(
    '/update-my-about',
    {
      schema: schemas.updateMyAbout
    },
    async (req, reply) => {
      const logger = fastify.log.child({ req, res: reply });
      
      // Only validate picture if it's being changed
      if (req.body.picture !== undefined) {
        const currentUser = await fastify.prisma.user.findUnique({
          where: { id: req.user?.id },
          select: { picture: true }
        });
        
        // Only validate if the picture is actually different
        if (req.body.picture !== currentUser?.picture) {
          const pictureIsValid = isValidPictureUrl(req.body.picture);
          if (!pictureIsValid) {
            logger.warn(`Invalid picture URL: ${req.body.picture}`);
            void reply.code(400);
            return { message: 'flash.wrong-updating', type: 'danger' } as const;
          }
        }
      }

      try {
        // Build update data object, only including fields that are provided
        const updateData: {
          about?: string;
          name?: string;
          location?: string;
          picture?: string;
        } = {};
        

Review comment (suggestion):
```suggestion
      if (req.body.picture) {
```
If it's undefined, nothing will be updated (which is fine)

Code after:
        });

        return reply.send({
          message: 'flash.username-updated',
          type: 'success',
          variables: { username: newUsernameDisplay }
        });
      } catch (err) {
        logger.error(err);
        fastify.Sentry.captureException(err);
        void reply.code(500);
        await reply.send({ message: 'flash.wrong-updating', type: 'danger' });
      }
    }
  );

  fastify.put(
    '/update-my-about',
    {
      schema: schemas.updateMyAbout
    },
    async (req, reply) => {
      const logger = fastify.log.child({ req, res: reply });

      // No need to validate if picture is being deleted.
      if (req.body.picture) {
        if (req.body.picture !== req.user!.picture) {
          if (!isValidPictureUrl(req.body.picture)) {
            logger.warn(`Invalid picture URL: ${req.body.picture}`);
            void reply.code(400);
            return { message: 'flash.wrong-updating', type: 'danger' } as const;
          }
        }
      }

      try {
        await fastify.prisma.user.update({
          where: { id: req.user?.id },
          data: {
            about: req.body.about,
            name: req.body.name,
            location: req.body.location,
            picture: req.body.picture
          }
        });

        return {
          message: 'flash.updated-about-me',
          type: 'success'
        } as const;
      } catch (err) {
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/protected/settings.ts (TypeScript)

Code before:
          }
        });

        return reply.send({
          message: 'flash.username-updated',
          type: 'success',
          variables: { username: newUsernameDisplay }
        });
      } catch (err) {
        logger.error(err);
        fastify.Sentry.captureException(err);
        void reply.code(500);
        await reply.send({ message: 'flash.wrong-updating', type: 'danger' });
      }
    }
  );

  fastify.put(
    '/update-my-about',
    {
      schema: schemas.updateMyAbout
    },
    async (req, reply) => {
      const logger = fastify.log.child({ req, res: reply });
      
      // Only validate picture if it's being changed
      if (req.body.picture !== undefined) {
        const currentUser = await fastify.prisma.user.findUnique({
          where: { id: req.user?.id },
          select: { picture: true }
        });
        
        // Only validate if the picture is actually different
        if (req.body.picture !== currentUser?.picture) {
          const pictureIsValid = isValidPictureUrl(req.body.picture);
          if (!pictureIsValid) {
            logger.warn(`Invalid picture URL: ${req.body.picture}`);
            void reply.code(400);
            return { message: 'flash.wrong-updating', type: 'danger' } as const;
          }
        }
      }

      try {
        // Build update data object, only including fields that are provided
        const updateData: {
          about?: string;
          name?: string;
          location?: string;
          picture?: string;
        } = {};

Review comment (suggestion):
```suggestion
      // No need to validate if picture is being deleted.
```

Code after:
          }
        });

        return reply.send({
          message: 'flash.username-updated',
          type: 'success',
          variables: { username: newUsernameDisplay }
        });
      } catch (err) {
        logger.error(err);
        fastify.Sentry.captureException(err);
        void reply.code(500);
        await reply.send({ message: 'flash.wrong-updating', type: 'danger' });
      }
    }
  );

  fastify.put(
    '/update-my-about',
    {
      schema: schemas.updateMyAbout
    },
    async (req, reply) => {
      const logger = fastify.log.child({ req, res: reply });

      // No need to validate if picture is being deleted.
      if (req.body.picture) {
        if (req.body.picture !== req.user!.picture) {
          if (!isValidPictureUrl(req.body.picture)) {
            logger.warn(`Invalid picture URL: ${req.body.picture}`);
            void reply.code(400);
            return { message: 'flash.wrong-updating', type: 'danger' } as const;
          }
        }
      }

      try {
        await fastify.prisma.user.update({
          where: { id: req.user?.id },
          data: {
            about: req.body.about,
            name: req.body.name,
            location: req.body.location,
            picture: req.body.picture
          }
        });

        return {
          message: 'flash.updated-about-me',
          type: 'success'
        } as const;
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/protected/settings.ts (TypeScript)

Code before:
      } catch (err) {
        logger.error(err);
        fastify.Sentry.captureException(err);
        void reply.code(500);
        await reply.send({ message: 'flash.wrong-updating', type: 'danger' });
      }
    }
  );

  fastify.put(
    '/update-my-about',
    {
      schema: schemas.updateMyAbout
    },
    async (req, reply) => {
      const logger = fastify.log.child({ req, res: reply });

      // No need to validate if picture is being deleted.
      if (req.body.picture) {
        const currentUser = await fastify.prisma.user.findUnique({
          where: { id: req.user?.id },
          select: { picture: true }
        });

        // Only validate if the picture is actually different
        if (req.body.picture !== currentUser?.picture) {
          if (!isValidPictureUrl(req.body.picture)) {
            logger.warn(`Invalid picture URL: ${req.body.picture}`);
            void reply.code(400);
            return { message: 'flash.wrong-updating', type: 'danger' } as const;
          }
        }
      }

      try {
        await fastify.prisma.user.update({
          where: { id: req.user?.id },
          data: {
            about: req.body.about,
            name: req.body.name,
            location: req.body.location,
            picture: req.body.picture
          }
        });

        return {
          message: 'flash.updated-about-me',
          type: 'success'
        } as const;
      } catch (err) {
        logger.error(err);

Review comment (suggestion):
```suggestion
        if (req.body.picture !== req.user!.picture) {
```

Code after:
      } catch (err) {
        logger.error(err);
        fastify.Sentry.captureException(err);
        void reply.code(500);
        await reply.send({ message: 'flash.wrong-updating', type: 'danger' });
      }
    }
  );

  fastify.put(
    '/update-my-about',
    {
      schema: schemas.updateMyAbout
    },
    async (req, reply) => {
      const logger = fastify.log.child({ req, res: reply });

      // No need to validate if picture is being deleted.
      if (req.body.picture) {
        if (req.body.picture !== req.user!.picture) {
          if (!isValidPictureUrl(req.body.picture)) {
            logger.warn(`Invalid picture URL: ${req.body.picture}`);
            void reply.code(400);
            return { message: 'flash.wrong-updating', type: 'danger' } as const;
          }
        }
      }

      try {
        await fastify.prisma.user.update({
          where: { id: req.user?.id },
          data: {
            about: req.body.about,
            name: req.body.name,
            location: req.body.location,
            picture: req.body.picture
          }
        });

        return {
          message: 'flash.updated-about-me',
          type: 'success'
        } as const;
      } catch (err) {
        logger.error(err);
        fastify.Sentry.captureException(err);
        void reply.code(500);
        return { message: 'flash.wrong-updating', type: 'danger' } as const;
      }
    }
  );
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/helpers/auth-helpers.test.ts (TypeScript)

Code before:
    test('should not prevent user creation if drip campaign record creation fails', async () => {
      fastify.gb.isOn = vi.fn(() => true);

      // Mock dripCampaign.create to throw an error
      const createSpy = vi
        .spyOn(fastify.prisma.dripCampaign, 'create')
        .mockRejectedValueOnce(new Error('Database error'));

      const user = await findOrCreateUser(fastify, email);

      expect(user).toBeDefined();
      expect(user.id).toBeTruthy();

      // Verify error was captured by Sentry
      expect(captureException).toHaveBeenCalledTimes(1);
      expect(captureException).toHaveBeenCalledWith(
        expect.objectContaining({
          message: 'Database error'
        })
      );

      createSpy.mockRestore();
    });

    test('should not create drip campaign for existing users', async () => {
      fastify.gb.isOn = vi.fn(() => true);

      // Create user first
      await fastify.prisma.user.create({ data: createUserInput(email) });

      // Call findOrCreateUser for existing user
      await findOrCreateUser(fastify, email);

      // Verify no drip campaign record was created
      const dripCampaigns = await fastify.prisma.dripCampaign.findMany({
        where: { email }
      });

      expect(dripCampaigns).toHaveLength(0);
    });
  });
});


Review comment (suggestion):
```suggestion
      vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true);
```

Code after:
        where: { userId: user.id }
      });

      expect(dripCampaign).toBeNull();
    });

    test('should not prevent user creation if drip campaign record creation fails', async () => {
      vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true);

      // Mock dripCampaign.create to throw an error
      const createSpy = vi
        .spyOn(fastify.prisma.dripCampaign, 'create')
        .mockRejectedValueOnce(new Error('Database error'));

      const user = await findOrCreateUser(fastify, email);

      expect(user).toBeDefined();
      expect(user.id).toBeTruthy();

      // Verify error was captured by Sentry
      expect(captureException).toHaveBeenCalledTimes(1);
      expect(captureException).toHaveBeenCalledWith(
        expect.objectContaining({
          message: 'Database error'
        })
      );

      createSpy.mockRestore();
    });

    test('should not create drip campaign for existing users', async () => {
      vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true);

      // Create user first
      await fastify.prisma.user.create({ data: createUserInput(email) });

      // Call findOrCreateUser for existing user
      await findOrCreateUser(fastify, email);

      // Verify no drip campaign record was created
      const dripCampaigns = await fastify.prisma.dripCampaign.findMany({
        where: { email }
      });

      expect(dripCampaigns).toHaveLength(0);
    });
  });
});
Repository: freeCodeCamp/freeCodeCamp
File: curriculum/.lintstagedrc.mjs (JavaScript)

Code before:
/* eslint-disable filenames-simple/naming-convention */
import path from 'node:path';

import { createLintStagedConfig } from '@freecodecamp/eslint-config/lintstaged';

const linterConfigPath = path.resolve(
  import.meta.dirname,
  './challenges/.markdownlint.yaml'
);

export default {
  ...createLintStagedConfig(import.meta.dirname),
  './challenges/**/*.md': files =>
    files.map(
      filename =>
        `pnpm challenge-linter --config=${linterConfigPath} '${filename}'`
    )
};


Review comment (suggestion):
```suggestion
import path from 'node:path';
import { createLintStagedConfig } from '@freecodecamp/eslint-config/lintstaged';
```

Code after:
/* eslint-disable filenames-simple/naming-convention */
import path from 'node:path';
import { createLintStagedConfig } from '@freecodecamp/eslint-config/lintstaged';

const linterConfigPath = path.resolve(
  import.meta.dirname,
  './challenges/.markdownlint.yaml'
);

export default {
  ...createLintStagedConfig(import.meta.dirname),
  './challenges/**/*.md': files =>
    files.map(
      filename =>
        `pnpm challenge-linter --config=${linterConfigPath} '${filename}'`
    )
};
Repository: freeCodeCamp/freeCodeCamp
File: client/src/templates/Challenges/exam-download/show.tsx (TypeScript)

Code before:
import { createSelector } from 'reselect';
import { connect } from 'react-redux';
import Spinner from 'react-spinkit';

import LearnLayout from '../../../components/layouts/learn';
import ChallengeTitle from '../components/challenge-title';
import useDetectOS, { type UserOSState } from '../utils/use-detect-os';
import type {
  ChallengeNode,
  CompletedChallenge,
  User
} from '../../../redux/prop-types';
import {
  completedChallengesSelector,
  isSignedInSelector,
  userSelector
} from '../../../redux/selectors';
import { examAttempts } from '../../../utils/ajax';
import MissingPrerequisites from '../exam/components/missing-prerequisites';
import { isChallengeCompletedSelector } from '../redux/selectors';
import envData from '../../../../config/env.json';
import { Attempts } from './attempts';
import ExamTokenControls from './exam-token-controls';

import './show.css';
import { Link } from '../../../components/helpers';
import { SuperBlocks } from '@freecodecamp/shared/config/curriculum';

const { deploymentEnv } = envData;

interface GitProps {
  tag_name: string;
  assets: {
    browser_download_url: string;
  }[];
  name: string;
  draft: boolean;
  prerelease: boolean;
}

function PrerequisitesCallout({
  id,
  completedChallenges,
  nodes,
  examSuperBlock,
  isSignedIn,
  isHonest
}: ExamPrerequisitesProps & {
  isSignedIn: boolean;
  isHonest: boolean;
}) {

Review comment (refactor):
```suggestion
import { Link, Loader } from '../../../components/helpers';
```

Code after:
import { createSelector } from 'reselect';
import { connect } from 'react-redux';

import LearnLayout from '../../../components/layouts/learn';
import ChallengeTitle from '../components/challenge-title';
import useDetectOS, { type UserOSState } from '../utils/use-detect-os';
import type {
  ChallengeNode,
  CompletedChallenge,
  User
} from '../../../redux/prop-types';
import {
  completedChallengesSelector,
  isSignedInSelector,
  userSelector
} from '../../../redux/selectors';
import { examAttempts } from '../../../utils/ajax';
import MissingPrerequisites from '../exam/components/missing-prerequisites';
import { isChallengeCompletedSelector } from '../redux/selectors';
import envData from '../../../../config/env.json';
import { Attempts } from './attempts';
import ExamTokenControls from './exam-token-controls';

import './show.css';
import { Link, Loader } from '../../../components/helpers';
import { SuperBlocks } from '@freecodecamp/shared/config/curriculum';

const { deploymentEnv } = envData;

interface GitProps {
  tag_name: string;
  assets: {
    browser_download_url: string;
  }[];
  name: string;
  draft: boolean;
  prerelease: boolean;
}

function PrerequisitesCallout({
  id,
  completedChallenges,
  challenges,
  examSuperBlock,
  isSignedIn,
  isHonest
}: ExamPrerequisitesProps & {
  isSignedIn: boolean;
  isHonest: boolean;
}) {
  const { t } = useTranslation();