dead-code-analyzer
v1.5.0
Published
Dead code analyzer for ServiceNow with transitive/recursive dead code detection
Downloads
6
Maintainers
Readme
Dead Code Analyzer for ServiceNow
A powerful static analysis tool that identifies unused (dead) code in your ServiceNow scoped applications. Analyzes JavaScript from XML files, detects method definitions and usage patterns, and generates detailed reports to help you maintain a clean, efficient codebase.
🎯 Why Use This Tool?
- Improve Code Quality: Remove unused methods and reduce technical debt
- Faster Development: Easier navigation and understanding of active code
- Better Performance: Less code to load and maintain
- Reduced Risk: Identify and remove potentially vulnerable unused code
- Compliance: Meet code quality standards and audit requirements
✨ Features
- Comprehensive Analysis: Scans all ServiceNow XML files including Script Includes, Business Rules, UI Actions, and more
- Smart Detection: Uses Babel AST parsing for accurate JavaScript analysis
- ServiceNow Patterns: Recognizes
Class.create(), lifecycle methods, and ServiceNow-specific code patterns - Recursive Scanning: Analyzes nested directories and all XML-embedded JavaScript
- JavaScript Everywhere: Extracts and validates JavaScript from XML fields, CDATA sections, and attributes
- Detailed Reports: Generates actionable reports with line numbers, method details, and statistics
- Zero Configuration: Works out of the box with sensible defaults
- Fast: Analyzes hundreds of files in seconds
📋 Prerequisites
- Node.js 18 or higher
- ServiceNow XML export files from your scoped application
🚀 Quick Start
Installation
# Install globally
npm install -g dead-code-analyzer
# Or use with npx (no installation needed)
npx dead-code-analyzerBasic Usage
# Analyze current directory
dead-code-analyzer
# Analyze specific folder
dead-code-analyzer /path/to/servicenow/update
# Analyze with custom output location
dead-code-analyzer my-app -o ./reports/dead-code-report.txt
# Enable debug logging
dead-code-analyzer my-app -l debugExample Workflow
# 1. Export your ServiceNow application
# - In ServiceNow, go to System Applications > Studio
# - Select your application
# - Export to XML (Source Control > Export to XML)
# 2. Navigate to the exported update folder
cd ~/Downloads/my-app-export/update
# 3. Run the analyzer
dead-code-analyzer
# 4. Review the generated report
cat dead-code-report.txt
# 5. Clean up identified dead code
# - Review each method carefully
# - Remove unused private methods first
# - Test thoroughly after each removal💡 Real-World Example
Let's say you have a ServiceNow scoped application with 50+ Script Includes:
# Navigate to your application's update directory
cd ~/projects/my-incident-app/update
# Run the analyzer
dead-code-analyzer
# Output shows:
# ✓ Found 50 XML files
# ✓ Extracted 45 Script Includes
# ✓ Detected 250 methods
# ✗ Found 35 potentially unused methods (14%)
#
# Report saved to: dead-code-report.txtResults:
- Identified 35 unused methods across 12 files
- Removed 20 private helper methods safely
- Reviewed 15 public methods with team
- Cleaned up 400+ lines of dead code
- Improved code maintainability and reduced technical debt
📖 Usage
Command Options
dead-code-analyzer [path] [options]
Arguments:
path Path to folder containing ServiceNow XML files
(default: current directory)
Options:
-o, --output <path> Output file for the report (default: ./dead-code-report.txt)
-l, --log-level <level> Log level: debug, info, warn, error (default: info)
-h, --help Show help messageOutput
The analyzer generates a comprehensive text report showing:
============================================================
ANALYSIS SUMMARY
============================================================
📁 Files Analyzed: 410
📊 Total Methods: 171
✓ Methods Used: 617
✗ Dead Methods: 36 (21.05%)
- Private: 9
- Public: 27
📉 Dead Code Lines: ~349 lines🔍 What Gets Analyzed
The tool analyzes JavaScript code from all ServiceNow XML files, including:
- Script Includes (
sys_script_include) - Business Rules (
sys_script) - UI Actions (
sys_ui_action) - Scheduled Scripts (
sysauto_script) - Fix Scripts (
sys_script_fix) - Client Scripts (
sys_script_client) - UI Policies (
sys_ui_policy) - Workflow Scripts and more
What It Detects
Method Definitions:
- Prototype methods:
MyClass.prototype.myMethod = function() {} - Object methods:
{ myMethod: function() {} } - Function declarations:
function myMethod() {} - Arrow functions:
const myMethod = () => {} - Private methods (starting with
_)
Method Usage:
- Direct calls:
myMethod() - Member calls:
this.myMethod(),obj.myMethod() - Constructor calls:
new MyClass() - Chained calls:
obj.method1().method2() - Dynamic references in strings
Smart Exclusions
The tool automatically excludes:
- Client-callable methods (marked as
client_callable) - ServiceNow lifecycle methods (
initialize,type,constructor) - Methods from external libraries
- Dynamically invoked methods (when detected)
📊 Sample Report
================================================================================
SERVICENOW DEAD CODE ANALYSIS REPORT
================================================================================
Generated: November 6, 2025, 10:45 AM
Files Analyzed: 410
Analysis Duration: 0.93s
================================================================================
POTENTIALLY DEAD METHODS
================================================================================
File: MyScriptInclude.js (sys_script_include)
Class: MyScriptInclude
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[PRIVATE] _helperMethod()
Location: Lines 45-52 (8 lines)
Type: object
Reason: No references found
[PUBLIC] unusedMethod()
Location: Lines 78-95 (18 lines)
Type: object
Reason: No references found
⚠️ RECOMMENDATION: Review private methods first - they're safer to remove⚠️ Important Considerations
Understanding False Positives
The analyzer uses static analysis and may flag methods as dead that are actually used in ways it cannot detect:
- Dynamic invocation: Methods called via
eval(),window[methodName](), or computed properties - Framework callbacks: ServiceNow may call methods based on naming conventions
- External integrations: REST APIs, SOAP endpoints, or integration hub actions
- Client-side code: Methods invoked from UI Pages, widgets, or portal pages
- Reflection patterns: Methods accessed through
GlideRecord.getValue()or similar
Best Practices
✅ DO:
- Review each flagged method carefully before deletion
- Start with private methods (prefixed with
_) - they're safer to remove - Run comprehensive tests after removing any code
- Use version control and create a backup before cleanup
- Search globally for the method name (including in UI Actions, client scripts, etc.)
- Consider marking methods as
@deprecatedbefore removing
❌ DON'T:
- Delete all flagged methods without review
- Remove public methods without stakeholder approval
- Skip testing after code removal
- Forget to check for REST/SOAP/IntegrationHub usage
🔧 Advanced Usage
Custom Output Location
# Generate report in specific directory
dead-code-analyzer ~/my-app -o ~/reports/cleanup-$(date +%Y%m%d).txtDebug Mode
# See detailed analysis information
dead-code-analyzer my-app -l debugCI/CD Integration
# Add to your build pipeline
npx dead-code-analyzer /path/to/exported/xml -o build/dead-code-report.txt
# Check if dead code percentage exceeds threshold
# (requires custom scripting around the tool)🔧 Troubleshooting
"No files found to analyze"
Problem: The analyzer didn't find any XML files.
Solutions:
- Verify you're in the correct directory (should contain
.xmlfiles) - Check if files are exported correctly from ServiceNow
- Use absolute path:
dead-code-analyzer /full/path/to/update - Enable debug logging:
dead-code-analyzer -l debug
"Failed to parse X scripts"
Problem: Some JavaScript files have syntax errors.
Solutions:
- Review the list of failed files in the output
- Check if those files have valid JavaScript
- These files will be skipped, but analysis continues
- Fix syntax errors in ServiceNow and re-export
"Too many false positives"
Problem: Methods you know are used are flagged as dead.
Possible causes:
- Methods called dynamically or via eval
- Methods used in client-side scripts
- External API endpoints
- IntegrationHub actions
Solutions:
- Review carefully - these may be special cases
- Document why they're kept if flagged as dead
- Consider adding comments in code:
// Used by IntegrationHub
Performance Issues
Problem: Analysis is slow on large codebases.
Solutions:
- Analyze specific subdirectories first
- Use SSD storage for faster file I/O
- Close other applications to free memory
- Consider analyzing in smaller batches
🤝 Contributing
Contributions are welcome! Please:
- 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
Development Guidelines
- Follow existing code patterns (SOLID principles, design patterns)
- Add tests for new features
- Keep files under 500 lines
- Use comprehensive logging
- Update documentation
🐛 Known Limitations
- Dynamic method calls: Cannot detect methods invoked via
eval()or computed properties - Cross-scope calls: May miss methods called from different scoped applications
- Client-side usage: Cannot analyze methods called from UI scripts or portal widgets
- External systems: Cannot detect usage from REST/SOAP clients or external integrations
- GlideRecord patterns: Some ServiceNow-specific patterns may not be fully recognized
- Parse errors: Files with syntax errors will be skipped
📚 Resources
📄 License
MIT License - see LICENSE file for details
💬 Support
- Issues: Report bugs or request features on GitHub Issues
- Questions: For usage questions, please check existing issues first
- Community: Share your experience and help others
🙏 Acknowledgments
Built for the ServiceNow developer community to help maintain clean, efficient code.
Made with ❤️ for ServiceNow Developers
