Contributor Playbook & MDX Elements
This page is the living documentation for maintaining and expanding CSPrimer. It serves seven key functions:
- Local Scaffolding Tools: One-click visual dashboard and terminal CLI to generate courses, roadmaps, and articles.
- Metadata Architecture: Clear rules for how Categories, Series, and Roadmaps relate.
- Complete Schemas & Type Reference: Exhaustive specifications of all collection schemas, allowed values, and TypeScript types.
- Interactive Component Showcase: Live preview, props reference, and copy-pasteable snippets for custom MDX components.
- Algorithm Visualizer Playbook & AI Prompt Template: Copy-pasteable prompt and architecture guide to generate visualizers for any Java DSA problem using LLMs.
- Infrastructure, Hosting & Deployment Architecture: Production setup across Vercel, Cloudflare DNS, Cloudinary CDN, and domain canonicalization.
- Performance & Scale Engineering: Micro-chunking for 500+ visualizers, memory leak prevention under ViewTransitions, and build optimizations.
1. Automated Local Scaffolding
To eliminate tedious manual JSON updates and frontmatter mistakes, use our local scaffolding tools:
- Web Dashboard (Visual)
- Terminal CLI
Visual Content Studio (npm run admin)
Run the local Dev Studio dashboard alongside your Astro dev server:
npm run admin
Open http://localhost:4322 in your browser.
- Tab 1: Course Series Cards: Interactive card grid of all 45 courses to set status (
🟢 Live,⏳ In Progress,🔒 Planned,🔁 Revisiting), and edit details (title, description, time, weight). - Tab 2: Syllabus & Lessons: Organize chapters and lessons with
▲/▼reordering, accurate status toggles, and detection of unassigned files on disk. - Tab 3: Create Lesson / Project: Smart switcher between Course Lesson (category strictly locked to course track), Hands-on Project (surfaced on
/articles), and Standalone Deep Dive. - Tab 4: Reorder Roadmaps: Visual track manager with
▲ Upand▼ Downbuttons to reorder courses along learning paths, plus a 1-click Sync Weights to Courses button. - Tab 5: New Series: Form to scaffold a new course series and register it into
roadmapOrder.json. - Tab 6: All Articles Explorer: Instant real-time search across all 300+ articles with track filtering and 1-click draft toggling.
- Tab 7: Interview Bytes: Manage flashcard-style interview questions with syntax-highlighted code and topic filters.
- Tab 8: Shorts Studio: Manage YouTube Shorts and micro-learning video explainers.
- Tab 9: Images & WebP: Convert local source images to WebP and upload to Cloudinary.
- Tab 10: Problems Studio: Full code editors, registries, and 1-click article tag inserters for interactive code exercises.
2. Architecture & Metadata Rules
The Core Hierarchy
The platform organizes content in a 3-tier hierarchy:
Category (Track) ➔ Series (Course) ➔ Articles (Lessons)
| Level | Where Configured | Purpose |
|---|---|---|
| 1. Category / Track | src/config/roadmapOrder.json | Top-level learning domain (Core-CS, DSA, Development, System-Design, AI-Engineering). |
| 2. Series / Course | src/content/series/<id>.json | Structured course with a syllabus (navbar). Defines "category": "<Track>". |
| 3. Lessons | src/content/articles/<slug>.md | The actual educational lessons. Linked via series: "<id>". |
| Standalone Articles | src/content/articles/<slug>.md | Independent tutorials or build projects. Omit series; categorized via categories: [...]. |
Important Metadata Rules
- Course Lessons (
seriesis set):- When an article has
series: "docker", its learning category is inherited directly from the parent course. - Lessons are grouped in the course syllabus and do not clutter the general
/articlesproject listing.
- When an article has
- Standalone Articles (
seriesis omitted):- Must specify
categoriesusing one or more of the 5 canonical categories below. - These are surfaced on
/articles(Projects & Deep Dives).
- Must specify
- The 5 Canonical Categories:
"Core-CS": Operating systems, computer networks, computer architecture, databases, compilers."DSA": Data structures, algorithms, complexity analysis, interview problem sets."Development": Frontend, backend, fullstack frameworks, APIs, databases, tooling."System-Design": Distributed systems, microservices, cloud architectures, scalability."AI-Engineering": Machine learning, LLM integrations, embeddings, AI agents.
3. Step-by-Step Creation Playbooks
- 1. Standalone Article
- 2. Course / Series
- 3. Short
- 4. Interview Byte
- 5. TryCode Exercise
- 6. Roadmap Track
Adding a Standalone Article or Project
Use this for single-topic deep dives, project write-ups, or tutorials that do not belong to a sequential course syllabus.
Step 1: Create the markdown or MDX file
Create src/content/articles/<your-article-slug>.md (or .mdx if using custom components).
Step 2: Add Frontmatter
Important: Do not add the
serieskey for standalone articles.
---
title: "Building an LRU Cache from Scratch in TypeScript"
description: "Learn cache eviction policies by implementing a doubly linked list + hash map cache."
categories: ["Development"]
author: "Arjit Sharma"
draft: false
featured: false
---
Step 3: Write Content
Write in standard Markdown or import MDX components (e.g. <Notice>, <Badge>, <Accordion>).
4. Complete Schemas & Type Reference
This section provides the static field definitions, types, defaults, and allowed values for every content collection defined in src/content/config.ts.
4.1 Articles Collection Schema
Location: src/content/articles/*.md or *.mdx
Purpose: Standalone articles, project tutorials, and course lessons.
| Field | Type | Required | Default | Allowed Values / Constraints | Description |
|---|---|---|---|---|---|
title | string | Yes | — | Non-empty string | Article title shown in headings and cards |
subtitle | string | No | undefined | Any string | Secondary subhead for lessons or deep dives |
meta_title | string | No | undefined | String (≤ 60 chars recommended) | SEO <title> tag override |
description | string | No | undefined | String (≤ 160 chars recommended) | Meta and OpenGraph description |
image | string | No | undefined | Relative path (e.g. /images/og-image.jpg) | Card thumbnail and social share preview |
author | string | No | undefined | e.g. "Arjit Sharma" | Content author |
series | string | No | undefined | Filename of series in src/content/series/ | Links lesson to a course. Omit for standalone articles |
categories | string[] | No | ["others"] | Core-CS, DSA, Development, System-Design, AI-Engineering | Subject classification tag |
draft | boolean | No | false | true, false | Excludes article from production builds when true |
year | number | No | undefined | 4-digit year (e.g. 2025) | Publishing / revision year |
featured | boolean | No | false | true, false | Highlighted in hero card carousel |
TypeScript Interface
export interface ArticleFrontmatter {
title: string;
subtitle?: string;
meta_title?: string;
description?: string;
image?: string;
author?: string;
series?: string;
categories: ("Core-CS" | "DSA" | "Development" | "System-Design" | "AI-Engineering" | "others")[];
draft?: boolean;
year?: number;
featured?: boolean;
}
4.2 Series / Course Collection Schema
Location: src/content/series/<course-id>.json
Purpose: Course metadata, syllabus chapters, and sidebar navigation hierarchy.
| Field | Type | Required | Default | Allowed Values / Constraints | Description |
|---|---|---|---|---|---|
title | string | Yes | — | Non-empty string | Course display title |
subtitle | string | No | undefined | Any string | Course tagline |
description | string | Yes | — | Any string | Course summary on course overview cards |
image | string | No | undefined | Path to thumbnail | Cover banner image |
category | string | No | "Course" | "Core-CS", "DSA", "Development", "System-Design", "AI-Engineering" | Learning track bucket |
status | string | No | undefined | 'planned', 'in-progress', 're-visiting' | Global course progress status (replaces legacy ongoing) |
ongoing | boolean | string | No | false | true, false | (Deprecated) Replaced by status: "re-visiting" / "in-progress" |
time | string | No | undefined | e.g. "4 hours", "12 lessons" | Estimated completion time |
weight | number | No | 100 | Integer | Sort weight (lower appears first) |
navbar | Array<Section> | Yes | — | Array of syllabus sections | Ordered chapters and lesson links (see below) |
resources | Array<Resource> | No | [] | Array of supplementary references | Special “Further Learnings & Resources” section shown exclusively on individual course pages; excluded from roadmaps |
Navbar Structure (navbar)
Each section inside navbar contains:
subheading:string(e.g."1. Foundations")link: Array of lesson links:type:"articles"|"external"url:string(article slug insrc/content/articles/without.md, or external URL)title:string(lesson title)status:'planned'|'in-progress'|'re-visiting'(optional;'planned'displays a lock icon)
Resources Structure (resources)
Special section for supplementary external courses, official docs, books, or handwritten notes.
- Where it appears: Exclusively on
/courses/[course]. - Roadmap exclusion: Excluded from roadmaps, drawer checklists, and completion percentages.
- Editable in Studio: Tab 2 of
npm run adminallows 1-click adding, editing, reordering, and saving. - Each entry contains:
title:string(e.g."Alex Aiken - Stanford lectures")url:string(External URLhttps://...or internal article path/articles/<slug>)description:string(optional note or caption)
TypeScript Interface
export type CourseStatus = 'planned' | 'in-progress' | 're-visiting';
export interface SeriesNavbarLink {
type: 'articles' | 'external';
url: string;
title: string;
status?: CourseStatus;
}
export interface SeriesNavbarSection {
subheading: string;
link: SeriesNavbarLink[];
}
export interface CourseResource {
title: string;
url: string;
description?: string;
}
export interface SeriesData {
title: string;
subtitle?: string;
description: string;
image?: string;
category: string;
ongoing?: boolean | string;
status?: CourseStatus;
time?: string;
weight: number;
navbar: SeriesNavbarSection[];
resources?: CourseResource[];
}
4.3 Shorts Collection Schema
Location: src/content/shorts/<series>/<slug>.md
Purpose: Bite-sized video explainers and quick reference concepts.
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
title | string | Yes | — | Title of the short |
youtubeId | string | Yes | — | 11-character YouTube video ID (e.g. LbeV3TwK48s) |
series | string | Yes | — | Series slug folder identifier (e.g. "oci-shorts") |
seriesName | string | Yes | — | Human-readable series title (e.g. "Oracle Cloud") |
order | number | No | 0 | Progression sequence number within the shorts series |
4.4 Interview Questions Schema
Location: src/content/interview-questions/<topic>.yaml
Purpose: Structured questions and answers powering Interview Bytes and Anki flashcard modal.
Root YAML property: questions: Array<InterviewQuestion>
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
id | string | number | Yes | — | Unique numeric or string question ID |
question | string | Yes | — | The interview question text |
answer | string[] | Yes | — | Array of strings (rendered as bullet points or paragraphs) |
code | string | No | undefined | Optional code snippet or execution example |
tags | string[] | No | [] | Category & topic filter tags (e.g. [javascript, async]) |
date | date | No | undefined | Date added / updated |
related_images | string[] | No | [] | Asset paths relative to /src/assets/ |
4.5 TryCode Problem Schema
Location: src/problems/frontend/<problem-id>.ts
Purpose: Browser-based interactive JavaScript/TypeScript coding exercises.
| Field | Type | Required | Default | Allowed Values / Description |
|---|---|---|---|---|
id | string | Yes | — | Unique problem ID (must match filename) |
title | string | Yes | — | Problem title shown in the editor header |
starterCode | string | Yes | — | Initial code stub provided to the student |
tests | TestCase[] | Yes | — | Array of { input: any[], expected: any, customCheck?: string } test cases |
mode | string | No | "function" | "function" (pure JS algorithm) or "dom" (interactive DOM manipulation) |
html | string | No | "" | Initial DOM markup for "dom" mode problems |
TypeScript Interface
export interface TestCase {
input: any[];
expected: any;
customCheck?: string; // JavaScript function string returning boolean or value
}
export interface Problem {
id: string;
title: string;
mode?: "function" | "dom";
starterCode: string;
tests: TestCase[];
html?: string;
}
4.6 Pages Collection Schema
Location: src/content/pages/*.md or *.mdx
Purpose: Standalone regular site pages (e.g. /about, /elements, /changelog).
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
title | string | Yes | — | Page title |
description | string | No | undefined | Page SEO description |
5. Interactive MDX Component Catalog
All components below are auto-imported and immediately available in any .mdx file without manual import statements.
5.1 Notice Callouts (<Notice>)
Use callout boxes to draw attention to notes, best practices, tips, or critical warnings.
note
Note Callout: Use for contextual details, background information, or general notes.
tip
Tip Callout: Use for performance optimizations, helpful hints, or time-saving shortcuts.
info
Info Callout: Use for important informational updates or reference links.
warning
Warning Callout: Use for caveats, breaking changes, or restrictions (e.g., frontend-only constraints).
Usage Code
<Notice type="note">This is a note callout.</Notice>
<Notice type="tip">This is a helpful tip.</Notice>
<Notice type="info">This is an informational announcement.</Notice>
<Notice type="warning">This is a critical warning.</Notice>
5.2 Badges (<Badge>)
Inline status indicators for feature updates, changelogs, or requirements.
addedchangedremovedsecurity
Usage Code
<Badge type="added">added</Badge>
<Badge type="changed">changed</Badge>
<Badge type="removed">removed</Badge>
<Badge type="security">security</Badge>
5.3 Buttons (<Button>)
Styled call-to-action buttons for links, documentation, or resource downloads.
Usage Code
<Button href="/roadmaps" style="solid">Explore Roadmaps</Button>
<Button href="/courses" style="outline">Browse Courses</Button>
5.4 Accordions (<Accordion>)
Expandable accordion container for FAQs, solutions, or deep-dive collapsible explanations.
When should I use a Series instead of a Standalone Article?
Create a Series when:
- The content consists of multiple sequential lessons or chapters.
- You need a persistent sidebar navigation and previous/next chapter progression.
- The course belongs to a categorized learning path on
/roadmaps.
Create a Standalone Article when:
- It is a single project, quick tutorial, or independent deep dive.
- It does not require a sidebar syllabus.
How do I mark a lesson as planned/locked in a course?
In src/content/series/<id>.json, set "status": "planned" on the link object:
{
"type": "articles",
"url": "distributed-consensus",
"title": "Distributed Consensus (Raft & Paxos)",
"status": "planned"
}
This displays the lesson with a lock icon and disables navigation until it is published.
Usage Code
<Accordion title="Your Accordion Title Here">
Your collapsible explanation, code snippets, or list items go here.
</Accordion>
5.5 Tabs (<Tabs> & <Tab>)
Clean multi-panel switcher for tabbed content (e.g. comparing languages, alternatives, or multi-step flows).
- TypeScript
- Python
- Go
interface User {
id: string;
name: string;
role: "admin" | "engineer";
}
const user: User = { id: "1", name: "Arjit", role: "engineer" };
Usage Code
<Tabs>
<Tab name="Tab 1">
Content for tab 1...
</Tab>
<Tab name="Tab 2">
Content for tab 2...
</Tab>
</Tabs>
5.6 Interactive TryCode Runner (<TryCode>)
Live, in-browser Monaco-based code editor and test runner for frontend JavaScript and DOM interview drills.
Deduplicate Cart Items While Preserving Order
Props Reference
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
problemId | string | Yes | — | Unique problem ID corresponding to a file in src/problems/frontend/<id>.ts |
Usage Code
<!-- Function Mode (Pure JavaScript algorithms) -->
<TryCode problemId="array-unique" />
<!-- DOM Mode (Interactive UI & DOM manipulation) -->
<TryCode problemId="counter-dom" />
5.7 Video & YouTube Embeds (<Youtube> & <Video>)
Responsive 16:9 media embeds with lazy loading.
Usage Code
<!-- YouTube Embed (Responsive 16:9) -->
<Youtube id="uzR3VB1kfMw" title="Introduction to Distributed Systems" />
<!-- Local or Remote HTML5 Video -->
<Video src="https://joy1.videvo.net/videvo_files/video/free/video0467/large_watermarked/_import_61516692993d77.04238324_preview.mp4" title="System Demo" />
5.8 Algorithm Visualizer (<AlgoVisualizer>)
Interactive step-by-step algorithm visualizer supporting arrays, hash maps, sets, queues, deques, stacks, trees, heaps, linked lists, and DP tables with variable tracking and execution timeline controls.
Sample: Binary Search
Demonstrates halving the search space using low, mid, and high pointers along with an active subarray window bounding the candidate range.
Initialize Search Space
Target is 23. The search interval is initially the entire array [0..9].
int low = 0, high = nums.length - 1; Props Reference
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
problemId | string | Yes | — | Unique problem ID corresponding to a file in src/problems/algorithms/<slug>.ts |
Usage Code
<!-- Binary Search Visualization -->
<AlgoVisualizer problemId="sample-binary-search" />
<!-- Two Sum Array + Hash Map Visualization -->
<AlgoVisualizer problemId="02-two-sum" />
[!TIP] For the complete specification, step builder API, and AI prompt template to generate new DSA visualizers, see Section 7: Algorithm Visualizer Guide.
5.9 Interactive Git Visualizer (<GitVisualizer>)
Interactive visualizer demonstrating Git internals, staging phases, commit graphs, branch pointers, merges, rebases, and conflict resolutions.
Git Basic Workflow
Step 1 of 4: Initialize RepositoryActive workspace where files are created & edited.
Prepared files staged via git add.
Immutable snapshots created via git commit.
$ git init Creates a new Git repository and sets up the internal .git database for tracking files.
Props Reference
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
scenario | string | Yes | — | Scenario identifier from src/visualizations/git/scenarios.ts |
title | string | No | Scenario title | Custom display title override in header |
Complete Supported Scenarios Catalog
| Scenario ID | Topic | Default View |
|---|---|---|
intro-phases | Three Phases of Git Content | stages |
intro-branches | Branches: Parallel Workflows | graph |
basic-workflow | Git Basic Workflow (Modify $\rightarrow$ Stage $\rightarrow$ Commit) | stages |
diff-stages | Inspecting Changes (git diff vs git diff --staged) | stages |
cloning | Repository Cloning | graph |
branching | Branch Creation & Switching | graph |
detached-head | Detached HEAD State | graph |
merge-fast-forward | Fast-Forward Merge | graph |
merge-3way | 3-Way Recursive Merge Snapshot | graph |
cherry-pick | Cherry-Picking Commits | graph |
merge-conflict | Resolving Merge Conflicts | special |
stashing | Git Stashing Workspace State | stages |
stash-stack | Managing Multiple Stashes (LIFO Stack) | stages |
reset-modes | Git Reset Comparison Matrix (Soft vs Mixed vs Hard) | stages |
reset-revert | Git Revert: Safe Public History Undo | graph |
reflog | Git Reflog Safety Net | graph |
rebase | Git Rebase: Linear History Reconstruction | graph |
squash | Squashing Commits with Interactive Rebase | special |
bisect | Git Bisect: Binary Search Bug Hunting | special |
fetch-pull-push | Remote Synchronization (Fetch vs Pull vs Push) | graph |
pull-requests | GitHub Collaboration & PR Workflow | graph |
submodules | Git Submodules: Pinned Dependencies | graph |
Usage Code
<GitVisualizer scenario="basic-workflow" />
<GitVisualizer scenario="merge-3way" title="3-Way Merge in Action" />
<GitVisualizer scenario="rebase" />
5.10 Changelog Entries (<Changelog>)
Timeline container for milestone releases, major curriculum additions, or platform changelog updates.
November 19, 2026
- Performance Optimization: Configured dynamic algorithm micro-chunking for 500+ DSA visualizers.
- Infrastructure: Automated Vercel edge caching and Cloudflare DNS alignment.
- Image Pipeline: Auto-injected lazy-loading and WebP/AVIF transformations.
Props Reference
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
date | string | Yes | — | Date string displayed on the left column (e.g. "November 19, 2026") |
Usage Code
<Changelog date="November 19, 2026">
- Added 50 new interactive DSA problem visualizers
- Released System Design deep dive on distributed consensus
</Changelog>
6. Standard Typography & Layout Elements
Headings Hierarchy
Heading 1 (# Heading 1)
Heading 2 (## Heading 2)
Heading 3 (### Heading 3)
Heading 4 (#### Heading 4)
Formatted Tables
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
GET | /api/questions.json | Returns all interview questions with optimized images | No |
POST | http://localhost:4322/api/create-series | Scaffolds new series and updates roadmaps | Local Dev Only |
POST | http://localhost:4322/api/create-article | Scaffolds article and updates syllabus navbar | Local Dev Only |
Pre-Publish Checklist
Before committing or pushing new content:
- File created in the designated folder (
articles/,series/,shorts/, etc.). - Frontmatter strictly validated against the schemas in Section 4.
- Category chosen from the 5 canonical values (
Core-CS,DSA,Development,System-Design,AI-Engineering). -
seriesfield matches the exact JSON course ID (if part of a course). -
roadmapOrder.jsonupdated with new series ID (handled automatically bynpm run admin/npm run scaffold). -
draft: falseset for all live content.
7. Algorithm Visualizer: AI Prompt & Generator Guide
This section provides the complete reference specification and copy-paste prompt template to generate interactive algorithm visualizers for any DSA problem (Sorting, Searching, HashMaps, Sets, Queues, Deques, Trees, Heaps, Stacks, Linked Lists, DP) using any AI assistant (ChatGPT, Claude, Gemini, Cursor, Antigravity).
7.1 Visualizer Architecture Overview
The visualizer system is composed of:
- Engine Component:
<AlgoVisualizer problemId="slug" />insrc/components/features/visualizer/AlgoVisualizer.astro. - Step Builder:
StepBuilderclass insrc/problems/algorithms/builder.tswith a fluent.step({ ... })API. - Type Definitions:
src/problems/algorithms/types.tsdefining all state models and render options. - Algorithm Directory: All algorithm definition files live in
src/problems/algorithms/<slug>.ts. - Registry:
src/problems/algorithms/index.ts(automatically updated viasyncAlgorithmIndex()).
7.2 Representation of All DSA Problem Types
The visualization engine supports representing any DSA problem type through flexible combinations of data structures:
| DSA Problem Type | How to Represent with StepBuilder | Key Properties Used |
|---|---|---|
| Merge Sort | Subarrays via arrays: [left, right, merged] or single array with window: [low, high] and merge pointers i, j, k | arrays or array.window, pointers |
| Quick Sort | Single array with partition pointers (low, pivot, high, i, j), swap highlights, and sub-range windows | pointers, highlights, window |
| Binary Search | Single array with low, mid, high pointers, active search interval window: [low, high], and match highlights | pointers: { low, mid, high }, window: [low, high] |
| Linear Search | Scanning pointer i checking each element with match/visited state highlights | pointers: { i }, highlights |
| Hash Map | Key-Value dictionary with searchKey and status banner (found, not-found, searching) | hashmap: Map or Record, searchKey, searchResult |
| Set / HashSet | Unique element collection with searchElement and membership verification banner (contains(x)) | set: Set or string[] or number[], searchElement, searchResult |
| Queue (FIFO) | First-In-First-Out queue with FRONT and REAR markers, showing enqueue at rear and dequeue at front (BFS) | queue: { items: [...], action: 'enqueue' | 'dequeue', label: 'Queue (FIFO)' } |
| Deque (Double Queue) | Double-ended queue with front (addFirst/removeFirst) and back (addLast/removeLast) markers (e.g. Monotonic Deque, Sliding Window Max) | deque: { items: [...], action: 'addFirst' | 'removeFirst' | 'addLast' | 'removeLast', label: 'Double-Ended Queue (Deque)' } |
| Stack (LIFO) | Last-In-First-Out container with vertical layout, TOP marker, depth count, and push/pop animations (brackets, monotonic stack) | stack: { items: [...], action: 'push' | 'pop', label: 'Stack (LIFO)' } |
| Binary Tree & BST | Node hierarchy with parent-child links, traversal highlights, and search targets | tree: { nodes: [...], rootId } |
| Tree + Array (Heaps) | Both array and tree in the exact same step, mapping array index i to tree nodes with children at 2i + 1 and 2i + 2 | array: { ... }, tree: { ... } |
| Linked List | Node chains with next pointers, head/curr/prev markers, and node reversal indicators | linkedList: { nodes: [...], headId } |
| Dynamic Programming | 1D or 2D state matrix with active computation cell, dependency cell highlights, and transition formula banner | dpTable: { grid, activeCell, highlightCells, formula } |
[!TIP] Stack vs. Queue vs. Deque Selection
- Stack (LIFO): Use
step.stack. Renders as a vertical container with aTOPmarker andpush/popoperations.- Queue (FIFO): Use
step.queue. Renders as a horizontal pipeline with← FRONT (Out)on the left andREAR (In) ←on the right withenqueue/dequeueoperations.- Deque (Double-Ended): Use
step.deque. Renders with bothFRONTandBACKmarkers, supportingaddFirst,removeFirst,addLast, andremoveLast. In the CMS Visual Step Builder, simply pick your desired data structure from the Container Type dropdown.
7.3 Core Authoring Rules
- Idiomatic Java in
codeLine: Always display the actual, readable Java statement executed at that step. - Pointers Only (No Window Text Badges): Arrays show labeled pointer arrows (
i,j,low,mid,high,left,right). Windows outline the active subarray boundary (window: [start, end]). Never put text labels or badge strings on or inside windows. - Variable Tracking in Header: Keep all numeric metrics, accumulators, sums, and status flags in
variables: { ... }. They render in a clean, dedicated bar above the visualization. - Freeform Categories: Category is an open string (e.g.
'Sorting','Sliding Window','Two Pointers','Trees & Heaps', or'General DSA'). - No Forced Complexity / Difficulty Tags: The visualizer player stays clean, focused entirely on the execution flow and intuitive mental model.
7.4 Copy-Paste AI Prompt Template
Copy the prompt below and paste it into any LLM or AI coding agent alongside your Java solution:
You are an expert DSA educator and TypeScript engineer building algorithm visualizers for CSPrimer.
Given the Java solution and problem below, create a fully working TypeScript algorithm definition file for the CSPrimer Algorithm Visualizer Engine.
### Output Destination
File path: `src/problems/algorithms/<problem-slug>.ts`
### Requirements
1. Import `AlgorithmDefinition`, `ExecutionStep` from `./types` and `StepBuilder` from `./builder`.
2. Export an object adhering to `AlgorithmDefinition`:
- `id`: `<problem-slug>`
- `title`: Clean Problem Title
- `category`: Freeform topic name (e.g. 'Sorting', 'Binary Search', 'Sliding Window', 'Hash Map', 'Set', 'Trees', 'Deques', or 'General DSA')
- `description`: 1-2 sentence high-level explanation
- `visualizationTypes`: Array of data structure renderers used: `['array']`, `['array', 'hashmap']`, `['set']`, `['deque']`, `['array', 'tree']`, etc.
- `defaultInputs`: Object containing default parameters (e.g. `{ nums: [4, 2, 7, 1, 3] }`)
- `inputSchema`: Array of input field schemas for the interactive "Customize" drawer
- `generateSteps(inputs)`: Returns `ExecutionStep[]` using `StepBuilder`.
3. Visualizer Step Rules:
- Use `const builder = new StepBuilder();`
- Call `builder.step({ title, description, codeLine, variables, ...structures })` for each step.
- `codeLine`: Exact line of standard Java code executed at this step.
- `variables`: Key-value map of current variables (e.g. `{ low: 0, high: 5, mid: 2 }`).
- `pointers`: Named indices pointing to array elements (e.g. `pointers: { low: 0, mid: 2, high: 5 }`).
- `window`: Active subarray window `window: [start, end]`. Never place text labels or badge strings in the window.
- `highlights`: Array of cell indices to highlight with visual states: `[0, 1]`.
- Data Structure Renderers Supported:
- **Array / Sorting / Searching**: `array: { values: [...], pointers: { ... }, highlights: [...], window: [start, end] }`
- **Multiple Arrays**: `arrays: [ { values: [...], label: 'A' }, { values: [...], label: 'B' } ]`
- **Hash Map**: `hashmap: map, searchKey: key, searchResult: 'found' | 'not-found'`
- **Set / HashSet**: `set: Array.from(set), searchElement: val, searchResult: 'found' | 'not-found'`
- **Queue**: `queue: [...queueItems]`
- **Deque (Double Queue)**: `deque: [...dequeItems]`
- **Stack**: `stack: [...stackItems]`
- **Binary Tree**: `tree: { nodes: [...], rootId: 'root' }`
- **Tree + Array (Heap)**: combine `array` and `tree` in the same step
- **Linked List**: `linkedList: { nodes: [...], headId: '0' }`
- **Dynamic Programming**: `dpTable: { grid: [...], activeCell: { row, col }, formula: '...' }`
4. Registration & MDX Embed:
- Provide the 1-line command to register the problem:
`node -e "import('./scripts/scaffold.mjs').then(m => m.syncAlgorithmIndex())"`
- Provide the MDX embed snippet:
`<AlgoVisualizer problemId="<problem-slug>" />`
---
### Java Code & Problem Details:
[PASTE YOUR JAVA SOLUTION AND PROBLEM DESCRIPTION HERE]
7.5 Reference Implementation Blueprints
Blueprint 1: Binary Search (Array + Pointers + Search Window)
import type { AlgorithmDefinition, ExecutionStep } from './types';
import { StepBuilder } from './builder';
export const binarySearch: AlgorithmDefinition = {
id: 'binary-search',
title: 'Binary Search',
category: 'Searching',
description: 'Searches for a target value within a sorted array by halving the search space each step.',
visualizationTypes: ['array'],
defaultInputs: {
nums: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91],
target: 23,
},
inputSchema: [
{
name: 'nums',
label: 'Sorted Array (comma-separated)',
type: 'number-array',
defaultValue: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91],
placeholder: '2, 5, 8, 12, 16, 23, 38, 56, 72, 91',
description: 'Ascending sorted array',
},
{
name: 'target',
label: 'Target Value',
type: 'number',
defaultValue: 23,
placeholder: '23',
description: 'Number to search for',
},
],
generateSteps: (inputs: Record<string, any>): ExecutionStep[] => {
const rawNums = inputs.nums;
const nums: number[] = Array.isArray(rawNums)
? rawNums.map(Number).filter((n) => !isNaN(n))
: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
const target = Number(inputs.target ?? 23);
const builder = new StepBuilder();
let low = 0;
let high = nums.length - 1;
builder.step({
title: 'Initialize Binary Search',
description: `Target is ${target}. Set low = 0 and high = ${high}.`,
codeLine: 'int low = 0, high = nums.length - 1;',
variables: { low, high, target },
array: {
values: [...nums],
pointers: { low, high },
window: [low, high],
label: 'nums[]',
},
});
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const midVal = nums[mid];
builder.step({
title: `Calculate Midpoint: mid = ${mid} (nums[mid] = ${midVal})`,
description: `Inspect middle element at index ${mid}.`,
codeLine: 'int mid = low + (high - low) / 2;',
variables: { low, mid, high, 'nums[mid]': midVal, target },
array: {
values: [...nums],
pointers: { low, mid, high },
highlights: [mid],
window: [low, high],
label: 'nums[]',
},
});
if (midVal === target) {
builder.step({
title: `Target Found at Index ${mid}!`,
description: `nums[${mid}] == ${target}. Return index ${mid}.`,
codeLine: 'if (nums[mid] == target) return mid;',
variables: { low, mid, high, resultIndex: mid, status: 'FOUND' },
array: {
values: [...nums],
pointers: { mid },
highlights: [{ index: mid, state: 'match' }],
label: 'nums[]',
},
});
return builder.build();
} else if (midVal < target) {
builder.step({
title: `nums[mid] = ${midVal} < ${target}: Discard Left Half`,
description: `Target must lie in the right half. Move low to mid + 1.`,
codeLine: 'low = mid + 1;',
variables: { low: mid + 1, mid, high, target },
array: {
values: [...nums],
pointers: { low: mid + 1, high },
window: [mid + 1, high],
label: 'nums[]',
},
});
low = mid + 1;
} else {
builder.step({
title: `nums[mid] = ${midVal} > ${target}: Discard Right Half`,
description: `Target must lie in the left half. Move high to mid - 1.`,
codeLine: 'high = mid - 1;',
variables: { low, mid, high: mid - 1, target },
array: {
values: [...nums],
pointers: { low, high: mid - 1 },
window: [low, Math.max(low, mid - 1)],
label: 'nums[]',
},
});
high = mid - 1;
}
}
builder.step({
title: 'Target Not Found',
description: `Search space exhausted (low > high). Target ${target} is not in the array.`,
codeLine: 'return -1;',
variables: { low, high, target, status: 'NOT FOUND' },
array: { values: [...nums], label: 'nums[]' },
});
return builder.build();
},
};
export default binarySearch;
Blueprint 2: Sliding Window Maximum (Array + Double Queue / Deque)
import type { AlgorithmDefinition, ExecutionStep } from './types';
import { StepBuilder } from './builder';
export const slidingWindowMax: AlgorithmDefinition = {
id: 'sliding-window-maximum',
title: 'Sliding Window Maximum',
category: 'Deques & Sliding Window',
description: 'Maintains a monotonic decreasing deque storing indices to find the maximum in each sliding window in O(N) time.',
visualizationTypes: ['array', 'deque'],
defaultInputs: {
nums: [1, 3, -1, -3, 5, 3, 6, 7],
k: 3,
},
inputSchema: [
{
name: 'nums',
label: 'Array',
type: 'number-array',
defaultValue: [1, 3, -1, -3, 5, 3, 6, 7],
placeholder: '1, 3, -1, -3, 5, 3, 6, 7',
description: 'Input numbers array',
},
{
name: 'k',
label: 'Window Size (k)',
type: 'number',
defaultValue: 3,
placeholder: '3',
description: 'Sliding window width',
},
],
generateSteps: (inputs: Record<string, any>): ExecutionStep[] => {
const rawNums = inputs.nums;
const nums: number[] = Array.isArray(rawNums)
? rawNums.map(Number).filter((n) => !isNaN(n))
: [1, 3, -1, -3, 5, 3, 6, 7];
const k = Math.max(1, Number(inputs.k ?? 3));
const builder = new StepBuilder();
const deque: number[] = []; // Stores indices
const result: number[] = [];
builder.step({
title: 'Initialize Monotonic Deque',
description: `Create an ArrayDeque to store indices of potential maximum elements in decreasing value order.`,
codeLine: 'Deque<Integer> deque = new ArrayDeque<>();',
variables: { k, dequeSize: 0 },
array: { values: [...nums], pointers: { i: 0 }, label: 'nums[]' },
deque: [],
});
for (let i = 0; i < nums.length; i++) {
// Remove elements outside current window
while (deque.length > 0 && deque[0] < i - k + 1) {
const removed = deque.shift()!;
builder.step({
title: `deque.removeFirst(): Out of Window`,
description: `Index ${removed} falls outside window [${i - k + 1}, ${i}]. Remove from front.`,
codeLine: 'if (!deque.isEmpty() && deque.peekFirst() < i - k + 1) deque.pollFirst();',
variables: { i, removedIndex: removed, 'deque.size()': deque.length },
array: { values: [...nums], pointers: { i }, window: [Math.max(0, i - k + 1), i], label: 'nums[]' },
deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
});
}
// Remove smaller elements from back
while (deque.length > 0 && nums[deque[deque.length - 1]] < nums[i]) {
const removed = deque.pop()!;
builder.step({
title: `deque.removeLast(): Monotonic Violation`,
description: `nums[${removed}] (${nums[removed]}) < nums[${i}] (${nums[i]}). Pop from back.`,
codeLine: 'while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) deque.pollLast();',
variables: { i, poppedIndex: removed, currentVal: nums[i] },
array: { values: [...nums], pointers: { i }, highlights: [i, removed], window: [Math.max(0, i - k + 1), i], label: 'nums[]' },
deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
});
}
deque.push(i);
builder.step({
title: `deque.addLast(${i}): Added Current Index`,
description: `Pushed index ${i} (value ${nums[i]}) to back of deque.`,
codeLine: 'deque.offerLast(i);',
variables: { i, currentVal: nums[i], windowMax: nums[deque[0]] },
array: { values: [...nums], pointers: { i }, window: [Math.max(0, i - k + 1), i], label: 'nums[]' },
deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
});
if (i >= k - 1) {
result.push(nums[deque[0]]);
builder.step({
title: `Record Window Maximum: ${nums[deque[0]]}`,
description: `Window [${i - k + 1}, ${i}] maximum is at front of deque: nums[${deque[0]}] = ${nums[deque[0]]}.`,
codeLine: 'result[i - k + 1] = nums[deque.peekFirst()];',
variables: { windowStart: i - k + 1, windowEnd: i, max: nums[deque[0]], resultSoFar: [...result] },
array: { values: [...nums], pointers: { max: deque[0] }, window: [i - k + 1, i], highlights: [deque[0]], label: 'nums[]' },
deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
});
}
}
return builder.build();
},
};
export default slidingWindowMax;
8. Infrastructure, Hosting & Deployment Architecture
This section documents the production hosting, CDN, domain canonicalization, and deployment setup powering CSPrimer.
8.1 Canonical Production Domain & 308 Redirection
The single authoritative canonical production domain is:
https://csprimer.org
All domain routing and search authority are unified under this domain:
| Domain | Status in Vercel | HTTP Behavior | Purpose |
|---|---|---|---|
csprimer.org | Production (Primary) | 200 OK | The canonical domain for all visitors, search engines, and social cards |
www.csprimer.org | Valid Configuration | 308 Permanent Redirect $\rightarrow$ csprimer.org | Standard www subdomain redirect |
csprimer.in | Valid Configuration | 308 Permanent Redirect $\rightarrow$ csprimer.org | Legacy domain alias redirect |
www.csprimer.in | Valid Configuration | 308 Permanent Redirect $\rightarrow$ csprimer.org | Legacy www alias redirect |
*.vercel.app | Valid Configuration | Direct / Preview Deployments | Staging and internal deployment previews |
Core Repository Configuration:
astro.config.mjs:site: "https://csprimer.org"(generates clean sitemaps and canonical tags).src/config/config.json:"base_url": "https://csprimer.org".public/robots.txt:Sitemap: https://csprimer.org/sitemap-index.xml.src/layouts/Base.astro: Canonical tags (<link rel="canonical">) and OpenGraph (og:url,og:image) automatically resolve tohttps://csprimer.org, preventing canonical redirect loops.
8.2 Vercel Edge Hosting Configuration (vercel.json)
Edge caching, routing rules, and security headers are configured at the repository root via vercel.json:
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"cleanUrls": true,
"trailingSlash": false,
"headers": [
{
"source": "/_astro/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000, immutable"
}
]
},
{
"source": "/images/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=86400, stale-while-revalidate=604800"
}
]
},
{
"source": "/pdfs/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=604800, stale-while-revalidate=86400"
}
]
},
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" },
{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
]
}
]
}
- Hashed Assets (
/_astro/*): Given 1-year immutable caching (max-age=31536000, immutable). Browsers and edge caches never re-fetch fingerprinted JS and CSS. - Clean URLs:
cleanUrls: truewithtrailingSlash: falsematches Astro SSG routing perfectly. - Security Headers: Standard
nosniff,SAMEORIGIN, and strict referrer protection across all routes.
8.3 Node.js Runtime Version Requirement
- Requirement:
Node.js >= 22.0.0(Active LTS). - In
package.json:"engines": { "node": ">=22.0.0" } - In Vercel Project Settings:
- Navigate to Settings $\rightarrow$ General $\rightarrow$ Node.js Version.
- Select
22.xor24.x(never legacy20.xwhich is discontinued).
8.4 Cloudflare DNS & Proxy Guidelines
DNS for csprimer.org is managed in Cloudflare with the following configuration:
csprimer.org CNAME b3e9b5f5fbc27da1.vercel-dns-017.com DNS only (Grey Cloud)
www.csprimer.org CNAME b3e9b5f5fbc27da1.vercel-dns-017.com DNS only (Grey Cloud)
_vercel TXT vc-domain-verify=... DNS only
Recommended: “DNS only” (Grey Cloud)
- Why: Cloudflare operates purely as a lightning-fast authoritative DNS provider. Requests resolve directly to Vercel’s global Anycast Edge Network.
- Advantages:
- Zero risk of proxy interference with client module hydration or ViewTransitions.
- Eliminates double-proxy latency (Browser $\rightarrow$ Cloudflare $\rightarrow$ Vercel).
- Vercel automatically manages TLS certificates, HTTP/2, HTTP/3, and edge routing.
If Switching to “Proxied” (Orange Cloud):
If you ever enable Cloudflare’s HTTP proxy for WAF or custom page rules, you must configure these settings:
- SSL/TLS Encryption Mode: Set to Full (Strict). (Flexible mode causes an infinite 301/308 redirect loop).
- Rocket Loader: OFF. (Rocket Loader intercepts module scripts and breaks Astro ViewTransitions lifecycle events).
- Auto Minify (HTML/JS/CSS): OFF. (Vite already minifies; Cloudflare’s HTML minifier strips inline visualizer JSON payloads).
- Polish / Mirage: OFF. (Images are hosted on Cloudinary and should not be re-compressed).
8.5 Cloudinary Image Pipeline & Automatic Lazy-Loading
All article screenshots, architectural diagrams, and illustrations are hosted on Cloudinary:
URL Transformation Pattern:
https://res.cloudinary.com/dwa6rcttw/image/upload/f_auto,q_auto,w_800/<public-id>
f_auto: Delivers modern AVIF to Chrome, Firefox, and Safari 16+ (saving ~30–50% bandwidth compared to WebP), with automatic WebP/PNG fallbacks.q_auto: AI-driven perceptual compression balancing visual clarity and payload size.w_800: Responsive width constraint preventing desktop-resolution downloads on mobile devices.- CMS Automation: Tab 9 of
npm run adminandscripts/scaffold.mjsautomatically inject/f_auto,q_auto,w_800/into generated Markdown image tags.
AST Lazy Loading Plugin (rehypeLazyImages):
Configured in astro.config.mjs across both MDX and Markdown AST pipelines:
- Every
<img>tag rendered from markdown automatically receivesloading="lazy"anddecoding="async". - Prevents off-screen article images from competing with critical CSS/JS during page load.
- Preconnect hints (
<link rel="preconnect" href="https://res.cloudinary.com" />) are embedded inBase.astrofor instant TLS handshakes.
9. Performance & Scale Engineering Guide
This section explains how the platform achieves sub-second builds and fluid client transitions while scaling from 300 to 800+ articles and 200–500 DSA problem visualizers.
9.1 Dynamic Micro-Chunking for 200–500 DSA Visualizers
The Problem:
If an Astro site statically imports hundreds of algorithm definitions, Vite bundles them into a single monolithic JavaScript file (index.*.js). Every page visitor would download the code for all 500 algorithms, causing massive bundle bloat and sluggish first-contentful paint.
The Architectural Solution:
In src/components/features/visualizer/engine/visualizer-controller.ts:
- Negative globs exclude internal builder utilities from the loader:
const modules = import.meta.glob([ '../../../../problems/algorithms/*.ts', '!**/index.ts', '!**/builder.ts', '!**/types.ts' ]); - Each algorithm compiles into its own independent micro-chunk (
~2–3 KBeach, e.g.02-two-sum.*.js). - When a user navigates to an article containing
<AlgoVisualizer problemId="two-sum" />, only that single micro-chunk is fetched asynchronously on demand. - Adding 500 new DSA articles has zero impact on the base client bundle size.
9.2 Main-Thread Infinite Loop & Memory Guardrails
To protect against browser lockups during user testing or complex recursions:
MAX_STEPS = 300: Enforced inStepBuilder.addStep()(src/problems/algorithms/builder.ts).- If an algorithm enters a runaway loop or excessive state transitions on custom user inputs, step generation halts safely with a console warning rather than crashing the visitor’s browser tab.
9.3 Client-Side SPA Lifecycle & ViewTransitions Safety
Astro’s <ViewTransitions /> turns navigation into a client-side Single Page Application (SPA). The HTML <body> is swapped while JavaScript globals (window, document) persist.
Contributor Rules for Client Scripts:
-
Always Listen to
astro:page-load:- ❌ Never use
document.addEventListener("DOMContentLoaded", init)alone (it will not fire when navigating between pages). - ❌ Never run
init()at module top-level AND inastro:page-load(causes double-initialization). - ✅ Always use:
document.addEventListener("astro:page-load", () => { initComponent(); });
- ❌ Never use
-
Always Clean Up Global Window & Document Listeners:
- Attaching anonymous listeners to
windowordocumentinside anastro:page-loadhook creates memory leaks and duplicate triggers on every page visit. - Pattern A: AbortController (Recommended)
let abortController = new AbortController(); document.addEventListener("astro:before-swap", () => { abortController.abort(); abortController = new AbortController(); }); window.addEventListener("resize", handleResize, { signal: abortController.signal }); - Pattern B: Named Handler Unmounting
window.removeEventListener("keydown", window.__myHandlerRef); window.__myHandlerRef = handleKeyDown; window.addEventListener("keydown", handleKeyDown);
- Attaching anonymous listeners to
-
Debounce Scroll & Resize with
requestAnimationFrame:- In components like
TableOfContents.astro, scroll calculations are wrapped inrequestAnimationFrameto eliminate layout thrashing and maintain 60 FPS scrolling.
- In components like
9.4 Google Analytics 4 (GA4) Virtual Pageview Tracking
Because Astro swaps page content without a full document reload:
- Standard GA4 tracking tags only fire on the initial hard page load.
- In
src/layouts/Base.astro, anastro:page-loadlistener dispatches virtualpage_viewevents:let isFirstLoad = true; document.addEventListener("astro:page-load", () => { NProgress.done(); if (isFirstLoad) { isFirstLoad = false; return; } if (typeof window.gtag === "function") { window.gtag("event", "page_view", { page_location: window.location.href, page_title: document.title, }); } }); - This ensures 100% accurate traffic analytics across all 500+ articles without double-counting the initial visit.
10. Client State & LocalStorage Schema
The platform persists user progress and interactive states directly in browser localStorage. Below is the complete specification:
| Storage Key | Data Type | Purpose | Where Used |
|---|---|---|---|
roadmap_progress | Record<string, boolean> | Map of completed article slugs (e.g. {"arrays-intro": true}) | Roadmaps, Course Drawer, and Article completion buttons |
ib_starred | string[] | Array of starred interview question IDs (e.g. ["101", "102"]) | Interview Bytes, Filter pills, and Anki Revision Modal |
anki_history | Record<string, any> | Spaced repetition flashcard session scores, intervals, and dates | Anki Revision Modal (/revision) |
revision_planner_data | Record<string, any> | User’s custom revision schedule, checkboxes, and notes | Revision Planner (/revision) |