Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

46.7 KB
Raw Blame
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as z from 'zod';
import { declareCommand } from './command';

import type { AnyCommandSchema } from './command';

const elementTargetDescription = 'Exact target element reference from the page snapshot, or a unique element selector';

const numberArg = z.preprocess((val, ctx) => {
  const number = Number(val);
  if (Number.isNaN(number)) {
    ctx.issues.push({
      code: 'custom',
      message: `expected number, received '${val}'`,
      input: val,
    });
  }
  return number;
}, z.number());

// Minimist returns a string for a single occurrence and an array for repeated.
const stringArrayArg = z.union([z.string(), z.array(z.string())]).transform(v => Array.isArray(v) ? v : [v]);

// Navigation commands

const open = declareCommand({
  name: 'open',
  description: 'Open the browser',
  category: 'core',
  args: z.object({
    url: z.string().optional().describe('The URL to navigate to'),
  }),
  options: z.object({
    browser: z.string().optional().describe('Browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.'),
    config: z.string().optional().describe('Path to the configuration file, defaults to .playwright/cli.config.json'),
    device: z.string().optional().describe('Emulate a specific device, for example "iPhone 15".'),
    headed: z.boolean().optional().describe('Run browser in headed mode'),
    ['idle-timeout']: numberArg.optional().describe('Shut the session down after this many milliseconds without a command. Defaults to one hour for headless browsers, never for headed ones. Pass 0 to disable.'),
    mobile: z.boolean().optional().describe('Emulate a generic mobile device (Pixel 10 for Chromium, iPhone 17 for WebKit). Mobile pages are usually lighter, which saves tokens.'),
    persistent: z.boolean().optional().describe('Use persistent browser profile'),
    profile: z.string().optional().describe('Path to a persistent user data directory.'),
  }),
  toolName: '',
  toolParams: () => ({}),
});

const attach = declareCommand({
  name: 'attach',
  description: 'Attach to a running Playwright browser',
  category: 'core',
  args: z.object({
    name: z.string().optional().describe('Bound browser name to attach to'),
  }),
  options: z.object({
    cdp: z.string().optional().describe('Connect to an existing browser via CDP endpoint URL.'),
    endpoint: z.string().optional().describe('Playwright browser server endpoint to attach to.'),
    extension: z.union([z.boolean(), z.string()]).optional().describe('Connect to browser extension, optionally specify browser name (e.g. --extension=chrome)'),
    config: z.string().optional().describe('Path to the configuration file, defaults to .playwright/cli.config.json'),
    session: z.string().optional().describe('Session name (defaults to bound browser name or "default")'),
    ['idle-timeout']: numberArg.optional().describe('Detach after this many milliseconds without a command. Attached browsers are never detached by default.'),
  }),
  toolName: 'browser_snapshot',
  toolParams: () => ({ filename: '<auto>' }),
});

const close = declareCommand({
  name: 'close',
  description: 'Close the browser',
  category: 'core',
  args: z.object({}),
  toolName: '',
  toolParams: () => ({}),
});

const detach = declareCommand({
  name: 'detach',
  description: 'Detach from an attached browser',
  category: 'core',
  args: z.object({}),
  toolName: '',
  toolParams: () => ({}),
});

const goto = declareCommand({
  name: 'goto',
  description: 'Navigate to a URL',
  category: 'core',
  args: z.object({
    url: z.string().describe('The URL to navigate to'),
  }),
  toolName: 'browser_navigate',
  toolParams: ({ url }) => ({ url }),
});

const goBack = declareCommand({
  name: 'go-back',
  description: 'Go back to the previous page',
  category: 'navigation',
  args: z.object({}),
  toolName: 'browser_navigate_back',
  toolParams: () => ({}),
});

const goForward = declareCommand({
  name: 'go-forward',
  description: 'Go forward to the next page',
  category: 'navigation',
  args: z.object({}),
  toolName: 'browser_navigate_forward',
  toolParams: () => ({}),
});

const reload = declareCommand({
  name: 'reload',
  description: 'Reload the current page',
  category: 'navigation',
  args: z.object({}),
  toolName: 'browser_reload',
  toolParams: () => ({}),
});

// Keyboard

const pressKey = declareCommand({
  name: 'press',
  description: 'Press a key on the keyboard, `a`, `ArrowLeft`',
  category: 'keyboard',
  args: z.object({
    key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),
  }),
  toolName: 'browser_press_key',
  toolParams: ({ key }) => ({ key }),
});

const type = declareCommand({
  name: 'type',
  description: 'Type text into editable element',
  category: 'core',
  args: z.object({
    text: z.string().describe('Text to type into the element'),
  }),
  options: z.object({
    submit: z.boolean().optional().describe('Whether to submit entered text (press Enter after)'),
  }),
  toolName: 'browser_press_sequentially',
  toolParams: ({ text, submit }) => ({ text, submit }),
});

const keydown = declareCommand({
  name: 'keydown',
  description: 'Press a key down on the keyboard',
  category: 'keyboard',
  args: z.object({
    key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),
  }),
  toolName: 'browser_keydown',
  toolParams: ({ key }) => ({ key }),
});

const keyup = declareCommand({
  name: 'keyup',
  description: 'Press a key up on the keyboard',
  category: 'keyboard',
  args: z.object({
    key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),
  }),
  toolName: 'browser_keyup',
  toolParams: ({ key }) => ({ key }),
});

// Mouse

const mouseMove = declareCommand({
  name: 'mousemove',
  description: 'Move mouse to a given position',
  category: 'mouse',
  args: z.object({
    x: numberArg.describe('X coordinate'),
    y: numberArg.describe('Y coordinate'),
  }),
  toolName: 'browser_mouse_move_xy',
  toolParams: ({ x, y }) => ({ x, y }),
});

const mouseDown = declareCommand({
  name: 'mousedown',
  description: 'Press mouse down',
  category: 'mouse',
  args: z.object({
    button: z.string().optional().describe('Button to press, defaults to left'),
  }),
  toolName: 'browser_mouse_down',
  toolParams: ({ button }) => ({ button }),
});

const mouseUp = declareCommand({
  name: 'mouseup',
  description: 'Press mouse up',
  category: 'mouse',
  args: z.object({
    button: z.string().optional().describe('Button to press, defaults to left'),
  }),
  toolName: 'browser_mouse_up',
  toolParams: ({ button }) => ({ button }),
});

const mouseWheel = declareCommand({
  name: 'mousewheel',
  description: 'Scroll mouse wheel',
  category: 'mouse',
  args: z.object({
    dx: numberArg.describe('X delta'),
    dy: numberArg.describe('Y delta'),
  }),
  toolName: 'browser_mouse_wheel',
  toolParams: ({ dx: deltaX, dy: deltaY }) => ({ deltaX, deltaY }),
});

// Core

const click = declareCommand({
  name: 'click',
  description: 'Perform click on a web page',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
    button: z.string().optional().describe('Button to click, defaults to left'),
  }),
  options: z.object({
    modifiers: stringArrayArg.optional().describe('Modifier key to press (repeatable)'),
  }),
  toolName: 'browser_click',
  toolParams: ({ target, button, modifiers }) => ({ target, button, modifiers }),
});

const doubleClick = declareCommand({
  name: 'dblclick',
  description: 'Perform double click on a web page',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
    button: z.string().optional().describe('Button to click, defaults to left'),
  }),
  options: z.object({
    modifiers: stringArrayArg.optional().describe('Modifier key to press (repeatable)'),
  }),
  toolName: 'browser_click',
  toolParams: ({ target, button, modifiers }) => ({ target, button, modifiers, doubleClick: true }),
});

const drag = declareCommand({
  name: 'drag',
  description: 'Perform drag and drop between two elements',
  category: 'core',
  args: z.object({
    startTarget: z.string().describe('Exact source element reference from the page snapshot, or a unique element selector'),
    endTarget: z.string().describe(elementTargetDescription),
  }),
  toolName: 'browser_drag',
  toolParams: ({ startTarget, endTarget }) => ({ startTarget, endTarget }),
});

const drop = declareCommand({
  name: 'drop',
  description: 'Drop files or data onto an element',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
  }),
  options: z.object({
    path: stringArrayArg.optional().describe('Absolute path to a file to drop onto the element (repeatable)'),
    data: stringArrayArg.optional().describe('Data to drop in "mime/type=value" format, e.g. --data "text/plain=hello" (repeatable)'),
  }),
  toolName: 'browser_drop',
  toolParams: ({ target, path, data }) => {
    let dataMap: Record<string, string> | undefined;
    if (data) {
      dataMap = {};
      for (const entry of data) {
        const idx = entry.indexOf('=');
        if (idx === -1)
          throw new Error(`--data must be in "mime/type=value" format, got: ${entry}`);
        dataMap[entry.slice(0, idx)] = entry.slice(idx + 1);
      }
    }
    return { target, paths: path, data: dataMap };
  },
});

const fill = declareCommand({
  name: 'fill',
  description: 'Fill text into editable element',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
    text: z.string().describe('Text to fill into the element'),
  }),
  options: z.object({
    submit: z.boolean().optional().describe('Whether to submit entered text (press Enter after)'),
  }),
  toolName: 'browser_type',
  toolParams: ({ target, text, submit }) => ({ target, text, submit }),
});

const hover = declareCommand({
  name: 'hover',
  description: 'Hover over element on page',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
  }),
  toolName: 'browser_hover',
  toolParams: ({ target }) => ({ target }),
});

const select = declareCommand({
  name: 'select',
  description: 'Select an option in a dropdown',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
    val: z.string().describe('Value to select in the dropdown'),
  }),
  toolName: 'browser_select_option',
  toolParams: ({ target, val: value }) => ({ target, values: [value] }),
});

const fileUpload = declareCommand({
  name: 'upload',
  description: 'Upload one or multiple files',
  category: 'core',
  args: z.object({
    files: stringArrayArg.describe('The absolute paths to the files to upload'),
  }),
  toolName: 'browser_file_upload',
  toolParams: ({ files }) => ({ paths: files }),
});

const check = declareCommand({
  name: 'check',
  description: 'Check a checkbox or radio button',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
  }),
  toolName: 'browser_check',
  toolParams: ({ target }) => ({ target }),
});

const uncheck = declareCommand({
  name: 'uncheck',
  description: 'Uncheck a checkbox or radio button',
  category: 'core',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
  }),
  toolName: 'browser_uncheck',
  toolParams: ({ target }) => ({ target }),
});

const snapshot = declareCommand({
  name: 'snapshot',
  description: 'Capture page snapshot to obtain element ref',
  category: 'core',
  args: z.object({
    target: z.string().optional().describe('Element reference from the previous page snapshot, or a unique element selector for the root element to capture a partial snapshot instead of the whole page'),
  }),
  options: z.object({
    filename: z.string().optional().describe('Save snapshot to markdown file instead of returning it in the response.'),
    depth: numberArg.optional().describe('Limit snapshot depth, unlimited by default.'),
    boxes: z.boolean().optional().describe('Include each element\'s bounding box as [box=x,y,width,height] in the snapshot. Coordinates are viewport-relative, in CSS pixels (Element.getBoundingClientRect).'),
  }),
  toolName: 'browser_snapshot',
  toolParams: ({ filename, target, depth, boxes }) => ({ filename, target, depth, boxes }),
});

const find = declareCommand({
  name: 'find',
  description: 'Search the page snapshot for text or a regexp, returning matching nodes with surrounding context (like search snippets)',
  category: 'core',
  args: z.object({
    text: z.string().optional().describe('Plain text to search for in the page snapshot (case-insensitive substring match)'),
  }),
  options: z.object({
    regex: z.string().optional().describe('Regular expression to search for in the page snapshot. Provide either a text argument or --regex, not both.'),
    filename: z.string().optional().describe('Save results to a file instead of returning them in the response.'),
    ['max-results']: numberArg.optional().describe('Maximum number of matching items to return, unlimited by default.'),
  }),
  toolName: 'browser_find',
  toolParams: ({ text, regex, filename, ['max-results']: maxResults }) => ({ text, regex, filename, maxResults }),
});

const generateLocator = declareCommand({
  name: 'generate-locator',
  description: 'Generate a Playwright locator for the given element',
  category: 'devtools',
  args: z.object({
    target: z.string().describe(elementTargetDescription),
  }),
  toolName: 'browser_generate_locator',
  toolParams: ({ target }) => ({ target }),
});

const highlight = declareCommand({
  name: 'highlight',
  description: 'Show (or with --hide, remove) a highlight overlay for an element; `--hide` without a target hides all page highlights.',
  category: 'devtools',
  args: z.object({
    target: z.string().optional().describe(elementTargetDescription),
  }),
  options: z.object({
    hide: z.boolean().optional().describe('Hide a previously added highlight for this element, or all page highlights when no element is given'),
    style: z.string().optional().describe('Additional inline CSS applied to the highlight overlay, e.g. "outline: 2px dashed red"'),
  }),
  toolName: ({ hide }) => hide ? 'browser_hide_highlight' : 'browser_highlight',
  toolParams: ({ target, style }) => ({ target, style }),
});

const evaluate = declareCommand({
  name: 'eval',
  description: 'Evaluate JavaScript expression on page or element',
  category: 'core',
  args: z.object({
    func: z.string().describe('() => { /* code */ } or (element) => { /* code */ } when element is provided'),
    target: z.string().optional().describe(elementTargetDescription),
  }),
  options: z.object({
    filename: z.string().optional().describe('Save evaluation result to a file instead of returning it in the response.'),
  }),
  toolName: 'browser_evaluate',
  toolParams: ({ func, target, filename }) => ({ function: func, filename, target }),
});

const dialogAccept = declareCommand({
  name: 'dialog-accept',
  description: 'Accept a dialog',
  category: 'core',
  args: z.object({
    prompt: z.string().optional().describe('The text of the prompt in case of a prompt dialog.'),
  }),
  toolName: 'browser_handle_dialog',
  toolParams: ({ prompt: promptText }) => ({ accept: true, promptText }),
});

const dialogDismiss = declareCommand({
  name: 'dialog-dismiss',
  description: 'Dismiss a dialog',
  category: 'core',
  args: z.object({}),
  toolName: 'browser_handle_dialog',
  toolParams: () => ({ accept: false }),
});

const resize = declareCommand({
  name: 'resize',
  description: 'Resize the browser window',
  category: 'core',
  args: z.object({
    w: numberArg.describe('Width of the browser window'),
    h: numberArg.describe('Height of the browser window'),
  }),
  toolName: 'browser_resize',
  toolParams: ({ w: width, h: height }) => ({ width, height }),
});

const setColorScheme = declareCommand({
  name: 'set-color-scheme',
  description: 'Emulate the light or dark color scheme',
  category: 'emulation',
  args: z.object({
    scheme: z.enum(['light', 'dark']).describe('Color scheme to emulate'),
  }),
  toolName: 'browser_emulate_media',
  toolParams: ({ scheme: colorScheme }) => ({ colorScheme }),
});

const setReducedMotion = declareCommand({
  name: 'set-reduced-motion',
  description: 'Emulate the reduced motion preference',
  category: 'emulation',
  args: z.object({
    motion: z.enum(['reduce', 'no-preference']).describe('Reduced motion preference to emulate'),
  }),
  toolName: 'browser_emulate_media',
  toolParams: ({ motion: reducedMotion }) => ({ reducedMotion }),
});

const setForcedColors = declareCommand({
  name: 'set-forced-colors',
  description: 'Emulate forced colors mode',
  category: 'emulation',
  args: z.object({
    colors: z.enum(['active', 'none']).describe('Forced colors mode to emulate'),
  }),
  toolName: 'browser_emulate_media',
  toolParams: ({ colors: forcedColors }) => ({ forcedColors }),
});

const setContrast = declareCommand({
  name: 'set-contrast',
  description: 'Emulate the preferred contrast',
  category: 'emulation',
  args: z.object({
    contrast: z.enum(['more', 'no-preference']).describe('Contrast preference to emulate'),
  }),
  toolName: 'browser_emulate_media',
  toolParams: ({ contrast }) => ({ contrast }),
});

const setMedia = declareCommand({
  name: 'set-media',
  description: 'Emulate the CSS media type',
  category: 'emulation',
  args: z.object({
    media: z.enum(['screen', 'print']).describe('CSS media type to emulate'),
  }),
  toolName: 'browser_emulate_media',
  toolParams: ({ media }) => ({ media }),
});

const clearColorScheme = declareCommand({
  name: 'clear-color-scheme',
  description: 'Clear color scheme emulation',
  category: 'emulation',
  args: z.object({}),
  toolName: 'browser_emulate_media',
  toolParams: () => ({ colorScheme: null }),
});

const clearReducedMotion = declareCommand({
  name: 'clear-reduced-motion',
  description: 'Clear reduced motion emulation',
  category: 'emulation',
  args: z.object({}),
  toolName: 'browser_emulate_media',
  toolParams: () => ({ reducedMotion: null }),
});

const clearForcedColors = declareCommand({
  name: 'clear-forced-colors',
  description: 'Clear forced colors emulation',
  category: 'emulation',
  args: z.object({}),
  toolName: 'browser_emulate_media',
  toolParams: () => ({ forcedColors: null }),
});

const clearContrast = declareCommand({
  name: 'clear-contrast',
  description: 'Clear preferred contrast emulation',
  category: 'emulation',
  args: z.object({}),
  toolName: 'browser_emulate_media',
  toolParams: () => ({ contrast: null }),
});

const clearMedia = declareCommand({
  name: 'clear-media',
  description: 'Clear CSS media type emulation',
  category: 'emulation',
  args: z.object({}),
  toolName: 'browser_emulate_media',
  toolParams: () => ({ media: null }),
});

const runCode = declareCommand({
  name: 'run-code',
  description: 'Run Playwright code snippet',
  category: 'devtools',
  args: z.object({
    code: z.string().optional().describe('A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction.'),
  }),
  options: z.object({
    filename: z.string().optional().describe('Load code from the specified file.'),
  }),
  toolName: 'browser_run_code_unsafe',
  toolParams: ({ code, filename }) => ({ code, filename }),
});

// Tabs

const tabList = declareCommand({
  name: 'tab-list',
  description: 'List all tabs',
  category: 'tabs',
  args: z.object({}),
  toolName: 'browser_tabs',
  toolParams: () => ({ action: 'list' }),
});

const tabNew = declareCommand({
  name: 'tab-new',
  description: 'Create a new tab',
  category: 'tabs',
  args: z.object({
    url: z.string().optional().describe('The URL to navigate to in the new tab. If omitted, the new tab will be blank.'),
  }),
  options: z.object({
    ['isolated-context']: z.string().optional().describe('Name of an isolated browser context to create the tab in. Tabs in the same isolated context share cookies and storage.'),
  }),
  toolName: 'browser_tabs',
  toolParams: ({ url, ['isolated-context']: isolatedContext }) => ({ action: 'new', url, isolatedContext }),
});

const tabClose = declareCommand({
  name: 'tab-close',
  description: 'Close a browser tab',
  category: 'tabs',
  args: z.object({
    index: numberArg.optional().describe('Tab index. If omitted, current tab is closed.'),
  }),
  toolName: 'browser_tabs',
  toolParams: ({ index }) => ({ action: 'close', index }),
});

const tabSelect = declareCommand({
  name: 'tab-select',
  description: 'Select a browser tab',
  category: 'tabs',
  args: z.object({
    index: numberArg.describe('Tab index'),
  }),
  toolName: 'browser_tabs',
  toolParams: ({ index }) => ({ action: 'select', index }),
});

// Storage

const stateLoad = declareCommand({
  name: 'state-load',
  description: 'Loads browser storage (authentication) state from a file',
  category: 'storage',
  args: z.object({
    filename: z.string().describe('File name to load the storage state from.'),
  }),
  toolName: 'browser_set_storage_state',
  toolParams: ({ filename }) => ({ filename }),
});

const stateSave = declareCommand({
  name: 'state-save',
  description: 'Saves the current storage (authentication) state to a file',
  category: 'storage',
  args: z.object({
    filename: z.string().optional().describe('File name to save the storage state to.'),
  }),
  toolName: 'browser_storage_state',
  toolParams: ({ filename }) => ({ filename }),
});

// Cookies

const cookieList = declareCommand({
  name: 'cookie-list',
  description: 'List all cookies (optionally filtered by domain/path)',
  category: 'storage',
  raw: true,
  args: z.object({}),
  options: z.object({
    domain: z.string().optional().describe('Filter cookies by domain'),
    path: z.string().optional().describe('Filter cookies by path'),
  }),
  toolName: 'browser_cookie_list',
  toolParams: ({ domain, path }) => ({ domain, path }),
});

const cookieGet = declareCommand({
  name: 'cookie-get',
  description: 'Get a specific cookie by name',
  category: 'storage',
  raw: true,
  args: z.object({
    name: z.string().describe('Cookie name'),
  }),
  toolName: 'browser_cookie_get',
  toolParams: ({ name }) => ({ name }),
});

const cookieSet = declareCommand({
  name: 'cookie-set',
  description: 'Set a cookie with optional flags',
  category: 'storage',
  args: z.object({
    name: z.string().describe('Cookie name'),
    value: z.string().describe('Cookie value'),
  }),
  options: z.object({
    domain: z.string().optional().describe('Cookie domain'),
    path: z.string().optional().describe('Cookie path'),
    expires: numberArg.optional().describe('Cookie expiration as Unix timestamp'),
    httpOnly: z.boolean().optional().describe('Whether the cookie is HTTP only'),
    secure: z.boolean().optional().describe('Whether the cookie is secure'),
    sameSite: z.enum(['Strict', 'Lax', 'None']).optional().describe('Cookie SameSite attribute'),
  }),
  toolName: 'browser_cookie_set',
  toolParams: ({ name, value, domain, path, expires, httpOnly, secure, sameSite }) => ({ name, value, domain, path, expires, httpOnly, secure, sameSite }),
});

const cookieDelete = declareCommand({
  name: 'cookie-delete',
  description: 'Delete a specific cookie (optionally only on a given domain/path)',
  category: 'storage',
  args: z.object({
    name: z.string().describe('Cookie name'),
  }),
  options: z.object({
    domain: z.string().optional().describe('Only delete the cookie on this domain'),
    path: z.string().optional().describe('Only delete the cookie on this path'),
  }),
  toolName: 'browser_cookie_delete',
  toolParams: ({ name, domain, path }) => ({ name, domain, path }),
});

const cookieClear = declareCommand({
  name: 'cookie-clear',
  description: 'Clear all cookies',
  category: 'storage',
  args: z.object({}),
  toolName: 'browser_cookie_clear',
  toolParams: () => ({}),
});

// LocalStorage

const localStorageList = declareCommand({
  name: 'localstorage-list',
  description: 'List all localStorage key-value pairs',
  category: 'storage',
  raw: true,
  args: z.object({}),
  toolName: 'browser_localstorage_list',
  toolParams: () => ({}),
});

const localStorageGet = declareCommand({
  name: 'localstorage-get',
  description: 'Get a localStorage item by key',
  category: 'storage',
  raw: true,
  args: z.object({
    key: z.string().describe('Key to get'),
  }),
  toolName: 'browser_localstorage_get',
  toolParams: ({ key }) => ({ key }),
});

const localStorageSet = declareCommand({
  name: 'localstorage-set',
  description: 'Set a localStorage item',
  category: 'storage',
  args: z.object({
    key: z.string().describe('Key to set'),
    value: z.string().describe('Value to set'),
  }),
  toolName: 'browser_localstorage_set',
  toolParams: ({ key, value }) => ({ key, value }),
});

const localStorageDelete = declareCommand({
  name: 'localstorage-delete',
  description: 'Delete a localStorage item',
  category: 'storage',
  args: z.object({
    key: z.string().describe('Key to delete'),
  }),
  toolName: 'browser_localstorage_delete',
  toolParams: ({ key }) => ({ key }),
});

const localStorageClear = declareCommand({
  name: 'localstorage-clear',
  description: 'Clear all localStorage',
  category: 'storage',
  args: z.object({}),
  toolName: 'browser_localstorage_clear',
  toolParams: () => ({}),
});

// SessionStorage

const sessionStorageList = declareCommand({
  name: 'sessionstorage-list',
  description: 'List all sessionStorage key-value pairs',
  category: 'storage',
  raw: true,
  args: z.object({}),
  toolName: 'browser_sessionstorage_list',
  toolParams: () => ({}),
});

const sessionStorageGet = declareCommand({
  name: 'sessionstorage-get',
  description: 'Get a sessionStorage item by key',
  category: 'storage',
  raw: true,
  args: z.object({
    key: z.string().describe('Key to get'),
  }),
  toolName: 'browser_sessionstorage_get',
  toolParams: ({ key }) => ({ key }),
});

const sessionStorageSet = declareCommand({
  name: 'sessionstorage-set',
  description: 'Set a sessionStorage item',
  category: 'storage',
  args: z.object({
    key: z.string().describe('Key to set'),
    value: z.string().describe('Value to set'),
  }),
  toolName: 'browser_sessionstorage_set',
  toolParams: ({ key, value }) => ({ key, value }),
});

const sessionStorageDelete = declareCommand({
  name: 'sessionstorage-delete',
  description: 'Delete a sessionStorage item',
  category: 'storage',
  args: z.object({
    key: z.string().describe('Key to delete'),
  }),
  toolName: 'browser_sessionstorage_delete',
  toolParams: ({ key }) => ({ key }),
});

const sessionStorageClear = declareCommand({
  name: 'sessionstorage-clear',
  description: 'Clear all sessionStorage',
  category: 'storage',
  args: z.object({}),
  toolName: 'browser_sessionstorage_clear',
  toolParams: () => ({}),
});

// Network

const routeMock = declareCommand({
  name: 'route',
  description: 'Mock network requests matching a URL pattern',
  category: 'network',
  args: z.object({
    pattern: z.string().describe('URL pattern to match (e.g., "**/api/users")'),
  }),
  options: z.object({
    status: numberArg.optional().describe('HTTP status code (default: 200)'),
    body: z.string().optional().describe('Response body (text or JSON string)'),
    ['content-type']: z.string().optional().describe('Content-Type header'),
    header: stringArrayArg.optional().describe('Header to add in "Name: Value" format (repeatable)'),
    ['remove-header']: z.string().optional().describe('Comma-separated header names to remove'),
  }),
  toolName: 'browser_route',
  toolParams: ({ pattern, status, body, ['content-type']: contentType, header: headers, ['remove-header']: removeHeaders }) => ({
    pattern,
    status,
    body,
    contentType,
    headers,
    removeHeaders,
  }),
});

const routeList = declareCommand({
  name: 'route-list',
  description: 'List all active network routes',
  category: 'network',
  raw: true,
  args: z.object({}),
  toolName: 'browser_route_list',
  toolParams: () => ({}),
});

const unroute = declareCommand({
  name: 'unroute',
  description: 'Remove routes matching a pattern (or all routes)',
  category: 'network',
  args: z.object({
    pattern: z.string().optional().describe('URL pattern to unroute (omit to remove all)'),
  }),
  toolName: 'browser_unroute',
  toolParams: ({ pattern }) => ({ pattern }),
});

const networkStateSet = declareCommand({
  name: 'network-state-set',
  description: 'Set the browser network state to online or offline',
  category: 'network',
  args: z.object({
    state: z.enum(['online', 'offline']).describe('Set to "offline" to simulate offline mode, "online" to restore network connectivity'),
  }),
  toolName: 'browser_network_state_set',
  toolParams: ({ state }) => ({ state }),
});

// Export

const screenshot = declareCommand({
  name: 'screenshot',
  description: 'screenshot of the current page or element',
  category: 'export',
  args: z.object({
    target: z.string().optional().describe(elementTargetDescription),
  }),
  options: z.object({
    filename: z.string().optional().describe('File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg|webp}` if not specified.'),
    type: z.enum(['png', 'jpeg', 'webp']).optional().describe('Image format. If unset, inferred from the filename extension, otherwise png.'),
    ['full-page']: z.boolean().optional().describe('When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport.'),
    hires: z.boolean().optional().describe('When true, captures a high-resolution screenshot using device pixels (accounts for the device pixel ratio), instead of CSS pixels.'),
  }),
  toolName: 'browser_take_screenshot',
  toolParams: ({ target, filename, type, ['full-page']: fullPage, hires }) => ({ filename, target, type, fullPage, scale: hires ? 'device' : undefined }),
});

const pdfSave = declareCommand({
  name: 'pdf',
  description: 'Save page as PDF',
  category: 'export',
  args: z.object({}),
  options: z.object({
    filename: z.string().optional().describe('File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified.'),
  }),
  toolName: 'browser_pdf_save',
  toolParams: ({ filename }) => ({ filename }),
});

// DevTools

const consoleList = declareCommand({
  name: 'console',
  description: 'List console messages',
  category: 'devtools',
  args: z.object({
    ['min-level']: z.string().optional().describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".'),
  }),
  options: z.object({
    all: z.boolean().optional().describe('Whether to return all console messages since the beginning of the session, not just since the last navigation'),
    clear: z.boolean().optional().describe('Whether to clear the console list'),
  }),
  toolName: ({ clear }) => clear ? 'browser_console_clear' : 'browser_console_messages',
  toolParams: ({ ['min-level']: level, all, clear }) => clear ? ({}) : ({ level, all }),
});

const networkRequests = declareCommand({
  name: 'requests',
  description: 'List all network requests since loading the page. Each request is numbered for use with the `request` command.',
  category: 'network',
  args: z.object({}),
  options: z.object({
    static: z.boolean().optional().describe('Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.'),
    filter: z.string().optional().describe('Only return requests whose URL matches this regexp (e.g. "/api/.*user").'),
    all: z.boolean().optional().describe('Whether to return all network requests since the beginning of the session, not just since the last navigation'),
    clear: z.boolean().optional().describe('Whether to clear the network list'),
  }),
  toolName: ({ clear }) => clear ? 'browser_network_clear' : 'browser_network_requests',
  toolParams: ({ static: s, filter, all, clear }) => clear ? ({}) : ({ static: s, filter, all }),
});

const filenameOption = z.string().optional().describe('Filename to save the result to. If not provided, output is returned as text.');

const networkRequest = declareCommand({
  name: 'request',
  description: 'Show full details (headers, body, response) of a single network request by its number from the `requests` command.',
  category: 'network',
  args: z.object({
    index: numberArg.describe('1-based number of the request as listed by `requests`'),
  }),
  options: z.object({
    filename: filenameOption,
  }),
  toolName: 'browser_network_request',
  toolParams: ({ index, filename }) => ({ index, filename }),
});

const networkRequestHeaders = declareCommand({
  name: 'request-headers',
  description: 'Print only the request headers for a single network request by its number from the `requests` command.',
  category: 'network',
  raw: true,
  args: z.object({
    index: numberArg.describe('1-based number of the request as listed by `requests`'),
  }),
  options: z.object({
    filename: filenameOption,
  }),
  toolName: 'browser_network_request',
  toolParams: ({ index, filename }) => ({ index, part: 'request-headers', filename }),
});

const networkRequestBody = declareCommand({
  name: 'request-body',
  description: 'Print only the request body for a single network request by its number from the `requests` command.',
  category: 'network',
  raw: true,
  args: z.object({
    index: numberArg.describe('1-based number of the request as listed by `requests`'),
  }),
  options: z.object({
    filename: filenameOption,
  }),
  toolName: 'browser_network_request',
  toolParams: ({ index, filename }) => ({ index, part: 'request-body', filename }),
});

const networkResponseHeaders = declareCommand({
  name: 'response-headers',
  description: 'Print only the response headers for a single network request by its number from the `requests` command.',
  category: 'network',
  raw: true,
  args: z.object({
    index: numberArg.describe('1-based number of the request as listed by `requests`'),
  }),
  options: z.object({
    filename: filenameOption,
  }),
  toolName: 'browser_network_request',
  toolParams: ({ index, filename }) => ({ index, part: 'response-headers', filename }),
});

const networkResponseBody = declareCommand({
  name: 'response-body',
  description: 'Print the response body for a single network request by its number from the `requests` command. Textual bodies are inlined; binary bodies are saved to a file and the path is printed.',
  category: 'network',
  raw: true,
  args: z.object({
    index: numberArg.describe('1-based number of the request as listed by `requests`'),
  }),
  options: z.object({
    filename: filenameOption,
  }),
  toolName: 'browser_network_request',
  toolParams: ({ index, filename }) => ({ index, part: 'response-body', filename }),
});

const recordingStart = declareCommand({
  name: 'recording-start',
  description: 'Start recording user actions',
  category: 'devtools',
  toolName: 'browser_start_recording',
  toolParams: () => ({}),
});

const recordingStop = declareCommand({
  name: 'recording-stop',
  description: 'Stop recording user actions and print them as Playwright code',
  category: 'devtools',
  toolName: 'browser_stop_recording',
  toolParams: () => ({}),
});

const tracingStart = declareCommand({
  name: 'tracing-start',
  description: 'Start trace recording',
  category: 'devtools',
  args: z.object({}),
  toolName: 'browser_start_tracing',
  toolParams: () => ({}),
});

const tracingStop = declareCommand({
  name: 'tracing-stop',
  description: 'Stop trace recording',
  category: 'devtools',
  args: z.object({}),
  toolName: 'browser_stop_tracing',
  toolParams: () => ({}),
});

const videoStart = declareCommand({
  name: 'video-start',
  description: 'Start video recording',
  category: 'devtools',
  args: z.object({
    filename: z.string().optional().describe('Filename to save the video.'),
  }),
  options: z.object({
    size: z.string().optional().describe('Video frame size, e.g. "800x600". If not specified, the size of the recorded video will fit 800x800.'),
    fps: numberArg.optional().describe('Video frame rate in frames per second, defaults to 25.'),
    cursor: z.boolean().optional().describe('Render an animated mouse cursor that travels to each action point. Paces actions by 800ms so that the cursor has time to travel.'),
  }),
  toolName: 'browser_start_video',
  toolParams: ({ filename, size, fps, cursor }) => {
    const parsedSize = size ? size.split('x').map(Number) : undefined;
    return { filename, size: parsedSize ? { width: parsedSize[0], height: parsedSize[1] } : undefined, fps, cursor };
  }
});

const videoStop = declareCommand({
  name: 'video-stop',
  description: 'Stop video recording',
  category: 'devtools',
  toolName: 'browser_stop_video',
  toolParams: () => ({}),
});

const videoChapter = declareCommand({
  name: 'video-chapter',
  description: 'Add a chapter marker to the video recording',
  category: 'devtools',
  args: z.object({
    title: z.string().describe('Chapter title.'),
  }),
  options: z.object({
    description: z.string().optional().describe('Chapter description.'),
    duration: numberArg.optional().describe('Duration in milliseconds to show the chapter card.'),
  }),
  toolName: 'browser_video_chapter',
  toolParams: ({ title, description, duration }) => ({ title, description, duration }),
});

const actionPositionArg = z.enum(['top-left', 'top', 'top-right', 'bottom-left', 'bottom', 'bottom-right']);
const actionCursorArg = z.enum(['none', 'pointer']);

const videoShowActions = declareCommand({
  name: 'video-show-actions',
  description: 'Annotate subsequent CLI/MCP actions on the page with a callout that names the action and, when styled, marks the action point and highlights the target element',
  category: 'devtools',
  args: z.object({}),
  options: z.object({
    duration: numberArg.optional().describe('How long each action annotation stays on screen, in milliseconds. Defaults to 500.'),
    position: actionPositionArg.optional().describe('Where to place the action title: top-left, top, top-right, bottom-left, bottom, bottom-right. Defaults to top-right.'),
    cursor: actionCursorArg.optional().describe('Cursor decoration: "pointer" (default) animates a mouse pointer between action points; "none" disables it.'),
    ['point-style']: z.string().optional().describe('CSS declarations for the zero-sized marker centered on the action point, e.g. "width: 20px; height: 20px; border-radius: 50%; background: red". Not shown when omitted.'),
    ['highlight-style']: z.string().optional().describe('CSS declarations for the box that covers the target element, e.g. "outline: 2px solid #333". Not shown when omitted.'),
    ['title-style']: z.string().optional().describe('CSS declarations for the action title, e.g. "font-size: 16px".'),
  }),
  toolName: 'browser_video_show_actions',
  toolParams: ({ duration, position, cursor, ['point-style']: point, ['highlight-style']: highlight, ['title-style']: title }) => ({ duration, position, cursor, style: point || highlight || title ? { point, highlight, title } : undefined }),
});

const videoHideActions = declareCommand({
  name: 'video-hide-actions',
  description: 'Stop annotating actions performed on the page',
  category: 'devtools',
  toolName: 'browser_video_hide_actions',
  toolParams: () => ({}),
});

const dashboardShow = declareCommand({
  name: 'show',
  description: 'Show Playwright Dashboard',
  category: 'devtools',
  raw: true,
  args: z.object({}),
  options: z.object({
    port: numberArg.optional().describe('Start as a blocking HTTP server on this port (use 0 for a random port)'),
    host: z.string().optional().describe('Host to bind to when using --port (defaults to localhost)'),
    annotate: z.boolean().optional().describe('Switch the dashboard into annotation mode.'),
    kill: z.boolean().optional().describe('Kill the dashboard daemon.'),
  }),
  toolName: ({ annotate }) => annotate ? 'browser_annotate' : '',
  toolParams: () => ({}),
});

const resume = declareCommand({
  name: 'resume',
  description: 'Resume the test execution',
  category: 'devtools',
  args: z.object({}),
  toolName: 'browser_resume',
  toolParams: ({ step }) => ({ step }),
});

const stepOver = declareCommand({
  name: 'step-over',
  description: 'Step over the next call in the test',
  category: 'devtools',
  args: z.object({}),
  toolName: 'browser_resume',
  toolParams: ({}) => ({ step: true }),
});

const pauseAt = declareCommand({
  name: 'pause-at',
  description: 'Run the test up to a specific location and pause there',
  category: 'devtools',
  args: z.object({
    location: z.string().describe('Location to pause at. Format is <file>:<line>, e.g. "example.spec.ts:42".'),
  }),
  toolName: 'browser_resume',
  toolParams: ({ location }) => ({ location }),
});

// Sessions

const sessionList = declareCommand({
  name: 'list',
  description: 'List browser sessions',
  category: 'browsers',
  args: z.object({}),
  options: z.object({
    all: z.boolean().optional().describe('List all browser sessions across all workspaces'),
  }),
  toolName: '',
  toolParams: () => ({}),
});

const sessionCloseAll = declareCommand({
  name: 'close-all',
  description: 'Close all browser sessions',
  category: 'browsers',
  toolName: '',
  toolParams: () => ({}),
});

const killAll = declareCommand({
  name: 'kill-all',
  description: 'Forcefully kill all browser sessions (for stale/zombie processes)',
  category: 'browsers',
  toolName: '',
  toolParams: () => ({}),
});

const deleteData = declareCommand({
  name: 'delete-data',
  description: 'Delete session data',
  category: 'core',
  toolName: '',
  toolParams: () => ({}),
});

const configPrint = declareCommand({
  name: 'config-print',
  description: 'Print the final resolved config after merging CLI options, environment variables and config file.',
  category: 'config',
  hidden: true,
  toolName: 'browser_get_config',
  toolParams: () => ({}),
});

const install = declareCommand({
  name: 'install',
  description: 'Initialize workspace',
  category: 'install',
  args: z.object({}),
  options: z.object({
    skills: z.string().optional().describe('Install skills, possible values: claude (default), agents.'),
    global: z.boolean().optional().describe('Install skills into the home directory instead of the workspace (alias: -g). Requires --skills.'),
  }),
  toolName: '',
  toolParams: () => ({}),
});

const installBrowser = declareCommand({
  name: 'install-browser',
  description: 'Install browser',
  category: 'install',
  args: z.object({
    browser: z.string().optional().describe('Browser to install'),
  }),
  options: z.object({
    ['with-deps']: z.boolean().optional().describe('Install system dependencies for browsers'),
    ['dry-run']: z.boolean().optional().describe('Do not execute installation, only print information'),
    list: z.boolean().optional().describe('Prints list of browsers from all Playwright installations'),
    force: z.boolean().optional().describe('Force reinstall of already installed browsers'),
    ['only-shell']: z.boolean().optional().describe('Only install headless shell when installing Chromium'),
    ['no-shell']: z.boolean().optional().describe('Do not install Chromium headless shell'),
  }),
  toolName: '',
  toolParams: () => ({}),
});

const tray = declareCommand({
  name: 'tray',
  description: 'Run tray',
  category: 'config',
  hidden: true,
  toolName: '',
  toolParams: () => ({}),
});

// WebMCP

function parseWebMCPParams(params: string | undefined) {
  if (params === undefined)
    return undefined;
  let parsed: unknown;
  try {
    parsed = JSON.parse(params);
  } catch (e) {
    throw new Error(`error: '--params' option: expected a JSON object, received '${params}'`);
  }
  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
    throw new Error(`error: '--params' option: expected a JSON object, received '${params}'`);
  return parsed as Record<string, unknown>;
}

const webmcpList = declareCommand({
  name: 'webmcp-list',
  description: 'List the WebMCP tools registered by the page',
  category: 'webmcp',
  args: z.object({}),
  toolName: 'browser_webmcp_list',
  toolParams: () => ({}),
});

const webmcpCall = declareCommand({
  name: 'webmcp-call',
  description: 'Call a WebMCP tool registered by the page',
  category: 'webmcp',
  args: z.object({
    name: z.string().describe('Name of the WebMCP tool to call'),
  }),
  options: z.object({
    params: z.string().optional().describe('Tool input parameters as a JSON object, for example \'{"query":"cats"}\''),
    frame: z.string().optional().describe('Frame that registered the tool, as reported by webmcp-list, when the tool name is ambiguous'),
  }),
  toolName: 'browser_webmcp_call',
  toolParams: ({ name, params, frame }) => ({ name, params: parseWebMCPParams(params), frame }),
});

const commandsArray: AnyCommandSchema[] = [
  // core category
  open,
  attach,
  close,
  detach,
  goto,
  type,
  click,
  doubleClick,
  fill,
  drag,
  drop,
  hover,
  select,
  fileUpload,
  check,
  uncheck,
  snapshot,
  find,
  evaluate,
  consoleList,
  dialogAccept,
  dialogDismiss,
  resize,
  runCode,
  deleteData,

  // navigation category
  goBack,
  goForward,
  reload,

  // keyboard category
  pressKey,
  keydown,
  keyup,

  // mouse category
  mouseMove,
  mouseDown,
  mouseUp,
  mouseWheel,

  // export category
  screenshot,
  pdfSave,

  // tabs category
  tabList,
  tabNew,
  tabClose,
  tabSelect,

  // storage category
  stateLoad,
  stateSave,
  cookieList,
  cookieGet,
  cookieSet,
  cookieDelete,
  cookieClear,
  localStorageList,
  localStorageGet,
  localStorageSet,
  localStorageDelete,
  localStorageClear,
  sessionStorageList,
  sessionStorageGet,
  sessionStorageSet,
  sessionStorageDelete,
  sessionStorageClear,

  // emulation category
  setColorScheme,
  setReducedMotion,
  setForcedColors,
  setContrast,
  setMedia,
  clearColorScheme,
  clearReducedMotion,
  clearForcedColors,
  clearContrast,
  clearMedia,

  // network category
  networkRequests,
  networkRequest,
  networkRequestHeaders,
  networkRequestBody,
  networkResponseHeaders,
  networkResponseBody,
  routeMock,
  routeList,
  unroute,
  networkStateSet,

  // config category
  configPrint,

  // install category
  install,
  installBrowser,

  // devtools category
  recordingStart,
  recordingStop,
  tracingStart,
  tracingStop,
  videoStart,
  videoStop,
  videoChapter,
  videoShowActions,
  videoHideActions,
  dashboardShow,
  pauseAt,
  resume,
  stepOver,
  generateLocator,
  highlight,

  // session category
  sessionList,
  sessionCloseAll,
  killAll,

  // webmcp category
  webmcpList,
  webmcpCall,

  // Hidden commands
  tray,
];

export const commands = Object.fromEntries(commandsArray.map(cmd => [cmd.name, cmd]));