javascript
#!/usr/bin/env node
const { Command } = require('commander');
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');
const shell = require('shelljs');
const lighthouse = require('lighthouse-ci');
const pa11y = require('pa11y-ci');
const cheerio = require('cheerio');
const axios = require('axios');
const os = require('os');
const program = new Command();
program.version('1.0.0');
// Built-in Templates (EJS)
const TEMPLATES = {
landing: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 2rem; }
h1 { color: #333; }
.cta { background: #007bff; color: white; padding: 1rem 2rem; text-decoration: none; border-radius: 5px; }
</style>
</head>
<body>
<h1><%= title %></h1>
<p><%= content %></p>
<% if (cta) { %>
<a href="<%= cta.url %>" class="cta"><%= cta.text %></a>
<% } %>
<script>
// Analytics placeholder (e.g., GA4)
console.log('Micro-site loaded: <%= title %>');
</script>
</body>
</html>`.trim(),
form: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<script src="https://cdn.jsdelivr.net/npm/netlify-form-handler@1/dist/netlify-form-handler.min.js"></script>
<style> /* Same as landing */ </style>
</head>
<body>
<h1><%= title %></h1>
<p><%= content %></p>
<form netlify name="contact" method="POST">
<input type="hidden" name="form-name" value="contact">
<input type="email" name="email" placeholder="Email" required>
<textarea name="message" placeholder="Message" required></textarea>
<button type="submit">Submit</button>
</form>
</body>
</html>`.trim(),
blog: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<style> /* Same as landing */ </style>
</head>
<body>
<h1><%= title %></h1>
<% posts.forEach(post => { %>
<article>
<h2><%= post.title %></h2>
<p><%= post.excerpt %></p>
<a href="<%= post.link %>">Read more</a>
</article>
<% }); %>
</body>
</html>`.trim()
};
// Config storage (JSON in dist/)
function loadConfig(dir) {
return JSON.parse(fs.readFileSync(path.join(dir, 'config.json'), 'utf8'));
}
function saveConfig(dir, config) {
fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify(config, null, 2));
}
// Create micro-site
program
.command('create <name>')
.option('-t, --template <type>', 'Template: landing|form|blog', 'landing')
.option('-c, --content <text>', 'Main content')
.option('--cta-text <text>', 'CTA button text')
.option('--cta-url <url>', 'CTA button URL')
.option('--posts <json>', 'Blog posts JSON array', '[]')
.option('--deploy', 'Auto-deploy after create')
.description('Create a new micro-site')
.action(async (name, options) => {
const dist = path.join(process.cwd(), `dist-${name.toLowerCase().replace(/\s+/g, '-')}`);
shell.mkdir('-p', dist);
const config = {
name, template: options.template, content: options.content || `${name} landing page.`,
cta: options.ctaText ? { text: options.ctaText, url: options.ctaUrl } : null,
posts: JSON.parse(options.posts),
created: new Date().toISOString(),
redirects: [] // e.g., [{ from: '/old', to: '/new', status: 301 }]
};
saveConfig(dist, config);
const html = ejs.render(TEMPLATES[options.template], config);
fs.writeFileSync(path.join(dist, 'index.html'), html);
// Add _redirects for Netlify
const redirects = config.redirects.map(r => `${r.from} ${r.to} ${r.status || 301}`).join('\n');
fs.writeFileSync(path.join(dist, '_redirects'), redirects || '/* /index.html 200'); // SPA fallback
// netlify.toml for deploy settings
const toml = `[build]
command = "echo 'Static site ready'"
publish = "."
[[redirects]]
from = "/*"
to = "/index.html"
status = 200`;
fs.writeFileSync(path.join(dist, 'netlify.toml'), toml);
console.log(`✅ Created micro-site at ${dist}`);
console.log(`📋 Config preview:\n${JSON.stringify(config, null, 2)}`);
if (options.deploy) {
await deploySite(dist);
}
});
// QA: Lighthouse + pa11y + link check
program
.command('qa <dir>')
.description('Run QA on dist folder')
.action(async (dir) => {
console.log('🔍 Running QA...');
// 1. Link check
const $ = cheerio.load(fs.readFileSync(path.join(dir, 'index.html')));
$('a[href]').each((i, el) => {
const href = $(el).attr('href');
if (href && !href.startsWith('#') && !href.startsWith('http')) {
console.warn(`⚠️ Relative link: ${href} (test manually)`);
}
});
// 2. Serve locally for testing (lighthouse/pa11y need server)
const port = 8080;
const server = shell.exec(`npx serve ${dir} -p ${port} -s`, { async: true });
await new Promise(r => setTimeout(r, 2000)); // Wait for server
try {
// pa11y accessibility
const pa11yResults = await pa11y({ url: `http://localhost:${port}`, standard: 'WCAG2AA' });
console.log('♿ Accessibility:', pa11yResults.length === 0 ? '✅ Passed' : `❌ ${pa11yResults.length} issues`);
// Lighthouse (perf/SEO/a11y/BP)
const lhr = await lighthouse(`http://localhost:${port}`, {
logLevel: 'info',
numberOfRuns: 1,
output: 'json',
onlyCategories: ['performance', 'seo', 'accessibility', 'best-practices']
});
const scores = lhr.lhr.categories;
Object.entries(scores).forEach(([cat, score]) => {
const emoji = score.score > 0.9 ? '✅' : score.score > 0.7 ? '⚠️' : '❌';
console.log(`${emoji} ${cat}: ${Math.round(score.score * 100)}`);
});
fs.writeFileSync(path.join(dir, 'lighthouse-report.json'), JSON.stringify(lhr.lhr, null, 2));
console.log('📊 Report saved: lighthouse-report.json');
} finally {
shell.exec(`pkill -f "serve ${dir}" || true`);
}
});
// Deploy to Netlify
async function deploySite(dir) {
console.log('🚀 Deploying to Netlify...');
const config = loadConfig(dir);
const siteName = `micro-${config.name.toLowerCase().replace(/\s+/g, '-')}`;
// Create/deploy site
shell.cd(dir);
const deployResult = shell.exec(`netlify deploy --prod --dir=. --site=${siteName} --alias=${siteName}`, { silent: true });
if (deployResult.code !== 0) {
console.error('❌ Deploy failed:', deployResult.stderr);
return;
}
// Get deploy URL
const { data: sites } = await axios.get('https://api.netlify.com/api/v1/sites', {
headers: { Authorization: `Bearer ${shell.exec('netlify api:listSites | jq -r .[0].api_key', { silent: true }).stdout.trim()}` } // Simplified; use env NETLIFY_API_TOKEN
});
const url = sites.find(s => s.name === siteName)?.url || `${siteName}.netlify.app`;
console.log(`🌐 Live at: ${url}`);
console.log(`🔗 Set custom domain: netlify sites:set-site-name ${siteName} --domain=yourdomain.com`);
}
// Deploy command
program
.command('deploy <dir>')
.option('--domain <domain>', 'Custom domain')
.description('Deploy dist to Netlify')
.action(deploySite);
// Redirects
program
.command('redirect <dir>')
.option('--add <rule>', 'Add redirect: "/old -> /new 301"')
.description('Manage redirects')
.action((dir, options) => {
const config = loadConfig(dir);
if (options.add) {
const [from, toStatus] = options.add.split(' -> ');
const [to, status = '301'] = toStatus.split(' ');
config.redirects.push({ from, to, status: +status });
saveConfig(dir, config);
fs.writeFileSync(path.join(dir, '_redirects'), config.redirects.map(r => `${r.from} ${r.to} ${r.status}`).join('\n') || '/* /index.html 200');
}
console.log('🔄 Redirects:\n', config.redirects.map(r => `${r.from} → ${r.to} (${r.status})`).join('\n') || 'None');
});
program.parse();
Netlify handles HTTPS, forms, functions out-of-box. Scales to 0! 🚀 Questions? Ask Sherlock.