Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion packages/php-wasm/universal/src/lib/php-request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,8 @@ export class PHPRequestHandler {
* ```
*
* @param request - PHP Request data.
* @param followRedirects - Follow redirects when the response code is 301 or 302.
* @returns The response.
*/
async request(request: PHPRequest): Promise<PHPResponse> {
const isAbsolute = URL.canParse(request.url);
Expand Down Expand Up @@ -410,10 +412,43 @@ export class PHPRequestHandler {
// Pass along URL with the #fragment filtered out
url: requestedUrl.toString(),
};
return this.#spawnPHPAndDispatchRequest(
const response = await this.#spawnPHPAndDispatchRequest(
effectiveRequest,
fsPath
);

/**
* If the response is a redirect, and the request is configured to
* follow redirects, we need to recursively call request() with the
* new URL.
*
* If the response is a redirect, and the request is configured to
* error on redirects, we need to throw an error.
*
* Otherwise, we return the response.
*
* This matches the behavior of the JavaScript fetch API.
* https://developer.mozilla.org/en-US/docs/Web/API/Request/redirect
*/
if (
response.headers['location'] &&
response.headers['location'].length === 1 &&
[301, 302].includes(response.httpStatusCode)
) {
if (request.redirect === 'error') {
return Promise.reject(
new Error(
'TypeError: NetworkError when attempting to fetch resource.'
)
);
} else if (request.redirect === 'follow') {
return await this.request({
url: response.headers['location'][0],
redirect: request.redirect,
});
}
}
return response;
} else {
return this.#serveStaticFile(primaryPhp, fsPath);
}
Expand Down
8 changes: 8 additions & 0 deletions packages/php-wasm/universal/src/lib/universal-php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ export interface PHPRequest {
* and sent with a `multipart/form-data` header.
*/
body?: string | Uint8Array | Record<string, string | Uint8Array | File>;

/**
* Whether to follow redirects.
* - `follow`: Follow redirects.
* - `manual`: Return the redirect response. (Default)
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should manual stay the default behavior or should we follow by default like JS fetch and browsers do?

* - `error`: Throw an error if a redirect is encountered.
*/
redirect?: 'follow' | 'manual' | 'error';
}

export interface PHPRunOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { loadNodeRuntime } from '@php-wasm/node';
import { readFileSync } from 'fs';
import { join } from 'path';
import { login } from './login';
import { PHPRequest, PHPRequestHandler } from '@php-wasm/universal';
import { PHPRequestHandler } from '@php-wasm/universal';

describe('Blueprint step enableMultisite', () => {
let handler: PHPRequestHandler;
Expand All @@ -33,16 +33,6 @@ describe('Blueprint step enableMultisite', () => {
return { php, handler };
}

const requestFollowRedirects = async (request: PHPRequest) => {
let response = await handler.request(request);
while (response.httpStatusCode === 302) {
response = await handler.request({
url: response.headers['location'][0],
});
}
return response;
};

[
{
absoluteUrl: 'http://playground-domain/scope:987987/',
Expand Down Expand Up @@ -81,8 +71,9 @@ describe('Blueprint step enableMultisite', () => {
* the admin bar includes the multisite menu.
*/
await login(php, {});
const response = await requestFollowRedirects({
const response = await handler.request({
url: '/',
redirect: 'follow',
});
expect(response.httpStatusCode).toEqual(200);
expect(response.text).toContain('My Sites');
Expand Down
26 changes: 10 additions & 16 deletions packages/playground/blueprints/src/lib/steps/login.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PHP, PHPRequest } from '@php-wasm/universal';
import { PHP } from '@php-wasm/universal';
import { RecommendedPHPVersion } from '@wp-playground/common';
import {
getSqliteDatabaseModule,
Expand Down Expand Up @@ -26,29 +26,21 @@ describe('Blueprint step login', () => {
php = await handler.getPrimaryPhp();
});

const requestFollowRedirects = async (request: PHPRequest) => {
let response = await handler.request(request);
while (response.httpStatusCode === 302) {
response = await handler.request({
url: response.headers['location'][0],
});
}
return response;
};

it('should log the user in', async () => {
await login(php, {});
const response = await requestFollowRedirects({
const response = await handler.request({
url: '/',
redirect: 'follow',
});
expect(response.httpStatusCode).toBe(200);
expect(response.text).toContain('Edit site');
expect(response.text).toContain('Edit Site');
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This label changed in a recent version of WP, and the test stopped working.

});

it('should log the user into wp-admin', async () => {
await login(php, {});
const response = await requestFollowRedirects({
const response = await handler.request({
url: '/wp-admin/',
redirect: 'follow',
});
expect(response.httpStatusCode).toBe(200);
expect(response.text).toContain('Dashboard');
Expand All @@ -60,8 +52,9 @@ describe('Blueprint step login', () => {
PLAYGROUND_FORCE_AUTO_LOGIN_ENABLED: true,
},
});
const response = await requestFollowRedirects({
const response = await handler.request({
url: '/?playground_force_auto_login_as_user=admin',
redirect: 'follow',
});
expect(response.httpStatusCode).toBe(200);
expect(response.text).toContain('Dashboard');
Expand All @@ -81,8 +74,9 @@ describe('Blueprint step login', () => {
}
`
);
const response = await requestFollowRedirects({
const response = await handler.request({
url: '/nonce-test.php',
redirect: 'follow',
});
expect(response.text).toBe('1');
});
Expand Down
13 changes: 0 additions & 13 deletions packages/playground/cli/jest.config.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/playground/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
},
"license": "GPL-2.0-or-later",
"type": "module",
"main": "main.js",
"main": "index.js",
"bin": "wp-playground.js",
"gitHead": "2f8d8f3cea548fbd75111e8659a92f601cddc593"
}
11 changes: 7 additions & 4 deletions packages/playground/cli/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,14 @@
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"executor": "@nx/vite:test",
"outputs": ["{workspaceRoot}/coverage/playground/cli"],
"options": {
"jestConfig": "packages/playground/cli/jest.config.ts",
"passWithNoTests": true
"passWithNoTests": true,
"reportsDirectory": "../../../coverage/packages/playground/cli",
"typecheck": {
"tsconfig": "{projectRoot}/tsconfig.spec.json"
}
},
"configurations": {
"ci": {
Expand Down
Loading
Loading