@wordpress/api-fetch 6.36.0 → 6.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -0
- package/build/index.js +26 -43
- package/build/index.js.map +1 -1
- package/build/middlewares/fetch-all-middleware.js +16 -32
- package/build/middlewares/fetch-all-middleware.js.map +1 -1
- package/build/middlewares/http-v1.js +6 -8
- package/build/middlewares/http-v1.js.map +1 -1
- package/build/middlewares/media-upload.js +4 -14
- package/build/middlewares/media-upload.js.map +1 -1
- package/build/middlewares/namespace-endpoint.js +2 -6
- package/build/middlewares/namespace-endpoint.js.map +1 -1
- package/build/middlewares/nonce.js +7 -8
- package/build/middlewares/nonce.js.map +1 -1
- package/build/middlewares/preloading.js +5 -14
- package/build/middlewares/preloading.js.map +1 -1
- package/build/middlewares/root-url.js +4 -11
- package/build/middlewares/root-url.js.map +1 -1
- package/build/middlewares/theme-preview.js +0 -5
- package/build/middlewares/theme-preview.js.map +1 -1
- package/build/middlewares/user-locale.js +0 -5
- package/build/middlewares/user-locale.js.map +1 -1
- package/build/types.js.map +1 -1
- package/build/utils/response.js +3 -14
- package/build/utils/response.js.map +1 -1
- package/build-module/index.js +28 -32
- package/build-module/index.js.map +1 -1
- package/build-module/middlewares/fetch-all-middleware.js +18 -30
- package/build-module/middlewares/fetch-all-middleware.js.map +1 -1
- package/build-module/middlewares/http-v1.js +6 -7
- package/build-module/middlewares/http-v1.js.map +1 -1
- package/build-module/middlewares/media-upload.js +6 -13
- package/build-module/middlewares/media-upload.js.map +1 -1
- package/build-module/middlewares/namespace-endpoint.js +2 -5
- package/build-module/middlewares/namespace-endpoint.js.map +1 -1
- package/build-module/middlewares/nonce.js +7 -7
- package/build-module/middlewares/nonce.js.map +1 -1
- package/build-module/middlewares/preloading.js +6 -13
- package/build-module/middlewares/preloading.js.map +1 -1
- package/build-module/middlewares/root-url.js +5 -9
- package/build-module/middlewares/root-url.js.map +1 -1
- package/build-module/middlewares/theme-preview.js +1 -4
- package/build-module/middlewares/theme-preview.js.map +1 -1
- package/build-module/middlewares/user-locale.js +1 -4
- package/build-module/middlewares/user-locale.js.map +1 -1
- package/build-module/types.js.map +1 -1
- package/build-module/utils/response.js +4 -11
- package/build-module/utils/response.js.map +1 -1
- package/build-types/index.d.ts +6 -6
- package/build-types/index.d.ts.map +1 -1
- package/package.json +4 -4
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["@wordpress/api-fetch/src/index.js"],"names":["__","createNonceMiddleware","createRootURLMiddleware","createPreloadingMiddleware","fetchAllMiddleware","namespaceEndpointMiddleware","httpV1Middleware","userLocaleMiddleware","mediaUploadMiddleware","createThemePreviewMiddleware","parseResponseAndNormalizeError","parseAndThrowError","DEFAULT_HEADERS","Accept","DEFAULT_OPTIONS","credentials","middlewares","registerMiddleware","middleware","unshift","checkStatus","response","status","defaultFetchHandler","nextOptions","url","path","data","parse","remainingOptions","body","headers","JSON","stringify","responsePromise","window","fetch","location","href","then","value","Promise","resolve","catch","err","name","code","message","fetchHandler","setFetchHandler","newFetchHandler","apiFetch","options","enhancedHandler","reduceRight","next","workingOptions","error","reject","nonceEndpoint","text","nonceMiddleware","nonce","use"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,EAAT,QAAmB,iBAAnB;AAEA;AACA;AACA;;AACA,OAAOC,qBAAP,MAAkC,qBAAlC;AACA,OAAOC,uBAAP,MAAoC,wBAApC;AACA,OAAOC,0BAAP,MAAuC,0BAAvC;AACA,OAAOC,kBAAP,MAA+B,oCAA/B;AACA,OAAOC,2BAAP,MAAwC,kCAAxC;AACA,OAAOC,gBAAP,MAA6B,uBAA7B;AACA,OAAOC,oBAAP,MAAiC,2BAAjC;AACA,OAAOC,qBAAP,MAAkC,4BAAlC;AACA,OAAOC,4BAAP,MAAyC,6BAAzC;AACA,SACCC,8BADD,EAECC,kBAFD,QAGO,kBAHP;AAKA;AACA;AACA;AAC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,CAAoCc,KAAF,IAAa;AACrD,QAAKA,KAAK,CAACX,IAAN,KAAe,2BAApB,EAAkD;AACjD,aAAOL,OAAO,CAACiB,MAAR,CAAgBD,KAAhB,CAAP;AACA,KAHoD,CAKrD;;;AACA,WACCtB,MAAM,CACL;AADK,KAEJC,KAFF,CAESe,QAAQ,CAACQ,aAFlB,EAGEpB,IAHF,CAGQnB,WAHR,EAIEmB,IAJF,CAIUZ,IAAF,IAAYA,IAAI,CAACiC,IAAL,EAJpB,EAKErB,IALF,CAKUqB,IAAF,IAAY;AAClB;AACAT,MAAAA,QAAQ,CAACU,eAAT,CAAyBC,KAAzB,GAAiCF,IAAjC;AACA,aAAOT,QAAQ,CAAEC,OAAF,CAAf;AACA,KATF,CADD;AAYA,GAlBM,CAAP;AAmBA;;AAEDD,QAAQ,CAACY,GAAT,GAAe9C,kBAAf;AACAkC,QAAQ,CAACF,eAAT,GAA2BA,eAA3B;AAEAE,QAAQ,CAAClD,qBAAT,GAAiCA,qBAAjC;AACAkD,QAAQ,CAAChD,0BAAT,GAAsCA,0BAAtC;AACAgD,QAAQ,CAACjD,uBAAT,GAAmCA,uBAAnC;AACAiD,QAAQ,CAAC/C,kBAAT,GAA8BA,kBAA9B;AACA+C,QAAQ,CAAC3C,qBAAT,GAAiCA,qBAAjC;AACA2C,QAAQ,CAAC1C,4BAAT,GAAwCA,4BAAxC;AAEA,eAAe0C,QAAf","sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport createNonceMiddleware from './middlewares/nonce';\nimport createRootURLMiddleware from './middlewares/root-url';\nimport createPreloadingMiddleware from './middlewares/preloading';\nimport fetchAllMiddleware from './middlewares/fetch-all-middleware';\nimport namespaceEndpointMiddleware from './middlewares/namespace-endpoint';\nimport httpV1Middleware from './middlewares/http-v1';\nimport userLocaleMiddleware from './middlewares/user-locale';\nimport mediaUploadMiddleware from './middlewares/media-upload';\nimport createThemePreviewMiddleware from './middlewares/theme-preview';\nimport {\n\tparseResponseAndNormalizeError,\n\tparseAndThrowError,\n} from './utils/response';\n\n/**\n * Default set of header values which should be sent with every request unless\n * explicitly provided through apiFetch options.\n *\n * @type {Record<string, string>}\n */\nconst DEFAULT_HEADERS = {\n\t// The backend uses the Accept header as a condition for considering an\n\t// incoming request as a REST request.\n\t//\n\t// See: https://core.trac.wordpress.org/ticket/44534\n\tAccept: 'application/json, */*;q=0.1',\n};\n\n/**\n * Default set of fetch option values which should be sent with every request\n * unless explicitly provided through apiFetch options.\n *\n * @type {Object}\n */\nconst DEFAULT_OPTIONS = {\n\tcredentials: 'include',\n};\n\n/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */\n/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */\n\n/**\n * @type {import('./types').APIFetchMiddleware[]}\n */\nconst middlewares = [\n\tuserLocaleMiddleware,\n\tnamespaceEndpointMiddleware,\n\thttpV1Middleware,\n\tfetchAllMiddleware,\n];\n\n/**\n * Register a middleware\n *\n * @param {import('./types').APIFetchMiddleware} middleware\n */\nfunction registerMiddleware( middleware ) {\n\tmiddlewares.unshift( middleware );\n}\n\n/**\n * Checks the status of a response, throwing the Response as an error if\n * it is outside the 200 range.\n *\n * @param {Response} response\n * @return {Response} The response if the status is in the 200 range.\n */\nconst checkStatus = ( response ) => {\n\tif ( response.status >= 200 && response.status < 300 ) {\n\t\treturn response;\n\t}\n\n\tthrow response;\n};\n\n/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/\n\n/**\n * @type {FetchHandler}\n */\nconst defaultFetchHandler = ( nextOptions ) => {\n\tconst { url, path, data, parse = true, ...remainingOptions } = nextOptions;\n\tlet { body, headers } = nextOptions;\n\n\t// Merge explicitly-provided headers with default values.\n\theaders = { ...DEFAULT_HEADERS, ...headers };\n\n\t// The `data` property is a shorthand for sending a JSON body.\n\tif ( data ) {\n\t\tbody = JSON.stringify( data );\n\t\theaders[ 'Content-Type' ] = 'application/json';\n\t}\n\n\tconst responsePromise = window.fetch(\n\t\t// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.\n\t\turl || path || window.location.href,\n\t\t{\n\t\t\t...DEFAULT_OPTIONS,\n\t\t\t...remainingOptions,\n\t\t\tbody,\n\t\t\theaders,\n\t\t}\n\t);\n\n\treturn responsePromise.then(\n\t\t( value ) =>\n\t\t\tPromise.resolve( value )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.catch( ( response ) => parseAndThrowError( response, parse ) )\n\t\t\t\t.then( ( response ) =>\n\t\t\t\t\tparseResponseAndNormalizeError( response, parse )\n\t\t\t\t),\n\t\t( err ) => {\n\t\t\t// Re-throw AbortError for the users to handle it themselves.\n\t\t\tif ( err && err.name === 'AbortError' ) {\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\t// Otherwise, there is most likely no network connection.\n\t\t\t// Unfortunately the message might depend on the browser.\n\t\t\tthrow {\n\t\t\t\tcode: 'fetch_error',\n\t\t\t\tmessage: __( 'You are probably offline.' ),\n\t\t\t};\n\t\t}\n\t);\n};\n\n/** @type {FetchHandler} */\nlet fetchHandler = defaultFetchHandler;\n\n/**\n * Defines a custom fetch handler for making the requests that will override\n * the default one using window.fetch\n *\n * @param {FetchHandler} newFetchHandler The new fetch handler\n */\nfunction setFetchHandler( newFetchHandler ) {\n\tfetchHandler = newFetchHandler;\n}\n\n/**\n * @template T\n * @param {import('./types').APIFetchOptions} options\n * @return {Promise<T>} A promise representing the request processed via the registered middlewares.\n */\nfunction apiFetch( options ) {\n\t// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,\n\t// converting `middlewares = [ m1, m2, m3 ]` into:\n\t// ```\n\t// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );\n\t// ```\n\tconst enhancedHandler = middlewares.reduceRight(\n\t\t( /** @type {FetchHandler} */ next, middleware ) => {\n\t\t\treturn ( workingOptions ) => middleware( workingOptions, next );\n\t\t},\n\t\tfetchHandler\n\t);\n\n\treturn enhancedHandler( options ).catch( ( error ) => {\n\t\tif ( error.code !== 'rest_cookie_invalid_nonce' ) {\n\t\t\treturn Promise.reject( error );\n\t\t}\n\n\t\t// If the nonce is invalid, refresh it and try again.\n\t\treturn (\n\t\t\twindow\n\t\t\t\t// @ts-ignore\n\t\t\t\t.fetch( apiFetch.nonceEndpoint )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.then( ( data ) => data.text() )\n\t\t\t\t.then( ( text ) => {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tapiFetch.nonceMiddleware.nonce = text;\n\t\t\t\t\treturn apiFetch( options );\n\t\t\t\t} )\n\t\t);\n\t} );\n}\n\napiFetch.use = registerMiddleware;\napiFetch.setFetchHandler = setFetchHandler;\n\napiFetch.createNonceMiddleware = createNonceMiddleware;\napiFetch.createPreloadingMiddleware = createPreloadingMiddleware;\napiFetch.createRootURLMiddleware = createRootURLMiddleware;\napiFetch.fetchAllMiddleware = fetchAllMiddleware;\napiFetch.mediaUploadMiddleware = mediaUploadMiddleware;\napiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;\n\nexport default apiFetch;\n"]}
|
|
1
|
+
{"version":3,"names":["__","createNonceMiddleware","createRootURLMiddleware","createPreloadingMiddleware","fetchAllMiddleware","namespaceEndpointMiddleware","httpV1Middleware","userLocaleMiddleware","mediaUploadMiddleware","createThemePreviewMiddleware","parseResponseAndNormalizeError","parseAndThrowError","DEFAULT_HEADERS","Accept","DEFAULT_OPTIONS","credentials","middlewares","registerMiddleware","middleware","unshift","checkStatus","response","status","defaultFetchHandler","nextOptions","url","path","data","parse","remainingOptions","body","headers","JSON","stringify","responsePromise","window","fetch","location","href","then","value","Promise","resolve","catch","err","name","code","message","fetchHandler","setFetchHandler","newFetchHandler","apiFetch","options","enhancedHandler","reduceRight","next","workingOptions","error","reject","nonceEndpoint","text","nonceMiddleware","nonce","use"],"sources":["@wordpress/api-fetch/src/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport createNonceMiddleware from './middlewares/nonce';\nimport createRootURLMiddleware from './middlewares/root-url';\nimport createPreloadingMiddleware from './middlewares/preloading';\nimport fetchAllMiddleware from './middlewares/fetch-all-middleware';\nimport namespaceEndpointMiddleware from './middlewares/namespace-endpoint';\nimport httpV1Middleware from './middlewares/http-v1';\nimport userLocaleMiddleware from './middlewares/user-locale';\nimport mediaUploadMiddleware from './middlewares/media-upload';\nimport createThemePreviewMiddleware from './middlewares/theme-preview';\nimport {\n\tparseResponseAndNormalizeError,\n\tparseAndThrowError,\n} from './utils/response';\n\n/**\n * Default set of header values which should be sent with every request unless\n * explicitly provided through apiFetch options.\n *\n * @type {Record<string, string>}\n */\nconst DEFAULT_HEADERS = {\n\t// The backend uses the Accept header as a condition for considering an\n\t// incoming request as a REST request.\n\t//\n\t// See: https://core.trac.wordpress.org/ticket/44534\n\tAccept: 'application/json, */*;q=0.1',\n};\n\n/**\n * Default set of fetch option values which should be sent with every request\n * unless explicitly provided through apiFetch options.\n *\n * @type {Object}\n */\nconst DEFAULT_OPTIONS = {\n\tcredentials: 'include',\n};\n\n/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */\n/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */\n\n/**\n * @type {import('./types').APIFetchMiddleware[]}\n */\nconst middlewares = [\n\tuserLocaleMiddleware,\n\tnamespaceEndpointMiddleware,\n\thttpV1Middleware,\n\tfetchAllMiddleware,\n];\n\n/**\n * Register a middleware\n *\n * @param {import('./types').APIFetchMiddleware} middleware\n */\nfunction registerMiddleware( middleware ) {\n\tmiddlewares.unshift( middleware );\n}\n\n/**\n * Checks the status of a response, throwing the Response as an error if\n * it is outside the 200 range.\n *\n * @param {Response} response\n * @return {Response} The response if the status is in the 200 range.\n */\nconst checkStatus = ( response ) => {\n\tif ( response.status >= 200 && response.status < 300 ) {\n\t\treturn response;\n\t}\n\n\tthrow response;\n};\n\n/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/\n\n/**\n * @type {FetchHandler}\n */\nconst defaultFetchHandler = ( nextOptions ) => {\n\tconst { url, path, data, parse = true, ...remainingOptions } = nextOptions;\n\tlet { body, headers } = nextOptions;\n\n\t// Merge explicitly-provided headers with default values.\n\theaders = { ...DEFAULT_HEADERS, ...headers };\n\n\t// The `data` property is a shorthand for sending a JSON body.\n\tif ( data ) {\n\t\tbody = JSON.stringify( data );\n\t\theaders[ 'Content-Type' ] = 'application/json';\n\t}\n\n\tconst responsePromise = window.fetch(\n\t\t// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.\n\t\turl || path || window.location.href,\n\t\t{\n\t\t\t...DEFAULT_OPTIONS,\n\t\t\t...remainingOptions,\n\t\t\tbody,\n\t\t\theaders,\n\t\t}\n\t);\n\n\treturn responsePromise.then(\n\t\t( value ) =>\n\t\t\tPromise.resolve( value )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.catch( ( response ) => parseAndThrowError( response, parse ) )\n\t\t\t\t.then( ( response ) =>\n\t\t\t\t\tparseResponseAndNormalizeError( response, parse )\n\t\t\t\t),\n\t\t( err ) => {\n\t\t\t// Re-throw AbortError for the users to handle it themselves.\n\t\t\tif ( err && err.name === 'AbortError' ) {\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\t// Otherwise, there is most likely no network connection.\n\t\t\t// Unfortunately the message might depend on the browser.\n\t\t\tthrow {\n\t\t\t\tcode: 'fetch_error',\n\t\t\t\tmessage: __( 'You are probably offline.' ),\n\t\t\t};\n\t\t}\n\t);\n};\n\n/** @type {FetchHandler} */\nlet fetchHandler = defaultFetchHandler;\n\n/**\n * Defines a custom fetch handler for making the requests that will override\n * the default one using window.fetch\n *\n * @param {FetchHandler} newFetchHandler The new fetch handler\n */\nfunction setFetchHandler( newFetchHandler ) {\n\tfetchHandler = newFetchHandler;\n}\n\n/**\n * @template T\n * @param {import('./types').APIFetchOptions} options\n * @return {Promise<T>} A promise representing the request processed via the registered middlewares.\n */\nfunction apiFetch( options ) {\n\t// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,\n\t// converting `middlewares = [ m1, m2, m3 ]` into:\n\t// ```\n\t// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );\n\t// ```\n\tconst enhancedHandler = middlewares.reduceRight(\n\t\t( /** @type {FetchHandler} */ next, middleware ) => {\n\t\t\treturn ( workingOptions ) => middleware( workingOptions, next );\n\t\t},\n\t\tfetchHandler\n\t);\n\n\treturn enhancedHandler( options ).catch( ( error ) => {\n\t\tif ( error.code !== 'rest_cookie_invalid_nonce' ) {\n\t\t\treturn Promise.reject( error );\n\t\t}\n\n\t\t// If the nonce is invalid, refresh it and try again.\n\t\treturn (\n\t\t\twindow\n\t\t\t\t// @ts-ignore\n\t\t\t\t.fetch( apiFetch.nonceEndpoint )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.then( ( data ) => data.text() )\n\t\t\t\t.then( ( text ) => {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tapiFetch.nonceMiddleware.nonce = text;\n\t\t\t\t\treturn apiFetch( options );\n\t\t\t\t} )\n\t\t);\n\t} );\n}\n\napiFetch.use = registerMiddleware;\napiFetch.setFetchHandler = setFetchHandler;\n\napiFetch.createNonceMiddleware = createNonceMiddleware;\napiFetch.createPreloadingMiddleware = createPreloadingMiddleware;\napiFetch.createRootURLMiddleware = createRootURLMiddleware;\napiFetch.fetchAllMiddleware = fetchAllMiddleware;\napiFetch.mediaUploadMiddleware = mediaUploadMiddleware;\napiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;\n\nexport default apiFetch;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,EAAE,QAAQ,iBAAiB;;AAEpC;AACA;AACA;AACA,OAAOC,qBAAqB,MAAM,qBAAqB;AACvD,OAAOC,uBAAuB,MAAM,wBAAwB;AAC5D,OAAOC,0BAA0B,MAAM,0BAA0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
/**
|
|
11
12
|
* Apply query arguments to both URL and Path, whichever is present.
|
|
12
13
|
*
|
|
@@ -14,63 +15,59 @@ import apiFetch from '..';
|
|
|
14
15
|
* @param {Record<string, string | number>} queryArgs
|
|
15
16
|
* @return {import('../types').APIFetchOptions} The request with the modified query args
|
|
16
17
|
*/
|
|
17
|
-
|
|
18
18
|
const modifyQuery = ({
|
|
19
19
|
path,
|
|
20
20
|
url,
|
|
21
21
|
...options
|
|
22
|
-
}, queryArgs) => ({
|
|
22
|
+
}, queryArgs) => ({
|
|
23
|
+
...options,
|
|
23
24
|
url: url && addQueryArgs(url, queryArgs),
|
|
24
25
|
path: path && addQueryArgs(path, queryArgs)
|
|
25
26
|
});
|
|
27
|
+
|
|
26
28
|
/**
|
|
27
29
|
* Duplicates parsing functionality from apiFetch.
|
|
28
30
|
*
|
|
29
31
|
* @param {Response} response
|
|
30
32
|
* @return {Promise<any>} Parsed response json.
|
|
31
33
|
*/
|
|
32
|
-
|
|
33
|
-
|
|
34
34
|
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
|
|
35
|
+
|
|
35
36
|
/**
|
|
36
37
|
* @param {string | null} linkHeader
|
|
37
38
|
* @return {{ next?: string }} The parsed link header.
|
|
38
39
|
*/
|
|
39
|
-
|
|
40
|
-
|
|
41
40
|
const parseLinkHeader = linkHeader => {
|
|
42
41
|
if (!linkHeader) {
|
|
43
42
|
return {};
|
|
44
43
|
}
|
|
45
|
-
|
|
46
44
|
const match = linkHeader.match(/<([^>]+)>; rel="next"/);
|
|
47
45
|
return match ? {
|
|
48
46
|
next: match[1]
|
|
49
47
|
} : {};
|
|
50
48
|
};
|
|
49
|
+
|
|
51
50
|
/**
|
|
52
51
|
* @param {Response} response
|
|
53
52
|
* @return {string | undefined} The next page URL.
|
|
54
53
|
*/
|
|
55
|
-
|
|
56
|
-
|
|
57
54
|
const getNextPageUrl = response => {
|
|
58
55
|
const {
|
|
59
56
|
next
|
|
60
57
|
} = parseLinkHeader(response.headers.get('link'));
|
|
61
58
|
return next;
|
|
62
59
|
};
|
|
60
|
+
|
|
63
61
|
/**
|
|
64
62
|
* @param {import('../types').APIFetchOptions} options
|
|
65
63
|
* @return {boolean} True if the request contains an unbounded query.
|
|
66
64
|
*/
|
|
67
|
-
|
|
68
|
-
|
|
69
65
|
const requestContainsUnboundedQuery = options => {
|
|
70
66
|
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
|
|
71
67
|
const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
|
|
72
68
|
return pathIsUnbounded || urlIsUnbounded;
|
|
73
69
|
};
|
|
70
|
+
|
|
74
71
|
/**
|
|
75
72
|
* The REST API enforces an upper limit on the per_page option. To handle large
|
|
76
73
|
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
|
|
@@ -78,47 +75,40 @@ const requestContainsUnboundedQuery = options => {
|
|
|
78
75
|
*
|
|
79
76
|
* @type {import('../types').APIFetchMiddleware}
|
|
80
77
|
*/
|
|
81
|
-
|
|
82
|
-
|
|
83
78
|
const fetchAllMiddleware = async (options, next) => {
|
|
84
79
|
if (options.parse === false) {
|
|
85
80
|
// If a consumer has opted out of parsing, do not apply middleware.
|
|
86
81
|
return next(options);
|
|
87
82
|
}
|
|
88
|
-
|
|
89
83
|
if (!requestContainsUnboundedQuery(options)) {
|
|
90
84
|
// If neither url nor path is requesting all items, do not apply middleware.
|
|
91
85
|
return next(options);
|
|
92
|
-
}
|
|
93
|
-
|
|
86
|
+
}
|
|
94
87
|
|
|
95
|
-
|
|
88
|
+
// Retrieve requested page of results.
|
|
89
|
+
const response = await apiFetch({
|
|
90
|
+
...modifyQuery(options, {
|
|
96
91
|
per_page: 100
|
|
97
92
|
}),
|
|
98
93
|
// Ensure headers are returned for page 1.
|
|
99
94
|
parse: false
|
|
100
95
|
});
|
|
101
96
|
const results = await parseResponse(response);
|
|
102
|
-
|
|
103
97
|
if (!Array.isArray(results)) {
|
|
104
98
|
// We have no reliable way of merging non-array results.
|
|
105
99
|
return results;
|
|
106
100
|
}
|
|
107
|
-
|
|
108
101
|
let nextPage = getNextPageUrl(response);
|
|
109
|
-
|
|
110
102
|
if (!nextPage) {
|
|
111
103
|
// There are no further pages to request.
|
|
112
104
|
return results;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
let mergedResults =
|
|
117
|
-
/** @type {any[]} */
|
|
118
|
-
[].concat(results);
|
|
105
|
+
}
|
|
119
106
|
|
|
107
|
+
// Iteratively fetch all remaining pages until no "next" header is found.
|
|
108
|
+
let mergedResults = /** @type {any[]} */[].concat(results);
|
|
120
109
|
while (nextPage) {
|
|
121
|
-
const nextResponse = await apiFetch({
|
|
110
|
+
const nextResponse = await apiFetch({
|
|
111
|
+
...options,
|
|
122
112
|
// Ensure the URL for the next page is used instead of any provided path.
|
|
123
113
|
path: undefined,
|
|
124
114
|
url: nextPage,
|
|
@@ -129,9 +119,7 @@ const fetchAllMiddleware = async (options, next) => {
|
|
|
129
119
|
mergedResults = mergedResults.concat(nextResults);
|
|
130
120
|
nextPage = getNextPageUrl(nextResponse);
|
|
131
121
|
}
|
|
132
|
-
|
|
133
122
|
return mergedResults;
|
|
134
123
|
};
|
|
135
|
-
|
|
136
124
|
export default fetchAllMiddleware;
|
|
137
125
|
//# sourceMappingURL=fetch-all-middleware.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"names":["addQueryArgs","apiFetch","modifyQuery","path","url","options","queryArgs","parseResponse","response","json","Promise","reject","parseLinkHeader","linkHeader","match","next","getNextPageUrl","headers","get","requestContainsUnboundedQuery","pathIsUnbounded","indexOf","urlIsUnbounded","fetchAllMiddleware","parse","per_page","results","Array","isArray","nextPage","mergedResults","concat","nextResponse","undefined","nextResults"],"sources":["@wordpress/api-fetch/src/middlewares/fetch-all-middleware.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport apiFetch from '..';\n\n/**\n * Apply query arguments to both URL and Path, whichever is present.\n *\n * @param {import('../types').APIFetchOptions} props\n * @param {Record<string, string | number>} queryArgs\n * @return {import('../types').APIFetchOptions} The request with the modified query args\n */\nconst modifyQuery = ( { path, url, ...options }, queryArgs ) => ( {\n\t...options,\n\turl: url && addQueryArgs( url, queryArgs ),\n\tpath: path && addQueryArgs( path, queryArgs ),\n} );\n\n/**\n * Duplicates parsing functionality from apiFetch.\n *\n * @param {Response} response\n * @return {Promise<any>} Parsed response json.\n */\nconst parseResponse = ( response ) =>\n\tresponse.json ? response.json() : Promise.reject( response );\n\n/**\n * @param {string | null} linkHeader\n * @return {{ next?: string }} The parsed link header.\n */\nconst parseLinkHeader = ( linkHeader ) => {\n\tif ( ! linkHeader ) {\n\t\treturn {};\n\t}\n\tconst match = linkHeader.match( /<([^>]+)>; rel=\"next\"/ );\n\treturn match\n\t\t? {\n\t\t\t\tnext: match[ 1 ],\n\t\t }\n\t\t: {};\n};\n\n/**\n * @param {Response} response\n * @return {string | undefined} The next page URL.\n */\nconst getNextPageUrl = ( response ) => {\n\tconst { next } = parseLinkHeader( response.headers.get( 'link' ) );\n\treturn next;\n};\n\n/**\n * @param {import('../types').APIFetchOptions} options\n * @return {boolean} True if the request contains an unbounded query.\n */\nconst requestContainsUnboundedQuery = ( options ) => {\n\tconst pathIsUnbounded =\n\t\t!! options.path && options.path.indexOf( 'per_page=-1' ) !== -1;\n\tconst urlIsUnbounded =\n\t\t!! options.url && options.url.indexOf( 'per_page=-1' ) !== -1;\n\treturn pathIsUnbounded || urlIsUnbounded;\n};\n\n/**\n * The REST API enforces an upper limit on the per_page option. To handle large\n * collections, apiFetch consumers can pass `per_page=-1`; this middleware will\n * then recursively assemble a full response array from all available pages.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst fetchAllMiddleware = async ( options, next ) => {\n\tif ( options.parse === false ) {\n\t\t// If a consumer has opted out of parsing, do not apply middleware.\n\t\treturn next( options );\n\t}\n\tif ( ! requestContainsUnboundedQuery( options ) ) {\n\t\t// If neither url nor path is requesting all items, do not apply middleware.\n\t\treturn next( options );\n\t}\n\n\t// Retrieve requested page of results.\n\tconst response = await apiFetch( {\n\t\t...modifyQuery( options, {\n\t\t\tper_page: 100,\n\t\t} ),\n\t\t// Ensure headers are returned for page 1.\n\t\tparse: false,\n\t} );\n\n\tconst results = await parseResponse( response );\n\n\tif ( ! Array.isArray( results ) ) {\n\t\t// We have no reliable way of merging non-array results.\n\t\treturn results;\n\t}\n\n\tlet nextPage = getNextPageUrl( response );\n\n\tif ( ! nextPage ) {\n\t\t// There are no further pages to request.\n\t\treturn results;\n\t}\n\n\t// Iteratively fetch all remaining pages until no \"next\" header is found.\n\tlet mergedResults = /** @type {any[]} */ ( [] ).concat( results );\n\twhile ( nextPage ) {\n\t\tconst nextResponse = await apiFetch( {\n\t\t\t...options,\n\t\t\t// Ensure the URL for the next page is used instead of any provided path.\n\t\t\tpath: undefined,\n\t\t\turl: nextPage,\n\t\t\t// Ensure we still get headers so we can identify the next page.\n\t\t\tparse: false,\n\t\t} );\n\t\tconst nextResults = await parseResponse( nextResponse );\n\t\tmergedResults = mergedResults.concat( nextResults );\n\t\tnextPage = getNextPageUrl( nextResponse );\n\t}\n\treturn mergedResults;\n};\n\nexport default fetchAllMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,YAAY,QAAQ,gBAAgB;;AAE7C;AACA;AACA;AACA,OAAOC,QAAQ,MAAM,IAAI;;AAEzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,WAAW,GAAGA,CAAE;EAAEC,IAAI;EAAEC,GAAG;EAAE,GAAGC;AAAQ,CAAC,EAAEC,SAAS,MAAQ;EACjE,GAAGD,OAAO;EACVD,GAAG,EAAEA,GAAG,IAAIJ,YAAY,CAAEI,GAAG,EAAEE,SAAU,CAAC;EAC1CH,IAAI,EAAEA,IAAI,IAAIH,YAAY,CAAEG,IAAI,EAAEG,SAAU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
9
10
|
*
|
|
@@ -14,32 +15,30 @@ const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
|
|
|
14
15
|
*
|
|
15
16
|
* @type {string}
|
|
16
17
|
*/
|
|
17
|
-
|
|
18
18
|
const DEFAULT_METHOD = 'GET';
|
|
19
|
+
|
|
19
20
|
/**
|
|
20
21
|
* API Fetch middleware which overrides the request method for HTTP v1
|
|
21
22
|
* compatibility leveraging the REST API X-HTTP-Method-Override header.
|
|
22
23
|
*
|
|
23
24
|
* @type {import('../types').APIFetchMiddleware}
|
|
24
25
|
*/
|
|
25
|
-
|
|
26
26
|
const httpV1Middleware = (options, next) => {
|
|
27
27
|
const {
|
|
28
28
|
method = DEFAULT_METHOD
|
|
29
29
|
} = options;
|
|
30
|
-
|
|
31
30
|
if (OVERRIDE_METHODS.has(method.toUpperCase())) {
|
|
32
|
-
options = {
|
|
33
|
-
|
|
31
|
+
options = {
|
|
32
|
+
...options,
|
|
33
|
+
headers: {
|
|
34
|
+
...options.headers,
|
|
34
35
|
'X-HTTP-Method-Override': method,
|
|
35
36
|
'Content-Type': 'application/json'
|
|
36
37
|
},
|
|
37
38
|
method: 'POST'
|
|
38
39
|
};
|
|
39
40
|
}
|
|
40
|
-
|
|
41
41
|
return next(options);
|
|
42
42
|
};
|
|
43
|
-
|
|
44
43
|
export default httpV1Middleware;
|
|
45
44
|
//# sourceMappingURL=http-v1.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"names":["OVERRIDE_METHODS","Set","DEFAULT_METHOD","httpV1Middleware","options","next","method","has","toUpperCase","headers"],"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;AAED,eAAeD,gBAAgB"}
|
|
@@ -2,40 +2,38 @@
|
|
|
2
2
|
* WordPress dependencies
|
|
3
3
|
*/
|
|
4
4
|
import { __ } from '@wordpress/i18n';
|
|
5
|
+
|
|
5
6
|
/**
|
|
6
7
|
* Internal dependencies
|
|
7
8
|
*/
|
|
8
|
-
|
|
9
9
|
import { parseAndThrowError, parseResponseAndNormalizeError } from '../utils/response';
|
|
10
|
+
|
|
10
11
|
/**
|
|
11
12
|
* @param {import('../types').APIFetchOptions} options
|
|
12
13
|
* @return {boolean} True if the request is for media upload.
|
|
13
14
|
*/
|
|
14
|
-
|
|
15
15
|
function isMediaUploadRequest(options) {
|
|
16
16
|
const isCreateMethod = !!options.method && options.method === 'POST';
|
|
17
17
|
const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
|
|
18
18
|
return isMediaEndpoint && isCreateMethod;
|
|
19
19
|
}
|
|
20
|
+
|
|
20
21
|
/**
|
|
21
22
|
* Middleware handling media upload failures and retries.
|
|
22
23
|
*
|
|
23
24
|
* @type {import('../types').APIFetchMiddleware}
|
|
24
25
|
*/
|
|
25
|
-
|
|
26
|
-
|
|
27
26
|
const mediaUploadMiddleware = (options, next) => {
|
|
28
27
|
if (!isMediaUploadRequest(options)) {
|
|
29
28
|
return next(options);
|
|
30
29
|
}
|
|
31
|
-
|
|
32
30
|
let retries = 0;
|
|
33
31
|
const maxRetries = 5;
|
|
32
|
+
|
|
34
33
|
/**
|
|
35
34
|
* @param {string} attachmentId
|
|
36
35
|
* @return {Promise<any>} Processed post response.
|
|
37
36
|
*/
|
|
38
|
-
|
|
39
37
|
const postProcess = attachmentId => {
|
|
40
38
|
retries++;
|
|
41
39
|
return next({
|
|
@@ -49,7 +47,6 @@ const mediaUploadMiddleware = (options, next) => {
|
|
|
49
47
|
if (retries < maxRetries) {
|
|
50
48
|
return postProcess(attachmentId);
|
|
51
49
|
}
|
|
52
|
-
|
|
53
50
|
next({
|
|
54
51
|
path: `/wp/v2/media/${attachmentId}?force=true`,
|
|
55
52
|
method: 'DELETE'
|
|
@@ -57,12 +54,11 @@ const mediaUploadMiddleware = (options, next) => {
|
|
|
57
54
|
return Promise.reject();
|
|
58
55
|
});
|
|
59
56
|
};
|
|
60
|
-
|
|
61
|
-
|
|
57
|
+
return next({
|
|
58
|
+
...options,
|
|
62
59
|
parse: false
|
|
63
60
|
}).catch(response => {
|
|
64
61
|
const attachmentId = response.headers.get('x-wp-upload-attachment-id');
|
|
65
|
-
|
|
66
62
|
if (response.status >= 500 && response.status < 600 && attachmentId) {
|
|
67
63
|
return postProcess(attachmentId).catch(() => {
|
|
68
64
|
if (options.parse !== false) {
|
|
@@ -71,14 +67,11 @@ const mediaUploadMiddleware = (options, next) => {
|
|
|
71
67
|
message: __('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
|
|
72
68
|
});
|
|
73
69
|
}
|
|
74
|
-
|
|
75
70
|
return Promise.reject(response);
|
|
76
71
|
});
|
|
77
72
|
}
|
|
78
|
-
|
|
79
73
|
return parseAndThrowError(response, options.parse);
|
|
80
74
|
}).then(response => parseResponseAndNormalizeError(response, options.parse));
|
|
81
75
|
};
|
|
82
|
-
|
|
83
76
|
export default mediaUploadMiddleware;
|
|
84
77
|
//# sourceMappingURL=media-upload.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"names":["__","parseAndThrowError","parseResponseAndNormalizeError","isMediaUploadRequest","options","isCreateMethod","method","isMediaEndpoint","path","indexOf","url","mediaUploadMiddleware","next","retries","maxRetries","postProcess","attachmentId","data","action","parse","catch","Promise","reject","response","headers","get","status","code","message","then"],"sources":["@wordpress/api-fetch/src/middlewares/media-upload.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport {\n\tparseAndThrowError,\n\tparseResponseAndNormalizeError,\n} from '../utils/response';\n\n/**\n * @param {import('../types').APIFetchOptions} options\n * @return {boolean} True if the request is for media upload.\n */\nfunction isMediaUploadRequest( options ) {\n\tconst isCreateMethod = !! options.method && options.method === 'POST';\n\tconst isMediaEndpoint =\n\t\t( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||\n\t\t( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );\n\n\treturn isMediaEndpoint && isCreateMethod;\n}\n\n/**\n * Middleware handling media upload failures and retries.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst mediaUploadMiddleware = ( options, next ) => {\n\tif ( ! isMediaUploadRequest( options ) ) {\n\t\treturn next( options );\n\t}\n\n\tlet retries = 0;\n\tconst maxRetries = 5;\n\n\t/**\n\t * @param {string} attachmentId\n\t * @return {Promise<any>} Processed post response.\n\t */\n\tconst postProcess = ( attachmentId ) => {\n\t\tretries++;\n\t\treturn next( {\n\t\t\tpath: `/wp/v2/media/${ attachmentId }/post-process`,\n\t\t\tmethod: 'POST',\n\t\t\tdata: { action: 'create-image-subsizes' },\n\t\t\tparse: false,\n\t\t} ).catch( () => {\n\t\t\tif ( retries < maxRetries ) {\n\t\t\t\treturn postProcess( attachmentId );\n\t\t\t}\n\t\t\tnext( {\n\t\t\t\tpath: `/wp/v2/media/${ attachmentId }?force=true`,\n\t\t\t\tmethod: 'DELETE',\n\t\t\t} );\n\n\t\t\treturn Promise.reject();\n\t\t} );\n\t};\n\n\treturn next( { ...options, parse: false } )\n\t\t.catch( ( response ) => {\n\t\t\tconst attachmentId = response.headers.get(\n\t\t\t\t'x-wp-upload-attachment-id'\n\t\t\t);\n\t\t\tif (\n\t\t\t\tresponse.status >= 500 &&\n\t\t\t\tresponse.status < 600 &&\n\t\t\t\tattachmentId\n\t\t\t) {\n\t\t\t\treturn postProcess( attachmentId ).catch( () => {\n\t\t\t\t\tif ( options.parse !== false ) {\n\t\t\t\t\t\treturn Promise.reject( {\n\t\t\t\t\t\t\tcode: 'post_process',\n\t\t\t\t\t\t\tmessage: __(\n\t\t\t\t\t\t\t\t'Media upload failed. If this is a photo or a large image, please scale it down and try again.'\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.reject( response );\n\t\t\t\t} );\n\t\t\t}\n\t\t\treturn parseAndThrowError( response, options.parse );\n\t\t} )\n\t\t.then( ( response ) =>\n\t\t\tparseResponseAndNormalizeError( response, options.parse )\n\t\t);\n};\n\nexport default mediaUploadMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,EAAE,QAAQ,iBAAiB;;AAEpC;AACA;AACA;AACA,SACCC,kBAAkB,EAClBC,8BAA8B,QACxB,mBAAmB;;AAE1B;AACA;AACA;AACA;AACA,SAASC,oBAAoBA,CAAEC,OAAO,EAAG;EACxC,MAAMC,cAAc,GAAG,CAAC,CAAED,OAAO,CAACE,MAAM,IAAIF,OAAO,CAACE,MAAM,KAAK,MAAM;EACrE,MAAMC,eAAe,GAClB,CAAC,CAAEH,OAAO,CAACI,IAAI,IAAIJ,OAAO,CAACI,IAAI,CAACC,OAAO,CAAE,cAAe,CAAC,KAAK,CAAC,CAAC,IAChE,CAAC,CAAEL,OAAO,CAACM,GAAG,IAAIN,OAAO,CAACM,GAAG,CAACD,OAAO,CAAE,cAAe,CAAC,KAAK,CAAC,CAAG;EAEnE,OAAOF,eAAe,IAAIF,cAAc;AACzC;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAMM,qBAAqB,GAAGA,CAAEP,OAAO,EAAEQ,IAAI,KAAM;EAClD,IAAK,CAAET,oBAAoB,CAAEC,OAAQ,CAAC,EAAG;IACxC,OAAOQ,IAAI,CAAER,OAAQ,CAAC;EACvB;EAEA,IAAIS,OAAO,GAAG,CAAC;EACf,MAAMC,UAAU,GAAG,CAAC;;EAEpB;AACD;AACA;AACA;EACC,MAAMC,WAAW,GAAKC,YAAY,IAAM;IACvCH,OAAO,EAAE;IACT,OAAOD,IAAI,CAAE;MACZJ,IAAI,EAAG,gBAAgBQ,YAAc,eAAc;MACnDV,MAAM,EAAE,MAAM;MACd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ndpointMiddleware = (options, next) => {
|
|
5
5
|
let path = options.path;
|
|
6
6
|
let namespaceTrimmed, endpointTrimmed;
|
|
7
|
-
|
|
8
7
|
if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
|
|
9
8
|
namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
|
|
10
9
|
endpointTrimmed = options.endpoint.replace(/^\//, '');
|
|
11
|
-
|
|
12
10
|
if (endpointTrimmed) {
|
|
13
11
|
path = namespaceTrimmed + '/' + endpointTrimmed;
|
|
14
12
|
} else {
|
|
15
13
|
path = namespaceTrimmed;
|
|
16
14
|
}
|
|
17
15
|
}
|
|
18
|
-
|
|
19
16
|
delete options.namespace;
|
|
20
17
|
delete options.endpoint;
|
|
21
|
-
return next({
|
|
18
|
+
return next({
|
|
19
|
+
...options,
|
|
22
20
|
path
|
|
23
21
|
});
|
|
24
22
|
};
|
|
25
|
-
|
|
26
23
|
export default namespaceAndEndpointMiddleware;
|
|
27
24
|
//# sourceMappingURL=namespace-endpoint.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"names":["namespaceAndEndpointMiddleware","options","next","path","namespaceTrimmed","endpointTrimmed","namespace","endpoint","replace"],"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;AAED,eAAeH,8BAA8B"}
|
|
@@ -9,25 +9,25 @@ function createNonceMiddleware(nonce) {
|
|
|
9
9
|
const middleware = (options, next) => {
|
|
10
10
|
const {
|
|
11
11
|
headers = {}
|
|
12
|
-
} = options;
|
|
13
|
-
// thereof) was specified, no need to add a nonce header.
|
|
12
|
+
} = options;
|
|
14
13
|
|
|
14
|
+
// If an 'X-WP-Nonce' header (or any case-insensitive variation
|
|
15
|
+
// thereof) was specified, no need to add a nonce header.
|
|
15
16
|
for (const headerName in headers) {
|
|
16
17
|
if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
|
|
17
18
|
return next(options);
|
|
18
19
|
}
|
|
19
20
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
headers: {
|
|
21
|
+
return next({
|
|
22
|
+
...options,
|
|
23
|
+
headers: {
|
|
24
|
+
...headers,
|
|
23
25
|
'X-WP-Nonce': middleware.nonce
|
|
24
26
|
}
|
|
25
27
|
});
|
|
26
28
|
};
|
|
27
|
-
|
|
28
29
|
middleware.nonce = nonce;
|
|
29
30
|
return middleware;
|
|
30
31
|
}
|
|
31
|
-
|
|
32
32
|
export default createNonceMiddleware;
|
|
33
33
|
//# sourceMappingURL=nonce.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"names":["createNonceMiddleware","nonce","middleware","options","next","headers","headerName","toLowerCase"],"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;AAEA,eAAeF,qBAAqB"}
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
* WordPress dependencies
|
|
3
3
|
*/
|
|
4
4
|
import { addQueryArgs, getQueryArgs, normalizePath } from '@wordpress/url';
|
|
5
|
+
|
|
5
6
|
/**
|
|
6
7
|
* @param {Record<string, any>} preloadedData
|
|
7
8
|
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
|
|
8
9
|
*/
|
|
9
|
-
|
|
10
10
|
function createPreloadingMiddleware(preloadedData) {
|
|
11
11
|
const cache = Object.fromEntries(Object.entries(preloadedData).map(([path, data]) => [normalizePath(path), data]));
|
|
12
12
|
return (options, next) => {
|
|
@@ -14,42 +14,38 @@ function createPreloadingMiddleware(preloadedData) {
|
|
|
14
14
|
parse = true
|
|
15
15
|
} = options;
|
|
16
16
|
/** @type {string | void} */
|
|
17
|
-
|
|
18
17
|
let rawPath = options.path;
|
|
19
|
-
|
|
20
18
|
if (!rawPath && options.url) {
|
|
21
19
|
const {
|
|
22
20
|
rest_route: pathFromQuery,
|
|
23
21
|
...queryArgs
|
|
24
22
|
} = getQueryArgs(options.url);
|
|
25
|
-
|
|
26
23
|
if (typeof pathFromQuery === 'string') {
|
|
27
24
|
rawPath = addQueryArgs(pathFromQuery, queryArgs);
|
|
28
25
|
}
|
|
29
26
|
}
|
|
30
|
-
|
|
31
27
|
if (typeof rawPath !== 'string') {
|
|
32
28
|
return next(options);
|
|
33
29
|
}
|
|
34
|
-
|
|
35
30
|
const method = options.method || 'GET';
|
|
36
31
|
const path = normalizePath(rawPath);
|
|
37
|
-
|
|
38
32
|
if ('GET' === method && cache[path]) {
|
|
39
|
-
const cacheData = cache[path];
|
|
33
|
+
const cacheData = cache[path];
|
|
40
34
|
|
|
35
|
+
// Unsetting the cache key ensures that the data is only used a single time.
|
|
41
36
|
delete cache[path];
|
|
42
37
|
return prepareResponse(cacheData, !!parse);
|
|
43
38
|
} else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
|
|
44
|
-
const cacheData = cache[method][path];
|
|
39
|
+
const cacheData = cache[method][path];
|
|
45
40
|
|
|
41
|
+
// Unsetting the cache key ensures that the data is only used a single time.
|
|
46
42
|
delete cache[method][path];
|
|
47
43
|
return prepareResponse(cacheData, !!parse);
|
|
48
44
|
}
|
|
49
|
-
|
|
50
45
|
return next(options);
|
|
51
46
|
};
|
|
52
47
|
}
|
|
48
|
+
|
|
53
49
|
/**
|
|
54
50
|
* This is a helper function that sends a success response.
|
|
55
51
|
*
|
|
@@ -57,8 +53,6 @@ function createPreloadingMiddleware(preloadedData) {
|
|
|
57
53
|
* @param {boolean} parse
|
|
58
54
|
* @return {Promise<any>} Promise with the response.
|
|
59
55
|
*/
|
|
60
|
-
|
|
61
|
-
|
|
62
56
|
function prepareResponse(responseData, parse) {
|
|
63
57
|
return Promise.resolve(parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
|
|
64
58
|
status: 200,
|
|
@@ -66,6 +60,5 @@ function prepareResponse(responseData, parse) {
|
|
|
66
60
|
headers: responseData.headers
|
|
67
61
|
}));
|
|
68
62
|
}
|
|
69
|
-
|
|
70
63
|
export default createPreloadingMiddleware;
|
|
71
64
|
//# sourceMappingURL=preloading.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"names":["addQueryArgs","getQueryArgs","normalizePath","createPreloadingMiddleware","preloadedData","cache","Object","fromEntries","entries","map","path","data","options","next","parse","rawPath","url","rest_route","pathFromQuery","queryArgs","method","cacheData","prepareResponse","responseData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers"],"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":"AAAA;AACA;AACA;AACA,SAASA,YAAY,EAAEC,YAAY,EAAEC,aAAa,QAAQ,gBAAgB;;AAE1E;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,CAC1DT,aAAa,CAAEQ,IAAK,CAAC,EACrBC,IAAI,CACH,CACH,CAAC;EAED,OAAO,CAAEC,OAAO,EAAEC,IAAI,KAAM;IAC3B,MAAM;MAAEC,KAAK,GAAG;IAAK,CAAC,GAAGF,OAAO;IAChC;IACA,IAAIG,OAAO,GAAGH,OAAO,CAACF,IAAI;IAC1B,IAAK,CAAEK,OAAO,IAAIH,OAAO,CAACI,GAAG,EAAG;MAC/B,MAAM;QAAEC,UAAU,EAAEC,aAAa;QAAE,GAAGC;MAAU,CAAC,GAAGlB,YAAY,CAC/DW,OAAO,CAACI,GACT,CAAC;MAED,IAAK,OAAOE,aAAa,KAAK,QAAQ,EAA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U;EACtB,CAAE,CACN,CAAC;AACF;AAEA,eAAe9B,0BAA0B"}
|
|
@@ -2,39 +2,35 @@
|
|
|
2
2
|
* Internal dependencies
|
|
3
3
|
*/
|
|
4
4
|
import namespaceAndEndpointMiddleware from './namespace-endpoint';
|
|
5
|
+
|
|
5
6
|
/**
|
|
6
7
|
* @param {string} rootURL
|
|
7
8
|
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
|
|
8
9
|
*/
|
|
9
|
-
|
|
10
10
|
const createRootURLMiddleware = rootURL => (options, next) => {
|
|
11
11
|
return namespaceAndEndpointMiddleware(options, optionsWithPath => {
|
|
12
12
|
let url = optionsWithPath.url;
|
|
13
13
|
let path = optionsWithPath.path;
|
|
14
14
|
let apiRoot;
|
|
15
|
-
|
|
16
15
|
if (typeof path === 'string') {
|
|
17
16
|
apiRoot = rootURL;
|
|
18
|
-
|
|
19
17
|
if (-1 !== rootURL.indexOf('?')) {
|
|
20
18
|
path = path.replace('?', '&');
|
|
21
19
|
}
|
|
20
|
+
path = path.replace(/^\//, '');
|
|
22
21
|
|
|
23
|
-
|
|
22
|
+
// API root may already include query parameter prefix if site is
|
|
24
23
|
// configured to use plain permalinks.
|
|
25
|
-
|
|
26
24
|
if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
|
|
27
25
|
path = path.replace('?', '&');
|
|
28
26
|
}
|
|
29
|
-
|
|
30
27
|
url = apiRoot + path;
|
|
31
28
|
}
|
|
32
|
-
|
|
33
|
-
|
|
29
|
+
return next({
|
|
30
|
+
...optionsWithPath,
|
|
34
31
|
url
|
|
35
32
|
});
|
|
36
33
|
});
|
|
37
34
|
};
|
|
38
|
-
|
|
39
35
|
export default createRootURLMiddleware;
|
|
40
36
|
//# sourceMappingURL=root-url.js.map
|