JSDoc - pacificnm/wiki-ai GitHub Wiki

📖 JSDoc Documentation Standards

This document outlines the JSDoc documentation requirements and standards for the wiki-ai project.


🎯 Overview

JSDoc is used throughout the codebase to provide comprehensive documentation for functions, classes, modules, and other code elements. Proper JSDoc comments improve code maintainability and enable better IDE support.


📝 Basic JSDoc Syntax

Function Documentation

/**
 * Brief description of the function.
 * 
 * @param {string} title - The document title
 * @param {Object} options - Configuration options
 * @param {boolean} options.isPublic - Whether the document is public
 * @param {string[]} options.tags - Array of tags for the document
 * @returns {Promise<Object>} The created document object
 * @throws {Error} When title is empty
 * @example
 * const doc = await createDocument('My Title', { 
 *   isPublic: true, 
 *   tags: ['tutorial', 'guide'] 
 * });
 */
export async function createDocument(title, options) {
  // Implementation
}

Class Documentation

/**
 * Represents a document in the knowledge base.
 * 
 * @class
 * @extends BaseModel
 */
class Document extends BaseModel {
  /**
   * Create a new Document instance.
   * 
   * @param {Object} data - Document data
   * @param {string} data.title - Document title
   * @param {string} data.content - Document content
   */
  constructor(data) {
    super(data);
  }

  /**
   * Save the document to the database.
   * 
   * @async
   * @returns {Promise<Document>} The saved document
   * @memberof Document
   */
  async save() {
    // Implementation
  }
}

🏷️ Required JSDoc Tags

Core Tags (Required for all functions)

Tag Purpose Example
@description Function description (can be implicit) Creates a new document
@param Parameter description @param {string} title - The document title
@returns Return value description @returns {Promise<Object>} Created document

Optional Tags (Use when applicable)

Tag Purpose Example
@throws Documents exceptions @throws {ValidationError} When data is invalid
@example Usage example @example const result = await fn()
@async Marks async functions @async
@static Static methods @static
@memberof Class membership @memberof DocumentService
@override Overridden methods @override
@deprecated Deprecated functions @deprecated Use newFunction() instead

🏗️ Project-Specific Requirements

Controllers

/**
 * Create a new document.
 * 
 * @async
 * @function createDocument
 * @param {Object} req - Express request object
 * @param {Object} req.body - Request body containing document data
 * @param {string} req.body.title - Document title
 * @param {string} req.body.content - Document content
 * @param {Object} res - Express response object
 * @returns {Promise<void>} Sends JSON response
 * @throws {ValidationError} When request data is invalid
 * @throws {DatabaseError} When database operation fails
 * 
 * @example
 * // POST /api/documents
 * // Body: { title: "My Doc", content: "Content here" }
 * // Response: { success: true, document: {...} }
 */
export async function createDocument(req, res) {
  // Implementation
}

Services

/**
 * Document service for handling document operations.
 * 
 * @module DocumentService
 */

/**
 * Create a new document in the database.
 * 
 * @async
 * @function createDocument
 * @param {Object} documentData - Document data to create
 * @param {string} documentData.title - Document title
 * @param {string} documentData.content - Document content
 * @param {string} documentData.userId - ID of the user creating the document
 * @returns {Promise<Object>} The created document object
 * @throws {ValidationError} When document data is invalid
 * @throws {DatabaseError} When database operation fails
 * 
 * @example
 * const document = await createDocument({
 *   title: 'Getting Started',
 *   content: '# Welcome to the wiki',
 *   userId: '507f1f77bcf86cd799439011'
 * });
 */
export async function createDocument(documentData) {
  // Implementation
}

Models (Mongoose)

/**
 * Document model schema definition.
 * 
 * @typedef {Object} DocumentSchema
 * @property {string} title - Document title (required)
 * @property {string} content - Document content
 * @property {ObjectId} userId - Reference to User model
 * @property {string[]} tags - Array of document tags
 * @property {Date} createdAt - Creation timestamp
 * @property {Date} updatedAt - Last update timestamp
 */

/**
 * Mongoose model for documents.
 * 
 * @type {mongoose.Model<DocumentSchema>}
 */
export default mongoose.model('Document', documentSchema);

Middleware

/**
 * Authentication middleware to verify Firebase tokens.
 * 
 * @async
 * @function authenticateToken
 * @param {Object} req - Express request object
 * @param {Object} req.headers - Request headers
 * @param {string} req.headers.authorization - Authorization header with Bearer token
 * @param {Object} res - Express response object
 * @param {Function} next - Express next function
 * @returns {Promise<void>} Calls next() on success, sends error response on failure
 * @throws {AuthenticationError} When token is invalid or expired
 * 
 * @example
 * // Usage in routes
 * router.get('/protected', authenticateToken, (req, res) => {
 *   // req.user will be available here
 * });
 */
export async function authenticateToken(req, res, next) {
  // Implementation
}

🔧 Type Definitions

Custom Types

/**
 * User object structure.
 * 
 * @typedef {Object} User
 * @property {string} id - User ID
 * @property {string} email - User email address
 * @property {string} displayName - User display name
 * @property {('admin'|'user')} role - User role
 * @property {Date} createdAt - Account creation date
 */

/**
 * Document creation options.
 * 
 * @typedef {Object} CreateDocumentOptions
 * @property {boolean} [isPublic=false] - Whether document is publicly visible
 * @property {string[]} [tags=[]] - Document tags
 * @property {string} [categoryId] - Category ID for organization
 * @property {boolean} [createVersion=true] - Whether to create initial version
 */

MongoDB ObjectId Type

/**
 * MongoDB ObjectId type alias.
 * 
 * @typedef {import('mongoose').Types.ObjectId} ObjectId
 */

🚀 Best Practices

1. Be Descriptive but Concise

// ❌ Bad
/**
 * Gets doc
 */
function getDocument() {}

// ✅ Good  
/**
 * Retrieves a document by ID with populated references.
 * 
 * @param {string} id - Document ID
 * @returns {Promise<Object|null>} Document object or null if not found
 */
function getDocument(id) {}

2. Include Examples for Complex Functions

/**
 * Search documents with advanced filtering.
 * 
 * @param {Object} filters - Search filters
 * @param {string} [filters.query] - Text search query
 * @param {string[]} [filters.tags] - Filter by tags
 * @param {string} [filters.userId] - Filter by user
 * @returns {Promise<Object[]>} Array of matching documents
 * 
 * @example
 * // Search for documents with specific tags
 * const docs = await searchDocuments({
 *   query: 'tutorial',
 *   tags: ['beginner', 'guide'],
 *   userId: '507f1f77bcf86cd799439011'
 * });
 */

3. Document Error Conditions

/**
 * Update document by ID.
 * 
 * @param {string} id - Document ID
 * @param {Object} updates - Fields to update
 * @returns {Promise<Object>} Updated document
 * @throws {NotFoundError} When document doesn't exist
 * @throws {ValidationError} When update data is invalid
 * @throws {PermissionError} When user lacks update permission
 */

4. Use Proper Type Annotations

/**
 * Process document attachments.
 * 
 * @param {File[]} files - Array of uploaded files
 * @param {Object} options - Processing options
 * @param {number} options.maxSize - Maximum file size in bytes
 * @param {string[]} options.allowedTypes - Allowed MIME types
 * @returns {Promise<{success: boolean, files: Object[], errors: string[]}>} Processing results
 */

⚙️ IDE Integration

VS Code Configuration

Add to your .vscode/settings.json:

{
  "typescript.suggest.includeCompletions": "on",
  "javascript.suggest.includeCompletions": "on",
  "typescript.suggest.autoImports": true,
  "javascript.suggest.autoImports": true
}

ESLint Rules for JSDoc

// .eslintrc.js
module.exports = {
  plugins: ['jsdoc'],
  rules: {
    'jsdoc/require-description': 'error',
    'jsdoc/require-param': 'error',
    'jsdoc/require-param-description': 'error',
    'jsdoc/require-returns': 'error',
    'jsdoc/require-returns-description': 'error'
  }
};

📋 Documentation Checklist

Before committing code, ensure:

  • All public functions have JSDoc comments
  • All parameters are documented with correct types
  • Return values are documented
  • Error conditions are documented with @throws
  • Complex functions include @example tags
  • Custom types are defined with @typedef
  • Async functions are marked with @async
  • Class methods include @memberof tags

🔗 Resources

⚠️ **GitHub.com Fallback** ⚠️