Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

chore: ingest 2024 challenge script (#1655)

bautistaaadd45748d1691
diff --git a/apps/aot/src/app/events/[year]/[day]/layout.tsx b/apps/aot/src/app/events/[year]/[day]/layout.tsx
index 56bb0d55..b2b4fd94 100644
--- a/apps/aot/src/app/events/[year]/[day]/layout.tsx
+++ b/apps/aot/src/app/events/[year]/[day]/layout.tsx
@@ -6,6 +6,7 @@ import { TrackVisibiltyProvider } from './use-track-visibility.hook';
import { buildMetaForEventPage } from '~/utils/metadata';
import { isChallengeUnlocked } from '~/utils/time-utils';
import { notFound } from 'next/navigation';
+import { getAllFlags } from '~/utils/feature-flag';
interface Props {
params: {
@@ -27,7 +28,8 @@ export default async function LayoutData({
children: React.ReactNode;
params: { year: string; day: string };
}) {
- if (!isChallengeUnlocked(Number(year), Number(day))) {
+ const { unlockAotChallenges } = await getAllFlags();
+ if (!isChallengeUnlocked(Number(year), Number(day)) && !unlockAotChallenges) {
return notFound();
}
// we do the same query in page.tsx..
diff --git a/apps/aot/src/utils/feature-flag.ts b/apps/aot/src/utils/feature-flag.ts
index 205bf5df..a92fc6ce 100644
--- a/apps/aot/src/utils/feature-flag.ts
+++ b/apps/aot/src/utils/feature-flag.ts
@@ -9,6 +9,7 @@ export const mockFlags = {
enableHolidayEvent: true,
enableAotPlatform: true,
enableAotLandingPage: true,
+ unlockAotChallenges: true,
};
export async function getAllFlags() {
diff --git a/packages/db/package.json b/packages/db/package.json
index fd544df3..410fc5e2 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -25,6 +25,7 @@
"db:seed": "dotenv -e ../../.env tsx ./seed/dev.ts",
"db:prod:seed": "dotenv -e ../../.env tsx ./temp/populate-aot-challenges.ts && dotenv -e ../../.env tsx ./seed/prod.ts",
"db:leaderboard:seed": "dotenv -e ../../.env tsx ./seed/leaderboard.ts",
+ "db:aot:seed": "dotenv -e ../../.env tsx ./temp/aot-2024-ingest.ts",
"db:studio": "dotenv -e ../../.env prisma studio",
"format": "prettier . --check --cache --cache-location=\"node_modules/.cache/prettiercache\"",
"format:fix": "prettier . --write --cache --cache-location=\"node_modules/.cache/prettiercache\" --log-level=warn",
diff --git a/packages/db/temp/aot-2024-ingest.ts b/packages/db/temp/aot-2024-ingest.ts
new file mode 100644
index 00000000..d8cbd285
--- /dev/null
+++ b/packages/db/temp/aot-2024-ingest.ts
@@ -0,0 +1,135 @@
+import { type Prisma } from '@prisma/client';
+import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
+import { rm } from 'node:fs/promises';
+import path from 'node:path';
+import { simpleGit } from 'simple-git';
+import { prisma } from '../src';
+
+const token = process.env.MY_PAT;
+const repoOwner = 'dimitropoulos';
+const repoName = 'advent-of-typescript-2024';
+const repoUrl = `https://${token}:[email protected]/${repoOwner}/${repoName}.git`;
+const localDir = './.tmp/aot-2024';
+
+async function loadChallengesFromRepo() {
+ const git = simpleGit();
+ await git.clone(repoUrl, localDir, ['--depth', '1']);
+
+ const daysDir = path.join(localDir, 'days');
+
+ if (!existsSync(daysDir)) {
+ console.error(`The 'days' directory does not exist in the repository.`);
+ return;
+ }
+
+ const challengesToCreate: (Prisma.ChallengeCreateManyInput & { author: string })[] = [];
+
+ // Iterate through each subdirectory inside 'days'
+ const dayDirectories = readdirSync(daysDir).filter((item) => {
+ const itemPath = path.join(daysDir, item);
+ return statSync(itemPath).isDirectory();
+ });
+
+ for (const dayDir of dayDirectories) {
+ const dayPath = path.join(daysDir, dayDir);
+ const challengeToCreate: Prisma.ChallengeCreateManyInput & { author: string } = {
+ status: 'ACTIVE',
+ } as Prisma.ChallengeCreateManyInput & { author: string };
+
+ console.log(`\nContents of ${dayPath}:`);
+
+ // List all files in each day subdirectory
+ const files = readdirSync(dayPath);
+ files.forEach((file) => {
+ const filePath = path.join(dayPath, file);
+ const fileName = path.parse(filePath).name;
+ const fileContents = readFileSync(filePath, 'utf8');
+
+ console.log(`- ${fileName}:`);
+ console.log(fileContents);
+ console.log('---');
+ if (fileName === 'prompt') {
+ challengeToCreate.description = fileContents;
+ }
+ if (fileName === 'start') {
+ // replace the word export with nothing in fileContents
+ challengeToCreate.code = fileContents.replace('export ', '');
+ }
+ if (fileName === 'test') {
+ const filteredSolutionImport = fileContents
+ .split('\n')
+ .filter((line) => !line.includes('./solution'))
+ .join('\n');
+ challengeToCreate.tests = filteredSolutionImport;
+ }
+ if (fileName === 'metadata') {
+ const jsonData = JSON.parse(fileContents);
+ challengeToCreate.difficulty = jsonData.difficulty.toUpperCase();
+ challengeToCreate.name = jsonData.label;
+ challengeToCreate.slug = jsonData.id;
+ challengeToCreate.shortDescription = jsonData.description;
+ challengeToCreate.author = jsonData.author;
+ }
+ if (fileName === 'tsconfig') {
+ const jsonData = JSON.parse(fileContents);
+ console.log({ jsonData });
+ if (jsonData.compilerOptions != null) {
+ challengeToCreate.tsconfig = jsonData.compilerOptions;
+ }
+ }
+ });
+ challengesToCreate.push(challengeToCreate);
+ }
+
+ return challengesToCreate;
+}
+
+async function ingest() {
+ try {
+ const challengesToUpdateOrCreate = await loadChallengesFromRepo();
+
+ if (!challengesToUpdateOrCreate) {
+ console.error('No challenges to ingest.');
+ return;
+ }
+
+ const transactions = [];
+ for (const challenge of challengesToUpdateOrCreate) {
+ const author = await prisma.user.findFirstOrThrow({
+ where: {
+ name: challenge.author,
+ },
+ });
+ const { author: _, ...challengeWithoutAuthor } = challenge;
+ transactions.push(
+ prisma.challenge.upsert({
+ where: {
+ slug: challenge.slug,
+ },
+ update: {
+ ...challengeWithoutAuthor,
+ userId: author.id,
+ },
+ create: {
+ ...challengeWithoutAuthor,
+ userId: author.id,
+ },
+ }),
+ );
+ }
+
+ await prisma.$transaction(transactions);
+
+ await prisma.$disconnect();
+ } catch (error) {
+ console.error(error);
+ await prisma.$disconnect();
+ } finally {
+ await rm('./.tmp', {
+ recursive: true,
+ force: true,
+ });
+ }
+}
+
+ingest();
diff --git a/packages/ui/src/components/markdown.tsx b/packages/ui/src/components/markdown.tsx
index 30bad22a..bd26a267 100644
--- a/packages/ui/src/components/markdown.tsx
+++ b/packages/ui/src/components/markdown.tsx
@@ -120,6 +120,7 @@ export function Markdown({
}}
// FIXME: this is vuln to XSS and I don't know why we use it, let's remove it
// or add in a sanitizer lib like: https://github.com/rehypejs/rehype-sanitize
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
rehypePlugins={[rehypeRaw as any]}
remarkPlugins={[removeHtmlComments, remarkGfm, ...(disableMentions ? [] : [userMentions])]}
>