npm package: @omindu/seo.js
Description: SEO optimization Library for modern web applications - Comprehensive solution for meta tags, structured data, sitemaps, robots optimization, performance metrics, and search engine ranking factors
Author: Omindu Dissanayaka
Latest version: 1.1.0

# SEO.js - Search Engine Optimization Library

[![npm version](https://img.shields.io/npm/v/@omindu/seo.js.svg)](https://www.npmjs.com/package/@omindu/seo.js)
[![license](https://img.shields.io/npm/l/@omindu/seo.js.svg)](https://opensource.org/licenses/MIT)
[![downloads](https://img.shields.io/npm/dm/@omindu/seo.js.svg)](https://www.npmjs.com/package/@omindu/seo.js)

**SEO.js** is a comprehensive, modern SEO optimization framework for web applications. It provides a complete solution for meta tags management, structured data (JSON-LD), sitemap generation, robots optimization, performance monitoring, accessibility enhancement, mobile optimization, and much more.

## 📋 Table of Contents

- [Features](#-features)
- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Core Concepts](#-core-concepts)
- [API Reference](#-api-reference)
  - [Meta Tag Management](#meta-tag-management)
  - [Structured Data](#structured-data)
  - [Sitemap Generator](#sitemap-generator)
  - [Robots Optimizer](#robots-optimizer)
  - [Performance Optimizer](#performance-optimizer)
  - [Accessibility Enhancer](#accessibility-enhancer)
  - [Mobile Optimizer](#mobile-optimizer)
  - [Keyword Analyzer](#keyword-analyzer)
  - [Link Optimizer](#link-optimizer)
  - [Content Optimizer](#content-optimizer)
  - [Image Optimizer](#image-optimizer)
  - [URL Optimizer](#url-optimizer)
  - [Social Media Optimizer](#social-media-optimizer)
  - [Local SEO Optimizer](#local-seo-optimizer)
  - [E-commerce Optimizer](#e-commerce-optimizer)
- [Examples](#-examples)
- [Browser Support](#-browser-support)
- [License](#-license)

## ✨ Features

- **Meta Tags** - Full control over all meta tags, Open Graph, Twitter Cards
- **Structured Data** - JSON-LD schema generation for 15+ schema types
- **Sitemap** - XML sitemap generation with images, videos, news support
- **Performance** - Core Web Vitals monitoring, resource optimization
- **Accessibility** - WCAG compliance checks and improvements
- **Mobile** - Viewport optimization, touch improvements
- **Content Analysis** - Readability scoring, keyword density, heading structure
- **Link Management** - Internal/external link analysis, nofollow optimization
- **Image Optimization** - Lazy loading, alt text, dimension validation
- **URL Optimization** - Canonical URLs, trailing slashes, SEO-friendly URLs
- **Social Media** - Open Graph, Twitter Cards, share links
- **Local SEO** - LocalBusiness schema, Google Maps integration
- **E-commerce** - Product schema, reviews, Google Shopping feeds
- **Analytics** - SEO scoring, performance metrics, event tracking
- **Caching** - Built-in cache manager for performance
- **UMD Support** - Works with CommonJS, AMD, global variable

## 📦 Installation

### NPM

```bash
npm install @omindu/seo.js
```

### CDN

```html
<script src="https://unpkg.com/@omindu/seo.js@1.1.0/dist/seo.min.js"></script>
```

### Manual Download

Download the `seo.js` file and include it in your project:

```html
<script src="seo.js"></script>
```

## 🚀 Quick Start

### Basic Initialization

```javascript
// Create SEO instance with default config
const seo = SEO.create();

// Or with custom configuration
const seo = new SEO({
  debug: true,
  defaultLanguage: 'en',
  enablePerformanceMonitoring: true
});

// Initialize
seo.init();
```

### Complete Page Setup

```javascript
const seo = new SEO({ debug: true });

seo.setupPage({
  title: 'My Awesome Website - Home',
  description: 'This is the best website for learning SEO optimization',
  keywords: 'seo, optimization, javascript, library',
  author: 'Your Name',
  image: 'https://example.com/og-image.jpg',
  url: window.location.href,
  
  // Structured data with multiple schema types
  structuredData: {
    'Organization': {
      name: 'My Company',
      url: 'https://example.com',
      logo: 'https://example.com/logo.png',
      address: {
        streetAddress: '123 Business St',
        addressLocality: 'San Francisco',
        addressRegion: 'CA',
        postalCode: '94105',
        addressCountry: 'US'
      }
    },
    'Article': {
      headline: 'My Awesome Website - Home',
      description: 'This is the best website for learning SEO optimization',
      author: 'Your Name',
      datePublished: '2024-01-01',
      image: 'https://example.com/og-image.jpg'
    }
  }
});

// Generate SEO score
const score = seo.generateSEOScore();
console.log('SEO Score:', score.overall);
```

## 🎯 Core Concepts

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | boolean | `false` | Enable debug logging |
| `autoInit` | boolean | `true` | Auto initialize on load |
| `crawlDelay` | number | `1000` | Crawl delay for robots |
| `cacheTTL` | number | `3600000` | Cache TTL in milliseconds |
| `maxSitemapUrls` | number | `50000` | Max URLs per sitemap |
| `defaultLanguage` | string | `'en'` | Default language |
| `enablePerformanceMonitoring` | boolean | `true` | Enable Core Web Vitals |
| `enableAccessibilityChecks` | boolean | `true` | Enable WCAG checks |
| `enableMobileOptimization` | boolean | `true` | Enable mobile optimizations |

## 📚 API Reference

### Meta Tag Management

The MetaTagManager provides complete control over HTML meta tags.

```javascript
const metaManager = seo.engine.metaManager;

// Set individual meta tags
metaManager.setMetaTag('description', 'Your page description');
metaManager.setMetaTag('keywords', 'seo, javascript, library');
metaManager.setMetaTag('author', 'Your Name');

// Set Open Graph tags
metaManager.setMetaTag('og:title', 'Your Title');
metaManager.setMetaTag('og:image', 'https://example.com/image.jpg');

// Set default meta tags (applied if not exists)
metaManager.setDefaultMetaTags({
  'viewport': 'width=device-width, initial-scale=1'
});

// Set canonical URL
metaManager.setCanonicalURL('https://example.com/current-page');

// Set page title
metaManager.setTitle('My Page Title');

// Get meta tag score
const metaScore = metaManager.getScore();
console.log('Meta Tags Score:', metaScore);
```

### Structured Data

Generate JSON-LD structured data for rich snippets. Call via `setupPage()` or directly:

```javascript
const structuredDataManager = seo.engine.structuredDataManager;

// Add article schema
structuredDataManager.addArticleSchema({
  headline: 'How to Optimize SEO',
  description: 'Complete guide to SEO optimization',
  author: 'John Doe',
  datePublished: '2024-01-15',
  image: 'https://example.com/article.jpg'
});

// Add product schema
structuredDataManager.addProductSchema({
  name: 'Premium SEO Tool',
  description: 'Advanced SEO optimization software',
  image: 'https://example.com/product.jpg',
  offers: {
    price: '99.99',
    priceCurrency: 'USD'
  }
});

// Add event schema
structuredDataManager.addEventSchema({
  name: 'SEO Conference 2024',
  description: 'Annual SEO conference',
  startDate: '2024-06-15T09:00',
  endDate: '2024-06-17T18:00',
  location: {
    name: 'Convention Center',
    address: '123 Main St'
  }
});

// Add FAQ schema
structuredDataManager.addFAQPageSchema({
  items: [
    {
      question: 'What is SEO?',
      answer: 'SEO stands for Search Engine Optimization'
    }
  ]
});

// Add breadcrumb schema
structuredDataManager.addBreadcrumbSchema([
  { name: 'Home', url: 'https://example.com/' },
  { name: 'Products', url: 'https://example.com/products' }
]);

// Add organization schema
structuredDataManager.addOrganizationSchema({
  name: 'My Company',
  url: 'https://example.com',
  logo: 'https://example.com/logo.png'
});

// Get structured data score
const sdScore = structuredDataManager.getScore();
console.log('Structured Data Score:', sdScore);
```

### Sitemap Generator

Generate XML sitemaps with support for images, videos, and news.

```javascript
const sitemapManager = seo.engine.sitemapManager;

// Add single URL
sitemapManager.addURL('https://example.com/page-1', {
  lastmod: '2024-01-15',
  changefreq: 'weekly',
  priority: 0.8,
  images: [
    {
      loc: 'https://example.com/image1.jpg',
      title: 'Image 1',
      caption: 'Description of image 1'
    }
  ]
});

// Add multiple URLs
seo.sitemap.addMultipleURLs([
  {
    loc: 'https://example.com/page-2',
    priority: 0.7,
    changefreq: 'monthly'
  },
  {
    loc: 'https://example.com/page-3',
    priority: 0.6,
    changefreq: 'monthly'
  }
]);

// Generate sitemap XML
const sitemapXML = seo.sitemap.generateSitemap();
console.log(sitemapXML);

// Generate robots.txt
const robotsTxt = seo.sitemap.generateRobotsTxt();
console.log(robotsTxt);
```

### Robots Optimizer

control search engine crawling behavior.

```javascript
const robotManager = seo.engine.robotManager;

// Allow/disallow crawling
robotManager.allowCrawling('/public');
robotManager.disallowCrawling('/private');
robotManager.disallowCrawling('/admin');

// Set crawl delay
robotManager.setCrawlDelay(5); // 5 seconds

// Set robots directives
robotManager.setRobotsDirective('noarchive');
robotManager.setRobotsDirective('nosnippet');
```

### Performance Optimizer

Monitor Core Web Vitals and optimize resource loading.

```javascript
const perfOptimizer = seo.engine.performanceOptimizer;

// Analyze page performance
const performanceMetrics = perfOptimizer.analyzePageSpeed();
console.log({
  pageLoad: performanceMetrics.pageLoad,
  timeToFirstByte: performanceMetrics.timeToFirstByte
});

// Get performance score
const perfScore = perfOptimizer.getScore();
console.log('Performance Score:', perfScore);
```

### Accessibility Enhancer

Improve WCAG compliance automatically.

```javascript
const a11yEnhancer = seo.engine.accessibilityEnhancer;

// Accessibility checks happen automatically
// - Adds skip to content link
// - Ensures all images have alt text
// - Sets language attribute
// - Ensures proper heading structure
// - Adds ARIA landmarks

// Check accessibility score
const a11yScore = a11yEnhancer.getScore();
console.log('Accessibility Score:', a11yScore);
```

### Mobile Optimizer

Optimize for mobile devices.

```javascript
const mobileOptimizer = seo.engine.mobileOptimizer;

// Mobile optimization happens automatically
// - Sets proper viewport
// - Ensures touch-friendly elements
// - Makes images responsive

// Check mobile optimization score
const mobileScore = mobileOptimizer.getScore();
console.log('Mobile Score:', mobileScore);
```

### Keyword Analyzer

Analyze keyword usage and density.

```javascript
const keywordAnalyzer = seo.engine.keywordAnalyzer;

const keywordAnalysis = keywordAnalyzer.analyzePageContent();
console.log({
  recommendations: keywordAnalysis.recommendations
});

// Get keyword score
const keywordScore = keywordAnalyzer.getScore();
```

### Link Optimizer

Analyze and optimize internal/external links.

```javascript
const linkOptimizer = seo.engine.linkOptimizer;

// Analyze all links on page
const linkAnalysis = linkOptimizer.analyzeLinks();
console.log({
  internalLinks: linkAnalysis.internal.length,
  externalLinks: linkAnalysis.external.length,
  totalLinks: linkAnalysis.total
});

// Get link optimization score
const linkScore = linkOptimizer.getScore();
console.log('Link Score:', linkScore);
```

### Content Optimizer

Analyze content quality and readability.

```javascript
const contentOptimizer = seo.engine.contentOptimizer;

const contentAnalysis = contentOptimizer.analyzeContentQuality();
console.log({
  recommendations: contentAnalysis.recommendations
});

// Get content score
const contentScore = contentOptimizer.getScore();
console.log('Content Score:', contentScore);
```

### Image Optimizer

Optimize images for SEO and performance.

```javascript
const imageOptimizer = seo.engine.imageOptimizer;

// Enable lazy loading
imageOptimizer.optimizeLazyLoading();

// Analyze all images
const imageAnalysis = imageOptimizer.analyzeImages();
imageAnalysis.forEach(img => {
  console.log({
    src: img.src,
    alt: img.alt,
    hasDimensions: img.hasDimensions,
    isLazyLoaded: img.isLazyLoaded
  });
});

// Get image optimization score
const imageScore = imageOptimizer.getScore();
console.log('Image Score:', imageScore);
```

### URL Optimizer

Optimize URL structure for SEO.

```javascript
const urlOptimizer = seo.engine.urlOptimizer;

// Generate SEO-friendly URL from title
const seoUrl = urlOptimizer.generateSEOFriendlyURL('My Awesome Article!');
console.log(seoUrl); // "my-awesome-article"
```

### Social Media Optimizer

Optimize for social media sharing.

```javascript
const socialOptimizer = seo.engine.socialMediaOptimizer;

// Generate Open Graph tags
socialOptimizer.generateOpenGraphTags({
  title: 'My Awesome Content',
  description: 'Check out this amazing article',
  image: 'https://example.com/image.jpg',
  url: 'https://example.com/article'
});

// Generate Twitter Card tags
socialOptimizer.generateTwitterCardTags({
  cardType: 'summary_large_image',
  site: '@mysite',
  creator: '@author',
  title: 'My Awesome Content',
  description: 'Check out this amazing article',
  image: 'https://example.com/image.jpg'
});

// Generate social share links
const shareLinks = socialOptimizer.generateSocialShareLinks({
  url: 'https://example.com/article',
  title: 'My Awesome Content',
  description: 'Check out this amazing article'
});
console.log(shareLinks);

// Get social media optimization score
const socialScore = socialOptimizer.getScore();
console.log('Social Media Score:', socialScore);

// Generate social share links
const shareLinks = seo.engine.socialMediaOptimizer.generateSocialShareLinks({
  url: 'https://example.com/article',
  title: 'My Awesome Article'
});
console.log(shareLinks);
// {
//   facebook: 'https://facebook.com/sharer.php?u=...',
//   twitter: 'https://twitter.com/intent/tweet?url=...',
//   linkedin: 'https://linkedin.com/shareArticle?url=...',
//   ...
// }

// Get social media score
const socialScore = seo.engine.socialMediaOptimizer.getScore();
```

### Local SEO Optimizer

Optimize for local search.

```javascript
// Setup local business
seo.engine.localSEOOptimizer.setupLocalBusiness({
  name: 'My Local Store',
  url: 'https://mystore.com',
  logo: 'https://mystore.com/logo.png',
  description: 'Best local store in town',
  address: '123 Main St',
  city: 'New York',
  region: 'NY',
  postalCode: '10001',
  country: 'US',
  phone: '+1-212-555-1234',
  hours: ['Mo-Fr 09:00-17:00', 'Sa 10:00-14:00'],
  coordinates: {
    lat: 40.7128,
    lng: -74.0060
  },
  priceRange: '$$',
  contactPoints: [
    {
      phone: '+1-212-555-1234',
      type: 'customer service',
      languages: ['en', 'es']
    }
  ]
});

// Generate Google Maps link
const mapLink = seo.engine.localSEOOptimizer.addGoogleMapsLink('123 Main St, New York, NY 10001');
document.body.appendChild(mapLink);

// Generate local business schema
const localSchema = seo.engine.localSEOOptimizer.generateLocalBusinessSchema();
```

### E-commerce Optimizer

Optimize e-commerce products.

```javascript
// Add product
seo.engine.ecommerceOptimizer.addProduct({
  id: 'PROD-123',
  name: 'Premium SEO Tool',
  description: 'Professional SEO optimization software',
  price: 99.99,
  currency: 'USD',
  image: 'https://example.com/product.jpg',
  url: 'https://example.com/product/seo-tool',
  brand: 'SEO Pro',
  sku: 'SEO-123',
  mpn: 'MPN-456',
  availability: 'https://schema.org/InStock',
  aggregateRating: {
    value: 4.5,
    count: 128,
    bestRating: 5
  }
});

// Add product review
seo.engine.ecommerceOptimizer.addProductReview('PROD-123', {
  author: 'John Doe',
  rating: 5,
  body: 'Excellent product, highly recommended!',
  datePublished: '2024-01-15',
  maxRating: 5
});

// Generate Google Shopping feed
const productFeed = seo.engine.ecommerceOptimizer.generateProductFeed();
console.log(productFeed);
```

### Analytics and Metrics

Monitor SEO performance.

```javascript
// Generate comprehensive SEO score
const seoScore = seo.generateSEOScore();
console.log('Overall SEO Score:', seoScore.overall);
console.log('Meta Score:', seoScore.meta);
console.log('Content Score:', seoScore.content);
console.log('Performance Score:', seoScore.performance);
console.log('Accessibility Score:', seoScore.accessibility);
console.log('Mobile Score:', seoScore.mobile);
console.log('Structured Data Score:', seoScore.structuredData);
console.log('Links Score:', seoScore.links);
console.log('Images Score:', seoScore.images);

// Get complete analytics
const analytics = seo.getMetrics();
console.log('Average SEO Score:', analytics.averageSEOScore);
console.log('Total Optimizations:', analytics.totalOptimizations);
console.log('Recent Events:', analytics.events.slice(-5));
console.log('Performance Metrics:', analytics.metrics);
```

### Complete Page Analysis

```javascript
const analysis = seo.analyze();
console.log('Complete SEO Analysis:', analysis);
// {
//   seoScore: { ... },
//   keywords: { ... },
//   links: { ... },
//   content: { ... },
//   images: [ ... ],
//   performance: { ... },
//   meta: Map { ... }
// }
```

## 💡 Examples

### React Integration

```javascript
import React, { useEffect } from 'react';
import SEO from '@omindu/seo.js';

function ProductPage({ product }) {
  useEffect(() => {
    const seo = new SEO();
    
    seo.setupPage({
      title: `${product.name} - Buy Now`,
      description: product.description,
      keywords: product.tags.join(', ')
    });
    
    seo.engine.structuredDataManager.addProductSchema({
      name: product.name,
      description: product.description,
      price: product.price,
      image: product.image,
      brand: product.brand,
      sku: product.sku
    });
    
    seo.engine.socialMediaOptimizer.generateOpenGraphTags({
      title: product.name,
      description: product.description,
      image: product.image,
      type: 'product'
    });
    
    return () => {
      // Cleanup if needed
    };
  }, [product]);
  
  return <div>{/* Product content */}</div>;
}
```

### Vue.js Integration

```javascript
<template>
  <div>
    <!-- Your content -->
  </div>
</template>

<script>
import SEO from '@omindu/seo.js';

export default {
  name: 'ArticlePage',
  props: ['article'],
  mounted() {
    this.seo = new SEO({ debug: process.env.NODE_ENV === 'development' });
    
    this.seo.setupPage({
      title: this.article.title,
      description: this.article.excerpt,
      author: this.article.author.name
    });
    
    this.seo.engine.structuredDataManager.addArticleSchema({
      title: this.article.title,
      description: this.article.excerpt,
      author: this.article.author,
      publishedDate: this.article.date,
      image: this.article.image
    });
  },
  beforeDestroy() {
    // Cleanup
  }
};
</script>
```

### Angular Integration

```typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import SEO from '@omindu/seo.js';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit, OnDestroy {
  private seo: any;
  
  ngOnInit() {
    this.seo = new SEO();
    
    this.seo.setupPage({
      title: 'Home Page',
      description: 'Welcome to our website',
      keywords: 'home, welcome, main'
    });
    
    this.seo.engine.structuredDataManager.addOrganizationSchema({
      name: 'My Company',
      url: window.location.origin,
      logo: `${window.location.origin}/logo.png`
    });
  }
  
  ngOnDestroy() {
    // Cleanup if needed
  }
}
```

### Express.js Sitemap Generation

```javascript
const express = require('express');
const SEO = require('@omindu/seo.js');

const app = express();

app.get('/sitemap.xml', (req, res) => {
  const seo = new SEO();
  
  // Add URLs from database
  const urls = [
    { loc: 'https://example.com/', priority: 1.0, changefreq: 'daily' },
    { loc: 'https://example.com/about', priority: 0.8, changefreq: 'monthly' },
    { loc: 'https://example.com/contact', priority: 0.7, changefreq: 'yearly' }
  ];
  
  seo.engine.sitemapManager.addMultipleURLs(urls);
  
  const sitemap = seo.engine.sitemapManager.generateSitemap();
  
  res.header('Content-Type', 'application/xml');
  res.send(sitemap);
});

app.get('/robots.txt', (req, res) => {
  const seo = new SEO();
  const robots = seo.engine.sitemapManager.generateRobotsTxt();
  
  res.header('Content-Type', 'text/plain');
  res.send(robots);
});
```

## 🌐 Browser Support

| Browser | Version |
|---------|---------|
| Chrome  | 60+     |
| Firefox | 55+     |
| Safari  | 11+     |
| Edge    | 79+     |
| IE      | Not supported |

## 📄 License

MIT © Omindu Dissanayaka

---

## 🆘 Support & Contributing

- **Issues**: [GitHub Issues](https://github.com/OminduDissanayaka/seo-js/issues)
- **Pull Requests**: Welcome!
- **Documentation**: See source code for detailed JSDoc comments

## 🎉 Acknowledgments

- Schema.org for structured data standards
- Google for Core Web Vitals
- WCAG for accessibility guidelines

---

**Made with ❤️ for the open source community**
```