fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

185
node_modules/@wordpress/api-fetch/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,185 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _nonce = _interopRequireDefault(require("./middlewares/nonce"));
var _rootUrl = _interopRequireDefault(require("./middlewares/root-url"));
var _preloading = _interopRequireDefault(require("./middlewares/preloading"));
var _fetchAllMiddleware = _interopRequireDefault(require("./middlewares/fetch-all-middleware"));
var _namespaceEndpoint = _interopRequireDefault(require("./middlewares/namespace-endpoint"));
var _httpV = _interopRequireDefault(require("./middlewares/http-v1"));
var _userLocale = _interopRequireDefault(require("./middlewares/user-locale"));
var _mediaUpload = _interopRequireDefault(require("./middlewares/media-upload"));
var _themePreview = _interopRequireDefault(require("./middlewares/theme-preview"));
var _response = require("./utils/response");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Default set of header values which should be sent with every request unless
* explicitly provided through apiFetch options.
*
* @type {Record<string, string>}
*/
const DEFAULT_HEADERS = {
// The backend uses the Accept header as a condition for considering an
// incoming request as a REST request.
//
// See: https://core.trac.wordpress.org/ticket/44534
Accept: 'application/json, */*;q=0.1'
};
/**
* Default set of fetch option values which should be sent with every request
* unless explicitly provided through apiFetch options.
*
* @type {Object}
*/
const DEFAULT_OPTIONS = {
credentials: 'include'
};
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
/**
* @type {import('./types').APIFetchMiddleware[]}
*/
const middlewares = [_userLocale.default, _namespaceEndpoint.default, _httpV.default, _fetchAllMiddleware.default];
/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
function registerMiddleware(middleware) {
middlewares.unshift(middleware);
}
/**
* Checks the status of a response, throwing the Response as an error if
* it is outside the 200 range.
*
* @param {Response} response
* @return {Response} The response if the status is in the 200 range.
*/
const checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw response;
};
/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
/**
* @type {FetchHandler}
*/
const defaultFetchHandler = nextOptions => {
const {
url,
path,
data,
parse = true,
...remainingOptions
} = nextOptions;
let {
body,
headers
} = nextOptions;
// Merge explicitly-provided headers with default values.
headers = {
...DEFAULT_HEADERS,
...headers
};
// The `data` property is a shorthand for sending a JSON body.
if (data) {
body = JSON.stringify(data);
headers['Content-Type'] = 'application/json';
}
const responsePromise = window.fetch(
// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
url || path || window.location.href, {
...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers
});
return responsePromise.then(value => Promise.resolve(value).then(checkStatus).catch(response => (0, _response.parseAndThrowError)(response, parse)).then(response => (0, _response.parseResponseAndNormalizeError)(response, parse)), err => {
// Re-throw AbortError for the users to handle it themselves.
if (err && err.name === 'AbortError') {
throw err;
}
// Otherwise, there is most likely no network connection.
// Unfortunately the message might depend on the browser.
throw {
code: 'fetch_error',
message: (0, _i18n.__)('You are probably offline.')
};
});
};
/** @type {FetchHandler} */
let fetchHandler = defaultFetchHandler;
/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {FetchHandler} newFetchHandler The new fetch handler
*/
function setFetchHandler(newFetchHandler) {
fetchHandler = newFetchHandler;
}
/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
function apiFetch(options) {
// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
// converting `middlewares = [ m1, m2, m3 ]` into:
// ```
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
// ```
const enhancedHandler = middlewares.reduceRight(( /** @type {FetchHandler} */next, middleware) => {
return workingOptions => middleware(workingOptions, next);
}, fetchHandler);
return enhancedHandler(options).catch(error => {
if (error.code !== 'rest_cookie_invalid_nonce') {
return Promise.reject(error);
}
// If the nonce is invalid, refresh it and try again.
return window
// @ts-ignore
.fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
// @ts-ignore
apiFetch.nonceMiddleware.nonce = text;
return apiFetch(options);
});
});
}
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;
apiFetch.createNonceMiddleware = _nonce.default;
apiFetch.createPreloadingMiddleware = _preloading.default;
apiFetch.createRootURLMiddleware = _rootUrl.default;
apiFetch.fetchAllMiddleware = _fetchAllMiddleware.default;
apiFetch.mediaUploadMiddleware = _mediaUpload.default;
apiFetch.createThemePreviewMiddleware = _themePreview.default;
var _default = exports.default = apiFetch;
//# sourceMappingURL=index.js.map

1
node_modules/@wordpress/api-fetch/build/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,132 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
var _ = _interopRequireDefault(require(".."));
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Apply query arguments to both URL and Path, whichever is present.
*
* @param {import('../types').APIFetchOptions} props
* @param {Record<string, string | number>} queryArgs
* @return {import('../types').APIFetchOptions} The request with the modified query args
*/
const modifyQuery = ({
path,
url,
...options
}, queryArgs) => ({
...options,
url: url && (0, _url.addQueryArgs)(url, queryArgs),
path: path && (0, _url.addQueryArgs)(path, queryArgs)
});
/**
* Duplicates parsing functionality from apiFetch.
*
* @param {Response} response
* @return {Promise<any>} Parsed response json.
*/
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
/**
* @param {string | null} linkHeader
* @return {{ next?: string }} The parsed link header.
*/
const parseLinkHeader = linkHeader => {
if (!linkHeader) {
return {};
}
const match = linkHeader.match(/<([^>]+)>; rel="next"/);
return match ? {
next: match[1]
} : {};
};
/**
* @param {Response} response
* @return {string | undefined} The next page URL.
*/
const getNextPageUrl = response => {
const {
next
} = parseLinkHeader(response.headers.get('link'));
return next;
};
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request contains an unbounded query.
*/
const requestContainsUnboundedQuery = options => {
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
return pathIsUnbounded || urlIsUnbounded;
};
/**
* The REST API enforces an upper limit on the per_page option. To handle large
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
* then recursively assemble a full response array from all available pages.
*
* @type {import('../types').APIFetchMiddleware}
*/
const fetchAllMiddleware = async (options, next) => {
if (options.parse === false) {
// If a consumer has opted out of parsing, do not apply middleware.
return next(options);
}
if (!requestContainsUnboundedQuery(options)) {
// If neither url nor path is requesting all items, do not apply middleware.
return next(options);
}
// Retrieve requested page of results.
const response = await (0, _.default)({
...modifyQuery(options, {
per_page: 100
}),
// Ensure headers are returned for page 1.
parse: false
});
const results = await parseResponse(response);
if (!Array.isArray(results)) {
// We have no reliable way of merging non-array results.
return results;
}
let nextPage = getNextPageUrl(response);
if (!nextPage) {
// There are no further pages to request.
return results;
}
// Iteratively fetch all remaining pages until no "next" header is found.
let mergedResults = /** @type {any[]} */[].concat(results);
while (nextPage) {
const nextResponse = await (0, _.default)({
...options,
// Ensure the URL for the next page is used instead of any provided path.
path: undefined,
url: nextPage,
// Ensure we still get headers so we can identify the next page.
parse: false
});
const nextResults = await parseResponse(nextResponse);
mergedResults = mergedResults.concat(nextResults);
nextPage = getNextPageUrl(nextResponse);
}
return mergedResults;
};
var _default = exports.default = fetchAllMiddleware;
//# sourceMappingURL=fetch-all-middleware.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* Set of HTTP methods which are eligible to be overridden.
*
* @type {Set<string>}
*/
const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
/**
* Default request method.
*
* "A request has an associated method (a method). Unless stated otherwise it
* is `GET`."
*
* @see https://fetch.spec.whatwg.org/#requests
*
* @type {string}
*/
const DEFAULT_METHOD = 'GET';
/**
* API Fetch middleware which overrides the request method for HTTP v1
* compatibility leveraging the REST API X-HTTP-Method-Override header.
*
* @type {import('../types').APIFetchMiddleware}
*/
const httpV1Middleware = (options, next) => {
const {
method = DEFAULT_METHOD
} = options;
if (OVERRIDE_METHODS.has(method.toUpperCase())) {
options = {
...options,
headers: {
...options.headers,
'X-HTTP-Method-Override': method,
'Content-Type': 'application/json'
},
method: 'POST'
};
}
return next(options);
};
var _default = exports.default = httpV1Middleware;
//# sourceMappingURL=http-v1.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["OVERRIDE_METHODS","Set","DEFAULT_METHOD","httpV1Middleware","options","next","method","has","toUpperCase","headers","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/http-v1.js"],"sourcesContent":["/**\n * Set of HTTP methods which are eligible to be overridden.\n *\n * @type {Set<string>}\n */\nconst OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] );\n\n/**\n * Default request method.\n *\n * \"A request has an associated method (a method). Unless stated otherwise it\n * is `GET`.\"\n *\n * @see https://fetch.spec.whatwg.org/#requests\n *\n * @type {string}\n */\nconst DEFAULT_METHOD = 'GET';\n\n/**\n * API Fetch middleware which overrides the request method for HTTP v1\n * compatibility leveraging the REST API X-HTTP-Method-Override header.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst httpV1Middleware = ( options, next ) => {\n\tconst { method = DEFAULT_METHOD } = options;\n\tif ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {\n\t\toptions = {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...options.headers,\n\t\t\t\t'X-HTTP-Method-Override': method,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t};\n\t}\n\n\treturn next( options );\n};\n\nexport default httpV1Middleware;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,MAAMA,gBAAgB,GAAG,IAAIC,GAAG,CAAE,CAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAG,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,cAAc,GAAG,KAAK;;AAE5B;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,gBAAgB,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC7C,MAAM;IAAEC,MAAM,GAAGJ;EAAe,CAAC,GAAGE,OAAO;EAC3C,IAAKJ,gBAAgB,CAACO,GAAG,CAAED,MAAM,CAACE,WAAW,CAAC,CAAE,CAAC,EAAG;IACnDJ,OAAO,GAAG;MACT,GAAGA,OAAO;MACVK,OAAO,EAAE;QACR,GAAGL,OAAO,CAACK,OAAO;QAClB,wBAAwB,EAAEH,MAAM;QAChC,cAAc,EAAE;MACjB,CAAC;MACDA,MAAM,EAAE;IACT,CAAC;EACF;EAEA,OAAOD,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAM,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaT,gBAAgB","ignoreList":[]}

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _response = require("../utils/response");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request is for media upload.
*/
function isMediaUploadRequest(options) {
const isCreateMethod = !!options.method && options.method === 'POST';
const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
return isMediaEndpoint && isCreateMethod;
}
/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = (options, next) => {
if (!isMediaUploadRequest(options)) {
return next(options);
}
let retries = 0;
const maxRetries = 5;
/**
* @param {string} attachmentId
* @return {Promise<any>} Processed post response.
*/
const postProcess = attachmentId => {
retries++;
return next({
path: `/wp/v2/media/${attachmentId}/post-process`,
method: 'POST',
data: {
action: 'create-image-subsizes'
},
parse: false
}).catch(() => {
if (retries < maxRetries) {
return postProcess(attachmentId);
}
next({
path: `/wp/v2/media/${attachmentId}?force=true`,
method: 'DELETE'
});
return Promise.reject();
});
};
return next({
...options,
parse: false
}).catch(response => {
const attachmentId = response.headers.get('x-wp-upload-attachment-id');
if (response.status >= 500 && response.status < 600 && attachmentId) {
return postProcess(attachmentId).catch(() => {
if (options.parse !== false) {
return Promise.reject({
code: 'post_process',
message: (0, _i18n.__)('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
});
}
return Promise.reject(response);
});
}
return (0, _response.parseAndThrowError)(response, options.parse);
}).then(response => (0, _response.parseResponseAndNormalizeError)(response, options.parse));
};
var _default = exports.default = mediaUploadMiddleware;
//# sourceMappingURL=media-upload.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @type {import('../types').APIFetchMiddleware}
*/
const namespaceAndEndpointMiddleware = (options, next) => {
let path = options.path;
let namespaceTrimmed, endpointTrimmed;
if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
endpointTrimmed = options.endpoint.replace(/^\//, '');
if (endpointTrimmed) {
path = namespaceTrimmed + '/' + endpointTrimmed;
} else {
path = namespaceTrimmed;
}
}
delete options.namespace;
delete options.endpoint;
return next({
...options,
path
});
};
var _default = exports.default = namespaceAndEndpointMiddleware;
//# sourceMappingURL=namespace-endpoint.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["namespaceAndEndpointMiddleware","options","next","path","namespaceTrimmed","endpointTrimmed","namespace","endpoint","replace","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/namespace-endpoint.js"],"sourcesContent":["/**\n * @type {import('../types').APIFetchMiddleware}\n */\nconst namespaceAndEndpointMiddleware = ( options, next ) => {\n\tlet path = options.path;\n\tlet namespaceTrimmed, endpointTrimmed;\n\n\tif (\n\t\ttypeof options.namespace === 'string' &&\n\t\ttypeof options.endpoint === 'string'\n\t) {\n\t\tnamespaceTrimmed = options.namespace.replace( /^\\/|\\/$/g, '' );\n\t\tendpointTrimmed = options.endpoint.replace( /^\\//, '' );\n\t\tif ( endpointTrimmed ) {\n\t\t\tpath = namespaceTrimmed + '/' + endpointTrimmed;\n\t\t} else {\n\t\t\tpath = namespaceTrimmed;\n\t\t}\n\t}\n\n\tdelete options.namespace;\n\tdelete options.endpoint;\n\n\treturn next( {\n\t\t...options,\n\t\tpath,\n\t} );\n};\n\nexport default namespaceAndEndpointMiddleware;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA,MAAMA,8BAA8B,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC3D,IAAIC,IAAI,GAAGF,OAAO,CAACE,IAAI;EACvB,IAAIC,gBAAgB,EAAEC,eAAe;EAErC,IACC,OAAOJ,OAAO,CAACK,SAAS,KAAK,QAAQ,IACrC,OAAOL,OAAO,CAACM,QAAQ,KAAK,QAAQ,EACnC;IACDH,gBAAgB,GAAGH,OAAO,CAACK,SAAS,CAACE,OAAO,CAAE,UAAU,EAAE,EAAG,CAAC;IAC9DH,eAAe,GAAGJ,OAAO,CAACM,QAAQ,CAACC,OAAO,CAAE,KAAK,EAAE,EAAG,CAAC;IACvD,IAAKH,eAAe,EAAG;MACtBF,IAAI,GAAGC,gBAAgB,GAAG,GAAG,GAAGC,eAAe;IAChD,CAAC,MAAM;MACNF,IAAI,GAAGC,gBAAgB;IACxB;EACD;EAEA,OAAOH,OAAO,CAACK,SAAS;EACxB,OAAOL,OAAO,CAACM,QAAQ;EAEvB,OAAOL,IAAI,CAAE;IACZ,GAAGD,OAAO;IACVE;EACD,CAAE,CAAC;AACJ,CAAC;AAAC,IAAAM,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaX,8BAA8B","ignoreList":[]}

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @param {string} nonce
* @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
*/
function createNonceMiddleware(nonce) {
/**
* @type {import('../types').APIFetchMiddleware & { nonce: string }}
*/
const middleware = (options, next) => {
const {
headers = {}
} = options;
// If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
for (const headerName in headers) {
if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
return next(options);
}
}
return next({
...options,
headers: {
...headers,
'X-WP-Nonce': middleware.nonce
}
});
};
middleware.nonce = nonce;
return middleware;
}
var _default = exports.default = createNonceMiddleware;
//# sourceMappingURL=nonce.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createNonceMiddleware","nonce","middleware","options","next","headers","headerName","toLowerCase","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/nonce.js"],"sourcesContent":["/**\n * @param {string} nonce\n * @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.\n */\nfunction createNonceMiddleware( nonce ) {\n\t/**\n\t * @type {import('../types').APIFetchMiddleware & { nonce: string }}\n\t */\n\tconst middleware = ( options, next ) => {\n\t\tconst { headers = {} } = options;\n\n\t\t// If an 'X-WP-Nonce' header (or any case-insensitive variation\n\t\t// thereof) was specified, no need to add a nonce header.\n\t\tfor ( const headerName in headers ) {\n\t\t\tif (\n\t\t\t\theaderName.toLowerCase() === 'x-wp-nonce' &&\n\t\t\t\theaders[ headerName ] === middleware.nonce\n\t\t\t) {\n\t\t\t\treturn next( options );\n\t\t\t}\n\t\t}\n\n\t\treturn next( {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...headers,\n\t\t\t\t'X-WP-Nonce': middleware.nonce,\n\t\t\t},\n\t\t} );\n\t};\n\n\tmiddleware.nonce = nonce;\n\n\treturn middleware;\n}\n\nexport default createNonceMiddleware;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA,SAASA,qBAAqBA,CAAEC,KAAK,EAAG;EACvC;AACD;AACA;EACC,MAAMC,UAAU,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;IACvC,MAAM;MAAEC,OAAO,GAAG,CAAC;IAAE,CAAC,GAAGF,OAAO;;IAEhC;IACA;IACA,KAAM,MAAMG,UAAU,IAAID,OAAO,EAAG;MACnC,IACCC,UAAU,CAACC,WAAW,CAAC,CAAC,KAAK,YAAY,IACzCF,OAAO,CAAEC,UAAU,CAAE,KAAKJ,UAAU,CAACD,KAAK,EACzC;QACD,OAAOG,IAAI,CAAED,OAAQ,CAAC;MACvB;IACD;IAEA,OAAOC,IAAI,CAAE;MACZ,GAAGD,OAAO;MACVE,OAAO,EAAE;QACR,GAAGA,OAAO;QACV,YAAY,EAAEH,UAAU,CAACD;MAC1B;IACD,CAAE,CAAC;EACJ,CAAC;EAEDC,UAAU,CAACD,KAAK,GAAGA,KAAK;EAExB,OAAOC,UAAU;AAClB;AAAC,IAAAM,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcV,qBAAqB","ignoreList":[]}

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
/**
* WordPress dependencies
*/
/**
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
function createPreloadingMiddleware(preloadedData) {
const cache = Object.fromEntries(Object.entries(preloadedData).map(([path, data]) => [(0, _url.normalizePath)(path), data]));
return (options, next) => {
const {
parse = true
} = options;
/** @type {string | void} */
let rawPath = options.path;
if (!rawPath && options.url) {
const {
rest_route: pathFromQuery,
...queryArgs
} = (0, _url.getQueryArgs)(options.url);
if (typeof pathFromQuery === 'string') {
rawPath = (0, _url.addQueryArgs)(pathFromQuery, queryArgs);
}
}
if (typeof rawPath !== 'string') {
return next(options);
}
const method = options.method || 'GET';
const path = (0, _url.normalizePath)(rawPath);
if ('GET' === method && cache[path]) {
const cacheData = cache[path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[path];
return prepareResponse(cacheData, !!parse);
} else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
const cacheData = cache[method][path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[method][path];
return prepareResponse(cacheData, !!parse);
}
return next(options);
};
}
/**
* This is a helper function that sends a success response.
*
* @param {Record<string, any>} responseData
* @param {boolean} parse
* @return {Promise<any>} Promise with the response.
*/
function prepareResponse(responseData, parse) {
return Promise.resolve(parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
status: 200,
statusText: 'OK',
headers: responseData.headers
}));
}
var _default = exports.default = createPreloadingMiddleware;
//# sourceMappingURL=preloading.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_url","require","createPreloadingMiddleware","preloadedData","cache","Object","fromEntries","entries","map","path","data","normalizePath","options","next","parse","rawPath","url","rest_route","pathFromQuery","queryArgs","getQueryArgs","addQueryArgs","method","cacheData","prepareResponse","responseData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/preloading.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArgs, normalizePath } from '@wordpress/url';\n\n/**\n * @param {Record<string, any>} preloadedData\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nfunction createPreloadingMiddleware( preloadedData ) {\n\tconst cache = Object.fromEntries(\n\t\tObject.entries( preloadedData ).map( ( [ path, data ] ) => [\n\t\t\tnormalizePath( path ),\n\t\t\tdata,\n\t\t] )\n\t);\n\n\treturn ( options, next ) => {\n\t\tconst { parse = true } = options;\n\t\t/** @type {string | void} */\n\t\tlet rawPath = options.path;\n\t\tif ( ! rawPath && options.url ) {\n\t\t\tconst { rest_route: pathFromQuery, ...queryArgs } = getQueryArgs(\n\t\t\t\toptions.url\n\t\t\t);\n\n\t\t\tif ( typeof pathFromQuery === 'string' ) {\n\t\t\t\trawPath = addQueryArgs( pathFromQuery, queryArgs );\n\t\t\t}\n\t\t}\n\n\t\tif ( typeof rawPath !== 'string' ) {\n\t\t\treturn next( options );\n\t\t}\n\n\t\tconst method = options.method || 'GET';\n\t\tconst path = normalizePath( rawPath );\n\n\t\tif ( 'GET' === method && cache[ path ] ) {\n\t\t\tconst cacheData = cache[ path ];\n\n\t\t\t// Unsetting the cache key ensures that the data is only used a single time.\n\t\t\tdelete cache[ path ];\n\n\t\t\treturn prepareResponse( cacheData, !! parse );\n\t\t} else if (\n\t\t\t'OPTIONS' === method &&\n\t\t\tcache[ method ] &&\n\t\t\tcache[ method ][ path ]\n\t\t) {\n\t\t\tconst cacheData = cache[ method ][ path ];\n\n\t\t\t// Unsetting the cache key ensures that the data is only used a single time.\n\t\t\tdelete cache[ method ][ path ];\n\n\t\t\treturn prepareResponse( cacheData, !! parse );\n\t\t}\n\n\t\treturn next( options );\n\t};\n}\n\n/**\n * This is a helper function that sends a success response.\n *\n * @param {Record<string, any>} responseData\n * @param {boolean} parse\n * @return {Promise<any>} Promise with the response.\n */\nfunction prepareResponse( responseData, parse ) {\n\treturn Promise.resolve(\n\t\tparse\n\t\t\t? responseData.body\n\t\t\t: new window.Response( JSON.stringify( responseData.body ), {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\theaders: responseData.headers,\n\t\t\t } )\n\t);\n}\n\nexport default createPreloadingMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA,SAASC,0BAA0BA,CAAEC,aAAa,EAAG;EACpD,MAAMC,KAAK,GAAGC,MAAM,CAACC,WAAW,CAC/BD,MAAM,CAACE,OAAO,CAAEJ,aAAc,CAAC,CAACK,GAAG,CAAE,CAAE,CAAEC,IAAI,EAAEC,IAAI,CAAE,KAAM,CAC1D,IAAAC,kBAAa,EAAEF,IAAK,CAAC,EACrBC,IAAI,CACH,CACH,CAAC;EAED,OAAO,CAAEE,OAAO,EAAEC,IAAI,KAAM;IAC3B,MAAM;MAAEC,KAAK,GAAG;IAAK,CAAC,GAAGF,OAAO;IAChC;IACA,IAAIG,OAAO,GAAGH,OAAO,CAACH,IAAI;IAC1B,IAAK,CAAEM,OAAO,IAAIH,OAAO,CAACI,GAAG,EAAG;MAC/B,MAAM;QAAEC,UAAU,EAAEC,aAAa;QAAE,GAAGC;MAAU,CAAC,GAAG,IAAAC,iBAAY,EAC/DR,OAAO,CAACI,GACT,CAAC;MAED,IAAK,OAAOE,aAAa,KAAK,QAAQ,EAAG;QACxCH,OAAO,GAAG,IAAAM,iBAAY,EAAEH,aAAa,EAAEC,SAAU,CAAC;MACnD;IACD;IAEA,IAAK,OAAOJ,OAAO,KAAK,QAAQ,EAAG;MAClC,OAAOF,IAAI,CAAED,OAAQ,CAAC;IACvB;IAEA,MAAMU,MAAM,GAAGV,OAAO,CAACU,MAAM,IAAI,KAAK;IACtC,MAAMb,IAAI,GAAG,IAAAE,kBAAa,EAAEI,OAAQ,CAAC;IAErC,IAAK,KAAK,KAAKO,MAAM,IAAIlB,KAAK,CAAEK,IAAI,CAAE,EAAG;MACxC,MAAMc,SAAS,GAAGnB,KAAK,CAAEK,IAAI,CAAE;;MAE/B;MACA,OAAOL,KAAK,CAAEK,IAAI,CAAE;MAEpB,OAAOe,eAAe,CAAED,SAAS,EAAE,CAAC,CAAET,KAAM,CAAC;IAC9C,CAAC,MAAM,IACN,SAAS,KAAKQ,MAAM,IACpBlB,KAAK,CAAEkB,MAAM,CAAE,IACflB,KAAK,CAAEkB,MAAM,CAAE,CAAEb,IAAI,CAAE,EACtB;MACD,MAAMc,SAAS,GAAGnB,KAAK,CAAEkB,MAAM,CAAE,CAAEb,IAAI,CAAE;;MAEzC;MACA,OAAOL,KAAK,CAAEkB,MAAM,CAAE,CAAEb,IAAI,CAAE;MAE9B,OAAOe,eAAe,CAAED,SAAS,EAAE,CAAC,CAAET,KAAM,CAAC;IAC9C;IAEA,OAAOD,IAAI,CAAED,OAAQ,CAAC;EACvB,CAAC;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASY,eAAeA,CAAEC,YAAY,EAAEX,KAAK,EAAG;EAC/C,OAAOY,OAAO,CAACC,OAAO,CACrBb,KAAK,GACFW,YAAY,CAACG,IAAI,GACjB,IAAIC,MAAM,CAACC,QAAQ,CAAEC,IAAI,CAACC,SAAS,CAAEP,YAAY,CAACG,IAAK,CAAC,EAAE;IAC1DK,MAAM,EAAE,GAAG;IACXC,UAAU,EAAE,IAAI;IAChBC,OAAO,EAAEV,YAAY,CAACU;EACtB,CAAE,CACN,CAAC;AACF;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcpC,0BAA0B","ignoreList":[]}

View File

@@ -0,0 +1,43 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _namespaceEndpoint = _interopRequireDefault(require("./namespace-endpoint"));
/**
* Internal dependencies
*/
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = rootURL => (options, next) => {
return (0, _namespaceEndpoint.default)(options, optionsWithPath => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
if (typeof path === 'string') {
apiRoot = rootURL;
if (-1 !== rootURL.indexOf('?')) {
path = path.replace('?', '&');
}
path = path.replace(/^\//, '');
// API root may already include query parameter prefix if site is
// configured to use plain permalinks.
if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
path = path.replace('?', '&');
}
url = apiRoot + path;
}
return next({
...optionsWithPath,
url
});
});
};
var _default = exports.default = createRootURLMiddleware;
//# sourceMappingURL=root-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_namespaceEndpoint","_interopRequireDefault","require","createRootURLMiddleware","rootURL","options","next","namespaceAndEndpointMiddleware","optionsWithPath","url","path","apiRoot","indexOf","replace","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/root-url.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport namespaceAndEndpointMiddleware from './namespace-endpoint';\n\n/**\n * @param {string} rootURL\n * @return {import('../types').APIFetchMiddleware} Root URL middleware.\n */\nconst createRootURLMiddleware = ( rootURL ) => ( options, next ) => {\n\treturn namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => {\n\t\tlet url = optionsWithPath.url;\n\t\tlet path = optionsWithPath.path;\n\t\tlet apiRoot;\n\n\t\tif ( typeof path === 'string' ) {\n\t\t\tapiRoot = rootURL;\n\n\t\t\tif ( -1 !== rootURL.indexOf( '?' ) ) {\n\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t}\n\n\t\t\tpath = path.replace( /^\\//, '' );\n\n\t\t\t// API root may already include query parameter prefix if site is\n\t\t\t// configured to use plain permalinks.\n\t\t\tif (\n\t\t\t\t'string' === typeof apiRoot &&\n\t\t\t\t-1 !== apiRoot.indexOf( '?' )\n\t\t\t) {\n\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t}\n\n\t\t\turl = apiRoot + path;\n\t\t}\n\n\t\treturn next( {\n\t\t\t...optionsWithPath,\n\t\t\turl,\n\t\t} );\n\t} );\n};\n\nexport default createRootURLMiddleware;\n"],"mappings":";;;;;;;AAGA,IAAAA,kBAAA,GAAAC,sBAAA,CAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA,MAAMC,uBAAuB,GAAKC,OAAO,IAAM,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACnE,OAAO,IAAAC,0BAA8B,EAAEF,OAAO,EAAIG,eAAe,IAAM;IACtE,IAAIC,GAAG,GAAGD,eAAe,CAACC,GAAG;IAC7B,IAAIC,IAAI,GAAGF,eAAe,CAACE,IAAI;IAC/B,IAAIC,OAAO;IAEX,IAAK,OAAOD,IAAI,KAAK,QAAQ,EAAG;MAC/BC,OAAO,GAAGP,OAAO;MAEjB,IAAK,CAAC,CAAC,KAAKA,OAAO,CAACQ,OAAO,CAAE,GAAI,CAAC,EAAG;QACpCF,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,GAAG,EAAE,GAAI,CAAC;MAChC;MAEAH,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,KAAK,EAAE,EAAG,CAAC;;MAEhC;MACA;MACA,IACC,QAAQ,KAAK,OAAOF,OAAO,IAC3B,CAAC,CAAC,KAAKA,OAAO,CAACC,OAAO,CAAE,GAAI,CAAC,EAC5B;QACDF,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,GAAG,EAAE,GAAI,CAAC;MAChC;MAEAJ,GAAG,GAAGE,OAAO,GAAGD,IAAI;IACrB;IAEA,OAAOJ,IAAI,CAAE;MACZ,GAAGE,eAAe;MAClBC;IACD,CAAE,CAAC;EACJ,CAAE,CAAC;AACJ,CAAC;AAAC,IAAAK,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEab,uBAAuB","ignoreList":[]}

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
/**
* WordPress dependencies
*/
/**
* This appends a `wp_theme_preview` parameter to the REST API request URL if
* the admin URL contains a `theme` GET parameter.
*
* If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,
* then bypass this middleware.
*
* @param {Record<string, any>} themePath
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
const createThemePreviewMiddleware = themePath => (options, next) => {
if (typeof options.url === 'string') {
const wpThemePreview = (0, _url.getQueryArg)(options.url, 'wp_theme_preview');
if (wpThemePreview === undefined) {
options.url = (0, _url.addQueryArgs)(options.url, {
wp_theme_preview: themePath
});
} else if (wpThemePreview === '') {
options.url = (0, _url.removeQueryArgs)(options.url, 'wp_theme_preview');
}
}
if (typeof options.path === 'string') {
const wpThemePreview = (0, _url.getQueryArg)(options.path, 'wp_theme_preview');
if (wpThemePreview === undefined) {
options.path = (0, _url.addQueryArgs)(options.path, {
wp_theme_preview: themePath
});
} else if (wpThemePreview === '') {
options.path = (0, _url.removeQueryArgs)(options.path, 'wp_theme_preview');
}
}
return next(options);
};
var _default = exports.default = createThemePreviewMiddleware;
//# sourceMappingURL=theme-preview.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_url","require","createThemePreviewMiddleware","themePath","options","next","url","wpThemePreview","getQueryArg","undefined","addQueryArgs","wp_theme_preview","removeQueryArgs","path","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/theme-preview.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArg, removeQueryArgs } from '@wordpress/url';\n\n/**\n * This appends a `wp_theme_preview` parameter to the REST API request URL if\n * the admin URL contains a `theme` GET parameter.\n *\n * If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,\n * then bypass this middleware.\n *\n * @param {Record<string, any>} themePath\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nconst createThemePreviewMiddleware = ( themePath ) => ( options, next ) => {\n\tif ( typeof options.url === 'string' ) {\n\t\tconst wpThemePreview = getQueryArg( options.url, 'wp_theme_preview' );\n\t\tif ( wpThemePreview === undefined ) {\n\t\t\toptions.url = addQueryArgs( options.url, {\n\t\t\t\twp_theme_preview: themePath,\n\t\t\t} );\n\t\t} else if ( wpThemePreview === '' ) {\n\t\t\toptions.url = removeQueryArgs( options.url, 'wp_theme_preview' );\n\t\t}\n\t}\n\n\tif ( typeof options.path === 'string' ) {\n\t\tconst wpThemePreview = getQueryArg( options.path, 'wp_theme_preview' );\n\t\tif ( wpThemePreview === undefined ) {\n\t\t\toptions.path = addQueryArgs( options.path, {\n\t\t\t\twp_theme_preview: themePath,\n\t\t\t} );\n\t\t} else if ( wpThemePreview === '' ) {\n\t\t\toptions.path = removeQueryArgs( options.path, 'wp_theme_preview' );\n\t\t}\n\t}\n\n\treturn next( options );\n};\n\nexport default createThemePreviewMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,4BAA4B,GAAKC,SAAS,IAAM,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC1E,IAAK,OAAOD,OAAO,CAACE,GAAG,KAAK,QAAQ,EAAG;IACtC,MAAMC,cAAc,GAAG,IAAAC,gBAAW,EAAEJ,OAAO,CAACE,GAAG,EAAE,kBAAmB,CAAC;IACrE,IAAKC,cAAc,KAAKE,SAAS,EAAG;MACnCL,OAAO,CAACE,GAAG,GAAG,IAAAI,iBAAY,EAAEN,OAAO,CAACE,GAAG,EAAE;QACxCK,gBAAgB,EAAER;MACnB,CAAE,CAAC;IACJ,CAAC,MAAM,IAAKI,cAAc,KAAK,EAAE,EAAG;MACnCH,OAAO,CAACE,GAAG,GAAG,IAAAM,oBAAe,EAAER,OAAO,CAACE,GAAG,EAAE,kBAAmB,CAAC;IACjE;EACD;EAEA,IAAK,OAAOF,OAAO,CAACS,IAAI,KAAK,QAAQ,EAAG;IACvC,MAAMN,cAAc,GAAG,IAAAC,gBAAW,EAAEJ,OAAO,CAACS,IAAI,EAAE,kBAAmB,CAAC;IACtE,IAAKN,cAAc,KAAKE,SAAS,EAAG;MACnCL,OAAO,CAACS,IAAI,GAAG,IAAAH,iBAAY,EAAEN,OAAO,CAACS,IAAI,EAAE;QAC1CF,gBAAgB,EAAER;MACnB,CAAE,CAAC;IACJ,CAAC,MAAM,IAAKI,cAAc,KAAK,EAAE,EAAG;MACnCH,OAAO,CAACS,IAAI,GAAG,IAAAD,oBAAe,EAAER,OAAO,CAACS,IAAI,EAAE,kBAAmB,CAAC;IACnE;EACD;EAEA,OAAOR,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAU,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEad,4BAA4B","ignoreList":[]}

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
/**
* WordPress dependencies
*/
/**
* @type {import('../types').APIFetchMiddleware}
*/
const userLocaleMiddleware = (options, next) => {
if (typeof options.url === 'string' && !(0, _url.hasQueryArg)(options.url, '_locale')) {
options.url = (0, _url.addQueryArgs)(options.url, {
_locale: 'user'
});
}
if (typeof options.path === 'string' && !(0, _url.hasQueryArg)(options.path, '_locale')) {
options.path = (0, _url.addQueryArgs)(options.path, {
_locale: 'user'
});
}
return next(options);
};
var _default = exports.default = userLocaleMiddleware;
//# sourceMappingURL=user-locale.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_url","require","userLocaleMiddleware","options","next","url","hasQueryArg","addQueryArgs","_locale","path","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/user-locale.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, hasQueryArg } from '@wordpress/url';\n\n/**\n * @type {import('../types').APIFetchMiddleware}\n */\nconst userLocaleMiddleware = ( options, next ) => {\n\tif (\n\t\ttypeof options.url === 'string' &&\n\t\t! hasQueryArg( options.url, '_locale' )\n\t) {\n\t\toptions.url = addQueryArgs( options.url, { _locale: 'user' } );\n\t}\n\n\tif (\n\t\ttypeof options.path === 'string' &&\n\t\t! hasQueryArg( options.path, '_locale' )\n\t) {\n\t\toptions.path = addQueryArgs( options.path, { _locale: 'user' } );\n\t}\n\n\treturn next( options );\n};\n\nexport default userLocaleMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA,MAAMC,oBAAoB,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACjD,IACC,OAAOD,OAAO,CAACE,GAAG,KAAK,QAAQ,IAC/B,CAAE,IAAAC,gBAAW,EAAEH,OAAO,CAACE,GAAG,EAAE,SAAU,CAAC,EACtC;IACDF,OAAO,CAACE,GAAG,GAAG,IAAAE,iBAAY,EAAEJ,OAAO,CAACE,GAAG,EAAE;MAAEG,OAAO,EAAE;IAAO,CAAE,CAAC;EAC/D;EAEA,IACC,OAAOL,OAAO,CAACM,IAAI,KAAK,QAAQ,IAChC,CAAE,IAAAH,gBAAW,EAAEH,OAAO,CAACM,IAAI,EAAE,SAAU,CAAC,EACvC;IACDN,OAAO,CAACM,IAAI,GAAG,IAAAF,iBAAY,EAAEJ,OAAO,CAACM,IAAI,EAAE;MAAED,OAAO,EAAE;IAAO,CAAE,CAAC;EACjE;EAEA,OAAOJ,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAO,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaV,oBAAoB","ignoreList":[]}

6
node_modules/@wordpress/api-fetch/build/types.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=types.js.map

1
node_modules/@wordpress/api-fetch/build/types.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"names":[],"sources":["@wordpress/api-fetch/src/types.ts"],"sourcesContent":["export interface APIFetchOptions extends RequestInit {\n\t// Override headers, we only accept it as an object due to the `nonce` middleware\n\theaders?: Record< string, string >;\n\tpath?: string;\n\turl?: string;\n\t/**\n\t * @default true\n\t */\n\tparse?: boolean;\n\tdata?: any;\n\tnamespace?: string;\n\tendpoint?: string;\n}\n\nexport type APIFetchMiddleware = (\n\toptions: APIFetchOptions,\n\tnext: ( nextOptions: APIFetchOptions ) => Promise< any >\n) => Promise< any >;\n"],"mappings":"","ignoreList":[]}

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseAndThrowError = parseAndThrowError;
exports.parseResponseAndNormalizeError = void 0;
var _i18n = require("@wordpress/i18n");
/**
* WordPress dependencies
*/
/**
* Parses the apiFetch response.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any> | null | Response} Parsed response.
*/
const parseResponse = (response, shouldParseResponse = true) => {
if (shouldParseResponse) {
if (response.status === 204) {
return null;
}
return response.json ? response.json() : Promise.reject(response);
}
return response;
};
/**
* Calls the `json` function on the Response, throwing an error if the response
* doesn't have a json function or if parsing the json itself fails.
*
* @param {Response} response
* @return {Promise<any>} Parsed response.
*/
const parseJsonAndNormalizeError = response => {
const invalidJsonError = {
code: 'invalid_json',
message: (0, _i18n.__)('The response is not a valid JSON response.')
};
if (!response || !response.json) {
throw invalidJsonError;
}
return response.json().catch(() => {
throw invalidJsonError;
});
};
/**
* Parses the apiFetch response properly and normalize response errors.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any>} Parsed response.
*/
const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => {
return Promise.resolve(parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse));
};
/**
* Parses a response, throwing an error if parsing the response fails.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
* @return {Promise<any>} Parsed response.
*/
exports.parseResponseAndNormalizeError = parseResponseAndNormalizeError;
function parseAndThrowError(response, shouldParseResponse = true) {
if (!shouldParseResponse) {
throw response;
}
return parseJsonAndNormalizeError(response).then(error => {
const unknownError = {
code: 'unknown_error',
message: (0, _i18n.__)('An unknown error occurred.')
};
throw error || unknownError;
});
}
//# sourceMappingURL=response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_i18n","require","parseResponse","response","shouldParseResponse","status","json","Promise","reject","parseJsonAndNormalizeError","invalidJsonError","code","message","__","catch","parseResponseAndNormalizeError","resolve","res","parseAndThrowError","exports","then","error","unknownError"],"sources":["@wordpress/api-fetch/src/utils/response.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Parses the apiFetch response.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n *\n * @return {Promise<any> | null | Response} Parsed response.\n */\nconst parseResponse = ( response, shouldParseResponse = true ) => {\n\tif ( shouldParseResponse ) {\n\t\tif ( response.status === 204 ) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn response.json ? response.json() : Promise.reject( response );\n\t}\n\n\treturn response;\n};\n\n/**\n * Calls the `json` function on the Response, throwing an error if the response\n * doesn't have a json function or if parsing the json itself fails.\n *\n * @param {Response} response\n * @return {Promise<any>} Parsed response.\n */\nconst parseJsonAndNormalizeError = ( response ) => {\n\tconst invalidJsonError = {\n\t\tcode: 'invalid_json',\n\t\tmessage: __( 'The response is not a valid JSON response.' ),\n\t};\n\n\tif ( ! response || ! response.json ) {\n\t\tthrow invalidJsonError;\n\t}\n\n\treturn response.json().catch( () => {\n\t\tthrow invalidJsonError;\n\t} );\n};\n\n/**\n * Parses the apiFetch response properly and normalize response errors.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n *\n * @return {Promise<any>} Parsed response.\n */\nexport const parseResponseAndNormalizeError = (\n\tresponse,\n\tshouldParseResponse = true\n) => {\n\treturn Promise.resolve(\n\t\tparseResponse( response, shouldParseResponse )\n\t).catch( ( res ) => parseAndThrowError( res, shouldParseResponse ) );\n};\n\n/**\n * Parses a response, throwing an error if parsing the response fails.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n * @return {Promise<any>} Parsed response.\n */\nexport function parseAndThrowError( response, shouldParseResponse = true ) {\n\tif ( ! shouldParseResponse ) {\n\t\tthrow response;\n\t}\n\n\treturn parseJsonAndNormalizeError( response ).then( ( error ) => {\n\t\tconst unknownError = {\n\t\t\tcode: 'unknown_error',\n\t\t\tmessage: __( 'An unknown error occurred.' ),\n\t\t};\n\n\t\tthrow error || unknownError;\n\t} );\n}\n"],"mappings":";;;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,aAAa,GAAGA,CAAEC,QAAQ,EAAEC,mBAAmB,GAAG,IAAI,KAAM;EACjE,IAAKA,mBAAmB,EAAG;IAC1B,IAAKD,QAAQ,CAACE,MAAM,KAAK,GAAG,EAAG;MAC9B,OAAO,IAAI;IACZ;IAEA,OAAOF,QAAQ,CAACG,IAAI,GAAGH,QAAQ,CAACG,IAAI,CAAC,CAAC,GAAGC,OAAO,CAACC,MAAM,CAAEL,QAAS,CAAC;EACpE;EAEA,OAAOA,QAAQ;AAChB,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMM,0BAA0B,GAAKN,QAAQ,IAAM;EAClD,MAAMO,gBAAgB,GAAG;IACxBC,IAAI,EAAE,cAAc;IACpBC,OAAO,EAAE,IAAAC,QAAE,EAAE,4CAA6C;EAC3D,CAAC;EAED,IAAK,CAAEV,QAAQ,IAAI,CAAEA,QAAQ,CAACG,IAAI,EAAG;IACpC,MAAMI,gBAAgB;EACvB;EAEA,OAAOP,QAAQ,CAACG,IAAI,CAAC,CAAC,CAACQ,KAAK,CAAE,MAAM;IACnC,MAAMJ,gBAAgB;EACvB,CAAE,CAAC;AACJ,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMK,8BAA8B,GAAGA,CAC7CZ,QAAQ,EACRC,mBAAmB,GAAG,IAAI,KACtB;EACJ,OAAOG,OAAO,CAACS,OAAO,CACrBd,aAAa,CAAEC,QAAQ,EAAEC,mBAAoB,CAC9C,CAAC,CAACU,KAAK,CAAIG,GAAG,IAAMC,kBAAkB,CAAED,GAAG,EAAEb,mBAAoB,CAAE,CAAC;AACrE,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AANAe,OAAA,CAAAJ,8BAAA,GAAAA,8BAAA;AAOO,SAASG,kBAAkBA,CAAEf,QAAQ,EAAEC,mBAAmB,GAAG,IAAI,EAAG;EAC1E,IAAK,CAAEA,mBAAmB,EAAG;IAC5B,MAAMD,QAAQ;EACf;EAEA,OAAOM,0BAA0B,CAAEN,QAAS,CAAC,CAACiB,IAAI,CAAIC,KAAK,IAAM;IAChE,MAAMC,YAAY,GAAG;MACpBX,IAAI,EAAE,eAAe;MACrBC,OAAO,EAAE,IAAAC,QAAE,EAAE,4BAA6B;IAC3C,CAAC;IAED,MAAMQ,KAAK,IAAIC,YAAY;EAC5B,CAAE,CAAC;AACJ","ignoreList":[]}