@wordpress/api-fetch 7.29.1-next.f34ab90e9.0 → 7.30.1-next.6870dfe5b.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 +50 -51
- package/build/index.js.map +1 -1
- package/build/middlewares/fetch-all-middleware.js +14 -14
- package/build/middlewares/fetch-all-middleware.js.map +1 -1
- package/build/middlewares/http-v1.js +6 -5
- package/build/middlewares/http-v1.js.map +1 -1
- package/build/middlewares/media-upload.js +7 -7
- package/build/middlewares/media-upload.js.map +1 -1
- package/build/middlewares/namespace-endpoint.js +2 -1
- package/build/middlewares/namespace-endpoint.js.map +1 -1
- package/build/middlewares/nonce.js +7 -5
- package/build/middlewares/nonce.js.map +1 -1
- package/build/middlewares/preloading.js +10 -7
- package/build/middlewares/preloading.js.map +1 -1
- package/build/middlewares/root-url.js +2 -2
- package/build/middlewares/root-url.js.map +1 -1
- package/build/middlewares/theme-preview.js +6 -2
- package/build/middlewares/theme-preview.js.map +1 -1
- package/build/middlewares/user-locale.js +2 -1
- package/build/middlewares/user-locale.js.map +1 -1
- package/build/types.js.map +1 -1
- package/build/utils/response.js +31 -50
- package/build/utils/response.js.map +1 -1
- package/build-module/index.js +38 -52
- package/build-module/index.js.map +1 -1
- package/build-module/middlewares/fetch-all-middleware.js +14 -15
- package/build-module/middlewares/fetch-all-middleware.js.map +1 -1
- package/build-module/middlewares/http-v1.js +6 -5
- package/build-module/middlewares/http-v1.js.map +1 -1
- package/build-module/middlewares/media-upload.js +7 -8
- package/build-module/middlewares/media-upload.js.map +1 -1
- package/build-module/middlewares/namespace-endpoint.js +2 -1
- package/build-module/middlewares/namespace-endpoint.js.map +1 -1
- package/build-module/middlewares/nonce.js +7 -5
- package/build-module/middlewares/nonce.js.map +1 -1
- package/build-module/middlewares/preloading.js +10 -7
- package/build-module/middlewares/preloading.js.map +1 -1
- package/build-module/middlewares/root-url.js +3 -2
- package/build-module/middlewares/root-url.js.map +1 -1
- package/build-module/middlewares/theme-preview.js +5 -2
- package/build-module/middlewares/theme-preview.js.map +1 -1
- package/build-module/middlewares/user-locale.js +2 -1
- package/build-module/middlewares/user-locale.js.map +1 -1
- package/build-module/types.js.map +1 -1
- package/build-module/utils/response.js +30 -48
- package/build-module/utils/response.js.map +1 -1
- package/build-types/index.d.ts +25 -32
- package/build-types/index.d.ts.map +1 -1
- package/build-types/middlewares/fetch-all-middleware.d.ts +5 -4
- package/build-types/middlewares/fetch-all-middleware.d.ts.map +1 -1
- package/build-types/middlewares/http-v1.d.ts +8 -3
- package/build-types/middlewares/http-v1.d.ts.map +1 -1
- package/build-types/middlewares/media-upload.d.ts +5 -4
- package/build-types/middlewares/media-upload.d.ts.map +1 -1
- package/build-types/middlewares/namespace-endpoint.d.ts +4 -3
- package/build-types/middlewares/namespace-endpoint.d.ts.map +1 -1
- package/build-types/middlewares/nonce.d.ts +9 -4
- package/build-types/middlewares/nonce.d.ts.map +1 -1
- package/build-types/middlewares/preloading.d.ts +8 -4
- package/build-types/middlewares/preloading.d.ts.map +1 -1
- package/build-types/middlewares/root-url.d.ts +8 -4
- package/build-types/middlewares/root-url.d.ts.map +1 -1
- package/build-types/middlewares/theme-preview.d.ts +8 -4
- package/build-types/middlewares/theme-preview.d.ts.map +1 -1
- package/build-types/middlewares/user-locale.d.ts +4 -3
- package/build-types/middlewares/user-locale.d.ts.map +1 -1
- package/build-types/types.d.ts +4 -3
- package/build-types/types.d.ts.map +1 -1
- package/build-types/utils/response.d.ts +13 -5
- package/build-types/utils/response.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/{index.js → index.ts} +78 -69
- package/src/middlewares/{fetch-all-middleware.js → fetch-all-middleware.ts} +24 -20
- package/src/middlewares/{http-v1.js → http-v1.ts} +8 -6
- package/src/middlewares/{media-upload.js → media-upload.ts} +13 -12
- package/src/middlewares/{namespace-endpoint.js → namespace-endpoint.ts} +7 -2
- package/src/middlewares/{nonce.js → nonce.ts} +15 -7
- package/src/middlewares/{preloading.js → preloading.ts} +21 -11
- package/src/middlewares/root-url.ts +47 -0
- package/src/middlewares/test/{fetch-all-middleware.js → fetch-all-middleware.ts} +1 -1
- package/src/middlewares/test/{http-v1.js → http-v1.ts} +7 -4
- package/src/middlewares/test/{media-upload.js → media-upload.ts} +2 -1
- package/src/middlewares/test/{namespace-endpoint.js → namespace-endpoint.ts} +2 -1
- package/src/middlewares/test/{nonce.js → nonce.ts} +5 -4
- package/src/middlewares/test/{preloading.js → preloading.ts} +31 -11
- package/src/middlewares/test/{root-url.js → root-url.ts} +2 -1
- package/src/middlewares/test/{user-locale.js → user-locale.ts} +9 -8
- package/src/middlewares/theme-preview.ts +60 -0
- package/src/middlewares/{user-locale.js → user-locale.ts} +4 -2
- package/src/test/index.js +218 -147
- package/src/types.ts +10 -5
- package/src/utils/response.ts +64 -0
- package/tsconfig.tsbuildinfo +1 -1
- package/src/middlewares/root-url.js +0 -44
- package/src/middlewares/theme-preview.js +0 -42
- package/src/utils/response.js +0 -85
|
@@ -1 +1 @@
|
|
|
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","forEach","key","value","toLowerCase","replace","_","encodeURI","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/preloading.
|
|
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","forEach","key","value","toLowerCase","replace","_","encodeURI","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/preloading.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArgs, normalizePath } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport type { APIFetchMiddleware } from '../types';\n\n/**\n * @param preloadedData\n * @return Preloading middleware.\n */\nfunction createPreloadingMiddleware(\n\tpreloadedData: Record< string, any >\n): APIFetchMiddleware {\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\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 responseData\n * @param parse\n * @return Promise with the response.\n */\nfunction prepareResponse(\n\tresponseData: Record< string, any >,\n\tparse: boolean\n) {\n\tif ( parse ) {\n\t\treturn Promise.resolve( responseData.body );\n\t}\n\n\ttry {\n\t\treturn Promise.resolve(\n\t\t\tnew window.Response( JSON.stringify( responseData.body ), {\n\t\t\t\tstatus: 200,\n\t\t\t\tstatusText: 'OK',\n\t\t\t\theaders: responseData.headers,\n\t\t\t} )\n\t\t);\n\t} catch {\n\t\t// See: https://github.com/WordPress/gutenberg/issues/67358#issuecomment-2621163926.\n\t\tObject.entries(\n\t\t\tresponseData.headers as Record< string, string >\n\t\t).forEach( ( [ key, value ] ) => {\n\t\t\tif ( key.toLowerCase() === 'link' ) {\n\t\t\t\tresponseData.headers[ key ] = value.replace(\n\t\t\t\t\t/<([^>]+)>/,\n\t\t\t\t\t( _, url ) => `<${ encodeURI( url ) }>`\n\t\t\t\t);\n\t\t\t}\n\t\t} );\n\n\t\treturn Promise.resolve(\n\t\t\tparse\n\t\t\t\t? responseData.body\n\t\t\t\t: new window.Response( JSON.stringify( responseData.body ), {\n\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\t\theaders: responseData.headers,\n\t\t\t\t } )\n\t\t);\n\t}\n}\n\nexport default createPreloadingMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA,SAASC,0BAA0BA,CAClCC,aAAoC,EACf;EACrB,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,IAAIG,OAAO,GAAGH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Ac,EACb;EACD,IAAKA,KAAK,EAAG;IACZ,OAAOY,OAAO,CAACC,OAAO,CAAEF,YAAY,CAACG,IAAK,CAAC;EAC5C;EAEA,IAAI;IACH,OAAOF,OAAO,CAACC,OAAO,CACrB,IAAIE,MAAM,CAACC,QAAQ,CAAEC,IAAI,CAACC,SAAS,CAAEP,YAAY,CAACG,IAAK,CAAC,EAAE;MACzDK,MAAM,EAAE,GAAG;MACXC,UAAU,EAAE,IAAI;MAChBC,OAAO,EAAEV,YAAY,CAACU;IACvB,CAAE,CACH,CAAC;EACF,CAAC,CAAC,MAAM;IACP;IACA9B,MAAM,CAACE,OAAO,CACbkB,YAAY,CAACU,OACd,CAAC,CAACC,OAAO,CAAE,CAAE,CAAEC,GAAG,EAAEC,KAAK,CAAE,KAAM;MAChC,IAAKD,GAAG,CAACE,WAAW,CAAC,CAAC,KAAK,MAAM,EAAG;QACnCd,YAAY,CAACU,OAAO,CAAEE,GAAG,CAAE,GAAGC,KAAK,CAACE,OAAO,CAC1C,WAAW,EACX,CAAEC,CAAC,EAAEzB,GAAG,KAAM,IAAK0B,SAAS,CAAE1B,GAAI,CAAC,GACpC,CAAC;MACF;IACD,CAAE,CAAC;IAEH,OAAOU,OAAO,CAACC,OAAO,CACrBb,KAAK,GACFW,YAAY,CAACG,IAAI,GACjB,IAAIC,MAAM,CAACC,QAAQ,CAAEC,IAAI,CAACC,SAAS,CAAEP,YAAY,CAACG,IAAK,CAAC,EAAE;MAC1DK,MAAM,EAAE,GAAG;MACXC,UAAU,EAAE,IAAI;MAChBC,OAAO,EAAEV,YAAY,CAACU;IACtB,CAAE,CACN,CAAC;EACF;AACD;AAAC,IAAAQ,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEc3C,0BAA0B","ignoreList":[]}
|
|
@@ -11,8 +11,8 @@ var _namespaceEndpoint = _interopRequireDefault(require("./namespace-endpoint"))
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
|
-
* @param
|
|
15
|
-
* @return
|
|
14
|
+
* @param rootURL
|
|
15
|
+
* @return Root URL middleware.
|
|
16
16
|
*/
|
|
17
17
|
const createRootURLMiddleware = rootURL => (options, next) => {
|
|
18
18
|
return (0, _namespaceEndpoint.default)(options, optionsWithPath => {
|
|
@@ -1 +1 @@
|
|
|
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.
|
|
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.ts"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport type { APIFetchMiddleware } from '../types';\nimport namespaceAndEndpointMiddleware from './namespace-endpoint';\n\n/**\n * @param rootURL\n * @return Root URL middleware.\n */\nconst createRootURLMiddleware =\n\t( rootURL: string ): APIFetchMiddleware =>\n\t( options, next ) => {\n\t\treturn namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => {\n\t\t\tlet url = optionsWithPath.url;\n\t\t\tlet path = optionsWithPath.path;\n\t\t\tlet apiRoot;\n\n\t\t\tif ( typeof path === 'string' ) {\n\t\t\t\tapiRoot = rootURL;\n\n\t\t\t\tif ( -1 !== rootURL.indexOf( '?' ) ) {\n\t\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t\t}\n\n\t\t\t\tpath = path.replace( /^\\//, '' );\n\n\t\t\t\t// API root may already include query parameter prefix if site is\n\t\t\t\t// configured to use plain permalinks.\n\t\t\t\tif (\n\t\t\t\t\t'string' === typeof apiRoot &&\n\t\t\t\t\t-1 !== apiRoot.indexOf( '?' )\n\t\t\t\t) {\n\t\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t\t}\n\n\t\t\t\turl = apiRoot + path;\n\t\t\t}\n\n\t\t\treturn next( {\n\t\t\t\t...optionsWithPath,\n\t\t\t\turl,\n\t\t\t} );\n\t\t} );\n\t};\n\nexport default createRootURLMiddleware;\n"],"mappings":";;;;;;;AAIA,IAAAA,kBAAA,GAAAC,sBAAA,CAAAC,OAAA;AAJA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA,MAAMC,uBAAuB,GAC1BC,OAAe,IACjB,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACpB,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,GAEYb,uBAAuB","ignoreList":[]}
|
|
@@ -9,6 +9,10 @@ var _url = require("@wordpress/url");
|
|
|
9
9
|
* WordPress dependencies
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
/**
|
|
13
|
+
* Internal dependencies
|
|
14
|
+
*/
|
|
15
|
+
|
|
12
16
|
/**
|
|
13
17
|
* This appends a `wp_theme_preview` parameter to the REST API request URL if
|
|
14
18
|
* the admin URL contains a `theme` GET parameter.
|
|
@@ -16,8 +20,8 @@ var _url = require("@wordpress/url");
|
|
|
16
20
|
* If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,
|
|
17
21
|
* then bypass this middleware.
|
|
18
22
|
*
|
|
19
|
-
* @param
|
|
20
|
-
* @return
|
|
23
|
+
* @param themePath
|
|
24
|
+
* @return Preloading middleware.
|
|
21
25
|
*/
|
|
22
26
|
const createThemePreviewMiddleware = themePath => (options, next) => {
|
|
23
27
|
if (typeof options.url === 'string') {
|
|
@@ -1 +1 @@
|
|
|
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.
|
|
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.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArg, removeQueryArgs } from '@wordpress/url';\n/**\n * Internal dependencies\n */\nimport type { APIFetchMiddleware } from '../types';\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 themePath\n * @return Preloading middleware.\n */\nconst createThemePreviewMiddleware =\n\t( themePath: Record< string, any > ): APIFetchMiddleware =>\n\t( options, next ) => {\n\t\tif ( typeof options.url === 'string' ) {\n\t\t\tconst wpThemePreview = getQueryArg(\n\t\t\t\toptions.url,\n\t\t\t\t'wp_theme_preview'\n\t\t\t);\n\t\t\tif ( wpThemePreview === undefined ) {\n\t\t\t\toptions.url = addQueryArgs( options.url, {\n\t\t\t\t\twp_theme_preview: themePath,\n\t\t\t\t} );\n\t\t\t} else if ( wpThemePreview === '' ) {\n\t\t\t\toptions.url = removeQueryArgs(\n\t\t\t\t\toptions.url,\n\t\t\t\t\t'wp_theme_preview'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif ( typeof options.path === 'string' ) {\n\t\t\tconst wpThemePreview = getQueryArg(\n\t\t\t\toptions.path,\n\t\t\t\t'wp_theme_preview'\n\t\t\t);\n\t\t\tif ( wpThemePreview === undefined ) {\n\t\t\t\toptions.path = addQueryArgs( options.path, {\n\t\t\t\t\twp_theme_preview: themePath,\n\t\t\t\t} );\n\t\t\t} else if ( wpThemePreview === '' ) {\n\t\t\t\toptions.path = removeQueryArgs(\n\t\t\t\t\toptions.path,\n\t\t\t\t\t'wp_theme_preview'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn next( options );\n\t};\n\nexport default createThemePreviewMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAEA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,4BAA4B,GAC/BC,SAAgC,IAClC,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACpB,IAAK,OAAOD,OAAO,CAACE,GAAG,KAAK,QAAQ,EAAG;IACtC,MAAMC,cAAc,GAAG,IAAAC,gBAAW,EACjCJ,OAAO,CAACE,GAAG,EACX,kBACD,CAAC;IACD,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,EAC5BR,OAAO,CAACE,GAAG,EACX,kBACD,CAAC;IACF;EACD;EAEA,IAAK,OAAOF,OAAO,CAACS,IAAI,KAAK,QAAQ,EAAG;IACvC,MAAMN,cAAc,GAAG,IAAAC,gBAAW,EACjCJ,OAAO,CAACS,IAAI,EACZ,kBACD,CAAC;IACD,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,EAC7BR,OAAO,CAACS,IAAI,EACZ,kBACD,CAAC;IACF;EACD;EAEA,OAAOR,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAU,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEYd,4BAA4B","ignoreList":[]}
|
|
@@ -10,8 +10,9 @@ var _url = require("@wordpress/url");
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
13
|
+
* Internal dependencies
|
|
14
14
|
*/
|
|
15
|
+
|
|
15
16
|
const userLocaleMiddleware = (options, next) => {
|
|
16
17
|
if (typeof options.url === 'string' && !(0, _url.hasQueryArg)(options.url, '_locale')) {
|
|
17
18
|
options.url = (0, _url.addQueryArgs)(options.url, {
|
|
@@ -1 +1 @@
|
|
|
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.
|
|
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.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, hasQueryArg } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport type { APIFetchMiddleware } from '../types';\n\nconst userLocaleMiddleware: APIFetchMiddleware = ( 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;;AAGA,MAAMC,oBAAwC,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACrE,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":[]}
|
package/build/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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?:
|
|
1
|
+
{"version":3,"names":[],"sources":["@wordpress/api-fetch/src/types.ts"],"sourcesContent":["export interface APIFetchOptions< Parse extends boolean = boolean >\n\textends 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?: Parse;\n\tdata?: any;\n\tnamespace?: string;\n\tendpoint?: string;\n}\n\nexport type FetchHandler< Parse extends boolean = boolean > = (\n\tnextOptions: APIFetchOptions< Parse >\n) => Promise< any >;\n\nexport type APIFetchMiddleware< Parse extends boolean = boolean > = (\n\toptions: APIFetchOptions< Parse >,\n\tnext: FetchHandler< Parse >\n) => Promise< any >;\n"],"mappings":"","ignoreList":[]}
|
package/build/utils/response.js
CHANGED
|
@@ -4,80 +4,61 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
exports.parseAndThrowError = parseAndThrowError;
|
|
7
|
-
exports.parseResponseAndNormalizeError =
|
|
7
|
+
exports.parseResponseAndNormalizeError = parseResponseAndNormalizeError;
|
|
8
8
|
var _i18n = require("@wordpress/i18n");
|
|
9
9
|
/**
|
|
10
10
|
* WordPress dependencies
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
/**
|
|
14
|
-
* Parses the apiFetch response.
|
|
15
|
-
*
|
|
16
|
-
* @param {Response} response
|
|
17
|
-
* @param {boolean} shouldParseResponse
|
|
18
|
-
*
|
|
19
|
-
* @return {Promise<any> | null | Response} Parsed response.
|
|
20
|
-
*/
|
|
21
|
-
const parseResponse = (response, shouldParseResponse = true) => {
|
|
22
|
-
if (shouldParseResponse) {
|
|
23
|
-
if (response.status === 204) {
|
|
24
|
-
return null;
|
|
25
|
-
}
|
|
26
|
-
return response.json ? response.json() : Promise.reject(response);
|
|
27
|
-
}
|
|
28
|
-
return response;
|
|
29
|
-
};
|
|
30
|
-
|
|
31
13
|
/**
|
|
32
14
|
* Calls the `json` function on the Response, throwing an error if the response
|
|
33
15
|
* doesn't have a json function or if parsing the json itself fails.
|
|
34
16
|
*
|
|
35
|
-
* @param
|
|
36
|
-
* @return
|
|
17
|
+
* @param response
|
|
18
|
+
* @return Parsed response.
|
|
37
19
|
*/
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
20
|
+
async function parseJsonAndNormalizeError(response) {
|
|
21
|
+
try {
|
|
22
|
+
return await response.json();
|
|
23
|
+
} catch {
|
|
24
|
+
throw {
|
|
25
|
+
code: 'invalid_json',
|
|
26
|
+
message: (0, _i18n.__)('The response is not a valid JSON response.')
|
|
27
|
+
};
|
|
45
28
|
}
|
|
46
|
-
|
|
47
|
-
throw invalidJsonError;
|
|
48
|
-
});
|
|
49
|
-
};
|
|
29
|
+
}
|
|
50
30
|
|
|
51
31
|
/**
|
|
52
32
|
* Parses the apiFetch response properly and normalize response errors.
|
|
53
33
|
*
|
|
54
|
-
* @param
|
|
55
|
-
* @param
|
|
34
|
+
* @param response
|
|
35
|
+
* @param shouldParseResponse
|
|
56
36
|
*
|
|
57
|
-
* @return
|
|
37
|
+
* @return Parsed response.
|
|
58
38
|
*/
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
39
|
+
async function parseResponseAndNormalizeError(response, shouldParseResponse = true) {
|
|
40
|
+
if (!shouldParseResponse) {
|
|
41
|
+
return response;
|
|
42
|
+
}
|
|
43
|
+
if (response.status === 204) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
return await parseJsonAndNormalizeError(response);
|
|
47
|
+
}
|
|
62
48
|
|
|
63
49
|
/**
|
|
64
50
|
* Parses a response, throwing an error if parsing the response fails.
|
|
65
51
|
*
|
|
66
|
-
* @param
|
|
67
|
-
* @param
|
|
68
|
-
* @return
|
|
52
|
+
* @param response
|
|
53
|
+
* @param shouldParseResponse
|
|
54
|
+
* @return Never returns, always throws.
|
|
69
55
|
*/
|
|
70
|
-
|
|
71
|
-
function parseAndThrowError(response, shouldParseResponse = true) {
|
|
56
|
+
async function parseAndThrowError(response, shouldParseResponse = true) {
|
|
72
57
|
if (!shouldParseResponse) {
|
|
73
58
|
throw response;
|
|
74
59
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
message: (0, _i18n.__)('An unknown error occurred.')
|
|
79
|
-
};
|
|
80
|
-
throw error || unknownError;
|
|
81
|
-
});
|
|
60
|
+
|
|
61
|
+
// Parse the response JSON and throw it as an error.
|
|
62
|
+
throw await parseJsonAndNormalizeError(response);
|
|
82
63
|
}
|
|
83
64
|
//# sourceMappingURL=response.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_i18n","require","
|
|
1
|
+
{"version":3,"names":["_i18n","require","parseJsonAndNormalizeError","response","json","code","message","__","parseResponseAndNormalizeError","shouldParseResponse","status","parseAndThrowError"],"sources":["@wordpress/api-fetch/src/utils/response.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\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\n * @return Parsed response.\n */\nasync function parseJsonAndNormalizeError( response: Response ) {\n\ttry {\n\t\treturn await response.json();\n\t} catch {\n\t\tthrow {\n\t\t\tcode: 'invalid_json',\n\t\t\tmessage: __( 'The response is not a valid JSON response.' ),\n\t\t};\n\t}\n}\n\n/**\n * Parses the apiFetch response properly and normalize response errors.\n *\n * @param response\n * @param shouldParseResponse\n *\n * @return Parsed response.\n */\nexport async function parseResponseAndNormalizeError(\n\tresponse: Response,\n\tshouldParseResponse = true\n) {\n\tif ( ! shouldParseResponse ) {\n\t\treturn response;\n\t}\n\n\tif ( response.status === 204 ) {\n\t\treturn null;\n\t}\n\n\treturn await parseJsonAndNormalizeError( response );\n}\n\n/**\n * Parses a response, throwing an error if parsing the response fails.\n *\n * @param response\n * @param shouldParseResponse\n * @return Never returns, always throws.\n */\nexport async function parseAndThrowError(\n\tresponse: Response,\n\tshouldParseResponse = true\n) {\n\tif ( ! shouldParseResponse ) {\n\t\tthrow response;\n\t}\n\n\t// Parse the response JSON and throw it as an error.\n\tthrow await parseJsonAndNormalizeError( response );\n}\n"],"mappings":";;;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeC,0BAA0BA,CAAEC,QAAkB,EAAG;EAC/D,IAAI;IACH,OAAO,MAAMA,QAAQ,CAACC,IAAI,CAAC,CAAC;EAC7B,CAAC,CAAC,MAAM;IACP,MAAM;MACLC,IAAI,EAAE,cAAc;MACpBC,OAAO,EAAE,IAAAC,QAAE,EAAE,4CAA6C;IAC3D,CAAC;EACF;AACD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeC,8BAA8BA,CACnDL,QAAkB,EAClBM,mBAAmB,GAAG,IAAI,EACzB;EACD,IAAK,CAAEA,mBAAmB,EAAG;IAC5B,OAAON,QAAQ;EAChB;EAEA,IAAKA,QAAQ,CAACO,MAAM,KAAK,GAAG,EAAG;IAC9B,OAAO,IAAI;EACZ;EAEA,OAAO,MAAMR,0BAA0B,CAAEC,QAAS,CAAC;AACpD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeQ,kBAAkBA,CACvCR,QAAkB,EAClBM,mBAAmB,GAAG,IAAI,EACzB;EACD,IAAK,CAAEA,mBAAmB,EAAG;IAC5B,MAAMN,QAAQ;EACf;;EAEA;EACA,MAAM,MAAMD,0BAA0B,CAAEC,QAAS,CAAC;AACnD","ignoreList":[]}
|
package/build-module/index.js
CHANGED
|
@@ -16,12 +16,9 @@ import userLocaleMiddleware from './middlewares/user-locale';
|
|
|
16
16
|
import mediaUploadMiddleware from './middlewares/media-upload';
|
|
17
17
|
import createThemePreviewMiddleware from './middlewares/theme-preview';
|
|
18
18
|
import { parseResponseAndNormalizeError, parseAndThrowError } from './utils/response';
|
|
19
|
-
|
|
20
19
|
/**
|
|
21
20
|
* Default set of header values which should be sent with every request unless
|
|
22
21
|
* explicitly provided through apiFetch options.
|
|
23
|
-
*
|
|
24
|
-
* @type {Record<string, string>}
|
|
25
22
|
*/
|
|
26
23
|
const DEFAULT_HEADERS = {
|
|
27
24
|
// The backend uses the Accept header as a condition for considering an
|
|
@@ -34,49 +31,20 @@ const DEFAULT_HEADERS = {
|
|
|
34
31
|
/**
|
|
35
32
|
* Default set of fetch option values which should be sent with every request
|
|
36
33
|
* unless explicitly provided through apiFetch options.
|
|
37
|
-
*
|
|
38
|
-
* @type {Object}
|
|
39
34
|
*/
|
|
40
35
|
const DEFAULT_OPTIONS = {
|
|
41
36
|
credentials: 'include'
|
|
42
37
|
};
|
|
43
|
-
|
|
44
|
-
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
|
|
45
|
-
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* @type {import('./types').APIFetchMiddleware[]}
|
|
49
|
-
*/
|
|
50
38
|
const middlewares = [userLocaleMiddleware, namespaceEndpointMiddleware, httpV1Middleware, fetchAllMiddleware];
|
|
51
39
|
|
|
52
40
|
/**
|
|
53
41
|
* Register a middleware
|
|
54
42
|
*
|
|
55
|
-
* @param
|
|
43
|
+
* @param middleware
|
|
56
44
|
*/
|
|
57
45
|
function registerMiddleware(middleware) {
|
|
58
46
|
middlewares.unshift(middleware);
|
|
59
47
|
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Checks the status of a response, throwing the Response as an error if
|
|
63
|
-
* it is outside the 200 range.
|
|
64
|
-
*
|
|
65
|
-
* @param {Response} response
|
|
66
|
-
* @return {Response} The response if the status is in the 200 range.
|
|
67
|
-
*/
|
|
68
|
-
const checkStatus = response => {
|
|
69
|
-
if (response.status >= 200 && response.status < 300) {
|
|
70
|
-
return response;
|
|
71
|
-
}
|
|
72
|
-
throw response;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* @type {FetchHandler}
|
|
79
|
-
*/
|
|
80
48
|
const defaultFetchHandler = nextOptions => {
|
|
81
49
|
const {
|
|
82
50
|
url,
|
|
@@ -101,7 +69,7 @@ const defaultFetchHandler = nextOptions => {
|
|
|
101
69
|
body = JSON.stringify(data);
|
|
102
70
|
headers['Content-Type'] = 'application/json';
|
|
103
71
|
}
|
|
104
|
-
const responsePromise =
|
|
72
|
+
const responsePromise = globalThis.fetch(
|
|
105
73
|
// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
|
|
106
74
|
url || path || window.location.href, {
|
|
107
75
|
...DEFAULT_OPTIONS,
|
|
@@ -109,46 +77,59 @@ const defaultFetchHandler = nextOptions => {
|
|
|
109
77
|
body,
|
|
110
78
|
headers
|
|
111
79
|
});
|
|
112
|
-
return responsePromise.then(
|
|
80
|
+
return responsePromise.then(response => {
|
|
81
|
+
// If the response is not 2xx, still parse the response body as JSON
|
|
82
|
+
// but throw the JSON as error.
|
|
83
|
+
if (!response.ok) {
|
|
84
|
+
return parseAndThrowError(response, parse);
|
|
85
|
+
}
|
|
86
|
+
return parseResponseAndNormalizeError(response, parse);
|
|
87
|
+
}, err => {
|
|
113
88
|
// Re-throw AbortError for the users to handle it themselves.
|
|
114
89
|
if (err && err.name === 'AbortError') {
|
|
115
90
|
throw err;
|
|
116
91
|
}
|
|
117
92
|
|
|
118
|
-
//
|
|
119
|
-
//
|
|
93
|
+
// If the browser reports being offline, we'll just assume that
|
|
94
|
+
// this is why the request failed.
|
|
95
|
+
if (!globalThis.navigator.onLine) {
|
|
96
|
+
throw {
|
|
97
|
+
code: 'offline_error',
|
|
98
|
+
message: __('Unable to connect. Please check your Internet connection.')
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Hard to diagnose further due to how Window.fetch reports errors.
|
|
120
103
|
throw {
|
|
121
104
|
code: 'fetch_error',
|
|
122
|
-
message: __('
|
|
105
|
+
message: __('Could not get a valid response from the server.')
|
|
123
106
|
};
|
|
124
107
|
});
|
|
125
108
|
};
|
|
126
|
-
|
|
127
|
-
/** @type {FetchHandler} */
|
|
128
109
|
let fetchHandler = defaultFetchHandler;
|
|
129
110
|
|
|
130
111
|
/**
|
|
131
112
|
* Defines a custom fetch handler for making the requests that will override
|
|
132
113
|
* the default one using window.fetch
|
|
133
114
|
*
|
|
134
|
-
* @param
|
|
115
|
+
* @param newFetchHandler The new fetch handler
|
|
135
116
|
*/
|
|
136
117
|
function setFetchHandler(newFetchHandler) {
|
|
137
118
|
fetchHandler = newFetchHandler;
|
|
138
119
|
}
|
|
139
|
-
|
|
140
120
|
/**
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
* @
|
|
121
|
+
* Fetch
|
|
122
|
+
*
|
|
123
|
+
* @param options The options for the fetch.
|
|
124
|
+
* @return A promise representing the request processed via the registered middlewares.
|
|
144
125
|
*/
|
|
145
|
-
|
|
126
|
+
const apiFetch = options => {
|
|
146
127
|
// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
|
|
147
128
|
// converting `middlewares = [ m1, m2, m3 ]` into:
|
|
148
129
|
// ```
|
|
149
130
|
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
|
|
150
131
|
// ```
|
|
151
|
-
const enhancedHandler = middlewares.reduceRight((
|
|
132
|
+
const enhancedHandler = middlewares.reduceRight((next, middleware) => {
|
|
152
133
|
return workingOptions => middleware(workingOptions, next);
|
|
153
134
|
}, fetchHandler);
|
|
154
135
|
return enhancedHandler(options).catch(error => {
|
|
@@ -157,15 +138,19 @@ function apiFetch(options) {
|
|
|
157
138
|
}
|
|
158
139
|
|
|
159
140
|
// If the nonce is invalid, refresh it and try again.
|
|
160
|
-
return
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
141
|
+
return globalThis.fetch(apiFetch.nonceEndpoint).then(response => {
|
|
142
|
+
// If the nonce refresh fails, it means we failed to recover from the original
|
|
143
|
+
// `rest_cookie_invalid_nonce` error and that it's time to finally re-throw it.
|
|
144
|
+
if (!response.ok) {
|
|
145
|
+
return Promise.reject(error);
|
|
146
|
+
}
|
|
147
|
+
return response.text();
|
|
148
|
+
}).then(text => {
|
|
164
149
|
apiFetch.nonceMiddleware.nonce = text;
|
|
165
150
|
return apiFetch(options);
|
|
166
151
|
});
|
|
167
152
|
});
|
|
168
|
-
}
|
|
153
|
+
};
|
|
169
154
|
apiFetch.use = registerMiddleware;
|
|
170
155
|
apiFetch.setFetchHandler = setFetchHandler;
|
|
171
156
|
apiFetch.createNonceMiddleware = createNonceMiddleware;
|
|
@@ -175,4 +160,5 @@ apiFetch.fetchAllMiddleware = fetchAllMiddleware;
|
|
|
175
160
|
apiFetch.mediaUploadMiddleware = mediaUploadMiddleware;
|
|
176
161
|
apiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;
|
|
177
162
|
export default apiFetch;
|
|
163
|
+
export * from './types';
|
|
178
164
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
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,0BAA0B;AACjE,OAAOC,kBAAkB,MAAM,oCAAoC;AACnE,OAAOC,2BAA2B,MAAM,kCAAkC;AAC1E,OAAOC,gBAAgB,MAAM,uBAAuB;AACpD,OAAOC,oBAAoB,MAAM,2BAA2B;AAC5D,OAAOC,qBAAqB,MAAM,4BAA4B;AAC9D,OAAOC,4BAA4B,MAAM,6BAA6B;AACtE,SACCC,8BAA8B,EAC9BC,kBAAkB,QACZ,kBAAkB;;AAEzB;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,eAAe,GAAG;EACvB;EACA;EACA;EACA;EACAC,MAAM,EAAE;AACT,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,eAAe,GAAG;EACvBC,WAAW,EAAE;AACd,CAAC;;AAED;AACA;;AAEA;AACA;AACA;AACA,MAAMC,WAAW,GAAG,CACnBT,oBAAoB,EACpBF,2BAA2B,EAC3BC,gBAAgB,EAChBF,kBAAkB,CAClB;;AAED;AACA;AACA;AACA;AACA;AACA,SAASa,kBAAkBA,CAAEC,UAAU,EAAG;EACzCF,WAAW,CAACG,OAAO,CAAED,UAAW,CAAC;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAME,WAAW,GAAKC,QAAQ,IAAM;EACnC,IAAKA,QAAQ,CAACC,MAAM,IAAI,GAAG,IAAID,QAAQ,CAACC,MAAM,GAAG,GAAG,EAAG;IACtD,OAAOD,QAAQ;EACh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+C,QAAQ,CAAC3C,qBAAqB,GAAGA,qBAAqB;AACtD2C,QAAQ,CAAC1C,4BAA4B,GAAGA,4BAA4B;AAEpE,eAAe0C,QAAQ","ignoreList":[]}
|
|
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","defaultFetchHandler","nextOptions","url","path","data","parse","remainingOptions","body","headers","JSON","stringify","responsePromise","globalThis","fetch","window","location","href","then","response","ok","err","name","navigator","onLine","code","message","fetchHandler","setFetchHandler","newFetchHandler","apiFetch","options","enhancedHandler","reduceRight","next","workingOptions","catch","error","Promise","reject","nonceEndpoint","text","nonceMiddleware","nonce","use"],"sources":["@wordpress/api-fetch/src/index.ts"],"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';\nimport type {\n\tAPIFetchMiddleware,\n\tAPIFetchOptions,\n\tFetchHandler,\n} from './types';\n\n/**\n * Default set of header values which should be sent with every request unless\n * explicitly provided through apiFetch options.\n */\nconst DEFAULT_HEADERS: APIFetchOptions[ '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 */\nconst DEFAULT_OPTIONS: APIFetchOptions = {\n\tcredentials: 'include',\n};\n\nconst middlewares: Array< APIFetchMiddleware > = [\n\tuserLocaleMiddleware,\n\tnamespaceEndpointMiddleware,\n\thttpV1Middleware,\n\tfetchAllMiddleware,\n];\n\n/**\n * Register a middleware\n *\n * @param middleware\n */\nfunction registerMiddleware( middleware: APIFetchMiddleware ) {\n\tmiddlewares.unshift( middleware );\n}\n\nconst defaultFetchHandler: FetchHandler = ( 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 = globalThis.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( response ) => {\n\t\t\t// If the response is not 2xx, still parse the response body as JSON\n\t\t\t// but throw the JSON as error.\n\t\t\tif ( ! response.ok ) {\n\t\t\t\treturn parseAndThrowError( response, parse );\n\t\t\t}\n\n\t\t\treturn parseResponseAndNormalizeError( response, parse );\n\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// If the browser reports being offline, we'll just assume that\n\t\t\t// this is why the request failed.\n\t\t\tif ( ! globalThis.navigator.onLine ) {\n\t\t\t\tthrow {\n\t\t\t\t\tcode: 'offline_error',\n\t\t\t\t\tmessage: __(\n\t\t\t\t\t\t'Unable to connect. Please check your Internet connection.'\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Hard to diagnose further due to how Window.fetch reports errors.\n\t\t\tthrow {\n\t\t\t\tcode: 'fetch_error',\n\t\t\t\tmessage: __(\n\t\t\t\t\t'Could not get a valid response from the server.'\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t);\n};\n\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 newFetchHandler The new fetch handler\n */\nfunction setFetchHandler( newFetchHandler: FetchHandler ) {\n\tfetchHandler = newFetchHandler;\n}\n\ninterface apiFetch {\n\t< T, Parse extends boolean = true >(\n\t\toptions: APIFetchOptions< Parse >\n\t): Promise< Parse extends true ? T : Response >;\n\tnonceEndpoint?: string;\n\tnonceMiddleware?: ReturnType< typeof createNonceMiddleware >;\n\tuse: ( middleware: APIFetchMiddleware ) => void;\n\tsetFetchHandler: ( newFetchHandler: FetchHandler ) => void;\n\tcreateNonceMiddleware: typeof createNonceMiddleware;\n\tcreatePreloadingMiddleware: typeof createPreloadingMiddleware;\n\tcreateRootURLMiddleware: typeof createRootURLMiddleware;\n\tfetchAllMiddleware: typeof fetchAllMiddleware;\n\tmediaUploadMiddleware: typeof mediaUploadMiddleware;\n\tcreateThemePreviewMiddleware: typeof createThemePreviewMiddleware;\n}\n\n/**\n * Fetch\n *\n * @param options The options for the fetch.\n * @return A promise representing the request processed via the registered middlewares.\n */\nconst apiFetch: 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< FetchHandler >(\n\t\t( 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 globalThis\n\t\t\t.fetch( apiFetch.nonceEndpoint! )\n\t\t\t.then( ( response ) => {\n\t\t\t\t// If the nonce refresh fails, it means we failed to recover from the original\n\t\t\t\t// `rest_cookie_invalid_nonce` error and that it's time to finally re-throw it.\n\t\t\t\tif ( ! response.ok ) {\n\t\t\t\t\treturn Promise.reject( error );\n\t\t\t\t}\n\n\t\t\t\treturn response.text();\n\t\t\t} )\n\t\t\t.then( ( text ) => {\n\t\t\t\tapiFetch.nonceMiddleware!.nonce = text;\n\t\t\t\treturn apiFetch( options );\n\t\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;\nexport * from './types';\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,0BAA0B;AACjE,OAAOC,kBAAkB,MAAM,oCAAoC;AACnE,OAAOC,2BAA2B,MAAM,kCAAkC;AAC1E,OAAOC,gBAAgB,MAAM,uBAAu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e,CAAC,CAChCtB,IAAI,CAAIC,QAAQ,IAAM;MACtB;MACA;MACA,IAAK,CAAEA,QAAQ,CAACC,EAAE,EAAG;QACpB,OAAOkB,OAAO,CAACC,MAAM,CAAEF,KAAM,CAAC;MAC/B;MAEA,OAAOlB,QAAQ,CAACsB,IAAI,CAAC,CAAC;IACvB,CAAE,CAAC,CACFvB,IAAI,CAAIuB,IAAI,IAAM;MAClBX,QAAQ,CAACY,eAAe,CAAEC,KAAK,GAAGF,IAAI;MACtC,OAAOX,QAAQ,CAAEC,OAAQ,CAAC;IAC3B,CAAE,CAAC;EACL,CAAE,CAAC;AACJ,CAAC;AAEDD,QAAQ,CAACc,GAAG,GAAG9C,kBAAkB;AACjCgC,QAAQ,CAACF,eAAe,GAAGA,eAAe;AAE1CE,QAAQ,CAAChD,qBAAqB,GAAGA,qBAAqB;AACtDgD,QAAQ,CAAC9C,0BAA0B,GAAGA,0BAA0B;AAChE8C,QAAQ,CAAC/C,uBAAuB,GAAGA,uBAAuB;AAC1D+C,QAAQ,CAAC7C,kBAAkB,GAAGA,kBAAkB;AAChD6C,QAAQ,CAACzC,qBAAqB,GAAGA,qBAAqB;AACtDyC,QAAQ,CAACxC,4BAA4B,GAAGA,4BAA4B;AAEpE,eAAewC,QAAQ;AACvB,cAAc,SAAS","ignoreList":[]}
|
|
@@ -7,13 +7,12 @@ import { addQueryArgs } from '@wordpress/url';
|
|
|
7
7
|
* Internal dependencies
|
|
8
8
|
*/
|
|
9
9
|
import apiFetch from '..';
|
|
10
|
-
|
|
11
10
|
/**
|
|
12
11
|
* Apply query arguments to both URL and Path, whichever is present.
|
|
13
12
|
*
|
|
14
|
-
* @param {
|
|
15
|
-
* @param {Record<string, string | number>}
|
|
16
|
-
* @return
|
|
13
|
+
* @param {APIFetchOptions} props The request options
|
|
14
|
+
* @param {Record< string, string | number >} queryArgs
|
|
15
|
+
* @return The request with the modified query args
|
|
17
16
|
*/
|
|
18
17
|
const modifyQuery = ({
|
|
19
18
|
path,
|
|
@@ -28,14 +27,14 @@ const modifyQuery = ({
|
|
|
28
27
|
/**
|
|
29
28
|
* Duplicates parsing functionality from apiFetch.
|
|
30
29
|
*
|
|
31
|
-
* @param
|
|
32
|
-
* @return
|
|
30
|
+
* @param response
|
|
31
|
+
* @return Parsed response json.
|
|
33
32
|
*/
|
|
34
33
|
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
|
|
35
34
|
|
|
36
35
|
/**
|
|
37
|
-
* @param
|
|
38
|
-
* @return
|
|
36
|
+
* @param linkHeader
|
|
37
|
+
* @return The parsed link header.
|
|
39
38
|
*/
|
|
40
39
|
const parseLinkHeader = linkHeader => {
|
|
41
40
|
if (!linkHeader) {
|
|
@@ -48,8 +47,8 @@ const parseLinkHeader = linkHeader => {
|
|
|
48
47
|
};
|
|
49
48
|
|
|
50
49
|
/**
|
|
51
|
-
* @param
|
|
52
|
-
* @return
|
|
50
|
+
* @param response
|
|
51
|
+
* @return The next page URL.
|
|
53
52
|
*/
|
|
54
53
|
const getNextPageUrl = response => {
|
|
55
54
|
const {
|
|
@@ -59,8 +58,8 @@ const getNextPageUrl = response => {
|
|
|
59
58
|
};
|
|
60
59
|
|
|
61
60
|
/**
|
|
62
|
-
* @param
|
|
63
|
-
* @return
|
|
61
|
+
* @param options
|
|
62
|
+
* @return True if the request contains an unbounded query.
|
|
64
63
|
*/
|
|
65
64
|
const requestContainsUnboundedQuery = options => {
|
|
66
65
|
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
|
|
@@ -72,8 +71,8 @@ const requestContainsUnboundedQuery = options => {
|
|
|
72
71
|
* The REST API enforces an upper limit on the per_page option. To handle large
|
|
73
72
|
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
|
|
74
73
|
* then recursively assemble a full response array from all available pages.
|
|
75
|
-
*
|
|
76
|
-
* @
|
|
74
|
+
* @param options
|
|
75
|
+
* @param next
|
|
77
76
|
*/
|
|
78
77
|
const fetchAllMiddleware = async (options, next) => {
|
|
79
78
|
if (options.parse === false) {
|
|
@@ -105,7 +104,7 @@ const fetchAllMiddleware = async (options, next) => {
|
|
|
105
104
|
}
|
|
106
105
|
|
|
107
106
|
// Iteratively fetch all remaining pages until no "next" header is found.
|
|
108
|
-
let mergedResults =
|
|
107
|
+
let mergedResults = [].concat(results);
|
|
109
108
|
while (nextPage) {
|
|
110
109
|
const nextResponse = await apiFetch({
|
|
111
110
|
...options,
|
|
@@ -1 +1 @@
|
|
|
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.
|
|
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.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport apiFetch from '..';\nimport type { APIFetchMiddleware, APIFetchOptions } from '../types';\n\n/**\n * Apply query arguments to both URL and Path, whichever is present.\n *\n * @param {APIFetchOptions} props The request options\n * @param {Record< string, string | number >} queryArgs\n * @return The request with the modified query args\n */\nconst modifyQuery = (\n\t{ path, url, ...options }: APIFetchOptions,\n\tqueryArgs: Record< string, string | number >\n): APIFetchOptions => ( {\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\n * @return Parsed response json.\n */\nconst parseResponse = ( response: Response ) =>\n\tresponse.json ? response.json() : Promise.reject( response );\n\n/**\n * @param linkHeader\n * @return The parsed link header.\n */\nconst parseLinkHeader = ( linkHeader: string | null ) => {\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\n * @return The next page URL.\n */\nconst getNextPageUrl = ( response: Response ) => {\n\tconst { next } = parseLinkHeader( response.headers.get( 'link' ) );\n\treturn next;\n};\n\n/**\n * @param options\n * @return True if the request contains an unbounded query.\n */\nconst requestContainsUnboundedQuery = ( options: APIFetchOptions ) => {\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 * @param options\n * @param next\n */\nconst fetchAllMiddleware: APIFetchMiddleware = 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 = ( [] as Array< 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;AAGzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,WAAW,GAAGA,CACnB;EAAEC,IAAI;EAAEC,GAAG;EAAE,GAAGC;AAAyB,CAAC,EAC1CC,SAA4C,MACrB;EACvB,GAAGD,OAAO;EACVD,GAAG,EAAEA,GAAG,IAAIJ,YAAY,CAAEI,GAAG,EAAEE,SAAU,CAAC;EAC1CH,IAAI,EAAEA,IAAI,IAAIH,YAAY,CAAEG,IAAI,EAAEG,SAAU;AAC7C,CAAC,CAAE;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,aAAa,GAAKC,QAAkB,IACzCA,QAAQ,CAACC,IAAI,GAAGD,QAAQ,CAACC,IAAI,CAAC,CAAC,GAAGC,OAAO,CAACC,MAAM,CAAEH,QAAS,CAAC;;AAE7D;AACA;AACA;AACA;AACA,MAAMI,eAAe,GAAKC,UAAyB,IAAM;EACxD,IAAK,CAAEA,UAAU,EAAG;IACnB,OA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