// seo-framework.js - Core SEO Framework for JavaScript Applications
/**
* ═══════════════════════════════════════════════════════════════════════════
* SEO CONFIGURATION TYPES
* ═══════════════════════════════════════════════════════════════════════════
*/
/**
* @typedef {Object} SEOConfig
* @property {string} title - Page title
* @property {string} description - Meta description
* @property {string} canonical - Canonical URL
* @property {OpenGraphConfig} openGraph - Open Graph metadata
* @property {TwitterConfig} twitter - Twitter Card metadata
* @property {SchemaConfig} schema - JSON-LD structured data
* @property {RobotsConfig} robots - Robots directives
*/
/**
* @typedef {'CSR' | 'SSR' | 'SSG' | 'ISR'} RenderingStrategy
*/
class SEOFramework {
constructor(options = {}) {
this.config = {
defaultTitle: options.defaultTitle || 'My Site',
titleTemplate: options.titleTemplate || '%s | My Site',
defaultDescription: options.defaultDescription || '',
siteUrl: options.siteUrl || 'https://example.com',
defaultLocale: options.defaultLocale || 'en_US',
...options
};
this.renderingStrategy = options.renderingStrategy || 'SSR';
this.diagnostics = new SEODiagnostics();
}
/**
* Generate complete meta tags for a page
*/
generateMetaTags(pageConfig) {
const merged = this.mergeWithDefaults(pageConfig);
return {
title: this.formatTitle(merged.title),
meta: [
// Basic Meta Tags
{ name: 'description', content: merged.description },
{ name: 'robots', content: this.generateRobotsContent(merged.robots) },
// Open Graph
{ property: 'og:title', content: merged.openGraph?.title || merged.title },
{ property: 'og:description', content: merged.openGraph?.description || merged.description },
{ property: 'og:type', content: merged.openGraph?.type || 'website' },
{ property: 'og:url', content: merged.canonical },
{ property: 'og:image', content: merged.openGraph?.image },
{ property: 'og:locale', content: merged.locale || this.config.defaultLocale },
// Twitter Card
{ name: 'twitter:card', content: merged.twitter?.card || 'summary_large_image' },
{ name: 'twitter:title', content: merged.twitter?.title || merged.title },
{ name: 'twitter:description', content: merged.twitter?.description || merged.description },
{ name: 'twitter:image', content: merged.twitter?.image || merged.openGraph?.image },
// Additional SEO
{ name: 'author', content: merged.author },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
].filter(tag => tag.content),
link: [
{ rel: 'canonical', href: merged.canonical },
...this.generateAlternateLinks(merged.alternates),
].filter(link => link.href),
script: [
this.generateSchemaScript(merged.schema)
].filter(Boolean)
};
}
formatTitle(title) {
if (!title) return this.config.defaultTitle;
return this.config.titleTemplate.replace('%s', title);
}
generateRobotsContent(robots = {}) {
const directives = [];
if (robots.noindex) directives.push('noindex');
else directives.push('index');
if (robots.nofollow) directives.push('nofollow');
else directives.push('follow');
if (robots.noarchive) directives.push('noarchive');
if (robots.nosnippet) directives.push('nosnippet');
if (robots.maxSnippet) directives.push(`max-snippet:${robots.maxSnippet}`);
if (robots.maxImagePreview) directives.push(`max-image-preview:${robots.maxImagePreview}`);
if (robots.maxVideoPreview) directives.push(`max-video-preview:${robots.maxVideoPreview}`);
return directives.join(', ');
}
generateSchemaScript(schema) {
if (!schema) return null;
return {
type: 'application/ld+json',
innerHTML: JSON.stringify(schema, null, 2)
};
}
generateAlternateLinks(alternates = {}) {
const links = [];
if (alternates.languages) {
Object.entries(alternates.languages).forEach(([lang, url]) => {
links.push({ rel: 'alternate', hreflang: lang, href: url });
});
}
if (alternates.canonical) {
links.push({ rel: 'alternate', href: alternates.canonical });
}
return links;
}
mergeWithDefaults(pageConfig) {
return {
...this.config,
...pageConfig,
openGraph: { ...this.config.openGraph, ...pageConfig.openGraph },
twitter: { ...this.config.twitter, ...pageConfig.twitter },
};
}
}
/**
* ═══════════════════════════════════════════════════════════════════════════
* RENDERING STRATEGY IMPLEMENTATIONS
* ═══════════════════════════════════════════════════════════════════════════
*/
/**
* SSR Implementation for Node.js/Express
*/
class SSRRenderer {
constructor(options = {}) {
this.cache = new Map();
this.cacheEnabled = options.cacheEnabled ?? true;
this.cacheTTL = options.cacheTTL || 60000; // 1 minute
}
/**
* Server-side render a React component
*/
async renderToString(Component, props, context) {
const React = require('react');
const ReactDOMServer = require('react-dom/server');
// Create element with context
const element = React.createElement(
SSRContextProvider,
{ value: context },
React.createElement(Component, props)
);
// Collect data requirements
const dataRequirements = await this.collectDataRequirements(element);
// Render with collected data
const html = ReactDOMServer.renderToString(element);
return {
html,
data: dataRequirements,
head: context.head || []
};
}
/**
* Stream SSR for better TTFB
*/
renderToStream(Component, props, context) {
const React = require('react');
const { renderToPipeableStream } = require('react-dom/server');
const element = React.createElement(
SSRContextProvider,
{ value: context },
React.createElement(Component, props)
);
return renderToPipeableStream(element, {
onShellReady() {
// Shell is ready, can start streaming
},
onShellError(error) {
console.error('Shell error:', error);
},
onAllReady() {
// All content ready
},
onError(error) {
console.error('Streaming error:', error);
}
});
}
async collectDataRequirements(element) {
// Traverse component tree and collect getServerSideProps calls
const requirements = [];
// Implementation depends on your data fetching strategy
return requirements;
}
}
/**
* ISR Implementation
*/
class ISRHandler {
constructor(options = {}) {
this.cache = new Map();
this.revalidateQueue = new Set();
this.defaultRevalidate = options.defaultRevalidate || 60; // seconds
}
/**
* Get or generate page with ISR
*/
async getPage(path, generateFn, options = {}) {
const cacheKey = this.getCacheKey(path);
const cached = this.cache.get(cacheKey);
const revalidate = options.revalidate || this.defaultRevalidate;
if (cached) {
const age = Date.now() - cached.timestamp;
const isStale = age > revalidate * 1000;
if (isStale && !this.revalidateQueue.has(cacheKey)) {
// Trigger background revalidation
this.backgroundRevalidate(cacheKey, generateFn, options);
}
return {
html: cached.html,
headers: {
'Cache-Control': `s-maxage=${revalidate}, stale-while-revalidate`,
'X-Cache': isStale ? 'STALE' : 'HIT',
'X-Cache-Age': Math.floor(age / 1000)
}
};
}
// Generate new page
const result = await this.generateAndCache(cacheKey, generateFn, options);
return {
html: result.html,
headers: {
'Cache-Control': `s-maxage=${revalidate}, stale-while-revalidate`,
'X-Cache': 'MISS'
}
};
}
async generateAndCache(cacheKey, generateFn, options) {
const html = await generateFn();
this.cache.set(cacheKey, {
html,
timestamp: Date.now(),
options
});
return { html };
}
async backgroundRevalidate(cacheKey, generateFn, options) {
this.revalidateQueue.add(cacheKey);
try {
await this.generateAndCache(cacheKey, generateFn, options);
console.log(`ISR: Revalidated ${cacheKey}`);
} catch (error) {
console.error(`ISR: Revalidation failed for ${cacheKey}:`, error);
} finally {
this.revalidateQueue.delete(cacheKey);
}
}
getCacheKey(path) {
return `isr:${path}`;
}
/**
* On-demand revalidation
*/
async revalidate(path) {
const cacheKey = this.getCacheKey(path);
this.cache.delete(cacheKey);
return { revalidated: true, path };
}
}
/**
* SSG Build-time Generation
*/
class SSGGenerator {
constructor(options = {}) {
this.outputDir = options.outputDir || './dist';
this.routes = [];
}
/**
* Register routes for static generation
*/
registerRoute(path, generateFn, options = {}) {
this.routes.push({ path, generateFn, options });
}
/**
* Generate all static pages
*/
async generateAll() {
const fs = require('fs').promises;
const path = require('path');
const results = [];
for (const route of this.routes) {
console.log(`SSG: Generating ${route.path}...`);
try {
// Handle dynamic routes
const paths = route.options.getStaticPaths
? await route.options.getStaticPaths()
: [{ params: {} }];
for (const pathConfig of paths) {
const resolvedPath = this.resolvePath(route.path, pathConfig.params);
const html = await route.generateFn(pathConfig.params);
const filePath = path.join(
this.outputDir,
resolvedPath === '/' ? 'index.html' : `${resolvedPath}/index.html`
);
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, html);
results.push({
path: resolvedPath,
file: filePath,
success: true
});
}
} catch (error) {
results.push({
path: route.path,
success: false,
error: error.message
});
}
}
return results;
}
resolvePath(pathTemplate, params) {
let resolved = pathTemplate;
Object.entries(params).forEach(([key, value]) => {
resolved = resolved.replace(`[${key}]`, value);
resolved = resolved.replace(`[...${key}]`, Array.isArray(value) ? value.join('/') : value);
});
return resolved;
}
}
module.exports = { SEOFramework, SSRRenderer, ISRHandler, SSGGenerator };
// hydration-patterns.js - Complete Hydration Solutions
/**
* ═══════════════════════════════════════════════════════════════════════════
* HYDRATION ARCHITECTURE
* ═══════════════════════════════════════════════════════════════════════════
*
* ┌──────────────────────────────────────────────────────────────────────┐
* │ HYDRATION PROCESS FLOW │
* │ │
* │ Server-Rendered HTML │
* │ ┌─────────────────────────────────────────────────────────────┐ │
* │ │ <div id="root"> │ │
* │ │ <header>...</header> ──────┐ │ │
* │ │ <main> │ │ │
* │ │ <article>...</article> │ Static HTML │ │
* │ │ <sidebar>...</sidebar> │ (Visible immediately) │ │
* │ │ </main> │ │ │
* │ │ <footer>...</footer> ──────┘ │ │
* │ │ </div> │ │
* │ │ <script>__DATA__={...}</script> ◄── Serialized State │ │
* │ └─────────────────────────────────────────────────────────────┘ │
* │ │ │
* │ ▼ │
* │ ┌─────────────────────────────────────────────────────────────┐ │
* │ │ HYDRATION PHASE │ │
* │ │ │ │
* │ │ 1. Parse HTML ──────────────────────────────────────┐ │ │
* │ │ 2. Load JavaScript ─────────────────────────────────┤ │ │
* │ │ 3. Deserialize State ───────────────────────────────┤ │ │
* │ │ 4. Attach Event Listeners ──────────────────────────┤ │ │
* │ │ 5. Reconcile Virtual DOM ───────────────────────────┤ │ │
* │ │ │ │ │
* │ │ ▼ │ │
* │ │ ┌───────────────────────────────────────────────────────┐ │ │
* │ │ │ INTERACTIVE APPLICATION │ │ │
* │ │ │ (Event handlers attached, state synchronized) │ │ │
* │ │ └───────────────────────────────────────────────────────┘ │ │
* │ └─────────────────────────────────────────────────────────────┘ │
* │ │
* │ ⚠️ HYDRATION MISMATCHES │
* │ ┌─────────────────────────────────────────────────────────────┐ │
* │ │ Server HTML: <div>Hello World</div> │ │
* │ │ Client Render: <div>Hello <span>World</span></div> │ │
* │ │ │ │
* │ │ Result: ❌ Hydration Error! DOM mismatch detected │ │
* │ │ Impact: Full re-render, performance degradation, SEO harm │ │
* │ └─────────────────────────────────────────────────────────────┘ │
* │ │
* └──────────────────────────────────────────────────────────────────────┘
*/
import React, {
Suspense,
useState,
useEffect,
createContext,
useContext,
useId,
useSyncExternalStore
} from 'react';
/**
* Hydration Context for sharing state between server and client
*/
const HydrationContext = createContext({
isHydrated: false,
isServer: typeof window === 'undefined'
});
/**
* Provider that manages hydration state
*/
export function HydrationProvider({ children, initialData = {} }) {
const [isHydrated, setIsHydrated] = useState(false);
const isServer = typeof window === 'undefined';
useEffect(() => {
setIsHydrated(true);
}, []);
// Serialize initial data for client hydration
const serializedData = isServer
? JSON.stringify(initialData)
: null;
return (
<HydrationContext.Provider value={{ isHydrated, isServer, initialData }}>
{children}
{isServer && (
<script
id="__HYDRATION_DATA__"
type="application/json"
dangerouslySetInnerHTML={{ __html: serializedData }}
/>
)}
</HydrationContext.Provider>
);
}
/**
* Hook to access hydration state
*/
export function useHydration() {
return useContext(HydrationContext);
}
/**
* Safe hydration hook - prevents hydration mismatches
*/
export function useHydrationSafe(serverValue, clientValue) {
const { isHydrated } = useHydration();
const