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