Brak opisu

api-fetch.js 23KB

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