jpglens Documentation

Everything you need to know about AI-powered UI testing

v1.1.1 Updated 3 hours ago

Installation

Get started with jpglens in your project. Choose your preferred package manager:

npm install --save-dev jpglens
yarn add --dev jpglens
pnpm add -D jpglens

📦 Package Information

jpglens is available on npm registry with full TypeScript support and comprehensive documentation.

Quick Start

Get jpglens running in your tests in under 5 minutes.

1. Set up your API key

jpglens works with OpenAI-compatible APIs. Set your API key as an environment variable:

# .env file
JPGLENS_API_KEY="your-openrouter-or-openai-key"
JPGLENS_MODEL="anthropic/claude-3-5-sonnet"

2. Add to your tests

Choose your testing framework and add AI analysis:

// tests/example.spec.js
import { test } from '@playwright/test';
import { analyzeUserJourney } from 'jpglens/playwright';

test('AI analyzes checkout flow', async ({ page }) => {
  await page.goto('/checkout');
  
  // Your existing test actions
  await page.fill('[data-testid="email"]', 'user@example.com');
  await page.click('[data-testid="continue"]');
  
  // Add AI analysis
  await analyzeUserJourney(page, {
    stage: 'checkout-form',
    userIntent: 'complete purchase',
    userContext: {
      persona: 'first-time-buyer',
      device: 'mobile'
    }
  });
});
// cypress/e2e/example.cy.js
import 'jpglens/cypress';

describe('Checkout Flow', () => {
  it('analyzes user experience', () => {
    cy.visit('/checkout');
    
    // Your existing test actions
    cy.get('[data-cy="email"]').type('user@example.com');
    cy.get('[data-cy="continue"]').click();
    
    // Add AI analysis
    cy.analyzeUserExperience({
      stage: 'checkout-form',
      userIntent: 'complete purchase',
      userContext: {
        persona: 'first-time-buyer',
        device: 'mobile'
      }
    });
  });
});

3. Run your tests

Execute your tests as usual. jpglens will provide AI-powered insights:

npx playwright test
# or
npx cypress run

✅ That's it!

jpglens will analyze your UI and provide detailed feedback on usability, accessibility, and user experience. Check your console or generated reports for insights.

Configuration

Customize jpglens behavior with a configuration file.

Configuration File

Create a jpglens.config.js file in your project root:

// jpglens.config.js
export default {
  // AI Provider Configuration
  ai: {
    provider: 'openrouter',
    model: 'anthropic/claude-3-5-sonnet',
    apiKey: process.env.JPGLENS_API_KEY,
    maxTokens: 4000,
    temperature: 0.1
  },

  // Analysis Configuration
  analysis: {
    types: ['usability', 'accessibility', 'visual-design', 'performance'],
    depth: 'comprehensive', // 'quick' | 'standard' | 'comprehensive'
    includeScreenshots: true
  },

  // Reporting Configuration
  reporting: {
    enabled: true,
    outputDir: './jpglens-reports',
    format: 'markdown', // 'markdown' | 'json' | 'html'
    template: 'detailed',
    includeScreenshots: true,
    customPrompts: {
      'mobile-focus': 'Analyze specifically for mobile usability',
      'accessibility-deep': 'Deep dive into WCAG 2.1 compliance'
    }
  },

  // User Personas
  userPersonas: {
    'power-user': {
      expertise: 'expert',
      device: 'desktop',
      goals: ['efficiency', 'advanced-features']
    },
    'mobile-user': {
      expertise: 'novice',
      device: 'mobile',
      goals: ['simplicity', 'speed']
    }
  }
};

Environment Variables

Set these environment variables for configuration:

Variable Description Required
JPGLENS_API_KEY Your OpenRouter, OpenAI, or Anthropic API key Yes
JPGLENS_MODEL AI model to use (e.g., "anthropic/claude-3-5-sonnet") No
JPGLENS_DEBUG Enable debug logging No

Playwright Integration

jpglens integrates seamlessly with Playwright for comprehensive browser testing.

Basic Usage

import { test } from '@playwright/test';
import { analyzeUserJourney, quickAnalyze } from 'jpglens/playwright';

test('comprehensive analysis', async ({ page }) => {
  await page.goto('/app');
  
  // Detailed analysis with full context
  await analyzeUserJourney(page, {
    stage: 'dashboard-overview',
    userIntent: 'understand key metrics',
    userContext: {
      persona: 'business-analyst',
      deviceContext: 'desktop',
      expertise: 'intermediate'
    },
    criticalElements: ['charts', 'kpi-cards', 'navigation'],
    businessContext: {
      industry: 'saas',
      userRole: 'admin'
    }
  });
  
  // Quick analysis for rapid feedback
  await quickAnalyze(page, 'navigation-menu');
});

User Journey Analysis

Analyze complete user workflows across multiple pages:

import { analyzeCompleteJourney } from 'jpglens/playwright';

const userJourney = {
  name: 'user-onboarding',
  persona: 'first-time-user',
  device: 'mobile',
  stages: [
    {
      name: 'landing',
      page: '/',
      userGoal: 'understand value proposition',
      aiAnalysis: 'first-impression and trust signals'
    },
    {
      name: 'signup',
      page: '/register',
      userGoal: 'create account with minimal friction',
      aiAnalysis: 'form usability and conversion optimization'
    },
    {
      name: 'activation',
      page: '/welcome',
      userGoal: 'understand next steps',
      aiAnalysis: 'onboarding clarity and engagement'
    }
  ]
};

test('analyze complete user journey', async ({ page }) => {
  const results = await analyzeCompleteJourney(userJourney);
  // Results contain analysis for each stage
});

💡 Pro Tip

Use quickAnalyze() for rapid feedback during development, and analyzeUserJourney() for comprehensive analysis in your CI/CD pipeline.

Cypress Integration

jpglens integrates seamlessly with Cypress for end-to-end testing with AI-powered insights.

Installation

npm install --save-dev jpglens

Basic Usage

// cypress/e2e/example.cy.js
import 'jpglens/cypress';

describe('User Experience Analysis', () => {
  it('analyzes checkout flow', () => {
    cy.visit('/checkout');
    
    // Your existing test actions
    cy.get('[data-cy="email"]').type('user@example.com');
    cy.get('[data-cy="continue"]').click();
    
    // Add AI analysis
    cy.analyzeUserExperience({
      stage: 'checkout-form',
      userIntent: 'complete purchase',
      userContext: {
        persona: 'first-time-buyer',
        device: 'mobile'
      }
    });
  });
});

Advanced Features

// Analyze specific elements
cy.get('.product-grid').analyzeElement({
  focus: 'usability',
  userContext: { device: 'mobile' }
});

// Journey analysis
cy.analyzeJourney({
  name: 'product-discovery',
  stages: ['landing', 'search', 'product-detail', 'cart']
});

Selenium Integration

Use jpglens with Selenium WebDriver for cross-browser AI-powered testing.

Basic Setup

import { WebDriver } from 'selenium-webdriver';
import { analyzeCurrentState, analyzeUserJourney } from 'jpglens/selenium';

const driver = new WebDriver(/* your driver config */);

// Quick analysis
await analyzeCurrentState(driver, {
  focus: 'accessibility',
  userContext: { device: 'desktop' }
});

// Journey analysis
await analyzeUserJourney(driver, {
  name: 'user-registration',
  persona: 'new-user',
  stages: [
    { name: 'form', actions: ['fill-email', 'fill-password'] },
    { name: 'verification', actions: ['click-verify'] }
  ]
});

Cross-Browser Testing

import { analyzeCrossBrowser } from 'jpglens/selenium';

const browsers = ['chrome', 'firefox', 'safari'];
const results = await analyzeCrossBrowser(browsers, {
  url: 'https://example.com',
  scenarios: ['mobile-nav', 'form-submission']
});

console.log(results.browserComparison);

Storybook Integration

Analyze component states and design systems within Storybook stories.

Story Analysis

// Button.stories.js
import { analyzeComponent } from 'jpglens/storybook';

export default {
  title: 'Button',
  component: Button,
};

export const Primary = {
  args: { variant: 'primary', children: 'Click me' },
  play: async ({ canvasElement }) => {
    await analyzeComponent(canvasElement, 'Button', {
      states: ['default', 'hover', 'focus', 'disabled'],
      focus: 'accessibility'
    });
  }
};

Component Library Analysis

import { analyzeComponentLibrary } from 'jpglens/storybook';

const components = [
  { name: 'Button', canvas: buttonCanvas, states: ['default', 'hover'] },
  { name: 'Input', canvas: inputCanvas, states: ['empty', 'filled', 'error'] }
];

const libraryAnalysis = await analyzeComponentLibrary(components);
console.log(libraryAnalysis.designSystemConsistency);

Testing Library Integration

Enhance React Testing Library tests with AI-powered component analysis.

Component Testing

import { render, screen } from '@testing-library/react';
import { analyzeRenderedComponent } from 'jpglens/testing-library';
import MyComponent from './MyComponent';

test('analyzes component accessibility', async () => {
  render(<MyComponent />);
  
  const analysis = await analyzeRenderedComponent(screen.getByTestId('component'), {
    focus: 'accessibility',
    includeAriaAnalysis: true
  });
  
  expect(analysis.accessibilityScore).toBeGreaterThan(0.9);
});

User Interaction Analysis

import userEvent from '@testing-library/user-event';

test('analyzes user interaction flow', async () => {
  const user = userEvent.setup();
  render(<LoginForm />);
  
  // Perform user actions
  await user.type(screen.getByLabelText(/email/i), 'user@example.com');
  await user.type(screen.getByLabelText(/password/i), 'password123');
  
  // Analyze the interaction
  await analyzeUserInteraction(screen.getByRole('form'), {
    interactionType: 'form-submission',
    userContext: { expertise: 'novice' }
  });
});

User Journeys

Define and analyze complete user workflows across multiple pages and interactions.

Journey Definition

const userJourney = {
  name: 'e-commerce-purchase',
  persona: 'first-time-buyer',
  device: 'mobile',
  stages: [
    {
      name: 'product-discovery',
      page: '/products',
      userGoal: 'find desired product',
      criticalElements: ['search', 'filters', 'product-grid']
    },
    {
      name: 'product-detail',
      page: '/product/123',
      userGoal: 'evaluate product details',
      criticalElements: ['images', 'description', 'reviews', 'add-to-cart']
    },
    {
      name: 'checkout',
      page: '/checkout',
      userGoal: 'complete purchase',
      criticalElements: ['form', 'payment', 'shipping-options']
    }
  ]
};

Journey Templates

import { getJourneyTemplate } from 'jpglens';

// Pre-built journey templates
const ecommerceJourney = getJourneyTemplate('e-commerce');
const saasOnboarding = getJourneyTemplate('saas-onboarding');
const contentConsumption = getJourneyTemplate('content-consumption');

Analysis Types

jpglens supports multiple analysis types to evaluate different aspects of your UI.

Available Analysis Types

🎯 Usability

Evaluates user interface design, navigation clarity, and interaction patterns.

types: ['usability']

♿ Accessibility

Checks WCAG compliance, screen reader compatibility, and inclusive design.

types: ['accessibility']

🎨 Visual Design

Analyzes visual hierarchy, color contrast, typography, and layout consistency.

types: ['visual-design']

⚡ Performance

Evaluates loading speed, responsiveness, and performance impact on UX.

types: ['performance']

📱 Mobile Optimization

Focuses on mobile-specific usability, touch targets, and responsive design.

types: ['mobile-optimization']

💰 Conversion Optimization

Analyzes conversion funnels, call-to-action effectiveness, and user flow.

types: ['conversion-optimization']

Configuration Example

const config = {
  analysis: {
    types: ['usability', 'accessibility', 'performance'],
    depth: 'comprehensive',
    includeScreenshots: true
  }
};

User Personas

Define user personas to tailor AI analysis for specific user types and contexts.

Built-in Personas

import { getUserPersona } from 'jpglens';

// Pre-defined personas
const businessUser = getUserPersona('business-user');
const mobileConsumer = getUserPersona('mobile-consumer');
const powerUser = getUserPersona('power-user');
const accessibilityUser = getUserPersona('accessibility-user');

Custom Persona Definition

const customPersona = {
  name: 'Senior Citizen',
  expertise: 'novice',
  device: 'tablet',
  urgency: 'low',
  goals: ['simplicity', 'large-text', 'clear-navigation'],
  painPoints: ['small-text', 'complex-interfaces', 'fast-animations'],
  context: 'Limited tech experience, values clarity and patience',
  assistiveTech: ['reading-glasses', 'voice-control']
};

Persona-Based Analysis

await analyzeUserJourney(page, {
  userContext: {
    persona: customPersona,
    deviceContext: 'tablet-portrait',
    expertise: 'novice'
  },
  stage: 'account-setup',
  userIntent: 'create account with minimal frustration'
});

Reporting

Generate comprehensive reports from jpglens analysis results.

Report Formats

import { generateReport } from 'jpglens/utils';

// HTML Report
const htmlReport = await generateReport(analysisResults, {
  format: 'html',
  template: 'executive-summary',
  includeScreenshots: true,
  theme: 'professional'
});

// Markdown Report
const markdownReport = await generateReport(analysisResults, {
  format: 'markdown',
  includeMetrics: true,
  groupByPriority: true
});

// JSON Report for CI/CD
const jsonReport = await generateReport(analysisResults, {
  format: 'json',
  structuredData: true,
  includeRawAnalysis: false
});

Custom Report Templates

const customTemplate = {
  name: 'accessibility-focused',
  sections: ['executive-summary', 'accessibility-issues', 'remediation-steps'],
  prioritize: ['critical-accessibility', 'wcag-violations'],
  includeScreenshots: true,
  format: 'html'
};

const report = await generateReport(results, { template: customTemplate });

Real-time Reporting

// Stream results to dashboard
const reportStream = createReportStream({
  destination: 'dashboard',
  realtime: true,
  filters: ['critical', 'high-priority']
});

await analyzeUserJourney(page, {
  // ... analysis config
  reporting: {
    stream: reportStream,
    immediate: true
  }
});

AI Analysis

Deep dive into jpglens AI-powered analysis capabilities and configuration.

AI Provider Configuration

const aiConfig = {
  provider: 'openrouter', // 'openai', 'anthropic', 'openrouter'
  model: 'anthropic/claude-3-5-sonnet',
  apiKey: process.env.JPGLENS_API_KEY,
  maxTokens: 4000,
  temperature: 0.1,
  fallbackModel: 'openai/gpt-4-vision-preview'
};

Custom Analysis Prompts

const customPrompts = {
  'e-commerce-focus': `
    Analyze this e-commerce interface focusing on:
    - Product discoverability
    - Purchase flow friction
    - Trust signals and security indicators
    - Mobile checkout optimization
  `,
  'accessibility-deep': `
    Perform comprehensive accessibility analysis:
    - WCAG 2.1 AA compliance
    - Screen reader compatibility
    - Keyboard navigation
    - Color contrast ratios
  `
};

await analyzeUserJourney(page, {
  customPrompts: customPrompts['e-commerce-focus']
});

AI Model Selection

Recommended Models

  • Claude 3.5 Sonnet - Best for detailed UI analysis and accessibility
  • GPT-4 Vision - Excellent for visual design evaluation
  • GPT-4o - Fast and cost-effective for basic analysis

Vision Testing

Leverage AI vision capabilities for advanced visual UI testing and analysis.

Visual Regression Testing

import { compareVisualStates } from 'jpglens/vision';

// Compare two visual states
const comparison = await compareVisualStates({
  baseline: baselineScreenshot,
  current: currentScreenshot,
  threshold: 0.95,
  ignoreRegions: ['.timestamp', '.dynamic-content'],
  aiAnalysis: true
});

if (comparison.hasSignificantChanges) {
  console.log('Visual changes detected:', comparison.changes);
}

Component Visual Testing

// Test component across different states
const componentStates = ['default', 'hover', 'focus', 'disabled', 'error'];

for (const state of componentStates) {
  await page.setComponentState(state);
  
  const analysis = await analyzeVisualState(page, {
    component: 'Button',
    state: state,
    focus: ['visual-consistency', 'accessibility', 'brand-compliance']
  });
  
  expect(analysis.brandConsistency).toBeGreaterThan(0.9);
}

Cross-Device Vision Testing

const devices = [
  { name: 'iPhone 13', viewport: { width: 390, height: 844 } },
  { name: 'iPad Pro', viewport: { width: 1024, height: 1366 } },
  { name: 'Desktop', viewport: { width: 1920, height: 1080 } }
];

const crossDeviceResults = await analyzeCrossDevice(devices, {
  url: '/product/123',
  scenarios: ['product-view', 'add-to-cart', 'quick-buy'],
  visionAnalysis: {
    checkLayoutShifts: true,
    validateResponsiveDesign: true,
    assessTouchTargets: true
  }
});

Custom Prompts

Create specialized AI analysis prompts for specific testing scenarios and requirements.

Prompt Templates

import { createCustomPrompt } from 'jpglens/utils';

// Template with variables
const promptTemplate = `
Analyze this {{pageType}} for {{userType}} users focusing on {{criteria}}.
Consider the following context: {{businessContext}}

Specific requirements:
- {{requirement1}}
- {{requirement2}}
- {{requirement3}}

Provide actionable recommendations for improvement.
`;

const customPrompt = createCustomPrompt(promptTemplate, {
  pageType: 'e-commerce checkout',
  userType: 'mobile',
  criteria: 'conversion optimization',
  businessContext: 'high-value B2B sales',
  requirement1: 'minimize form fields',
  requirement2: 'build trust through security indicators',
  requirement3: 'optimize for one-handed mobile use'
});

Industry-Specific Prompts

const industryPrompts = {
  healthcare: `
    Analyze this healthcare interface for:
    - HIPAA compliance indicators
    - Patient safety considerations
    - Medical terminology clarity
    - Emergency access patterns
  `,
  
  fintech: `
    Evaluate this financial interface for:
    - Security and trust signals
    - Regulatory compliance (PCI DSS)
    - Transaction clarity
    - Risk communication
  `,
  
  education: `
    Assess this educational platform for:
    - Learning accessibility (diverse abilities)
    - Age-appropriate design
    - Progress tracking clarity
    - Engagement patterns
  `
};

Dynamic Prompt Generation

function generateContextualPrompt(userJourney, businessGoals) {
  const basePrompt = `Analyze this ${userJourney.stage} interface`;
  const contextPrompt = `for ${userJourney.persona} users`;
  const goalPrompt = `focusing on ${businessGoals.join(', ')}`;
  
  return `${basePrompt} ${contextPrompt} ${goalPrompt}.
    
    Consider:
    - User's current goal: ${userJourney.userIntent}
    - Device context: ${userJourney.device}
    - Business priorities: ${businessGoals.join(', ')}
    
    Provide specific, actionable recommendations.`;
}

const prompt = generateContextualPrompt(
  { stage: 'checkout', persona: 'returning-customer', userIntent: 'quick purchase', device: 'mobile' },
  ['conversion-rate', 'user-satisfaction', 'cart-abandonment-reduction']
);

Plugins

Extend jpglens functionality with custom plugins and integrations.

Plugin Architecture

// Custom plugin structure
const customPlugin = {
  name: 'brand-consistency-checker',
  version: '1.0.0',
  
  // Plugin initialization
  init(config) {
    this.brandGuidelines = config.brandGuidelines;
    this.colorPalette = config.colorPalette;
    this.typography = config.typography;
  },
  
  // Analysis hook
  async analyze(screenshot, context) {
    const brandAnalysis = await this.checkBrandConsistency(screenshot);
    return {
      score: brandAnalysis.score,
      violations: brandAnalysis.violations,
      recommendations: brandAnalysis.recommendations
    };
  },
  
  // Custom analysis method
  async checkBrandConsistency(screenshot) {
    // Custom brand analysis logic
    return {
      score: 0.85,
      violations: ['incorrect-font-weight', 'off-brand-color'],
      recommendations: ['Use brand primary color #007bff', 'Apply medium font weight']
    };
  }
};

Plugin Registration

import { registerPlugin } from 'jpglens';

// Register custom plugin
registerPlugin(customPlugin, {
  brandGuidelines: './brand-guidelines.json',
  colorPalette: ['#007bff', '#28a745', '#dc3545'],
  typography: { primary: 'Inter', secondary: 'JetBrains Mono' }
});

// Use plugin in analysis
await analyzeUserJourney(page, {
  plugins: ['brand-consistency-checker'],
  pluginConfig: {
    'brand-consistency-checker': {
      strictMode: true,
      includeColorAnalysis: true
    }
  }
});

Available Plugin Types

🎨 Visual Plugins

Brand consistency, design system validation, visual regression

♿ Accessibility Plugins

WCAG validation, screen reader testing, color contrast

⚡ Performance Plugins

Core Web Vitals, loading analysis, optimization suggestions

🔒 Security Plugins

Security headers, vulnerability scanning, trust indicators

Performance

Optimize jpglens for speed and efficiency in your testing workflows.

Performance Configuration

const performanceConfig = {
  // Concurrent analysis
  concurrency: 3,
  
  // Cache settings
  cache: {
    enabled: true,
    ttl: 300000, // 5 minutes
    maxSize: 100  // 100 cached results
  },
  
  // Request optimization
  requests: {
    timeout: 30000,
    retries: 3,
    batchSize: 5
  },
  
  // Screenshot optimization
  screenshots: {
    quality: 80,
    format: 'webp',
    maxWidth: 1920,
    compression: true
  }
};

Batch Analysis

import { batchAnalyze } from 'jpglens/performance';

// Analyze multiple pages efficiently
const pages = [
  { url: '/home', name: 'homepage' },
  { url: '/products', name: 'product-listing' },
  { url: '/checkout', name: 'checkout' }
];

const batchResults = await batchAnalyze(pages, {
  concurrency: 3,
  sharedContext: {
    userContext: { persona: 'mobile-user' },
    analysisTypes: ['usability', 'performance']
  },
  optimization: {
    reuseSession: true,
    cacheScreenshots: true,
    parallelProcessing: true
  }
});

console.log(`Analyzed ${pages.length} pages in ${batchResults.totalTime}ms`);

Memory Management

// Optimize memory usage for large test suites
const memoryConfig = {
  // Clear screenshots after analysis
  autoCleanup: true,
  
  // Limit concurrent analyses
  maxConcurrentAnalyses: 2,
  
  // Stream results instead of storing in memory
  streamResults: true,
  
  // Garbage collection hints
  forceGC: true
};

await analyzeUserJourney(page, {
  ...standardConfig,
  performance: memoryConfig
});

Performance Monitoring

import { PerformanceMonitor } from 'jpglens/performance';

const monitor = new PerformanceMonitor();

monitor.on('analysis-start', (data) => {
  console.log(`Starting analysis: ${data.analysisId}`);
});

monitor.on('analysis-complete', (data) => {
  console.log(`Analysis completed in ${data.duration}ms`);
  console.log(`Memory usage: ${data.memoryUsage}MB`);
});

monitor.on('bottleneck-detected', (data) => {
  console.warn(`Performance bottleneck: ${data.bottleneck}`);
  console.warn(`Recommendation: ${data.recommendation}`);
});

Troubleshooting

Common issues and solutions for jpglens implementation and usage.

Common Issues

🔑 API Key Issues

Problem: "API key is required" error
Solution:
# Set environment variable
export JPGLENS_API_KEY="your-api-key-here"

# Or in .env file
JPGLENS_API_KEY=your-api-key-here
Problem: "Invalid API key" error
Solution: Verify your API key is correct and has proper permissions:
// Test API key
import { testAPIConnection } from 'jpglens/utils';

const isValid = await testAPIConnection();
if (!isValid) {
  console.error('API key is invalid or expired');
}

🖼️ Screenshot Issues

Problem: Screenshots are blank or corrupted
Solution:
// Wait for page to fully load
await page.waitForLoadState('networkidle');
await page.waitForTimeout(1000); // Additional wait

// Ensure viewport is set
await page.setViewportSize({ width: 1920, height: 1080 });
Problem: Dynamic content not captured
Solution:
// Wait for specific elements
await page.waitForSelector('.dynamic-content');
await page.waitForFunction(() => document.readyState === 'complete');

⚡ Performance Issues

Problem: Analysis taking too long
Solutions:
// Reduce analysis scope
const quickConfig = {
  analysis: {
    types: ['usability'], // Focus on one type
    depth: 'quick',       // Use quick analysis
    includeScreenshots: false
  }
};

// Use caching
const cachedConfig = {
  cache: {
    enabled: true,
    ttl: 600000 // 10 minutes
  }
};

Debug Mode

// Enable debug logging
process.env.JPGLENS_DEBUG = 'true';

// Or in configuration
const config = {
  debug: {
    enabled: true,
    logLevel: 'verbose', // 'error', 'warn', 'info', 'verbose'
    saveScreenshots: true,
    saveRequests: true
  }
};

await analyzeUserJourney(page, config);

Health Check

import { healthCheck } from 'jpglens/diagnostics';

// Run comprehensive health check
const health = await healthCheck();

console.log('API Connection:', health.apiConnection);
console.log('Browser Support:', health.browserSupport);
console.log('Dependencies:', health.dependencies);
console.log('Configuration:', health.configuration);

if (!health.overall) {
  console.log('Issues found:', health.issues);
  console.log('Recommendations:', health.recommendations);
}

Support Resources

Core API

The core jpglens API provides powerful functions for AI-powered UI analysis and testing.

quickAnalyze(page, options?)

Performs a rapid AI analysis of the current page state. Perfect for development and quick feedback.

Parameters

  • page Page - Playwright page object
  • options QuickAnalyzeOptions? - Optional configuration

Returns

Promise<QuickAnalysisResult> - Analysis results with insights and recommendations

Example

import { quickAnalyze } from 'jpglens/playwright';

test('analyze login page', async ({ page }) => {
  await page.goto('/login');
  
  const analysis = await quickAnalyze(page, {
    focus: 'usability',
    includeAccessibility: true
  });
  
  console.log(analysis.insights);
  expect(analysis.score).toBeGreaterThan(0.8);
});

analyzeUserJourney(journey, options?)

Analyzes a complete user journey across multiple pages and interactions.

Parameters

  • journey UserJourney - Journey definition with stages
  • options JourneyAnalysisOptions? - Optional configuration

Returns

Promise<JourneyAnalysisResult> - Comprehensive journey analysis

Example

const userJourney = {
  name: 'checkout-flow',
  persona: 'returning-customer',
  stages: [
    { name: 'cart', page: '/cart', userGoal: 'review items' },
    { name: 'checkout', page: '/checkout', userGoal: 'complete purchase' }
  ]
};

const results = await analyzeUserJourney(userJourney);
console.log(results.overallScore);
console.log(results.stageAnalysis);

Types & Interfaces

TypeScript definitions for jpglens API components.

QuickAnalyzeOptions

interface QuickAnalyzeOptions {
  focus?: 'usability' | 'performance' | 'accessibility' | 'visual' | 'all';
  includeAccessibility?: boolean;
  includePerformance?: boolean;
  customPrompts?: string[];
  outputFormat?: 'detailed' | 'summary' | 'json';
  aiProvider?: 'openai' | 'anthropic' | 'openrouter';
  model?: string;
}

QuickAnalysisResult

interface QuickAnalysisResult {
  score: number; // 0-1
  insights: string[];
  recommendations: Recommendation[];
  issues: Issue[];
  metadata: {
    timestamp: string;
    url: string;
    viewport: { width: number; height: number; };
    analysisTime: number;
  };
}

UserJourney

interface UserJourney {
  name: string;
  persona?: string;
  device?: 'desktop' | 'mobile' | 'tablet';
  stages: JourneyStage[];
}

interface JourneyStage {
  name: string;
  page: string;
  userGoal: string;
  aiAnalysis?: string;
  actions?: Action[];
}

Utilities

Helper functions and utilities for enhanced testing workflows.

generateReport(results, options?)

Generate comprehensive reports from analysis results.

import { generateReport } from 'jpglens/utils';

const report = await generateReport(analysisResults, {
  format: 'html',
  includeScreenshots: true,
  theme: 'dark'
});

await fs.writeFile('report.html', report);

createCustomPrompt(template, variables?)

Create custom AI analysis prompts for specialized testing scenarios.

const customPrompt = createCustomPrompt(
  'Analyze this {{pageType}} for {{userType}} users focusing on {{criteria}}',
  {
    pageType: 'e-commerce product page',
    userType: 'mobile',
    criteria: 'conversion optimization'
  }
);