UNPKG

@wordpress/e2e-test-utils

Version:
132 lines (120 loc) 4.03 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.batch = batch; exports.rest = rest; var _nodeFetch = _interopRequireDefault(require("node-fetch")); var _formData = _interopRequireDefault(require("form-data")); var _apiFetch = _interopRequireDefault(require("@wordpress/api-fetch")); var _config = require("./shared/config"); var _createUrl = require("./create-url"); /** * External dependencies */ /** * WordPress dependencies */ /** * Internal dependencies */ // `apiFetch` expects `window.fetch` to be available in its default handler. global.window = global.window || {}; global.window.fetch = _nodeFetch.default; const setAPIRootURL = (async () => { // Discover the API root url using link header. // See https://developer.wordpress.org/rest-api/using-the-rest-api/discovery/#link-header const res = await (0, _nodeFetch.default)(_config.WP_BASE_URL, { method: 'HEAD' }); const links = res.headers.get('link'); const restLink = links.match(/<([^>]+)>; rel="https:\/\/api\.w\.org\/"/); if (!restLink) { throw new Error(`Failed to discover REST API endpoint. Link header: ${links}`); } const [, rootURL] = restLink; _apiFetch.default.use(_apiFetch.default.createRootURLMiddleware(rootURL)); })(); async function login(retries = 3) { const formData = new _formData.default(); formData.append('log', _config.WP_USERNAME); formData.append('pwd', _config.WP_PASSWORD); // Login to admin using fetch. const loginResponse = await (0, _nodeFetch.default)((0, _createUrl.createURL)('wp-login.php'), { method: 'POST', headers: formData.getHeaders(), body: formData, redirect: 'manual' }); // Retrieve the cookies. const cookies = loginResponse.headers.get('set-cookie'); const cookie = cookies.split(',').map(setCookie => setCookie.split(';')[0]).join(';'); _apiFetch.default.nonceEndpoint = (0, _createUrl.createURL)('wp-admin/admin-ajax.php', 'action=rest-nonce'); // Get the initial nonce. const response = await (0, _nodeFetch.default)(_apiFetch.default.nonceEndpoint, { headers: { cookie } }); if (response.status === 200) { return { response, cookie }; } // Sometimes the nonce call will fail if a test has forced a new login // and invalidated the cookie, so retry the login in these instances. if (retries > 0) { return login(retries - 1); } throw new Error(`Fetch api call failed for ${_apiFetch.default.nonceEndpoint}: ${response.status}`); } const setNonce = (async () => { // Get the initial nonce. const loginRequest = await login(); const nonce = await loginRequest.response.text(); // Register the nonce middleware. _apiFetch.default.use(_apiFetch.default.createNonceMiddleware(nonce)); // For the nonce to work we have to also pass the cookies. _apiFetch.default.use(function setCookieMiddleware(request, next) { return next({ ...request, headers: { ...request.headers, cookie: loginRequest.cookie } }); }); })(); /** * Call REST API using `apiFetch` to build and clear test states. * * @param {Object} options `apiFetch` options. * @return {Promise<any>} The response value. */ async function rest(options = {}) { // Only need to set them once but before any requests. await Promise.all([setAPIRootURL, setNonce]); return await (0, _apiFetch.default)(options); } /** * Call a set of REST APIs in batch. * See https://make.wordpress.org/core/2020/11/20/rest-api-batch-framework-in-wordpress-5-6/ * Note that calling GET requests in batch is not supported. * * @param {Array<Object>} requests The request objects. * @return {Promise<any>} The response value. */ async function batch(requests) { return await rest({ method: 'POST', path: '/batch/v1', data: { requests, validation: 'require-all-validate' } }); } //# sourceMappingURL=rest-api.js.map