From 31248173b769057e225b1b6e53b5ce7e53dfe474 Mon Sep 17 00:00:00 2001 From: Carmen Wheeler Date: Sat, 26 Apr 2025 12:51:41 -0500 Subject: [PATCH] created modals, added fallback questions file and updated promptbuilder --- client/package-lock.json | 28 +- client/package.json | 4 +- client/src/components/BackgroundMusic.tsx | 42 +-- client/src/components/ModalBase.tsx | 33 +++ client/src/components/ModalBasel.tsx | 4 - client/src/components/NarrationModal.tsx | 30 ++- client/src/components/ResponseModal.tsx | 27 +- client/src/components/ui/dialog.tsx | 36 ++- client/src/lib/fallbackQuestions.ts | 142 ++++++++++ client/tailwind.config.js | 12 +- et --soft HEAD~1 | 30 +++ package-lock.json | 18 ++ package.json | 5 + server/models/Questions.ts | 13 + server/models/User.ts | 12 + server/routes/openai.ts | 102 +++---- server/seed.ts | 35 ++- server/src/utils/PromptBuilder.ts | 315 ++++++++++++---------- server/tsconfig.json | 8 +- 19 files changed, 612 insertions(+), 284 deletions(-) create mode 100644 client/src/components/ModalBase.tsx delete mode 100644 client/src/components/ModalBasel.tsx create mode 100644 client/src/lib/fallbackQuestions.ts create mode 100644 et --soft HEAD~1 diff --git a/client/package-lock.json b/client/package-lock.json index cf4bd40..1c3879c 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -9,9 +9,8 @@ "version": "0.0.0", "dependencies": { "@radix-ui/react-dialog": "^1.1.11", - "howler": "^2.2.4", "lucide-react": "^0.503.0", - "react": "^19.1.0", + "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { @@ -19,7 +18,6 @@ "@tailwindcss/postcss": "^4.1.4", "@types/react": "^19.0.10", "@types/react-dom": "^19.0.4", - "@types/react-howler": "^5.2.3", "@vitejs/plugin-react": "^4.3.4", "autoprefixer": "^10.4.21", "eslint": "^9.21.0", @@ -2006,13 +2004,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/howler": { - "version": "2.2.12", - "resolved": "https://registry.npmjs.org/@types/howler/-/howler-2.2.12.tgz", - "integrity": "sha512-hy769UICzOSdK0Kn1FBk4gN+lswcj1EKRkmiDtMkUGvFfYJzgaDXmVXkSShS2m89ERAatGIPnTUlp2HhfkVo5g==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -2040,17 +2031,6 @@ "@types/react": "^19.0.0" } }, - "node_modules/@types/react-howler": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/react-howler/-/react-howler-5.2.3.tgz", - "integrity": "sha512-0XJ+vHLgobVcc8G8f3jlnfIv3FVnUvEuxOyq3TwW9qNBeko7EhHDc9QYtY7mUTcrT86mPTAVCKWitY+TyzHWZw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/howler": "*", - "@types/react": "*" - } - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.31.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.31.0.tgz", @@ -3098,12 +3078,6 @@ "node": ">=8" } }, - "node_modules/howler": { - "version": "2.2.4", - "resolved": "https://registry.npmjs.org/howler/-/howler-2.2.4.tgz", - "integrity": "sha512-iARIBPgcQrwtEr+tALF+rapJ8qSc+Set2GJQl7xT1MQzWaVkFebdJhR3alVlSiUf5U7nAANKuj3aWpwerocD5w==", - "license": "MIT" - }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", diff --git a/client/package.json b/client/package.json index e5281a1..c27dfc3 100644 --- a/client/package.json +++ b/client/package.json @@ -11,9 +11,8 @@ }, "dependencies": { "@radix-ui/react-dialog": "^1.1.11", - "howler": "^2.2.4", "lucide-react": "^0.503.0", - "react": "^19.1.0", + "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { @@ -21,7 +20,6 @@ "@tailwindcss/postcss": "^4.1.4", "@types/react": "^19.0.10", "@types/react-dom": "^19.0.4", - "@types/react-howler": "^5.2.3", "@vitejs/plugin-react": "^4.3.4", "autoprefixer": "^10.4.21", "eslint": "^9.21.0", diff --git a/client/src/components/BackgroundMusic.tsx b/client/src/components/BackgroundMusic.tsx index 8401a32..bc86f9a 100644 --- a/client/src/components/BackgroundMusic.tsx +++ b/client/src/components/BackgroundMusic.tsx @@ -1,27 +1,27 @@ -import { useEffect } from 'react'; +// import { useEffect } from 'react'; -const BackgroundMusic = () => { - useEffect(() => { - const audio = new Audio('/80s-loop-5.wav'); // or '/background-music.mp3' - audio.loop = true; - audio.volume = 0.5; +// const BackgroundMusic = () => { +// useEffect(() => { +// const audio = new Audio('/80s-loop-5.wav'); // or '/background-music.mp3' +// audio.loop = true; +// audio.volume = 0.5; - // Try autoplay inside a user interaction-friendly trigger - const playAudio = () => { - audio.play().catch((err) => { - console.warn('Autoplay blocked by browser:', err); - }); - }; +// // Try autoplay inside a user interaction-friendly trigger +// const playAudio = () => { +// audio.play().catch((err) => { +// console.warn('Autoplay blocked by browser:', err); +// }); +// }; - // Listen for first click - document.body.addEventListener('click', playAudio, { once: true }); +// // Listen for first click +// document.body.addEventListener('click', playAudio, { once: true }); - return () => { - audio.pause(); - }; - }, []); +// return () => { +// audio.pause(); +// }; +// }, []); - return null; -}; +// return null; +// }; -export default BackgroundMusic; +// export default BackgroundMusic; diff --git a/client/src/components/ModalBase.tsx b/client/src/components/ModalBase.tsx new file mode 100644 index 0000000..ed6e0ec --- /dev/null +++ b/client/src/components/ModalBase.tsx @@ -0,0 +1,33 @@ +// src/components/ModalBase.tsx + +"use client"; + +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"; + +interface ModalBaseProps { + open: boolean; + onOpenChange: (open: boolean) => void; + title: string; + description?: string; + children?: React.ReactNode; +} + +const ModalBase = ({ open, onOpenChange, title, description, children }: ModalBaseProps) => { + return ( + + + + {title} + {description && ( + + {description} + + )} + + {children} + + + ); +}; + +export default ModalBase; diff --git a/client/src/components/ModalBasel.tsx b/client/src/components/ModalBasel.tsx deleted file mode 100644 index 58603f8..0000000 --- a/client/src/components/ModalBasel.tsx +++ /dev/null @@ -1,4 +0,0 @@ -ModalBase.tsx: -- Core styling and backdrop -- Accepts props: isOpen, content, onClose, variant -- Applies shared layout \ No newline at end of file diff --git a/client/src/components/NarrationModal.tsx b/client/src/components/NarrationModal.tsx index bba9540..e60fb14 100644 --- a/client/src/components/NarrationModal.tsx +++ b/client/src/components/NarrationModal.tsx @@ -1,3 +1,27 @@ -- Imports ModalBase -- Passes variant='narration' -- Can include avatar or sprite of Dr. Dan, text-only \ No newline at end of file +// src/components/NarrationModal.tsx + +"use client"; + +import ModalBase from "@/components/ModalBase"; + +interface NarrationModalProps { + isOpen: boolean; + onClose: () => void; + text: string; +} + +const NarrationModal = ({ isOpen, onClose, text }: NarrationModalProps) => { + return ( + { if (!open) onClose(); }} + title="Narration" + description={text} + > + {/* Optional: You can add more children here later if needed */} + + ); +}; + +export default NarrationModal; + diff --git a/client/src/components/ResponseModal.tsx b/client/src/components/ResponseModal.tsx index f13c0b9..da45528 100644 --- a/client/src/components/ResponseModal.tsx +++ b/client/src/components/ResponseModal.tsx @@ -1,4 +1,23 @@ -- Imports ModalBase -- Passes variant='response' -- Includes buttons for Try Again or Next -- Custom feedback messages \ No newline at end of file +"use client" + +import ModalBase from "@/components/ModalBase"; + +interface ResponseModalProps { + isOpen: boolean; + onClose: () => void; + text: string; + +} + +const ResponseModal = ({ isOpen, onClose, text }: ResponseModalProps) => { + return ( + { if(!open) onClose(); }} + title="Narration" + description={text} + > + + ); +}; +export default ResponseModal; \ No newline at end of file diff --git a/client/src/components/ui/dialog.tsx b/client/src/components/ui/dialog.tsx index f018786..620ea34 100644 --- a/client/src/components/ui/dialog.tsx +++ b/client/src/components/ui/dialog.tsx @@ -14,7 +14,7 @@ const DialogPortal = ({ ...props }: DialogPrimitive.DialogPortalProps) => ( ); const DialogOverlay = React.forwardRef< - React.ElementRef, + React.ComponentRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( , + React.ComponentRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( + ref={ref} + className={cn( + "fixed z-[70] left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-lg rounded-2xl bg-gradient-to-b from-blue-950 to-black text-white p-6 shadow-2xl ring-4 ring-blue-400/50 transition-all duration-500 ease-in-out animate-fadeIn", + className + )} + {...props} +> +
{children}
@@ -63,7 +64,7 @@ const DialogHeader = ({ DialogHeader.displayName = "DialogHeader"; const DialogTitle = React.forwardRef< - React.ElementRef, + React.ComponentRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( , + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogDescription.displayName = DialogPrimitive.Description.displayName; + export { Dialog, DialogTrigger, DialogContent, DialogHeader, - DialogTitle + DialogTitle, + DialogDescription }; diff --git a/client/src/lib/fallbackQuestions.ts b/client/src/lib/fallbackQuestions.ts new file mode 100644 index 0000000..1692caf --- /dev/null +++ b/client/src/lib/fallbackQuestions.ts @@ -0,0 +1,142 @@ +export interface FallbackQuestion { + question: string; + choices: string[]; + correctIndex: number; + } + +export const fallbackQuestion: Record = { + NullByte: [ + { + question: "What is the result of the expression `null + 1` in JavaScript?", + choices: ["1", "TypeError", "NaN", "undefined"], + correctIndex: 2, // "NaN" + }, + { + question: "Which of these values is *falsy* in JavaScript?", + choices: ["0", "'0'", "[]", "{}"], + correctIndex: 0, // 0 + }, + { + question: "How do you check if a variable `x` is exactly null (and not undefined)?", + choices: ["`x == null`", "`x === null`", "`typeof x === 'null'`", "`x instanceof Null`"], + correctIndex: 1, // x === null + }, + ], + + DeBug: [ + { + question: "What is wrong with this JavaScript code?\n\n```js\nlet num = 5;\nconsole.log(numm);\n```", + choices: [ + "SyntaxError", + "ReferenceError", + "TypeError", + "The code runs and logs undefined" + ], + correctIndex: 1, + }, + { + question: "What bug is in this if-statement?\n\n```js\nif (x = 5) {\n console.log(\"Equal!\");\n}\n```", + choices: [ + "It will throw an error", + "It will always be false", + "It assigns instead of compares", + "It compares incorrectly but still works" + ], + correctIndex: 2, + }, + { + question: "What will this function log?\n\n```js\nfunction greet() {\n \"Hello World\";\n}\nconsole.log(greet());\n```", + choices: [ + "Hello World", + "undefined", + "null", + "ReferenceError" + ], + correctIndex: 1, + } + ], + Python: [ + { + question: "What type of value does the expression `3.14` have in Python?", + choices: ["int", "str", "float", "bool"], + correctIndex: 2, + }, + { + question: "Which keyword is used to loop over a sequence in Python?", + choices: ["loop", "iterate", "for", "while"], + correctIndex: 2, + }, + { + question: "What is the value of `my_list[1]`?\n\n```python\nmy_list = [10, 20, 30]\n```", + choices: ["10", "20", "30", "Error"], + correctIndex: 1, + }, +], +Typerroruss: [ + { + question: "What happens if you try to call `.toUpperCase()` on an undefined value in JavaScript?", + choices: [ + "It returns undefined", + "It throws a TypeError", + "It logs 'undefined'", + "It returns null" + ], + correctIndex: 1, + }, + { + question: "What is the result of this JavaScript expression?\n\n```js\n'5' + 3\n```", + choices: [ + "'8'", + "'53'", + "8", + "Error" + ], + correctIndex: 1, + }, + { + question: "What happens if you access a property on `null` in JavaScript?", + choices: [ + "It throws a ReferenceError", + "It throws a TypeError", + "It returns null", + "It returns undefined" + ], + correctIndex: 1, + } +], +Codezilla: [ + { + question: "In a MongoDB query, what does the `$set` operator do?", + choices: [ + "Deletes fields from a document", + "Adds a new document to the collection", + "Updates specific fields in a document", + "Finds documents that match a condition" + ], + correctIndex: 2, + }, + { + question: "In React, why is providing a unique `key` prop important when rendering lists?", + choices: [ + "It helps React optimize rendering", + "It makes the list sortable", + "It binds event handlers automatically", + "It prevents API calls" + ], + correctIndex: 0, + }, + { + question: "What happens if error-handling middleware is placed before route handlers in Express?", + choices: [ + "It will not catch any errors", + "It will prevent routes from being reached", + "It will automatically reroute to '/'", + "It improves performance" + ], + correctIndex: 1, + } +], +} + + + diff --git a/client/tailwind.config.js b/client/tailwind.config.js index b5a69a8..6be31eb 100644 --- a/client/tailwind.config.js +++ b/client/tailwind.config.js @@ -5,7 +5,17 @@ module.exports = { "./src/**/*.{js,ts,jsx,tsx}", ], theme: { - extend: {}, + extend: { + keyframes: { + fadeIn: { + '0%': { opacity: 0 }, + '100%': { opacity: 1}, + }, + }, + animation: { + fadeIn: 'fadeIn 0.5s ease-in-out', + }, + }, }, plugins: [], } diff --git a/et --soft HEAD~1 b/et --soft HEAD~1 new file mode 100644 index 0000000..4848843 --- /dev/null +++ b/et --soft HEAD~1 @@ -0,0 +1,30 @@ +4724f5b (HEAD -> feature/Modals) HEAD@{0}: commit: committing to pull +9f2756b (group-origin/main, group-origin/HEAD) HEAD@{1}: pull group-origin main: Fast-forward +2e42503 (group-origin/feature/tts-integration, tts) HEAD@{2}: reset: moving to HEAD +2e42503 (group-origin/feature/tts-integration, tts) HEAD@{3}: checkout: moving from main to feature/Modals +9631bfb (main) HEAD@{4}: reset: moving to HEAD +9631bfb (main) HEAD@{5}: pull group-origin main: Fast-forward +9409cce HEAD@{6}: checkout: moving from feature/Modals to main +2e42503 (group-origin/feature/tts-integration, tts) HEAD@{7}: reset: moving to HEAD +2e42503 (group-origin/feature/tts-integration, tts) HEAD@{8}: reset: moving to HEAD~1 +5e2b808 HEAD@{9}: commit: added minion to promptbuilder and beginning code for models +2e42503 (group-origin/feature/tts-integration, tts) HEAD@{10}: checkout: moving from main to feature/Modals +9409cce HEAD@{11}: reset: moving to HEAD +9409cce HEAD@{12}: checkout: moving from feature/Modals to main +2e42503 (group-origin/feature/tts-integration, tts) HEAD@{13}: checkout: moving from tts to feature/Modals +2e42503 (group-origin/feature/tts-integration, tts) HEAD@{14}: commit: updated gitignore +82dd80c HEAD@{15}: commit (merge): Merge group main with my changes +c7b497a HEAD@{16}: commit: initial commit +944ba98 HEAD@{17}: pull origin main: Merge made by the 'ort' strategy. +5565cb0 (origin/tts) HEAD@{18}: reset: moving to HEAD +5565cb0 (origin/tts) HEAD@{19}: commit: created tts for characters +fe4b593 (origin/modals, modals) HEAD@{20}: checkout: moving from modals to tts +fe4b593 (origin/modals, modals) HEAD@{21}: commit: set up dir tree +f21ef68 HEAD@{22}: commit: updated code structure with modals, added tailwind framework and installs for testing modals +dc5f79c (origin/OpenAI, OpenAI) HEAD@{23}: checkout: moving from OpenAI to modals +dc5f79c (origin/OpenAI, OpenAI) HEAD@{24}: commit: added speech model to server +2b056df HEAD@{25}: commit: Added openai route, index.ts, promptbuilder +9409cce HEAD@{26}: checkout: moving from main to OpenAI +9409cce HEAD@{27}: commit: initial commit +f853f34 HEAD@{28}: Branch: renamed refs/heads/master to refs/heads/main +f853f34 HEAD@{30}: commit (initial): first commit diff --git a/package-lock.json b/package-lock.json index 251124c..203733b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,15 @@ "@types/express": "^5.0.1", "@types/node": "^22.14.1", "concurrently": "^9.1.2", +<<<<<<< Updated upstream "nodemon": "^3.1.10", +======= + "nodemon": "^3.1.9", + "tailwindcss": "^4.1.4", +<<<<<<< Updated upstream +>>>>>>> Stashed changes +======= +>>>>>>> Stashed changes "ts-node": "^10.9.2", "typescript": "^5.8.3" } @@ -2970,6 +2978,7 @@ "dev": true, "license": "MIT" }, +<<<<<<< Updated upstream "node_modules/tapable": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", @@ -2980,6 +2989,15 @@ "node": ">=6" } }, + "node_modules/tailwindcss": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.4.tgz", + "integrity": "sha512-1ZIUqtPITFbv/DxRmDr5/agPqJwF69d24m9qmM1939TJehgY539CtzeZRjbLt5G6fSy/7YqqYsfvoTEw9xUI2A==", + "dev": true, + "license": "MIT" + }, +======= +>>>>>>> Stashed changes "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", diff --git a/package.json b/package.json index 6d276d1..dbc7b61 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,12 @@ "@types/express": "^5.0.1", "@types/node": "^22.14.1", "concurrently": "^9.1.2", +<<<<<<< Updated upstream "nodemon": "^3.1.10", +======= + "nodemon": "^3.1.9", +>>>>>>> Stashed changes + "tailwindcss": "^4.1.4", "ts-node": "^10.9.2", "typescript": "^5.8.3" } diff --git a/server/models/Questions.ts b/server/models/Questions.ts index e69de29..f97b58d 100644 --- a/server/models/Questions.ts +++ b/server/models/Questions.ts @@ -0,0 +1,13 @@ +import mongoose, { Schema, Document } from "mongoose"; + +export interface IQuestion extends Document { + prompt: string; + difficulty: "easy" | "medium" | "hard"; +} + +const QuestionSchema: Schema = new Schema({ + prompt: { type: String, required: true }, + difficulty: { type: String, enum: ["easy", "medium", "hard"], required: true }, +}); + +export const Question = mongoose.model("Question", QuestionSchema); \ No newline at end of file diff --git a/server/models/User.ts b/server/models/User.ts index e69de29..56a6421 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -0,0 +1,12 @@ +// Ensure this file exports the User model +import mongoose from "mongoose"; + +const userSchema = new mongoose.Schema({ + username: String, + email: String, + password: String, +}); + +const User = mongoose.model("User", userSchema); + +export { User }; // Export the User model \ No newline at end of file diff --git a/server/routes/openai.ts b/server/routes/openai.ts index 996dc29..6bf0fba 100644 --- a/server/routes/openai.ts +++ b/server/routes/openai.ts @@ -7,65 +7,67 @@ import dotenv from 'dotenv'; dotenv.config(); const router = express.Router(); + +/** + * Parses the OpenAI response into a structured format. + * @param rawResponse - The raw response content from OpenAI. + * @returns A structured question object. + */ +function parseOpenAIResponse(rawResponse: string): GeneratedQuestion { + // Example parsing logic (adjust as needed based on actual response format) + const [question, ...choicesAndAnswer] = rawResponse.split('\n').filter(Boolean); + const choices = choicesAndAnswer.slice(0, -1); + const answer = choicesAndAnswer[choicesAndAnswer.length - 1]; + return { question, choices, answer }; +} const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); -/** Existing route: generate a coding question */ -router.post('/generate-question', async (req: Request, res: Response) : Promise => { - try { - const { track, level } = req.body; - if (!track || !level) { - res.status(400).json({ error: 'Missing track or level' }); - return; +type GeneratedQuestion = { + question: string; + choices: string[]; + answer: string; +}; + +/** Generate a coding question via OpenAI, with fallback */ +router.post( + '/generate-question', + async (req: Request, res: Response) : Promise => { + const { track, level, minion } = req.body; + if (!track || !level || !minion) { + res.status(400).json({ error: 'Missing track, level, or minion' }); + return; } + // Build the LLM prompt const prompt = PromptBuilder.getPrompt(track, level); - const completion = await openai.chat.completions.create({ - model: 'gpt-3.5-turbo', - messages: [{ role: 'user', content: prompt }], - max_tokens: 250, - }); - - const question = completion.choices[0].message.content; - res.json({ question }); - } catch (error) { - console.error(error); - res.status(500).json({ error: 'Failed to generate a question' }); - } -}); -type Character = 'Dr. Dan' | 'Nullbyte' | 'Pie-thon' | "D'Bug" | 'Codezilla'; -/** New route: generate speech for character */ -router.post('/tts', async (req: Request, res: Response): Promise => { - const { text, character } = req.body; + try { + const completion = await openai.chat.completions.create({ + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: prompt }], + max_tokens: 250, + }); - if (!text) { - res.status(400).json({ error: "Missing 'text'" }); - return; - } - - try { - const voiceMap = { - "Dr. Dan": "echo", - "Codezilla": "echo", - "Nullbyte": "nova", - "D'Bug": "shimmer" - }; + // Parse the raw text into structured question/choices/answer + const raw = completion.choices[0].message.content ?? ''; + const parsed = parseOpenAIResponse(raw); - const voice = voiceMap[character as keyof typeof voiceMap] || "echo"; + res.json(parsed); + } catch (err) { + console.error('OpenAI failed, falling back:', err); - const speech = await openai.audio.speech.create({ - model: 'tts-1', - voice, - input: text - }); + // Fallback: pick a hard-coded question + const fb = PromptBuilder.getFallbackQuestion(minion); - const buffer = Buffer.from(await speech.arrayBuffer()); - res.set({ "Content-Type": "audio/mpeg" }); - res.send(buffer); - } catch (err) { - console.error("TTS route error:", err); - res.status(500).json({ error: "Failed to generate speech." }); + res.json({ + question: fb.question, + choices: fb.choices, + answer: fb.choices[fb.correctIndex], + }); + } } -}); +); + +// ... your existing /tts route ... -export default router; \ No newline at end of file +export default router; diff --git a/server/seed.ts b/server/seed.ts index 646ef66..b43fbdb 100644 --- a/server/seed.ts +++ b/server/seed.ts @@ -1,22 +1,29 @@ import mongoose from "mongoose"; import dotenv from "dotenv"; -import { User } from "./models/User.ts"; -import { Question } from "./models/Question"; +import { User } from "./models/User"; +import { Question } from "./models/Questions"; // Ensure the file './models/Question.ts' exists and exports 'Question' dotenv.config(); -await mongoose.connect(process.env.MONGODB_URI!); +async function seedDatabase() { + await mongoose.connect(process.env.MONGODB_URI!); -// Wipe collections -await User.deleteMany({}); -await Question.deleteMany({}); + // Wipe collections + await User.deleteMany({}); + await Question.deleteMany({}); -// Seed data -await User.create({ username: "playerOne", email: "player@example.com", password: "123456" }); -await Question.insertMany([ - { prompt: "Explain closures in JavaScript", difficulty: "hard" }, - { prompt: "What is a component in React?", difficulty: "easy" } -]); + // Seed data + await User.create({ username: "playerOne", email: "player@example.com", password: "123456" }); + await Question.insertMany([ + { prompt: "Explain closures in JavaScript", difficulty: "hard" }, + { prompt: "What is a component in React?", difficulty: "easy" } + ]); -console.log("🌱 Seeding complete!"); -mongoose.connection.close(); + console.log("🌱 Seeding complete!"); + mongoose.connection.close(); +} + +seedDatabase().catch((error) => { + console.error("Error seeding database:", error); + mongoose.connection.close(); +}); diff --git a/server/src/utils/PromptBuilder.ts b/server/src/utils/PromptBuilder.ts index d56e25c..e950c74 100644 --- a/server/src/utils/PromptBuilder.ts +++ b/server/src/utils/PromptBuilder.ts @@ -1,146 +1,175 @@ +import { fallbackQuestions, FallbackQuestion } from "@/utils/fallbackQuestions"; + export class PromptBuilder { - static getPrompt(track: string, level: string): string { - // Choose minion based on level - switch (level) { - case 'easy': - return this.nullbytePrompt(track); - case 'medium': - return this.debugPrompt(track); - case 'hard': - return this.pythonPrompt(track); - case 'boss': - return this.codezillaPrompt(track); - default: - return this.genericPrompt(track, level); - } - } - - private static genericPrompt(track: string, level: string): string { - return ` - Generate a concise ${level} JavaScript multiple-choice coding question for a ${track}-level developer. - - Requirements: - - Focus on real-world coding concepts. - - Limit the question to 2 sentences max. - - Include 4 answer choices labeled A through D. - - Clearly indicate the correct answer at the end using: "Correct Answer: B" - - Format: - Question: ... - A) ... - B) ... - C) ... - D) ... - Correct Answer: ... - `; - } - - private static nullbytePrompt(track: string): string { - return ` - You're facing **Nullbyte**, the minion of bugs and broken logic. - - Generate an **easy-level** HTML, JavaScript, CSS multiple-choice coding question that focuses on **debugging or fixing broken code** for a ${track}-level developer. - - Requirements: - - Limit to 2 sentences max. - - Use a real JavaScript bug or common mistake (like misuse of == vs ===, off-by-one errors, etc). - - Provide 4 answer options labeled A-D. - - Indicate the correct answer at the end using: "Correct Answer: X" - - Format: - Question: ... - A) ... - B) ... - C) ... - D) ... - Correct Answer: ... - `; - } - - private static debugPrompt(track: string): string { - return ` - You're facing **D'bug**, the glitchy minion of confusion. - - Generate a **medium-level** multiple-choice JavaScript coding question that challenges the player to understand code behavior, logic, or flow — suitable for a ${track}-level developer. - - Requirements: - - Limit the question to 2 sentences max. - - Avoid fantasy themes. - - Provide 4 answer choices labeled A-D. - - End with "Correct Answer: X" - - Format: - Question: ... - A) ... - B) ... - C) ... - D) ... - Correct Answer: ... - `; - } - - private static pythonPrompt(track: string): string { - return ` - You’re up against **Pie-thon**, the toughest minion before the boss. - - Generate a **hard-level** Python multiple-choice question involving complex concepts (e.g. closures, asynchronous behavior, or prototypes), aimed at a ${track}-level developer. - - Requirements: - - Be concise (2 sentences max). - - Provide 4 answer options labeled A-D. - - Clearly indicate the correct answer. - - Format: - Question: ... - A) ... - B) ... - C) ... - D) ... - Correct Answer: ... - `; - } - - private static codezillaPrompt(track: string): string { - return ` - This is the final challenge: **Codezilla**, the boss monster of code. - - Generate a **boss-level** multiple-choice MERN Stack question that requires deep understanding of advanced topics (e.g. event loop, execution context, performance optimization), tailored for a ${track}-level developer. - - Requirements: - - Keep it under 2 sentences. - - Avoid fantasy language and be strictly technical. - - Include 4 choices labeled A-D and mark the correct answer. - - Format: - Question: ... - A) ... - B) ... - C) ... - D) ... - Correct Answer: ... - `; - } + /** + * Return the appropriate LLM prompt based on difficulty level + */ + static getPrompt(track: string, level: string): string { + switch (level) { + case 'easy': + return this.nullbytePrompt(track); + case 'medium': + return this.debugPrompt(track); + case 'hard': + return this.pythonPrompt(track); + case 'boss': + return this.codezillaPrompt(track); + default: + return this.genericPrompt(track, level); + } } - export function parseOpenAIResponse(raw: string) { - const lines = raw.split('\n').map(line => line.trim()).filter(line => line !== ''); - - let question = ''; - const choices: string[] = []; - let answer = ''; - - for (const line of lines) { - if (line.toLowerCase().startsWith('question:')) { - question = line.replace(/^question:\s*/i, '').trim(); - } else if (/^[a-dA-D]\)/.test(line)) { - choices.push(line); - } else if (line.toLowerCase().startsWith('correct answer')) { - const match = line.match(/[A-D]/i); - if (match) { - answer = match[0].toUpperCase(); - } - } - } - - return { question, choices, answer }; + + /** + * Generic prompt for unspecified levels + */ + private static genericPrompt(track: string, level: string): string { + return ` +Generate a concise ${level} JavaScript multiple-choice coding question for a ${track}-level developer. + +Requirements: +- Focus on real-world coding concepts. +- Limit the question to 2 sentences max. +- Include 4 answer choices labeled A through D. +- Clearly indicate the correct answer at the end using: "Correct Answer: B" + +Format: +Question: ... +A) ... +B) ... +C) ... +D) ... +Correct Answer: ... +`; } - \ No newline at end of file + + /** + * Easy-level question prompt for NullByte + */ + private static nullbytePrompt(track: string): string { + return ` +You're facing **NullByte**, the minion of bugs and broken logic. + +Generate an **easy-level** HTML, JavaScript, or CSS multiple-choice coding question that focuses on **debugging or fixing broken code** for a ${track}-level developer. + +Requirements: +- Limit to 2 sentences max. +- Use a real JavaScript bug or common mistake (like misuse of == vs ===, off-by-one errors, etc). +- Provide 4 answer options labeled A-D. +- Indicate the correct answer at the end using: "Correct Answer: X" + +Format: +Question: ... +A) ... +B) ... +C) ... +D) ... +Correct Answer: ... +`; + } + + /** + * Medium-level debugging prompt + */ + private static debugPrompt(track: string): string { + return ` +You're facing **D'bug**, the glitchy minion of confusion. + +Generate a **medium-level** multiple-choice JavaScript coding question that challenges the player to understand code behavior, logic, or flow — suitable for a ${track}-level developer. + +Requirements: +- Limit the question to 2 sentences max. +- Avoid fantasy themes. +- Provide 4 answer choices labeled A-D. +- End with "Correct Answer: X" + +Format: +Question: ... +A) ... +B) ... +C) ... +D) ... +Correct Answer: ... +`; + } + + /** + * Hard-level Python prompt + */ + private static pythonPrompt(track: string): string { + return ` +You’re up against **Pie-thon**, the toughest minion before the boss. + +Generate a **hard-level** Python multiple-choice question involving complex concepts (e.g. closures, asynchronous behavior, or prototypes), aimed at a ${track}-level developer. + +Requirements: +- Be concise (2 sentences max). +- Provide 4 answer options labeled A-D. +- Clearly indicate the correct answer. + +Format: +Question: ... +A) ... +B) ... +C) ... +D) ... +Correct Answer: ... +`; + } + + /** + * Boss-level Codezilla prompt + */ + private static codezillaPrompt(track: string): string { + return ` +This is the final challenge: **Codezilla**, the boss monster of code. + +Generate a **boss-level** multiple-choice MERN Stack question that requires deep understanding of advanced topics (e.g. event loop, execution context, performance optimization), tailored for a ${track}-level developer. + +Requirements: +- Keep it under 2 sentences. +- Avoid fantasy language and be strictly technical. +- Include 4 choices labeled A-D and mark the correct answer. + +Format: +Question: ... +A) ... +B) ... +C) ... +D) ... +Correct Answer: ... +`; + } + + /** + * If the LLM API fails, pick a random fallback question + */ + static getFallbackQuestion(minionName: string): FallbackQuestion { + const pool = fallbackQuestions[minionName] || []; + const idx = Math.floor(Math.random() * pool.length); + return pool[idx]; + } +} + +/** + * Parses the raw OpenAI response into question, choices, and answer + */ +export function parseOpenAIResponse(raw: string) { + const lines = raw.split("\n").map(line => line.trim()).filter(Boolean); + + let question = ""; + const choices: string[] = []; + let answer = ""; + + for (const line of lines) { + if (/^question:/i.test(line)) { + question = line.replace(/^question:\s*/i, ""); + } else if (/^[A-D]\)/.test(line)) { + choices.push(line); + } else if (/^correct answer:/i.test(line)) { + const match = line.match(/[A-D]/i); + if (match) answer = match[0].toUpperCase(); + } + } + + return { question, choices, answer }; +} diff --git a/server/tsconfig.json b/server/tsconfig.json index 904d43f..c5b78a2 100644 --- a/server/tsconfig.json +++ b/server/tsconfig.json @@ -27,10 +27,12 @@ /* Modules */ "module": "commonjs", /* Specify what module code is generated. */ + "baseUrl": "./", /* Set the base directory for resolving non-relative module names. */ + "paths": { /* Map module paths to specific directories. */ + "@/*": ["src/*"] + }, // "rootDir": "./", /* Specify the root folder within your source files. */ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ // "types": [], /* Specify type package names to be included without being referenced in a source file. */ @@ -110,4 +112,4 @@ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ } -} +} \ No newline at end of file