# Webby Advanced Usage Examples
## Custom Workflows
### 1. CI/CD Performance Gate
Check if site meets performance thresholds before deployment:
```typescript
// In your CI/CD pipeline
const result = await validate_performance_pagespeed("https://staging.example.com");
if (result.performance_score < 90) {
console.error("Performance threshold not met:", result.performance_score);
process.exit(1);
}
if (result.metrics.largestContentfulPaint > 2500) {
console.error("LCP too high:", result.metrics.largestContentfulPaint);
process.exit(1);
}
console.log("Performance checks passed!");
```
### 2. Multi-Location Testing
Test from different geographic locations:
```typescript
const locations = [
"Dulles:Chrome",
"London:Chrome",
"Tokyo:Chrome",
"Sydney:Chrome"
];
for (const location of locations) {
const result = await validate_performance_webpagetest(url, {
location,
waitForResults: true
});
console.log(`${location}: ${result.summary.loadTime}ms`);
}
```
### 3. Regression Testing
Compare before and after changes:
```typescript
// Before changes
const before = await validate_all_performance("https://production.example.com", {
webpagetestEnabled: true,
webpagetestWaitForResults: true
});
// Deploy changes...
// After changes
const after = await validate_all_performance("https://staging.example.com", {
webpagetestEnabled: true,
webpagetestWaitForResults: true
});
// Compare
const lcpBefore = before.pagespeed?.metrics.largestContentfulPaint;
const lcpAfter = after.pagespeed?.metrics.largestContentfulPaint;
if (lcpAfter > lcpBefore * 1.1) { // 10% regression
console.error(`LCP regressed: ${lcpBefore}ms → ${lcpAfter}ms`);
}
```
### 4. Accessibility Compliance Report
Generate comprehensive accessibility report:
```typescript
const result = await validate_accessibility_axe(url, {
wcagLevel: "wcag22aa" // Latest WCAG 2.2 AA
});
// Group by severity
const critical = result.issues.filter(i => i.impact === 'critical');
const serious = result.issues.filter(i => i.impact === 'serious');
console.log(`
Accessibility Report
====================
Total Violations: ${result.violations}
Critical: ${critical.length}
Serious: ${serious.length}
Passes: ${result.passes}
Critical Issues:
${critical.map(i => `- ${i.description} (${i.nodes} instances)`).join('\n')}
`);
```
### 5. Security Audit Pipeline
Complete security assessment:
```typescript
const audit = await validate_all_security(url, {
email: "security@company.com",
waitForSSL: true // Wait for complete SSL analysis
});
const issues = [];
// Check Mozilla Observatory
if (audit.mozilla_observatory.grade < 'B') {
issues.push(`HTTP security headers: ${audit.mozilla_observatory.grade}`);
}
// Check SSL Labs
if (audit.ssl_labs.grade < 'A') {
issues.push(`SSL configuration: ${audit.ssl_labs.grade}`);
}
// Check for specific security headers
if (audit.mozilla_observatory.tests_failed > 0) {
issues.push(`${audit.mozilla_observatory.tests_failed} security tests failed`);
}
if (issues.length > 0) {
console.error("Security issues found:", issues);
} else {
console.log("Security audit passed!");
}
```
## Batch Processing
### Test Multiple URLs
```typescript
const urls = [
"https://example.com",
"https://example.com/products",
"https://example.com/about",
"https://example.com/contact"
];
const results = await Promise.all(
urls.map(url => validate_performance_pagespeed(url))
);
// Find slowest page
const slowest = results.reduce((prev, current) =>
(current.performance_score < prev.performance_score) ? current : prev
);
console.log("Slowest page:", slowest.url, slowest.performance_score);
```
### Competitor Analysis
```typescript
const competitors = [
"https://competitor1.com",
"https://competitor2.com",
"https://competitor3.com",
"https://yoursite.com"
];
const results = await Promise.all(
competitors.map(async url => ({
url,
performance: await validate_performance_pagespeed(url),
accessibility: await validate_accessibility_axe(url)
}))
);
// Rank by performance
results.sort((a, b) =>
b.performance.performance_score - a.performance.performance_score
);
console.table(results.map(r => ({
Site: new URL(r.url).hostname,
Performance: r.performance.performance_score,
Accessibility: r.accessibility.violations,
LCP: r.performance.metrics.largestContentfulPaint
})));
```
## Custom Monitoring
### Scheduled Checks
```typescript
// Run every hour
setInterval(async () => {
const result = await validate_performance_pagespeed("https://example.com");
// Log to monitoring system
metrics.gauge('site.performance.score', result.performance_score);
metrics.gauge('site.performance.lcp', result.metrics.largestContentfulPaint);
// Alert if degraded
if (result.performance_score < 85) {
alerting.send({
severity: 'warning',
message: `Performance score dropped to ${result.performance_score}`
});
}
}, 3600000); // 1 hour
```
### Performance Budget
```typescript
const budgets = {
performance_score: 90,
accessibility_score: 95,
largestContentfulPaint: 2500,
totalBlockingTime: 200,
cumulativeLayoutShift: 0.1
};
async function checkBudget(url) {
const result = await validate_performance_pagespeed(url);
const violations = [];
for (const [metric, threshold] of Object.entries(budgets)) {
const value = metric.includes('_score')
? result[metric]
: result.metrics[metric];
if (metric.includes('_score') && value < threshold) {
violations.push(`${metric}: ${value} < ${threshold}`);
} else if (!metric.includes('_score') && value > threshold) {
violations.push(`${metric}: ${value} > ${threshold}`);
}
}
return {
passed: violations.length === 0,
violations
};
}
```
## Error Handling
### Retry Logic
```typescript
async function testWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const result = await validate_performance_pagespeed(url);
if (result.success) {
return result;
}
console.log(`Attempt ${i + 1} failed, retrying...`);
await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5s
} catch (error) {
if (i === maxRetries - 1) throw error;
console.log(`Error on attempt ${i + 1}, retrying...`);
}
}
}
```
### Graceful Degradation
```typescript
async function comprehensiveTest(url, email) {
const results = {
performance: null,
accessibility: null,
security: null
};
// Try performance (fast, usually reliable)
try {
results.performance = await validate_performance_pagespeed(url);
} catch (error) {
console.warn("Performance test failed:", error.message);
}
// Try accessibility (browser-based, may fail)
try {
results.accessibility = await validate_accessibility_axe(url);
} catch (error) {
console.warn("Accessibility test failed:", error.message);
}
// Try security (slow, may timeout)
try {
results.security = await validate_all_security(url, {
email,
waitForSSL: false // Don't wait for slow SSL Labs
});
} catch (error) {
console.warn("Security test failed:", error.message);
}
return results;
}
```
## Integration Examples
### With Slack
```typescript
async function notifySlack(url) {
const result = await validate_performance_pagespeed(url);
const color = result.performance_score >= 90 ? 'good' :
result.performance_score >= 70 ? 'warning' : 'danger';
await fetch('https://hooks.slack.com/services/YOUR/WEBHOOK/URL', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
attachments: [{
color,
title: `Performance Report: ${url}`,
fields: [
{ title: 'Score', value: result.performance_score, short: true },
{ title: 'LCP', value: `${result.metrics.largestContentfulPaint}ms`, short: true },
{ title: 'TBT', value: `${result.metrics.totalBlockingTime}ms`, short: true },
{ title: 'CLS', value: result.metrics.cumulativeLayoutShift, short: true }
]
}]
})
});
}
```
### With GitHub Actions
```yaml
# .github/workflows/performance.yml
name: Performance Check
on:
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install Webby
run: npm install -g webby-mcp
- name: Deploy to staging
run: # Your deploy script
- name: Run performance tests
run: |
node -e "
const result = require('webby-mcp').validate_performance_pagespeed(
'https://staging.example.com'
);
if (result.performance_score < 90) {
throw new Error('Performance threshold not met');
}
"
```
## Tips
1. **Rate Limiting**: Respect API quotas - space out requests
2. **Timeouts**: Set appropriate timeouts for different tools
3. **Caching**: Cache results when possible to save quotas
4. **Parallel Testing**: Run independent tests in parallel for speed
5. **Error Recovery**: Always handle errors gracefully
6. **Budget Alerts**: Set up alerts before hitting quota limits