npm package: @rahulrpandya/pw-core-design
Description: A core automation framework for Web and API testing built on Playwright
Author: Rahul R
Latest version: 1.0.3

# pw-core-design

<p align="center">
  <img src="https://img.shields.io/npm/v/@rahulrpandya/pw-core-design?style=flat-square" alt="npm version" />
  <img src="https://img.shields.io/npm/l/@rahulrpandya/pw-core-design?style=flat-square" alt="license" />
  <img src="https://img.shields.io/npm/dt/@rahulrpandya/pw-core-design?style=flat-square" alt="downloads" />
  <img src="https://img.shields.io/github/actions/workflow/status/MrRahulR/pw-core-design/ci.yml?style=flat-square" alt="build status" />
</p>

<p align="center">
  A lightweight, modular core automation framework for Web and API testing built on <a href="https://playwright.dev/">Playwright</a>.
</p>

---

## ✨ 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

```bash
npm install @rahulrpandya/pw-core-design playwright
```

### GitHub Packages

```bash
npm install @MrRahulR/pw-core-design playwright --registry=https://npm.pkg.github.com
```

### Yarn

```bash
yarn add @rahulrpandya/pw-core-design playwright
```

> **Note:** Playwright is a peer dependency. You need to install it separately.

After installation, install Playwright browsers:

```bash
npx playwright install
```

---

## 🚀 Quick Start

### Web Automation

```typescript
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', 'test@example.com');

  // Take screenshot
  await page.screenshot({ path: 'screenshot.png' });

  // Cleanup
  await browserManager.closeAll();
}

main();
```

### API Automation

```typescript
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: 'john@example.com'
  });
  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:

```env
# 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=INFO
```

#### Programmatic Configuration

```typescript
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.

```typescript
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.

```typescript
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

```typescript
// 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

```typescript
// 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

```typescript
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.

```typescript
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:

```typescript
// 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](./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:

```bash
npm run example:web
npm run example:api
npm run example:combined
```

---

## 🤝 Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## 🙏 Acknowledgments

- [Playwright](https://playwright.dev/) - The amazing automation library this framework is built on
- [TypeScript](https://www.typescriptlang.org/) - For type safety and great DX

---

<p align="center">
  Made with ❤️ for the testing community
</p>