@webority/mobile-core 0.156.0 → 0.158.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/README.md +1 -1
- package/lib/commonjs/api/contractCaller.js +1 -1
- package/lib/commonjs/api/publicClient.js +1 -1
- package/lib/commonjs/api/userClient.js +1 -1
- package/lib/commonjs/errors/extractApiError.js +1 -1
- package/lib/commonjs/query/apiBaseQuery.js +1 -1
- package/lib/commonjs/query/dataState.js +1 -1
- package/lib/commonjs/query/entityVersion.js +1 -1
- package/lib/module/api/contractCaller.js +1 -1
- package/lib/module/api/publicClient.js +1 -1
- package/lib/module/api/userClient.js +1 -1
- package/lib/module/errors/extractApiError.js +1 -1
- package/lib/module/query/apiBaseQuery.js +1 -1
- package/lib/module/query/dataState.js +1 -1
- package/lib/module/query/entityVersion.js +1 -1
- package/lib/typescript/commonjs/api/contractCaller.d.ts +7 -3
- package/lib/typescript/commonjs/errors/extractApiError.d.ts +6 -0
- package/lib/typescript/commonjs/pickers/index.d.ts +7 -2
- package/lib/typescript/commonjs/query/apiBaseQuery.d.ts +5 -0
- package/lib/typescript/commonjs/query/dataState.d.ts +6 -2
- package/lib/typescript/commonjs/query/entityVersion.d.ts +1 -1
- package/lib/typescript/commonjs/redux/errorToastMiddleware.d.ts +6 -4
- package/lib/typescript/commonjs/types/axios.d.ts +2 -0
- package/lib/typescript/module/api/contractCaller.d.ts +7 -3
- package/lib/typescript/module/errors/extractApiError.d.ts +6 -0
- package/lib/typescript/module/pickers/index.d.ts +7 -2
- package/lib/typescript/module/query/apiBaseQuery.d.ts +5 -0
- package/lib/typescript/module/query/dataState.d.ts +6 -2
- package/lib/typescript/module/query/entityVersion.d.ts +1 -1
- package/lib/typescript/module/redux/errorToastMiddleware.d.ts +6 -4
- package/lib/typescript/module/types/axios.d.ts +2 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -217,7 +217,7 @@ if (!result.saved) {
|
|
|
217
217
|
|
|
218
218
|
The message to show is `result.error.message` (the server's text), shown through the shared error path. The endpoint maps `version` to `ifMatch`.
|
|
219
219
|
|
|
220
|
-
A stale save re-reads the record once and saves again only when the server's copy of the form fields is unchanged; a second stale answer is returned. The retry is safe only when the save writes just the fields `toForm` covers, so a field a background job changed is never overwritten.
|
|
220
|
+
A stale save re-reads the record once and saves again only when the server's copy of the form fields is unchanged; a second stale answer is returned. The retry is safe only when the save writes just the fields `toForm` covers, so a field a background job changed is never overwritten. `save` may reject with an `ApiError` or with the raw axios error a service call throws: both re-read on a 412, and any other failure is rethrown as it came.
|
|
221
221
|
|
|
222
222
|
An axios service built outside RTK Query uses the same two rules: `withIfMatch(version, cfg)` returns `cfg` with the quoted `If-Match` header the base query sends, and `entityTagOf(response)` returns the strong ETag of a read (undefined for a weak or missing one), ready for `versionOf`.
|
|
223
223
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createContractCaller=void 0;var _call=require("@webority/api-contract/call");const createContractCaller=(e,t)=>async(r,a,o)=>{const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createContractCaller=void 0;var _call=require("@webority/api-contract/call");const createContractCaller=(e,t)=>async(r,a,o)=>{const s=(0,_call.buildContractRequest)(t[r],a,o),c=await e.request({method:s.method,url:s.url,...void 0===s.headers?{}:{headers:s.headers},data:s.data,responseType:s.responseType,...void 0===s.skipErrorLog?{}:{skipErrorLog:s.skipErrorLog},...void 0===s.expectedStatuses?{}:{expectedStatuses:s.expectedStatuses},...void 0===o?.signal?{}:{signal:o.signal},...void 0===o?.timeout?{}:{timeout:o.timeout},...void 0===o?.retry?{}:{retry:o.retry}});return(0,_call.contractReply)(t[r],c.status,c.data)};exports.createContractCaller=createContractCaller;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _axios=_interopRequireDefault(require("axios")),_index=require("../config/index.js"),_index2=require("../logger/index.js");require("../types/axios.js");var _baseUrl=require("./baseUrl.js"),_clientHeaders=require("./clientHeaders.js"),_curl=require("./curl.js"),_minAppVersion=require("./minAppVersion.js"),_multipart=require("./multipart.js"),_requestDefaults=require("./requestDefaults.js"),_responseBodyText=require("./responseBodyText.js"),_retry=require("./retry.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const publicClient=_axios.default.create({headers:{"Content-Type":"application/json",Accept:"application/json"}});(0,_baseUrl.applyConfiguredBaseUrl)(publicClient),(0,_requestDefaults.applyRequestDefaults)(publicClient),(0,_multipart.sendFormDataAsMultipart)(publicClient),(0,_minAppVersion.readMinAppVersion)(publicClient),(0,_retry.attachRetry)(publicClient),publicClient.interceptors.request.use(e=>(_index2.Logger.info(`Request: ${e.method?.toUpperCase()} ${e.url}`),(0,_index.getConfigValue)("logCurl")&&(0,_curl.logCurl)(e),e),e=>{const r=e instanceof Error?e.message:String(e);return _index2.Logger.error("Request error:",r),Promise.reject(e)}),(0,_clientHeaders.applyClientHeaders)(publicClient),publicClient.interceptors.response.use(e=>(_index2.Logger.info(`Response: ${e.status} from ${e.config.url}`),e),e=>{if(_axios.default.isCancel(e))return Promise.reject(e);if(_axios.default.isAxiosError(e)){const r=e.config;if(r?.skipErrorLog)return Promise.reject(e);e.response
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _axios=_interopRequireDefault(require("axios")),_index=require("../config/index.js"),_index2=require("../logger/index.js");require("../types/axios.js");var _baseUrl=require("./baseUrl.js"),_clientHeaders=require("./clientHeaders.js"),_curl=require("./curl.js"),_minAppVersion=require("./minAppVersion.js"),_multipart=require("./multipart.js"),_requestDefaults=require("./requestDefaults.js"),_responseBodyText=require("./responseBodyText.js"),_retry=require("./retry.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const publicClient=_axios.default.create({headers:{"Content-Type":"application/json",Accept:"application/json"}});(0,_baseUrl.applyConfiguredBaseUrl)(publicClient),(0,_requestDefaults.applyRequestDefaults)(publicClient),(0,_multipart.sendFormDataAsMultipart)(publicClient),(0,_minAppVersion.readMinAppVersion)(publicClient),(0,_retry.attachRetry)(publicClient),publicClient.interceptors.request.use(e=>(_index2.Logger.info(`Request: ${e.method?.toUpperCase()} ${e.url}`),(0,_index.getConfigValue)("logCurl")&&(0,_curl.logCurl)(e),e),e=>{const r=e instanceof Error?e.message:String(e);return _index2.Logger.error("Request error:",r),Promise.reject(e)}),(0,_clientHeaders.applyClientHeaders)(publicClient),publicClient.interceptors.response.use(e=>(_index2.Logger.info(`Response: ${e.status} from ${e.config.url}`),e),e=>{if(_axios.default.isCancel(e))return Promise.reject(e);if(_axios.default.isAxiosError(e)){const r=e.config;if(r?.skipErrorLog)return Promise.reject(e);if(e.response){const s=`Response error: ${(0,_responseBodyText.responseBodyText)(e.response.data,e.message)}, URL: ${r?.url}, Status: ${e.response.status}`;r?.expectedStatuses?.includes(e.response.status)?_index2.Logger.debug(s):_index2.Logger.error(s)}else _index2.Logger.info(`Network error or no response from server: ${e.message}, URL: ${r?.url}`)}else{const r=e instanceof Error?e.message:String(e);_index2.Logger.error(`Unknown response error: ${r}`)}return Promise.reject(e)});var _default=exports.default=publicClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestOfflineError=void 0,Object.defineProperty(exports,"SESSION_EXPIRED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_EXPIRED_CODE}}),Object.defineProperty(exports,"SESSION_REVOKED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_REVOKED_CODE}}),exports.default=void 0,Object.defineProperty(exports,"injectStore",{enumerable:!0,get:function(){return _tokenRefresh.injectStore}}),Object.defineProperty(exports,"injectUserAuth",{enumerable:!0,get:function(){return _tokenRefresh.injectUserAuth}}),Object.defineProperty(exports,"resetRefreshState",{enumerable:!0,get:function(){return _tokenRefresh.resetRefreshState}});var _axios=_interopRequireWildcard(require("axios")),_authStore=require("../auth/authStore.js"),_index=require("../config/index.js"),_index2=require("../logger/index.js"),_networkStatus=require("../network/networkStatus.js");require("../types/axios.js");var cache,_guards=require("../utils/guards.js"),_baseUrl=require("./baseUrl.js"),_clientHeaders=require("./clientHeaders.js"),_curl=require("./curl.js"),_minAppVersion=require("./minAppVersion.js"),_multipart=require("./multipart.js"),_requestDefaults=require("./requestDefaults.js"),_responseBodyText=require("./responseBodyText.js"),_retry=require("./retry.js"),_tokenRefresh=require("./tokenRefresh.js"),_workspace=require("./workspace.js");function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;var t,s,n=Object.defineProperty,o={__proto__:null,default:e};if(Object(e)!==e)return o;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,o)}for(s in e)"default"!==s&&{}.hasOwnProperty.call(e,s)&&((t=n&&Object.getOwnPropertyDescriptor(e,s))&&(t.get||t.set)?n(o,s,t):o[s]=e[s]);return o}class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}exports.RequestOfflineError=RequestOfflineError;class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[e.transformRequest??[]].flat();e.transformRequest=[function guarded(e,t){try{return r.reduce((e,r)=>r.call(this,e,t),e)}catch(e){throw endReplacement(this),e}}]};let openReplacementSteps=0,replacementStepsSettled=Promise.resolve(),settleReplacementSteps=null;const openReplacementStep=()=>{0===openReplacementSteps&&(replacementStepsSettled=new Promise(e=>{settleReplacementSteps=e})),openReplacementSteps+=1;let e=!1;return()=>{e||(e=!0,openReplacementSteps-=1,0===openReplacementSteps&&(settleReplacementSteps?.(),settleReplacementSteps=null))}},waitForReplacementStep=async()=>{for(;openReplacementSteps>0;)await replacementStepsSettled},readSentToken=e=>{const r=e.headers instanceof _axios.AxiosHeaders?e.headers.get("Authorization"):void 0;return"string"==typeof r&&r.startsWith("Bearer ")?r.slice(7):null},userClient=_axios.default.create({headers:{"Content-Type":"application/json"}});(0,_minAppVersion.readMinAppVersion)(userClient),(0,_retry.attachRetry)(userClient);const parseRawHeaders=e=>{const r={};if(void 0===e)return r;if(!(0,_guards.isRecord)(e))throw new Error("Request headers must be AxiosHeaders or a plain object.");for(const[t,s]of Object.entries(e)){if(void 0===s)continue;if(!(null===s||"string"==typeof s||"number"==typeof s||"boolean"==typeof s||Array.isArray(s)))throw new Error(`The request header "${t}" has a value no header can carry.`);r[t]=s}return r},setAuthHeader=(e,r)=>{e.headers instanceof _axios.AxiosHeaders?e.headers.set("Authorization",`Bearer ${r}`):e.headers=_axios.AxiosHeaders.from({...parseRawHeaders(e.headers),Authorization:`Bearer ${r}`})},isRefreshTokenRequest=e=>{const r=(0,_tokenRefresh.getRefreshPath)();return!!r&&!!e?.includes(r)};userClient.interceptors.request.use(e=>(e.replacesSession&&!isRefreshTokenRequest(e.url)&&(e._endReplacement=(0,_tokenRefresh.beginSessionReplacement)(),closeWindowIfTransformThrows(e)),e)),(0,_baseUrl.applyConfiguredBaseUrl)(userClient),(0,_requestDefaults.applyRequestDefaults)(userClient),(0,_multipart.sendFormDataAsMultipart)(userClient),userClient.interceptors.request.use(e=>((0,_index.getConfigValue)("logCurl")&&(0,_curl.logCurl)(e),e)),(0,_clientHeaders.applyClientHeaders)(userClient),userClient.interceptors.request.use(async e=>{endReplacement(e);if(!1===(await(0,_networkStatus.getLastKnownNetworkStatus)()).isConnected)return _index2.Logger.info(`Request blocked: device is offline. URL: ${e.url}`),Promise.reject(new RequestOfflineError);try{if(isRefreshTokenRequest(e.url))return e;await(0,_clientHeaders.stampAccountId)(e,(0,_tokenRefresh.getAccountIdProvider)());const r=await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY);if(!r?.token)throw new NoAccessTokenError;await waitForReplacementStep();const t=Date.now(),s=Date.parse(r.expiry);if(s<=t+3e4){_index2.Logger.info("Access token expired or about to expire, refreshing before request");const r=await(0,_tokenRefresh.refreshAccessToken)();setAuthHeader(e,r)}else setAuthHeader(e,r.token);return e}catch(r){return r instanceof NoAccessTokenError?_index2.Logger.info(`Request not sent: signed out. URL: ${e.url}`):(0,_tokenRefresh.isSessionEnd)(r)||_index2.Logger.error("Failed to attach token:",(0,_tokenRefresh.getErrorMessage)(r)),Promise.reject(r)}},e=>(_index2.Logger.error("Request error:",(0,_tokenRefresh.getErrorMessage)(e)),Promise.reject(e))),userClient.interceptors.response.use(async e=>{const r=e.config;if(r._endReplacement){const t=openReplacementStep();try{await(0,_tokenRefresh.storeReplacementSession)(e.data),await(r.onSessionReplaced?.(e.data))}finally{t(),endReplacement(r)}}return e},async e=>{if(endReplacement(_axios.default.isAxiosError(e)?e.config:void 0),_axios.default.isCancel(e))return Promise.reject(e);if(e instanceof RequestOfflineError||e instanceof NoAccessTokenError||e instanceof _tokenRefresh.SessionEndedError)return Promise.reject(e);if(!_axios.default.isAxiosError(e))return _index2.Logger.error(`Non-axios error in response interceptor: ${(0,_tokenRefresh.getErrorMessage)(e)}`),Promise.reject(e);const r=e,t=r.config;if(!r.response)return t?.skipErrorLog||_index2.Logger.info(`Network error or no response from server: ${r.message}, URL: ${t?.url}`),Promise.reject(e);if((0,_workspace.isWorkspaceChangedResponse)(r))return _index2.Logger.info(`Refused for another workspace. URL: ${t?.url}`),Promise.reject(new _workspace.WorkspaceChangedError("Refused for another workspace",{response:r.response,config:t,cause:e}));if(isRefreshTokenRequest(t?.url))return Promise.reject(e);if(401===r.response.status&&t&&!t._replayedWithCurrentToken&&!t.replacesSession&&(await(0,_tokenRefresh.waitForSessionReplacement)(),await(0,_tokenRefresh.currentTokenIfReplaced)(readSentToken(t)))){const r=await(0,_clientHeaders.readAccountId)((0,_tokenRefresh.getAccountIdProvider)());return(t._accountId??null)!==r?(_index2.Logger.info(`Workspace changed in flight; not sent again. URL: ${t.url}`),Promise.reject(new _workspace.WorkspaceChangedError("Workspace changed in flight",{config:t,cause:e}))):(_index2.Logger.info(`Session changed while the request was in flight; sending it again. URL: ${t.url}`),t._replayedWithCurrentToken=!0,userClient(t))}if(401===r.response.status&&t&&!t._retry){const s=(0,_tokenRefresh.sessionCodeOf)(r.response.data);if(null!==s)return _index2.Logger.warn(`Session ${s}, logging out without refresh. URL: ${t.url}`),(0,_tokenRefresh.resetRefreshState)(),await(0,_tokenRefresh.endSessionAndLogout)("terminated",s,(0,_tokenRefresh.sessionDetailOf)(r.response.data)),Promise.reject(e);if(_index2.Logger.warn(`Unauthorized URL: ${t.url}`),t._retry=!0,(0,_tokenRefresh.isRefreshInFlight)())return(0,_tokenRefresh.queueBehindRefresh)().then(e=>(_index2.Logger.info("Retrying request after token refresh:",t.url),setAuthHeader(t,e),userClient(t))).catch(e=>((0,_tokenRefresh.isSessionEnd)(e)||_index2.Logger.error("Failed to retry request after token refresh:",(0,_tokenRefresh.getErrorMessage)(e)),Promise.reject(e)));try{const e=await(0,_tokenRefresh.refreshAccessToken)();return setAuthHeader(t,e),userClient(t)}catch(e){return Promise.reject(e)}}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestOfflineError=void 0,Object.defineProperty(exports,"SESSION_EXPIRED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_EXPIRED_CODE}}),Object.defineProperty(exports,"SESSION_REVOKED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_REVOKED_CODE}}),exports.default=void 0,Object.defineProperty(exports,"injectStore",{enumerable:!0,get:function(){return _tokenRefresh.injectStore}}),Object.defineProperty(exports,"injectUserAuth",{enumerable:!0,get:function(){return _tokenRefresh.injectUserAuth}}),Object.defineProperty(exports,"resetRefreshState",{enumerable:!0,get:function(){return _tokenRefresh.resetRefreshState}});var _axios=_interopRequireWildcard(require("axios")),_authStore=require("../auth/authStore.js"),_index=require("../config/index.js"),_index2=require("../logger/index.js"),_networkStatus=require("../network/networkStatus.js");require("../types/axios.js");var cache,_guards=require("../utils/guards.js"),_baseUrl=require("./baseUrl.js"),_clientHeaders=require("./clientHeaders.js"),_curl=require("./curl.js"),_minAppVersion=require("./minAppVersion.js"),_multipart=require("./multipart.js"),_requestDefaults=require("./requestDefaults.js"),_responseBodyText=require("./responseBodyText.js"),_retry=require("./retry.js"),_tokenRefresh=require("./tokenRefresh.js"),_workspace=require("./workspace.js");function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;var t,s,n=Object.defineProperty,o={__proto__:null,default:e};if(Object(e)!==e)return o;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,o)}for(s in e)"default"!==s&&{}.hasOwnProperty.call(e,s)&&((t=n&&Object.getOwnPropertyDescriptor(e,s))&&(t.get||t.set)?n(o,s,t):o[s]=e[s]);return o}class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}exports.RequestOfflineError=RequestOfflineError;class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[e.transformRequest??[]].flat();e.transformRequest=[function guarded(e,t){try{return r.reduce((e,r)=>r.call(this,e,t),e)}catch(e){throw endReplacement(this),e}}]};let openReplacementSteps=0,replacementStepsSettled=Promise.resolve(),settleReplacementSteps=null;const openReplacementStep=()=>{0===openReplacementSteps&&(replacementStepsSettled=new Promise(e=>{settleReplacementSteps=e})),openReplacementSteps+=1;let e=!1;return()=>{e||(e=!0,openReplacementSteps-=1,0===openReplacementSteps&&(settleReplacementSteps?.(),settleReplacementSteps=null))}},waitForReplacementStep=async()=>{for(;openReplacementSteps>0;)await replacementStepsSettled},readSentToken=e=>{const r=e.headers instanceof _axios.AxiosHeaders?e.headers.get("Authorization"):void 0;return"string"==typeof r&&r.startsWith("Bearer ")?r.slice(7):null},userClient=_axios.default.create({headers:{"Content-Type":"application/json"}});(0,_minAppVersion.readMinAppVersion)(userClient),(0,_retry.attachRetry)(userClient);const parseRawHeaders=e=>{const r={};if(void 0===e)return r;if(!(0,_guards.isRecord)(e))throw new Error("Request headers must be AxiosHeaders or a plain object.");for(const[t,s]of Object.entries(e)){if(void 0===s)continue;if(!(null===s||"string"==typeof s||"number"==typeof s||"boolean"==typeof s||Array.isArray(s)))throw new Error(`The request header "${t}" has a value no header can carry.`);r[t]=s}return r},setAuthHeader=(e,r)=>{e.headers instanceof _axios.AxiosHeaders?e.headers.set("Authorization",`Bearer ${r}`):e.headers=_axios.AxiosHeaders.from({...parseRawHeaders(e.headers),Authorization:`Bearer ${r}`})},isRefreshTokenRequest=e=>{const r=(0,_tokenRefresh.getRefreshPath)();return!!r&&!!e?.includes(r)};userClient.interceptors.request.use(e=>(e.replacesSession&&!isRefreshTokenRequest(e.url)&&(e._endReplacement=(0,_tokenRefresh.beginSessionReplacement)(),closeWindowIfTransformThrows(e)),e)),(0,_baseUrl.applyConfiguredBaseUrl)(userClient),(0,_requestDefaults.applyRequestDefaults)(userClient),(0,_multipart.sendFormDataAsMultipart)(userClient),userClient.interceptors.request.use(e=>((0,_index.getConfigValue)("logCurl")&&(0,_curl.logCurl)(e),e)),(0,_clientHeaders.applyClientHeaders)(userClient),userClient.interceptors.request.use(async e=>{endReplacement(e);if(!1===(await(0,_networkStatus.getLastKnownNetworkStatus)()).isConnected)return _index2.Logger.info(`Request blocked: device is offline. URL: ${e.url}`),Promise.reject(new RequestOfflineError);try{if(isRefreshTokenRequest(e.url))return e;await(0,_clientHeaders.stampAccountId)(e,(0,_tokenRefresh.getAccountIdProvider)());const r=await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY);if(!r?.token)throw new NoAccessTokenError;await waitForReplacementStep();const t=Date.now(),s=Date.parse(r.expiry);if(s<=t+3e4){_index2.Logger.info("Access token expired or about to expire, refreshing before request");const r=await(0,_tokenRefresh.refreshAccessToken)();setAuthHeader(e,r)}else setAuthHeader(e,r.token);return e}catch(r){return r instanceof NoAccessTokenError?_index2.Logger.info(`Request not sent: signed out. URL: ${e.url}`):(0,_tokenRefresh.isSessionEnd)(r)||_index2.Logger.error("Failed to attach token:",(0,_tokenRefresh.getErrorMessage)(r)),Promise.reject(r)}},e=>(_index2.Logger.error("Request error:",(0,_tokenRefresh.getErrorMessage)(e)),Promise.reject(e))),userClient.interceptors.response.use(async e=>{const r=e.config;if(r._endReplacement){const t=openReplacementStep();try{await(0,_tokenRefresh.storeReplacementSession)(e.data),await(r.onSessionReplaced?.(e.data))}finally{t(),endReplacement(r)}}return e},async e=>{if(endReplacement(_axios.default.isAxiosError(e)?e.config:void 0),_axios.default.isCancel(e))return Promise.reject(e);if(e instanceof RequestOfflineError||e instanceof NoAccessTokenError||e instanceof _tokenRefresh.SessionEndedError)return Promise.reject(e);if(!_axios.default.isAxiosError(e))return _index2.Logger.error(`Non-axios error in response interceptor: ${(0,_tokenRefresh.getErrorMessage)(e)}`),Promise.reject(e);const r=e,t=r.config;if(!r.response)return t?.skipErrorLog||_index2.Logger.info(`Network error or no response from server: ${r.message}, URL: ${t?.url}`),Promise.reject(e);if((0,_workspace.isWorkspaceChangedResponse)(r))return _index2.Logger.info(`Refused for another workspace. URL: ${t?.url}`),Promise.reject(new _workspace.WorkspaceChangedError("Refused for another workspace",{response:r.response,config:t,cause:e}));if(isRefreshTokenRequest(t?.url))return Promise.reject(e);if(401===r.response.status&&t&&!t._replayedWithCurrentToken&&!t.replacesSession&&(await(0,_tokenRefresh.waitForSessionReplacement)(),await(0,_tokenRefresh.currentTokenIfReplaced)(readSentToken(t)))){const r=await(0,_clientHeaders.readAccountId)((0,_tokenRefresh.getAccountIdProvider)());return(t._accountId??null)!==r?(_index2.Logger.info(`Workspace changed in flight; not sent again. URL: ${t.url}`),Promise.reject(new _workspace.WorkspaceChangedError("Workspace changed in flight",{config:t,cause:e}))):(_index2.Logger.info(`Session changed while the request was in flight; sending it again. URL: ${t.url}`),t._replayedWithCurrentToken=!0,userClient(t))}if(401===r.response.status&&t&&!t._retry){const s=(0,_tokenRefresh.sessionCodeOf)(r.response.data);if(null!==s)return _index2.Logger.warn(`Session ${s}, logging out without refresh. URL: ${t.url}`),(0,_tokenRefresh.resetRefreshState)(),await(0,_tokenRefresh.endSessionAndLogout)("terminated",s,(0,_tokenRefresh.sessionDetailOf)(r.response.data)),Promise.reject(e);if(_index2.Logger.warn(`Unauthorized URL: ${t.url}`),t._retry=!0,(0,_tokenRefresh.isRefreshInFlight)())return(0,_tokenRefresh.queueBehindRefresh)().then(e=>(_index2.Logger.info("Retrying request after token refresh:",t.url),setAuthHeader(t,e),userClient(t))).catch(e=>((0,_tokenRefresh.isSessionEnd)(e)||_index2.Logger.error("Failed to retry request after token refresh:",(0,_tokenRefresh.getErrorMessage)(e)),Promise.reject(e)));try{const e=await(0,_tokenRefresh.refreshAccessToken)();return setAuthHeader(t,e),userClient(t)}catch(e){return Promise.reject(e)}}if(!t?.skipErrorLog){const e=`Response error: ${(0,_responseBodyText.responseBodyText)(r.response?.data,r.message)}, URL: ${t?.url}, Status: ${r.response.status}`;t?.expectedStatuses?.includes(r.response.status)?_index2.Logger.debug(e):_index2.Logger.error(e)}return Promise.reject(e)});var _default=exports.default=userClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UNREACHABLE_MESSAGE=exports.UNEXPECTED_MESSAGE=exports.TIMEOUT_MESSAGE=exports.TIMEOUT_CODE=exports.SERVER_FAILURE_MESSAGE=exports.REQUEST_CANCELED_CODE=exports.OFFLINE_MESSAGE=exports.OFFLINE_CODE=exports.NETWORK_CODE=exports.CONTRACT_ERROR_CODE=void 0,exports.apiErrorMessage=apiErrorMessage,exports.extractApiError=extractApiError,exports.toFieldPath=exports.isNoResponse=exports.isApiError=void 0;var _requestPlatform=require("./requestPlatform.js");const SERVER_FAILURE_MESSAGE=exports.SERVER_FAILURE_MESSAGE="Something went wrong on our side. Please try again in a moment.",OFFLINE_MESSAGE=exports.OFFLINE_MESSAGE="You appear to be offline. Check your connection and try again.",UNREACHABLE_MESSAGE=exports.UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and try again.",TIMEOUT_MESSAGE=exports.TIMEOUT_MESSAGE="That took too long to respond. Check your connection and try again.",UNEXPECTED_MESSAGE=exports.UNEXPECTED_MESSAGE="Something went wrong. Please try again.",REQUEST_CANCELED_CODE=exports.REQUEST_CANCELED_CODE="request_canceled",CONTRACT_ERROR_CODE=exports.CONTRACT_ERROR_CODE="contract_error",TIMEOUT_CODE=exports.TIMEOUT_CODE="timeout",NETWORK_CODE=exports.NETWORK_CODE="network",OFFLINE_CODE=exports.OFFLINE_CODE="offline",MAX_MESSAGE_LENGTH=300,INTERNAL_ERROR_CODE="internal_error",requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const r=FLEET_DEFAULT_REFUSALS[e];if(void 0===r||null===t||t.code!==r.code)return null;const s=nonEmptyString(t.detail);return null===s||s===r.sentence?r.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),userSafe=e=>{const t=nonEmptyString(e);return null===t||looksLikeDiagnostics(t)?null:t},toFieldPath=e=>e.replace(/^\$\.?/,"").split(".").map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(".");exports.toFieldPath=toFieldPath;const firstMessage=e=>{if(Array.isArray(e)){for(const t of e){const e=nonEmptyString(t);if(null!==e)return e}return null}return nonEmptyString(e)},addError=(e,t,r)=>{const s=toFieldPath(t);""===s?e.form??=r:s in e.fields||(e.fields[s]=r)},readErrors=e=>{const t={fields:{},form:null};if(Array.isArray(e)){for(const r of e){if(!isDict(r))continue;const e=nonEmptyString(r.message);null!==e&&addError(t,"string"==typeof r.field?r.field:"",e)}return t}if(!isDict(e))return t;for(const[r,s]of Object.entries(e)){const e=firstMessage(s);null!==e&&addError(t,r,e)}return t},isApiError=e=>isDict(e)&&"string"==typeof e.message&&"number"==typeof e.status&&"boolean"==typeof e.offline&&isDict(e.fieldErrors);exports.isApiError=isApiError;const build=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const r="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,s="string"==typeof r?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(r):null;return s?.[1]??null},fromNoResponse=e=>{const t=nonEmptyString(e.code),r=nonEmptyString(e.name),s=nonEmptyString(e.message),n=requestTraceId(e);return"CanceledError"===r||"ERR_CANCELED"===t?build({code:REQUEST_CANCELED_CODE,message:UNEXPECTED_MESSAGE,traceId:n,diagnostic:s}):"ECONNABORTED"===t||"ETIMEDOUT"===t?build({code:TIMEOUT_CODE,message:TIMEOUT_MESSAGE,offline:!0,traceId:n,diagnostic:s}):"RequestOfflineError"===r||"ERR_NETWORK"===t||"Network Error"===s||"Network request failed"===s?(0,_requestPlatform.isOfflineFailure)(e)?build({code:OFFLINE_CODE,message:OFFLINE_MESSAGE,offline:!0,traceId:n,diagnostic:s}):build({code:NETWORK_CODE,message:UNREACHABLE_MESSAGE,offline:!0,traceId:n,diagnostic:s}):build({message:UNEXPECTED_MESSAGE,traceId:n,diagnostic:s})};function extractApiError(e){if(isApiError(e))return e;if("string"==typeof e)return build({message:userSafe(e)??UNEXPECTED_MESSAGE,diagnostic:e||null});if(!isDict(e))return build({message:UNEXPECTED_MESSAGE,diagnostic:null==e?null:String(e)});if(!0===e.isContractError)return build({code:CONTRACT_ERROR_CODE,message:userSafe(e.message)??UNEXPECTED_MESSAGE,diagnostic:nonEmptyString(e.message)});const t=isDict(e.response)?e.response:null,r="number"==typeof t?.status?t.status:"number"==typeof e.status?e.status:0,s=t?t.data:e.body;if(0===r&&null==s)return fromNoResponse(e);const n=isDict(s)?s:null,{fields:o,form:E}=readErrors(n?.errors),i=nonEmptyString(n?.code),a=nonEmptyString(n?.traceId)??requestTraceId(e),l=nonEmptyString(n?.detail)??nonEmptyString(n?.title)??nonEmptyString(s)??nonEmptyString(e.message);let
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UNREACHABLE_MESSAGE=exports.UNEXPECTED_MESSAGE=exports.TIMEOUT_MESSAGE=exports.TIMEOUT_CODE=exports.SERVER_FAILURE_MESSAGE=exports.REQUEST_CANCELED_CODE=exports.OFFLINE_MESSAGE=exports.OFFLINE_CODE=exports.NETWORK_CODE=exports.CONTRACT_ERROR_CODE=void 0,exports.apiErrorMessage=apiErrorMessage,exports.extractApiError=extractApiError,exports.toFieldPath=exports.isNoResponse=exports.isApiError=void 0;var _requestPlatform=require("./requestPlatform.js");const SERVER_FAILURE_MESSAGE=exports.SERVER_FAILURE_MESSAGE="Something went wrong on our side. Please try again in a moment.",OFFLINE_MESSAGE=exports.OFFLINE_MESSAGE="You appear to be offline. Check your connection and try again.",UNREACHABLE_MESSAGE=exports.UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and try again.",TIMEOUT_MESSAGE=exports.TIMEOUT_MESSAGE="That took too long to respond. Check your connection and try again.",UNEXPECTED_MESSAGE=exports.UNEXPECTED_MESSAGE="Something went wrong. Please try again.",REQUEST_CANCELED_CODE=exports.REQUEST_CANCELED_CODE="request_canceled",CONTRACT_ERROR_CODE=exports.CONTRACT_ERROR_CODE="contract_error",TIMEOUT_CODE=exports.TIMEOUT_CODE="timeout",NETWORK_CODE=exports.NETWORK_CODE="network",OFFLINE_CODE=exports.OFFLINE_CODE="offline",MAX_MESSAGE_LENGTH=300,INTERNAL_ERROR_CODE="internal_error",requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const r=FLEET_DEFAULT_REFUSALS[e];if(void 0===r||null===t||t.code!==r.code)return null;const s=nonEmptyString(t.detail);return null===s||s===r.sentence?r.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),userSafe=e=>{const t=nonEmptyString(e);return null===t||looksLikeDiagnostics(t)?null:t},toFieldPath=e=>e.replace(/^\$\.?/,"").split(".").map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(".");exports.toFieldPath=toFieldPath;const firstMessage=e=>{if(Array.isArray(e)){for(const t of e){const e=nonEmptyString(t);if(null!==e)return e}return null}return nonEmptyString(e)},addError=(e,t,r)=>{const s=toFieldPath(t);""===s?e.form??=r:s in e.fields||(e.fields[s]=r)},readErrors=e=>{const t={fields:{},form:null};if(Array.isArray(e)){for(const r of e){if(!isDict(r))continue;const e=nonEmptyString(r.message);null!==e&&addError(t,"string"==typeof r.field?r.field:"",e)}return t}if(!isDict(e))return t;for(const[r,s]of Object.entries(e)){const e=firstMessage(s);null!==e&&addError(t,r,e)}return t},isApiError=e=>isDict(e)&&"string"==typeof e.message&&"number"==typeof e.status&&"boolean"==typeof e.offline&&isDict(e.fieldErrors)&&isDict(e.extensions);exports.isApiError=isApiError;const build=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,extensions:{},...e}),STANDARD_PROBLEM_MEMBERS=new Set(["type","title","status","detail","instance","code","errors","traceId"]),problemExtensions=e=>null===e?{}:Object.fromEntries(Object.entries(e).filter(([e])=>!STANDARD_PROBLEM_MEMBERS.has(e))),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const r="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,s="string"==typeof r?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(r):null;return s?.[1]??null},fromNoResponse=e=>{const t=nonEmptyString(e.code),r=nonEmptyString(e.name),s=nonEmptyString(e.message),n=requestTraceId(e);return"CanceledError"===r||"ERR_CANCELED"===t?build({code:REQUEST_CANCELED_CODE,message:UNEXPECTED_MESSAGE,traceId:n,diagnostic:s}):"ECONNABORTED"===t||"ETIMEDOUT"===t?build({code:TIMEOUT_CODE,message:TIMEOUT_MESSAGE,offline:!0,traceId:n,diagnostic:s}):"RequestOfflineError"===r||"ERR_NETWORK"===t||"Network Error"===s||"Network request failed"===s?(0,_requestPlatform.isOfflineFailure)(e)?build({code:OFFLINE_CODE,message:OFFLINE_MESSAGE,offline:!0,traceId:n,diagnostic:s}):build({code:NETWORK_CODE,message:UNREACHABLE_MESSAGE,offline:!0,traceId:n,diagnostic:s}):build({message:UNEXPECTED_MESSAGE,traceId:n,diagnostic:s})};function extractApiError(e){if(isApiError(e))return e;if("string"==typeof e)return build({message:userSafe(e)??UNEXPECTED_MESSAGE,diagnostic:e||null});if(!isDict(e))return build({message:UNEXPECTED_MESSAGE,diagnostic:null==e?null:String(e)});if(!0===e.isContractError)return build({code:CONTRACT_ERROR_CODE,message:userSafe(e.message)??UNEXPECTED_MESSAGE,diagnostic:nonEmptyString(e.message)});const t=isDict(e.response)?e.response:null,r="number"==typeof t?.status?t.status:"number"==typeof e.status?e.status:0,s=t?t.data:e.body;if(0===r&&null==s)return fromNoResponse(e);const n=isDict(s)?s:null,{fields:o,form:E}=readErrors(n?.errors),i=nonEmptyString(n?.code),a=nonEmptyString(n?.traceId)??requestTraceId(e),l=nonEmptyString(n?.detail)??nonEmptyString(n?.title)??nonEmptyString(s)??nonEmptyString(e.message);let c;if(r>=500){c=(null!==i&&i!==INTERNAL_ERROR_CODE?userSafe(n?.detail):null)??SERVER_FAILURE_MESSAGE}else c=fleetDefaultRefusalSentence(r,n)??userSafe(Object.values(o)[0])??userSafe(E)??userSafe(n?.detail)??userSafe(n?.title)??userSafe(s)??(r?requestFailedMessage(r):UNEXPECTED_MESSAGE);const u=isDict(e.config)?e.config:null,S=null===u?null:nonEmptyString(u.url),f=null!==u&&"_accountId"in u?nonEmptyString(u._accountId):null;return build({code:i,message:c,fieldErrors:o,status:r,traceId:a,diagnostic:l,extensions:problemExtensions(n),...null===S?{}:{requestUrl:S},...null===f?{}:{accountId:f}})}const isNoResponse=e=>extractApiError(e).offline;function apiErrorMessage(e,t){const r=extractApiError(e);if(r.offline||null!==t&&!t)return r.message;if(r.status>=500&&r.message!==SERVER_FAILURE_MESSAGE)return r.message;return r.status>=500||r.code===REQUEST_CANCELED_CODE||r.message===UNEXPECTED_MESSAGE||r.message===requestFailedMessage(r.status)?t??null:r.message}exports.isNoResponse=isNoResponse;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.strongEntityTag=exports.ifMatchValue=exports.createApiBaseQuery=void 0;var _axios=_interopRequireDefault(require("axios")),_index=require("../errors/index.js"),_index2=require("../logger/index.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const encodeParam=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent("object"==typeof e?JSON.stringify(e):String(e)),strongEntityTag=e=>{if("string"==typeof e&&!e.startsWith("W/"))return/^"([^"]*)"$/.exec(e)?.[1]};exports.strongEntityTag=strongEntityTag;const ifMatchValue=e=>`"${e}"`;exports.ifMatchValue=ifMatchValue;const requestHeaders=e=>{const t={};if(e.ifMatch&&(t["If-Match"]=ifMatchValue(e.ifMatch)),e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),0===Object.keys(t).length)return e.headers;const r=Object.keys(t).map(e=>e.toLowerCase()),s=Object.entries(e.headers??{}).filter(([e])=>!r.includes(e.toLowerCase()));return{...Object.fromEntries(s),...t}},PRECONDITION_FAILED_CODE="precondition_failed",asPreconditionFailure=e=>412===e.status?{...e,code:"precondition_failed"}:e,serializeParams=e=>t=>{const r=[];for(const[s,a]of Object.entries(t)){if(null==a)continue;const t=encodeURIComponent(s);if(Array.isArray(a))if("comma"===e)r.push(`${t}=${a.map(encodeParam).join(",")}`);else{const s="brackets"===e?`${t}[]`:t;for(const e of a)r.push(`${s}=${encodeParam(e)}`)}else r.push(`${t}=${encodeParam(a)}`)}return r.join("&")},createApiBaseQuery=({client:e,publicClient:t})=>async(r,{signal:s},a)=>{const i="string"==typeof r?{url:r}:r,o=i.silent??a?.silent??!1,n=i.expectedStatuses??a?.expectedStatuses,c=i.paramsFormat??a?.paramsFormat,u=i.public?t:e;if(!
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.strongEntityTag=exports.ifMatchValue=exports.createApiBaseQuery=void 0;var _axios=_interopRequireDefault(require("axios")),_index=require("../errors/index.js"),_index2=require("../logger/index.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const checkedMaxRetries=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t)||t<0)throw new Error(`createApiBaseQuery: "${e}" sets extraOptions.maxRetries to ${String(t)}; it must be a whole number of 0 or more.`);return t},encodeParam=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent("object"==typeof e?JSON.stringify(e):String(e)),strongEntityTag=e=>{if("string"==typeof e&&!e.startsWith("W/"))return/^"([^"]*)"$/.exec(e)?.[1]};exports.strongEntityTag=strongEntityTag;const ifMatchValue=e=>`"${e}"`;exports.ifMatchValue=ifMatchValue;const requestHeaders=e=>{const t={};if(e.ifMatch&&(t["If-Match"]=ifMatchValue(e.ifMatch)),e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),0===Object.keys(t).length)return e.headers;const r=Object.keys(t).map(e=>e.toLowerCase()),s=Object.entries(e.headers??{}).filter(([e])=>!r.includes(e.toLowerCase()));return{...Object.fromEntries(s),...t}},PRECONDITION_FAILED_CODE="precondition_failed",asPreconditionFailure=e=>412===e.status?{...e,code:"precondition_failed"}:e,serializeParams=e=>t=>{const r=[];for(const[s,a]of Object.entries(t)){if(null==a)continue;const t=encodeURIComponent(s);if(Array.isArray(a))if("comma"===e)r.push(`${t}=${a.map(encodeParam).join(",")}`);else{const s="brackets"===e?`${t}[]`:t;for(const e of a)r.push(`${s}=${encodeParam(e)}`)}else r.push(`${t}=${encodeParam(a)}`)}return r.join("&")},createApiBaseQuery=({client:e,publicClient:t})=>async(r,{signal:s},a)=>{const i="string"==typeof r?{url:r}:r,o=i.silent??a?.silent??!1,n=i.expectedStatuses??a?.expectedStatuses,c=i.paramsFormat??a?.paramsFormat,u=void 0===a?.maxRetries?void 0:checkedMaxRetries(i.url,a.maxRetries),d=i.public?t:e;if(!d)throw new Error(`createApiBaseQuery: "${i.url}" is marked public but no publicClient was passed.`);const p=requestHeaders(i),l={url:i.url,method:i.method??"GET",data:i.data,params:i.params,...c?{paramsSerializer:serializeParams(c)}:{},...void 0!==p?{headers:p}:{},...void 0!==i.responseType?{responseType:i.responseType}:{},...void 0!==i.timeout?{timeout:i.timeout}:{},...void 0===u?{}:{retry:{retries:u}},signal:s,skipErrorLog:!0};try{const e=await d.request(l),t=strongEntityTag(e.headers?.etag);return{data:e.data,meta:{silent:o,status:e.status,...void 0!==t&&{entityTag:t}}}}catch(e){const t=asPreconditionFailure((0,_index.extractApiError)(e)),r=_axios.default.isCancel(e);r||_index2.Logger.requestFailed(e,{expectedStatuses:n});const s=_axios.default.isAxiosError(e)?strongEntityTag(e.response?.headers?.etag):void 0;return{error:t,meta:{silent:o||r,status:t.status,...n&&{expectedStatuses:n},...void 0!==s&&{entityTag:s}}}}};exports.createApiBaseQuery=createApiBaseQuery;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useDataState=useDataState,exports.useInfiniteDataState=useInfiniteDataState;var _react=require("react"),_extractApiError=require("../errors/extractApiError.js");const isEmptyByDefault=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useDataState=useDataState,exports.useInfiniteDataState=useInfiniteDataState;var _react=require("react"),_extractApiError=require("../errors/extractApiError.js");const isEmptyByDefault=r=>Array.isArray(r)?0===r.length:!("object"!=typeof r||null===r||!("items"in r)||!Array.isArray(r.items))&&0===r.items.length;function useDataState(r,e){const{currentData:t,error:a,isFetching:i,isUninitialized:s,refetch:o,fulfilledTimeStamp:n}=r,u=!0===e?.keepPreviousData?r.data:void 0,l=e?.isEmpty??isEmptyByDefault;return(0,_react.useMemo)(()=>{const settled=(r,e)=>l(r)?{status:"empty",refreshing:i,refresh:o,refetch:o,fulfilledTimeStamp:n,refreshError:e}:{status:"data",data:r,refreshing:i,refresh:o,refetch:o,fulfilledTimeStamp:n,refreshError:e};return void 0!==t?settled(t,void 0===a?null:(0,_extractApiError.extractApiError)(a)):void 0!==a?{status:"error",error:(0,_extractApiError.extractApiError)(a),retry:o,refetch:o}:!0===s?{status:"idle"}:void 0!==u?settled(u,null):{status:"loading",refetch:o}},[t,u,a,i,s,o,l,n])}function useInfiniteDataState(r,e){const{currentData:t,error:a,isFetching:i,isFetchingNextPage:s,hasNextPage:o,isError:n,isFetchNextPageError:u,isUninitialized:l,refetch:c,fetchNextPage:f,fulfilledTimeStamp:p}=r,d=!0===e?.keepPreviousData&&void 0===t&&void 0===a&&!0!==l?r.data:void 0,h=t??d,m=(0,_react.useMemo)(()=>(h?.pages??[]).flatMap(r=>r.items),[h]),g=(0,_react.useMemo)(()=>{if(void 0===h)return void 0!==a?{status:"error",error:(0,_extractApiError.extractApiError)(a),retry:c,refetch:c}:!0===l?{status:"idle"}:{status:"loading",refetch:c};const r=i&&!s,e=n&&!0!==u&&void 0!==t?(0,_extractApiError.extractApiError)(a):null;return 0===m.length?{status:"empty",refreshing:r,refresh:c,refetch:c,fulfilledTimeStamp:p,refreshError:e}:{status:"data",data:m,refreshing:r,refresh:c,refetch:c,fulfilledTimeStamp:p,refreshError:e}},[h,a,n,u,t,i,s,l,m,c,p]),E=(0,_react.useMemo)(()=>{const r=h?.pages[0];if(void 0===r)return;const{items:e,...t}=r;return t},[h]),x=h?.pages[h.pages.length-1],A=x?.totalCount??null,v=x?.totalCountCapped??!1,y=n&&!0===u,_=n&&!0!==u&&void 0!==t;return{state:g,paging:(0,_react.useMemo)(()=>({hasMore:o,loadingMore:s,errorMore:y?(0,_extractApiError.extractApiError)(a):null,refreshError:_?(0,_extractApiError.extractApiError)(a):null,totalCount:A,totalCountCapped:v,loadMore:()=>{!o||s||y||f()},retryMore:()=>{y&&f()}}),[o,s,y,_,a,A,v,f]),firstPage:E}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.withIfMatch=exports.versionOf=exports.saveWithVersion=exports.entityTagOf=void 0;var _index=require("../errors/index.js"),_apiBaseQuery=require("./apiBaseQuery.js");const versionOf=(e,r)=>{const t="object"==typeof e&&null!==e&&"version"in e?e.version:void 0;return"string"==typeof t&&""!==t?t:void 0===r||""===r?void 0:r};exports.versionOf=versionOf;const withIfMatch=(e,r)=>{const t=Object.entries({...r?.headers}).filter(([e])=>"if-match"!==e.toLowerCase());return{...r,headers:{...Object.fromEntries(t),"If-Match":(0,_apiBaseQuery.ifMatchValue)(e)}}};exports.withIfMatch=withIfMatch;const entityTagOf=e=>{const r=e.headers;if("object"==typeof r&&null!==r&&"etag"in r)return(0,_apiBaseQuery.strongEntityTag)(r.etag)};exports.entityTagOf=entityTagOf;const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.withIfMatch=exports.versionOf=exports.saveWithVersion=exports.entityTagOf=void 0;var _index=require("../errors/index.js"),_apiBaseQuery=require("./apiBaseQuery.js");const versionOf=(e,r)=>{const t="object"==typeof e&&null!==e&&"version"in e?e.version:void 0;return"string"==typeof t&&""!==t?t:void 0===r||""===r?void 0:r};exports.versionOf=versionOf;const withIfMatch=(e,r)=>{const t=Object.entries({...r?.headers}).filter(([e])=>"if-match"!==e.toLowerCase());return{...r,headers:{...Object.fromEntries(t),"If-Match":(0,_apiBaseQuery.ifMatchValue)(e)}}};exports.withIfMatch=withIfMatch;const entityTagOf=e=>{const r=e.headers;if("object"==typeof r&&null!==r&&"etag"in r)return(0,_apiBaseQuery.strongEntityTag)(r.etag)};exports.entityTagOf=entityTagOf;const staleOf=e=>{const r=(0,_index.extractApiError)(e);return 412===r.status?r:void 0},saveWithVersion=async({record:e,entityTag:r,form:t,toForm:s,read:o,save:i})=>{const a=versionOf(e,r);if(void 0===a)throw new Error("saveWithVersion: the record has no version to send as If-Match");try{return await i(t,a),{saved:!0}}catch(r){const a=staleOf(r);if(void 0===a)throw r;const n=await o(),c=versionOf(n.record,n.entityTag);if(!(JSON.stringify(s(n.record))===JSON.stringify(s(e)))||void 0===c)return{saved:!1,error:a,fresh:n.record};try{return await i(t,c),{saved:!0}}catch(e){const r=staleOf(e);if(void 0===r)throw e;return{saved:!1,error:r,fresh:n.record}}}};exports.saveWithVersion=saveWithVersion;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{buildContractRequest}from"@webority/api-contract/call";export const createContractCaller=(t,e)=>async(r,a
|
|
1
|
+
"use strict";import{buildContractRequest,contractReply}from"@webority/api-contract/call";export const createContractCaller=(t,e)=>async(r,o,a)=>{const s=buildContractRequest(e[r],o,a),i=await t.request({method:s.method,url:s.url,...void 0===s.headers?{}:{headers:s.headers},data:s.data,responseType:s.responseType,...void 0===s.skipErrorLog?{}:{skipErrorLog:s.skipErrorLog},...void 0===s.expectedStatuses?{}:{expectedStatuses:s.expectedStatuses},...void 0===a?.signal?{}:{signal:a.signal},...void 0===a?.timeout?{}:{timeout:a.timeout},...void 0===a?.retry?{}:{retry:a.retry}});return contractReply(e[r],i.status,i.data)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import axios from"axios";import{getConfigValue}from"../config/index.js";import{Logger}from"../logger/index.js";import"../types/axios.js";import{applyConfiguredBaseUrl}from"./baseUrl.js";import{applyClientHeaders}from"./clientHeaders.js";import{logCurl}from"./curl.js";import{readMinAppVersion}from"./minAppVersion.js";import{sendFormDataAsMultipart}from"./multipart.js";import{applyRequestDefaults}from"./requestDefaults.js";import{responseBodyText}from"./responseBodyText.js";import{attachRetry}from"./retry.js";const publicClient=axios.create({headers:{"Content-Type":"application/json",Accept:"application/json"}});applyConfiguredBaseUrl(publicClient),applyRequestDefaults(publicClient),sendFormDataAsMultipart(publicClient),readMinAppVersion(publicClient),attachRetry(publicClient),publicClient.interceptors.request.use(e=>(Logger.info(`Request: ${e.method?.toUpperCase()} ${e.url}`),getConfigValue("logCurl")&&logCurl(e),e),e=>{const r=e instanceof Error?e.message:String(e);return Logger.error("Request error:",r),Promise.reject(e)}),applyClientHeaders(publicClient),publicClient.interceptors.response.use(e=>(Logger.info(`Response: ${e.status} from ${e.config.url}`),e),e=>{if(axios.isCancel(e))return Promise.reject(e);if(axios.isAxiosError(e)){const r=e.config;if(r?.skipErrorLog)return Promise.reject(e);e.response
|
|
1
|
+
"use strict";import axios from"axios";import{getConfigValue}from"../config/index.js";import{Logger}from"../logger/index.js";import"../types/axios.js";import{applyConfiguredBaseUrl}from"./baseUrl.js";import{applyClientHeaders}from"./clientHeaders.js";import{logCurl}from"./curl.js";import{readMinAppVersion}from"./minAppVersion.js";import{sendFormDataAsMultipart}from"./multipart.js";import{applyRequestDefaults}from"./requestDefaults.js";import{responseBodyText}from"./responseBodyText.js";import{attachRetry}from"./retry.js";const publicClient=axios.create({headers:{"Content-Type":"application/json",Accept:"application/json"}});applyConfiguredBaseUrl(publicClient),applyRequestDefaults(publicClient),sendFormDataAsMultipart(publicClient),readMinAppVersion(publicClient),attachRetry(publicClient),publicClient.interceptors.request.use(e=>(Logger.info(`Request: ${e.method?.toUpperCase()} ${e.url}`),getConfigValue("logCurl")&&logCurl(e),e),e=>{const r=e instanceof Error?e.message:String(e);return Logger.error("Request error:",r),Promise.reject(e)}),applyClientHeaders(publicClient),publicClient.interceptors.response.use(e=>(Logger.info(`Response: ${e.status} from ${e.config.url}`),e),e=>{if(axios.isCancel(e))return Promise.reject(e);if(axios.isAxiosError(e)){const r=e.config;if(r?.skipErrorLog)return Promise.reject(e);if(e.response){const o=`Response error: ${responseBodyText(e.response.data,e.message)}, URL: ${r?.url}, Status: ${e.response.status}`;r?.expectedStatuses?.includes(e.response.status)?Logger.debug(o):Logger.error(o)}else Logger.info(`Network error or no response from server: ${e.message}, URL: ${r?.url}`)}else{const r=e instanceof Error?e.message:String(e);Logger.error(`Unknown response error: ${r}`)}return Promise.reject(e)});export default publicClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import axios,{AxiosHeaders}from"axios";import{ACCESS_TOKEN_KEY,getToken}from"../auth/authStore.js";import{getConfigValue}from"../config/index.js";import{Logger}from"../logger/index.js";import{getLastKnownNetworkStatus}from"../network/networkStatus.js";import"../types/axios.js";import{isRecord}from"../utils/guards.js";import{applyConfiguredBaseUrl}from"./baseUrl.js";import{applyClientHeaders,readAccountId,stampAccountId}from"./clientHeaders.js";import{logCurl}from"./curl.js";import{readMinAppVersion}from"./minAppVersion.js";import{sendFormDataAsMultipart}from"./multipart.js";import{applyRequestDefaults}from"./requestDefaults.js";import{responseBodyText}from"./responseBodyText.js";import{attachRetry}from"./retry.js";import{beginSessionReplacement,currentTokenIfReplaced,endSessionAndLogout,getAccountIdProvider,getErrorMessage,getRefreshPath,isRefreshInFlight,isSessionEnd,queueBehindRefresh,refreshAccessToken,resetRefreshState,SessionEndedError,sessionCodeOf,sessionDetailOf,storeReplacementSession,waitForSessionReplacement}from"./tokenRefresh.js";import{isWorkspaceChangedResponse,WorkspaceChangedError}from"./workspace.js";export{injectStore,injectUserAuth,resetRefreshState,SESSION_EXPIRED_CODE,SESSION_REVOKED_CODE}from"./tokenRefresh.js";export class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[e.transformRequest??[]].flat();e.transformRequest=[function guarded(e,t){try{return r.reduce((e,r)=>r.call(this,e,t),e)}catch(e){throw endReplacement(this),e}}]};let openReplacementSteps=0,replacementStepsSettled=Promise.resolve(),settleReplacementSteps=null;const openReplacementStep=()=>{0===openReplacementSteps&&(replacementStepsSettled=new Promise(e=>{settleReplacementSteps=e})),openReplacementSteps+=1;let e=!1;return()=>{e||(e=!0,openReplacementSteps-=1,0===openReplacementSteps&&(settleReplacementSteps?.(),settleReplacementSteps=null))}},waitForReplacementStep=async()=>{for(;openReplacementSteps>0;)await replacementStepsSettled},readSentToken=e=>{const r=e.headers instanceof AxiosHeaders?e.headers.get("Authorization"):void 0;return"string"==typeof r&&r.startsWith("Bearer ")?r.slice(7):null},userClient=axios.create({headers:{"Content-Type":"application/json"}});readMinAppVersion(userClient),attachRetry(userClient);const parseRawHeaders=e=>{const r={};if(void 0===e)return r;if(!isRecord(e))throw new Error("Request headers must be AxiosHeaders or a plain object.");for(const[t,s]of Object.entries(e)){if(void 0===s)continue;if(!(null===s||"string"==typeof s||"number"==typeof s||"boolean"==typeof s||Array.isArray(s)))throw new Error(`The request header "${t}" has a value no header can carry.`);r[t]=s}return r},setAuthHeader=(e,r)=>{e.headers instanceof AxiosHeaders?e.headers.set("Authorization",`Bearer ${r}`):e.headers=AxiosHeaders.from({...parseRawHeaders(e.headers),Authorization:`Bearer ${r}`})},isRefreshTokenRequest=e=>{const r=getRefreshPath();return!!r&&!!e?.includes(r)};userClient.interceptors.request.use(e=>(e.replacesSession&&!isRefreshTokenRequest(e.url)&&(e._endReplacement=beginSessionReplacement(),closeWindowIfTransformThrows(e)),e)),applyConfiguredBaseUrl(userClient),applyRequestDefaults(userClient),sendFormDataAsMultipart(userClient),userClient.interceptors.request.use(e=>(getConfigValue("logCurl")&&logCurl(e),e)),applyClientHeaders(userClient),userClient.interceptors.request.use(async e=>{endReplacement(e);if(!1===(await getLastKnownNetworkStatus()).isConnected)return Logger.info(`Request blocked: device is offline. URL: ${e.url}`),Promise.reject(new RequestOfflineError);try{if(isRefreshTokenRequest(e.url))return e;await stampAccountId(e,getAccountIdProvider());const r=await getToken(ACCESS_TOKEN_KEY);if(!r?.token)throw new NoAccessTokenError;await waitForReplacementStep();const t=Date.now(),s=Date.parse(r.expiry);if(s<=t+3e4){Logger.info("Access token expired or about to expire, refreshing before request");const r=await refreshAccessToken();setAuthHeader(e,r)}else setAuthHeader(e,r.token);return e}catch(r){return r instanceof NoAccessTokenError?Logger.info(`Request not sent: signed out. URL: ${e.url}`):isSessionEnd(r)||Logger.error("Failed to attach token:",getErrorMessage(r)),Promise.reject(r)}},e=>(Logger.error("Request error:",getErrorMessage(e)),Promise.reject(e))),userClient.interceptors.response.use(async e=>{const r=e.config;if(r._endReplacement){const t=openReplacementStep();try{await storeReplacementSession(e.data),await(r.onSessionReplaced?.(e.data))}finally{t(),endReplacement(r)}}return e},async e=>{if(endReplacement(axios.isAxiosError(e)?e.config:void 0),axios.isCancel(e))return Promise.reject(e);if(e instanceof RequestOfflineError||e instanceof NoAccessTokenError||e instanceof SessionEndedError)return Promise.reject(e);if(!axios.isAxiosError(e))return Logger.error(`Non-axios error in response interceptor: ${getErrorMessage(e)}`),Promise.reject(e);const r=e,t=r.config;if(!r.response)return t?.skipErrorLog||Logger.info(`Network error or no response from server: ${r.message}, URL: ${t?.url}`),Promise.reject(e);if(isWorkspaceChangedResponse(r))return Logger.info(`Refused for another workspace. URL: ${t?.url}`),Promise.reject(new WorkspaceChangedError("Refused for another workspace",{response:r.response,config:t,cause:e}));if(isRefreshTokenRequest(t?.url))return Promise.reject(e);if(401===r.response.status&&t&&!t._replayedWithCurrentToken&&!t.replacesSession&&(await waitForSessionReplacement(),await currentTokenIfReplaced(readSentToken(t)))){const r=await readAccountId(getAccountIdProvider());return(t._accountId??null)!==r?(Logger.info(`Workspace changed in flight; not sent again. URL: ${t.url}`),Promise.reject(new WorkspaceChangedError("Workspace changed in flight",{config:t,cause:e}))):(Logger.info(`Session changed while the request was in flight; sending it again. URL: ${t.url}`),t._replayedWithCurrentToken=!0,userClient(t))}if(401===r.response.status&&t&&!t._retry){const s=sessionCodeOf(r.response.data);if(null!==s)return Logger.warn(`Session ${s}, logging out without refresh. URL: ${t.url}`),resetRefreshState(),await endSessionAndLogout("terminated",s,sessionDetailOf(r.response.data)),Promise.reject(e);if(Logger.warn(`Unauthorized URL: ${t.url}`),t._retry=!0,isRefreshInFlight())return queueBehindRefresh().then(e=>(Logger.info("Retrying request after token refresh:",t.url),setAuthHeader(t,e),userClient(t))).catch(e=>(isSessionEnd(e)||Logger.error("Failed to retry request after token refresh:",getErrorMessage(e)),Promise.reject(e)));try{const e=await refreshAccessToken();return setAuthHeader(t,e),userClient(t)}catch(e){return Promise.reject(e)}}
|
|
1
|
+
"use strict";import axios,{AxiosHeaders}from"axios";import{ACCESS_TOKEN_KEY,getToken}from"../auth/authStore.js";import{getConfigValue}from"../config/index.js";import{Logger}from"../logger/index.js";import{getLastKnownNetworkStatus}from"../network/networkStatus.js";import"../types/axios.js";import{isRecord}from"../utils/guards.js";import{applyConfiguredBaseUrl}from"./baseUrl.js";import{applyClientHeaders,readAccountId,stampAccountId}from"./clientHeaders.js";import{logCurl}from"./curl.js";import{readMinAppVersion}from"./minAppVersion.js";import{sendFormDataAsMultipart}from"./multipart.js";import{applyRequestDefaults}from"./requestDefaults.js";import{responseBodyText}from"./responseBodyText.js";import{attachRetry}from"./retry.js";import{beginSessionReplacement,currentTokenIfReplaced,endSessionAndLogout,getAccountIdProvider,getErrorMessage,getRefreshPath,isRefreshInFlight,isSessionEnd,queueBehindRefresh,refreshAccessToken,resetRefreshState,SessionEndedError,sessionCodeOf,sessionDetailOf,storeReplacementSession,waitForSessionReplacement}from"./tokenRefresh.js";import{isWorkspaceChangedResponse,WorkspaceChangedError}from"./workspace.js";export{injectStore,injectUserAuth,resetRefreshState,SESSION_EXPIRED_CODE,SESSION_REVOKED_CODE}from"./tokenRefresh.js";export class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[e.transformRequest??[]].flat();e.transformRequest=[function guarded(e,t){try{return r.reduce((e,r)=>r.call(this,e,t),e)}catch(e){throw endReplacement(this),e}}]};let openReplacementSteps=0,replacementStepsSettled=Promise.resolve(),settleReplacementSteps=null;const openReplacementStep=()=>{0===openReplacementSteps&&(replacementStepsSettled=new Promise(e=>{settleReplacementSteps=e})),openReplacementSteps+=1;let e=!1;return()=>{e||(e=!0,openReplacementSteps-=1,0===openReplacementSteps&&(settleReplacementSteps?.(),settleReplacementSteps=null))}},waitForReplacementStep=async()=>{for(;openReplacementSteps>0;)await replacementStepsSettled},readSentToken=e=>{const r=e.headers instanceof AxiosHeaders?e.headers.get("Authorization"):void 0;return"string"==typeof r&&r.startsWith("Bearer ")?r.slice(7):null},userClient=axios.create({headers:{"Content-Type":"application/json"}});readMinAppVersion(userClient),attachRetry(userClient);const parseRawHeaders=e=>{const r={};if(void 0===e)return r;if(!isRecord(e))throw new Error("Request headers must be AxiosHeaders or a plain object.");for(const[t,s]of Object.entries(e)){if(void 0===s)continue;if(!(null===s||"string"==typeof s||"number"==typeof s||"boolean"==typeof s||Array.isArray(s)))throw new Error(`The request header "${t}" has a value no header can carry.`);r[t]=s}return r},setAuthHeader=(e,r)=>{e.headers instanceof AxiosHeaders?e.headers.set("Authorization",`Bearer ${r}`):e.headers=AxiosHeaders.from({...parseRawHeaders(e.headers),Authorization:`Bearer ${r}`})},isRefreshTokenRequest=e=>{const r=getRefreshPath();return!!r&&!!e?.includes(r)};userClient.interceptors.request.use(e=>(e.replacesSession&&!isRefreshTokenRequest(e.url)&&(e._endReplacement=beginSessionReplacement(),closeWindowIfTransformThrows(e)),e)),applyConfiguredBaseUrl(userClient),applyRequestDefaults(userClient),sendFormDataAsMultipart(userClient),userClient.interceptors.request.use(e=>(getConfigValue("logCurl")&&logCurl(e),e)),applyClientHeaders(userClient),userClient.interceptors.request.use(async e=>{endReplacement(e);if(!1===(await getLastKnownNetworkStatus()).isConnected)return Logger.info(`Request blocked: device is offline. URL: ${e.url}`),Promise.reject(new RequestOfflineError);try{if(isRefreshTokenRequest(e.url))return e;await stampAccountId(e,getAccountIdProvider());const r=await getToken(ACCESS_TOKEN_KEY);if(!r?.token)throw new NoAccessTokenError;await waitForReplacementStep();const t=Date.now(),s=Date.parse(r.expiry);if(s<=t+3e4){Logger.info("Access token expired or about to expire, refreshing before request");const r=await refreshAccessToken();setAuthHeader(e,r)}else setAuthHeader(e,r.token);return e}catch(r){return r instanceof NoAccessTokenError?Logger.info(`Request not sent: signed out. URL: ${e.url}`):isSessionEnd(r)||Logger.error("Failed to attach token:",getErrorMessage(r)),Promise.reject(r)}},e=>(Logger.error("Request error:",getErrorMessage(e)),Promise.reject(e))),userClient.interceptors.response.use(async e=>{const r=e.config;if(r._endReplacement){const t=openReplacementStep();try{await storeReplacementSession(e.data),await(r.onSessionReplaced?.(e.data))}finally{t(),endReplacement(r)}}return e},async e=>{if(endReplacement(axios.isAxiosError(e)?e.config:void 0),axios.isCancel(e))return Promise.reject(e);if(e instanceof RequestOfflineError||e instanceof NoAccessTokenError||e instanceof SessionEndedError)return Promise.reject(e);if(!axios.isAxiosError(e))return Logger.error(`Non-axios error in response interceptor: ${getErrorMessage(e)}`),Promise.reject(e);const r=e,t=r.config;if(!r.response)return t?.skipErrorLog||Logger.info(`Network error or no response from server: ${r.message}, URL: ${t?.url}`),Promise.reject(e);if(isWorkspaceChangedResponse(r))return Logger.info(`Refused for another workspace. URL: ${t?.url}`),Promise.reject(new WorkspaceChangedError("Refused for another workspace",{response:r.response,config:t,cause:e}));if(isRefreshTokenRequest(t?.url))return Promise.reject(e);if(401===r.response.status&&t&&!t._replayedWithCurrentToken&&!t.replacesSession&&(await waitForSessionReplacement(),await currentTokenIfReplaced(readSentToken(t)))){const r=await readAccountId(getAccountIdProvider());return(t._accountId??null)!==r?(Logger.info(`Workspace changed in flight; not sent again. URL: ${t.url}`),Promise.reject(new WorkspaceChangedError("Workspace changed in flight",{config:t,cause:e}))):(Logger.info(`Session changed while the request was in flight; sending it again. URL: ${t.url}`),t._replayedWithCurrentToken=!0,userClient(t))}if(401===r.response.status&&t&&!t._retry){const s=sessionCodeOf(r.response.data);if(null!==s)return Logger.warn(`Session ${s}, logging out without refresh. URL: ${t.url}`),resetRefreshState(),await endSessionAndLogout("terminated",s,sessionDetailOf(r.response.data)),Promise.reject(e);if(Logger.warn(`Unauthorized URL: ${t.url}`),t._retry=!0,isRefreshInFlight())return queueBehindRefresh().then(e=>(Logger.info("Retrying request after token refresh:",t.url),setAuthHeader(t,e),userClient(t))).catch(e=>(isSessionEnd(e)||Logger.error("Failed to retry request after token refresh:",getErrorMessage(e)),Promise.reject(e)));try{const e=await refreshAccessToken();return setAuthHeader(t,e),userClient(t)}catch(e){return Promise.reject(e)}}if(!t?.skipErrorLog){const e=`Response error: ${responseBodyText(r.response?.data,r.message)}, URL: ${t?.url}, Status: ${r.response.status}`;t?.expectedStatuses?.includes(r.response.status)?Logger.debug(e):Logger.error(e)}return Promise.reject(e)});export default userClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{isOfflineFailure}from"./requestPlatform.js";export const SERVER_FAILURE_MESSAGE="Something went wrong on our side. Please try again in a moment.";export const OFFLINE_MESSAGE="You appear to be offline. Check your connection and try again.";export const UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and try again.";export const TIMEOUT_MESSAGE="That took too long to respond. Check your connection and try again.";export const UNEXPECTED_MESSAGE="Something went wrong. Please try again.";export const REQUEST_CANCELED_CODE="request_canceled";export const CONTRACT_ERROR_CODE="contract_error";export const TIMEOUT_CODE="timeout";export const NETWORK_CODE="network";export const OFFLINE_CODE="offline";const MAX_MESSAGE_LENGTH=300,INTERNAL_ERROR_CODE="internal_error",requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const n=FLEET_DEFAULT_REFUSALS[e];if(void 0===n||null===t||t.code!==n.code)return null;const r=nonEmptyString(t.detail);return null===r||r===n.sentence?n.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),userSafe=e=>{const t=nonEmptyString(e);return null===t||looksLikeDiagnostics(t)?null:t};export const toFieldPath=e=>e.replace(/^\$\.?/,"").split(".").map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(".");const firstMessage=e=>{if(Array.isArray(e)){for(const t of e){const e=nonEmptyString(t);if(null!==e)return e}return null}return nonEmptyString(e)},addError=(e,t,n)=>{const r=toFieldPath(t);""===r?e.form??=n:r in e.fields||(e.fields[r]=n)},readErrors=e=>{const t={fields:{},form:null};if(Array.isArray(e)){for(const n of e){if(!isDict(n))continue;const e=nonEmptyString(n.message);null!==e&&addError(t,"string"==typeof n.field?n.field:"",e)}return t}if(!isDict(e))return t;for(const[n,r]of Object.entries(e)){const e=firstMessage(r);null!==e&&addError(t,n,e)}return t};export const isApiError=e=>isDict(e)&&"string"==typeof e.message&&"number"==typeof e.status&&"boolean"==typeof e.offline&&isDict(e.fieldErrors);const build=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const n="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,r="string"==typeof n?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null;return r?.[1]??null},fromNoResponse=e=>{const t=nonEmptyString(e.code),n=nonEmptyString(e.name),r=nonEmptyString(e.message),
|
|
1
|
+
"use strict";import{isOfflineFailure}from"./requestPlatform.js";export const SERVER_FAILURE_MESSAGE="Something went wrong on our side. Please try again in a moment.";export const OFFLINE_MESSAGE="You appear to be offline. Check your connection and try again.";export const UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and try again.";export const TIMEOUT_MESSAGE="That took too long to respond. Check your connection and try again.";export const UNEXPECTED_MESSAGE="Something went wrong. Please try again.";export const REQUEST_CANCELED_CODE="request_canceled";export const CONTRACT_ERROR_CODE="contract_error";export const TIMEOUT_CODE="timeout";export const NETWORK_CODE="network";export const OFFLINE_CODE="offline";const MAX_MESSAGE_LENGTH=300,INTERNAL_ERROR_CODE="internal_error",requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const n=FLEET_DEFAULT_REFUSALS[e];if(void 0===n||null===t||t.code!==n.code)return null;const r=nonEmptyString(t.detail);return null===r||r===n.sentence?n.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),userSafe=e=>{const t=nonEmptyString(e);return null===t||looksLikeDiagnostics(t)?null:t};export const toFieldPath=e=>e.replace(/^\$\.?/,"").split(".").map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(".");const firstMessage=e=>{if(Array.isArray(e)){for(const t of e){const e=nonEmptyString(t);if(null!==e)return e}return null}return nonEmptyString(e)},addError=(e,t,n)=>{const r=toFieldPath(t);""===r?e.form??=n:r in e.fields||(e.fields[r]=n)},readErrors=e=>{const t={fields:{},form:null};if(Array.isArray(e)){for(const n of e){if(!isDict(n))continue;const e=nonEmptyString(n.message);null!==e&&addError(t,"string"==typeof n.field?n.field:"",e)}return t}if(!isDict(e))return t;for(const[n,r]of Object.entries(e)){const e=firstMessage(r);null!==e&&addError(t,n,e)}return t};export const isApiError=e=>isDict(e)&&"string"==typeof e.message&&"number"==typeof e.status&&"boolean"==typeof e.offline&&isDict(e.fieldErrors)&&isDict(e.extensions);const build=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,extensions:{},...e}),STANDARD_PROBLEM_MEMBERS=new Set(["type","title","status","detail","instance","code","errors","traceId"]),problemExtensions=e=>null===e?{}:Object.fromEntries(Object.entries(e).filter(([e])=>!STANDARD_PROBLEM_MEMBERS.has(e))),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const n="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,r="string"==typeof n?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null;return r?.[1]??null},fromNoResponse=e=>{const t=nonEmptyString(e.code),n=nonEmptyString(e.name),r=nonEmptyString(e.message),s=requestTraceId(e);return"CanceledError"===n||"ERR_CANCELED"===t?build({code:"request_canceled",message:UNEXPECTED_MESSAGE,traceId:s,diagnostic:r}):"ECONNABORTED"===t||"ETIMEDOUT"===t?build({code:"timeout",message:TIMEOUT_MESSAGE,offline:!0,traceId:s,diagnostic:r}):"RequestOfflineError"===n||"ERR_NETWORK"===t||"Network Error"===r||"Network request failed"===r?isOfflineFailure(e)?build({code:"offline",message:OFFLINE_MESSAGE,offline:!0,traceId:s,diagnostic:r}):build({code:"network",message:UNREACHABLE_MESSAGE,offline:!0,traceId:s,diagnostic:r}):build({message:UNEXPECTED_MESSAGE,traceId:s,diagnostic:r})};export function extractApiError(e){if(isApiError(e))return e;if("string"==typeof e)return build({message:userSafe(e)??UNEXPECTED_MESSAGE,diagnostic:e||null});if(!isDict(e))return build({message:UNEXPECTED_MESSAGE,diagnostic:null==e?null:String(e)});if(!0===e.isContractError)return build({code:"contract_error",message:userSafe(e.message)??UNEXPECTED_MESSAGE,diagnostic:nonEmptyString(e.message)});const t=isDict(e.response)?e.response:null,n="number"==typeof t?.status?t.status:"number"==typeof e.status?e.status:0,r=t?t.data:e.body;if(0===n&&null==r)return fromNoResponse(e);const s=isDict(r)?r:null,{fields:o,form:i}=readErrors(s?.errors),a=nonEmptyString(s?.code),l=nonEmptyString(s?.traceId)??requestTraceId(e),E=nonEmptyString(s?.detail)??nonEmptyString(s?.title)??nonEmptyString(r)??nonEmptyString(e.message);let c;if(n>=500){c=(null!==a&&"internal_error"!==a?userSafe(s?.detail):null)??SERVER_FAILURE_MESSAGE}else c=fleetDefaultRefusalSentence(n,s)??userSafe(Object.values(o)[0])??userSafe(i)??userSafe(s?.detail)??userSafe(s?.title)??userSafe(r)??(n?requestFailedMessage(n):UNEXPECTED_MESSAGE);const u=isDict(e.config)?e.config:null,f=null===u?null:nonEmptyString(u.url),d=null!==u&&"_accountId"in u?nonEmptyString(u._accountId):null;return build({code:a,message:c,fieldErrors:o,status:n,traceId:l,diagnostic:E,extensions:problemExtensions(s),...null===f?{}:{requestUrl:f},...null===d?{}:{accountId:d}})}export const isNoResponse=e=>extractApiError(e).offline;export function apiErrorMessage(e,t){const n=extractApiError(e);if(n.offline||null!==t&&!t)return n.message;if(n.status>=500&&n.message!==SERVER_FAILURE_MESSAGE)return n.message;return n.status>=500||"request_canceled"===n.code||n.message===UNEXPECTED_MESSAGE||n.message===requestFailedMessage(n.status)?t??null:n.message}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import axios from"axios";import{extractApiError}from"../errors/index.js";import{Logger}from"../logger/index.js";const encodeParam=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent("object"==typeof e?JSON.stringify(e):String(e));export const strongEntityTag=e=>{if("string"==typeof e&&!e.startsWith("W/"))return/^"([^"]*)"$/.exec(e)?.[1]};export const ifMatchValue=e=>`"${e}"`;const requestHeaders=e=>{const t={};if(e.ifMatch&&(t["If-Match"]=ifMatchValue(e.ifMatch)),e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),0===Object.keys(t).length)return e.headers;const r=Object.keys(t).map(e=>e.toLowerCase()),s=Object.entries(e.headers??{}).filter(([e])=>!r.includes(e.toLowerCase()));return{...Object.fromEntries(s),...t}},PRECONDITION_FAILED_CODE="precondition_failed",asPreconditionFailure=e=>412===e.status?{...e,code:"precondition_failed"}:e,serializeParams=e=>t=>{const r=[];for(const[s,o]of Object.entries(t)){if(null==o)continue;const t=encodeURIComponent(s);if(Array.isArray(o))if("comma"===e)r.push(`${t}=${o.map(encodeParam).join(",")}`);else{const s="brackets"===e?`${t}[]`:t;for(const e of o)r.push(`${s}=${encodeParam(e)}`)}else r.push(`${t}=${encodeParam(o)}`)}return r.join("&")};export const createApiBaseQuery=({client:e,publicClient:t})=>async(r,{signal:s},o)=>{const a="string"==typeof r?{url:r}:r,i=a.silent??o?.silent??!1,n=a.expectedStatuses??o?.expectedStatuses,c=a.paramsFormat??o?.paramsFormat,p=a.public?t:e;if(!p)throw new Error(`createApiBaseQuery: "${a.url}" is marked public but no publicClient was passed.`);const
|
|
1
|
+
"use strict";import axios from"axios";import{extractApiError}from"../errors/index.js";import{Logger}from"../logger/index.js";const checkedMaxRetries=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t)||t<0)throw new Error(`createApiBaseQuery: "${e}" sets extraOptions.maxRetries to ${String(t)}; it must be a whole number of 0 or more.`);return t},encodeParam=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent("object"==typeof e?JSON.stringify(e):String(e));export const strongEntityTag=e=>{if("string"==typeof e&&!e.startsWith("W/"))return/^"([^"]*)"$/.exec(e)?.[1]};export const ifMatchValue=e=>`"${e}"`;const requestHeaders=e=>{const t={};if(e.ifMatch&&(t["If-Match"]=ifMatchValue(e.ifMatch)),e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),0===Object.keys(t).length)return e.headers;const r=Object.keys(t).map(e=>e.toLowerCase()),s=Object.entries(e.headers??{}).filter(([e])=>!r.includes(e.toLowerCase()));return{...Object.fromEntries(s),...t}},PRECONDITION_FAILED_CODE="precondition_failed",asPreconditionFailure=e=>412===e.status?{...e,code:"precondition_failed"}:e,serializeParams=e=>t=>{const r=[];for(const[s,o]of Object.entries(t)){if(null==o)continue;const t=encodeURIComponent(s);if(Array.isArray(o))if("comma"===e)r.push(`${t}=${o.map(encodeParam).join(",")}`);else{const s="brackets"===e?`${t}[]`:t;for(const e of o)r.push(`${s}=${encodeParam(e)}`)}else r.push(`${t}=${encodeParam(o)}`)}return r.join("&")};export const createApiBaseQuery=({client:e,publicClient:t})=>async(r,{signal:s},o)=>{const a="string"==typeof r?{url:r}:r,i=a.silent??o?.silent??!1,n=a.expectedStatuses??o?.expectedStatuses,c=a.paramsFormat??o?.paramsFormat,d=void 0===o?.maxRetries?void 0:checkedMaxRetries(a.url,o.maxRetries),p=a.public?t:e;if(!p)throw new Error(`createApiBaseQuery: "${a.url}" is marked public but no publicClient was passed.`);const u=requestHeaders(a),m={url:a.url,method:a.method??"GET",data:a.data,params:a.params,...c?{paramsSerializer:serializeParams(c)}:{},...void 0!==u?{headers:u}:{},...void 0!==a.responseType?{responseType:a.responseType}:{},...void 0!==a.timeout?{timeout:a.timeout}:{},...void 0===d?{}:{retry:{retries:d}},signal:s,skipErrorLog:!0};try{const e=await p.request(m),t=strongEntityTag(e.headers?.etag);return{data:e.data,meta:{silent:i,status:e.status,...void 0!==t&&{entityTag:t}}}}catch(e){const t=asPreconditionFailure(extractApiError(e)),r=axios.isCancel(e);r||Logger.requestFailed(e,{expectedStatuses:n});const s=axios.isAxiosError(e)?strongEntityTag(e.response?.headers?.etag):void 0;return{error:t,meta:{silent:i||r,status:t.status,...n&&{expectedStatuses:n},...void 0!==s&&{entityTag:s}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useMemo}from"react";import{extractApiError}from"../errors/extractApiError.js";const isEmptyByDefault=
|
|
1
|
+
"use strict";import{useMemo}from"react";import{extractApiError}from"../errors/extractApiError.js";const isEmptyByDefault=r=>Array.isArray(r)?0===r.length:!("object"!=typeof r||null===r||!("items"in r)||!Array.isArray(r.items))&&0===r.items.length;export function useDataState(r,e){const{currentData:t,error:a,isFetching:i,isUninitialized:s,refetch:o,fulfilledTimeStamp:n}=r,l=!0===e?.keepPreviousData?r.data:void 0,u=e?.isEmpty??isEmptyByDefault;return useMemo(()=>{const settled=(r,e)=>u(r)?{status:"empty",refreshing:i,refresh:o,refetch:o,fulfilledTimeStamp:n,refreshError:e}:{status:"data",data:r,refreshing:i,refresh:o,refetch:o,fulfilledTimeStamp:n,refreshError:e};return void 0!==t?settled(t,void 0===a?null:extractApiError(a)):void 0!==a?{status:"error",error:extractApiError(a),retry:o,refetch:o}:!0===s?{status:"idle"}:void 0!==l?settled(l,null):{status:"loading",refetch:o}},[t,l,a,i,s,o,u,n])}export function useInfiniteDataState(r,e){const{currentData:t,error:a,isFetching:i,isFetchingNextPage:s,hasNextPage:o,isError:n,isFetchNextPageError:l,isUninitialized:u,refetch:f,fetchNextPage:c,fulfilledTimeStamp:p}=r,d=!0===e?.keepPreviousData&&void 0===t&&void 0===a&&!0!==u?r.data:void 0,h=t??d,m=useMemo(()=>(h?.pages??[]).flatMap(r=>r.items),[h]),g=useMemo(()=>{if(void 0===h)return void 0!==a?{status:"error",error:extractApiError(a),retry:f,refetch:f}:!0===u?{status:"idle"}:{status:"loading",refetch:f};const r=i&&!s,e=n&&!0!==l&&void 0!==t?extractApiError(a):null;return 0===m.length?{status:"empty",refreshing:r,refresh:f,refetch:f,fulfilledTimeStamp:p,refreshError:e}:{status:"data",data:m,refreshing:r,refresh:f,refetch:f,fulfilledTimeStamp:p,refreshError:e}},[h,a,n,l,t,i,s,u,m,f,p]),E=useMemo(()=>{const r=h?.pages[0];if(void 0===r)return;const{items:e,...t}=r;return t},[h]),v=h?.pages[h.pages.length-1],y=v?.totalCount??null,x=v?.totalCountCapped??!1,A=n&&!0===l,M=n&&!0!==l&&void 0!==t;return{state:g,paging:useMemo(()=>({hasMore:o,loadingMore:s,errorMore:A?extractApiError(a):null,refreshError:M?extractApiError(a):null,totalCount:y,totalCountCapped:x,loadMore:()=>{!o||s||A||c()},retryMore:()=>{A&&c()}}),[o,s,A,M,a,y,x,c]),firstPage:E}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{
|
|
1
|
+
"use strict";import{extractApiError}from"../errors/index.js";import{ifMatchValue,strongEntityTag}from"./apiBaseQuery.js";export const versionOf=(r,t)=>{const e="object"==typeof r&&null!==r&&"version"in r?r.version:void 0;return"string"==typeof e&&""!==e?e:void 0===t||""===t?void 0:t};export const withIfMatch=(r,t)=>{const e=Object.entries({...t?.headers}).filter(([r])=>"if-match"!==r.toLowerCase());return{...t,headers:{...Object.fromEntries(e),"If-Match":ifMatchValue(r)}}};export const entityTagOf=r=>{const t=r.headers;if("object"==typeof t&&null!==t&&"etag"in t)return strongEntityTag(t.etag)};const staleOf=r=>{const t=extractApiError(r);return 412===t.status?t:void 0};export const saveWithVersion=async({record:r,entityTag:t,form:e,toForm:o,read:s,save:i})=>{const n=versionOf(r,t);if(void 0===n)throw new Error("saveWithVersion: the record has no version to send as If-Match");try{return await i(e,n),{saved:!0}}catch(t){const n=staleOf(t);if(void 0===n)throw t;const a=await s(),c=versionOf(a.record,a.entityTag);if(!(JSON.stringify(o(a.record))===JSON.stringify(o(r)))||void 0===c)return{saved:!1,error:n,fresh:a.record};try{return await i(e,c),{saved:!0}}catch(r){const t=staleOf(r);if(void 0===t)throw r;return{saved:!1,error:t,fresh:a.record}}}};
|
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
import { type OperationEntry, type OperationShape } from "@webority/api-contract/call";
|
|
1
|
+
import { type ContractCallOptions, type OperationEntry, type OperationShape } from "@webority/api-contract/call";
|
|
2
2
|
import type { AxiosInstance, AxiosRequestConfig } from "axios";
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Per-call options: an abort signal, a timeout, the client's retry override (`false`, or a policy such as `{ retries: 1 }`),
|
|
5
|
+
* call headers the contract does not declare, `skipErrorLog` and `expectedStatuses`. buildContractRequest validates the
|
|
6
|
+
* headers and the two error options, and throws ContractCallError on an invalid value before anything is sent.
|
|
7
|
+
*/
|
|
8
|
+
export type ContractCallConfig = Pick<AxiosRequestConfig, "signal" | "timeout" | "retry"> & ContractCallOptions;
|
|
5
9
|
export type ContractCaller<TOperations extends {
|
|
6
10
|
readonly [K in keyof TOperations]: OperationShape;
|
|
7
11
|
}> = <TId extends keyof TOperations & string>(id: TId, request: TOperations[TId]["request"], config?: ContractCallConfig) => Promise<TOperations[TId]["response"]>;
|
|
@@ -13,6 +13,12 @@ export interface ApiError {
|
|
|
13
13
|
traceId: string | null;
|
|
14
14
|
/** What the server or runtime actually said. For the logger, never for the screen. */
|
|
15
15
|
diagnostic: string | null;
|
|
16
|
+
/**
|
|
17
|
+
* Every member of the problem body other than `type`, `title`, `status`, `detail`, `instance`,
|
|
18
|
+
* `code`, `errors` and `traceId`, as the server sent it. Empty when the body had none or no answer
|
|
19
|
+
* arrived. Read a documented member through a type guard; never render one.
|
|
20
|
+
*/
|
|
21
|
+
extensions: Readonly<Record<string, unknown>>;
|
|
16
22
|
/** The request address the failed call was sent to. For the logger and the caller, never the screen. */
|
|
17
23
|
requestUrl?: string | undefined;
|
|
18
24
|
/** The Account-Id the failed call was sent with. For the logger and the caller, never the screen. */
|
|
@@ -5,11 +5,16 @@ export interface PickedFile {
|
|
|
5
5
|
size?: number | undefined;
|
|
6
6
|
meta?: Record<string, unknown> | undefined;
|
|
7
7
|
}
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* One way to pick files. `F` is what `pick` resolves: a source that prepares its
|
|
10
|
+
* files (resized, renamed) names its own file type, and a picker hands that same
|
|
11
|
+
* object to its `onPick`.
|
|
12
|
+
*/
|
|
13
|
+
export interface PickerSource<F extends PickedFile = PickedFile> {
|
|
9
14
|
key: string;
|
|
10
15
|
label: string;
|
|
11
16
|
description?: string | undefined;
|
|
12
|
-
pick: () => Promise<
|
|
17
|
+
pick: () => Promise<F[]>;
|
|
13
18
|
}
|
|
14
19
|
export interface PhotoOptions {
|
|
15
20
|
maxEdgePx?: number | undefined;
|
|
@@ -40,6 +40,11 @@ export interface ApiExtraOptions {
|
|
|
40
40
|
silent?: boolean | undefined;
|
|
41
41
|
expectedStatuses?: number[] | undefined;
|
|
42
42
|
paramsFormat?: ParamsFormat | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* How many times the client resends a failed call that its retry rule allows, in place of the
|
|
45
|
+
* client's `retries` setting; `0` sends it once. RTK Query's own `retry()` reads the same name.
|
|
46
|
+
*/
|
|
47
|
+
maxRetries?: number | undefined;
|
|
43
48
|
}
|
|
44
49
|
export declare const strongEntityTag: (value: unknown) => string | undefined;
|
|
45
50
|
/** The `If-Match` header value for a version: the version in quotes, as an ETag is sent. */
|
|
@@ -18,6 +18,8 @@ export type DataState<T> = {
|
|
|
18
18
|
readonly refresh: () => void;
|
|
19
19
|
readonly refetch: () => void;
|
|
20
20
|
readonly fulfilledTimeStamp?: number | undefined;
|
|
21
|
+
/** A failed refetch while this result stays on screen; null when the last fetch succeeded. The hooks always set it. */
|
|
22
|
+
readonly refreshError?: ApiError | null | undefined;
|
|
21
23
|
} | {
|
|
22
24
|
readonly status: "data";
|
|
23
25
|
readonly data: T;
|
|
@@ -25,6 +27,8 @@ export type DataState<T> = {
|
|
|
25
27
|
readonly refresh: () => void;
|
|
26
28
|
readonly refetch: () => void;
|
|
27
29
|
readonly fulfilledTimeStamp?: number | undefined;
|
|
30
|
+
/** A failed refetch while these rows stay on screen; null when the last fetch succeeded. The hooks always set it. */
|
|
31
|
+
readonly refreshError?: ApiError | null | undefined;
|
|
28
32
|
};
|
|
29
33
|
/** The members of an RTK Query hook result that useDataState reads. */
|
|
30
34
|
export interface QueryResultLike<T> {
|
|
@@ -84,8 +88,8 @@ export interface InfiniteListPaging extends PagedListPaging {
|
|
|
84
88
|
/**
|
|
85
89
|
* Rules, in order:
|
|
86
90
|
* 1. currentData is not undefined: "empty" when isEmpty says so, else "data"; refreshing is isFetching; refresh is refetch;
|
|
87
|
-
* fulfilledTimeStamp is passed through.
|
|
88
|
-
* A failed refetch that still holds currentData stays here
|
|
91
|
+
* fulfilledTimeStamp is passed through, still the last successful fetch's time.
|
|
92
|
+
* A failed refetch that still holds currentData stays here, with the failure in refreshError (null otherwise).
|
|
89
93
|
* 2. error is set: "error", with error passed through extractApiError and retry calling refetch.
|
|
90
94
|
* It wins over a kept previous result, so a failed new query never shows the old arguments' rows as its answer.
|
|
91
95
|
* 3. isUninitialized is true: "idle", the query is skipped and the block draws nothing.
|
|
@@ -27,7 +27,7 @@ export interface SaveWithVersionOptions<R, F> {
|
|
|
27
27
|
toForm: (record: R) => F;
|
|
28
28
|
/** Reads the record as the server holds it now. */
|
|
29
29
|
read: () => Promise<VersionedRead<R>>;
|
|
30
|
-
/** Sends `form` with `version` as If-Match. Rejects with the ApiError
|
|
30
|
+
/** Sends `form` with `version` as If-Match. Rejects with the failed reply: an ApiError, or the raw axios error a service call throws. */
|
|
31
31
|
save: (form: F, version: string) => Promise<void>;
|
|
32
32
|
}
|
|
33
33
|
export type SaveWithVersionResult<R> = {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Middleware, MiddlewareAPI, UnknownAction } from "@reduxjs/toolkit";
|
|
1
|
+
import type { Middleware, MiddlewareAPI, ThunkDispatch, UnknownAction } from "@reduxjs/toolkit";
|
|
2
2
|
import { type ApiError } from "../errors/extractApiError";
|
|
3
3
|
/**
|
|
4
4
|
* Toasts every rejected thunk and every failed RTK Query call, so no screen has to remember
|
|
@@ -32,11 +32,13 @@ import { type ApiError } from "../errors/extractApiError";
|
|
|
32
32
|
export type ShowErrorToast = (message: string, error: ApiError) => void;
|
|
33
33
|
/** What `onRejected` decides for one rejection: `'toast'`, `'silent'`, or nothing for the default rules. */
|
|
34
34
|
export type RejectionDecision = "toast" | "silent" | undefined;
|
|
35
|
+
/** The store's dispatch as the middleware sees it: plain actions and thunks. */
|
|
36
|
+
type StoreDispatch = ThunkDispatch<unknown, unknown, UnknownAction>;
|
|
35
37
|
/**
|
|
36
38
|
* The product's hook into every rejection the middleware sees. `api` is the store's
|
|
37
|
-
* `dispatch` and `getState`, for a side effect that reads or updates state.
|
|
39
|
+
* `dispatch` and `getState`, for a side effect that reads or updates state; its dispatch takes thunks.
|
|
38
40
|
*/
|
|
39
|
-
export type OnRejected = (action: UnknownAction, error: ApiError, api: MiddlewareAPI) => RejectionDecision;
|
|
41
|
+
export type OnRejected = (action: UnknownAction, error: ApiError, api: MiddlewareAPI<StoreDispatch>) => RejectionDecision;
|
|
40
42
|
export interface ErrorToastOptions {
|
|
41
43
|
showToast: ShowErrorToast;
|
|
42
44
|
/** Server `code` values a screen answers in its own way (a paywall, a terms gate). */
|
|
@@ -51,6 +53,6 @@ export interface ErrorToastOptions {
|
|
|
51
53
|
type Dict = Record<string, unknown>;
|
|
52
54
|
/** Is this a rejected createAsyncThunk or RTK Query action that asked not to be toasted? */
|
|
53
55
|
export declare const isSilentRejection: (meta: Dict) => boolean;
|
|
54
|
-
export declare function errorToastMiddleware(options: ErrorToastOptions): Middleware
|
|
56
|
+
export declare function errorToastMiddleware(options: ErrorToastOptions): Middleware<object, unknown, StoreDispatch>;
|
|
55
57
|
export {};
|
|
56
58
|
//# sourceMappingURL=errorToastMiddleware.d.ts.map
|
|
@@ -3,6 +3,8 @@ declare module "axios" {
|
|
|
3
3
|
interface AxiosRequestConfig {
|
|
4
4
|
/** When true, the library's response-error interceptors do not log this request's failure. */
|
|
5
5
|
skipErrorLog?: boolean | undefined;
|
|
6
|
+
/** Statuses the caller handles itself: a failure with one still rejects, but the library logs it at debug instead of error. */
|
|
7
|
+
expectedStatuses?: readonly number[] | undefined;
|
|
6
8
|
/**
|
|
7
9
|
* The request ends the current session and answers with a new one in the refresh
|
|
8
10
|
* response's shape (a workspace switch, a reissue after a security change). userClient
|
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
import { type OperationEntry, type OperationShape } from "@webority/api-contract/call";
|
|
1
|
+
import { type ContractCallOptions, type OperationEntry, type OperationShape } from "@webority/api-contract/call";
|
|
2
2
|
import type { AxiosInstance, AxiosRequestConfig } from "axios";
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Per-call options: an abort signal, a timeout, the client's retry override (`false`, or a policy such as `{ retries: 1 }`),
|
|
5
|
+
* call headers the contract does not declare, `skipErrorLog` and `expectedStatuses`. buildContractRequest validates the
|
|
6
|
+
* headers and the two error options, and throws ContractCallError on an invalid value before anything is sent.
|
|
7
|
+
*/
|
|
8
|
+
export type ContractCallConfig = Pick<AxiosRequestConfig, "signal" | "timeout" | "retry"> & ContractCallOptions;
|
|
5
9
|
export type ContractCaller<TOperations extends {
|
|
6
10
|
readonly [K in keyof TOperations]: OperationShape;
|
|
7
11
|
}> = <TId extends keyof TOperations & string>(id: TId, request: TOperations[TId]["request"], config?: ContractCallConfig) => Promise<TOperations[TId]["response"]>;
|
|
@@ -13,6 +13,12 @@ export interface ApiError {
|
|
|
13
13
|
traceId: string | null;
|
|
14
14
|
/** What the server or runtime actually said. For the logger, never for the screen. */
|
|
15
15
|
diagnostic: string | null;
|
|
16
|
+
/**
|
|
17
|
+
* Every member of the problem body other than `type`, `title`, `status`, `detail`, `instance`,
|
|
18
|
+
* `code`, `errors` and `traceId`, as the server sent it. Empty when the body had none or no answer
|
|
19
|
+
* arrived. Read a documented member through a type guard; never render one.
|
|
20
|
+
*/
|
|
21
|
+
extensions: Readonly<Record<string, unknown>>;
|
|
16
22
|
/** The request address the failed call was sent to. For the logger and the caller, never the screen. */
|
|
17
23
|
requestUrl?: string | undefined;
|
|
18
24
|
/** The Account-Id the failed call was sent with. For the logger and the caller, never the screen. */
|
|
@@ -5,11 +5,16 @@ export interface PickedFile {
|
|
|
5
5
|
size?: number | undefined;
|
|
6
6
|
meta?: Record<string, unknown> | undefined;
|
|
7
7
|
}
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* One way to pick files. `F` is what `pick` resolves: a source that prepares its
|
|
10
|
+
* files (resized, renamed) names its own file type, and a picker hands that same
|
|
11
|
+
* object to its `onPick`.
|
|
12
|
+
*/
|
|
13
|
+
export interface PickerSource<F extends PickedFile = PickedFile> {
|
|
9
14
|
key: string;
|
|
10
15
|
label: string;
|
|
11
16
|
description?: string | undefined;
|
|
12
|
-
pick: () => Promise<
|
|
17
|
+
pick: () => Promise<F[]>;
|
|
13
18
|
}
|
|
14
19
|
export interface PhotoOptions {
|
|
15
20
|
maxEdgePx?: number | undefined;
|
|
@@ -40,6 +40,11 @@ export interface ApiExtraOptions {
|
|
|
40
40
|
silent?: boolean | undefined;
|
|
41
41
|
expectedStatuses?: number[] | undefined;
|
|
42
42
|
paramsFormat?: ParamsFormat | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* How many times the client resends a failed call that its retry rule allows, in place of the
|
|
45
|
+
* client's `retries` setting; `0` sends it once. RTK Query's own `retry()` reads the same name.
|
|
46
|
+
*/
|
|
47
|
+
maxRetries?: number | undefined;
|
|
43
48
|
}
|
|
44
49
|
export declare const strongEntityTag: (value: unknown) => string | undefined;
|
|
45
50
|
/** The `If-Match` header value for a version: the version in quotes, as an ETag is sent. */
|
|
@@ -18,6 +18,8 @@ export type DataState<T> = {
|
|
|
18
18
|
readonly refresh: () => void;
|
|
19
19
|
readonly refetch: () => void;
|
|
20
20
|
readonly fulfilledTimeStamp?: number | undefined;
|
|
21
|
+
/** A failed refetch while this result stays on screen; null when the last fetch succeeded. The hooks always set it. */
|
|
22
|
+
readonly refreshError?: ApiError | null | undefined;
|
|
21
23
|
} | {
|
|
22
24
|
readonly status: "data";
|
|
23
25
|
readonly data: T;
|
|
@@ -25,6 +27,8 @@ export type DataState<T> = {
|
|
|
25
27
|
readonly refresh: () => void;
|
|
26
28
|
readonly refetch: () => void;
|
|
27
29
|
readonly fulfilledTimeStamp?: number | undefined;
|
|
30
|
+
/** A failed refetch while these rows stay on screen; null when the last fetch succeeded. The hooks always set it. */
|
|
31
|
+
readonly refreshError?: ApiError | null | undefined;
|
|
28
32
|
};
|
|
29
33
|
/** The members of an RTK Query hook result that useDataState reads. */
|
|
30
34
|
export interface QueryResultLike<T> {
|
|
@@ -84,8 +88,8 @@ export interface InfiniteListPaging extends PagedListPaging {
|
|
|
84
88
|
/**
|
|
85
89
|
* Rules, in order:
|
|
86
90
|
* 1. currentData is not undefined: "empty" when isEmpty says so, else "data"; refreshing is isFetching; refresh is refetch;
|
|
87
|
-
* fulfilledTimeStamp is passed through.
|
|
88
|
-
* A failed refetch that still holds currentData stays here
|
|
91
|
+
* fulfilledTimeStamp is passed through, still the last successful fetch's time.
|
|
92
|
+
* A failed refetch that still holds currentData stays here, with the failure in refreshError (null otherwise).
|
|
89
93
|
* 2. error is set: "error", with error passed through extractApiError and retry calling refetch.
|
|
90
94
|
* It wins over a kept previous result, so a failed new query never shows the old arguments' rows as its answer.
|
|
91
95
|
* 3. isUninitialized is true: "idle", the query is skipped and the block draws nothing.
|
|
@@ -27,7 +27,7 @@ export interface SaveWithVersionOptions<R, F> {
|
|
|
27
27
|
toForm: (record: R) => F;
|
|
28
28
|
/** Reads the record as the server holds it now. */
|
|
29
29
|
read: () => Promise<VersionedRead<R>>;
|
|
30
|
-
/** Sends `form` with `version` as If-Match. Rejects with the ApiError
|
|
30
|
+
/** Sends `form` with `version` as If-Match. Rejects with the failed reply: an ApiError, or the raw axios error a service call throws. */
|
|
31
31
|
save: (form: F, version: string) => Promise<void>;
|
|
32
32
|
}
|
|
33
33
|
export type SaveWithVersionResult<R> = {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Middleware, MiddlewareAPI, UnknownAction } from "@reduxjs/toolkit";
|
|
1
|
+
import type { Middleware, MiddlewareAPI, ThunkDispatch, UnknownAction } from "@reduxjs/toolkit";
|
|
2
2
|
import { type ApiError } from "../errors/extractApiError.js";
|
|
3
3
|
/**
|
|
4
4
|
* Toasts every rejected thunk and every failed RTK Query call, so no screen has to remember
|
|
@@ -32,11 +32,13 @@ import { type ApiError } from "../errors/extractApiError.js";
|
|
|
32
32
|
export type ShowErrorToast = (message: string, error: ApiError) => void;
|
|
33
33
|
/** What `onRejected` decides for one rejection: `'toast'`, `'silent'`, or nothing for the default rules. */
|
|
34
34
|
export type RejectionDecision = "toast" | "silent" | undefined;
|
|
35
|
+
/** The store's dispatch as the middleware sees it: plain actions and thunks. */
|
|
36
|
+
type StoreDispatch = ThunkDispatch<unknown, unknown, UnknownAction>;
|
|
35
37
|
/**
|
|
36
38
|
* The product's hook into every rejection the middleware sees. `api` is the store's
|
|
37
|
-
* `dispatch` and `getState`, for a side effect that reads or updates state.
|
|
39
|
+
* `dispatch` and `getState`, for a side effect that reads or updates state; its dispatch takes thunks.
|
|
38
40
|
*/
|
|
39
|
-
export type OnRejected = (action: UnknownAction, error: ApiError, api: MiddlewareAPI) => RejectionDecision;
|
|
41
|
+
export type OnRejected = (action: UnknownAction, error: ApiError, api: MiddlewareAPI<StoreDispatch>) => RejectionDecision;
|
|
40
42
|
export interface ErrorToastOptions {
|
|
41
43
|
showToast: ShowErrorToast;
|
|
42
44
|
/** Server `code` values a screen answers in its own way (a paywall, a terms gate). */
|
|
@@ -51,6 +53,6 @@ export interface ErrorToastOptions {
|
|
|
51
53
|
type Dict = Record<string, unknown>;
|
|
52
54
|
/** Is this a rejected createAsyncThunk or RTK Query action that asked not to be toasted? */
|
|
53
55
|
export declare const isSilentRejection: (meta: Dict) => boolean;
|
|
54
|
-
export declare function errorToastMiddleware(options: ErrorToastOptions): Middleware
|
|
56
|
+
export declare function errorToastMiddleware(options: ErrorToastOptions): Middleware<object, unknown, StoreDispatch>;
|
|
55
57
|
export {};
|
|
56
58
|
//# sourceMappingURL=errorToastMiddleware.d.ts.map
|
|
@@ -3,6 +3,8 @@ declare module "axios" {
|
|
|
3
3
|
interface AxiosRequestConfig {
|
|
4
4
|
/** When true, the library's response-error interceptors do not log this request's failure. */
|
|
5
5
|
skipErrorLog?: boolean | undefined;
|
|
6
|
+
/** Statuses the caller handles itself: a failure with one still rejects, but the library logs it at debug instead of error. */
|
|
7
|
+
expectedStatuses?: readonly number[] | undefined;
|
|
6
8
|
/**
|
|
7
9
|
* The request ends the current session and answers with a new one in the refresh
|
|
8
10
|
* response's shape (a workspace switch, a reissue after a security change). userClient
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.158.0",
|
|
4
4
|
"description": "Platform layer for Webority React Native apps: HTTP clients, auth/token storage, config, logging, formatters, validators, network status, permissions, storage, version checks and over-the-air updates. No UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react-native",
|
|
@@ -399,7 +399,7 @@
|
|
|
399
399
|
}
|
|
400
400
|
},
|
|
401
401
|
"dependencies": {
|
|
402
|
-
"@webority/api-contract": "0.
|
|
402
|
+
"@webority/api-contract": "0.158.0",
|
|
403
403
|
"axios": "^1.19.0",
|
|
404
404
|
"libphonenumber-js": "^1.12.41"
|
|
405
405
|
},
|