diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a2d40d368a..e4f3e9146c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -294,6 +294,52 @@ jobs: # E2E Playwright tests - builds inline per runner for faster parallel execution # Previously used a prepare job + artifact sharing, but inline builds allow # all shards to start immediately in parallel, reducing total wall time. + test-e2e-reprint-import: + if: github.repository == 'WordPress/wordpress-playground' || github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 40 + permissions: + contents: read # Required to clone the repo. + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: ./.github/actions/prepare-playground + - name: Install PHP for the source site + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + extensions: sqlite3, pdo_sqlite, gd, mbstring, curl, zip, xml + tools: none + - name: Install Playwright Browser + run: sudo npx playwright install chromium --with-deps + - name: Build app for E2E tests + run: CORS_PROXY_URL=http://127.0.0.1:5263/cors-proxy.php? npx nx e2e:playwright:prepare-app-deploy-and-offline-mode playground-website + - name: Serve a WordPress site with Reprint Server + run: | + bash packages/playground/website/playwright/reprint-site/serve.sh > /tmp/reprint-site.log 2>&1 & + for _ in $(seq 1 120); do + if curl -sf http://127.0.0.1:8181/playground-e2e-manifest.json > /dev/null; then + exit 0 + fi + sleep 2 + done + echo "The source site did not come up:" + cat /tmp/reprint-site.log + exit 1 + - name: Run Playwright reprint-import tests + run: sudo CI=true PLAYWRIGHT_TEST_GROUP=reprint-import REPRINT_E2E_SITE_URL=http://127.0.0.1:8181/ npx playwright test --config=packages/playground/website/playwright/playwright.ci.config.ts --project=chromium + - name: Source site log + if: ${{ failure() }} + run: cat /tmp/reprint-site.log + - uses: actions/upload-artifact@v4 + if: ${{ failure() }} + with: + name: playwright-report-reprint-import + path: packages/playground/website/playwright-report/ + if-no-files-found: ignore + retention-days: 7 + test-e2e-playwright: if: github.repository == 'WordPress/wordpress-playground' || github.event_name == 'pull_request' runs-on: ubuntu-latest diff --git a/packages/php-wasm/compile/php/emscripten-sleep.test.cjs b/packages/php-wasm/compile/php/emscripten-sleep.test.cjs new file mode 100644 index 00000000000..722c0e2abf3 --- /dev/null +++ b/packages/php-wasm/compile/php/emscripten-sleep.test.cjs @@ -0,0 +1,113 @@ +const { readFileSync, globSync } = require('node:fs'); +const { join } = require('node:path'); +const { runInNewContext } = require('node:vm'); +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); + +// Test the compiler input and the checked-in loaders: a source-only change +// would leave existing browser downloads using the slow timer path. +const librarySource = readFileSync( + join(__dirname, 'phpwasm-emscripten-library.js'), + 'utf8' +); +const implementations = [ + [ + 'compiler library', + `${librarySource}\nLibraryManager.library.emscripten_sleep;`, + ], + ...globSync('*/*/php_*.js', { + cwd: join(__dirname, '../../web-builds'), + }).map((path) => { + const source = readFileSync( + join(__dirname, '../../web-builds', path), + 'utf8' + ); + const start = source.indexOf('var _emscripten_sleep ='); + const end = source.indexOf('_emscripten_sleep.sig', start); + assert.ok(start !== -1 && end > start, `Missing sleep in ${path}`); + return [path, `${source.slice(start, end)}\n_emscripten_sleep;`]; + }), +]; + +for (const [name, source] of implementations) { + describe(name, () => { + it('yields zero-delay sleeps to a task, keeping the runtime alive', () => { + const runtime = createRuntime(source); + runtime.sleep(0); + assert.equal(runtime.tasks.length, 1); + assert.equal(runtime.timers.length, 0); + assert.deepEqual(runtime.events, ['keepalive']); + runtime.tasks.shift()(); + assert.deepEqual(runtime.events, [ + 'keepalive', + 'release', + 'callback', + 'wake', + ]); + }); + + it('keeps positive sleeps on the existing timer path', () => { + const runtime = createRuntime(source); + runtime.sleep(125); + assert.equal(runtime.tasks.length, 0); + assert.equal(runtime.timers.length, 1); + assert.equal(runtime.timers[0].delay, 125); + runtime.timers[0].callback(); + assert.deepEqual(runtime.events, ['wake']); + }); + + for (const scheduler of [undefined, {}]) { + it(`uses the timer when postTask is unavailable (${JSON.stringify(scheduler)})`, () => { + const runtime = createRuntime(source, scheduler); + runtime.sleep(0); + assert.equal(runtime.tasks.length, 0); + assert.equal(runtime.timers.length, 1); + assert.equal(runtime.timers[0].delay, 0); + runtime.timers[0].callback(); + assert.deepEqual(runtime.events, ['wake']); + }); + } + + it('lets callUserCallback skip resuming an aborted runtime', () => { + const runtime = createRuntime(source); + runtime.sleep(0); + runtime.context.callUserCallback = () => + runtime.events.push('aborted'); + runtime.tasks.shift()(); + assert.deepEqual(runtime.events, [ + 'keepalive', + 'release', + 'aborted', + ]); + }); + }); +} + +function createRuntime(source, ...schedulerOverride) { + const events = []; + const tasks = []; + const timers = []; + const context = { + LibraryManager: { library: {} }, + mergeInto: Object.assign, + autoAddDeps() {}, + Asyncify: { handleSleep: (start) => start(() => events.push('wake')) }, + safeSetTimeout: (callback, delay) => timers.push({ callback, delay }), + runtimeKeepalivePush: () => events.push('keepalive'), + runtimeKeepalivePop: () => events.push('release'), + callUserCallback: (callback) => { + events.push('callback'); + callback(); + }, + scheduler: schedulerOverride.length + ? schedulerOverride[0] + : { postTask: (callback) => tasks.push(callback) }, + }; + return { + sleep: runInNewContext(source, context), + context, + events, + tasks, + timers, + }; +} diff --git a/packages/php-wasm/compile/php/phpwasm-emscripten-library.js b/packages/php-wasm/compile/php/phpwasm-emscripten-library.js index ba57b40faf9..4a1cc0ff59d 100644 --- a/packages/php-wasm/compile/php/phpwasm-emscripten-library.js +++ b/packages/php-wasm/compile/php/phpwasm-emscripten-library.js @@ -8,6 +8,32 @@ 'use strict'; const LibraryExample = { + emscripten_sleep__deps: [ + '$Asyncify', + '$safeSetTimeout', + '$runtimeKeepalivePush', + '$runtimeKeepalivePop', + '$callUserCallback', + ], + emscripten_sleep__sig: 'vi', + emscripten_sleep__async: true, + emscripten_sleep: function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }, + // Emscripten dependencies: $PHPWASM__deps: ['$allocateUTF8OnStack', '$addOnInit'], $PHPWASM__postset: 'PHPWASM.init();', diff --git a/packages/php-wasm/compile/project.json b/packages/php-wasm/compile/project.json index 7174355f265..fe8dc2af28e 100644 --- a/packages/php-wasm/compile/project.json +++ b/packages/php-wasm/compile/project.json @@ -2,6 +2,16 @@ "name": "php-wasm-compile", "$schema": "../../../node_modules/nx/schemas/project-schema.json", "targets": { + "test": { + "executor": "nx:run-commands", + "inputs": [ + "default", + "{workspaceRoot}/packages/php-wasm/web-builds/*/*/php_*.js" + ], + "options": { + "command": "node --test packages/php-wasm/compile/php/emscripten-sleep.test.cjs" + } + }, "compile": { "executor": "nx:run-commands", "options": { diff --git a/packages/php-wasm/fs-journal/src/lib/fs-journal.ts b/packages/php-wasm/fs-journal/src/lib/fs-journal.ts index 3d311c111dc..7abdca86779 100644 --- a/packages/php-wasm/fs-journal/src/lib/fs-journal.ts +++ b/packages/php-wasm/fs-journal/src/lib/fs-journal.ts @@ -367,8 +367,45 @@ export function normalizeFilesystemOperations( let journal = input; while (true) { const substitutions: Record = {}; + // Most download records only affect one file. Looking up that path + // avoids comparing every chunk write with every other file in the site. + // Rebuild after each substitution pass because renames change paths. + const entriesByPath = new Map(); + const directoryRenames: number[] = []; + for (let i = 0; i < journal.length; i++) { + const entry = journal[i]; + const path = + entry.operation === 'RENAME' ? entry.toPath : entry.path; + if (!entriesByPath.has(path)) entriesByPath.set(path, []); + entriesByPath.get(path)!.push(i); + if ( + entry.operation === 'RENAME' && + entry.nodeType === 'directory' + ) { + directoryRenames.push(i); + } + } for (let i = journal.length - 1; i >= 0; i--) { - for (let j = i - 1; j >= 0; j--) { + const entry = journal[i]; + let candidates: number[]; + if ( + entry.operation === 'RENAME' && + entry.nodeType === 'directory' + ) { + // Moving a directory may rewrite any earlier descendant path. + candidates = Array.from({ length: i }, (_, j) => j); + } else { + candidates = entriesByPath.get(entry.path) ?? []; + if (entry.operation === 'RENAME') { + // Keep detecting unsupported rename chains through a parent. + candidates = [ + ...new Set([...candidates, ...directoryRenames]), + ]; + } + } + // Substitutions depend on visiting earlier records newest-first. + for (const j of [...candidates].sort((a, b) => b - a)) { + if (j >= i) continue; const formerType = checkRelationship(journal[i], journal[j]); if (formerType === 'none') { continue; diff --git a/packages/php-wasm/fs-journal/src/test/fs-journal.spec.ts b/packages/php-wasm/fs-journal/src/test/fs-journal.spec.ts index 3457f5dc9a3..e4ebd22e3c6 100644 --- a/packages/php-wasm/fs-journal/src/test/fs-journal.spec.ts +++ b/packages/php-wasm/fs-journal/src/test/fs-journal.spec.ts @@ -182,6 +182,33 @@ describe('Journal MemFS', () => { }); describe('normalizeFilesystemOperations()', () => { + it('normalizes a large download without scanning unrelated paths for every write', () => { + // Downloads write each file in chunks. Comparing all pairs of these + // records blocks the PHP worker, including error and log delivery. + // Count path reads rather than timing the test on different machines. + let pathReads = 0; + const journal: FilesystemOperation[] = []; + const expected: FilesystemOperation[] = []; + for (let i = 0; i < 33057; i++) { + const path = `/wordpress/wp-content/uploads/file-${i}`; + for (let chunk = 0; chunk < 6; chunk++) { + journal.push({ + operation: chunk === 0 ? 'CREATE' : 'WRITE', + nodeType: 'file', + get path() { + if (++pathReads > 3000000) { + throw new Error( + 'Bulk download normalization scanned too many paths' + ); + } + return path; + }, + }); + } + expected.push({ operation: 'WRITE', nodeType: 'file', path }); + } + expect(normalizeFilesystemOperations(journal)).toEqual(expected); + }); it('Normalizes CREATE and WRITE + multiple WRITE file ops to a single WRITE', () => { const expected = [ { operation: 'WRITE', path: '/test', nodeType: 'file' }, diff --git a/packages/php-wasm/logger/src/lib/collectors/collect-php-logs.spec.ts b/packages/php-wasm/logger/src/lib/collectors/collect-php-logs.spec.ts new file mode 100644 index 00000000000..5f3f2d47ac7 --- /dev/null +++ b/packages/php-wasm/logger/src/lib/collectors/collect-php-logs.spec.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, vi } from 'vitest'; +import { collectPhpLogs } from './collect-php-logs'; +import type { UniversalPHP } from '../types'; +import type { Logger } from '../logger'; + +describe('PHP log collection after a site import', () => { + it('reads appended records once and restarts after replacement or removal', async () => { + const logs = createCollector(); + await logs.request('old log'); + await logs.request('old log\nnew error'); + await logs.request('old log\nnew error'); + await logs.request('fatal'); + await logs.request('other'); // Same length, but an imported file. + await logs.request(''); + await logs.request('fatal'); + expect(logs.messages()).toEqual([ + 'old log', + '\nnew error', + 'fatal', + 'other', + 'fatal', + ]); + }); + it('does not share offsets between Playgrounds', async () => { + const first = createCollector(); + const second = createCollector(); + await first.request('a much longer old log'); + await second.request('error'); + expect(second.messages()).toEqual(['error']); + }); +}); + +function createCollector() { + const callbacks: Record Promise> = {}; + let log = ''; + const logger = { logMessage: vi.fn() }; + collectPhpLogs( + logger as unknown as Logger, + { + addEventListener: (name: string, callback: () => Promise) => { + callbacks[name] = callback; + }, + fileExists: async () => !!log, + readFileAsText: async () => log, + } as unknown as UniversalPHP + ); + return { + request: async (next: string) => { + log = next; + await callbacks['request.end'](); + }, + messages: () => + logger.logMessage.mock.calls.map(([record]) => record.message), + }; +} diff --git a/packages/php-wasm/logger/src/lib/collectors/collect-php-logs.ts b/packages/php-wasm/logger/src/lib/collectors/collect-php-logs.ts index d9c4a3f081a..c6aa878f171 100644 --- a/packages/php-wasm/logger/src/lib/collectors/collect-php-logs.ts +++ b/packages/php-wasm/logger/src/lib/collectors/collect-php-logs.ts @@ -1,7 +1,6 @@ import type { UniversalPHP, PHPRequestErrorEvent } from '../types'; import { type Logger, LogPrefix, LogSeverity } from '../logger'; -let lastPHPLogLength = 0; export const errorLogPath = '/wordpress/wp-content/debug.log'; /** @@ -26,16 +25,21 @@ export const collectPhpLogs = ( loggerInstance: Logger, playground: UniversalPHP ) => { + let lastPHPLog = ''; playground.addEventListener('request.end', async () => { const log = await getRequestPhpErrorLog(playground); - if (log.length > lastPHPLogLength) { - const currentLog = log.substring(lastPHPLogLength); + // Imports can replace debug.log with a shorter or unrelated file. Track + // each Playground separately and only skip a prefix we actually read. + const currentLog = log.startsWith(lastPHPLog) + ? log.substring(lastPHPLog.length) + : log; + lastPHPLog = log; + if (currentLog) { loggerInstance.logMessage({ message: currentLog, severity: LogSeverity.Log, raw: true, }); - lastPHPLogLength = log.length; } }); playground.addEventListener('request.error', (event) => { diff --git a/packages/php-wasm/universal/src/lib/php-worker.ts b/packages/php-wasm/universal/src/lib/php-worker.ts index d44a24f9739..0d6c735fde5 100644 --- a/packages/php-wasm/universal/src/lib/php-worker.ts +++ b/packages/php-wasm/universal/src/lib/php-worker.ts @@ -205,9 +205,9 @@ export class PHPWorker implements LimitedPHPApi, AsyncDisposable { const state = _private.get(this)!; const primaryPhp = state.php; if ( - !state.requestHandler && - !primaryPhp?.requestHandler && - primaryPhp + primaryPhp && + (request.usePrimaryPhp || + (!state.requestHandler && !primaryPhp.requestHandler)) ) { return await primaryPhp.run(request); } @@ -235,9 +235,9 @@ export class PHPWorker implements LimitedPHPApi, AsyncDisposable { const state = _private.get(this)!; const primaryPhp = state.php; if ( - !state.requestHandler && - !primaryPhp?.requestHandler && - primaryPhp + primaryPhp && + (request.usePrimaryPhp || + (!state.requestHandler && !primaryPhp.requestHandler)) ) { return await primaryPhp.runStream(request); } diff --git a/packages/php-wasm/universal/src/lib/php.spec.ts b/packages/php-wasm/universal/src/lib/php.spec.ts index cc9b3ec068d..2ade090ebd7 100644 --- a/packages/php-wasm/universal/src/lib/php.spec.ts +++ b/packages/php-wasm/universal/src/lib/php.spec.ts @@ -67,6 +67,46 @@ async function readStream(stream: ReadableStream) { } describe('PHP mounts', () => { + it('unmounts the current runtime when the same handler is reapplied', async () => { + const php = new PHP(); + (php as any)[__private__dont__use] = { FS: {} }; + const oldUnmount = vi.fn(async () => {}); + const newUnmount = vi.fn(async () => {}); + const handler = vi + .fn() + .mockResolvedValueOnce(oldUnmount) + .mockResolvedValueOnce(newUnmount); + const unmount = await php.mount('/mounted', handler); + // Runtime rotation tears down the old mount, then reapplies its handler. + await unmount(); + await php.mount('/mounted', handler); + + await unmount(); + await unmount(); + + expect(oldUnmount).toHaveBeenCalledTimes(1); + expect(newUnmount).toHaveBeenCalledTimes(1); + }); + + it('does not unmount an unrelated replacement at the same path', async () => { + const php = new PHP(); + (php as any)[__private__dont__use] = { FS: {} }; + const oldUnmount = vi.fn(async () => {}); + const newUnmount = vi.fn(async () => {}); + const unmount = await php.mount('/mounted', async () => oldUnmount); + await unmount(); + const unmountReplacement = await php.mount( + '/mounted', + async () => newUnmount + ); + + await unmount(); + expect(oldUnmount).toHaveBeenCalledTimes(1); + expect(newUnmount).not.toHaveBeenCalled(); + await unmountReplacement(); + expect(newUnmount).toHaveBeenCalledTimes(1); + }); + it('forgets mount tracking even when the unmount callback fails', async () => { // `PHP#mount` stores each mount in the private `#mounts` map and // returns a thin wrapper that: diff --git a/packages/php-wasm/universal/src/lib/php.ts b/packages/php-wasm/universal/src/lib/php.ts index 338eff7d22f..50a3d68160b 100644 --- a/packages/php-wasm/universal/src/lib/php.ts +++ b/packages/php-wasm/universal/src/lib/php.ts @@ -1672,7 +1672,15 @@ export class PHP implements Disposable { }, }; this.#mounts[virtualFSPath] = mountObject; - return () => mountObject.unmount(); + return async () => { + // Runtime rotation reapplies the handler with a new teardown callback. + // Follow that replacement, but never detach an unrelated mount that + // later reused this path with a different handler. + const currentMount = this.#mounts[virtualFSPath]; + if (currentMount?.mountHandler === mountHandler) { + await currentMount.unmount(); + } + }; } /** diff --git a/packages/php-wasm/universal/src/lib/universal-php.ts b/packages/php-wasm/universal/src/lib/universal-php.ts index 2f2af232ff6..1db66225f56 100644 --- a/packages/php-wasm/universal/src/lib/universal-php.ts +++ b/packages/php-wasm/universal/src/lib/universal-php.ts @@ -176,6 +176,17 @@ export interface PHPRunOptions { * The code snippet to eval instead of a php file. */ code?: string; + + /** + * Run on the primary PHP instance instead of any pooled instance. + * + * Pooled instances see shared paths through a proxy filesystem whose + * node cache is not invalidated when the primary deletes a file. A job + * that spans several runs and rewrites its own state files must stay on + * the primary so every run sees the same filesystem. The run waits for + * the primary to become free. + */ + usePrimaryPhp?: boolean; } /** diff --git a/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js b/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js index 917748e4828..89e08f903be 100644 --- a/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js +++ b/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js @@ -6537,8 +6537,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js b/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js index ced12cf49cb..bd786bffe54 100644 --- a/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js +++ b/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js @@ -6490,8 +6490,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js b/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js index 7891810719d..59c515505f9 100644 --- a/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js +++ b/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js @@ -6552,8 +6552,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js b/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js index 232c871a86d..44a18349639 100644 --- a/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js +++ b/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js @@ -6505,8 +6505,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js b/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js index 3af834717a3..f4bc9ed1dbd 100644 --- a/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js +++ b/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js @@ -6552,8 +6552,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js b/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js index 940f49318c9..bceafa0d34f 100644 --- a/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js +++ b/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js @@ -6505,8 +6505,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js b/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js index fe311730ccd..4f0a4e884a5 100644 --- a/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js +++ b/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js @@ -6562,8 +6562,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js b/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js index e66c02ea686..ebb27f42273 100644 --- a/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js +++ b/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js @@ -6515,8 +6515,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js b/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js index 5f62125b2a3..09c0595430a 100644 --- a/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js +++ b/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js @@ -6562,8 +6562,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js b/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js index 62363193c83..6bdf5de6a9f 100644 --- a/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js +++ b/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js @@ -6515,8 +6515,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js b/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js index 1cee6ef1bfe..1391aa42c14 100644 --- a/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js +++ b/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js @@ -6562,8 +6562,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js b/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js index e47065455e9..07a167b9c82 100644 --- a/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js +++ b/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js @@ -6515,8 +6515,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js b/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js index 1e8501d34dd..145c7a2e3db 100644 --- a/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js +++ b/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js @@ -6562,8 +6562,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js b/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js index 47174e83015..a61c04716ec 100644 --- a/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js +++ b/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js @@ -6515,8 +6515,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js b/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js index 3b06bfe39a7..d34caff98df 100644 --- a/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js +++ b/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js @@ -6562,8 +6562,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js b/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js index b65a2b592b2..d32d1eb554a 100644 --- a/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js +++ b/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js @@ -6515,8 +6515,22 @@ export function init(RuntimeName, PHPLoader) { callUserCallback(func); }, timeout); }; - var _emscripten_sleep = (ms) => - Asyncify.handleSleep((wakeUp) => safeSetTimeout(wakeUp, ms)); + var _emscripten_sleep = function (ms) { + return Asyncify.handleSleep((wakeUp) => { + // select() yields between socket reads. Nested zero-delay timers are + // clamped by browsers, adding seconds to even a local curl download. + // Use a task (not a microtask) so network events still get a turn. + if (ms === 0 && globalThis.scheduler?.postTask) { + runtimeKeepalivePush(); + globalThis.scheduler.postTask(() => { + runtimeKeepalivePop(); + callUserCallback(wakeUp); + }); + } else { + safeSetTimeout(wakeUp, ms); + } + }); + }; _emscripten_sleep.sig = 'vi'; _emscripten_sleep.isAsync = true; var ENV = PHPLoader.ENV || {}; diff --git a/packages/php-wasm/web-service-worker/src/lib/fetch-with-cors-proxy.ts b/packages/php-wasm/web-service-worker/src/lib/fetch-with-cors-proxy.ts index 52e030ff692..d5b3c3cb7d8 100644 --- a/packages/php-wasm/web-service-worker/src/lib/fetch-with-cors-proxy.ts +++ b/packages/php-wasm/web-service-worker/src/lib/fetch-with-cors-proxy.ts @@ -27,6 +27,13 @@ export async function fetchWithCorsProxy( : new URL(requestObject.url); if (isLocalhost(requestUrlObj)) { + // Local PHP development servers speak HTTP/1.1. Chrome requires HTTP/2 + // for a streaming upload, even when the entire body is already available. + if (requestUrlObj.protocol === 'http:' && requestObject.body) { + requestObject = await cloneRequest(requestObject, { + body: await readBodyUntilAborted(requestObject), + }); + } return await fetch(requestObject); } @@ -157,6 +164,50 @@ export async function fetchWithCorsProxy( } } +/** + * Buffers a request body. Request.arrayBuffer() ignores the request's abort + * signal, so a body stream that never closes would keep the fetch pending + * forever; this reader stops as soon as the signal aborts. + */ +async function readBodyUntilAborted(request: Request): Promise { + const { signal } = request; + const abortError = () => + signal.reason ?? + new DOMException('The request was aborted.', 'AbortError'); + if (signal.aborted) { + throw abortError(); + } + const reader = request.body!.getReader(); + const cancel = () => { + reader.cancel(signal.reason).catch(() => {}); + }; + signal.addEventListener('abort', cancel, { once: true }); + const chunks: Uint8Array[] = []; + let length = 0; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) { + break; + } + chunks.push(value); + length += value.byteLength; + } + } finally { + signal.removeEventListener('abort', cancel); + } + if (signal.aborted) { + throw abortError(); + } + const body = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + body.set(chunk, offset); + offset += chunk.byteLength; + } + return body.buffer; +} + function isLocalhost(url: URL) { return ( url.hostname === 'localhost' || diff --git a/packages/php-wasm/web-service-worker/src/lib/utils.ts b/packages/php-wasm/web-service-worker/src/lib/utils.ts index e08c9d5f4ec..161aa94660c 100644 --- a/packages/php-wasm/web-service-worker/src/lib/utils.ts +++ b/packages/php-wasm/web-service-worker/src/lib/utils.ts @@ -240,6 +240,7 @@ export async function cloneRequest( } return new Request(overrides['url'] || request.url, { + signal: request.signal, body, method: request.method, headers: request.headers, diff --git a/packages/php-wasm/web-service-worker/src/test/fetch-with-cors-proxy.spec.ts b/packages/php-wasm/web-service-worker/src/test/fetch-with-cors-proxy.spec.ts index c279845b73a..bc5a55a6aca 100644 --- a/packages/php-wasm/web-service-worker/src/test/fetch-with-cors-proxy.spec.ts +++ b/packages/php-wasm/web-service-worker/src/test/fetch-with-cors-proxy.spec.ts @@ -247,7 +247,7 @@ describe('fetchWithCorsProxy', () => { expect(request.url).toBe('http://localhost:1234/v1/chat/completions'); }); - it('passes request through to fetch for localhost http:// URLs', async () => { + it('buffers streamed uploads to localhost HTTP/1.1 servers', async () => { const fetchMock = vi .spyOn(globalThis, 'fetch') .mockResolvedValue(new Response('ok')); @@ -269,9 +269,35 @@ describe('fetchWithCorsProxy', () => { expect(fetchMock).toHaveBeenCalledTimes(1); const sentRequest = fetchMock.mock.calls[0][0] as Request; - // Direct fetch — no buffering, same Request passed through. - expect(sentRequest).toBe(request); - expect(request.bodyUsed).toBe(false); + // Buffer before direct fetch: Chrome cannot stream to an HTTP/1.1 server. + expect(sentRequest).not.toBe(request); + expect(sentRequest.url).toBe(request.url); + expect(sentRequest.method).toBe('POST'); + expect(await sentRequest.text()).toBe('streamed data'); + expect(request.bodyUsed).toBe(true); + }); + + it('stops buffering a localhost upload whose body never closes when aborted', async () => { + const fetchMock = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response('ok')); + const controller = new AbortController(); + const request = new Request('http://127.0.0.1:8181/?reprint-api', { + method: 'POST', + body: new ReadableStream({ + start(stream) { + stream.enqueue(new TextEncoder().encode('partial')); + // Never closes: a stalled producer. + }, + }), + signal: controller.signal, + // @ts-expect-error duplex is required for streamed bodies. + duplex: 'half', + }); + const pending = fetchWithCorsProxy(request, undefined, undefined); + setTimeout(() => controller.abort(), 10); + await expect(pending).rejects.toMatchObject({ name: 'AbortError' }); + expect(fetchMock).not.toHaveBeenCalled(); }); it('passes request through to fetch for https:// URLs without proxy', async () => { diff --git a/packages/php-wasm/web-service-worker/src/test/utils.spec.ts b/packages/php-wasm/web-service-worker/src/test/utils.spec.ts index a0e421740c8..3b551c1a2f3 100644 --- a/packages/php-wasm/web-service-worker/src/test/utils.spec.ts +++ b/packages/php-wasm/web-service-worker/src/test/utils.spec.ts @@ -6,6 +6,18 @@ import { } from '../lib/utils'; describe('cloneRequest', () => { + it('keeps cancellation when rewriting a request URL for the proxy', async () => { + const controller = new AbortController(); + const request = new Request('https://example.com', { + signal: controller.signal, + }); + const cloned = await cloneRequest(request, { + url: 'https://proxy.example/?https://example.com', + }); + expect(cloned.signal.aborted).toBe(false); + controller.abort(); + expect(cloned.signal.aborted).toBe(true); + }); it('should clone request headers', async () => { const request = new Request('http://localhost', { headers: { diff --git a/packages/php-wasm/web/src/lib/directory-handle-mount.spec.ts b/packages/php-wasm/web/src/lib/directory-handle-mount.spec.ts index 3e3e28bdae1..0e275929fcb 100644 --- a/packages/php-wasm/web/src/lib/directory-handle-mount.spec.ts +++ b/packages/php-wasm/web/src/lib/directory-handle-mount.spec.ts @@ -83,6 +83,95 @@ class MemoryDirectoryHandle { } } +describe('loading saved OPFS files', () => { + it('bounds queued reads as well as active reads for large directories', async () => { + const { FS, php } = createFakePhp(); + FS.lookupPath.mockImplementation(() => { + throw new Error('Not mounted yet'); + }); + const releaseReads = deferred(); + const createDataFile = vi.fn(); + let enumerated = 0; + const root = { + async *values() { + for (let i = 0; i < 200; i++) { + enumerated++; + yield { + kind: 'file', + name: `file-${i}`, + async getFile() { + await releaseReads.promise; + return new Blob(['saved']); + }, + }; + } + }, + } as unknown as FileSystemDirectoryHandle; + const mount = createDirectoryHandleMountHandler(root); + const copy = mount(php, { ...FS, createDataFile } as any, '/wordpress'); + try { + await vi.waitFor(() => + expect(enumerated).toBeGreaterThanOrEqual(40) + ); + // One entry may be waiting for a slot. The rest must stay in the + // directory iterator instead of accumulating pending promises. + expect(enumerated).toBeLessThanOrEqual(41); + } finally { + releaseReads.resolve(); + await copy; + } + expect(createDataFile).toHaveBeenCalledTimes(200); + }); + it('reports a read failure after draining outstanding reads', async () => { + const { FS, php } = createFakePhp(); + FS.lookupPath.mockImplementation(() => { + throw new Error('Not mounted yet'); + }); + const releaseRead = deferred(); + const failedRead = new Error('Cannot read saved file'); + const createDataFile = vi.fn(); + const onMount = vi.fn(); + const root = { + async *values() { + yield { + kind: 'file', + name: 'slow', + getFile: async () => { + await releaseRead.promise; + return new Blob(['saved']); + }, + }; + yield { + kind: 'file', + name: 'broken', + getFile: async () => { + throw failedRead; + }, + }; + }, + } as unknown as FileSystemDirectoryHandle; + let settled = false; + const copy = createDirectoryHandleMountHandler(root, { + initialSync: {}, + onMount, + })(php, { ...FS, createDataFile } as any, '/wordpress'); + void Promise.resolve(copy).then( + () => { + settled = true; + }, + () => { + settled = true; + } + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(settled).toBe(false); + releaseRead.resolve(); + await expect(copy).rejects.toBe(failedRead); + expect(createDataFile).toHaveBeenCalledTimes(1); + expect(onMount).not.toHaveBeenCalled(); + }); +}); + describe('journalFSEventsToOpfs', () => { it('flushes pending journaled file changes to OPFS', async () => { const { FS, files, php } = createFakePhp(); @@ -386,6 +475,38 @@ describe('journalFSEventsToOpfs', () => { loggerError.mockRestore(); }); + it('preserves a quota failure when the errored stream also rejects cleanup', async () => { + const { FS, files, php } = createFakePhp(); + const opfsRoot = new MemoryDirectoryHandle('root'); + const file = await opfsRoot.getFileHandle('file.txt', { create: true }); + const failure = new DOMException( + 'Browser storage is full', + 'QuotaExceededError' + ); + const abort = vi + .fn() + .mockRejectedValue(new TypeError('Stream is errored')); + vi.spyOn(file, 'createWritable').mockResolvedValue({ + truncate: vi.fn().mockResolvedValue(undefined), + write: vi.fn().mockRejectedValue(failure), + close: vi + .fn() + .mockRejectedValue( + new TypeError('Cannot close an errored stream') + ), + abort, + } as unknown as FileSystemWritableFileStream); + const mount = journalFSEventsToOpfs( + php, + opfsRoot as unknown as FileSystemDirectoryHandle, + '/wordpress' + ); + files.set('/wordpress/file.txt', encode('saved')); + FS.write({ path: '/wordpress/file.txt' }); + await expect(mount.flush()).rejects.toBe(failure); + expect(abort).toHaveBeenCalledOnce(); + }); + it('can retry after a failed explicit flush', async () => { let failNextWrite = true; const { FS, files, php } = createFakePhp(); diff --git a/packages/php-wasm/web/src/lib/directory-handle-mount.ts b/packages/php-wasm/web/src/lib/directory-handle-mount.ts index 720ed8d96b7..4d902191e27 100644 --- a/packages/php-wasm/web/src/lib/directory-handle-mount.ts +++ b/packages/php-wasm/web/src/lib/directory-handle-mount.ts @@ -161,51 +161,74 @@ async function copyOpfsToMemfs( }); const ops: Array> = []; + let copyError: unknown; const stack: Array<[FileSystemDirectoryHandle, string]> = [ [opfsRoot, memfsRoot], ]; - while (stack.length > 0) { - const [opfsParent, memfsParentPath] = stack.pop()!; - - for await (const opfsHandle of opfsParent.values()) { - const op = semaphore.run(async () => { - const memfsEntryPath = joinPaths( - memfsParentPath, - opfsHandle.name - ); - if (opfsHandle.kind === 'directory') { - try { - FS.mkdir(memfsEntryPath); - } catch (e) { - if ((e as any)?.errno !== 20) { - logger.error(e); - // We ignore the error if the directory already exists, - // and throw otherwise. - throw e; - } - } - stack.push([opfsHandle, memfsEntryPath]); - } else if (opfsHandle.kind === 'file') { - const file = await opfsHandle.getFile(); - const byteArray = new Uint8Array(await file.arrayBuffer()); - FS.createDataFile( + try { + while (stack.length > 0) { + const [opfsParent, memfsParentPath] = stack.pop()!; + + for await (const opfsHandle of opfsParent.values()) { + // Acquire before creating the promise. Queuing the entire site then + // repeatedly awaiting Promise.any(ops) attaches callbacks to every + // queued read and can exhaust the JS heap on large saved sites. + const release = await semaphore.acquire(); + if (copyError !== undefined) { + release(); + throw copyError; + } + const op = (async () => { + const memfsEntryPath = joinPaths( memfsParentPath, - opfsHandle.name, - byteArray, - true, - true, - true + opfsHandle.name ); - } - ops.splice(ops.indexOf(op), 1); - }); - ops.push(op); - } - // Let the ongoing operations catch-up to the stack. - while (stack.length === 0 && ops.length > 0) { - await Promise.any(ops); + if (opfsHandle.kind === 'directory') { + try { + FS.mkdir(memfsEntryPath); + } catch (e) { + if ((e as any)?.errno !== 20) { + logger.error(e); + // We ignore the error if the directory already exists, + // and throw otherwise. + throw e; + } + } + stack.push([opfsHandle, memfsEntryPath]); + } else if (opfsHandle.kind === 'file') { + const file = await opfsHandle.getFile(); + const byteArray = new Uint8Array( + await file.arrayBuffer() + ); + FS.createDataFile( + memfsParentPath, + opfsHandle.name, + byteArray, + true, + true, + true + ); + } + })() + .catch((error) => { + copyError ??= error; + }) + .finally(() => { + ops.splice(ops.indexOf(op), 1); + release(); + }); + ops.push(op); + } + // Let the ongoing operations catch-up to the stack. + while (stack.length === 0 && ops.length > 0) { + await Promise.any(ops); + } } + } finally { + // Finish outstanding reads before a failed mount can be retried. + await Promise.all(ops); } + if (copyError !== undefined) throw copyError; } export async function copyMemfsToOpfs( @@ -364,9 +387,18 @@ async function overwriteOpfsFile( try { await writer.truncate(0); await writer.write(buffer); - } finally { - await writer.close(); + } catch (error) { + // A failed write can leave the stream errored. Closing it would hide + // the useful cause (for example, exceeded storage quota) behind a TypeError. + try { + if ('abort' in writer) await writer.abort(); + else await writer.close(); + } catch { + // Preserve the write failure even if cleanup also fails. + } + throw error; } + await writer.close(); } /** diff --git a/packages/playground/blueprints/public/blueprint-schema-validator.js b/packages/playground/blueprints/public/blueprint-schema-validator.js index 4fa1dd31bb6..0a667b81a22 100644 --- a/packages/playground/blueprints/public/blueprint-schema-validator.js +++ b/packages/playground/blueprints/public/blueprint-schema-validator.js @@ -1516,6 +1516,11 @@ const schema11 = { description: 'The code snippet to eval instead of a php file.', }, + usePrimaryPhp: { + type: 'boolean', + description: + 'Run on the primary PHP instance instead of any pooled instance.\n\nPooled instances see shared paths through a proxy filesystem whose node cache is not invalidated when the primary deletes a file. A job that spans several runs and rewrites its own state files must stay on the primary so every run sees the same filesystem. The run waits for the primary to become free.', + }, }, additionalProperties: false, }, @@ -7786,6 +7791,11 @@ const schema39 = { type: 'string', description: 'The code snippet to eval instead of a php file.', }, + usePrimaryPhp: { + type: 'boolean', + description: + 'Run on the primary PHP instance instead of any pooled instance.\n\nPooled instances see shared paths through a proxy filesystem whose node cache is not invalidated when the primary deletes a file. A job that spans several runs and rewrites its own state files must stay on the primary so every run sees the same filesystem. The run waits for the primary to become free.', + }, }, additionalProperties: false, }; @@ -8804,6 +8814,41 @@ function validate39( } else { var valid0 = true; } + if (valid0) { + if ( + data.usePrimaryPhp !== + undefined + ) { + const _errs51 = errors; + if ( + typeof data.usePrimaryPhp !== + 'boolean' + ) { + validate39.errors = + [ + { + instancePath: + instancePath + + '/usePrimaryPhp', + schemaPath: + '#/properties/usePrimaryPhp/type', + keyword: + 'type', + params: { + type: 'boolean', + }, + message: + 'must be boolean', + }, + ]; + return false; + } + var valid0 = + _errs51 === errors; + } else { + var valid0 = true; + } + } } } } diff --git a/packages/playground/blueprints/public/blueprint-schema.json b/packages/playground/blueprints/public/blueprint-schema.json index 824034d4262..044c51a2446 100644 --- a/packages/playground/blueprints/public/blueprint-schema.json +++ b/packages/playground/blueprints/public/blueprint-schema.json @@ -1852,6 +1852,10 @@ "code": { "type": "string", "description": "The code snippet to eval instead of a php file." + }, + "usePrimaryPhp": { + "type": "boolean", + "description": "Run on the primary PHP instance instead of any pooled instance.\n\nPooled instances see shared paths through a proxy filesystem whose node cache is not invalidated when the primary deletes a file. A job that spans several runs and rewrites its own state files must stay on the primary so every run sees the same filesystem. The run waits for the primary to become free." } }, "additionalProperties": false @@ -2316,13 +2320,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -2739,13 +2743,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -3151,13 +3155,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -3297,13 +3301,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -3840,13 +3844,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -3988,13 +3992,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -4292,13 +4296,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -4541,13 +4545,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] @@ -4844,7 +4848,7 @@ ], "description": "Plugin directory reference, e.g. \"jetpack\", \"jetpack@6.4\", or \"akismet@6.4.3\".\n\nThese refer to a specific plugin slugs in the WordPress.org plugin repository.\n\nFor example, a reference to \"wordpress-seo\" means the Yoast SEO plugin as seen on https://wordpress.org/plugins/wordpress-seo/.\n\nThe Plugin Directory Reference are only meaningful in:\n\n* The top-level `plugins` array\n* The `installPlugin` imperative step" }, - "alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177": { + "alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608": { "anyOf": [ { "type": "string" @@ -4858,13 +4862,13 @@ { "type": "array", "items": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } }, { "type": "object", "additionalProperties": { - "$ref": "#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177" + "$ref": "#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608" } } ] diff --git a/packages/playground/blueprints/public/blueprint-v2-schema-validator.js b/packages/playground/blueprints/public/blueprint-v2-schema-validator.js index a89b8fb14f8..c53c475300b 100644 --- a/packages/playground/blueprints/public/blueprint-v2-schema-validator.js +++ b/packages/playground/blueprints/public/blueprint-v2-schema-validator.js @@ -400,13 +400,13 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -869,14 +869,14 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -1325,14 +1325,14 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -1499,14 +1499,14 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -2079,14 +2079,14 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -2273,14 +2273,14 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -2599,13 +2599,13 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -2830,13 +2830,13 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -3097,7 +3097,7 @@ const schema11 = { description: 'Plugin directory reference, e.g. "jetpack", "jetpack@6.4", or "akismet@6.4.3".\n\nThese refer to a specific plugin slugs in the WordPress.org plugin repository.\n\nFor example, a reference to "wordpress-seo" means the Yoast SEO plugin as seen on https://wordpress.org/plugins/wordpress-seo/.\n\nThe Plugin Directory Reference are only meaningful in:\n\n* The top-level `plugins` array\n* The `installPlugin` imperative step', }, - 'alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177': + 'alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608': { anyOf: [ { type: 'string' }, @@ -3106,13 +3106,13 @@ const schema11 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -3510,13 +3510,13 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -3973,13 +3973,13 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -4392,14 +4392,14 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -4562,14 +4562,14 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -5090,14 +5090,14 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -5282,14 +5282,14 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -5579,13 +5579,13 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -5789,13 +5789,13 @@ const schema12 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], @@ -7098,13 +7098,13 @@ const schema37 = { { type: 'array', items: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, { type: 'object', additionalProperties: { - $ref: '#/definitions/alias-1337903113-151756-151850-1337903113-103902-151864-1337903113-103868-151864-1337903113-0-169177', + $ref: '#/definitions/alias-1337903113-152187-152281-1337903113-104333-152295-1337903113-104299-152295-1337903113-0-169608', }, }, ], diff --git a/packages/playground/remote/src/lib/offline-mode-cache.spec.ts b/packages/playground/remote/src/lib/offline-mode-cache.spec.ts new file mode 100644 index 00000000000..9d0879be4fc --- /dev/null +++ b/packages/playground/remote/src/lib/offline-mode-cache.spec.ts @@ -0,0 +1,27 @@ +import type * as OfflineCache from './offline-mode-cache'; + +vi.mock('virtual:remote-config', () => ({ buildVersion: 'test' })); + +describe('offline asset scope', () => { + let shouldCacheUrl: typeof OfflineCache.shouldCacheUrl; + beforeAll(async () => { + vi.stubGlobal('caches', { open: vi.fn().mockResolvedValue({}) }); + vi.stubGlobal('self', { + location: new URL('https://playground.test:9443'), + }); + ({ shouldCacheUrl } = await import('./offline-mode-cache')); + }); + afterAll(() => vi.unstubAllGlobals()); + + it('does not replay API responses from a WordPress site on another port', () => { + expect( + shouldCacheUrl(new URL('https://playground.test:9443/app.js')) + ).toBe(true); + expect( + shouldCacheUrl(new URL('https://playground.test:9417/?reprint-api')) + ).toBe(false); + expect( + shouldCacheUrl(new URL('http://playground.test:9443/?reprint-api')) + ).toBe(false); + }); +}); diff --git a/packages/playground/remote/src/lib/offline-mode-cache.ts b/packages/playground/remote/src/lib/offline-mode-cache.ts index 9ab7a622e0f..ebff93ceb88 100644 --- a/packages/playground/remote/src/lib/offline-mode-cache.ts +++ b/packages/playground/remote/src/lib/offline-mode-cache.ts @@ -206,9 +206,10 @@ export function shouldCacheUrl(url: URL) { } /** - * Allow only requests to the same hostname to be cached. + * Cache only this origin. Another port can serve a live WordPress site, + * whose API responses must not be replayed as Playground assets. */ - return self.location.hostname === url.hostname; + return self.location.origin === url.origin; } /** diff --git a/packages/playground/remote/src/lib/playground-worker-endpoint.spec.ts b/packages/playground/remote/src/lib/playground-worker-endpoint.spec.ts index 7e0440d14d1..f8d49dc4b52 100644 --- a/packages/playground/remote/src/lib/playground-worker-endpoint.spec.ts +++ b/packages/playground/remote/src/lib/playground-worker-endpoint.spec.ts @@ -4,6 +4,7 @@ import { MountStillActiveError, } from '@php-wasm/universal'; import type { MountHandler } from '@php-wasm/universal'; +import type { SyncProgressCallback } from '@php-wasm/web'; import { Semaphore } from '@php-wasm/util'; describe('PlaygroundWorkerEndpoint OPFS flushing', () => { @@ -32,6 +33,43 @@ describe('PlaygroundWorkerEndpoint OPFS flushing', () => { ); }, 15_000); + it.each(['copy', 'progress'])( + 'allows another save after initial %s fails', + async (failureStage) => { + const endpoint = await createEndpoint({}); + const php = createFakePhp(); + endpoint.__internal_getPHP = () => php; + const failure = new Error('Initial save failed'); + const onProgress = vi.fn(); + if (failureStage === 'copy') { + php[__private__dont__use].FS.readdir.mockImplementationOnce( + () => { + throw failure; + } + ); + } else { + onProgress.mockRejectedValueOnce(failure); + } + const options = { + device: { + type: 'local-fs' as const, + handle: createEmptyDirectoryHandle(), + }, + mountpoint: '/wordpress', + initialSyncDirection: 'memfs-to-opfs' as const, + }; + + await expect(endpoint.mountOpfs(options, onProgress)).rejects.toBe( + failure + ); + expect(await endpoint.hasOpfsMount('/wordpress')).toBe(false); + await endpoint.mountOpfs(options, onProgress); + expect(await endpoint.hasOpfsMount('/wordpress')).toBe(true); + await endpoint.unmountOpfs('/wordpress'); + expect(await endpoint.hasOpfsMount('/wordpress')).toBe(false); + } + ); + it('flushes the active OPFS mount', async () => { const endpoint = await createEndpoint({ '/wordpress': createOpfsMount(), @@ -44,6 +82,107 @@ describe('PlaygroundWorkerEndpoint OPFS flushing', () => { ); }); + it('flushes the replacement journal after PHP runtime rotation', async () => { + const endpoint = await createEndpoint({}); + const php = createFakePhp(); + endpoint.__internal_getPHP = () => php; + await endpoint.mountOpfs({ + device: { type: 'local-fs', handle: createEmptyDirectoryHandle() }, + mountpoint: '/wordpress', + }); + const oldMount = endpoint.opfsMounts['/wordpress']; + const oldFlush = vi.spyOn(oldMount, 'flush'); + // PHP reuses the mount handler when it creates a fresh runtime. Checking + // a normal second flush would miss the stale endpoint reference. + const handler = php.mount.mock.calls[0][1]; + await oldMount.unmount(); + await php.mount('/wordpress', handler); + const replacement = endpoint.opfsMounts['/wordpress']; + expect(replacement).not.toBe(oldMount); + const newFlush = vi.spyOn(replacement, 'flush'); + await endpoint.flushOpfs('/wordpress'); + expect(newFlush).toHaveBeenCalledTimes(1); + expect(oldFlush).not.toHaveBeenCalled(); + }); + + it.each(['copy', 'progress'])( + 'allows another save after replacement %s fails during runtime rotation', + async (failureStage) => { + const endpoint = await createEndpoint({}); + const php = createFakePhp(); + endpoint.__internal_getPHP = () => php; + const onProgress = vi.fn(); + const options = { + device: { + type: 'local-fs' as const, + handle: createEmptyDirectoryHandle(), + }, + mountpoint: '/wordpress', + initialSyncDirection: 'memfs-to-opfs' as const, + }; + await endpoint.mountOpfs(options, onProgress); + const handler = php.mount.mock.calls[0][1]; + // Rotation detaches the old journal before trying to set up its replacement. + await endpoint.opfsMounts['/wordpress'].unmount(); + const failure = new Error('Replacement save failed'); + if (failureStage === 'copy') { + php[__private__dont__use].FS.readdir.mockImplementationOnce( + () => { + throw failure; + } + ); + } else { + onProgress.mockRejectedValueOnce(failure); + } + + await expect(php.mount('/wordpress', handler)).rejects.toBe( + failure + ); + expect(await endpoint.hasOpfsMount('/wordpress')).toBe(false); + expect(endpoint.unmounts['/wordpress']).toBeUndefined(); + await expect(endpoint.flushOpfs('/wordpress')).rejects.toThrow( + 'No OPFS mount found' + ); + await endpoint.mountOpfs(options, onProgress); + await endpoint.flushOpfs('/wordpress'); + await endpoint.unmountOpfs('/wordpress'); + } + ); + + it('does not expose a replacement journal until its initial copy completes', async () => { + const endpoint = await createEndpoint({}); + const php = createFakePhp(); + endpoint.__internal_getPHP = () => php; + const onProgress = vi.fn(); + await endpoint.mountOpfs( + { + device: { + type: 'local-fs', + handle: createEmptyDirectoryHandle(), + }, + mountpoint: '/wordpress', + initialSyncDirection: 'memfs-to-opfs', + }, + onProgress + ); + const oldMount = endpoint.opfsMounts['/wordpress']; + const handler = php.mount.mock.calls[0][1]; + await oldMount.unmount(); + onProgress.mockClear(); + onProgress.mockImplementationOnce(async () => { + expect(await endpoint.hasOpfsMount('/wordpress')).toBe(false); + await expect(endpoint.flushOpfs('/wordpress')).rejects.toThrow( + 'No OPFS mount found' + ); + }); + + await php.mount('/wordpress', handler); + + expect(onProgress).toHaveBeenCalled(); + expect(endpoint.opfsMounts['/wordpress']).not.toBe(oldMount); + await endpoint.flushOpfs('/wordpress'); + }); + it('reports whether an OPFS mount is active', async () => { const endpoint = await createEndpoint({ '/wordpress': createOpfsMount(), @@ -246,13 +385,17 @@ async function createEndpoint( return endpoint as { __internal_getPHP?: () => ReturnType; hasOpfsMount(mountpoint: string): Promise; - mountOpfs(options: { - device: { - type: 'local-fs'; - handle: FileSystemDirectoryHandle; - }; - mountpoint: string; - }): Promise; + mountOpfs( + options: { + device: { + type: 'local-fs'; + handle: FileSystemDirectoryHandle; + }; + mountpoint: string; + initialSyncDirection?: 'opfs-to-memfs' | 'memfs-to-opfs'; + }, + onProgress?: SyncProgressCallback + ): Promise; flushOpfs(mountpoint: string): Promise; unmountOpfs(mountpoint: string): Promise; opfsMounts: typeof opfsMounts; @@ -273,6 +416,7 @@ function createOpfsMount() { function createFakePhp(options: { skipMountHandler?: boolean } = {}) { const FS = { + readdir: vi.fn(() => ['.', '..']), write: vi.fn(), truncate: vi.fn(), unlink: vi.fn(), diff --git a/packages/playground/remote/src/lib/playground-worker-endpoint.ts b/packages/playground/remote/src/lib/playground-worker-endpoint.ts index 3d6cff02383..6504445674a 100644 --- a/packages/playground/remote/src/lib/playground-worker-endpoint.ts +++ b/packages/playground/remote/src/lib/playground-worker-endpoint.ts @@ -632,18 +632,33 @@ export abstract class PlaygroundWorkerEndpoint extends PHPWorker { } const handle = await directoryHandleFromMountDevice(options.device); let opfsMount: DirectoryHandleMount | undefined; - const unmount = await php.mount( - options.mountpoint, - createDirectoryHandleMountHandler(handle, { - initialSync: { - onProgress, - direction: options.initialSyncDirection, - }, - onMount(mount) { - opfsMount = mount; - }, - }) - ); + const mountHandler = createDirectoryHandleMountHandler(handle, { + initialSync: { + onProgress, + direction: options.initialSyncDirection, + }, + onMount: (mount) => { + opfsMount = mount; + }, + }); + const unmount = await php.mount(options.mountpoint, async (...args) => { + // Runtime rotation invokes this handler again after detaching the old + // journal. Explicit flushes must use the replacement, but only after + // initial sync succeeds: a failed copy discards its journal and must + // allow another save, whether this is the first mount or a replacement. + delete this.opfsMounts[options.mountpoint]; + opfsMount = undefined; + try { + const unmount = await mountHandler(...args); + if (opfsMount !== undefined) { + this.opfsMounts[options.mountpoint] = opfsMount; + } + return unmount; + } catch (error) { + delete this.unmounts[options.mountpoint]; + throw error; + } + }); if (opfsMount === undefined) { try { await unmount(); @@ -655,7 +670,6 @@ export abstract class PlaygroundWorkerEndpoint extends PHPWorker { ); } this.unmounts[options.mountpoint] = unmount; - this.opfsMounts[options.mountpoint] = opfsMount; } } diff --git a/packages/playground/website/playwright/e2e/php-code-snippet.spec.ts b/packages/playground/website/playwright/e2e/php-code-snippet.spec.ts index b192d6bc2b0..d8d1e4600eb 100644 --- a/packages/playground/website/playwright/e2e/php-code-snippet.spec.ts +++ b/packages/playground/website/playwright/e2e/php-code-snippet.spec.ts @@ -16,7 +16,6 @@ const DEMO_URL = './php-code-snippet-e2e.html'; const DOCS_URL = 'https://wordpress.github.io/wordpress-playground/guides/php-code-snippets/'; const CLIENT_INDEX_SOURCE = `${process.cwd()}/packages/playground/client/src/index.ts`; -const TOOLKIT_AUTOLOAD_SOURCE = `${process.cwd()}/packages/playground/website/public/php-toolkit-autoload.txt`; const pageErrors = new WeakMap(); test.describe('php-code-snippet embed', () => { @@ -36,7 +35,7 @@ test.describe('php-code-snippet embed', () => { }); test('renders all snippets with Run buttons', async ({ page }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); await waitForPhpSnippetDefinition(page); for (const name of [ 'hello.php', @@ -69,7 +68,7 @@ test.describe('php-code-snippet embed', () => { }); test('decodes JSON-encoded child payloads', async ({ page }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); await waitForPhpSnippetDefinition(page); await page.evaluate(() => { document.body.insertAdjacentHTML( @@ -100,7 +99,7 @@ test.describe('php-code-snippet embed', () => { test('rejects JSON child payloads that are not strings', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); await waitForPhpSnippetDefinition(page); const rejected = await page.evaluate(async () => { @@ -147,7 +146,7 @@ test.describe('php-code-snippet embed', () => { test('runs snippets with implicit opening tags and real filenames', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); await waitForPhpSnippetDefinition(page); await page.evaluate(() => { document.body.insertAdjacentHTML( @@ -212,7 +211,7 @@ test.describe('php-code-snippet embed', () => { test('rejects missing prepended scripts and explicit opening tags before boot', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); await waitForPhpSnippetDefinition(page); await page.evaluate(() => { document.body.insertAdjacentHTML( @@ -266,7 +265,7 @@ test.describe('php-code-snippet embed', () => { test('runnable snippets are editable by default unless readonly', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const defaultEditable = await waitForRenderedPhpSnippet( page, 'php-snippet[name="hello.php"]' @@ -310,7 +309,7 @@ test.describe('php-code-snippet embed', () => { test('runnable=false renders a read-only snippet without Run', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const snippet = page.locator('php-snippet[name="illustration.php"]'); await expect(snippet).toBeVisible(); @@ -327,7 +326,7 @@ test.describe('php-code-snippet embed', () => { test('wp=none progress copy says runtime instead of WordPress', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const phpOnly = page.locator('php-snippet[name="just-php.php"]'); const withWordPress = page.locator('php-snippet[name="hello.php"]'); @@ -352,7 +351,7 @@ test.describe('php-code-snippet embed', () => { test('Run button width stays stable across progress labels', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); const runButton = editable.locator('.run'); @@ -373,7 +372,7 @@ test.describe('php-code-snippet embed', () => { test('first Run boots the runtime and shows button progress + output', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const first = page.locator('php-snippet').nth(0); const runButton = first.locator('.run'); const runSpinner = first.locator('.run-spinner'); @@ -412,21 +411,11 @@ test.describe('php-code-snippet embed', () => { }); test('subsequent snippets reuse the shared runtime', async ({ page }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const first = page.locator('php-snippet').nth(0); const second = page.locator('php-snippet').nth(1); const third = page.locator('php-snippet').nth(2); - await ensurePlaygroundClientIsServed(page); - await page.locator('php-snippet').evaluateAll((snippets) => { - for (const snippet of snippets) { - snippet.setAttribute( - 'playground-origin', - window.location.origin - ); - } - }); - // Boot the runtime via the first snippet. await first.locator('.run').click(); await expect(first.locator('.output')).toBeVisible({ @@ -470,7 +459,7 @@ test.describe('php-code-snippet embed', () => { test('snippets sharing a blueprint share one runtime and see its mu-plugin', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const alice = page.locator('php-snippet[name="greet-alice.php"]'); const bob = page.locator('php-snippet[name="greet-bob.php"]'); @@ -495,7 +484,7 @@ test.describe('php-code-snippet embed', () => { }); test('editable snippet runs the user-typed code', async ({ page }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); const textarea = editable.locator('textarea.ta'); @@ -521,7 +510,7 @@ test.describe('php-code-snippet embed', () => { test('Run button queues clicks while a snippet is running', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); @@ -553,7 +542,7 @@ test.describe('php-code-snippet embed', () => { test('Run button starts from pointer activation even if click is canceled', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); @@ -592,7 +581,7 @@ test.describe('php-code-snippet embed', () => { test('Run button works while the code editor textarea is focused', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); @@ -661,7 +650,7 @@ test.describe('php-code-snippet embed', () => { test('Run button handles repeated mouse clicks after completion', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); @@ -698,7 +687,7 @@ test.describe('php-code-snippet embed', () => { page, browserName, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); const textarea = editable.locator('textarea.ta'); @@ -740,7 +729,7 @@ test.describe('php-code-snippet embed', () => { }); test('output refresh keeps the light result styling', async ({ page }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); @@ -780,15 +769,10 @@ test.describe('php-code-snippet embed', () => { test('wp="none" + blueprint installs a PHP toolkit usable from the snippet', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const snippet = page.locator('php-snippet[name="quickstart.php"]'); await expect(snippet).toBeVisible(); - await ensurePlaygroundClientIsServed(page); - await ensureToolkitAutoloadIsServed(page); - await snippet.evaluate((element) => { - element.setAttribute('playground-origin', window.location.origin); - }); // The snippet ships with an expected-output script that pre-fills the // output panel. Wait for the real run to execute by watching the run // button enter and exit its busy state. @@ -814,7 +798,7 @@ test.describe('php-code-snippet embed', () => { test('Run button shows progress while a snippet is running', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const editable = page.locator('php-snippet[name="scratch.php"]'); await expect(editable).toBeVisible(); const textarea = editable.locator('textarea.ta'); @@ -881,7 +865,7 @@ test.describe('php-code-snippet embed', () => { test('expected output shows before Run and is replaced by real output', async ({ page, }) => { - await page.goto(DEMO_URL); + await openSnippetDemo(page); const snippet = page.locator('php-snippet[name="precomputed.php"]'); await expect(snippet.locator('.progress')).toHaveCount(0); @@ -906,6 +890,17 @@ test.describe('php-code-snippet embed', () => { }); }); +/** Opens the fixture with the client and runtime from the build under test. */ +async function openSnippetDemo(page: Page) { + await page.goto(DEMO_URL); + await ensurePlaygroundClientIsServed(page); + await page.locator('php-snippet').evaluateAll((snippets) => { + for (const snippet of snippets) { + snippet.setAttribute('playground-origin', window.location.origin); + } + }); +} + async function ensurePlaygroundClientIsServed(page: Page) { const clientUrl = new URL('/client/index.js', page.url()).href; const response = await page.request.get(clientUrl); @@ -920,21 +915,6 @@ async function ensurePlaygroundClientIsServed(page: Page) { }); } -async function ensureToolkitAutoloadIsServed(page: Page) { - const autoloadUrl = new URL('/php-toolkit-autoload.txt', page.url()).href; - const response = await page.request.get(autoloadUrl); - if (response.ok()) { - return; - } - - await page.route(autoloadUrl, async (route) => { - await route.fulfill({ - path: TOOLKIT_AUTOLOAD_SOURCE, - contentType: 'text/plain', - }); - }); -} - async function waitForPhpSnippetDefinition(page: Page) { await page.evaluate(() => customElements.whenDefined('php-snippet')); } diff --git a/packages/playground/website/playwright/e2e/reprint-import.spec.ts b/packages/playground/website/playwright/e2e/reprint-import.spec.ts new file mode 100644 index 00000000000..d6a89fe5cfd --- /dev/null +++ b/packages/playground/website/playwright/e2e/reprint-import.spec.ts @@ -0,0 +1,210 @@ +import { test, expect } from '../playground-fixtures'; + +/** + * Clones a real WordPress site served by playwright/reprint-site/serve.sh + * into a new Playground through the UI, then checks the copy: files + * including generated thumbnails and non-ASCII paths, rewritten URLs in + * posts, options and custom tables, and the administrator session. + * + * Needs REPRINT_E2E_SITE_URL pointing at that site. CI runs it in the + * `reprint-import` group; locally, start the site first. + */ +const siteUrl = process.env.REPRINT_E2E_SITE_URL; + +test( + 'clones a live site and imports its files and database', + { tag: '@reprint-import' }, + async ({ website, browserName }) => { + test.skip(!siteUrl, 'REPRINT_E2E_SITE_URL is not set.'); + test.skip(browserName !== 'chromium', 'One browser covers the pull.'); + test.setTimeout(15 * 60_000); + + const manifest = await ( + await fetch(new URL('playground-e2e-manifest.json', siteUrl)) + ).json(); + const sourceOrigin = new URL(siteUrl!).origin; + + await website.goto('./'); + const page = website.page; + await page.waitForFunction(() => + Boolean((window as any).playgroundSites?.getClient()) + ); + // Start from a saved site so a stale address would reopen the wrong one. + const original = await page.evaluate(() => + (window as any).playgroundSites.saveInBrowser() + ); + await expect(page.getByText('Saved', { exact: true })).toBeVisible(); + await website.goto('./?site-slug=' + encodeURIComponent(original.slug)); + await page.waitForFunction(() => + Boolean((window as any).playgroundSites?.getClient()) + ); + await page + .getByRole('button', { name: 'New Playground', exact: true }) + .click(); + await page.getByRole('button', { name: 'Clone a live site' }).click(); + const pane = page.getByRole('dialog', { + name: 'Clone a WordPress site pane', + }); + await pane + .getByRole('textbox', { name: 'Live site URL', exact: true }) + .fill(siteUrl!); + await pane.getByRole('button', { name: 'Check site' }).click(); + // The key step opens only when Reprint Server answered the probe. + const key = pane.locator('input[type=password]'); + await expect(key).toBeVisible(); + await key.fill( + process.env.REPRINT_E2E_SECRET || 'playground-e2e-secret' + ); + await pane.getByRole('button', { name: 'Clone site' }).click(); + + const openSite = page.getByRole('button', { name: 'Open site' }); + await expect(openSite).toBeVisible({ timeout: 12 * 60_000 }); + await expect(page.getByText('Try resuming')).toHaveCount(0); + + const copy = await page.evaluate( + async ({ manifest, sourceOrigin }) => { + const client = (window as any).playgroundSites.getClient(); + const php = await client.run({ + code: ` get_option('home'), + 'heroContent' => get_post(${manifest.heroPost})->post_content, + 'firstContent' => get_post(${manifest.firstPost})->post_content, + 'heroMeta' => get_post_meta(${manifest.heroPost}, 'playground_e2e_gallery', true), + 'settings' => get_option('playground_e2e_settings'), + 'notes' => $wpdb->get_results('SELECT note, url FROM ${manifest.notesTable} ORDER BY id', ARRAY_A), + 'published' => (int) wp_count_posts()->publish, + 'editorName' => get_user_by('login', 'editor')->display_name, + 'thumbnailUrl' => wp_get_attachment_image_url(${manifest.attachment}, 'thumbnail'), + ]);`, + }); + // Diagnostics for CI: what the copy holds and what Reprint left behind. + const diagnostics = await client.run({ + code: `getPathname(), 29) . ' ' . $file->getSize(); + } + echo json_encode([ + 'posts' => $wpdb->get_results('SELECT ID, post_name, post_type, LENGTH(post_content) AS len FROM ' . $wpdb->posts . ' ORDER BY ID', ARRAY_A), + 'tables' => $wpdb->get_col('SHOW TABLES'), + 'db' => array_map(fn($f) => $f . ' ' . filesize($f), glob('/wordpress/wp-content/database/*')), + 'state' => $state, + ]);`, + }); + // eslint-disable-next-line no-console + console.log( + '[reprint-import] ' + diagnostics.text.slice(0, 6000) + ); + const admin = await client.request({ url: '/wp-admin/' }); + return { + db: JSON.parse(php.text), + thumbnailExists: await client.fileExists( + '/wordpress/' + manifest.thumbnail + ), + originalExists: await client.fileExists( + '/wordpress/' + manifest.original + ), + unicodeText: await client.readFileAsText( + '/wordpress/' + manifest.unicodeFile + ), + admin: { + status: admin.httpStatusCode, + text: admin.text, + }, + sourceOrigin, + }; + }, + { manifest, sourceOrigin } + ); + + // Files, including sizes WordPress generated on upload. + expect(copy.originalExists).toBe(true); + expect(copy.thumbnailExists).toBe(true); + expect(copy.unicodeText).toBe('unicode path\n'); + + // Every stored URL now points at the copy, not the live site. + expect(copy.db.home).not.toContain(sourceOrigin); + expect(copy.db.firstContent).not.toContain(sourceOrigin); + expect(copy.db.firstContent).toContain(`href="${copy.db.home}/?p=1"`); + // Shortcode URLs retain their slash escaping while using the copy, + // just like the unescaped image URL in the adjacent block. + expect(copy.db.heroContent).toContain( + `[vc_video link="${copy.db.home.replace(/\//g, '\\/')}\\/wp-content\\/uploads\\/video.mp4"]` + ); + expect(copy.db.heroContent).toContain(` tablist.clientWidth, - }; - }) - ).toEqual({ leftInset: 24, rightInset: 24, overflows: false }); const draft = newPane.locator('.cm-content'); await expect(draft).toBeFocused({ timeout: 5000 }); await draft.fill( @@ -2470,6 +2444,9 @@ test.describe('Default Playground storage', { tag: '@storage' }, () => { ) ) .toBe(true); + // Opening the subpanel moves its header until the height animation ends. + // Fixed-height panes keep their inline height after settling. + await waitForAnimationsToFinish(githubExportPane); const headingTop = await heading.evaluate( (element) => element.getBoundingClientRect().top ); @@ -3550,3 +3527,20 @@ test('should not include Google Analytics when VITE_GOOGLE_ANALYTICS_ID is not s .count(); expect(gtmScripts).toBe(0); }); + +/** + * Waits for the element's current animations to settle before measuring it. + * A resize can cancel and replace a transition, so awaiting one snapshot of + * animation.finished promises can reject before the replacement finishes. + */ +async function waitForAnimationsToFinish(element: Locator) { + await expect + .poll(() => + element.evaluate((node) => + node + .getAnimations() + .some((animation) => animation.playState === 'running') + ) + ) + .toBe(false); +} diff --git a/packages/playground/website/playwright/playwright.ci.config.ts b/packages/playground/website/playwright/playwright.ci.config.ts index 5f98e599d6f..6b6c5aaa42b 100644 --- a/packages/playground/website/playwright/playwright.ci.config.ts +++ b/packages/playground/website/playwright/playwright.ci.config.ts @@ -10,6 +10,9 @@ import playwrightConfig from './playwright.config'; * does not need to know which files contain storage tests. */ const storageTests = /@storage/; +// Pulls a real WordPress site served next to the runner; see +// playwright/reprint-site/serve.sh. Its own lane provisions that site. +const reprintImportTests = /@reprint-import/; const testGroupOptions = getTestGroupOptions(process.env.PLAYWRIGHT_TEST_GROUP); function getTestGroupOptions(testGroup: string | undefined) { @@ -18,12 +21,14 @@ function getTestGroupOptions(testGroup: string | undefined) { // Storage tests share browser-scoped OPFS, so one worker prevents // them from changing the same storage concurrently. return { grep: storageTests, workers: 1 }; + case 'reprint-import': + return { grep: reprintImportTests, workers: 1, retries: 1 }; case 'regular': - return { grepInvert: storageTests }; + return { grepInvert: /@storage|@reprint-import/ }; default: throw new Error( `Unsupported PLAYWRIGHT_TEST_GROUP: ${JSON.stringify(testGroup)}. ` + - 'Expected "regular" or "storage".' + 'Expected "regular", "storage" or "reprint-import".' ); } } diff --git a/packages/playground/website/playwright/reprint-site/seed.php b/packages/playground/website/playwright/reprint-site/seed.php new file mode 100644 index 00000000000..6a62a022b2d --- /dev/null +++ b/packages/playground/website/playwright/reprint-site/seed.php @@ -0,0 +1,105 @@ + 'image/jpeg', 'post_title' => 'Hero image', 'post_status' => 'inherit'], + $upload['file'] +); +wp_update_attachment_metadata( + $attachment_id, + wp_generate_attachment_metadata($attachment_id, $upload['file']) +); +$thumbnail_url = wp_get_attachment_image_url($attachment_id, 'thumbnail'); +$uploads = wp_get_upload_dir(); +$relative = fn(string $url) => ltrim(str_replace($uploads['baseurl'], 'wp-content/uploads', $url), '/'); + +$editor = wp_insert_user([ + 'user_login' => 'editor', + 'user_pass' => 'password', + 'user_email' => 'editor@example.com', + 'role' => 'editor', + 'display_name' => 'Zażółć Gęślą', +]); + +$posts = []; +for ($i = 1; $i <= 24; $i++) { + $posts[] = wp_insert_post([ + 'post_title' => "Entry $i: coffee, mountains and other things", + 'post_name' => "entry-$i", + 'post_status' => 'publish', + 'post_author' => $i % 3 === 0 ? $editor : 1, + 'post_content' => "

Paragraph $i links to the first entry " + . "and shows \"hero\" inline.

", + ]); +} + +// wp_insert_post() unslashes its input, so slash it to keep the backslashes +// page builders such as WPBakery store inside shortcode attributes. +$hero_post = wp_insert_post(wp_slash([ + 'post_title' => 'Hero post with an escaped shortcode URL', + 'post_name' => 'hero-post', + 'post_status' => 'publish', + 'post_content' => '[vc_row][vc_column width="1/2"][vc_video link="' + . str_replace('/', '\\/', $site_url) . '\\/wp-content\\/uploads\\/video.mp4"][/vc_column][/vc_row]' + . "\n
", +])); +set_post_thumbnail($hero_post, $attachment_id); +update_post_meta($hero_post, 'playground_e2e_gallery', [ + 'cover' => wp_get_attachment_url($attachment_id), + 'sizes' => ['thumb' => $thumbnail_url], +]); + +update_option('playground_e2e_settings', [ + 'hero' => wp_get_attachment_url($attachment_id), + 'links' => ["{$site_url}/?p={$hero_post}", "{$site_url}/feed/"], + 'label' => 'Zażółć gęślą jaźń', +]); +set_theme_mod('custom_logo', $attachment_id); + +global $wpdb; +$table = "{$wpdb->prefix}playground_e2e_notes"; +$wpdb->query("CREATE TABLE $table (id bigint unsigned NOT NULL AUTO_INCREMENT, note text NOT NULL, url text NOT NULL, PRIMARY KEY (id))"); +foreach (['first', 'second', 'third'] as $index => $note) { + $wpdb->insert($table, ['note' => $note, 'url' => "{$site_url}/?p=" . ($index + 1)]); +} + +// A file whose path is not ASCII, outside the year/month tree. +$unicode_dir = $uploads['basedir'] . '/zdjęcia'; +wp_mkdir_p($unicode_dir); +file_put_contents($unicode_dir . '/ślimak-🐌.txt', "unicode path\n"); + +echo json_encode([ + 'siteUrl' => $site_url, + 'heroPost' => $hero_post, + 'firstPost' => $posts[0], + 'attachment' => $attachment_id, + 'thumbnail' => $relative($thumbnail_url), + 'original' => $relative(wp_get_attachment_url($attachment_id)), + 'unicodeFile' => 'wp-content/uploads/zdjęcia/ślimak-🐌.txt', + 'notesTable' => $table, + 'postCount' => (int) wp_count_posts()->publish, +], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n"; diff --git a/packages/playground/website/playwright/reprint-site/serve.sh b/packages/playground/website/playwright/reprint-site/serve.sh new file mode 100755 index 00000000000..c54ebb1cda6 --- /dev/null +++ b/packages/playground/website/playwright/reprint-site/serve.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Provisions a WordPress site with Reprint Server and serves it for the +# import E2E test (playwright/e2e/reprint-import.spec.ts). +# +# bash serve.sh # http://127.0.0.1:8181/ +# REPRINT_E2E_PORT=9000 bash serve.sh +# +# The site runs on SQLite so it needs only PHP (with sqlite3 and gd). Reprint's +# own E2E suite covers MySQL sources; this one covers the Playground side. +set -euo pipefail + +PORT="${REPRINT_E2E_PORT:-8181}" +DIR="${REPRINT_E2E_DIR:-/tmp/playground-reprint-e2e-site}" +CACHE="${REPRINT_E2E_CACHE:-/tmp/playground-reprint-e2e-cache}" +SECRET="${REPRINT_E2E_SECRET:-playground-e2e-secret}" + +WP_VERSION=7.1.2 +SQLITE_PLUGIN_VERSION=3.0.2 +# Same release as the client pinned in src/lib/reprint/reprint.ts. +REPRINT_VERSION=v0.10.13 +REPRINT_SERVER_SHA256=5d8eb1080e7d680b7f1234f5672145f7f590fed514e192fb5c5175c9eed2f407 + +HERE="$(cd "$(dirname "$0")" && pwd)" +URL="http://127.0.0.1:${PORT}" +WP="php ${CACHE}/wp-cli.phar --path=${DIR}" + +fetch() { + if [ ! -s "$2" ]; then + curl -sfL "$1" -o "$2" + fi +} + +mkdir -p "$CACHE" +fetch "https://wordpress.org/wordpress-${WP_VERSION}.tar.gz" "${CACHE}/wordpress-${WP_VERSION}.tar.gz" +fetch "https://downloads.wordpress.org/plugin/sqlite-database-integration.${SQLITE_PLUGIN_VERSION}.zip" "${CACHE}/sqlite-database-integration.zip" +fetch "https://github.com/WordPress/reprint/releases/download/${REPRINT_VERSION}/reprint-exporter-wp.zip" "${CACHE}/reprint-server-${REPRINT_VERSION}.zip" +fetch "https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar" "${CACHE}/wp-cli.phar" +echo "${REPRINT_SERVER_SHA256} ${CACHE}/reprint-server-${REPRINT_VERSION}.zip" | shasum -a 256 -c - >/dev/null + +rm -rf "$DIR" +mkdir -p "$DIR" +tar xzf "${CACHE}/wordpress-${WP_VERSION}.tar.gz" --strip-components=1 -C "$DIR" +unzip -q "${CACHE}/sqlite-database-integration.zip" -d "${DIR}/wp-content/plugins" +mkdir -p "${DIR}/wp-content/plugins/reprint-server" +unzip -q "${CACHE}/reprint-server-${REPRINT_VERSION}.zip" -d "${DIR}/wp-content/plugins/reprint-server" +printf ' "${DIR}/wp-content/plugins/reprint-server/secret.php" + +# The SQLite drop-in, filled in the way WordPress Playground fills it. +sed \ + -e "s#{SQLITE_IMPLEMENTATION_FOLDER_PATH}#${DIR}/wp-content/plugins/sqlite-database-integration#" \ + -e "s#{SQLITE_PLUGIN}#sqlite-database-integration/load.php#" \ + "${DIR}/wp-content/plugins/sqlite-database-integration/db.copy" > "${DIR}/wp-content/db.php" + +$WP config create --dbname=wordpress --dbuser=wordpress --dbpass=wordpress --skip-check --quiet +$WP core install --url="$URL" --title="Reprint E2E source" \ + --admin_user=admin --admin_password=password --admin_email=admin@example.com \ + --skip-email --quiet +$WP plugin activate reprint-server --quiet +REPRINT_E2E_SITE_URL="$URL" $WP eval-file "${HERE}/seed.php" > "${DIR}/playground-e2e-manifest.json" + +echo "Serving ${DIR} at ${URL}" +# Reprint Server calls its own site during preflight. One worker would block +# on that loopback request while it is still serving the API call. +export PHP_CLI_SERVER_WORKERS=8 +exec php -S "127.0.0.1:${PORT}" -t "$DIR" -d display_errors=0 -d log_errors=1 diff --git a/packages/playground/website/public/php-code-snippet-e2e.html b/packages/playground/website/public/php-code-snippet-e2e.html index 7ebcc69cbe1..9caccb4322f 100644 --- a/packages/playground/website/public/php-code-snippet-e2e.html +++ b/packages/playground/website/public/php-code-snippet-e2e.html @@ -242,7 +242,7 @@

9. Pure PHP toolkit (no WordPress)

"path": "/tmp/php-toolkit/vendor/autoload.php", "data": { "resource": "url", - "url": "/php-toolkit-autoload.txt" + "url": "./php-toolkit-autoload.txt" } } ] diff --git a/packages/playground/website/src/components/dock/dock-pane.tsx b/packages/playground/website/src/components/dock/dock-pane.tsx index 42c0ff648b1..837dd74c644 100644 --- a/packages/playground/website/src/components/dock/dock-pane.tsx +++ b/packages/playground/website/src/components/dock/dock-pane.tsx @@ -19,10 +19,11 @@ import css from './style.module.css'; export type DockPaneHeaderOverride = { title: string; description?: string; - backLabel: string; + /** Without an onBack handler the header shows the title alone. */ + backLabel?: string; backButtonRef?: RefObject; focusBackButton?: boolean; - onBack: MouseEventHandler; + onBack?: MouseEventHandler; }; export type DockPaneProps = { @@ -130,7 +131,7 @@ export const DockPane = forwardRef( )} {showHeader && (
- {headerOverride && ( + {headerOverride?.onBack && ( + ) : section === 'transfer' ? ( + toolAction ) : undefined } headerOverride={paneHeaderOverride} @@ -1148,6 +1283,7 @@ export function Dock({ isVisible={paneContentVisible} mobileUi={isMobile} onPaneCloseBlockedChange={onPaneCloseBlockedChange} + onToolBackChange={setToolBack} onNewPlaygroundHeaderChange={ handleNewPlaygroundHeaderChange } @@ -1228,7 +1364,9 @@ export function Dock({ diff --git a/packages/playground/website/src/components/dock/style.module.css b/packages/playground/website/src/components/dock/style.module.css index 0fab2580b32..8d70ea47882 100644 --- a/packages/playground/website/src/components/dock/style.module.css +++ b/packages/playground/website/src/components/dock/style.module.css @@ -288,12 +288,24 @@ track transparent and away from the corner curve. Physical margins, not margin-block: logical properties resolve unreliably inside scrollbar pseudo-elements, and this track is always vertical. */ +.pane::-webkit-scrollbar { + background: transparent; + width: 10px; +} + .pane::-webkit-scrollbar-track { background: transparent; margin-bottom: var(--radius-pane); margin-top: var(--radius-pane); } +.pane::-webkit-scrollbar-thumb { + background: var(--interactive-border); + background-clip: padding-box; + border: 2px solid transparent; + border-radius: var(--radius-control); +} + .pane-editor { /* Editor panes drop the pane header and carry their title in the file-browser bar, so the body fills the whole pane. */ @@ -408,8 +420,12 @@ display: none; } +/* A header with a back button carries only the title, so the button centers + on that line. The negative side margins keep the 24px glyph, not the 36px + target, aligned with the pane gutter and close to the title. */ .pane-back { align-items: center; + align-self: center; background: transparent; border: 0; border-radius: var(--radius-control); @@ -417,11 +433,12 @@ cursor: pointer; display: inline-flex; flex: none; - height: 28px; + height: 36px; justify-content: center; margin-left: -6px; + margin-right: -6px; padding: 0; - width: 28px; + width: 36px; } .pane-back:hover { @@ -436,6 +453,8 @@ .pane-back svg { fill: currentColor; + height: 24px; + width: 24px; } /* Right-aligned header action (e.g. "New Playground" on Your Playgrounds): a @@ -481,6 +500,14 @@ padding-bottom: var(--space-3); } +/* A header with a back button is title-only. The button's box already adds + air on the left, and the body's first line follows directly, so both the + left gutter and the bottom break tighten. */ +.pane-header:has(.pane-back) { + padding-bottom: var(--space-3); + padding-left: var(--space-4); +} + .pane-header h2 { color: var(--ink); font-size: 20px; @@ -956,10 +983,6 @@ } } - .pane-back { - margin-top: -2px; - } - /* The dock's bottom bar already carries a "New" tool, so the in-pane "New Playground" header action is redundant on mobile — hide it so the close X can own the header's top-right corner without crowding. */ @@ -1454,7 +1477,7 @@ .dock-item:disabled, .dock-pill-btn:disabled, .pane-header-action:disabled { - cursor: default; + cursor: not-allowed; opacity: 0.45; } @@ -1464,6 +1487,15 @@ color: inherit; } +/* A locked dock keeps the expanded Dev Tools toggle marked as current, but + quietly: the dimmed full highlight read as a stray hover, and hovering it + made the fill vanish. Rest and hover now look the same. */ +.dock-item-active:disabled, +.dock-item-active:disabled:hover { + background: rgba(246, 246, 246, 0.1); + color: rgba(246, 246, 246, 0.68); +} + .dock-pill-btn:disabled:hover { background: transparent; color: rgba(246, 246, 246, 0.62); diff --git a/packages/playground/website/src/components/dock/tool-registry.tsx b/packages/playground/website/src/components/dock/tool-registry.tsx index 3ca2bec7bbf..06a80b9632f 100644 --- a/packages/playground/website/src/components/dock/tool-registry.tsx +++ b/packages/playground/website/src/components/dock/tool-registry.tsx @@ -18,6 +18,7 @@ import { TerminalTool, LogsTool, MailTool, + TransferTool, } from '../site-manager/site-info-panel/site-tool-renderers'; import type { SiteToolPanelProps } from '../site-manager/site-info-panel/site-tool-renderers'; import css from '../site-manager/site-info-panel/style.module.css'; @@ -47,7 +48,7 @@ const definitions = [ isPrimary: true, group: 'main', title: 'New Playground', - description: 'Spin up a fresh Playground or start from a Blueprint.', + description: 'Start from a Blueprint or clone a live site.', layout: 'default', fixedHeight: true, }, @@ -159,6 +160,19 @@ const definitions = [ Panel: MailTool, panelClassName: `${css.tabContents} ${css.mailTab}`, }, + { + section: 'transfer', + label: 'Pull site', + ariaLabel: 'Pull site', + icon: , + group: 'hidden', + title: 'Pull WordPress site', + description: + 'Bring a live site into Playground with Reprint. Your live site stays unchanged.', + layout: 'default', + Panel: TransferTool, + panelClassName: `${css.tabContents} ${css.toolTabContents}`, + }, { section: 'save', label: 'Store permanently', diff --git a/packages/playground/website/src/components/saved-playgrounds-panel/index.tsx b/packages/playground/website/src/components/saved-playgrounds-panel/index.tsx index daf1b3923e5..30b9f50eb1e 100644 --- a/packages/playground/website/src/components/saved-playgrounds-panel/index.tsx +++ b/packages/playground/website/src/components/saved-playgrounds-panel/index.tsx @@ -11,6 +11,7 @@ import { } from '@wordpress/components'; import { moreVertical, + download, upload, link, pencil, @@ -59,6 +60,7 @@ import { setDockOperationNotice, setDockPaneOpen, setDockPaneSection, + setCloneRequested, setSiteSlugToDelete, setWriteOwnBlueprintDraft, setWriteOwnSeededSlug, @@ -1437,41 +1439,75 @@ export function SavedPlaygroundsPanel({ >
void; + onToolBackChange?: SiteToolPanelProps['onBackChange']; onNewPlaygroundHeaderChange: ( header: DockPaneHeaderOverride | undefined ) => void; @@ -33,6 +35,7 @@ export const SiteManager = forwardRef( mobileUi, onPaneCloseBlockedChange, onNewPlaygroundHeaderChange, + onToolBackChange, }, ref ) { @@ -134,6 +137,8 @@ export const SiteManager = forwardRef( site={activeSite} activeTabName={activeSiteTab} mobileUi={mobileUi} + onBackChange={onToolBackChange} + onCloseBlockedChange={onPaneCloseBlockedChange} /> )}
diff --git a/packages/playground/website/src/components/site-manager/site-info-panel/index.tsx b/packages/playground/website/src/components/site-manager/site-info-panel/index.tsx index 9ea0563df49..b2595cfebc6 100644 --- a/packages/playground/website/src/components/site-manager/site-info-panel/index.tsx +++ b/packages/playground/website/src/components/site-manager/site-info-panel/index.tsx @@ -4,6 +4,7 @@ import { selectClientInfoBySiteSlug } from '../../../lib/state/redux/slice-clien import type { SiteInfo } from '../../../lib/state/redux/slice-sites'; import { useAppSelector } from '../../../lib/state/redux/store'; import { SiteToolPanels, type SiteInfoTabName } from './site-tool-panels'; +import type { SiteToolPanelProps } from './site-tool-renderers'; import css from './style.module.css'; export type { SiteInfoTabName } from './site-tool-panels'; @@ -14,10 +15,14 @@ export function SiteInfoPanel({ site, activeTabName, mobileUi, + onBackChange, + onCloseBlockedChange, }: { className: string; site: SiteInfo; mobileUi: boolean; + onBackChange?: SiteToolPanelProps['onBackChange']; + onCloseBlockedChange?: SiteToolPanelProps['onCloseBlockedChange']; activeTabName: SiteInfoTabName | null; }) { const clientInfo = useAppSelector((state) => @@ -52,6 +57,8 @@ export function SiteInfoPanel({ playground={playground} activeTabName={activeTabName} mobileUi={mobileUi} + onBackChange={onBackChange} + onCloseBlockedChange={onCloseBlockedChange} /> diff --git a/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-panels.tsx b/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-panels.tsx index 3a7e3f7f40a..668585b415b 100644 --- a/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-panels.tsx +++ b/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-panels.tsx @@ -14,11 +14,15 @@ export function SiteToolPanels({ playground, activeTabName, mobileUi = false, + onBackChange, + onCloseBlockedChange, }: { site: SiteToolPanelProps['site']; playground: SiteToolPanelProps['playground']; activeTabName: SiteInfoTabName | null; mobileUi?: boolean; + onBackChange?: SiteToolPanelProps['onBackChange']; + onCloseBlockedChange?: SiteToolPanelProps['onCloseBlockedChange']; }) { const [mountedTabNames, setMountedTabNames] = useState( () => (activeTabName ? [activeTabName] : []) @@ -51,6 +55,8 @@ export function SiteToolPanels({ site={site} playground={playground} isVisible={isVisible} + onBackChange={onBackChange} + onCloseBlockedChange={onCloseBlockedChange} mobileHeaderTarget={ isVisible && mobileUi ? editorHeaderSlot : null } diff --git a/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-renderers.tsx b/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-renderers.tsx index 886fe6bb37a..574eab1d8d6 100644 --- a/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-renderers.tsx +++ b/packages/playground/website/src/components/site-manager/site-info-panel/site-tool-renderers.tsx @@ -1,6 +1,8 @@ import { lazy, Suspense, useEffect, useState } from 'react'; +import type { ReactNode } from 'react'; import { Notice } from '@wordpress/components'; import type { PlaygroundClient } from '@wp-playground/client'; +import type { DockPaneHeaderOverride } from '../../dock/dock-pane'; import type { SiteInfo } from '../../../lib/state/redux/slice-sites'; import { setDockPaneOpen } from '../../../lib/state/redux/slice-ui'; import { @@ -32,11 +34,30 @@ const SiteTerminalPanel = lazy(() => })) ); +const SiteTransferPanel = lazy(() => + import('../site-transfer-panel').then((m) => ({ + default: m.SiteTransferPanel, + })) +); + +export type ToolHeaderState = Partial< + Pick +> & { + /** Rendered at the header's trailing edge, e.g. an overflow menu. */ + action?: ReactNode; + /** Hides the pane header; the title still names the pane for assistive tech. */ + hideHeader?: boolean; +}; + export type SiteToolPanelProps = { site: SiteInfo; playground: PlaygroundClient | undefined; isVisible: boolean; mobileHeaderTarget: HTMLElement | null; + /** Replaces the pane header while the tool is in a nested or busy state. */ + onBackChange?: (back: ToolHeaderState | undefined) => void; + /** Pins the pane: closing it and switching Dock tools stay disabled. */ + onCloseBlockedChange?: (blocked: boolean) => void; }; export function SettingsTool(): JSX.Element { @@ -172,3 +193,16 @@ export function LogsTool(): JSX.Element { export function MailTool(): JSX.Element { return ; } + +export function TransferTool(props: SiteToolPanelProps): JSX.Element { + // A clone starts from an empty form even when this site's panel was used. + const cloneRequested = useAppSelector((state) => state.ui.cloneRequested); + return ( + }> + + + ); +} diff --git a/packages/playground/website/src/components/site-manager/site-transfer-panel/index.spec.tsx b/packages/playground/website/src/components/site-manager/site-transfer-panel/index.spec.tsx new file mode 100644 index 00000000000..7c9b654b9d3 --- /dev/null +++ b/packages/playground/website/src/components/site-manager/site-transfer-panel/index.spec.tsx @@ -0,0 +1,685 @@ +// @vitest-environment jsdom +import { act, useState } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import type { PlaygroundClient } from '@wp-playground/client'; +import { updateSiteMetadata } from '../../../lib/state/redux/slice-sites'; +import { getPlaygroundDefinedPHPConstants } from '../../../lib/state/redux/playground-defined-php-constants'; +import type { SiteInfo } from '../../../lib/state/redux/slice-sites'; +import { detectReprint, transferSite } from '../../../lib/reprint/reprint'; +import type * as Reprint from '../../../lib/reprint/reprint'; +import { SiteTransferPanel } from './index'; +import { DockPane } from '../../dock/dock-pane'; +import type { + SiteToolPanelProps, + ToolHeaderState, +} from '../site-info-panel/site-tool-renderers'; + +const { ui, dispatch } = vi.hoisted(() => ({ + ui: { + pullRequestedForSite: undefined as string | undefined, + cloneRequested: false, + pendingClone: undefined as + | { slug: string; url: string; secret: string } + | undefined, + }, + dispatch: vi.fn(), +})); +vi.mock('../../../lib/state/redux/store', () => ({ + useAppDispatch: () => dispatch, + useAppSelector: (selector: (state: { ui: typeof ui }) => unknown) => + selector({ ui }), +})); +vi.mock('../../../lib/state/redux/slice-sites', () => ({ + preserveSite: vi.fn(), + selectAllSites: () => [], + updateSiteMetadata: vi.fn(), +})); +vi.mock('../../../lib/state/redux/site-management-api-middleware', () => ({ + useSitesAPI: () => ({ + createNewTemporarySite: vi.fn(async (slug: string) => slug), + autosaveTemporarySite: vi.fn(async () => ({})), + }), +})); +vi.mock('../../../lib/state/redux/playground-defined-php-constants', () => ({ + getPlaygroundDefinedPHPConstants: vi.fn(), +})); +vi.mock('../../../lib/reprint/reprint', async (original) => ({ + ...(await original()), + detectReprint: vi.fn(), + transferSite: vi.fn(), +})); +vi.mock('virtual:cors-proxy-url', () => ({ corsProxyUrl: '' })); +vi.mock('@wordpress/components', () => ({ + Button: ({ + children, + variant: _variant, + isDestructive: _destructive, + isBusy: _busy, + type = 'button', + ...props + }: React.ButtonHTMLAttributes & { + variant?: string; + isDestructive?: boolean; + isBusy?: boolean; + }) => ( + + ), + // The menu renders open so its items can be clicked like any button. + DropdownMenu: ({ + children, + }: { + children: (props: { onClose: () => void }) => React.ReactNode; + }) =>
{children({ onClose: () => {} })}
, + MenuItem: ({ + children, + ...props + }: React.ButtonHTMLAttributes) => ( + + ), + Notice: ({ children }: { children: React.ReactNode }) => ( +
{children}
+ ), + __experimentalVStack: ({ children }: { children: React.ReactNode }) => ( +
{children}
+ ), + TextControl: ({ + label, + onChange, + help: _help, + __nextHasNoMarginBottom: _noMargin, + ...props + }: Omit, 'onChange'> & { + label: string; + help?: string; + __nextHasNoMarginBottom?: boolean; + onChange: (value: string) => void; + }) => ( + + ), + TextareaControl: ({ + label, + __nextHasNoMarginBottom: _noMargin, + ...props + }: React.TextareaHTMLAttributes & { + label: string; + __nextHasNoMarginBottom?: boolean; + }) => ( +