PluginProbe
Gutenberg / 22.9.0
Gutenberg v22.9.0
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / scripts / api-fetch / index.js

index.js in Gutenberg 22.9.0, at build/scripts/api-fetch/index.js

527 lines 17.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 "use strict";
2 var wp;
3 (wp ||= {}).apiFetch = (() => {
4 var __create = Object.create;
5 var __defProp = Object.defineProperty;
6 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7 var __getOwnPropNames = Object.getOwnPropertyNames;
8 var __getProtoOf = Object.getPrototypeOf;
9 var __hasOwnProp = Object.prototype.hasOwnProperty;
10 var __commonJS = (cb, mod) => function __require() {
11 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12 };
13 var __export = (target, all) => {
14 for (var name in all)
15 __defProp(target, name, { get: all[name], enumerable: true });
16 };
17 var __copyProps = (to, from, except, desc) => {
18 if (from && typeof from === "object" || typeof from === "function") {
19 for (let key of __getOwnPropNames(from))
20 if (!__hasOwnProp.call(to, key) && key !== except)
21 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22 }
23 return to;
24 };
25 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26 // If the importer is in node compatibility mode or this is not an ESM
27 // file that has been converted to a CommonJS file using a Babel-
28 // compatible transform (i.e. "__esModule" has not been set), then set
29 // "default" to the CommonJS "module.exports" for node compatibility.
30 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31 mod
32 ));
33 var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
35 // package-external:@wordpress/i18n
36 var require_i18n = __commonJS({
37 "package-external:@wordpress/i18n"(exports, module) {
38 module.exports = window.wp.i18n;
39 }
40 });
41
42 // package-external:@wordpress/url
43 var require_url = __commonJS({
44 "package-external:@wordpress/url"(exports, module) {
45 module.exports = window.wp.url;
46 }
47 });
48
49 // packages/api-fetch/build-module/index.mjs
50 var index_exports = {};
51 __export(index_exports, {
52 default: () => index_default
53 });
54 var import_i18n3 = __toESM(require_i18n(), 1);
55
56 // packages/api-fetch/build-module/middlewares/nonce.mjs
57 function createNonceMiddleware(nonce) {
58 const middleware = (options, next) => {
59 const { headers = {} } = options;
60 for (const headerName in headers) {
61 if (headerName.toLowerCase() === "x-wp-nonce" && headers[headerName] === middleware.nonce) {
62 return next(options);
63 }
64 }
65 return next({
66 ...options,
67 headers: {
68 ...headers,
69 "X-WP-Nonce": middleware.nonce
70 }
71 });
72 };
73 middleware.nonce = nonce;
74 return middleware;
75 }
76 var nonce_default = createNonceMiddleware;
77
78 // packages/api-fetch/build-module/middlewares/namespace-endpoint.mjs
79 var namespaceAndEndpointMiddleware = (options, next) => {
80 let path = options.path;
81 let namespaceTrimmed, endpointTrimmed;
82 if (typeof options.namespace === "string" && typeof options.endpoint === "string") {
83 namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, "");
84 endpointTrimmed = options.endpoint.replace(/^\//, "");
85 if (endpointTrimmed) {
86 path = namespaceTrimmed + "/" + endpointTrimmed;
87 } else {
88 path = namespaceTrimmed;
89 }
90 }
91 delete options.namespace;
92 delete options.endpoint;
93 return next({
94 ...options,
95 path
96 });
97 };
98 var namespace_endpoint_default = namespaceAndEndpointMiddleware;
99
100 // packages/api-fetch/build-module/middlewares/root-url.mjs
101 var createRootURLMiddleware = (rootURL) => (options, next) => {
102 return namespace_endpoint_default(options, (optionsWithPath) => {
103 let url = optionsWithPath.url;
104 let path = optionsWithPath.path;
105 let apiRoot;
106 if (typeof path === "string") {
107 apiRoot = rootURL;
108 if (-1 !== rootURL.indexOf("?")) {
109 path = path.replace("?", "&");
110 }
111 path = path.replace(/^\//, "");
112 if ("string" === typeof apiRoot && -1 !== apiRoot.indexOf("?")) {
113 path = path.replace("?", "&");
114 }
115 url = apiRoot + path;
116 }
117 return next({
118 ...optionsWithPath,
119 url
120 });
121 });
122 };
123 var root_url_default = createRootURLMiddleware;
124
125 // packages/api-fetch/build-module/middlewares/preloading.mjs
126 var import_url = __toESM(require_url(), 1);
127 function createPreloadingMiddleware(preloadedData) {
128 const cache = Object.fromEntries(
129 Object.entries(preloadedData).map(([path, data]) => [
130 (0, import_url.normalizePath)(path),
131 data
132 ])
133 );
134 return (options, next) => {
135 const { parse = true } = options;
136 let rawPath = options.path;
137 if (!rawPath && options.url) {
138 const { rest_route: pathFromQuery, ...queryArgs } = (0, import_url.getQueryArgs)(
139 options.url
140 );
141 if (typeof pathFromQuery === "string") {
142 rawPath = (0, import_url.addQueryArgs)(pathFromQuery, queryArgs);
143 }
144 }
145 if (typeof rawPath !== "string") {
146 return next(options);
147 }
148 const method = options.method || "GET";
149 const path = (0, import_url.normalizePath)(rawPath);
150 if ("GET" === method && cache[path]) {
151 const cacheData = cache[path];
152 delete cache[path];
153 return prepareResponse(cacheData, !!parse);
154 } else if ("OPTIONS" === method && cache[method] && cache[method][path]) {
155 const cacheData = cache[method][path];
156 delete cache[method][path];
157 return prepareResponse(cacheData, !!parse);
158 }
159 return next(options);
160 };
161 }
162 function prepareResponse(responseData, parse) {
163 if (parse) {
164 return Promise.resolve(responseData.body);
165 }
166 try {
167 return Promise.resolve(
168 new window.Response(JSON.stringify(responseData.body), {
169 status: 200,
170 statusText: "OK",
171 headers: responseData.headers
172 })
173 );
174 } catch {
175 Object.entries(
176 responseData.headers
177 ).forEach(([key, value]) => {
178 if (key.toLowerCase() === "link") {
179 responseData.headers[key] = value.replace(
180 /<([^>]+)>/,
181 (_, url) => `<${encodeURI(url)}>`
182 );
183 }
184 });
185 return Promise.resolve(
186 parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
187 status: 200,
188 statusText: "OK",
189 headers: responseData.headers
190 })
191 );
192 }
193 }
194 var preloading_default = createPreloadingMiddleware;
195
196 // packages/api-fetch/build-module/middlewares/fetch-all-middleware.mjs
197 var import_url2 = __toESM(require_url(), 1);
198 var modifyQuery = ({ path, url, ...options }, queryArgs) => ({
199 ...options,
200 url: url && (0, import_url2.addQueryArgs)(url, queryArgs),
201 path: path && (0, import_url2.addQueryArgs)(path, queryArgs)
202 });
203 var parseResponse = (response) => response.json ? response.json() : Promise.reject(response);
204 var parseLinkHeader = (linkHeader) => {
205 if (!linkHeader) {
206 return {};
207 }
208 const match = linkHeader.match(/<([^>]+)>; rel="next"/);
209 return match ? {
210 next: match[1]
211 } : {};
212 };
213 var getNextPageUrl = (response) => {
214 const { next } = parseLinkHeader(response.headers.get("link"));
215 return next;
216 };
217 var requestContainsUnboundedQuery = (options) => {
218 const pathIsUnbounded = !!options.path && options.path.indexOf("per_page=-1") !== -1;
219 const urlIsUnbounded = !!options.url && options.url.indexOf("per_page=-1") !== -1;
220 return pathIsUnbounded || urlIsUnbounded;
221 };
222 var fetchAllMiddleware = async (options, next) => {
223 if (options.parse === false) {
224 return next(options);
225 }
226 if (!requestContainsUnboundedQuery(options)) {
227 return next(options);
228 }
229 const response = await index_default({
230 ...modifyQuery(options, {
231 per_page: 100
232 }),
233 // Ensure headers are returned for page 1.
234 parse: false
235 });
236 const results = await parseResponse(response);
237 if (!Array.isArray(results)) {
238 return results;
239 }
240 let nextPage = getNextPageUrl(response);
241 if (!nextPage) {
242 return results;
243 }
244 let mergedResults = [].concat(results);
245 while (nextPage) {
246 const nextResponse = await index_default({
247 ...options,
248 // Ensure the URL for the next page is used instead of any provided path.
249 path: void 0,
250 url: nextPage,
251 // Ensure we still get headers so we can identify the next page.
252 parse: false
253 });
254 const nextResults = await parseResponse(nextResponse);
255 mergedResults = mergedResults.concat(nextResults);
256 nextPage = getNextPageUrl(nextResponse);
257 }
258 return mergedResults;
259 };
260 var fetch_all_middleware_default = fetchAllMiddleware;
261
262 // packages/api-fetch/build-module/middlewares/http-v1.mjs
263 var OVERRIDE_METHODS = /* @__PURE__ */ new Set(["PATCH", "PUT", "DELETE"]);
264 var DEFAULT_METHOD = "GET";
265 var httpV1Middleware = (options, next) => {
266 const { method = DEFAULT_METHOD } = options;
267 if (OVERRIDE_METHODS.has(method.toUpperCase())) {
268 options = {
269 ...options,
270 headers: {
271 "Content-Type": "application/json",
272 ...options.headers,
273 "X-HTTP-Method-Override": method
274 },
275 method: "POST"
276 };
277 }
278 return next(options);
279 };
280 var http_v1_default = httpV1Middleware;
281
282 // packages/api-fetch/build-module/middlewares/user-locale.mjs
283 var import_url3 = __toESM(require_url(), 1);
284 var userLocaleMiddleware = (options, next) => {
285 if (typeof options.url === "string" && !(0, import_url3.hasQueryArg)(options.url, "_locale")) {
286 options.url = (0, import_url3.addQueryArgs)(options.url, { _locale: "user" });
287 }
288 if (typeof options.path === "string" && !(0, import_url3.hasQueryArg)(options.path, "_locale")) {
289 options.path = (0, import_url3.addQueryArgs)(options.path, { _locale: "user" });
290 }
291 return next(options);
292 };
293 var user_locale_default = userLocaleMiddleware;
294
295 // packages/api-fetch/build-module/middlewares/media-upload.mjs
296 var import_i18n2 = __toESM(require_i18n(), 1);
297
298 // packages/api-fetch/build-module/utils/response.mjs
299 var import_i18n = __toESM(require_i18n(), 1);
300 async function parseJsonAndNormalizeError(response) {
301 try {
302 return await response.json();
303 } catch {
304 throw {
305 code: "invalid_json",
306 message: (0, import_i18n.__)("The response is not a valid JSON response.")
307 };
308 }
309 }
310 async function parseResponseAndNormalizeError(response, shouldParseResponse = true) {
311 if (!shouldParseResponse) {
312 return response;
313 }
314 if (response.status === 204) {
315 return null;
316 }
317 return await parseJsonAndNormalizeError(response);
318 }
319 async function parseAndThrowError(response, shouldParseResponse = true) {
320 if (!shouldParseResponse) {
321 throw response;
322 }
323 throw await parseJsonAndNormalizeError(response);
324 }
325
326 // packages/api-fetch/build-module/middlewares/media-upload.mjs
327 function isMediaUploadRequest(options) {
328 const isCreateMethod = !!options.method && options.method === "POST";
329 const isMediaEndpoint = !!options.path && options.path.indexOf("/wp/v2/media") !== -1 || !!options.url && options.url.indexOf("/wp/v2/media") !== -1;
330 return isMediaEndpoint && isCreateMethod;
331 }
332 var mediaUploadMiddleware = (options, next) => {
333 if (!isMediaUploadRequest(options)) {
334 return next(options);
335 }
336 let retries = 0;
337 const maxRetries = 5;
338 const postProcess = (attachmentId) => {
339 retries++;
340 return next({
341 path: `/wp/v2/media/${attachmentId}/post-process`,
342 method: "POST",
343 data: { action: "create-image-subsizes" },
344 parse: false
345 }).catch(() => {
346 if (retries < maxRetries) {
347 return postProcess(attachmentId);
348 }
349 next({
350 path: `/wp/v2/media/${attachmentId}?force=true`,
351 method: "DELETE"
352 });
353 return Promise.reject();
354 });
355 };
356 return next({ ...options, parse: false }).catch((response) => {
357 if (!(response instanceof globalThis.Response)) {
358 return Promise.reject(response);
359 }
360 const attachmentId = response.headers.get(
361 "x-wp-upload-attachment-id"
362 );
363 if (response.status >= 500 && response.status < 600 && attachmentId) {
364 return postProcess(attachmentId).catch(() => {
365 if (options.parse !== false) {
366 return Promise.reject({
367 code: "post_process",
368 message: (0, import_i18n2.__)(
369 "Media upload failed. If this is a photo or a large image, please scale it down and try again."
370 )
371 });
372 }
373 return Promise.reject(response);
374 });
375 }
376 return parseAndThrowError(response, options.parse);
377 }).then(
378 (response) => parseResponseAndNormalizeError(response, options.parse)
379 );
380 };
381 var media_upload_default = mediaUploadMiddleware;
382
383 // packages/api-fetch/build-module/middlewares/theme-preview.mjs
384 var import_url4 = __toESM(require_url(), 1);
385 var createThemePreviewMiddleware = (themePath) => (options, next) => {
386 if (typeof options.url === "string") {
387 const wpThemePreview = (0, import_url4.getQueryArg)(
388 options.url,
389 "wp_theme_preview"
390 );
391 if (wpThemePreview === void 0) {
392 options.url = (0, import_url4.addQueryArgs)(options.url, {
393 wp_theme_preview: themePath
394 });
395 } else if (wpThemePreview === "") {
396 options.url = (0, import_url4.removeQueryArgs)(
397 options.url,
398 "wp_theme_preview"
399 );
400 }
401 }
402 if (typeof options.path === "string") {
403 const wpThemePreview = (0, import_url4.getQueryArg)(
404 options.path,
405 "wp_theme_preview"
406 );
407 if (wpThemePreview === void 0) {
408 options.path = (0, import_url4.addQueryArgs)(options.path, {
409 wp_theme_preview: themePath
410 });
411 } else if (wpThemePreview === "") {
412 options.path = (0, import_url4.removeQueryArgs)(
413 options.path,
414 "wp_theme_preview"
415 );
416 }
417 }
418 return next(options);
419 };
420 var theme_preview_default = createThemePreviewMiddleware;
421
422 // packages/api-fetch/build-module/index.mjs
423 var DEFAULT_HEADERS = {
424 // The backend uses the Accept header as a condition for considering an
425 // incoming request as a REST request.
426 //
427 // See: https://core.trac.wordpress.org/ticket/44534
428 Accept: "application/json, */*;q=0.1"
429 };
430 var DEFAULT_OPTIONS = {
431 credentials: "include"
432 };
433 var middlewares = [
434 user_locale_default,
435 namespace_endpoint_default,
436 http_v1_default,
437 fetch_all_middleware_default
438 ];
439 function registerMiddleware(middleware) {
440 middlewares.unshift(middleware);
441 }
442 var defaultFetchHandler = (nextOptions) => {
443 const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
444 let { body, headers } = nextOptions;
445 headers = { ...DEFAULT_HEADERS, ...headers };
446 if (data) {
447 body = JSON.stringify(data);
448 headers["Content-Type"] = "application/json";
449 }
450 const responsePromise = globalThis.fetch(
451 // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
452 url || path || window.location.href,
453 {
454 ...DEFAULT_OPTIONS,
455 ...remainingOptions,
456 body,
457 headers
458 }
459 );
460 return responsePromise.then(
461 (response) => {
462 if (!response.ok) {
463 return parseAndThrowError(response, parse);
464 }
465 return parseResponseAndNormalizeError(response, parse);
466 },
467 (err) => {
468 if (err && err.name === "AbortError") {
469 throw err;
470 }
471 if (!globalThis.navigator.onLine) {
472 throw {
473 code: "offline_error",
474 message: (0, import_i18n3.__)(
475 "Unable to connect. Please check your Internet connection."
476 )
477 };
478 }
479 throw {
480 code: "fetch_error",
481 message: (0, import_i18n3.__)(
482 "Could not get a valid response from the server."
483 )
484 };
485 }
486 );
487 };
488 var fetchHandler = defaultFetchHandler;
489 function setFetchHandler(newFetchHandler) {
490 fetchHandler = newFetchHandler;
491 }
492 var apiFetch = (options) => {
493 const enhancedHandler = middlewares.reduceRight(
494 (next, middleware) => {
495 return (workingOptions) => middleware(workingOptions, next);
496 },
497 fetchHandler
498 );
499 return enhancedHandler(options).catch((error) => {
500 if (error.code !== "rest_cookie_invalid_nonce") {
501 return Promise.reject(error);
502 }
503 return globalThis.fetch(apiFetch.nonceEndpoint).then((response) => {
504 if (!response.ok) {
505 return Promise.reject(error);
506 }
507 return response.text();
508 }).then((text) => {
509 apiFetch.nonceMiddleware.nonce = text;
510 return apiFetch(options);
511 });
512 });
513 };
514 apiFetch.use = registerMiddleware;
515 apiFetch.setFetchHandler = setFetchHandler;
516 apiFetch.createNonceMiddleware = nonce_default;
517 apiFetch.createPreloadingMiddleware = preloading_default;
518 apiFetch.createRootURLMiddleware = root_url_default;
519 apiFetch.fetchAllMiddleware = fetch_all_middleware_default;
520 apiFetch.mediaUploadMiddleware = media_upload_default;
521 apiFetch.createThemePreviewMiddleware = theme_preview_default;
522 var index_default = apiFetch;
523 return __toCommonJS(index_exports);
524 })();
525 if (typeof wp.apiFetch === 'object' && wp.apiFetch.default) { wp.apiFetch = wp.apiFetch.default; }
526 //# sourceMappingURL=index.js.map
527