ts-wp-payload-migration
v1.0.9
Published
WordPress to Payload CMS migration effort estimation tool
Downloads
30
Maintainers
Readme
WordPress to Payload CMS Migration Tool
A comprehensive TypeScript CLI tool for analyzing WordPress sites and generating detailed migration effort estimations, reports, and migration scripts for transitioning to Payload CMS.
🚀 Features
Core Analysis Capabilities
- WordPress Site Analysis: Deep scanning of WordPress installations, themes, plugins, and content
- SEO Plugin Detection: Comprehensive analysis of Yoast SEO, RankMath, All in One SEO, and custom SEO implementations
- Plugin Compatibility Assessment: Evaluation of WordPress plugins and their Payload CMS equivalents
- Theme Analysis: Custom theme code analysis and complexity assessment
- Database Schema Mapping: Automated mapping of WordPress database structures to Payload collections
- URL Structure Analysis: Permalink patterns, redirects, and URL migration planning
- Content Type Discovery: Automatic detection of custom post types, taxonomies, and meta fields
Migration Planning & Estimation
- Effort Estimation Engine: AI-powered estimation of migration complexity and time requirements
- Risk Assessment: Identification of potential migration risks and mitigation strategies
- Resource Planning: Team size and skill requirements analysis
- Timeline Generation: Detailed project timeline with milestones and dependencies
- Cost Estimation: Budget planning with breakdown by development phases
Report Generation
- Multi-Format Output: PDF, HTML, JSON, CSV, and Markdown reports
- Executive Summaries: High-level overviews for stakeholders
- Technical Documentation: Detailed technical specifications for developers
- Migration Scripts: Ready-to-use migration code and configurations
- Testing Checklists: Comprehensive QA and testing guidelines
📋 Prerequisites
- Node.js: Version 18.0.0 or higher
- TypeScript: Version 5.8.3 or higher
- Database Access: MySQL connection to WordPress database
- WordPress Access: File system access to WordPress installation
🛠️ Installation
Global Installation
npm install -g ts-wp-payload-migrationLocal Development
# Clone the repository
git clone https://github.com/techseria/ts-wp-payload-migration.git
cd ts-wp-payload-migration
# Install dependencies
npm install
# Build the project
npm run build
# Link for local development
npm link🎯 Quick Start
Automatic Analysis (Recommended)
The tool now automatically discovers WordPress configuration from wp-config.php:
# Navigate to your WordPress document root and run analysis
cd /var/www/html
ts-wp-payload-migration analyze
# Or specify WordPress root directory
ts-wp-payload-migration analyze --wp-root /path/to/wordpress
# Generate specific report formats
ts-wp-payload-migration analyze --format html,pdf,json --output ./reportsAdvanced Usage
# Full analysis with custom branding and options
ts-wp-payload-migration analyze \
--format pdf,html,json,csv \
--company "My Agency" \
--primary-color "#2563eb" \
--output ./detailed-report \
--verbose
# Exclude specific sections from reports
ts-wp-payload-migration analyze \
--exclude-sections executiveSummary,riskAssessment \
--csv-tables content,plugins,tasksWhat Happens Automatically
- 🔍 WordPress Discovery: Automatically finds
wp-config.phpin current directory - 🔐 Database Connection: Extracts database credentials from
wp-config.php - 🌐 Site URL Detection: Determines site URL from WordPress configuration
- 🗄️ Database Analysis: Connects and analyzes WordPress database content
- 📊 Report Generation: Creates comprehensive migration reports
Error Handling & Database Connection
The tool provides robust error handling with detailed, actionable error messages and comprehensive database connection management:
Database Connection Features
- Robust Error Handling: Comprehensive error classification with specific error types (authentication, permission, timeout, network, etc.)
- Safe Property Access: Uses optional chaining (
?.) throughout database connection logic to prevent runtime errors - Enhanced Logging: Detailed logging at multiple levels (verbose, info, warn, error) for troubleshooting
- Connection Pooling: Efficient connection pool management with automatic cleanup
- Read-Only Mode: Enforced read-only database access to prevent accidental data modification during analysis
- Retry Logic: Exponential backoff with jitter for failed connection attempts
- MySQL/MariaDB Compatibility: Full compatibility with both MySQL (5.7+) and MariaDB (10.2+)
Error Message Examples
# If wp-config.php is not found
❌ WordPress configuration not found!
Please ensure you're running this command from a WordPress document root directory.
# If database connection fails with specific error details
❌ Database connection failed: [authentication] Invalid credentials (code: ER_ACCESS_DENIED_ERROR)
Please check your WordPress database configuration in wp-config.php.
# If database host is unreachable
❌ Database connection failed: [network] Host 'localhost' not found (code: ENOTFOUND)
Please verify the database host configuration.
# If database permissions are insufficient
❌ Database connection failed: [permission] User 'wp_user' has no access to database 'wordpress_db'
Please check database user permissions.Database Connection Logging
The tool provides comprehensive logging for database operations:
# Verbose logging shows detailed connection process
🔌 Establishing database connection
🌐 Parsed connection details: host=localhost, port=3306
🏊 Creating connection pool
✅ Database connection established successfully
🔒 Enforcing read-only mode
📊 Retrieving server version: MySQL 8.0.35
🔤 Character set: utf8mb4Connection Pool Management
- Automatic Resource Cleanup: Connections are properly released back to the pool
- Pool Status Monitoring: Real-time tracking of active, idle, and total connections
- Safe Property Access: Uses optional chaining for pool configuration access
- Connection Validation: Ping tests and metadata retrieval before use
- Graceful Degradation: Handles connection failures with detailed error context
## 📁 Project Structure
ts-wp-payload-migration/ ├── src/ │ ├── commands/ # CLI command implementations │ │ ├── analyze.ts # Main analysis command │ │ └── index.ts # Command exports │ ├── core/ # Core analysis engine │ │ ├── analysis-orchestrator.ts # Main orchestration logic │ │ ├── types.ts # Core type definitions │ │ ├── seo-types.ts # SEO-specific types │ │ └── url-redirect-types.ts # URL/redirect types │ ├── scanners/ # WordPress analysis scanners │ │ ├── database-scanner.ts # Database analysis │ │ ├── plugin-analyzer.ts # Plugin detection & analysis │ │ ├── theme-analyzer.ts # Theme code analysis │ │ ├── seo-scanner.ts # SEO plugin detection │ │ ├── redirect-scanner.ts # URL redirect analysis │ │ ├── meta-field-analyzer.ts # Custom fields analysis │ │ └── index.ts # Scanner exports │ ├── estimators/ # Effort estimation engines │ │ ├── complexity-assessor.ts # Complexity calculations │ │ ├── effort-calculator.ts # Time/effort estimation │ │ ├── risk-assessment-engine.ts # Risk analysis │ │ └── estimation-engine.ts # Main estimation logic │ ├── generators/ # Report and code generators │ │ ├── report-generator.ts # Report generation │ │ ├── migration-planner.ts # Migration planning │ │ ├── payload-schema-generator.ts # Payload config generation │ │ ├── seo-mapping-generator.ts # SEO field mappings │ │ ├── pdf-generator.ts # PDF report generation │ │ └── templates/ # Report templates │ └── utils/ # Utility functions │ ├── config.ts # Configuration management │ ├── logger.ts # Logging utilities │ └── cache.ts # Caching mechanisms ├── dist/ # Compiled JavaScript output ├── docs/ # Documentation ├── examples/ # Usage examples └── tests/ # Test suites
## 🔧 Configuration
### Configuration File Example
```json
{
"database": {
"host": "localhost",
"port": 3306,
"database": "wordpress_db",
"username": "wp_user",
"password": "wp_pass"
},
"analysis": {
"includeSEO": true,
"includePlugins": true,
"includeThemes": true,
"includeCustomFields": true,
"includeRedirects": true
},
"output": {
"formats": ["pdf", "html", "json"],
"includeExecutiveSummary": true,
"includeTechnicalDetails": true,
"includeCodeSamples": true
},
"estimation": {
"teamSize": 3,
"experienceLevel": "intermediate",
"includeQA": true,
"includeDeployment": true
}
}Environment Variables
# Database Configuration
WP_DB_HOST=localhost
WP_DB_PORT=3306
WP_DB_NAME=wordpress_db
WP_DB_USER=wp_user
WP_DB_PASS=wp_pass
# Output Configuration
OUTPUT_DIR=./migration-reports
DEFAULT_FORMAT=pdf,html,json
# Analysis Options
INCLUDE_SEO=true
INCLUDE_PLUGINS=true
INCLUDE_THEMES=true📊 Analysis Components
1. WordPress Site Scanner
- File System Analysis: Scans WordPress core, themes, and plugins
- Database Schema Discovery: Maps WordPress database structure
- Content Analysis: Analyzes posts, pages, custom post types, and taxonomies
- Media Library Assessment: Evaluates media files and attachments
2. SEO Analysis Engine
- Plugin Detection: Identifies and analyzes SEO plugins (Yoast, RankMath, AIOSEO)
- Meta Field Mapping: Maps SEO meta fields to Payload CMS structure
- Schema.org Analysis: Detects structured data implementations
- Social Media Integration: Analyzes Open Graph and Twitter Card configurations
3. Plugin Compatibility Assessor
- Functionality Mapping: Maps WordPress plugins to Payload CMS equivalents
- Custom Code Detection: Identifies custom plugin modifications
- API Integration Analysis: Evaluates third-party integrations
- Security Assessment: Identifies potential security considerations
4. Theme Analysis System
- Template Hierarchy: Analyzes WordPress template structure
- Custom Code Complexity: Evaluates custom PHP, JavaScript, and CSS
- Hook Usage: Identifies WordPress hooks and filters usage
- Performance Impact: Assesses theme performance characteristics
📈 Estimation Algorithms
Complexity Scoring
- Low Complexity (1-3): Standard WordPress sites with minimal customization
- Medium Complexity (4-6): Sites with custom themes, moderate plugin usage
- High Complexity (7-10): Heavily customized sites with complex integrations
Effort Calculation Factors
- Content Volume: Number of posts, pages, and media files
- Custom Functionality: Custom post types, fields, and taxonomies
- Plugin Dependencies: Number and complexity of active plugins
- Theme Customization: Level of custom theme development
- SEO Implementation: Complexity of SEO setup and configurations
- Third-party Integrations: External API integrations and services
Risk Assessment Matrix
- Technical Risks: Complex custom code, deprecated functions, security vulnerabilities
- Data Risks: Large databases, complex relationships, data integrity concerns
- Timeline Risks: Resource availability, dependency management, testing requirements
- Business Risks: Downtime considerations, SEO impact, user experience changes
📋 Generated Reports
Executive Summary
- Project overview and recommendations
- High-level timeline and budget estimates
- Key risks and mitigation strategies
- Resource requirements and team composition
Technical Documentation
- Detailed WordPress analysis results
- Payload CMS configuration recommendations
- Database migration scripts and procedures
- SEO field mapping and migration strategies
Migration Scripts
- Payload CMS collection configurations
- Database migration scripts
- Content import procedures
- SEO data migration utilities
Testing Checklists
- Functional testing requirements
- Content validation procedures
- SEO verification steps
- Performance testing guidelines
🧪 Testing
# Run all tests
npm test
# Run specific test suites
npm run test:unit
npm run test:integration
npm run test:e2e
# Run tests with coverage
npm run test:coverage
# Run linting
npm run lint
# Format code
npm run format🚀 Development
Building the Project
# Clean previous builds
npm run clean
# Build for production
npm run build
# Build and watch for changes
npm run devCode Quality
- TypeScript: Strict type checking enabled
- ESLint: Code linting with TypeScript rules
- Prettier: Code formatting
- Husky: Pre-commit hooks for quality assurance
Contributing Guidelines
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📚 API Reference
Core Classes
AnalysisOrchestrator
Main orchestration class for WordPress analysis.
import { AnalysisOrchestrator } from './core/analysis-orchestrator';
const orchestrator = new AnalysisOrchestrator(config);
const results = await orchestrator.runAnalysis(wordpressPath);EstimationEngine
Effort and complexity estimation engine.
import { EstimationEngine } from './estimators/estimation-engine';
const engine = new EstimationEngine();
const estimate = engine.calculateEffort(analysisResults);ReportGenerator
Multi-format report generation.
import { ReportGenerator } from './generators/report-generator';
const generator = new ReportGenerator();
await generator.generateReport(results, { format: 'pdf' });Utility Functions
Database Connection
import { createDatabaseConnection } from './utils/database';
const connection = await createDatabaseConnection(dbConfig);Configuration Management
import { loadConfig } from './utils/config';
const config = loadConfig('./migration-config.json');🔍 Troubleshooting
Common Issues
Database Connection Errors
The tool provides detailed error classification and troubleshooting guidance:
# Check database connectivity manually
mysql -h localhost -u wp_user -p wordpress_db
# Verify credentials in wp-config.php
cat wp-config.php | grep -E "(DB_NAME|DB_USER|DB_PASSWORD|DB_HOST)"
# Test connection with verbose logging
DEBUG=wp-migration:* ts-wp-payload-migration analyze /path/to/wordpress --verboseCommon Database Error Types and Solutions:
Authentication Errors (
ER_ACCESS_DENIED_ERROR):- Verify username and password in wp-config.php
- Check if database user exists and has correct permissions
Database Not Found (
ER_BAD_DB_ERROR):- Confirm database name in wp-config.php matches actual database
- Verify database exists on the server
Permission Errors (
ER_DBACCESS_DENIED_ERROR):- Grant appropriate permissions to database user
- Ensure user has SELECT privileges on WordPress tables
Connection Refused (
ECONNREFUSED):- Check if MySQL/MariaDB service is running
- Verify host and port configuration
Host Not Found (
ENOTFOUND):- Verify database host address
- Check DNS resolution for remote hosts
Connection Timeout (
ETIMEDOUT):- Increase connection timeout in configuration
- Check network connectivity to database server
Connection Pool Troubleshooting:
# Monitor connection pool status in logs
ts-wp-payload-migration analyze --verbose 2>&1 | grep -E "(pool|connection)"
# Check for connection leaks
ts-wp-payload-migration analyze --verbose 2>&1 | grep -E "(release|cleanup)"File Permission Issues
# Ensure read access to WordPress directory
chmod -R 755 /path/to/wordpress
# Check file ownership
ls -la /path/to/wordpressMemory Issues with Large Sites
# Increase Node.js memory limit
node --max-old-space-size=4096 ./dist/run.mjs analyzeDebug Mode
# Enable debug logging
DEBUG=wp-migration:* ts-wp-payload-migration analyze /path/to/wordpress
# Verbose output
ts-wp-payload-migration analyze /path/to/wordpress --verbose📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🤝 Support
- Documentation: Full documentation
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: [email protected]
🙏 Acknowledgments
- Payload CMS for the excellent headless CMS platform
- WordPress for the robust content management system
- OCLIF for the CLI framework
- TypeScript for type safety and developer experience
Made with ❤️ for the WordPress and Payload CMS communities
