diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 4d7e3a8..79d5931 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,15 +5,15 @@ "email": "github@lackeyjb" }, "metadata": { - "description": "Playwright browser automation skill for Claude Code", - "version": "1.0.0" + "description": "Playwright browser automation skill for coding agents", + "version": "5.0.0" }, "plugins": [ { "name": "playwright-skill", "source": "./", - "description": "Claude Code Skill for general-purpose browser automation with Playwright. Claude autonomously writes and executes custom automation for testing pages, validating UX, and any browser task.", - "version": "4.1.0", + "description": "Agent Skill for general-purpose browser automation with Playwright. The agent writes and executes custom scripts for testing pages, validating UX, and automating browser tasks.", + "version": "5.0.0", "author": { "name": "lackeyjb" }, diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index fe6f261..746a7d8 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "playwright-skill", - "version": "4.1.0", - "description": "Claude Code Skill for general-purpose browser automation with Playwright. Auto-detects dev servers, writes clean test scripts to /tmp, and autonomously handles any browser automation task.", + "version": "5.0.0", + "description": "Agent Skill for general-purpose Playwright browser automation. Detects dev servers and helps coding agents write, execute, and preserve reusable browser scripts.", "author": { "name": "lackeyjb" }, diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..99a3f51 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Maintainer review is required for changes to the skill and its executor. +* @lackeyjb diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..f8b4f80 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,24 @@ +name: Bug report +description: Report a reproducible problem with the skill or executor. +title: "bug: " +labels: [bug] +body: + - type: textarea + id: problem + attributes: + label: Problem + description: What happened, and what did you expect? + validations: + required: true + - type: input + id: environment + attributes: + label: Environment + description: Include OS, Node.js, Playwright, and agent versions. + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Reproduction + description: Include the smallest script or prompt that reproduces the problem. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..c767f9f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,16 @@ +name: Feature request +description: Suggest a focused improvement. +title: "feat: " +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: Problem and proposed solution + description: What problem does this solve, and how would you use it? + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives considered diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..2931486 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: /skills/playwright-skill + schedule: + interval: monthly + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..9f47bb9 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +## Summary + + + +## Verification + +- [ ] `npm test` passes +- [ ] The relevant example or smoke test passes +- [ ] Documentation is updated when behavior changes + +## Checklist + +- [ ] This PR is focused and keeps the skill's loaded instructions concise. +- [ ] No credentials or generated browser artifacts are included. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d911e21 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,29 @@ +name: CI + +on: + push: + pull_request: + +jobs: + validate: + name: Validate (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + strategy: + matrix: + node: [20, 22, 24] + defaults: + run: + working-directory: skills/playwright-skill + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + cache-dependency-path: skills/playwright-skill/package-lock.json + - run: npm ci + - run: npx playwright install --with-deps chromium + - run: npm test + - run: node skills/playwright-skill/run.js tests/smoke.js + working-directory: . + - run: npx skills-ref@0.1.5 validate . diff --git a/.gitignore b/.gitignore index 9775690..dd45e75 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,6 @@ # Dependencies node_modules/ .npm/ -package-lock.json # Logs *.log @@ -27,6 +26,10 @@ screenshots/ *.jpg *.jpeg +# Keep checked-in documentation/demo images +!docs/**/*.png +!assets/**/*.png + # Environment .env .env.local diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5d7fddb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +## [5.0.0] - Unreleased + +### Changed + +- Updated the skill to the current Agent Skills frontmatter specification. +- Updated the runtime requirement to Node.js 20+ and Playwright 1.62+. +- Replaced the temporary-file executor with a child-process executor that preserves exit codes. +- Added explicit inline execution with `node run.js -e` and `PW_SCRIPT_DIR` support. +- Reduced helpers to focused browser setup, server detection, headers, cookie banners, and screenshots. +- Modernized examples around accessible locators and web-first waiting. +- Added CI, fixtures, unit tests, contribution templates, and Dependabot configuration. + +### Breaking changes + +- Helpers that duplicated Playwright actions, waits, extraction, authentication, and retries were removed. Use Playwright locators and assertions directly. +- Stdin execution through `run.js` was removed; use a script file or `-e`. +- `createContext()` no longer accepts a `mobile` option. Use Playwright device descriptors such as `devices['iPhone 15']` instead. +- `launchBrowser()` no longer passes `--no-sandbox` unconditionally. It is only added for Chromium when running as root; pass `args: ['--no-sandbox']` explicitly in other cases. +- An empty `PW_HEADLESS=` is now treated as unset and falls back to visible mode rather than headless. +- `run.js` executes scripts in the caller's working directory instead of the skill directory, so relative paths resolve against the user's project. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7e7606e..c205164 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,135 +1,42 @@ -# Contributing to Playwright Skill +# Contributing -Thank you for considering contributing to the Playwright Skill plugin for Claude Code! +Playwright Skill is an Agent Skill packaged as a Claude Code plugin. Focused +bug fixes, documentation improvements, and portable examples are welcome. -## How to Contribute +## Development -### Reporting Bugs +Requirements: Node.js 20+ and npm. -If you find a bug, please create an issue on GitHub with: -- Clear description of the problem -- Steps to reproduce -- Expected vs actual behavior -- Your environment (OS, Node version, Playwright version) -- Example code that demonstrates the issue - -### Suggesting Enhancements - -Enhancement suggestions are welcome! Please: -- Check existing issues first to avoid duplicates -- Clearly describe the enhancement and its benefits -- Provide examples of how it would be used - -### Pull Requests - -1. **Fork the repository** - ```bash - git clone https://github.com/lackeyjb/playwright-skill.git - cd playwright-skill - ``` - -2. **Create a feature branch** - ```bash - git checkout -b feature/your-feature-name - ``` - -3. **Make your changes** - - Follow the existing code style - - Add tests if applicable - - Update documentation as needed - -4. **Test your changes** - ```bash - npm run setup - # Test your changes with Claude Code - ``` - -5. **Commit your changes** - ```bash - git add . - git commit -m "feat: add your feature description" - ``` - -6. **Push to your fork** - ```bash - git push origin feature/your-feature-name - ``` - -7. **Create a Pull Request** - - Go to the original repository - - Click "New Pull Request" - - Select your fork and branch - - Provide a clear description of your changes - -## Development Guidelines - -### Code Style - -- Use clear, descriptive variable names -- Add comments for complex logic -- Keep functions focused on a single responsibility -- Follow existing patterns in the codebase - -### SKILL.md Guidelines - -- Keep examples concise (8-15 lines) -- Always show `headless: false` by default -- Include error handling in examples -- Add console.log statements for visibility -- Reference README.md for advanced topics - -### Commit Messages - -Use conventional commits format: -- `feat:` New features -- `fix:` Bug fixes -- `docs:` Documentation changes -- `refactor:` Code refactoring -- `test:` Adding tests -- `chore:` Maintenance tasks - -Examples: -``` -feat: add mobile device emulation helper -fix: resolve module resolution issue in run.js -docs: update installation instructions -``` - -### File Structure - -``` -playwright-skill/ -├── SKILL.md # Keep concise (~300 lines) -├── README.md # Full API reference -├── PLUGIN_README.md # Plugin distribution docs -├── run.js # Universal executor -├── package.json # Dependencies -├── plugin.json # Plugin metadata -└── lib/ - └── helpers.js # Utility functions +```bash +cd skills/playwright-skill +npm install +npx playwright install chromium +npm test +cd ../.. +node tests/smoke.js +npx skills-ref@0.1.5 validate skills/playwright-skill ``` -### Adding New Helpers +Keep browser artifacts out of the repository. Use the existing fixtures for +smoke coverage and add a focused `node:test` test for non-trivial helper logic. -When adding functions to `lib/helpers.js`: -1. Add clear JSDoc comments -2. Include error handling -3. Export the function -4. Update SKILL.md to mention it -5. Add example usage +## Pull requests -### Testing +- Open or reference an issue when the change is contributor-facing. +- Keep `SKILL.md` concise; put detailed material in `API_REFERENCE.md`. +- Use accessible locators and web-first assertions in examples. +- Update documentation when behavior or environment variables change. +- Include the commands used to verify the change. +- Use a conventional commit title such as `feat:`, `fix:`, `docs:`, or `test:`. -Before submitting: -1. Test with a fresh installation -2. Verify examples in SKILL.md work -3. Check that `run.js` handles edge cases -4. Ensure browser opens in visible mode by default +The v5.0.0 work is tracked in the [roadmap issue](https://github.com/lackeyjb/playwright-skill/issues/39). -## Questions? +## Reporting problems -Feel free to open an issue for discussion before starting work on major changes. +Use the issue templates and include the OS, Node.js version, Playwright +version, agent client, reproduction, and expected behavior. Questions and tool +comparisons belong in GitHub Discussions when enabled. ## License -By contributing, you agree that your contributions will be licensed under the MIT License. +By contributing, you agree that your contribution is licensed under MIT. diff --git a/README.md b/README.md index a3a36c9..fb30f51 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# Playwright Skill for Claude Code +# Playwright Skill -**General-purpose browser automation as a Claude Skill** +**General-purpose Playwright automation for coding agents** -A [Claude Skill](https://www.anthropic.com/blog/skills) that enables Claude to write and execute any Playwright automation on-the-fly - from simple page tests to complex multi-step flows. Packaged as a [Claude Code Plugin](https://docs.claude.com/en/docs/claude-code/plugins) for easy installation and distribution. +An [Agent Skill](https://agentskills.io) that enables coding agents to write and execute Playwright automation on the fly, from simple page tests to complex multi-step flows. It is also packaged as a [Claude Code Plugin](https://code.claude.com/docs/en/plugins) for convenient installation. Claude autonomously decides when to use this skill based on your browser automation needs, loading only the minimal information required for your specific task. @@ -12,14 +12,28 @@ Made using Claude Code. - **Any Automation Task** - Claude writes custom code for your specific request, not limited to pre-built scripts - **Visible Browser by Default** - See automation in real-time with `headless: false` -- **Zero Module Resolution Errors** - Universal executor ensures proper module access +- **Portable executor** - Runs file and inline scripts with stable module resolution - **Progressive Disclosure** - Concise SKILL.md with full API reference loaded only when needed - **Safe Cleanup** - Smart temp file management without race conditions - **Comprehensive Helpers** - Optional utility functions for common tasks ## Installation -This repository is structured as a [Claude Code Plugin](https://docs.claude.com/en/docs/claude-code/plugins) containing a skill. You can install it as either a **plugin** (recommended) or extract it as a **standalone skill**. +This repository contains a standard Agent Skill and a Claude Code plugin wrapper. The recommended installation method is Vercel's [`skills`](https://github.com/vercel-labs/skills) CLI, which installs skills into the native locations for supported agents. + +## Why this skill? + +Use this skill when the agent needs to write a real Playwright program: loops, +assertions, multiple contexts, network interception, screenshots, video, or a +script you want to keep and rerun. It also provides dev-server detection and a +small set of focused helpers. + +For straightforward interactive browsing, start with Microsoft's official +[`@playwright/cli`](https://github.com/microsoft/playwright-cli) and install its +agent skills with `playwright-cli install --skills`. For tool-based browser +control with accessibility snapshots, use +[`playwright-mcp`](https://github.com/microsoft/playwright-mcp). This project is +the code-first option when the automation itself is the useful artifact. ### Understanding the Structure @@ -33,75 +47,67 @@ playwright-skill/ # Plugin root └── SKILL.md ``` -Claude Code expects skills to be directly in folders under `.claude/skills/`, so manual installation requires extracting the nested skill folder. +The repository keeps the skill inside the plugin's `skills/` directory. Installers handle that layout automatically; manual copying is only a fallback for clients without an installer. --- -### Option 1: Plugin Installation (Recommended) +### Option 1: Install with `skills` (Recommended) -Install via Claude Code's plugin system for automatic updates and team distribution: +Install globally for your user: ```bash -# Add this repository as a marketplace -/plugin marketplace add lackeyjb/playwright-skill - -# Install the plugin -/plugin install playwright-skill@playwright-skill - -# Navigate to the skill directory and run setup -cd ~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill -npm run setup +npx skills add lackeyjb/playwright-skill --skill playwright-skill --global --yes ``` -Verify installation by running `/help` to confirm the skill is available. +Install only for the current project by omitting `--global`: ---- - -### Option 2: Standalone Skill Installation - -To install as a standalone skill (without the plugin system), extract only the skill folder: +```bash +npx skills add lackeyjb/playwright-skill --skill playwright-skill --yes +``` -**Global Installation (Available Everywhere):** +To target specific agents, add `--agent` followed by one or more agent IDs: ```bash -# Clone to a temporary location -git clone https://github.com/lackeyjb/playwright-skill.git /tmp/playwright-skill-temp +npx skills add lackeyjb/playwright-skill --skill playwright-skill --agent claude-code cursor --global --yes +``` -# Copy only the skill folder to your global skills directory -mkdir -p ~/.claude/skills -cp -r /tmp/playwright-skill-temp/skills/playwright-skill ~/.claude/skills/ +After installation, run setup from the installed skill directory: -# Navigate to the skill and run setup -cd ~/.claude/skills/playwright-skill +```bash npm run setup - -# Clean up temporary files -rm -rf /tmp/playwright-skill-temp ``` -**Project-Specific Installation:** +See the [`skills` CLI documentation](https://github.com/vercel-labs/skills) for supported agents and options. + +### Option 2: Claude Code Plugin + +Install via Claude Code's plugin system for automatic updates and team distribution: ```bash -# Clone to a temporary location -git clone https://github.com/lackeyjb/playwright-skill.git /tmp/playwright-skill-temp +# Add this repository as a marketplace +/plugin marketplace add lackeyjb/playwright-skill -# Copy only the skill folder to your project -mkdir -p .claude/skills -cp -r /tmp/playwright-skill-temp/skills/playwright-skill .claude/skills/ +# Install the plugin +/plugin install playwright-skill@playwright-skill -# Navigate to the skill and run setup -cd .claude/skills/playwright-skill +# Navigate to the skill directory and run setup +cd ~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill npm run setup - -# Clean up temporary files -rm -rf /tmp/playwright-skill-temp ``` -**Why this structure?** The plugin format requires the `skills/` directory for organizing multiple skills within a plugin. When installing as a standalone skill, you only need the inner `skills/playwright-skill/` folder contents. +Verify installation by running `/help` to confirm the skill is available. --- -### Option 3: Download Release +### Option 3: Other Agent Installations + +Agent Skills are supported by Claude Code, Cursor, GitHub Copilot, Codex, +Gemini CLI, OpenCode, and other clients. Install the directory containing +`SKILL.md` using the client’s documented skill path. If a client has no +installer, copy `skills/playwright-skill/` into its documented skill directory +and run `npm run setup` there. + +### Option 4: Download Release 1. Download and extract the latest release from [GitHub Releases](https://github.com/lackeyjb/playwright-skill/releases) 2. Copy only the `skills/playwright-skill/` folder to: @@ -121,7 +127,7 @@ Run `/help` to confirm the skill is loaded, then ask Claude to perform a simple ## Quick Start -After installation, simply ask Claude to test or automate any browser task. Claude will write custom Playwright code, execute it, and return results with screenshots and console output. +After installation, ask your agent to test or automate a browser task. It will write custom Playwright code, execute it, and return results with screenshots and console output. ## Usage Examples @@ -159,7 +165,7 @@ After installation, simply ask Claude to test or automate any browser task. Clau ## How It Works 1. Describe what you want to test or automate -2. Claude writes custom Playwright code for the task +2. Your agent writes custom Playwright code for the task 3. The universal executor (run.js) runs it with proper module resolution 4. Browser opens (visible by default) and automation executes 5. Results are displayed with console output and screenshots @@ -169,9 +175,8 @@ After installation, simply ask Claude to test or automate any browser task. Clau Default settings: - **Headless:** `false` (browser visible unless explicitly requested otherwise) -- **Slow Motion:** `100ms` for visibility -- **Timeout:** `30s` -- **Screenshots:** Saved to `/tmp/` +- **Slow Motion:** `0ms` by default; set `SLOW_MO` when useful +- **Screenshots:** Helper screenshots use the OS temp directory; set `PW_ARTIFACT_DIR` to choose another location ## Project Structure diff --git a/skills/playwright-skill/API_REFERENCE.md b/skills/playwright-skill/API_REFERENCE.md index 9ee2975..6d4b74f 100644 --- a/skills/playwright-skill/API_REFERENCE.md +++ b/skills/playwright-skill/API_REFERENCE.md @@ -95,10 +95,9 @@ const { chromium } = require('playwright'); const page = await context.newPage(); - // Navigate - await page.goto('https://example.com', { - waitUntil: 'networkidle' // Wait for network to be idle - }); + // Navigate, then assert a meaningful readiness signal. + await page.goto('https://example.com'); + await page.getByRole('link', { name: 'More information' }).waitFor(); // Your automation here @@ -270,8 +269,8 @@ await page.locator('button').waitFor({ state: 'detached' }); await page.waitForURL('**/success'); await page.waitForURL(url => url.pathname === '/dashboard'); -// Wait for network -await page.waitForLoadState('networkidle'); +// Prefer a user-visible assertion over network-idle heuristics. +await page.getByRole('heading', { name: 'Dashboard' }).waitFor(); await page.waitForLoadState('domcontentloaded'); // Wait for function @@ -422,7 +421,6 @@ PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Request-ID":"123"}' These headers are automatically applied to all requests when using: - `helpers.createContext(browser)` - headers merged automatically -- `getContextOptionsWithHeaders(options)` - utility injected by run.js wrapper **Precedence (highest to lowest):** 1. Headers passed directly in `options.extraHTTPHeaders` @@ -614,7 +612,7 @@ await frame.locator('button').click(); ```javascript async function scrollToBottom(page) { await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await page.waitForTimeout(500); + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => resolve()))); } ``` diff --git a/skills/playwright-skill/SKILL.md b/skills/playwright-skill/SKILL.md index 98c8214..83ad831 100644 --- a/skills/playwright-skill/SKILL.md +++ b/skills/playwright-skill/SKILL.md @@ -1,453 +1,205 @@ --- name: playwright-skill -description: Complete browser automation with Playwright. Auto-detects dev servers, writes clean test scripts to /tmp. Test pages, fill forms, take screenshots, check responsive design, validate UX, test login flows, check links, automate any browser task. Use when user wants to test websites, automate browser interactions, validate web functionality, or perform any browser-based testing. +description: Complete browser automation with Playwright. Auto-detects dev servers, writes reusable test scripts, and supports screenshots, responsive checks, UX validation, login flows, link checks, and arbitrary browser automation. Use when the user wants to test a website, automate browser interactions, validate web functionality, or perform browser-based testing. +license: MIT +compatibility: Requires Node.js 20+, npm, and network access on first setup to install Playwright and Chromium. +metadata: + author: lackeyjb + version: "5.0.0" +allowed-tools: Bash(node:*) Bash(npm:*) Read Write --- -**IMPORTANT - Path Resolution:** -This skill can be installed in different locations (plugin system, manual installation, global, or project-specific). Before executing any commands, determine the skill directory based on where you loaded this SKILL.md file, and use that path in all commands below. Replace `$SKILL_DIR` with the actual discovered path. - -Common installation paths: - -- Plugin system: `~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill` -- Manual global: `~/.claude/skills/playwright-skill` -- Project-specific: `/.claude/skills/playwright-skill` - # Playwright Browser Automation -General-purpose browser automation skill. I'll write custom Playwright code for any automation task you request and execute it via the universal executor. - -**CRITICAL WORKFLOW - Follow these steps in order:** - -1. **Auto-detect dev servers** - For localhost testing, ALWAYS run server detection FIRST: +Write and execute focused Playwright scripts for the user's request. Prefer the +skill's executor and helpers, but use the full Playwright API when needed. - ```bash - cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(servers => console.log(JSON.stringify(servers)))" - ``` - - - If **1 server found**: Use it automatically, inform user - - If **multiple servers found**: Ask user which one to test - - If **no servers found**: Ask for URL or offer to help start dev server - -2. **Write scripts to /tmp** - NEVER write test files to skill directory; always use `/tmp/playwright-test-*.js` - -3. **Use visible browser by default** - Always use `headless: false` unless user specifically requests headless mode +## Path resolution -4. **Parameterize URLs** - Always make URLs configurable via environment variable or constant at top of script - -## How It Works - -1. You describe what you want to test/automate -2. I auto-detect running dev servers (or ask for URL if testing external site) -3. I write custom Playwright code in `/tmp/playwright-test-*.js` (won't clutter your project) -4. I execute it via: `cd $SKILL_DIR && node run.js /tmp/playwright-test-*.js` -5. Results displayed in real-time, browser window visible for debugging -6. Test files auto-cleaned from /tmp by your OS - -## Setup (First Time) +This skill can be installed in several locations, so resolve its directory +first. Set `SKILL_DIR` to the directory containing this SKILL.md file, then run +the commands below as written: ```bash -cd $SKILL_DIR -npm run setup +export SKILL_DIR= ``` -This installs Playwright and Chromium browser. Only needed once. - -## Execution Pattern +If shell state does not persist between commands, substitute the literal path +for `$SKILL_DIR` in each command instead. -**Step 1: Detect dev servers (for localhost testing)** - -```bash -cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(s => console.log(JSON.stringify(s)))" -``` - -**Step 2: Write test script to /tmp with URL parameter** +Common installation paths: -```javascript -// /tmp/playwright-test-page.js -const { chromium } = require('playwright'); +- Plugin system: `~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill` +- Manual global: `~/.claude/skills/playwright-skill` +- Project-specific: `/.claude/skills/playwright-skill` -// Parameterized URL (detected or user-provided) -const TARGET_URL = 'http://localhost:3001'; // <-- Auto-detected or from user +## Workflow -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); +1. For localhost work, detect running servers before writing a URL: - await page.goto(TARGET_URL); - console.log('Page loaded:', await page.title()); + ```bash + node -e "require('$SKILL_DIR/lib/helpers').detectDevServers().then(s => console.log(JSON.stringify(s)))" + ``` - await page.screenshot({ path: '/tmp/screenshot.png', fullPage: true }); - console.log('📸 Screenshot saved to /tmp/screenshot.png'); + Use the only result automatically. Ask which URL to use when there are + multiple results. Ask for a URL or offer to start a server when none exist. +2. Write reusable scripts to `/tmp/playwright-test-*.js` unless the user asks + to save them in the project. Use `PW_SCRIPT_DIR` to preserve scripts. +3. Use a visible browser by default. Use `headless: true` only when requested + or when the environment has no display. +4. Put the target URL in a constant or environment variable. +5. Run scripts with `node "$SKILL_DIR/run.js" `. +6. Report actions, failures, and artifact paths. Do not claim success without + checking the resulting page. - await browser.close(); -})(); -``` +## Setup -**Step 3: Execute from skill directory** +Run once: ```bash -cd $SKILL_DIR && node run.js /tmp/playwright-test-page.js +cd "$SKILL_DIR" && npm run setup ``` -## Common Patterns +This installs Playwright and Chromium. Use `cd "$SKILL_DIR" && npm run +install-all-browsers` when Firefox or WebKit is required. -### Test a Page (Multiple Viewports) +## Minimal example ```javascript -// /tmp/playwright-test-responsive.js const { chromium } = require('playwright'); -const TARGET_URL = 'http://localhost:3001'; // Auto-detected - -(async () => { - const browser = await chromium.launch({ headless: false, slowMo: 100 }); - const page = await browser.newPage(); - - // Desktop test - await page.setViewportSize({ width: 1920, height: 1080 }); - await page.goto(TARGET_URL); - console.log('Desktop - Title:', await page.title()); - await page.screenshot({ path: '/tmp/desktop.png', fullPage: true }); - - // Mobile test - await page.setViewportSize({ width: 375, height: 667 }); - await page.screenshot({ path: '/tmp/mobile.png', fullPage: true }); - - await browser.close(); -})(); -``` - -### Test Login Flow - -```javascript -// /tmp/playwright-test-login.js -const { chromium } = require('playwright'); - -const TARGET_URL = 'http://localhost:3001'; // Auto-detected +const targetUrl = process.env.TARGET_URL || 'http://localhost:3000'; (async () => { const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - await page.goto(`${TARGET_URL}/login`); - - await page.fill('input[name="email"]', 'test@example.com'); - await page.fill('input[name="password"]', 'password123'); - await page.click('button[type="submit"]'); - - // Wait for redirect - await page.waitForURL('**/dashboard'); - console.log('✅ Login successful, redirected to dashboard'); - - await browser.close(); -})(); -``` - -### Fill and Submit Form - -```javascript -// /tmp/playwright-test-form.js -const { chromium } = require('playwright'); - -const TARGET_URL = 'http://localhost:3001'; // Auto-detected - -(async () => { - const browser = await chromium.launch({ headless: false, slowMo: 50 }); - const page = await browser.newPage(); - - await page.goto(`${TARGET_URL}/contact`); - - await page.fill('input[name="name"]', 'John Doe'); - await page.fill('input[name="email"]', 'john@example.com'); - await page.fill('textarea[name="message"]', 'Test message'); - await page.click('button[type="submit"]'); - - // Verify submission - await page.waitForSelector('.success-message'); - console.log('✅ Form submitted successfully'); - - await browser.close(); -})(); -``` - -### Check for Broken Links - -```javascript -const { chromium } = require('playwright'); - -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - await page.goto('http://localhost:3000'); - - const links = await page.locator('a[href^="http"]').all(); - const results = { working: 0, broken: [] }; - - for (const link of links) { - const href = await link.getAttribute('href'); - try { - const response = await page.request.head(href); - if (response.ok()) { - results.working++; - } else { - results.broken.push({ url: href, status: response.status() }); - } - } catch (e) { - results.broken.push({ url: href, error: e.message }); - } - } - - console.log(`✅ Working links: ${results.working}`); - console.log(`❌ Broken links:`, results.broken); - - await browser.close(); -})(); -``` - -### Take Screenshot with Error Handling - -```javascript -const { chromium } = require('playwright'); - -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - try { - await page.goto('http://localhost:3000', { - waitUntil: 'networkidle', - timeout: 10000, - }); - - await page.screenshot({ - path: '/tmp/screenshot.png', - fullPage: true, - }); - - console.log('📸 Screenshot saved to /tmp/screenshot.png'); - } catch (error) { - console.error('❌ Error:', error.message); + const page = await browser.newPage(); + await page.goto(targetUrl); + console.log('Page loaded:', await page.title()); + await page.screenshot({ path: '/tmp/page.png', fullPage: true }); } finally { await browser.close(); } })(); ``` -### Test Responsive Design - -```javascript -// /tmp/playwright-test-responsive-full.js -const { chromium } = require('playwright'); - -const TARGET_URL = 'http://localhost:3001'; // Auto-detected +Run it: -(async () => { - const browser = await chromium.launch({ headless: false }); - const page = await browser.newPage(); - - const viewports = [ - { name: 'Desktop', width: 1920, height: 1080 }, - { name: 'Tablet', width: 768, height: 1024 }, - { name: 'Mobile', width: 375, height: 667 }, - ]; - - for (const viewport of viewports) { - console.log( - `Testing ${viewport.name} (${viewport.width}x${viewport.height})`, - ); - - await page.setViewportSize({ - width: viewport.width, - height: viewport.height, - }); - - await page.goto(TARGET_URL); - await page.waitForTimeout(1000); - - await page.screenshot({ - path: `/tmp/${viewport.name.toLowerCase()}.png`, - fullPage: true, - }); - } - - console.log('✅ All viewports tested'); - await browser.close(); -})(); +```bash +node "$SKILL_DIR/run.js" /tmp/playwright-test-page.js ``` -## Inline Execution (Simple Tasks) - -For quick one-off tasks, you can execute code inline without creating files: +For short one-off tasks, use inline execution: ```bash -# Take a quick screenshot -cd $SKILL_DIR && node run.js " -const browser = await chromium.launch({ headless: false }); -const page = await browser.newPage(); -await page.goto('http://localhost:3001'); -await page.screenshot({ path: '/tmp/quick-screenshot.png', fullPage: true }); -console.log('Screenshot saved'); -await browser.close(); -" +node "$SKILL_DIR/run.js" -e "const browser = await chromium.launch({headless: false}); try { const page = await browser.newPage(); await page.goto('https://example.com'); console.log(await page.title()); } finally { await browser.close(); }" ``` -**When to use inline vs files:** - -- **Inline**: Quick one-off tasks (screenshot, check if element exists, get page title) -- **Files**: Complex tests, responsive design checks, anything user might want to re-run - -## Available Helpers - -Optional utility functions in `lib/helpers.js`: - -```javascript -const helpers = require('./lib/helpers'); - -// Detect running dev servers (CRITICAL - use this first!) -const servers = await helpers.detectDevServers(); -console.log('Found servers:', servers); +The `-e` process exits as soon as the snippet settles, so close the browser +inside the snippet. -// Safe click with retry -await helpers.safeClick(page, 'button.submit', { retries: 3 }); +## Current Playwright patterns -// Safe type with clear -await helpers.safeType(page, '#username', 'testuser'); +Prefer locators that describe what a user sees, in this order: -// Take timestamped screenshot -await helpers.takeScreenshot(page, 'test-result'); +1. `page.getByRole()` with an accessible name +2. `page.getByLabel()` for form controls +3. `page.getByText()` for visible content +4. `page.getByTestId()` when the application provides a test contract -// Handle cookie banners -await helpers.handleCookieBanner(page); +Actions auto-wait for actionability. Use web-first assertions or a locator's +`waitFor()` instead of `waitForSelector()`, fixed sleeps, or `networkidle`. -// Extract table data -const data = await helpers.extractTableData(page, 'table.results'); +```javascript +await page.getByLabel('Email').fill('test@example.com'); +await page.getByRole('button', { name: 'Sign in' }).click(); +await page.waitForURL('**/dashboard'); +await page.getByRole('heading', { name: 'Dashboard' }).waitFor(); ``` -See `lib/helpers.js` for full list. - -## Custom HTTP Headers - -Configure custom headers for all HTTP requests via environment variables. Useful for: - -- Identifying automated traffic to your backend -- Getting LLM-optimized responses (e.g., plain text errors instead of styled HTML) -- Adding authentication tokens globally +## Common tasks -### Configuration - -**Single header (common case):** - -```bash -PW_HEADER_NAME=X-Automated-By PW_HEADER_VALUE=playwright-skill \ - cd $SKILL_DIR && node run.js /tmp/my-script.js -``` +### Responsive checks -**Multiple headers (JSON format):** +```javascript +const viewports = [ + { name: 'desktop', width: 1440, height: 900 }, + { name: 'mobile', width: 390, height: 844 }, +]; -```bash -PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Debug":"true"}' \ - cd $SKILL_DIR && node run.js /tmp/my-script.js +for (const viewport of viewports) { + await page.setViewportSize(viewport); + await page.goto(targetUrl); + await page.screenshot({ path: `/tmp/${viewport.name}.png`, fullPage: true }); +} ``` -### How It Works - -Headers are automatically applied when using `helpers.createContext()`: - -```javascript -const context = await helpers.createContext(browser); -const page = await context.newPage(); -// All requests from this page include your custom headers -``` +### Login flow -For scripts using raw Playwright API, use the injected `getContextOptionsWithHeaders()`: +Use test credentials supplied by the user. Never invent or expose real +credentials. Verify both the navigation and a post-login element. ```javascript -const context = await browser.newContext( - getContextOptionsWithHeaders({ viewport: { width: 1920, height: 1080 } }), -); +await page.goto(`${targetUrl}/login`); +await page.getByLabel('Email').fill(process.env.TEST_EMAIL); +await page.getByLabel('Password').fill(process.env.TEST_PASSWORD); +await page.getByRole('button', { name: /sign in|log in/i }).click(); +await page.waitForURL('**/dashboard'); +await page.getByRole('heading', { name: /dashboard/i }).waitFor(); ``` -## Advanced Usage - -For comprehensive Playwright API documentation, see [API_REFERENCE.md](API_REFERENCE.md): - -- Selectors & Locators best practices -- Network interception & API mocking -- Authentication & session management -- Visual regression testing -- Mobile device emulation -- Performance testing -- Debugging techniques -- CI/CD integration - -## Tips - -- **CRITICAL: Detect servers FIRST** - Always run `detectDevServers()` before writing test code for localhost testing -- **Custom headers** - Use `PW_HEADER_NAME`/`PW_HEADER_VALUE` env vars to identify automated traffic to your backend -- **Use /tmp for test files** - Write to `/tmp/playwright-test-*.js`, never to skill directory or user's project -- **Parameterize URLs** - Put detected/provided URL in a `TARGET_URL` constant at the top of every script -- **DEFAULT: Visible browser** - Always use `headless: false` unless user explicitly asks for headless mode -- **Headless mode** - Only use `headless: true` when user specifically requests "headless" or "background" execution -- **Slow down:** Use `slowMo: 100` to make actions visible and easier to follow -- **Wait strategies:** Use `waitForURL`, `waitForSelector`, `waitForLoadState` instead of fixed timeouts -- **Error handling:** Always use try-catch for robust automation -- **Console output:** Use `console.log()` to track progress and show what's happening - -## Troubleshooting - -**Playwright not installed:** +### Save scripts and artifacts ```bash -cd $SKILL_DIR && npm run setup +PW_SCRIPT_DIR=./playwright-tests node "$SKILL_DIR/run.js" /tmp/playwright-test-login.js +PW_ARTIFACT_DIR=./playwright-artifacts node "$SKILL_DIR/run.js" /tmp/playwright-test-page.js ``` -**Module not found:** -Ensure running from skill directory via `run.js` wrapper - -**Browser doesn't open:** -Check `headless: false` and ensure display available +`PW_SCRIPT_DIR` copies file-based scripts before execution and adds a timestamp +when a filename already exists. `PW_ARTIFACT_DIR` controls helper screenshot +output; the default is the operating system temporary directory. -**Element not found:** -Add wait: `await page.waitForSelector('.element', { timeout: 10000 })` +### Connect to an existing Chrome session -## Example Usage +Start Chrome with remote debugging enabled, then connect with Playwright: +```javascript +const browser = await chromium.connectOverCDP('http://127.0.0.1:9222'); +const page = browser.contexts()[0].pages()[0]; ``` -User: "Test if the marketing page looks good" -Claude: I'll test the marketing page across multiple viewports. Let me first detect running servers... -[Runs: detectDevServers()] -[Output: Found server on port 3001] -I found your dev server running on http://localhost:3001 +This reuses cookies and extensions in that session. Do not use it for secrets +unless the user explicitly asks; a connected browser has the user's access. -[Writes custom automation script to /tmp/playwright-test-marketing.js with URL parameterized] -[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-marketing.js] -[Shows results with screenshots from /tmp/] -``` +## Helpers -``` -User: "Check if login redirects correctly" +```javascript +const helpers = require(`${process.env.PW_SKILL_DIR}/lib/helpers`); -Claude: I'll test the login flow. First, let me check for running servers... -[Runs: detectDevServers()] -[Output: Found servers on ports 3000 and 3001] -I found 2 dev servers. Which one should I test? -- http://localhost:3000 -- http://localhost:3001 +const servers = await helpers.detectDevServers(); +const browser = await helpers.launchBrowser('chromium'); +const context = await helpers.createContext(browser); +const page = await context.newPage(); +await helpers.handleCookieBanner(page); +await helpers.takeScreenshot(page, 'result'); +``` -User: "Use 3001" +Available helpers are `detectDevServers`, `getExtraHeadersFromEnv`, +`launchBrowser`, `createContext`, `handleCookieBanner`, and `takeScreenshot`. +Use Playwright locators and assertions directly for actions, waits, extraction, +authentication, tables, and retries. -[Writes login automation to /tmp/playwright-test-login.js] -[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-login.js] -[Reports: ✅ Login successful, redirected to /dashboard] -``` +## Configuration -## Notes +- `PW_BROWSER`: `chromium`, `firefox`, or `webkit` for `launchBrowser()`. +- `PW_CHANNEL`: installed browser channel such as `chrome` or `msedge`. +- `PW_EXECUTABLE_PATH`: explicit browser executable path. +- `PW_HEADLESS`: `true` or `false`; visible mode is the default. +- `SLOW_MO`: action delay in milliseconds. +- `PW_HEADER_NAME` and `PW_HEADER_VALUE`: one extra HTTP header. +- `PW_EXTRA_HEADERS`: JSON object of extra HTTP headers. +- `PW_SCRIPT_DIR`: directory for preserving file-based scripts. +- `PW_ARTIFACT_DIR`: directory for helper-generated screenshots. -- Each automation is custom-written for your specific request -- Not limited to pre-built scripts - any browser task possible -- Auto-detects running dev servers to eliminate hardcoded URLs -- Test scripts written to `/tmp` for automatic cleanup (no clutter) -- Code executes reliably with proper module resolution via `run.js` -- Progressive disclosure - API_REFERENCE.md loaded only when advanced features needed +See [API_REFERENCE.md](API_REFERENCE.md) for network interception, API mocking, +authentication state, video, visual checks, device emulation, and CI patterns. diff --git a/skills/playwright-skill/lib/helpers.js b/skills/playwright-skill/lib/helpers.js index 0920d68..dadda57 100644 --- a/skills/playwright-skill/lib/helpers.js +++ b/skills/playwright-skill/lib/helpers.js @@ -1,292 +1,71 @@ -// playwright-helpers.js -// Reusable utility functions for Playwright automation - +const http = require('node:http'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); const { chromium, firefox, webkit } = require('playwright'); -/** - * Parse extra HTTP headers from environment variables. - * Supports two formats: - * - PW_HEADER_NAME + PW_HEADER_VALUE: Single header (simple, common case) - * - PW_EXTRA_HEADERS: JSON object for multiple headers (advanced) - * Single header format takes precedence if both are set. - * @returns {Object|null} Headers object or null if none configured - */ function getExtraHeadersFromEnv() { - const headerName = process.env.PW_HEADER_NAME; - const headerValue = process.env.PW_HEADER_VALUE; - - if (headerName && headerValue) { - return { [headerName]: headerValue }; - } + const name = process.env.PW_HEADER_NAME; + const value = process.env.PW_HEADER_VALUE; + if (name && value) return { [name]: value }; - const headersJson = process.env.PW_EXTRA_HEADERS; - if (headersJson) { - try { - const parsed = JSON.parse(headersJson); - if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { - return parsed; - } - console.warn('PW_EXTRA_HEADERS must be a JSON object, ignoring...'); - } catch (e) { - console.warn('Failed to parse PW_EXTRA_HEADERS as JSON:', e.message); - } + if (!process.env.PW_EXTRA_HEADERS) return null; + try { + const headers = JSON.parse(process.env.PW_EXTRA_HEADERS); + if (headers && typeof headers === 'object' && !Array.isArray(headers)) return headers; + console.warn('PW_EXTRA_HEADERS must be a JSON object; ignoring it.'); + } catch (error) { + console.warn(`Failed to parse PW_EXTRA_HEADERS: ${error.message}`); } - return null; } -/** - * Launch browser with standard configuration - * @param {string} browserType - 'chromium', 'firefox', or 'webkit' - * @param {Object} options - Additional launch options - */ -async function launchBrowser(browserType = 'chromium', options = {}) { - const defaultOptions = { - headless: process.env.HEADLESS !== 'false', - slowMo: process.env.SLOW_MO ? parseInt(process.env.SLOW_MO) : 0, - args: ['--no-sandbox', '--disable-setuid-sandbox'] +async function launchBrowser(browserType = process.env.PW_BROWSER || 'chromium', options = {}) { + const browser = { chromium, firefox, webkit }[browserType]; + if (!browser) throw new Error(`Invalid browser type: ${browserType}`); + + const headlessValue = process.env.PW_HEADLESS || process.env.HEADLESS || 'false'; + // ponytail: Chromium refuses to start as root without --no-sandbox; only add it there + const needsNoSandbox = browserType === 'chromium' && process.getuid?.() === 0; + const launchOptions = { + headless: headlessValue !== 'false', + slowMo: Number(process.env.SLOW_MO) || 0, + ...(process.env.PW_CHANNEL && { channel: process.env.PW_CHANNEL }), + ...(process.env.PW_EXECUTABLE_PATH && { executablePath: process.env.PW_EXECUTABLE_PATH }), + ...options, + ...(needsNoSandbox && { args: ['--no-sandbox', ...(options.args ?? [])] }), }; - - const browsers = { chromium, firefox, webkit }; - const browser = browsers[browserType]; - - if (!browser) { - throw new Error(`Invalid browser type: ${browserType}`); - } - - return await browser.launch({ ...defaultOptions, ...options }); -} - -/** - * Create a new page with viewport and user agent - * @param {Object} context - Browser context - * @param {Object} options - Page options - */ -async function createPage(context, options = {}) { - const page = await context.newPage(); - - if (options.viewport) { - await page.setViewportSize(options.viewport); - } - - if (options.userAgent) { - await page.setExtraHTTPHeaders({ - 'User-Agent': options.userAgent - }); - } - - // Set default timeout - page.setDefaultTimeout(options.timeout || 30000); - - return page; + return browser.launch(launchOptions); } -/** - * Smart wait for page to be ready - * @param {Object} page - Playwright page - * @param {Object} options - Wait options - */ -async function waitForPageReady(page, options = {}) { - const waitOptions = { - waitUntil: options.waitUntil || 'networkidle', - timeout: options.timeout || 30000 +async function createContext(browser, options = {}) { + const headers = { ...getExtraHeadersFromEnv(), ...options.extraHTTPHeaders }; + const contextOptions = { + viewport: { width: 1280, height: 720 }, + locale: 'en-US', + timezoneId: 'America/New_York', + ...options, + ...(Object.keys(headers).length > 0 && { extraHTTPHeaders: headers }), }; - - try { - await page.waitForLoadState(waitOptions.waitUntil, { - timeout: waitOptions.timeout - }); - } catch (e) { - console.warn('Page load timeout, continuing...'); - } - - // Additional wait for dynamic content if selector provided - if (options.waitForSelector) { - await page.waitForSelector(options.waitForSelector, { - timeout: options.timeout - }); - } + delete contextOptions.mobile; + return browser.newContext(contextOptions); } -/** - * Safe click with retry logic - * @param {Object} page - Playwright page - * @param {string} selector - Element selector - * @param {Object} options - Click options - */ -async function safeClick(page, selector, options = {}) { - const maxRetries = options.retries || 3; - const retryDelay = options.retryDelay || 1000; - - for (let i = 0; i < maxRetries; i++) { - try { - await page.waitForSelector(selector, { - state: 'visible', - timeout: options.timeout || 5000 - }); - await page.click(selector, { - force: options.force || false, - timeout: options.timeout || 5000 - }); - return true; - } catch (e) { - if (i === maxRetries - 1) { - console.error(`Failed to click ${selector} after ${maxRetries} attempts`); - throw e; - } - console.log(`Retry ${i + 1}/${maxRetries} for clicking ${selector}`); - await page.waitForTimeout(retryDelay); - } - } -} - -/** - * Safe text input with clear before type - * @param {Object} page - Playwright page - * @param {string} selector - Input selector - * @param {string} text - Text to type - * @param {Object} options - Type options - */ -async function safeType(page, selector, text, options = {}) { - await page.waitForSelector(selector, { - state: 'visible', - timeout: options.timeout || 10000 - }); - - if (options.clear !== false) { - await page.fill(selector, ''); - } - - if (options.slow) { - await page.type(selector, text, { delay: options.delay || 100 }); - } else { - await page.fill(selector, text); - } -} - -/** - * Extract text from multiple elements - * @param {Object} page - Playwright page - * @param {string} selector - Elements selector - */ -async function extractTexts(page, selector) { - await page.waitForSelector(selector, { timeout: 10000 }); - return await page.$$eval(selector, elements => - elements.map(el => el.textContent?.trim()).filter(Boolean) - ); -} - -/** - * Take screenshot with timestamp - * @param {Object} page - Playwright page - * @param {string} name - Screenshot name - * @param {Object} options - Screenshot options - */ async function takeScreenshot(page, name, options = {}) { - const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); - const filename = `${name}-${timestamp}.png`; - - await page.screenshot({ - path: filename, - fullPage: options.fullPage !== false, - ...options - }); - + const { directory, path: customPath, ...screenshotOptions } = options; + let filename = customPath; + if (!filename) { + const outputDirectory = directory || process.env.PW_ARTIFACT_DIR || os.tmpdir(); + fs.mkdirSync(outputDirectory, { recursive: true }); + filename = path.join(outputDirectory, `${name}-${new Date().toISOString().replace(/[:.]/g, '-')}.png`); + } + await page.screenshot({ path: filename, fullPage: screenshotOptions.fullPage !== false, ...screenshotOptions }); console.log(`Screenshot saved: ${filename}`); return filename; } -/** - * Handle authentication - * @param {Object} page - Playwright page - * @param {Object} credentials - Username and password - * @param {Object} selectors - Login form selectors - */ -async function authenticate(page, credentials, selectors = {}) { - const defaultSelectors = { - username: 'input[name="username"], input[name="email"], #username, #email', - password: 'input[name="password"], #password', - submit: 'button[type="submit"], input[type="submit"], button:has-text("Login"), button:has-text("Sign in")' - }; - - const finalSelectors = { ...defaultSelectors, ...selectors }; - - await safeType(page, finalSelectors.username, credentials.username); - await safeType(page, finalSelectors.password, credentials.password); - await safeClick(page, finalSelectors.submit); - - // Wait for navigation or success indicator - await Promise.race([ - page.waitForNavigation({ waitUntil: 'networkidle' }), - page.waitForSelector(selectors.successIndicator || '.dashboard, .user-menu, .logout', { timeout: 10000 }) - ]).catch(() => { - console.log('Login might have completed without navigation'); - }); -} - -/** - * Scroll page - * @param {Object} page - Playwright page - * @param {string} direction - 'down', 'up', 'top', 'bottom' - * @param {number} distance - Pixels to scroll (for up/down) - */ -async function scrollPage(page, direction = 'down', distance = 500) { - switch (direction) { - case 'down': - await page.evaluate(d => window.scrollBy(0, d), distance); - break; - case 'up': - await page.evaluate(d => window.scrollBy(0, -d), distance); - break; - case 'top': - await page.evaluate(() => window.scrollTo(0, 0)); - break; - case 'bottom': - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - break; - } - await page.waitForTimeout(500); // Wait for scroll animation -} - -/** - * Extract table data - * @param {Object} page - Playwright page - * @param {string} tableSelector - Table selector - */ -async function extractTableData(page, tableSelector) { - await page.waitForSelector(tableSelector); - - return await page.evaluate((selector) => { - const table = document.querySelector(selector); - if (!table) return null; - - const headers = Array.from(table.querySelectorAll('thead th')).map(th => - th.textContent?.trim() - ); - - const rows = Array.from(table.querySelectorAll('tbody tr')).map(tr => { - const cells = Array.from(tr.querySelectorAll('td')); - if (headers.length > 0) { - return cells.reduce((obj, cell, index) => { - obj[headers[index] || `column_${index}`] = cell.textContent?.trim(); - return obj; - }, {}); - } else { - return cells.map(cell => cell.textContent?.trim()); - } - }); - - return { headers, rows }; - }, tableSelector); -} - -/** - * Wait for and dismiss cookie banners - * @param {Object} page - Playwright page - * @param {number} timeout - Max time to wait - */ async function handleCookieBanner(page, timeout = 3000) { - const commonSelectors = [ + const selectors = [ 'button:has-text("Accept")', 'button:has-text("Accept all")', 'button:has-text("OK")', @@ -294,148 +73,43 @@ async function handleCookieBanner(page, timeout = 3000) { 'button:has-text("I agree")', '.cookie-accept', '#cookie-accept', - '[data-testid="cookie-accept"]' + '[data-testid="cookie-accept"]', ]; - - for (const selector of commonSelectors) { + for (const selector of selectors) { try { - const element = await page.waitForSelector(selector, { - timeout: timeout / commonSelectors.length, - state: 'visible' - }); - if (element) { - await element.click(); - console.log('Cookie banner dismissed'); - return true; - } - } catch (e) { - // Continue to next selector + await page.locator(selector).filter({ visible: true }).first().click({ timeout: timeout / selectors.length }); + console.log('Cookie banner dismissed'); + return true; + } catch { + // Try the next common selector. } } - return false; } -/** - * Retry a function with exponential backoff - * @param {Function} fn - Function to retry - * @param {number} maxRetries - Maximum retry attempts - * @param {number} initialDelay - Initial delay in ms - */ -async function retryWithBackoff(fn, maxRetries = 3, initialDelay = 1000) { - let lastError; - - for (let i = 0; i < maxRetries; i++) { - try { - return await fn(); - } catch (error) { - lastError = error; - const delay = initialDelay * Math.pow(2, i); - console.log(`Attempt ${i + 1} failed, retrying in ${delay}ms...`); - await new Promise(resolve => setTimeout(resolve, delay)); - } - } - - throw lastError; -} - -/** - * Create browser context with common settings - * @param {Object} browser - Browser instance - * @param {Object} options - Context options - */ -async function createContext(browser, options = {}) { - const envHeaders = getExtraHeadersFromEnv(); - - // Merge environment headers with any passed in options - const mergedHeaders = { - ...envHeaders, - ...options.extraHTTPHeaders - }; - - const defaultOptions = { - viewport: { width: 1280, height: 720 }, - userAgent: options.mobile - ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1' - : undefined, - permissions: options.permissions || [], - geolocation: options.geolocation, - locale: options.locale || 'en-US', - timezoneId: options.timezoneId || 'America/New_York', - // Only include extraHTTPHeaders if we have any - ...(Object.keys(mergedHeaders).length > 0 && { extraHTTPHeaders: mergedHeaders }) - }; - - return await browser.newContext({ ...defaultOptions, ...options }); -} - -/** - * Detect running dev servers on common ports - * @param {Array} customPorts - Additional ports to check - * @returns {Promise} Array of detected server URLs - */ async function detectDevServers(customPorts = []) { - const http = require('http'); - - // Common dev server ports - const commonPorts = [3000, 3001, 3002, 5173, 8080, 8000, 4200, 5000, 9000, 1234]; - const allPorts = [...new Set([...commonPorts, ...customPorts])]; - - const detectedServers = []; - - console.log('🔍 Checking for running dev servers...'); - - for (const port of allPorts) { - try { - await new Promise((resolve, reject) => { - const req = http.request({ - hostname: 'localhost', - port: port, - path: '/', - method: 'HEAD', - timeout: 500 - }, (res) => { - if (res.statusCode < 500) { - detectedServers.push(`http://localhost:${port}`); - console.log(` ✅ Found server on port ${port}`); - } - resolve(); - }); - - req.on('error', () => resolve()); - req.on('timeout', () => { - req.destroy(); - resolve(); - }); - - req.end(); + const ports = [...new Set([3000, 3001, 3002, 5173, 8080, 8000, 4200, 5000, 9000, 1234, ...customPorts])]; + const servers = []; + await Promise.all(ports.map(async port => { + await new Promise(resolve => { + const request = http.request({ hostname: 'localhost', port, path: '/', method: 'HEAD', timeout: 500 }, response => { + if (response.statusCode < 500) servers.push(port); + response.resume(); + resolve(); }); - } catch (e) { - // Port not available, continue - } - } - - if (detectedServers.length === 0) { - console.log(' ❌ No dev servers detected'); - } - - return detectedServers; + request.on('error', resolve); + request.on('timeout', () => { request.destroy(); resolve(); }); + request.end(); + }); + })); + return servers.sort((a, b) => a - b).map(port => `http://localhost:${port}`); } module.exports = { - launchBrowser, - createPage, - waitForPageReady, - safeClick, - safeType, - extractTexts, - takeScreenshot, - authenticate, - scrollPage, - extractTableData, - handleCookieBanner, - retryWithBackoff, createContext, detectDevServers, - getExtraHeadersFromEnv + getExtraHeadersFromEnv, + handleCookieBanner, + launchBrowser, + takeScreenshot, }; diff --git a/skills/playwright-skill/package-lock.json b/skills/playwright-skill/package-lock.json new file mode 100644 index 0000000..394a373 --- /dev/null +++ b/skills/playwright-skill/package-lock.json @@ -0,0 +1,63 @@ +{ + "name": "playwright-skill", + "version": "5.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "playwright-skill", + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "playwright": "^1.62.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", + "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.62.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", + "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/skills/playwright-skill/package.json b/skills/playwright-skill/package.json index ada6c8b..ca53ade 100644 --- a/skills/playwright-skill/package.json +++ b/skills/playwright-skill/package.json @@ -1,10 +1,11 @@ { "name": "playwright-skill", - "version": "4.1.0", - "description": "General-purpose browser automation with Playwright for Claude Code with auto-detection and smart test management", + "version": "5.0.0", + "description": "General-purpose Playwright browser automation for coding agents with dev-server detection and reusable scripts", "author": "lackeyjb", "main": "run.js", "scripts": { + "test": "node --test ../../tests/*.test.js", "setup": "npm install && npx playwright install chromium", "install-all-browsers": "npx playwright install chromium firefox webkit" }, @@ -17,10 +18,10 @@ "general-purpose" ], "dependencies": { - "playwright": "^1.57.0" + "playwright": "^1.62.0" }, "engines": { - "node": ">=14.0.0" + "node": ">=20.0.0" }, "license": "MIT" } diff --git a/skills/playwright-skill/run.js b/skills/playwright-skill/run.js index 10f2616..55ef973 100755 --- a/skills/playwright-skill/run.js +++ b/skills/playwright-skill/run.js @@ -1,228 +1,96 @@ #!/usr/bin/env node -/** - * Universal Playwright Executor for Claude Code - * - * Executes Playwright automation code from: - * - File path: node run.js script.js - * - Inline code: node run.js 'await page.goto("...")' - * - Stdin: cat script.js | node run.js - * - * Ensures proper module resolution by running from skill directory. - */ -const fs = require('fs'); -const path = require('path'); -const { execSync } = require('child_process'); +const fs = require('node:fs'); +const path = require('node:path'); +const { spawn } = require('node:child_process'); -// Change to skill directory for proper module resolution -process.chdir(__dirname); +const skillDir = __dirname; +const nodeModules = path.join(skillDir, 'node_modules'); -/** - * Check if Playwright is installed - */ -function checkPlaywrightInstalled() { +function ensurePlaywright() { try { - require.resolve('playwright'); - return true; - } catch (e) { - return false; - } -} - -/** - * Install Playwright if missing - */ -function installPlaywright() { - console.log('📦 Playwright not found. Installing...'); - try { - execSync('npm install', { stdio: 'inherit', cwd: __dirname }); - execSync('npx playwright install chromium', { stdio: 'inherit', cwd: __dirname }); - console.log('✅ Playwright installed successfully'); - return true; - } catch (e) { - console.error('❌ Failed to install Playwright:', e.message); - console.error('Please run manually: cd', __dirname, '&& npm run setup'); - return false; - } -} - -/** - * Get code to execute from various sources - */ -function getCodeToExecute() { - const args = process.argv.slice(2); - - // Case 1: File path provided - if (args.length > 0 && fs.existsSync(args[0])) { - const filePath = path.resolve(args[0]); - console.log(`📄 Executing file: ${filePath}`); - return fs.readFileSync(filePath, 'utf8'); - } - - // Case 2: Inline code provided as argument - if (args.length > 0) { - console.log('⚡ Executing inline code'); - return args.join(' '); - } - - // Case 3: Code from stdin - if (!process.stdin.isTTY) { - console.log('📥 Reading from stdin'); - return fs.readFileSync(0, 'utf8'); + require.resolve('playwright', { paths: [skillDir] }); + } catch { + console.error('Playwright is not installed. Run `npm run setup` in the skill directory.'); + process.exit(1); } - - // No input - console.error('❌ No code to execute'); - console.error('Usage:'); - console.error(' node run.js script.js # Execute file'); - console.error(' node run.js "code here" # Execute inline'); - console.error(' cat script.js | node run.js # Execute from stdin'); - process.exit(1); } -/** - * Clean up old temporary execution files from previous runs - */ -function cleanupOldTempFiles() { - try { - const files = fs.readdirSync(__dirname); - const tempFiles = files.filter(f => f.startsWith('.temp-execution-') && f.endsWith('.js')); - - if (tempFiles.length > 0) { - tempFiles.forEach(file => { - const filePath = path.join(__dirname, file); - try { - fs.unlinkSync(filePath); - } catch (e) { - // Ignore errors - file might be in use or already deleted - } - }); - } - } catch (e) { - // Ignore directory read errors +function saveScript(file) { + const directory = process.env.PW_SCRIPT_DIR; + if (!directory || !file) return; + + const targetDir = path.resolve(directory); + fs.mkdirSync(targetDir, { recursive: true }); + const name = path.basename(file); + let target = path.join(targetDir, name); + if (fs.existsSync(target)) { + const extension = path.extname(name); + const stem = path.basename(name, extension); + target = path.join(targetDir, `${stem}-${Date.now()}${extension}`); } + fs.copyFileSync(file, target); + console.log(`Script saved to: ${target}`); } -/** - * Wrap code in async IIFE if not already wrapped - */ -function wrapCodeIfNeeded(code) { - // Check if code already has require() and async structure - const hasRequire = code.includes('require('); - const hasAsyncIIFE = code.includes('(async () => {') || code.includes('(async()=>{'); - - // If it's already a complete script, return as-is - if (hasRequire && hasAsyncIIFE) { - return code; - } - - // If it's just Playwright commands, wrap in full template - if (!hasRequire) { - return ` -const { chromium, firefox, webkit, devices } = require('playwright'); -const helpers = require('./lib/helpers'); - -// Extra headers from environment variables (if configured) -const __extraHeaders = helpers.getExtraHeadersFromEnv(); - -/** - * Utility to merge environment headers into context options. - * Use when creating contexts with raw Playwright API instead of helpers.createContext(). - * @param {Object} options - Context options - * @returns {Object} Options with extraHTTPHeaders merged in - */ -function getContextOptionsWithHeaders(options = {}) { - if (!__extraHeaders) return options; - return { - ...options, - extraHTTPHeaders: { - ...__extraHeaders, - ...(options.extraHTTPHeaders || {}) - } - }; -} - -(async () => { - try { - ${code} - } catch (error) { - console.error('❌ Automation error:', error.message); - if (error.stack) { - console.error(error.stack); - } +function run(args) { + const child = spawn(process.execPath, args, { + // ponytail: keep the caller's cwd so relative paths in scripts and in + // PW_ARTIFACT_DIR resolve against the user's project, not the skill install. + cwd: process.cwd(), + env: { ...process.env, NODE_PATH: nodeModules, PW_SKILL_DIR: skillDir }, + stdio: 'inherit', + }); + const handlers = new Map(); + child.on('exit', (code, signal) => { + if (!signal) process.exit(code ?? 1); + // Re-raise so callers and shells see an interrupt rather than a plain failure. + for (const [name, handler] of handlers) process.off(name, handler); + process.kill(process.pid, signal); + }); + child.on('error', error => { + console.error(`Failed to start Node.js: ${error.message}`); process.exit(1); + }); + for (const signal of ['SIGINT', 'SIGTERM']) { + const handler = () => { + child.kill(signal); + // ponytail: child traps or ignores the signal? escalate so the parent cannot hang + setTimeout(() => child.kill('SIGKILL'), 2000).unref(); + }; + handlers.set(signal, handler); + process.on(signal, handler); } -})(); -`; - } - - // If has require but no async wrapper - if (!hasAsyncIIFE) { - return ` -(async () => { - try { - ${code} - } catch (error) { - console.error('❌ Automation error:', error.message); - if (error.stack) { - console.error(error.stack); - } - process.exit(1); - } -})(); -`; - } - - return code; } -/** - * Main execution - */ -async function main() { - console.log('🎭 Playwright Skill - Universal Executor\n'); +ensurePlaywright(); - // Clean up old temp files from previous runs - cleanupOldTempFiles(); - - // Check Playwright installation - if (!checkPlaywrightInstalled()) { - const installed = installPlaywright(); - if (!installed) { - process.exit(1); - } +const args = process.argv.slice(2); +if (args[0] === '-e' || args[0] === '--eval') { + const source = args.slice(1).join(' '); + if (!source) { + console.error('Usage: node run.js -e "await page.goto(\'https://example.com\')"'); + process.exit(1); } - - // Get code to execute - const rawCode = getCodeToExecute(); - const code = wrapCodeIfNeeded(rawCode); - - // Create temporary file for execution - const tempFile = path.join(__dirname, `.temp-execution-${Date.now()}.js`); - - try { - // Write code to temp file - fs.writeFileSync(tempFile, code, 'utf8'); - - // Execute the code - console.log('🚀 Starting automation...\n'); - require(tempFile); - - // Note: Temp file will be cleaned up on next run - // This allows long-running async operations to complete safely - - } catch (error) { - console.error('❌ Execution failed:', error.message); - if (error.stack) { - console.error('\n📋 Stack trace:'); - console.error(error.stack); - } + const helpersPath = JSON.stringify(path.join(skillDir, 'lib/helpers')); + const prefix = `const { chromium, firefox, webkit, devices } = require('playwright');\nconst helpers = require(${helpersPath});\n`; + // ponytail: exit once the snippet settles so a snippet that leaves the browser open + // cannot hang; the empty writes flush queued output first (pipe writes are async). + const exit = "async () => { for (const s of [process.stdout, process.stderr]) await new Promise(r => s.write('', r)); process.exit(process.exitCode ?? 0); }"; + run(['-e', `${prefix}\n(async () => {\n try {\n ${source}\n } catch (error) {\n console.error(error.stack || error.message);\n process.exitCode = 1;\n }\n})().finally(${exit});`]); +} else if (args[0]) { + const file = path.resolve(args[0]); + if (!fs.existsSync(file)) { + console.error(`Script not found: ${file}`); process.exit(1); } -} - -// Run main function -main().catch(error => { - console.error('❌ Fatal error:', error.message); + saveScript(file); + run([file, ...args.slice(1)]); +} else if (!process.stdin.isTTY) { + console.error('Stdin execution is no longer supported. Use a script file or `-e`.'); process.exit(1); -}); +} else { + console.error('Usage: node run.js [args...]'); + console.error(' or: node run.js -e "await page.goto(\'https://example.com\')"'); + process.exit(1); +} diff --git a/tests/executor.test.js b/tests/executor.test.js new file mode 100644 index 0000000..5f34b6d --- /dev/null +++ b/tests/executor.test.js @@ -0,0 +1,109 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const skillDir = path.resolve(__dirname, '../skills/playwright-skill'); + +test('file scripts can load skill helpers', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'playwright-skill-')); + const script = path.join(directory, 'helper-check.js'); + fs.writeFileSync(script, "const helpers = require(`${process.env.PW_SKILL_DIR}/lib/helpers`); console.log(typeof helpers.detectDevServers);"); + + const result = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), script], { + cwd: skillDir, + encoding: 'utf8', + }); + + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /function/); + fs.rmSync(directory, { recursive: true, force: true }); +}); + +test('throwing scripts propagate a non-zero exit code', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'playwright-skill-')); + const script = path.join(directory, 'throw-check.js'); + fs.writeFileSync(script, "throw new Error('boom');"); + + const result = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), script], { encoding: 'utf8' }); + + assert.notEqual(result.status, 0); + assert.match(result.stderr, /boom/); + fs.rmSync(directory, { recursive: true, force: true }); +}); + +test('missing scripts fail with a non-zero exit code', () => { + const result = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), '/nonexistent/missing.js'], { encoding: 'utf8' }); + + assert.notEqual(result.status, 0); + assert.match(result.stderr, /Script not found/); +}); + +test('inline execution exits even when handles stay open', () => { + const result = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), '-e', "setInterval(() => {}, 1000); console.log('inline-ok');"], { + encoding: 'utf8', + timeout: 15000, + }); + + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /inline-ok/); +}); + +test('inline execution flushes output larger than the pipe buffer', () => { + const size = 200000; + const result = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), '-e', `console.log('x'.repeat(${size}));`], { + encoding: 'utf8', + timeout: 15000, + maxBuffer: 10 * 1024 * 1024, + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.length, size + 1); +}); + +test('inline execution flushes stderr larger than the pipe buffer', () => { + const size = 200000; + const result = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), '-e', `console.error('y'.repeat(${size}));`], { + encoding: 'utf8', + timeout: 15000, + maxBuffer: 10 * 1024 * 1024, + }); + + assert.equal(result.status, 0); + assert.equal(result.stderr.length, size + 1); +}); + +test('scripts keep the caller working directory', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'playwright-skill-')); + const script = path.join(directory, 'cwd-check.js'); + fs.writeFileSync(script, 'console.log(process.cwd());'); + + const result = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), script], { + cwd: directory, + encoding: 'utf8', + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), fs.realpathSync(directory)); + fs.rmSync(directory, { recursive: true, force: true }); +}); + +test('PW_SCRIPT_DIR preserves scripts and avoids collisions', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'playwright-skill-')); + const saveDir = path.join(directory, 'saved'); + const script = path.join(directory, 'save-me.js'); + fs.writeFileSync(script, "console.log('saved');"); + + const runArgs = { encoding: 'utf8', env: { ...process.env, PW_SCRIPT_DIR: saveDir } }; + const first = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), script], runArgs); + const second = spawnSync(process.execPath, [path.join(skillDir, 'run.js'), script], runArgs); + + assert.equal(first.status, 0, first.stderr); + assert.equal(second.status, 0, second.stderr); + const saved = fs.readdirSync(saveDir); + assert.ok(saved.includes('save-me.js'), saved.join(', ')); + assert.equal(saved.filter(name => name.startsWith('save-me')).length, 2, saved.join(', ')); + fs.rmSync(directory, { recursive: true, force: true }); +}); diff --git a/tests/fixtures/dashboard.html b/tests/fixtures/dashboard.html new file mode 100644 index 0000000..01bebd9 --- /dev/null +++ b/tests/fixtures/dashboard.html @@ -0,0 +1,5 @@ + + + Dashboard fixture +

Dashboard

Signed in successfully.

+ diff --git a/tests/fixtures/login.html b/tests/fixtures/login.html new file mode 100644 index 0000000..93e4419 --- /dev/null +++ b/tests/fixtures/login.html @@ -0,0 +1,32 @@ + + + Login fixture + + +
+

Sign in

+
+ + + + + +
+ +
+ + + diff --git a/tests/helpers.test.js b/tests/helpers.test.js new file mode 100644 index 0000000..e1079f5 --- /dev/null +++ b/tests/helpers.test.js @@ -0,0 +1,81 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const http = require('node:http'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const helpers = require('../skills/playwright-skill/lib/helpers'); + +test('parses a single configured header', () => { + const previous = { + name: process.env.PW_HEADER_NAME, + value: process.env.PW_HEADER_VALUE, + extra: process.env.PW_EXTRA_HEADERS, + }; + + process.env.PW_HEADER_NAME = 'X-Test'; + process.env.PW_HEADER_VALUE = 'true'; + delete process.env.PW_EXTRA_HEADERS; + + assert.deepEqual(helpers.getExtraHeadersFromEnv(), { 'X-Test': 'true' }); + + restoreEnv(previous); +}); + +test('parses multiple configured headers', () => { + const previous = { + name: process.env.PW_HEADER_NAME, + value: process.env.PW_HEADER_VALUE, + extra: process.env.PW_EXTRA_HEADERS, + }; + + delete process.env.PW_HEADER_NAME; + delete process.env.PW_HEADER_VALUE; + process.env.PW_EXTRA_HEADERS = JSON.stringify({ 'X-One': '1', 'X-Two': '2' }); + + assert.deepEqual(helpers.getExtraHeadersFromEnv(), { 'X-One': '1', 'X-Two': '2' }); + + restoreEnv(previous); +}); + +test('detects a running HTTP server on a custom port', async () => { + const server = http.createServer((request, response) => { + response.writeHead(200); + response.end(); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + + try { + const servers = await helpers.detectDevServers([port]); + assert.ok(servers.includes(`http://localhost:${port}`)); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +test('creates a configured screenshot directory', async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'playwright-skill-')); + const previous = process.env.PW_ARTIFACT_DIR; + process.env.PW_ARTIFACT_DIR = path.join(directory, 'artifacts'); + + const page = { screenshot: async options => fs.writeFileSync(options.path, 'test') }; + const filename = await helpers.takeScreenshot(page, 'result'); + + assert.equal(fs.existsSync(filename), true); + if (previous === undefined) delete process.env.PW_ARTIFACT_DIR; + else process.env.PW_ARTIFACT_DIR = previous; + fs.rmSync(directory, { recursive: true, force: true }); +}); + +function restoreEnv(previous) { + setOrDelete('PW_HEADER_NAME', previous.name); + setOrDelete('PW_HEADER_VALUE', previous.value); + setOrDelete('PW_EXTRA_HEADERS', previous.extra); +} + +function setOrDelete(name, value) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; +} diff --git a/tests/smoke.js b/tests/smoke.js new file mode 100644 index 0000000..3d30195 --- /dev/null +++ b/tests/smoke.js @@ -0,0 +1,25 @@ +const path = require('node:path'); +const assert = require('node:assert/strict'); + +const skillDir = process.env.PW_SKILL_DIR || path.resolve(__dirname, '../skills/playwright-skill'); +const { chromium } = require(path.join(skillDir, 'node_modules/playwright')); +const helpers = require(path.join(skillDir, 'lib/helpers')); + +const loginUrl = `file://${path.resolve(__dirname, 'fixtures/login.html')}`; + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + + try { + await page.goto(loginUrl); + assert.equal(await helpers.handleCookieBanner(page), true, 'cookie banner should be dismissed'); + await page.getByLabel('Email').fill('test@example.com'); + await page.getByLabel('Password').fill('password'); + await page.getByRole('button', { name: 'Sign in' }).click(); + await page.waitForURL('**/dashboard.html'); + await page.getByRole('heading', { name: 'Dashboard' }).waitFor(); + } finally { + await browser.close(); + } +})();