@rahulrpandya/pw-core-design
v1.0.3
Published
A core automation framework for Web and API testing built on Playwright
Maintainers
Readme
pw-core-design
✨ Features
- 🌐 Web Automation - Full browser management with Chromium, Firefox, and WebKit support
- 🔌 API Testing - Complete HTTP client with authentication and interceptors
- ⚙️ Flexible Configuration - Environment variables and programmatic configuration
- 📝 Built-in Logging - Colorful, leveled logging with timestamps
- 📦 Modular Design - Import only what you need
- 🔷 TypeScript First - Full type safety and IntelliSense support
- 🚀 Easy to Extend - Use as a foundation for your test frameworks
📦 Installation
NPM
npm install @rahulrpandya/pw-core-design playwrightGitHub Packages
npm install @MrRahulR/pw-core-design playwright --registry=https://npm.pkg.github.comYarn
yarn add @rahulrpandya/pw-core-design playwrightNote: Playwright is a peer dependency. You need to install it separately.
After installation, install Playwright browsers:
npx playwright install🚀 Quick Start
Web Automation
import {
ConfigManager,
BrowserManager,
BrowserType
} from '@rahulrpandya/pw-core-design';
async function main() {
// Initialize configuration
const config = ConfigManager.getInstance();
config.init({
browser: { type: BrowserType.CHROMIUM, headless: false },
baseUrl: 'https://example.com'
});
// Launch browser
const browserManager = BrowserManager.getInstance();
await browserManager.launch();
// Create page and navigate
const page = await browserManager.createPage();
await page.goto('https://example.com');
// Interact with page
await page.click('button#submit');
await page.fill('input#email', '[email protected]');
// Take screenshot
await page.screenshot({ path: 'screenshot.png' });
// Cleanup
await browserManager.closeAll();
}
main();API Automation
import {
ConfigManager,
createApiClient
} from '@rahulrpandya/pw-core-design';
async function main() {
// Initialize configuration
ConfigManager.getInstance().init({
api: { baseUrl: 'https://api.example.com' }
});
// Create API client
const api = createApiClient();
await api.init();
// Make requests
const users = await api.get('/users');
console.log(users.body);
const newUser = await api.post('/users', {
name: 'John Doe',
email: '[email protected]'
});
console.log(newUser.body);
// Cleanup
await api.dispose();
}
main();📖 Documentation
Configuration
The framework supports both environment variables and programmatic configuration.
Environment Variables
Create a .env file in your project root:
# Browser Configuration
BROWSER=chromium # chromium, firefox, webkit
HEADLESS=true
SLOW_MO=0
DEVTOOLS=false
# Timeouts (milliseconds)
DEFAULT_TIMEOUT=30000
NAVIGATION_TIMEOUT=60000
ACTION_TIMEOUT=15000
# URLs
BASE_URL=http://localhost:3000
API_BASE_URL=http://localhost:3000/api
API_TIMEOUT=30000
# Viewport
VIEWPORT_WIDTH=1920
VIEWPORT_HEIGHT=1080
# Debug
DEBUG=false
LOG_LEVEL=INFOProgrammatic Configuration
import { ConfigManager, BrowserType } from '@rahulrpandya/pw-core-design';
const config = ConfigManager.getInstance();
config.init({
browser: {
type: BrowserType.FIREFOX,
headless: false,
slowMo: 100,
devtools: true
},
viewport: {
width: 1280,
height: 720
},
timeouts: {
default: 30000,
navigation: 60000,
action: 15000
},
baseUrl: 'https://myapp.com',
api: {
baseUrl: 'https://api.myapp.com',
timeout: 30000
},
debug: true
});BrowserManager
Manages Playwright browser instances, contexts, and pages.
import { BrowserManager } from '@rahulrpandya/pw-core-design';
const browserManager = BrowserManager.getInstance();
// Launch browser
await browserManager.launch();
// Create context with options
const context = await browserManager.createContext({
viewport: { width: 1280, height: 720 },
locale: 'en-US',
colorScheme: 'dark'
}, 'my-context');
// Create page in context
const page = await browserManager.createPage('my-context', 'my-page');
// Get existing page
const existingPage = browserManager.getPage('my-page');
// Get browser state
const state = browserManager.getState();
console.log(state);
// { isInitialized: true, browserType: 'chromium', contextCount: 1, pageCount: 1 }
// Take screenshot
await browserManager.takeScreenshot('my-page', './screenshot.png', { fullPage: true });
// Close specific resources
await browserManager.closePage('my-page');
await browserManager.closeContext('my-context');
// Close everything
await browserManager.closeAll();ApiClient
Handles HTTP requests with authentication, interceptors, and retry logic.
import { createApiClient, AuthType } from '@rahulrpandya/pw-core-design';
const api = createApiClient({
baseUrl: 'https://api.example.com',
timeout: 30000,
defaultHeaders: {
'X-Custom-Header': 'value'
}
});
await api.init();
// HTTP Methods
const getResponse = await api.get('/users');
const postResponse = await api.post('/users', { name: 'John' });
const putResponse = await api.put('/users/1', { name: 'Jane' });
const patchResponse = await api.patch('/users/1', { name: 'Jane' });
const deleteResponse = await api.delete('/users/1');
// With query parameters
const filtered = await api.get('/users', {
params: { role: 'admin', active: true }
});
// Response structure
console.log(getResponse.status); // 200
console.log(getResponse.statusText); // 'OK'
console.log(getResponse.body); // Response data
console.log(getResponse.headers); // Response headers
console.log(getResponse.ok); // true
console.log(getResponse.responseTime); // 150 (ms)Authentication
// Bearer Token
api.setBearerToken('your-jwt-token');
// Basic Auth
api.setBasicAuth('username', 'password');
// API Key
api.setApiKey('your-api-key', 'X-API-Key');
// Custom Auth
api.setAuth({
type: AuthType.CUSTOM,
customHeaders: {
'Authorization': 'Custom scheme token'
}
});
// Clear auth
api.clearAuth();Interceptors
// Request interceptor
api.addRequestInterceptor((url, options) => {
console.log(`Request: ${url}`);
// Modify request if needed
options.headers = { ...options.headers, 'X-Request-ID': 'uuid' };
return { url, options };
});
// Response interceptor
api.addResponseInterceptor((response) => {
console.log(`Response: ${response.status} in ${response.responseTime}ms`);
return response;
});
// Clear interceptors
api.clearInterceptors();Retry Configuration
const api = createApiClient({
baseUrl: 'https://api.example.com',
retryConfig: {
maxRetries: 3,
retryDelay: 1000,
retryOn: [500, 502, 503, 504]
}
});Logger
Built-in logging utility with levels and colors.
import { Logger, LogLevel, createLogger } from '@rahulrpandya/pw-core-design';
// Create logger with prefix
const logger = createLogger('MyModule');
// Log messages
logger.debug('Debug message');
logger.info('Info message');
logger.warn('Warning message');
logger.error('Error message', { details: 'error object' });
// Set global log level
Logger.setGlobalLevel(LogLevel.DEBUG);
// Create child logger
const childLogger = logger.child('SubModule');
childLogger.info('Message'); // [MyModule:SubModule] Message
// Visual helpers
logger.divider();
logger.group('Group Title');
logger.info('Grouped message');
logger.groupEnd();📁 Project Structure
pw-core-design/
├── src/
│ ├── api/ # API client module
│ │ ├── api.types.ts
│ │ ├── ApiClient.ts
│ │ └── index.ts
│ ├── browser/ # Browser manager module
│ │ ├── browser.types.ts
│ │ ├── BrowserManager.ts
│ │ └── index.ts
│ ├── config/ # Configuration module
│ │ ├── types.ts
│ │ ├── ConfigManager.ts
│ │ └── index.ts
│ ├── utils/ # Utilities
│ │ ├── logger.types.ts
│ │ ├── Logger.ts
│ │ └── index.ts
│ └── index.ts # Main entry point
├── examples/ # Usage examples
├── dist/ # Compiled output
├── package.json
├── tsconfig.json
└── README.md🔧 Using as a Base Framework
This package is designed to be used as a foundation for your test frameworks:
// my-test-framework/src/index.ts
import {
ConfigManager,
BrowserManager,
ApiClient,
createApiClient,
Logger
} from '@rahulrpandya/pw-core-design';
// Extend with your custom functionality
export class TestFramework {
private browserManager: BrowserManager;
private apiClient: ApiClient;
private logger: Logger;
constructor() {
this.browserManager = BrowserManager.getInstance();
this.apiClient = createApiClient();
this.logger = new Logger('TestFramework');
}
async setup() {
ConfigManager.getInstance().init();
await this.browserManager.launch();
await this.apiClient.init();
}
async teardown() {
await this.browserManager.closeAll();
await this.apiClient.dispose();
}
// Add your custom methods...
}🧪 Examples
Check the examples folder for complete working examples:
- Web Automation - Browser automation with forms, navigation, screenshots
- API Automation - REST API testing with all HTTP methods
- Combined - Integration testing with both Web and API
Run examples:
npm run example:web
npm run example:api
npm run example:combined🤝 Contributing
Contributions are welcome! Please read our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Playwright - The amazing automation library this framework is built on
- TypeScript - For type safety and great DX
