Skip to content

Latest commit

 

History

History
532 lines (425 loc) · 27.6 KB

AGENTS.md

File metadata and controls

532 lines (425 loc) · 27.6 KB

AGENTS.md

This file provides guidance to AI coding agents when working with code in this repository.

Project Overview

WordPress Playground is a monorepo that runs WordPress and PHP entirely in WebAssembly, enabling zero-setup WordPress environments in browsers, Node.js, and CLIs. The project consists of two major architectural layers and several supporting packages:

  1. PHP-WASM Layer (packages/php-wasm/*): Emscripten-compiled PHP runtime for web and Node.js
  2. Playground Layer (packages/playground/*): WordPress-specific tooling, client libraries, and applications
  3. Supporting packages: packages/nx-extensions/ (custom NX executors), packages/docs/ (Docusaurus documentation site), packages/meta/ (ESLint plugin, changelog tooling), packages/bun-extensions/ and packages/vite-extensions/ (build tooling)

Build System

This is an NX monorepo with npm workspaces. All commands use NX for task orchestration.

Node.js version: This project requires a specific Node.js version (defined in .nvmrc and the engines field in root package.json). Before running any commands, ensure the correct version is active (e.g., via nvm use or other version manager).

Initial Setup

From a fresh clone or new worktree, set up the repository before running builds, tests, or dev servers:

nvm use
npm ci

This is especially important for worktree-based agent tools, which may create a working tree without installing dependencies.

Common Commands

# Development
npm run dev                              # Start website dev server (localhost:5400); auto-reloads on code changes, no restart needed
npm run dev:docs                         # Start documentation site
npx nx dev playground-cli server         # Run CLI from source
# Building
npm run build                            # Build all packages
npm run build:website                    # Build the main website
npm run build:docs                       # Build documentation
npx nx build <package-name>              # Build specific package

# Testing
npm test                                 # Run all tests
npx nx test <package-name>               # Test specific package
npx nx e2e playground-website            # Run website Playwright E2E tests
npx nx run playground-website:e2e:playwright:ci # Run website Playwright E2E tests

# Running a single test file
npx nx test <package-name> --testFile=<test-file-name>

# Linting & Formatting
npm run lint                             # Lint all packages
npm run typecheck                        # Type check all packages
npm run format                           # Format code with Prettier
npm run format:uncommitted               # Format only uncommitted files

# PHP Recompilation (see compile-php-wasm skill for details)
npm run recompile:php:web                # Recompile all PHP versions for web
npm run recompile:php:node               # Recompile all PHP versions for Node.js
npm run recompile:php:web:next         # Recompile PHP next web binaries
npm run sync:php-next                  # Fetch gitignored PHP next assets for local dev

# WordPress Builds
npm run rebuild:wordpress-builds         # Rebuild all WordPress versions

Normal loopback website development keeps the SPA, PHP, OPFS, and directory handles on 127.0.0.1:5400, with rendered WordPress on 127.0.0.1:4400. localhost uses the same two ports. Vite's app proxy preserves the app Host; the remote server restricts direct WordPress-port requests to the WordPress bridge and worker loaders. Standalone remote, Personal WP, sync, and forwarded hosts retain their previous routing. Do not replace either server with an auto-selected port. A single Chromium CI smoke test covers the live Vite module graph; the full browser suite still runs once against the built cross-origin preview.

The WordPress-only origin prototype has build:wordpress-frame, preview:wordpress-frame, and e2e:wordpress-frame website targets. It runs on port 9500, separately from normal development. CI runs all website E2E tests once against the separate WordPress origin, with shared storage/import grouping. Deployment tests use the same boundary on port 7999. See packages/playground/website/bin/wordpress-frame/README.md for its boundaries. WordPress always uses the configured sandbox origin. PHP, OPFS, and directory handles stay on the app origin. Tabs share one app service worker and asset cache. App workers leave other releases' assets to HTTP so worker replacement cannot interrupt those downloads in WebKit, including /assets/ when rolling back to the root-only layout; their own release's assets keep offline caching. Standalone and self-hosted builds without a sandbox retain one origin. External embeds do not need a referrer or new URL parameters. This mode does not block WordPress from embedding fresh app/API documents. The normal WP Cloud deployment runs website-deployment/deploy-website.sh, which sets VITE_WORDPRESS_SITE_URL to https://wpsandbox.wordpress.net, PLAYGROUND_APP_ORIGIN to https://playground.wordpress.net, and a unique PLAYGROUND_RELEASE_ID. test-staging-deployment.sh runs that same script against a disposable staging site, and check-deployment.sh checks a deployed release over HTTP without changing it. Vite builds with base /releases/<id>/, so every asset URL names its release, and adds an inline origin check to every app HTML page, including copied public files: the WordPress bridge requires the sandbox origin, all other pages the app origin and their web-root URL, so retained releases' pages cannot start. JavaScript release ID validation is shared in packages/playground/remote/src/lib/release-id.ts. Compatibility code markers and removal conditions are listed in packages/playground/website-deployment/wordpress-frame/compatibility.md. When changing marked code, update that checklist and its coverage. Remove compatibility code only when its documented removal conditions hold; preserve supported portable/dev layouts. The target and the build:wordpress-frame preview assemble the upload with the same bin/assemble-website.mjs, so preview checks cover every published page. The single apply-update.sh installs the build as the public releases/<id>/ directory, moves its PHP endpoints to the Nginx-denied .playground-releases/<id>/, and copies entry pages plus a root /sw.js loader to the web root. Pages needing custom headers stay PHP-served. Its PHP steps live in apply-update.php, which it calls with arguments only. The cacheable playground-wordpress-builds:validate-static-documents target validates WordPress HTML, SVG, XHTML, and XML with a parsed-document DOMPurify check. Asset refresh and publication depend on it. It rejects active and unreviewed malformed content without rewriting bytes; reviewed upstream defects require reviewed hash lists per WordPress-relative path, shared across versions. WordPress Docker exports restore the mounted output directory's owner before host-side validation. Use container-visible IDs so rootless Docker keeps the files owned by the caller. Limit ownership repair to the exported version directory and core archive. Preserve SQLite's owner-only directory permissions when exporting build artifacts. The self-hosting download is built separately without release paths or production origins. Nginx serves existing files on both hostnames; custom-redirects.php handles only missing paths. Inactive releases expire after 30 days (configurable), protecting active and previous releases. release.json inventories owned root files; activation failures and manual rollback restore replaced/deleted files and remove newly introduced ones with the same installer. Cleanup failures retain lifecycle metadata for retry; prune runs only after both hosts have been purged. PHP's flock serializes the whole installer on each web root. Only the lock coordinator disables WP Cloud's auto-prepend bootstrap, preserving the shell environment for its child; PHP installation steps keep the normal bootstrap. Purge hosts are recorded outside root snapshots; PLAYGROUND_PURGE_ONLY=1 retries a failed purge without another rollback. Pending purges block further installations and rollbacks. Rollback records both the current and restored hostname pairs, including origin changes. Failed activation purges after restoring the previous files. Staging readiness checks require successful worker responses and retry transient HTTP errors; rollback compares both workers with their captured baseline bytes. The browser rehearsal rejects a non-trunk baseline before opening browsers or deploying. It first reloads trunk as a control, and logs errors with their phase and request URLs. The live deployment rehearsal forces a failed purge after restoring trunk, then retries it. Its unit tests run in playground-website:test. The staging browser rehearsal accepts PLAYGROUND_STAGING_FIREFOX_CHANNEL=moz-firefox to use installed Firefox when the bundled browser cannot launch locally. Do not add a second installer script. Host checks live in website-deployment/custom-redirects-lib.php, reached through its existing playground_handle_request() entry point. The sandbox host serves only bridge aliases for older clients and returns 404 otherwise, with scoped top-level GET navigations redirected to the configured app origin. Scoped app navigations serve the trusted WordPress iframe wrapper; iframe and subresource requests never redirect. App requests keep the existing redirects, headers, and PHP setup. One /sw.js serves both hostnames and chooses its role by origin. Personal WP keeps its no-argument public-file layout and separate script. The HTTP/install contract tests run with playground-website:test:wordpress-frame-router (Node 24 and PHP required). The WordPress bridge (wordpress-bridge.html) is the hidden sandbox iframe that relays HTTP between its service worker and app-origin PHP. Production bridge URLs name the app's release directory. Development and portable builds use build-version root aliases; older root-only production builds use those aliases too. Workers generate bridge HTML only for their own release/buildVersion and the unversioned compatibility alias. Other versions reach the server, so an installed worker cannot supply a removed script URL. The bridge waits for the worker it registers to activate before completing PHP startup.

WP Cloud's PHP-served static files support single bounded and open-ended byte ranges for runtime download retries. Other range forms get the full response; HEAD ignores Range. Run playground-website:test:static-file-ranges for the real PHP HTTP contract tests (Node 24 and PHP required); CI runs them with lint checks.

Package Naming Convention

  • @php-wasm/<name>: PHP runtime and utilities
  • @wp-playground/<name>: WordPress Playground features and tools

Architecture

Client-Remote Communication

The core architecture uses an iframe-based isolation model:

@wp-playground/client (parent window)
    ↓ postMessage API
@wp-playground/remote (iframe content, runs PHP)
    ↓
@php-wasm/web (PHP runtime)
    ↓
@php-wasm/universal (abstract interface)

Key packages:

  • @wp-playground/client: JavaScript API for embedding Playground in iframes
  • @wp-playground/remote: The HTML application running inside the iframe
  • @php-wasm/web: Browser-based PHP runtime (uses Emscripten WASM)
  • @php-wasm/node: Node.js-based PHP runtime
  • @php-wasm/universal: Abstract interface shared by web and node implementations

Personal WP explicitly opts into SharedWorkers via startPlaygroundWeb. Its ServiceWorker sends HTTP requests directly to the shared PHP runtime through MessagePorts. The main website retains dedicated workers and the existing window relay by default. Personal WP owns loopback-network delegation: its startup load listener configures its same-origin remote's WordPress frame before PHP boots. Its popup HTML entry opts in to the shared renderer and replaces the default popup in the combined Personal WP build. Shared remote and public popup documents do not opt in based on their hostname or URL parameters. Keep these app-specific policies in Personal WP. Deployment checks run once per Personal WP document; stale runtimes drain requests and flush OPFS before shutting down. Keep shared-runtime behavior behind the explicit opt-in.

Blueprint System

Blueprints are declarative JSON configurations that define WordPress site states. Located in @wp-playground/blueprints.

Key concepts:

  • Blueprint steps execute sequentially (e.g., installPlugin, login, runPHP)
  • Two execution modes: V1 (TypeScript runner) and V2 (experimental PHP runner)
  • Steps are defined in packages/playground/blueprints/src/lib/steps/
  • Each step has a .ts implementation and .spec.ts test file

Common blueprint steps:

  • installPlugin, activatePlugin: Plugin management
  • installTheme, activateTheme: Theme management
  • login: User authentication
  • runPHP, runPHPWithOptions: Execute PHP code
  • defineWpConfigConsts: Modify wp-config.php
  • importWxr, importWordPressFiles: Import content

Schema generation: Blueprint JSON schemas are auto-generated from TypeScript types. After modifying step interfaces, rebuild with npx nx build playground-blueprints. The schema is NOT auto-rebuilt in npm run dev mode.

Storage & Sync

  • @wp-playground/storage: Provides filesystem backends (IndexedDB in browser, filesystem in Node)
  • @wp-playground/sync: Multi-client synchronization for collaborative editing
  • @php-wasm/fs-journal: Tracks filesystem changes for synchronization

Browser WordPress boots record the site's public base URL in /wordpress/.playground-site-url. Stored sites without that record are migrated from their scoped app-origin URL before startup completes. Flush migrated data before saving the record; later boots must not rescan the database when the recorded URL still matches. Log migration failures and keep the site accessible; a missing completion record allows a later boot to retry.

WordPress Builds

@wp-playground/wordpress-builds compiles specific WordPress versions into the playground format. Each version is tested and bundled separately.

Multi-Runtime PHP Support

PHP binaries are compiled separately for:

  • Web (browser): Asyncify and JSPI variants for different browser capabilities
  • Node.js: Native async/await support

Version-specific builds: @php-wasm/web-7-4 through @php-wasm/web-8-5 (and corresponding node-builds)

Development Conventions

TypeScript

  • Type imports must be explicit: Use import type { Foo } from 'bar' (required for Node.js type stripping)
  • No parameter properties: TypeScript parameter properties are not supported by Node.js type stripping
  • Module resolution: bundler mode in tsconfig
  • Target: ES2021 with ESNext modules
  • Path aliases defined in tsconfig.base.json for cross-package imports

Code Style

  • Explicit conditions: Name the fact a branch depends on. If a value only implies that fact (a path, sentinel, or naming convention), derive a clearly named boolean once and use it at decision sites. Keep the inference in one place and explain why it holds. Prefer names that describe the actual behavior or layout.

  • Comment length: Max 100 characters per line (enforced by ESLint)

  • No console.log: Disallowed except in tests and bin/ scripts

  • Consistent type imports: Required by @typescript-eslint/consistent-type-imports

  • Module boundaries: Enforced via @nx/enforce-module-boundaries

    • Packages tagged scope:web-client cannot be depended on by others
    • scope:independent-from-php-binaries packages cannot depend on scope:php-binaries
  • Function ordering: First caller, then callee. When function A calls function B, write first A, then B.

  • Method ordering: First public, then protected, then private. Respect Function ordering as well.

  • UI consistency: Before adding custom control styles or wrappers, inspect equivalent controls in adjacent screens and reuse the existing shared component, variant, sizing, and design tokens. Add bespoke CSS only when shared primitives cannot express the required behavior, and verify the result side by side with neighboring UI.

  • Progress states: Use PaneLoading when an entire Dock pane is unavailable and InlineProgress when an operation leaves the surrounding pane visible. Keep progress inside an action button only when the button is the sole progress surface; do not show a second spinner or invent another loading container for the same operation.

  • Dock tools: Register destinations in packages/playground/website/src/components/dock/tool-registry.tsx. Each entry owns its group, navigation labels/icon, pane copy/layout, and optional site-tool panel. Developer tools use group: 'developer' and the shared SiteToolPanelProps interface; adapters for existing tools live in site-info-panel/site-tool-renderers.tsx. The host mounts panels on first use and retains them until the site changes. Do not add parallel navigation or routing lists.

  • Path manipulation: Never use ad-hoc string operations for file paths. Use the POSIX path utilities from @php-wasm/util (joinPaths, dirname, basename, normalizePath, ensureAbsolutePath, resolvePathUnder, etc.) instead of Node.js path (which can produce Windows-style paths). If the package you're modifying has its own paths.ts, prefer that; otherwise import from @php-wasm/util. Do not invent regex/string-splitting path normalization, prefix stripping, traversal checks, or separator rewriting when an existing path utility applies. Preserve valid path bytes such as backslashes unless an existing native-path conversion helper explicitly calls for changing them. New path helpers should be co-located with the existing paths.ts in the relevant package, with tests.

  • Review feedback pattern: When feedback points out invented regexes, duplicate helpers, speculative wrappers, or byte-changing normalization, treat that as a signal to simplify the model and use existing utilities instead of defending the new abstraction.

Testing

CI removes the slow Azure Ubuntu mirror from the runner's apt mirror list before installing browser dependencies. The public Ubuntu archive and security mirrors remain available.

  • Test files: Co-located with implementation as *.spec.ts
  • Test runner: Vitest (via @nx/vite:test) for most packages; some packages use Jest (via @nx/jest)
  • Coverage: Reports to coverage/packages/<package-name>
  • E2E tests: Playwright for website testing
  • Always fix failing tests: Never skip failing tests; fix the code to make tests pass

Test-value gate

Tests are maintenance code. Do not add one merely because production code changed.

Do not test:

  • literal JSX or static configuration;
  • copy, CSS classes, visual variants, element counts, or ordering;
  • exact pixel dimensions, spacing values, or other CSS outcomes copied into unit-test fixtures;
  • presentation-only visibility controlled by an adjacent conditional;
  • behavior that would change only when someone intentionally reverses the product decision.

Before adding a test, name all three:

  1. The stable contract it protects.
  2. A plausible accidental regression.
  3. The independent code path that could cause that regression.

If you cannot name all three concretely, do not add the test.

A test is not independent when its expected value must be edited whenever adjacent CSS changes. Delete or avoid that test instead of updating its numbers.

Use screenshots and manual interaction for visual-only changes. Tests are not required for every PR. Never add tests simply to make a PR appear complete.

CI tests the Node file-lock fallback on Node 24 and the current Node release. It builds the published Node package, checks that the native addon is optional, and runs PHP/SQLite, CLI multi-worker, and worker-wait tests with that addon moved out of resolution. The addon is restored before the shared dependency cache is saved.

Dependabot's daily version check opens PRs for fs-ext-extra-prebuilt patch releases. It raises the minimum package version and updates the lockfile; the existing Dependabot lockfile workflow preserves workspace links. An explicit trunk target keeps this version-update allow-list out of security-update settings. Other dependencies remain eligible for security updates.

Package Structure

All published packages follow this pattern:

packages/[layer]/[package-name]/
├── src/
│   ├── index.ts              # Main entry point
│   └── lib/                  # Implementation
├── package.json              # npm metadata
├── project.json              # NX build configuration
├── tsconfig.json             # Base TypeScript config
├── tsconfig.lib.json         # Library build config
├── tsconfig.spec.json        # Test config
└── README.md                 # Package documentation

Some packages have their own AGENTS.md with package-specific guidance. Check for one when working within a package.

Publishing

  • Dual format: All packages publish both ESM (.js) and CommonJS (.cjs)
  • publishConfig.directory: Points to dist/packages/[layer]/[package-name]
  • Lerna: Used for coordinated multi-package publishing (npm run release)
  • Exports field: Defines both import and require conditions
  • Version management: All packages versioned together (see lerna.json for current version)

Special Workflows

Running Tests from Source

# Individual package test
npx nx test playground-blueprints

# Run specific test file
npx nx test playground-blueprints --testFile=activate-plugin.spec.ts

# Run with coverage
npx nx test playground-blueprints --coverage

# E2E tests
npx nx e2e playground-website

CLI Development

The Playground CLI (@wp-playground/cli) can be run directly from source:

npx nx dev playground-cli server --wp=6.8 --php=8.4 --auto-mount

CLI features:

  • --auto-mount: Automatically detect and mount plugin/theme/WordPress directory
  • --blueprint=<path>: Execute a blueprint JSON file
  • --mount=<src>:<dest>: Manually mount directories
  • --login: Auto-login as admin
  • --php=<version>: Choose PHP version (7.4-8.5)
  • --wp=<version>: Choose WordPress version

Git Operations

  • Default branch: trunk is the primary development branch
  • Never use bare git push: Always specify remote and branch explicitly
  • Shallow clone recommended: git clone -b trunk --single-branch --depth 1

Working with PHP Binaries

PHP binaries are pre-compiled and committed to the repository. Recompilation is rarely needed. For compilation commands, build flags, and troubleshooting, see the compile-php-wasm skill. For debugging WASM crashes, see the debug-php-wasm-main-module and debug-php-wasm-side-modules skills.

Custom NX Executors

Located in packages/nx-extensions/src/executors/:

  • build: Builds packages
  • built-script: Runs scripts from built output
  • package-json: Generates package.json with correct exports
  • assert-built-esm-and-cjs: Verifies dual-format build
  • package-for-self-hosting: Creates distributable archives

Reprint Client Asset

The website's sync-reprint target verifies and downloads the selected Reprint client before builds and standalone dev startup. The generated asset lives in the ignored packages/playground/website/public/assets/optional/reprint/ directory and is loaded on demand. Use npm exec -- nx run playground-website:update-reprint to update the version and checksum together in src/lib/reprint/release.json; see the website README.

Key Files & Directories

  • nx.json: NX workspace configuration
  • tsconfig.base.json: TypeScript path aliases and compiler options
  • package.json: Root package with all npm scripts
  • lerna.json: Version management and publish configuration
  • .eslintrc.json: ESLint rules including module boundaries
  • packages/playground/blueprints/src/lib/steps/: Blueprint step implementations
  • packages/php-wasm/universal/: Core PHP abstraction layer
  • packages/php-wasm/compile/: Docker/Emscripten PHP build pipeline
  • packages/playground/website/: Main demo application
  • packages/playground/cli/: CLI tool implementation
  • packages/docs/: Docusaurus documentation site
  • packages/meta/: Internal tooling (ESLint plugin, changelog)

Documentation

  • Deployed to https://wordpress.github.io/wordpress-playground/
  • Built with Docusaurus in packages/docs/
  • API reference generated with TypeDoc from package source
  • Docusaurus generates manifest.json and translation-availability.json in the build output for the default locale. The handbook manifest derives pages, titles, hierarchy, and order from loaded docs and sidebars. Legacy handbook URL and generated Markdown exceptions live in plugins/generate-handbook-manifest.js. Run npx nx run docs-site:test-plugins when changing these build plugins.
  • The docs build generates handbook Markdown in packages/docs/site/static/handbook/ from TypeDoc. Regenerate and commit these files when their source docs or API comments change; the WordPress.org importer reads them through manifest.json.
  • When adding screenshots to Markdown docs, use the raw GitHub URL for the committed asset, for example https://raw.githubusercontent.com/WordPress/wordpress-playground/refs/heads/trunk/packages/docs/site/static/img/.... Relative /img/... links work in Docusaurus but are not preserved by the WordPress.org handbook importer.

Important Notes

  • Backwards compatibility: Breaking changes are acceptable and often useful during development, but must be surfaced to the developer. When creating a PR, clearly document any breaking changes in the PR description. Key downstream consumers include Telex, Studio, and wp-env
  • Offline support: Website can be built for offline use with service workers
  • WordPress major and beta versions: Auto-refreshed via GitHub Actions
  • SQLite integration: WordPress uses SQLite by default (no MySQL required)
  • Security: Iframe-based isolation prevents untrusted code execution in parent window

General Guidelines for working with Nx

  • For navigating/exploring the workspace, invoke the nx-workspace skill first - it has patterns for querying projects, targets, and dependencies
  • When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through nx (i.e. nx run, nx run-many, nx affected) instead of using the underlying tooling directly
  • Prefix nx commands with the workspace's package manager (e.g., pnpm nx build, npm exec nx test) - avoids using globally installed CLI
  • You have access to the Nx MCP server and its tools, use them to help the user
  • For Nx plugin best practices, check node_modules/@nx/<plugin>/PLUGIN.md. Not all plugins have this file - proceed without it if unavailable.
  • NEVER guess CLI flags - always check nx_docs or --help first when unsure

Scaffolding & Generators

  • For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the nx-generate skill FIRST before exploring or calling MCP tools

When to use nx_docs

  • USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge cases
  • DON'T USE for: basic generator syntax (nx g @nx/react:app), standard commands, things you already know
  • The nx-generate skill handles generator discovery internally - don't call nx_docs just to look up generator syntax