You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

754 lines
22 KiB

1 year ago
  1. /******/ (function() { // webpackBootstrap
  2. /******/ "use strict";
  3. /******/ // The require scope
  4. /******/ var __webpack_require__ = {};
  5. /******/
  6. /************************************************************************/
  7. /******/ /* webpack/runtime/define property getters */
  8. /******/ !function() {
  9. /******/ // define getter functions for harmony exports
  10. /******/ __webpack_require__.d = function(exports, definition) {
  11. /******/ for(var key in definition) {
  12. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  13. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  14. /******/ }
  15. /******/ }
  16. /******/ };
  17. /******/ }();
  18. /******/
  19. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  20. /******/ !function() {
  21. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  22. /******/ }();
  23. /******/
  24. /************************************************************************/
  25. var __webpack_exports__ = {};
  26. // EXPORTS
  27. __webpack_require__.d(__webpack_exports__, {
  28. "default": function() { return /* binding */ build_module; }
  29. });
  30. ;// CONCATENATED MODULE: external ["wp","i18n"]
  31. var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
  32. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/nonce.js
  33. /**
  34. * @param {string} nonce
  35. * @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
  36. */
  37. function createNonceMiddleware(nonce) {
  38. /**
  39. * @type {import('../types').APIFetchMiddleware & { nonce: string }}
  40. */
  41. const middleware = (options, next) => {
  42. const {
  43. headers = {}
  44. } = options;
  45. // If an 'X-WP-Nonce' header (or any case-insensitive variation
  46. // thereof) was specified, no need to add a nonce header.
  47. for (const headerName in headers) {
  48. if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
  49. return next(options);
  50. }
  51. }
  52. return next({
  53. ...options,
  54. headers: {
  55. ...headers,
  56. 'X-WP-Nonce': middleware.nonce
  57. }
  58. });
  59. };
  60. middleware.nonce = nonce;
  61. return middleware;
  62. }
  63. /* harmony default export */ var nonce = (createNonceMiddleware);
  64. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/namespace-endpoint.js
  65. /**
  66. * @type {import('../types').APIFetchMiddleware}
  67. */
  68. const namespaceAndEndpointMiddleware = (options, next) => {
  69. let path = options.path;
  70. let namespaceTrimmed, endpointTrimmed;
  71. if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
  72. namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
  73. endpointTrimmed = options.endpoint.replace(/^\//, '');
  74. if (endpointTrimmed) {
  75. path = namespaceTrimmed + '/' + endpointTrimmed;
  76. } else {
  77. path = namespaceTrimmed;
  78. }
  79. }
  80. delete options.namespace;
  81. delete options.endpoint;
  82. return next({
  83. ...options,
  84. path
  85. });
  86. };
  87. /* harmony default export */ var namespace_endpoint = (namespaceAndEndpointMiddleware);
  88. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/root-url.js
  89. /**
  90. * Internal dependencies
  91. */
  92. /**
  93. * @param {string} rootURL
  94. * @return {import('../types').APIFetchMiddleware} Root URL middleware.
  95. */
  96. const createRootURLMiddleware = rootURL => (options, next) => {
  97. return namespace_endpoint(options, optionsWithPath => {
  98. let url = optionsWithPath.url;
  99. let path = optionsWithPath.path;
  100. let apiRoot;
  101. if (typeof path === 'string') {
  102. apiRoot = rootURL;
  103. if (-1 !== rootURL.indexOf('?')) {
  104. path = path.replace('?', '&');
  105. }
  106. path = path.replace(/^\//, '');
  107. // API root may already include query parameter prefix if site is
  108. // configured to use plain permalinks.
  109. if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
  110. path = path.replace('?', '&');
  111. }
  112. url = apiRoot + path;
  113. }
  114. return next({
  115. ...optionsWithPath,
  116. url
  117. });
  118. });
  119. };
  120. /* harmony default export */ var root_url = (createRootURLMiddleware);
  121. ;// CONCATENATED MODULE: external ["wp","url"]
  122. var external_wp_url_namespaceObject = window["wp"]["url"];
  123. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/preloading.js
  124. /**
  125. * WordPress dependencies
  126. */
  127. /**
  128. * @param {Record<string, any>} preloadedData
  129. * @return {import('../types').APIFetchMiddleware} Preloading middleware.
  130. */
  131. function createPreloadingMiddleware(preloadedData) {
  132. const cache = Object.fromEntries(Object.entries(preloadedData).map(([path, data]) => [(0,external_wp_url_namespaceObject.normalizePath)(path), data]));
  133. return (options, next) => {
  134. const {
  135. parse = true
  136. } = options;
  137. /** @type {string | void} */
  138. let rawPath = options.path;
  139. if (!rawPath && options.url) {
  140. const {
  141. rest_route: pathFromQuery,
  142. ...queryArgs
  143. } = (0,external_wp_url_namespaceObject.getQueryArgs)(options.url);
  144. if (typeof pathFromQuery === 'string') {
  145. rawPath = (0,external_wp_url_namespaceObject.addQueryArgs)(pathFromQuery, queryArgs);
  146. }
  147. }
  148. if (typeof rawPath !== 'string') {
  149. return next(options);
  150. }
  151. const method = options.method || 'GET';
  152. const path = (0,external_wp_url_namespaceObject.normalizePath)(rawPath);
  153. if ('GET' === method && cache[path]) {
  154. const cacheData = cache[path];
  155. // Unsetting the cache key ensures that the data is only used a single time.
  156. delete cache[path];
  157. return prepareResponse(cacheData, !!parse);
  158. } else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
  159. const cacheData = cache[method][path];
  160. // Unsetting the cache key ensures that the data is only used a single time.
  161. delete cache[method][path];
  162. return prepareResponse(cacheData, !!parse);
  163. }
  164. return next(options);
  165. };
  166. }
  167. /**
  168. * This is a helper function that sends a success response.
  169. *
  170. * @param {Record<string, any>} responseData
  171. * @param {boolean} parse
  172. * @return {Promise<any>} Promise with the response.
  173. */
  174. function prepareResponse(responseData, parse) {
  175. return Promise.resolve(parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
  176. status: 200,
  177. statusText: 'OK',
  178. headers: responseData.headers
  179. }));
  180. }
  181. /* harmony default export */ var preloading = (createPreloadingMiddleware);
  182. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/fetch-all-middleware.js
  183. /**
  184. * WordPress dependencies
  185. */
  186. /**
  187. * Internal dependencies
  188. */
  189. /**
  190. * Apply query arguments to both URL and Path, whichever is present.
  191. *
  192. * @param {import('../types').APIFetchOptions} props
  193. * @param {Record<string, string | number>} queryArgs
  194. * @return {import('../types').APIFetchOptions} The request with the modified query args
  195. */
  196. const modifyQuery = ({
  197. path,
  198. url,
  199. ...options
  200. }, queryArgs) => ({
  201. ...options,
  202. url: url && (0,external_wp_url_namespaceObject.addQueryArgs)(url, queryArgs),
  203. path: path && (0,external_wp_url_namespaceObject.addQueryArgs)(path, queryArgs)
  204. });
  205. /**
  206. * Duplicates parsing functionality from apiFetch.
  207. *
  208. * @param {Response} response
  209. * @return {Promise<any>} Parsed response json.
  210. */
  211. const parseResponse = response => response.json ? response.json() : Promise.reject(response);
  212. /**
  213. * @param {string | null} linkHeader
  214. * @return {{ next?: string }} The parsed link header.
  215. */
  216. const parseLinkHeader = linkHeader => {
  217. if (!linkHeader) {
  218. return {};
  219. }
  220. const match = linkHeader.match(/<([^>]+)>; rel="next"/);
  221. return match ? {
  222. next: match[1]
  223. } : {};
  224. };
  225. /**
  226. * @param {Response} response
  227. * @return {string | undefined} The next page URL.
  228. */
  229. const getNextPageUrl = response => {
  230. const {
  231. next
  232. } = parseLinkHeader(response.headers.get('link'));
  233. return next;
  234. };
  235. /**
  236. * @param {import('../types').APIFetchOptions} options
  237. * @return {boolean} True if the request contains an unbounded query.
  238. */
  239. const requestContainsUnboundedQuery = options => {
  240. const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
  241. const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
  242. return pathIsUnbounded || urlIsUnbounded;
  243. };
  244. /**
  245. * The REST API enforces an upper limit on the per_page option. To handle large
  246. * collections, apiFetch consumers can pass `per_page=-1`; this middleware will
  247. * then recursively assemble a full response array from all available pages.
  248. *
  249. * @type {import('../types').APIFetchMiddleware}
  250. */
  251. const fetchAllMiddleware = async (options, next) => {
  252. if (options.parse === false) {
  253. // If a consumer has opted out of parsing, do not apply middleware.
  254. return next(options);
  255. }
  256. if (!requestContainsUnboundedQuery(options)) {
  257. // If neither url nor path is requesting all items, do not apply middleware.
  258. return next(options);
  259. }
  260. // Retrieve requested page of results.
  261. const response = await build_module({
  262. ...modifyQuery(options, {
  263. per_page: 100
  264. }),
  265. // Ensure headers are returned for page 1.
  266. parse: false
  267. });
  268. const results = await parseResponse(response);
  269. if (!Array.isArray(results)) {
  270. // We have no reliable way of merging non-array results.
  271. return results;
  272. }
  273. let nextPage = getNextPageUrl(response);
  274. if (!nextPage) {
  275. // There are no further pages to request.
  276. return results;
  277. }
  278. // Iteratively fetch all remaining pages until no "next" header is found.
  279. let mergedResults = /** @type {any[]} */[].concat(results);
  280. while (nextPage) {
  281. const nextResponse = await build_module({
  282. ...options,
  283. // Ensure the URL for the next page is used instead of any provided path.
  284. path: undefined,
  285. url: nextPage,
  286. // Ensure we still get headers so we can identify the next page.
  287. parse: false
  288. });
  289. const nextResults = await parseResponse(nextResponse);
  290. mergedResults = mergedResults.concat(nextResults);
  291. nextPage = getNextPageUrl(nextResponse);
  292. }
  293. return mergedResults;
  294. };
  295. /* harmony default export */ var fetch_all_middleware = (fetchAllMiddleware);
  296. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/http-v1.js
  297. /**
  298. * Set of HTTP methods which are eligible to be overridden.
  299. *
  300. * @type {Set<string>}
  301. */
  302. const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
  303. /**
  304. * Default request method.
  305. *
  306. * "A request has an associated method (a method). Unless stated otherwise it
  307. * is `GET`."
  308. *
  309. * @see https://fetch.spec.whatwg.org/#requests
  310. *
  311. * @type {string}
  312. */
  313. const DEFAULT_METHOD = 'GET';
  314. /**
  315. * API Fetch middleware which overrides the request method for HTTP v1
  316. * compatibility leveraging the REST API X-HTTP-Method-Override header.
  317. *
  318. * @type {import('../types').APIFetchMiddleware}
  319. */
  320. const httpV1Middleware = (options, next) => {
  321. const {
  322. method = DEFAULT_METHOD
  323. } = options;
  324. if (OVERRIDE_METHODS.has(method.toUpperCase())) {
  325. options = {
  326. ...options,
  327. headers: {
  328. ...options.headers,
  329. 'X-HTTP-Method-Override': method,
  330. 'Content-Type': 'application/json'
  331. },
  332. method: 'POST'
  333. };
  334. }
  335. return next(options);
  336. };
  337. /* harmony default export */ var http_v1 = (httpV1Middleware);
  338. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/user-locale.js
  339. /**
  340. * WordPress dependencies
  341. */
  342. /**
  343. * @type {import('../types').APIFetchMiddleware}
  344. */
  345. const userLocaleMiddleware = (options, next) => {
  346. if (typeof options.url === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.url, '_locale')) {
  347. options.url = (0,external_wp_url_namespaceObject.addQueryArgs)(options.url, {
  348. _locale: 'user'
  349. });
  350. }
  351. if (typeof options.path === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.path, '_locale')) {
  352. options.path = (0,external_wp_url_namespaceObject.addQueryArgs)(options.path, {
  353. _locale: 'user'
  354. });
  355. }
  356. return next(options);
  357. };
  358. /* harmony default export */ var user_locale = (userLocaleMiddleware);
  359. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/utils/response.js
  360. /**
  361. * WordPress dependencies
  362. */
  363. /**
  364. * Parses the apiFetch response.
  365. *
  366. * @param {Response} response
  367. * @param {boolean} shouldParseResponse
  368. *
  369. * @return {Promise<any> | null | Response} Parsed response.
  370. */
  371. const response_parseResponse = (response, shouldParseResponse = true) => {
  372. if (shouldParseResponse) {
  373. if (response.status === 204) {
  374. return null;
  375. }
  376. return response.json ? response.json() : Promise.reject(response);
  377. }
  378. return response;
  379. };
  380. /**
  381. * Calls the `json` function on the Response, throwing an error if the response
  382. * doesn't have a json function or if parsing the json itself fails.
  383. *
  384. * @param {Response} response
  385. * @return {Promise<any>} Parsed response.
  386. */
  387. const parseJsonAndNormalizeError = response => {
  388. const invalidJsonError = {
  389. code: 'invalid_json',
  390. message: (0,external_wp_i18n_namespaceObject.__)('The response is not a valid JSON response.')
  391. };
  392. if (!response || !response.json) {
  393. throw invalidJsonError;
  394. }
  395. return response.json().catch(() => {
  396. throw invalidJsonError;
  397. });
  398. };
  399. /**
  400. * Parses the apiFetch response properly and normalize response errors.
  401. *
  402. * @param {Response} response
  403. * @param {boolean} shouldParseResponse
  404. *
  405. * @return {Promise<any>} Parsed response.
  406. */
  407. const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => {
  408. return Promise.resolve(response_parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse));
  409. };
  410. /**
  411. * Parses a response, throwing an error if parsing the response fails.
  412. *
  413. * @param {Response} response
  414. * @param {boolean} shouldParseResponse
  415. * @return {Promise<any>} Parsed response.
  416. */
  417. function parseAndThrowError(response, shouldParseResponse = true) {
  418. if (!shouldParseResponse) {
  419. throw response;
  420. }
  421. return parseJsonAndNormalizeError(response).then(error => {
  422. const unknownError = {
  423. code: 'unknown_error',
  424. message: (0,external_wp_i18n_namespaceObject.__)('An unknown error occurred.')
  425. };
  426. throw error || unknownError;
  427. });
  428. }
  429. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/media-upload.js
  430. /**
  431. * WordPress dependencies
  432. */
  433. /**
  434. * Internal dependencies
  435. */
  436. /**
  437. * @param {import('../types').APIFetchOptions} options
  438. * @return {boolean} True if the request is for media upload.
  439. */
  440. function isMediaUploadRequest(options) {
  441. const isCreateMethod = !!options.method && options.method === 'POST';
  442. const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
  443. return isMediaEndpoint && isCreateMethod;
  444. }
  445. /**
  446. * Middleware handling media upload failures and retries.
  447. *
  448. * @type {import('../types').APIFetchMiddleware}
  449. */
  450. const mediaUploadMiddleware = (options, next) => {
  451. if (!isMediaUploadRequest(options)) {
  452. return next(options);
  453. }
  454. let retries = 0;
  455. const maxRetries = 5;
  456. /**
  457. * @param {string} attachmentId
  458. * @return {Promise<any>} Processed post response.
  459. */
  460. const postProcess = attachmentId => {
  461. retries++;
  462. return next({
  463. path: `/wp/v2/media/${attachmentId}/post-process`,
  464. method: 'POST',
  465. data: {
  466. action: 'create-image-subsizes'
  467. },
  468. parse: false
  469. }).catch(() => {
  470. if (retries < maxRetries) {
  471. return postProcess(attachmentId);
  472. }
  473. next({
  474. path: `/wp/v2/media/${attachmentId}?force=true`,
  475. method: 'DELETE'
  476. });
  477. return Promise.reject();
  478. });
  479. };
  480. return next({
  481. ...options,
  482. parse: false
  483. }).catch(response => {
  484. const attachmentId = response.headers.get('x-wp-upload-attachment-id');
  485. if (response.status >= 500 && response.status < 600 && attachmentId) {
  486. return postProcess(attachmentId).catch(() => {
  487. if (options.parse !== false) {
  488. return Promise.reject({
  489. code: 'post_process',
  490. message: (0,external_wp_i18n_namespaceObject.__)('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
  491. });
  492. }
  493. return Promise.reject(response);
  494. });
  495. }
  496. return parseAndThrowError(response, options.parse);
  497. }).then(response => parseResponseAndNormalizeError(response, options.parse));
  498. };
  499. /* harmony default export */ var media_upload = (mediaUploadMiddleware);
  500. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/theme-preview.js
  501. /**
  502. * WordPress dependencies
  503. */
  504. /**
  505. * This appends a `wp_theme_preview` parameter to the REST API request URL if
  506. * the admin URL contains a `theme` GET parameter.
  507. *
  508. * @param {Record<string, any>} themePath
  509. * @return {import('../types').APIFetchMiddleware} Preloading middleware.
  510. */
  511. const createThemePreviewMiddleware = themePath => (options, next) => {
  512. if (typeof options.url === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.url, 'wp_theme_preview')) {
  513. options.url = (0,external_wp_url_namespaceObject.addQueryArgs)(options.url, {
  514. wp_theme_preview: themePath
  515. });
  516. }
  517. if (typeof options.path === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.path, 'wp_theme_preview')) {
  518. options.path = (0,external_wp_url_namespaceObject.addQueryArgs)(options.path, {
  519. wp_theme_preview: themePath
  520. });
  521. }
  522. return next(options);
  523. };
  524. /* harmony default export */ var theme_preview = (createThemePreviewMiddleware);
  525. ;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/index.js
  526. /**
  527. * WordPress dependencies
  528. */
  529. /**
  530. * Internal dependencies
  531. */
  532. /**
  533. * Default set of header values which should be sent with every request unless
  534. * explicitly provided through apiFetch options.
  535. *
  536. * @type {Record<string, string>}
  537. */
  538. const DEFAULT_HEADERS = {
  539. // The backend uses the Accept header as a condition for considering an
  540. // incoming request as a REST request.
  541. //
  542. // See: https://core.trac.wordpress.org/ticket/44534
  543. Accept: 'application/json, */*;q=0.1'
  544. };
  545. /**
  546. * Default set of fetch option values which should be sent with every request
  547. * unless explicitly provided through apiFetch options.
  548. *
  549. * @type {Object}
  550. */
  551. const DEFAULT_OPTIONS = {
  552. credentials: 'include'
  553. };
  554. /** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
  555. /** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
  556. /**
  557. * @type {import('./types').APIFetchMiddleware[]}
  558. */
  559. const middlewares = [user_locale, namespace_endpoint, http_v1, fetch_all_middleware];
  560. /**
  561. * Register a middleware
  562. *
  563. * @param {import('./types').APIFetchMiddleware} middleware
  564. */
  565. function registerMiddleware(middleware) {
  566. middlewares.unshift(middleware);
  567. }
  568. /**
  569. * Checks the status of a response, throwing the Response as an error if
  570. * it is outside the 200 range.
  571. *
  572. * @param {Response} response
  573. * @return {Response} The response if the status is in the 200 range.
  574. */
  575. const checkStatus = response => {
  576. if (response.status >= 200 && response.status < 300) {
  577. return response;
  578. }
  579. throw response;
  580. };
  581. /** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
  582. /**
  583. * @type {FetchHandler}
  584. */
  585. const defaultFetchHandler = nextOptions => {
  586. const {
  587. url,
  588. path,
  589. data,
  590. parse = true,
  591. ...remainingOptions
  592. } = nextOptions;
  593. let {
  594. body,
  595. headers
  596. } = nextOptions;
  597. // Merge explicitly-provided headers with default values.
  598. headers = {
  599. ...DEFAULT_HEADERS,
  600. ...headers
  601. };
  602. // The `data` property is a shorthand for sending a JSON body.
  603. if (data) {
  604. body = JSON.stringify(data);
  605. headers['Content-Type'] = 'application/json';
  606. }
  607. const responsePromise = window.fetch(
  608. // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
  609. url || path || window.location.href, {
  610. ...DEFAULT_OPTIONS,
  611. ...remainingOptions,
  612. body,
  613. headers
  614. });
  615. return responsePromise.then(value => Promise.resolve(value).then(checkStatus).catch(response => parseAndThrowError(response, parse)).then(response => parseResponseAndNormalizeError(response, parse)), err => {
  616. // Re-throw AbortError for the users to handle it themselves.
  617. if (err && err.name === 'AbortError') {
  618. throw err;
  619. }
  620. // Otherwise, there is most likely no network connection.
  621. // Unfortunately the message might depend on the browser.
  622. throw {
  623. code: 'fetch_error',
  624. message: (0,external_wp_i18n_namespaceObject.__)('You are probably offline.')
  625. };
  626. });
  627. };
  628. /** @type {FetchHandler} */
  629. let fetchHandler = defaultFetchHandler;
  630. /**
  631. * Defines a custom fetch handler for making the requests that will override
  632. * the default one using window.fetch
  633. *
  634. * @param {FetchHandler} newFetchHandler The new fetch handler
  635. */
  636. function setFetchHandler(newFetchHandler) {
  637. fetchHandler = newFetchHandler;
  638. }
  639. /**
  640. * @template T
  641. * @param {import('./types').APIFetchOptions} options
  642. * @return {Promise<T>} A promise representing the request processed via the registered middlewares.
  643. */
  644. function apiFetch(options) {
  645. // creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
  646. // converting `middlewares = [ m1, m2, m3 ]` into:
  647. // ```
  648. // opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
  649. // ```
  650. const enhancedHandler = middlewares.reduceRight(( /** @type {FetchHandler} */next, middleware) => {
  651. return workingOptions => middleware(workingOptions, next);
  652. }, fetchHandler);
  653. return enhancedHandler(options).catch(error => {
  654. if (error.code !== 'rest_cookie_invalid_nonce') {
  655. return Promise.reject(error);
  656. }
  657. // If the nonce is invalid, refresh it and try again.
  658. return window
  659. // @ts-ignore
  660. .fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
  661. // @ts-ignore
  662. apiFetch.nonceMiddleware.nonce = text;
  663. return apiFetch(options);
  664. });
  665. });
  666. }
  667. apiFetch.use = registerMiddleware;
  668. apiFetch.setFetchHandler = setFetchHandler;
  669. apiFetch.createNonceMiddleware = nonce;
  670. apiFetch.createPreloadingMiddleware = preloading;
  671. apiFetch.createRootURLMiddleware = root_url;
  672. apiFetch.fetchAllMiddleware = fetch_all_middleware;
  673. apiFetch.mediaUploadMiddleware = media_upload;
  674. apiFetch.createThemePreviewMiddleware = theme_preview;
  675. /* harmony default export */ var build_module = (apiFetch);
  676. (window.wp = window.wp || {}).apiFetch = __webpack_exports__["default"];
  677. /******/ })()
  678. ;