Video Tutorials
Create engaging video documentation
Your open-source library has gained traction with 10K GitHub stars, but users complain about poor documentation. You need to create API references, usage guides, architecture docs, migration guides, and interactive examples. The codebase spans 50K lines with complex APIs, and you need everything ready for the major v2.0 release next week.
By completing this lesson, you’ll master:
Create comprehensive documentation including:
Start by analyzing what exists:
@src @docs"Analyze the current documentation state:- What documentation exists?- What's outdated or incorrect?- What's completely missing?- How is it organized?- What formats are used?Create a documentation gap analysis report"
"Design a comprehensive documentation structure for:- API Reference (auto-generated from code)- Tutorials (task-based learning)- Conceptual Guides (understanding the system)- How-to Guides (solving specific problems)- Architecture Docs (system design)- Contributing Guide (for open source)Create a documentation plan with priorities"
Switch to Agent mode:
"Set up modern documentation infrastructure:- Install and configure documentation generator- Set up markdown processing pipeline- Configure syntax highlighting- Add search functionality- Set up deployment workflowUse Docusaurus or similar tool"
Example documentation config:
module.exports = { title: 'MyLibrary Documentation', tagline: 'Powerful, Type-Safe, and Easy to Use', url: 'https://docs.mylibrary.dev', baseUrl: '/',
presets: [ [ '@docusaurus/preset-classic', { docs: { sidebarPath: require.resolve('./sidebars.js'), editUrl: 'https://github.com/myorg/mylibrary/edit/main/', remarkPlugins: [ require('remark-code-import'), require('remark-math'), ], rehypePlugins: [ require('rehype-katex'), ], }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }, ], ],
plugins: [ [ '@docusaurus/plugin-content-docs', { id: 'api', path: 'api', routeBasePath: 'api', sidebarPath: require.resolve('./sidebarsApi.js'), }, ], '@docusaurus/plugin-ideal-image', [ 'docusaurus-plugin-typedoc', { entryPoints: ['../src/index.ts'], tsconfig: '../tsconfig.json', out: 'api', sidebar: { categoryLabel: 'API Reference', position: 1, }, }, ], ],
themeConfig: { navbar: { title: 'MyLibrary', items: [ { type: 'doc', docId: 'intro', position: 'left', label: 'Docs', }, { to: '/api', label: 'API', position: 'left', }, { href: 'https://github.com/myorg/mylibrary', label: 'GitHub', position: 'right', }, ], },
algolia: { appId: 'YOUR_APP_ID', apiKey: 'YOUR_SEARCH_API_KEY', indexName: 'mylibrary', },
prism: { theme: lightCodeTheme, darkTheme: darkCodeTheme, additionalLanguages: ['rust', 'elixir'], }, },};
{ "mcpServers": { "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp"] } }}
"Using Context7 MCP, show me the latest:- React 18 documentation patterns- TypeScript 5 doc comment standards- Jest testing documentation examples- Popular library documentation structures"
// Get specific library docs"Using Context7: How does Next.js 14 document:- API routes- Component props- Configuration options- Migration guides"
"Using Context7, show current JSDoc standards for:- Async functions- Generic types- React components- Error handling
Then apply to our codebase"
"Using Context7, find examples of:- Database connection pooling- Authentication middleware- React hooks usage- Error boundaries
Adapt for our documentation"
"Using Context7, analyze how libraries handle:- Breaking changes documentation- Version migration guides- Deprecation notices- Upgrade paths"
"Using Context7 MCP, compare documentation styles:- React vs Vue component docs- Express vs Fastify API docs- Prisma vs TypeORM schema docsWhat patterns work best for our library?"
// Get framework-specific conventions"Using Context7: Show me Docusaurus best practices for:- Navigation structure- Search optimization- Versioned documentation- Interactive examples"
"Using Context7 MCP, check our dependencies:- Are we using deprecated APIs?- What's the migration path for outdated methods?- Which libraries have major updates?- What are the new best practices?"
// Update documentation accordingly"Based on Context7 findings, update our docs to:- Reference current API methods- Use modern syntax examples- Follow latest conventions- Include deprecation warnings"
Real-time Updates:
"Using Context7, what's new in React Router v6.4+?Update our routing documentation to reflect:- New data loading patterns- Error boundary changes- Route configuration updates"
Cross-Library Learning:
"Using Context7, how do popular libraries document:- Authentication flows (NextAuth, Auth0, Supabase)- State management (Redux, Zustand, Jotai)- Form handling (React Hook Form, Formik)Apply best patterns to our docs"
Version-Aware Documentation:
"Using Context7, create version-specific docs:- v1.x using old API- v2.x with new features- Migration guide between versions- Compatibility matrix"
@src"Generate comprehensive API documentation:- Extract all public APIs- Document parameters and return types- Include type information- Add usage examples for each method- Document edge cases and errors- Create cross-referencesUse JSDoc/TSDoc format"
Example generated documentation:
/** * Creates a connection pool for database operations with automatic * retry logic and connection recycling. * * @example * ```typescript * // Basic usage * const pool = createPool({ * host: 'localhost', * database: 'myapp', * max: 20 * }); * * // With advanced options * const pool = createPool({ * host: 'db.example.com', * port: 5432, * database: 'production', * user: 'dbuser', * password: process.env.DB_PASSWORD, * max: 50, * idleTimeoutMillis: 30000, * connectionTimeoutMillis: 2000, * retryAttempts: 3, * retryDelay: 1000, * ssl: { * rejectUnauthorized: true, * ca: fs.readFileSync('./ca-cert.pem') * } * }); * * // Using the pool * const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]); * ``` * * @param config - Pool configuration options * @param config.host - Database host address * @param config.port - Database port (default: 5432) * @param config.database - Database name * @param config.user - Database user * @param config.password - Database password * @param config.max - Maximum number of clients in the pool (default: 10) * @param config.idleTimeoutMillis - Idle client timeout (default: 10000) * @param config.connectionTimeoutMillis - Connection timeout (default: 0) * @param config.retryAttempts - Number of retry attempts (default: 3) * @param config.retryDelay - Delay between retries in ms (default: 1000) * @param config.ssl - SSL configuration object or boolean * * @returns A configured database pool instance * * @throws {ConnectionError} When unable to establish database connection * @throws {ConfigurationError} When required configuration is missing * @throws {SSLError} When SSL configuration is invalid * * @see {@link Pool} for pool instance methods * @see {@link query} for executing queries * @see {@link transaction} for transaction support * * @since 1.0.0 * @public */export function createPool(config: PoolConfig): Pool { validateConfig(config);
const pool = new Pool({ ...defaultConfig, ...config, // Retry logic wrapper Client: createRetryableClient(config), });
// Add event handlers pool.on('error', (err, client) => { logger.error('Unexpected error on idle client', err); });
pool.on('connect', (client) => { logger.debug('New client connected to pool'); });
return wrapPoolMethods(pool);}
/** * Pool configuration options * @public */export interface PoolConfig { /** Database host address */ host: string;
/** Database port @defaultValue 5432 */ port?: number;
/** Database name */ database: string;
/** Database user */ user?: string;
/** Database password */ password?: string;
/** * Maximum number of clients in the pool * @defaultValue 10 * @remarks * Consider your database's connection limits when setting this value. * Each client consumes resources on both application and database server. */ max?: number;
/** * Number of milliseconds a client must sit idle before being closed * @defaultValue 10000 */ idleTimeoutMillis?: number;
/** * Number of milliseconds to wait before timing out when connecting * @defaultValue 0 (no timeout) */ connectionTimeoutMillis?: number;
/** * Number of times to retry failed connections * @defaultValue 3 */ retryAttempts?: number;
/** * Delay between connection retry attempts in milliseconds * @defaultValue 1000 */ retryDelay?: number;
/** * SSL configuration * @example * ```typescript * // Enable SSL with default settings * ssl: true * * // Custom SSL configuration * ssl: { * rejectUnauthorized: true, * ca: fs.readFileSync('./ca-cert.pem'), * key: fs.readFileSync('./client-key.pem'), * cert: fs.readFileSync('./client-cert.pem') * } * ``` */ ssl?: boolean | SSLConfig;}
@src/types"Document all TypeScript types and interfaces:- Extract type definitions- Document type parameters- Show inheritance hierarchy- Create type usage examples- Document discriminated unions- Add type guards examples"
@src @tests"Generate code examples for all major features:- Basic usage examples- Advanced patterns- Error handling examples- Performance optimization examples- Integration examples- Full application examplesExtract from tests where possible"
@src @examples"Create a comprehensive getting started guide:- Installation instructions (npm, yarn, pnpm)- Basic setup and configuration- First simple example- Common use cases- Troubleshooting section- Next stepsMake it beginner-friendly but comprehensive"
Example getting started guide:
# Getting Started with MyLibrary
## Installation
MyLibrary can be installed using your favorite package manager:
```bash# npmnpm install mylibrary
# yarnyarn add mylibrary
# pnpmpnpm add mylibrary
// ES Modules (recommended)import { createPool, query } from 'mylibrary';
// CommonJSconst { createPool, query } = require('mylibrary');
import { createPool } from 'mylibrary';
// Create a connection poolconst pool = createPool({ host: 'localhost', database: 'myapp', user: 'myuser', password: 'mypassword'});
// Test the connectiontry { const result = await pool.query('SELECT NOW()'); console.log('Connected successfully:', result.rows[0]);} catch (error) { console.error('Connection failed:', error);}
// Simple queryconst users = await pool.query('SELECT * FROM users');console.log(`Found ${users.rowCount} users`);
// Parameterized query (prevents SQL injection)const userId = 123;const user = await pool.query( 'SELECT * FROM users WHERE id = $1', [userId]);
// Using the query builderconst activeUsers = await pool .select('id', 'name', 'email') .from('users') .where('active', true) .orderBy('created_at', 'DESC') .limit(10) .execute();
// Automatic connection managementasync function getUser(id: number) { // Connection is automatically acquired and released return pool.query('SELECT * FROM users WHERE id = $1', [id]);}
// Manual connection management for transactionsasync function transferFunds(from: number, to: number, amount: number) { const client = await pool.connect();
try { await client.query('BEGIN');
await client.query( 'UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from] );
await client.query( 'UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to] );
await client.query('COMMIT'); } catch (error) { await client.query('ROLLBACK'); throw error; } finally { client.release(); }}
import { DatabaseError, ConnectionError } from 'mylibrary';
try { const result = await pool.query('SELECT * FROM users');} catch (error) { if (error instanceof ConnectionError) { console.error('Database connection failed:', error.message); // Implement retry logic or fallback } else if (error instanceof DatabaseError) { console.error('Query failed:', error.message); // Log query details for debugging } else { console.error('Unexpected error:', error); }}
const pool = createPool({ host: process.env.DB_HOST || 'localhost', port: parseInt(process.env.DB_PORT || '5432'), database: process.env.DB_NAME || 'development', user: process.env.DB_USER, password: process.env.DB_PASSWORD, max: parseInt(process.env.DB_POOL_SIZE || '10'), // Enable SSL in production ssl: process.env.NODE_ENV === 'production'});
const pool = createPool({ // Connection settings host: 'db.example.com', port: 5432, database: 'production',
// Pool settings max: 20, // Maximum pool size min: 5, // Minimum pool size idleTimeoutMillis: 30000, // Close idle clients after 30s connectionTimeoutMillis: 2000, // Timeout new connections after 2s
// Retry settings retryAttempts: 3, retryDelay: 1000,
// Monitoring onConnect: (client) => { console.log('Client connected'); }, onError: (error, client) => { console.error('Pool error:', error); }});
Connection Timeout
// Increase connection timeoutconst pool = createPool({ connectionTimeoutMillis: 5000, // 5 seconds // ... other config});
Too Many Connections
// Monitor pool usageconsole.log('Total clients:', pool.totalCount);console.log('Idle clients:', pool.idleCount);console.log('Waiting requests:', pool.waitingCount);
// Adjust pool size based on usageconst pool = createPool({ max: 50, // Increase maximum connections // ... other config});
SSL Connection Issues
// Debug SSL connectionsconst pool = createPool({ ssl: { rejectUnauthorized: false, // Only for development! // For production, provide proper certificates ca: fs.readFileSync('./server-ca.pem'), }});
Now that you have MyLibrary up and running:
Explore Advanced Features
Best Practices
Integration Guides
2. **Create Topic Guides**
```typescript"Generate in-depth guides for specific topics:- Authentication patterns- Performance optimization- Error handling strategies- Testing approaches- Deployment guides- Security best practicesEach guide should be comprehensive and practical"
"Create interactive documentation:- Live code playgrounds- Runnable examples- Interactive API explorer- Step-by-step tutorials- Video demonstrationsUse CodeSandbox or similar"
@src"Create architecture documentation:- System overview diagram- Component relationships- Data flow diagrams- Sequence diagrams for key flows- Deployment architectureUse Mermaid or PlantUML"
Example architecture documentation:
# System Architecture
## Overview
MyLibrary follows a modular architecture designed for scalability and maintainability.
```mermaidgraph TB subgraph "Application Layer" APP[Your Application] end
subgraph "MyLibrary Core" API[Public API] QM[Query Manager] PM[Pool Manager] CM[Connection Manager] RM[Retry Manager] end
subgraph "Database Layer" PG[(PostgreSQL)] MY[(MySQL)] MS[(SQL Server)] end
APP --> API API --> QM API --> PM QM --> CM PM --> CM CM --> RM RM --> PG RM --> MY RM --> MS
Responsible for managing database connection pools:
Handles query execution and optimization:
Low-level connection handling:
Implements resilience patterns:
The core functionality has no external dependencies, ensuring:
Extended functionality through plugins:
import { createPool } from 'mylibrary';import { metricsPlugin } from 'mylibrary-metrics';import { cachingPlugin } from 'mylibrary-cache';
const pool = createPool({ // ... config plugins: [ metricsPlugin({ provider: 'prometheus' }), cachingPlugin({ ttl: 300 }) ]});
Full TypeScript support with:
2. **Document Design Decisions**
```typescript"Create ADR (Architecture Decision Records):- Key design decisions- Alternatives considered- Rationale for choices- Trade-offs accepted- Migration strategiesFollow ADR template"
"Document performance characteristics:- Benchmark results- Optimization techniques- Scaling strategies- Resource requirements- Bottleneck analysisInclude real measurements"
"Create automated documentation pipeline:- Extract docs from source code- Generate on every commit- Update version-specific docs- Deploy to documentation site- Notify about breaking changesUse GitHub Actions"
Example automation workflow:
name: Documentation
on: push: branches: [main] paths: - 'src/**' - 'docs/**' pull_request: branches: [main]
jobs: generate-docs: runs-on: ubuntu-latest
steps: - uses: actions/checkout@v3
- name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18' cache: 'npm'
- name: Install dependencies run: npm ci
- name: Generate API documentation run: | npm run docs:api npm run docs:types
- name: Check documentation coverage run: | npm run docs:coverage # Fail if coverage < 90%
- name: Generate examples from tests run: npm run docs:examples
- name: Build documentation site run: npm run docs:build
- name: Run documentation tests run: | # Test all code examples npm run docs:test-examples
# Check for broken links npm run docs:check-links
- name: Deploy to GitHub Pages if: github.ref == 'refs/heads/main' uses: peaceiris/actions-gh-pages@v3 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs/build
- name: Update search index if: github.ref == 'refs/heads/main' run: | npm run docs:update-search env: ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }}
"Create tests for documentation:- Validate code examples compile- Test example outputs- Check API completeness- Verify link integrity- Ensure version consistencyRun in CI/CD"
"Create documentation quality metrics:- Coverage percentage- Freshness indicators- Example completeness- Search effectiveness- User feedback integrationDisplay in dashboard"
Use Context7 to stay current:
// Research before documenting"Using Context7 MCP, research:- How does React document hooks?- What's the TypeScript standard for generics?- How do popular ORMs document queries?"
// Validate against current standards"Using Context7, verify our examples use:- Latest syntax (ES2024+)- Current library versions- Modern best practices- Non-deprecated APIs"
// Find documentation inspiration"Using Context7, show me excellent docs for:- API rate limiting- WebSocket connections- Authentication flowsUse as templates for our docs"
Treat docs like code:
/** * @example <caption>Basic connection pool</caption> * ```typescript * const pool = createPool({ * host: 'localhost', * database: 'myapp' * }); * ``` * * @example <caption>Production configuration</caption> * ```typescript * const pool = createPool({ * host: process.env.DB_HOST, * database: process.env.DB_NAME, * max: 50, * ssl: true * }); * ``` */export function createPool(config: PoolConfig): Pool { // Implementation}
Keep docs in sync with code:
// Generate docs from testsdescribe('createPool', () => { it('creates a basic pool', () => { // @doc-example: basic-pool const pool = createPool({ host: 'localhost', database: 'test' });
expect(pool).toBeDefined(); // @end-doc-example });});
Layer information for different audiences:
// Simple select queryconst users = await db .select('*') .from('users') .execute();
// Complex query with joinsconst posts = await db .select('posts.*', 'users.name as author') .from('posts') .join('users', 'posts.user_id', 'users.id') .where('posts.published', true) .orderBy('posts.created_at', 'DESC') .limit(10) .execute();
// Dynamic query buildingconst query = db.select().from('products');
if (filters.category) { query.where('category', filters.category);}
if (filters.priceRange) { query.whereBetween('price', [filters.priceRange.min, filters.priceRange.max] );}
const results = await query .orderBy(sortField, sortOrder) .paginate(page, perPage);
Problem: Code examples no longer work
Solution:
// Test all examples automaticallyimport { extractExamples } from './docs-utils';
describe('Documentation Examples', () => { const examples = extractExamples('./docs');
test.each(examples)('$name should run without errors', async ({ code }) => { const result = await runExample(code); expect(result.error).toBeUndefined(); } );});
Problem: Examples lack necessary setup
Solution:
## Complete Example
```typescript// Required importsimport { createPool } from 'mylibrary';import dotenv from 'dotenv';
// Load environment variablesdotenv.config();
// Create pool with error handlingasync function setupDatabase() { try { const pool = createPool({ host: process.env.DB_HOST, database: process.env.DB_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD });
// Test connection await pool.query('SELECT 1'); console.log('Database connected');
return pool; } catch (error) { console.error('Database connection failed:', error); process.exit(1); }}
// Use in applicationconst pool = await setupDatabase();
Problem: Users can’t find what they need
Solution:
// Add search metadata/** * @keywords connection, pool, database, postgres, mysql * @category Database * @since 1.0.0 */
// Create search synonymsconst searchSynonyms = { 'connect': ['connection', 'pool', 'client'], 'query': ['select', 'insert', 'update', 'delete', 'sql'], 'error': ['exception', 'failure', 'problem']};
Advanced documentation features:
Internationalization
Interactive Learning
AI-Powered Features
MCP-Enhanced Documentation
Your documentation succeeds when:
Projects with great documentation report:
Before publishing:
You’ve mastered documentation generation. Continue your journey:
Video Tutorials
Create engaging video documentation
API Explorer
Build interactive API playground
Contribution Guide
Enable community documentation
Continue to Next Lesson →