@webority/web-core 0.155.0 → 0.156.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 +23 -1
- package/dist/api/contractCaller.js +1 -1
- package/dist/api-contract/dist/call.js +1 -1
- package/dist/index.js +1 -1
- package/dist/query/contractQuery.js +1 -0
- package/dist/query/dataState.js +1 -1
- package/dist/query/index.js +1 -1
- package/dist/types/api/contractCaller.d.ts +4 -2
- package/dist/types/api/index.d.ts +1 -1
- package/dist/types/query/contractQuery.d.ts +17 -0
- package/dist/types/query/dataState.d.ts +5 -2
- package/dist/types/query/index.d.ts +2 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -485,7 +485,29 @@ const page = await call("Standards_List", { query: { page: 1 } }, { signal, time
|
|
|
485
485
|
```
|
|
486
486
|
|
|
487
487
|
The caller adds no catch: a failure reaches the caller as the client's curated error. `signal` and
|
|
488
|
-
`timeout` are optional and go to the request as they are.
|
|
488
|
+
`timeout` are optional and go to the request as they are. A list in `query` goes out as repeated keys:
|
|
489
|
+
`{ query: { ids: [1, 2] } }` sends `ids=1&ids=2`. The third argument takes `signal`, `timeout` and `retry`
|
|
490
|
+
(`false`, or a policy such as `{ retries: 1 }`). `client` may be any object with axios's `request` method.
|
|
491
|
+
|
|
492
|
+
### RTK Query endpoints from a contract
|
|
493
|
+
|
|
494
|
+
`createContractQuery` builds the request for an RTK Query endpoint from the same contract, by operation id.
|
|
495
|
+
The endpoint's `query` returns it, and the shared base query sends it, so toasts, retry, silent and ETag meta
|
|
496
|
+
work as for a hand-written endpoint. File downloads stay on the contract caller: `contractQuery` refuses a
|
|
497
|
+
blob operation.
|
|
498
|
+
|
|
499
|
+
```ts
|
|
500
|
+
import { type ContractResponse, createContractQuery } from "@webority/web-core";
|
|
501
|
+
import { operations, type Operations } from "./api/contract";
|
|
502
|
+
|
|
503
|
+
const contractQuery = createContractQuery<Operations>(operations);
|
|
504
|
+
|
|
505
|
+
endpoints: (builder) => ({
|
|
506
|
+
getPages: builder.query<ContractResponse<Operations, "getPages">, string[]>({
|
|
507
|
+
query: (pageIds) => contractQuery("getPages", { query: { pageIds } }),
|
|
508
|
+
}),
|
|
509
|
+
});
|
|
510
|
+
```
|
|
489
511
|
|
|
490
512
|
## Develop
|
|
491
513
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildContractRequest as e}from"../api-contract/dist/call.js";var t=(t,n)=>async(r,i,a)=>{let o=e(n[r],i);return(await t.request({method:o.method,url:o.url
|
|
1
|
+
import{buildContractRequest as e}from"../api-contract/dist/call.js";var t=(t,n)=>async(r,i,a)=>{let o=e(n[r],i);return(await t.request({method:o.method,url:o.url,...o.headers!==void 0&&{headers:o.headers},data:o.data,responseType:o.responseType,...a?.signal!==void 0&&{signal:a.signal},...a?.timeout!==void 0&&{timeout:a.timeout},...a?.retry!==void 0&&{retry:a.retry}})).data};export{t as createContractCaller};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g;function n(n,
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g,n=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e));function r(e){let t=[];for(let[r,i]of Object.entries(e??{})){if(i==null)continue;let e=encodeURIComponent(r);for(let r of Array.isArray(i)?i:[i])r!=null&&t.push(`${e}=${n(r)}`)}return t.join(`&`)}function i(n,i){let a=n.path.replace(t,(t,r)=>{let a=i.path?.[r],o=a===void 0?``:String(a);if(o===``)throw new e(`${n.method} ${n.path} needs a non-empty path value for "${r}"`);if(o===`.`||o===`..`)throw new e(`${n.method} ${n.path} needs a path value for "${r}" other than "." or ".."`);return encodeURIComponent(o)}),o=r(i.query);return{method:n.method,url:o===``?a:`${a}?${o}`,headers:i.headers,data:i.body,responseType:n.replyKind===`blob`?`blob`:`json`}}export{e as ContractCallError,i as buildContractRequest};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DEFAULT_BUILD_CHECK_INTERVAL_MS as e,DEFAULT_LOG_LEVEL as t,DEFAULT_RETRIES as n,DEFAULT_TIMEOUT_MS as r,DEFAULT_VERSION_URL as i,getConfig as a,getConfigValue as o,resetConfig as s,setConfig as c}from"./config/index.js";import{TRACEPARENT_HEADER as l,applyRequestDefaults as u,newTraceparent as d}from"./api/requestDefaults.js";import{Logger as f,configureLogger as p,getDeviceContext as m,setDeviceContext as h,setRemoteLogger as g}from"./logger/logger.js";import{decodeJWT as _,getJWTExpiry as v,isJWTExpired as y}from"./auth/jwt.js";import{ACCESS_TOKEN_KEY as b,LEGACY_REFRESH_TOKEN_LIFETIME_MS as x,REFRESH_TOKEN_KEY as S,SESSION_USER_KEY as C,addSessionEndedListener as w,clearSession as T,getKeepSignedIn as E,getSessionUser as D,getToken as O,hasSession as k,hasSessionEndedInTab as A,removeSessionUser as j,removeToken as M,setKeepSignedIn as N,setLegacyTokenKeys as P,storeSessionUser as F,storeToken as I}from"./auth/authStore.js";import{addNetworkStatusListener as L,getNetworkStatus as R,setNetworkStatusImplementation as z,useNetworkStatus as B}from"./network/networkStatus.js";import{ACCOUNT_ID_HEADER as V,CLIENT_BUILD_HEADER as H,CLIENT_KIND as U,CLIENT_KIND_HEADER as W,getClientBuild as G}from"./api/clientHeaders.js";import{initWebority as K}from"./initSDK.js";import{DESIGN_SAMPLE_HEADER as q,DESIGN_SAMPLE_QUERY_KEY as J,DESIGN_SAMPLE_STORAGE_KEY as Y,applyDesignSample as X,readDesignSampleTicket as Z}from"./api/designSample.js";import{MIN_APP_VERSION_HEADER as Q,addMinAppVersionListener as $,getMinAppVersion as ee}from"./api/minAppVersion.js";import{WORKSPACE_CHANGED_CODE as te,WorkspaceChangedError as ne,isWorkspaceChangedError as re}from"./api/workspaceChanged.js";import{IDEMPOTENCY_KEY_HEADER as ie,attachRetry as ae,isNeverSentError as oe,isRetryableFailure as se,isRetryableStatus as ce,retryAfterMs as le}from"./api/retry.js";import{REFRESH_LOCK_NAME as ue,withCrossTabRefreshLock as de}from"./api/crossTabRefreshLock.js";import fe from"./api/publicClient.js";import{SESSION_EXPIRED_CODE as pe,SESSION_REVOKED_CODE as me,injectStore as he,injectUserAuth as ge,refreshAccessToken as _e,resetRefreshState as ve}from"./api/tokenRefresh.js";import ye,{RequestOfflineError as be}from"./api/userClient.js";import{initUserAuth as xe}from"./initUserAuth.js";import{readBlobErrorBody as Se}from"./api/blobErrorBody.js";import{createContractCaller as Ce}from"./api/contractCaller.js";import{CONTRACT_ERROR_CODE as we,NETWORK_CODE as Te,OFFLINE_CODE as Ee,OFFLINE_MESSAGE as De,REQUEST_CANCELED_CODE as Oe,SERVER_FAILURE_MESSAGE as ke,TIMEOUT_CODE as Ae,TIMEOUT_MESSAGE as je,UNEXPECTED_MESSAGE as Me,UNREACHABLE_MESSAGE as Ne,apiErrorMessage as Pe,extractApiError as Fe,isApiError as Ie,isNoResponse as Le,toFieldPath as Re}from"./errors/extractApiError.js";import{parseResponse as ze}from"./errors/parseResponse.js";import{contentDispositionFileName as Be,downloadFile as Ve}from"./api/downloadFile.js";import{newIdempotencyKey as He}from"./api/idempotencyKey.js";import{configureFormatters as Ue,getFormatterConfig as We}from"./formatters/formatConfig.js";import{formatCurrency as Ge}from"./formatters/currency.js";import{addDays as Ke}from"./formatters/dateMath.js";import{formatDate as qe,formatDateTime as Je,formatMinor as Ye,formatNumber as Xe,formatPercent as Ze,formatRelative as Qe,formatTime as $e}from"./formatters/house.js";import{staticUrl as et}from"./static/index.js";import{createApiBaseQuery as tt}from"./query/apiBaseQuery.js";import{APP_API_DEFAULTS as
|
|
1
|
+
import{DEFAULT_BUILD_CHECK_INTERVAL_MS as e,DEFAULT_LOG_LEVEL as t,DEFAULT_RETRIES as n,DEFAULT_TIMEOUT_MS as r,DEFAULT_VERSION_URL as i,getConfig as a,getConfigValue as o,resetConfig as s,setConfig as c}from"./config/index.js";import{TRACEPARENT_HEADER as l,applyRequestDefaults as u,newTraceparent as d}from"./api/requestDefaults.js";import{Logger as f,configureLogger as p,getDeviceContext as m,setDeviceContext as h,setRemoteLogger as g}from"./logger/logger.js";import{decodeJWT as _,getJWTExpiry as v,isJWTExpired as y}from"./auth/jwt.js";import{ACCESS_TOKEN_KEY as b,LEGACY_REFRESH_TOKEN_LIFETIME_MS as x,REFRESH_TOKEN_KEY as S,SESSION_USER_KEY as C,addSessionEndedListener as w,clearSession as T,getKeepSignedIn as E,getSessionUser as D,getToken as O,hasSession as k,hasSessionEndedInTab as A,removeSessionUser as j,removeToken as M,setKeepSignedIn as N,setLegacyTokenKeys as P,storeSessionUser as F,storeToken as I}from"./auth/authStore.js";import{addNetworkStatusListener as L,getNetworkStatus as R,setNetworkStatusImplementation as z,useNetworkStatus as B}from"./network/networkStatus.js";import{ACCOUNT_ID_HEADER as V,CLIENT_BUILD_HEADER as H,CLIENT_KIND as U,CLIENT_KIND_HEADER as W,getClientBuild as G}from"./api/clientHeaders.js";import{initWebority as K}from"./initSDK.js";import{DESIGN_SAMPLE_HEADER as q,DESIGN_SAMPLE_QUERY_KEY as J,DESIGN_SAMPLE_STORAGE_KEY as Y,applyDesignSample as X,readDesignSampleTicket as Z}from"./api/designSample.js";import{MIN_APP_VERSION_HEADER as Q,addMinAppVersionListener as $,getMinAppVersion as ee}from"./api/minAppVersion.js";import{WORKSPACE_CHANGED_CODE as te,WorkspaceChangedError as ne,isWorkspaceChangedError as re}from"./api/workspaceChanged.js";import{IDEMPOTENCY_KEY_HEADER as ie,attachRetry as ae,isNeverSentError as oe,isRetryableFailure as se,isRetryableStatus as ce,retryAfterMs as le}from"./api/retry.js";import{REFRESH_LOCK_NAME as ue,withCrossTabRefreshLock as de}from"./api/crossTabRefreshLock.js";import fe from"./api/publicClient.js";import{SESSION_EXPIRED_CODE as pe,SESSION_REVOKED_CODE as me,injectStore as he,injectUserAuth as ge,refreshAccessToken as _e,resetRefreshState as ve}from"./api/tokenRefresh.js";import ye,{RequestOfflineError as be}from"./api/userClient.js";import{initUserAuth as xe}from"./initUserAuth.js";import{readBlobErrorBody as Se}from"./api/blobErrorBody.js";import{createContractCaller as Ce}from"./api/contractCaller.js";import{CONTRACT_ERROR_CODE as we,NETWORK_CODE as Te,OFFLINE_CODE as Ee,OFFLINE_MESSAGE as De,REQUEST_CANCELED_CODE as Oe,SERVER_FAILURE_MESSAGE as ke,TIMEOUT_CODE as Ae,TIMEOUT_MESSAGE as je,UNEXPECTED_MESSAGE as Me,UNREACHABLE_MESSAGE as Ne,apiErrorMessage as Pe,extractApiError as Fe,isApiError as Ie,isNoResponse as Le,toFieldPath as Re}from"./errors/extractApiError.js";import{parseResponse as ze}from"./errors/parseResponse.js";import{contentDispositionFileName as Be,downloadFile as Ve}from"./api/downloadFile.js";import{newIdempotencyKey as He}from"./api/idempotencyKey.js";import{configureFormatters as Ue,getFormatterConfig as We}from"./formatters/formatConfig.js";import{formatCurrency as Ge}from"./formatters/currency.js";import{addDays as Ke}from"./formatters/dateMath.js";import{formatDate as qe,formatDateTime as Je,formatMinor as Ye,formatNumber as Xe,formatPercent as Ze,formatRelative as Qe,formatTime as $e}from"./formatters/house.js";import{staticUrl as et}from"./static/index.js";import{createApiBaseQuery as tt}from"./query/apiBaseQuery.js";import{createContractQuery as nt}from"./query/contractQuery.js";import{APP_API_DEFAULTS as rt,createAppApi as it}from"./query/createAppApi.js";import{useDataState as at,useInfiniteDataState as ot}from"./query/dataState.js";import{entityTagOf as st,saveWithVersion as ct,versionOf as lt,withIfMatch as ut}from"./query/entityVersion.js";import{setupApiListeners as dt}from"./query/listeners.js";import{LIST_QUERY_RESERVED as ft,SEARCH_PARAM as pt,buildListQuery as mt,emptyFacetValue as ht,isFacetActive as gt,listQueryParamNames as _t,parseListQuery as vt}from"./query/listQuery.js";import{getNextPageParam as yt,getPreviousPageParam as bt,hasNextPage as xt,hasPreviousPage as St}from"./query/paging.js";import{LIST_TAG_ID as Ct,itemTag as wt,listTag as Tt,providesList as Et,providesPagedList as Dt}from"./query/tags.js";import{useListQuery as Ot}from"./query/useListQuery.js";import{errorToastMiddleware as kt,isSilentRejection as At}from"./redux/errorToastMiddleware.js";import{createRootReducer as jt,resetState as Mt}from"./redux/rootReducer.js";import{SERIALIZABLE_IGNORED_ACTION_PATHS as Nt}from"./redux/serializableCheck.js";import{hasRecentlyReloaded as Pt,importWithReload as Ft,isChunkLoadError as It,lazyWithReload as Lt,markReloaded as Rt}from"./router/chunkReload.js";import{classifyRouteError as zt,useRouteErrorReport as Bt}from"./router/routeError.js";import{ErrorBoundary as Vt}from"./router/ErrorBoundary.js";import{hasPermission as Ht}from"./router/permissions.js";import{RETURN_TO_PARAM as Ut,buildLoginPath as Wt,getReturnTo as Gt,toSafeReturnTo as Kt}from"./router/returnTo.js";import{PublicOnly as qt,RequireAuth as Jt,RequirePermission as Yt}from"./router/guards.js";import{publicOnly as Xt,requireAuth as Zt,requirePermission as Qt,withGuards as $t}from"./router/loaders.js";import{defineRouteTable as en}from"./router/routeTable.js";import{Storage as tn,isStorageAvailable as nn,setStorageImplementation as rn,syncSessionStorage as an,syncStorage as on}from"./storage/index.js";import{isBuildBelowMinimum as sn,parseBuildNumber as cn}from"./versionCheck/buildNumber.js";import{addDeployedBuildListener as ln,getNewerDeployedBuild as un,startDeployedBuildCheck as dn}from"./versionCheck/deployedBuild.js";import{installReloadOnNavigate as fn,isUpdateAvailable as pn,useVersionCheck as mn}from"./versionCheck/index.js";export{b as ACCESS_TOKEN_KEY,V as ACCOUNT_ID_HEADER,rt as APP_API_DEFAULTS,H as CLIENT_BUILD_HEADER,U as CLIENT_KIND,W as CLIENT_KIND_HEADER,we as CONTRACT_ERROR_CODE,e as DEFAULT_BUILD_CHECK_INTERVAL_MS,t as DEFAULT_LOG_LEVEL,n as DEFAULT_RETRIES,r as DEFAULT_TIMEOUT_MS,i as DEFAULT_VERSION_URL,q as DESIGN_SAMPLE_HEADER,J as DESIGN_SAMPLE_QUERY_KEY,Y as DESIGN_SAMPLE_STORAGE_KEY,Vt as ErrorBoundary,ie as IDEMPOTENCY_KEY_HEADER,x as LEGACY_REFRESH_TOKEN_LIFETIME_MS,ft as LIST_QUERY_RESERVED,Ct as LIST_TAG_ID,f as Logger,Q as MIN_APP_VERSION_HEADER,Te as NETWORK_CODE,Ee as OFFLINE_CODE,De as OFFLINE_MESSAGE,qt as PublicOnly,ue as REFRESH_LOCK_NAME,S as REFRESH_TOKEN_KEY,Oe as REQUEST_CANCELED_CODE,Ut as RETURN_TO_PARAM,be as RequestOfflineError,Jt as RequireAuth,Yt as RequirePermission,pt as SEARCH_PARAM,Nt as SERIALIZABLE_IGNORED_ACTION_PATHS,ke as SERVER_FAILURE_MESSAGE,pe as SESSION_EXPIRED_CODE,me as SESSION_REVOKED_CODE,C as SESSION_USER_KEY,tn as Storage,Ae as TIMEOUT_CODE,je as TIMEOUT_MESSAGE,l as TRACEPARENT_HEADER,Me as UNEXPECTED_MESSAGE,Ne as UNREACHABLE_MESSAGE,te as WORKSPACE_CHANGED_CODE,ne as WorkspaceChangedError,Ke as addDays,ln as addDeployedBuildListener,$ as addMinAppVersionListener,L as addNetworkStatusListener,w as addSessionEndedListener,Pe as apiErrorMessage,X as applyDesignSample,u as applyRequestDefaults,ae as attachRetry,mt as buildListQuery,Wt as buildLoginPath,zt as classifyRouteError,T as clearSession,Ue as configureFormatters,p as configureLogger,Be as contentDispositionFileName,tt as createApiBaseQuery,it as createAppApi,Ce as createContractCaller,nt as createContractQuery,jt as createRootReducer,_ as decodeJWT,en as defineRouteTable,Ve as downloadFile,ht as emptyFacetValue,st as entityTagOf,kt as errorToastMiddleware,Fe as extractApiError,Ge as formatCurrency,qe as formatDate,Je as formatDateTime,Ye as formatMinor,Xe as formatNumber,Ze as formatPercent,Qe as formatRelative,$e as formatTime,G as getClientBuild,a as getConfig,o as getConfigValue,m as getDeviceContext,We as getFormatterConfig,v as getJWTExpiry,E as getKeepSignedIn,ee as getMinAppVersion,R as getNetworkStatus,un as getNewerDeployedBuild,yt as getNextPageParam,bt as getPreviousPageParam,Gt as getReturnTo,D as getSessionUser,O as getToken,xt as hasNextPage,Ht as hasPermission,St as hasPreviousPage,Pt as hasRecentlyReloaded,k as hasSession,A as hasSessionEndedInTab,Ft as importWithReload,xe as initUserAuth,K as initWebority,he as injectStore,ge as injectUserAuth,fn as installReloadOnNavigate,Ie as isApiError,sn as isBuildBelowMinimum,It as isChunkLoadError,gt as isFacetActive,y as isJWTExpired,oe as isNeverSentError,Le as isNoResponse,se as isRetryableFailure,ce as isRetryableStatus,At as isSilentRejection,nn as isStorageAvailable,pn as isUpdateAvailable,re as isWorkspaceChangedError,wt as itemTag,Lt as lazyWithReload,_t as listQueryParamNames,Tt as listTag,Rt as markReloaded,He as newIdempotencyKey,d as newTraceparent,cn as parseBuildNumber,vt as parseListQuery,ze as parseResponse,Et as providesList,Dt as providesPagedList,fe as publicClient,Xt as publicOnly,Se as readBlobErrorBody,Z as readDesignSampleTicket,_e as refreshAccessToken,j as removeSessionUser,M as removeToken,Zt as requireAuth,Qt as requirePermission,s as resetConfig,ve as resetRefreshState,Mt as resetState,le as retryAfterMs,ct as saveWithVersion,c as setConfig,h as setDeviceContext,N as setKeepSignedIn,P as setLegacyTokenKeys,z as setNetworkStatusImplementation,g as setRemoteLogger,rn as setStorageImplementation,dt as setupApiListeners,dn as startDeployedBuildCheck,et as staticUrl,F as storeSessionUser,I as storeToken,an as syncSessionStorage,on as syncStorage,Re as toFieldPath,Kt as toSafeReturnTo,at as useDataState,ot as useInfiniteDataState,Ot as useListQuery,B as useNetworkStatus,Bt as useRouteErrorReport,mn as useVersionCheck,ye as userClient,lt as versionOf,de as withCrossTabRefreshLock,$t as withGuards,ut as withIfMatch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ContractCallError as e,buildContractRequest as t}from"../api-contract/dist/call.js";var n=n=>(r,i,a)=>{let o=n[r],s=t(o,i);if(o.replyKind===`blob`)throw new e(`${o.method} ${o.path} replies with a file; a file download goes through the contract caller, not a store query`);if(s.method===`QUERY`)throw new e(`${o.method} ${o.path} uses the QUERY method, which the base query does not send`);return{...a,url:s.url,method:s.method,...s.data!==void 0&&{data:s.data},...s.headers!==void 0&&{headers:s.headers}}};export{n as createContractQuery};
|
package/dist/query/dataState.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractApiError as e}from"../errors/extractApiError.js";import{useMemo as t}from"react";function n(n,i){let{currentData:a,error:o,isFetching:s,isUninitialized:c,refetch:l,fulfilledTimeStamp:u}=n,d=i?.keepPreviousData===!0?n.data:void 0,f=i?.isEmpty??r;return t(()=>{let t=()=>{l()},n=e=>f(e)?{status:`empty`,refreshing:s,refresh:t,refetch:t,fulfilledTimeStamp:u}:{status:`data`,data:e,refreshing:s,refresh:t,refetch:t,fulfilledTimeStamp:u};return a===void 0?o===void 0?c===!0?{status:`idle`}:d===void 0?{status:`loading`,refetch:t}:n(d):{status:`error`,error:e(o),retry:t,refetch:t}:n(a)},[a,d,o,s,c,l,f,u])}var r=e=>Array.isArray(e)?e.length===0:typeof e==`object`&&e&&`items`in e&&Array.isArray(e.items)?e.items.length===0:!1;function i(n){let{currentData:r,error:i,isFetching:a,isFetchingNextPage:o,hasNextPage:s,isError:c,isFetchNextPageError:l,isUninitialized:u,refetch:d,fetchNextPage:f,fulfilledTimeStamp:p}=n,m=t(()=>(r?.pages??[]).flatMap(e=>e.items),[r]),h=t(()=>{let t=()=>{d()};if(r===void 0)return i===void 0?u===!0?{status:`idle`}:{status:`loading`,refetch:t}:{status:`error`,error:e(i),retry:t,refetch:t};let n=a&&!o;return m.length===0?{status:`empty`,refreshing:n,refresh:t,refetch:t,fulfilledTimeStamp:p}:{status:`data`,data:m,refreshing:n,refresh:t,refetch:t,fulfilledTimeStamp:p}},[r,i,a,o,u,m,d,p]),g=c&&l;return{state:h,paging:t(()=>({hasMore:s,loadingMore:o,errorMore:g?e(i):null,loadMore:()=>{s&&!o&&!g&&f()},retryMore:()=>{g&&f()}}),[s,o,g,i,f])}}export{n as useDataState,i as useInfiniteDataState};
|
|
1
|
+
import{extractApiError as e}from"../errors/extractApiError.js";import{useMemo as t}from"react";function n(n,i){let{currentData:a,error:o,isFetching:s,isUninitialized:c,refetch:l,fulfilledTimeStamp:u}=n,d=i?.keepPreviousData===!0?n.data:void 0,f=i?.isEmpty??r;return t(()=>{let t=()=>{l()},n=e=>f(e)?{status:`empty`,refreshing:s,refresh:t,refetch:t,fulfilledTimeStamp:u}:{status:`data`,data:e,refreshing:s,refresh:t,refetch:t,fulfilledTimeStamp:u};return a===void 0?o===void 0?c===!0?{status:`idle`}:d===void 0?{status:`loading`,refetch:t}:n(d):{status:`error`,error:e(o),retry:t,refetch:t}:n(a)},[a,d,o,s,c,l,f,u])}var r=e=>Array.isArray(e)?e.length===0:typeof e==`object`&&e&&`items`in e&&Array.isArray(e.items)?e.items.length===0:!1;function i(n){let{currentData:r,error:i,isFetching:a,isFetchingNextPage:o,hasNextPage:s,isError:c,isFetchNextPageError:l,isUninitialized:u,refetch:d,fetchNextPage:f,fulfilledTimeStamp:p}=n,m=t(()=>(r?.pages??[]).flatMap(e=>e.items),[r]),h=t(()=>{let t=()=>{d()};if(r===void 0)return i===void 0?u===!0?{status:`idle`}:{status:`loading`,refetch:t}:{status:`error`,error:e(i),retry:t,refetch:t};let n=a&&!o;return m.length===0?{status:`empty`,refreshing:n,refresh:t,refetch:t,fulfilledTimeStamp:p}:{status:`data`,data:m,refreshing:n,refresh:t,refetch:t,fulfilledTimeStamp:p}},[r,i,a,o,u,m,d,p]),g=c&&l===!0;return{state:h,paging:t(()=>({hasMore:s,loadingMore:o,errorMore:g?e(i):null,loadMore:()=>{s&&!o&&!g&&f()},retryMore:()=>{g&&f()}}),[s,o,g,i,f])}}export{n as useDataState,i as useInfiniteDataState};
|
package/dist/query/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createApiBaseQuery as e}from"./apiBaseQuery.js";import{APP_API_DEFAULTS as
|
|
1
|
+
import{createApiBaseQuery as e}from"./apiBaseQuery.js";import{createContractQuery as t}from"./contractQuery.js";import{APP_API_DEFAULTS as n,createAppApi as r}from"./createAppApi.js";import{useDataState as i,useInfiniteDataState as a}from"./dataState.js";import{entityTagOf as o,saveWithVersion as s,versionOf as c,withIfMatch as l}from"./entityVersion.js";import{setupApiListeners as u}from"./listeners.js";import{LIST_QUERY_RESERVED as d,SEARCH_PARAM as f,buildListQuery as p,emptyFacetValue as m,isFacetActive as h,listQueryParamNames as g,parseListQuery as _}from"./listQuery.js";import{getNextPageParam as v,getPreviousPageParam as y,hasNextPage as b,hasPreviousPage as x}from"./paging.js";import{LIST_TAG_ID as S,itemTag as C,listTag as w,providesList as T,providesPagedList as E}from"./tags.js";import{useListQuery as D}from"./useListQuery.js";export{n as APP_API_DEFAULTS,d as LIST_QUERY_RESERVED,S as LIST_TAG_ID,f as SEARCH_PARAM,p as buildListQuery,e as createApiBaseQuery,r as createAppApi,t as createContractQuery,m as emptyFacetValue,o as entityTagOf,v as getNextPageParam,y as getPreviousPageParam,b as hasNextPage,x as hasPreviousPage,h as isFacetActive,C as itemTag,g as listQueryParamNames,w as listTag,_ as parseListQuery,T as providesList,E as providesPagedList,s as saveWithVersion,u as setupApiListeners,i as useDataState,a as useInfiniteDataState,D as useListQuery,c as versionOf,l as withIfMatch};
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { type OperationEntry, type OperationShape } from "@webority/api-contract/call";
|
|
2
2
|
import type { AxiosInstance, AxiosRequestConfig } from "axios";
|
|
3
|
+
/** Per-call options: an abort signal, a timeout, and the client's retry override (`false`, or a policy such as `{ retries: 1 }`). */
|
|
4
|
+
export type ContractCallConfig = Pick<AxiosRequestConfig, "signal" | "timeout" | "retry">;
|
|
3
5
|
/** Calls one operation of a generated contract by its id; resolves to the reply the contract types for it. */
|
|
4
6
|
export type ContractCaller<TOperations extends {
|
|
5
7
|
readonly [K in keyof TOperations]: OperationShape;
|
|
6
|
-
}> = <TId extends keyof TOperations & string>(id: TId, request: TOperations[TId]["request"], config?:
|
|
8
|
+
}> = <TId extends keyof TOperations & string>(id: TId, request: TOperations[TId]["request"], config?: ContractCallConfig) => Promise<TOperations[TId]["response"]>;
|
|
7
9
|
/**
|
|
8
10
|
* Builds the typed caller for one generated contract. Errors are the client's own: an interceptor
|
|
9
11
|
* on `client` turns a failure into the curated error, so the caller adds no catch.
|
|
10
12
|
*/
|
|
11
|
-
export declare const createContractCaller: <TOperations extends { readonly [K in keyof TOperations]: OperationShape; }>(client: AxiosInstance, operations: { readonly [K in keyof TOperations & string]: OperationEntry; }) => ContractCaller<TOperations>;
|
|
13
|
+
export declare const createContractCaller: <TOperations extends { readonly [K in keyof TOperations]: OperationShape; }>(client: Pick<AxiosInstance, "request">, operations: { readonly [K in keyof TOperations & string]: OperationEntry; }) => ContractCaller<TOperations>;
|
|
@@ -4,7 +4,7 @@ export { initUserAuth } from "../initUserAuth";
|
|
|
4
4
|
export { readBlobErrorBody } from "./blobErrorBody";
|
|
5
5
|
export type { AccountIdProvider, ClientKind } from "./clientHeaders";
|
|
6
6
|
export { ACCOUNT_ID_HEADER, CLIENT_BUILD_HEADER, CLIENT_KIND, CLIENT_KIND_HEADER, getClientBuild, } from "./clientHeaders";
|
|
7
|
-
export type { ContractCaller } from "./contractCaller";
|
|
7
|
+
export type { ContractCallConfig, ContractCaller } from "./contractCaller";
|
|
8
8
|
export { createContractCaller } from "./contractCaller";
|
|
9
9
|
export { REFRESH_LOCK_NAME, withCrossTabRefreshLock } from "./crossTabRefreshLock";
|
|
10
10
|
export { applyDesignSample, DESIGN_SAMPLE_HEADER, DESIGN_SAMPLE_QUERY_KEY, DESIGN_SAMPLE_STORAGE_KEY, readDesignSampleTicket, } from "./designSample";
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type OperationEntry, type OperationShape } from "@webority/api-contract/call";
|
|
2
|
+
import type { ApiRequest } from "./apiBaseQuery";
|
|
3
|
+
/** Base query options a contract call keeps: every ApiRequest field the contract does not decide. */
|
|
4
|
+
export type ContractQueryOptions = Omit<ApiRequest, "url" | "method" | "data" | "headers" | "responseType" | "params" | "paramsFormat">;
|
|
5
|
+
/** The reply type of one contract operation, for an endpoint's result type. */
|
|
6
|
+
export type ContractResponse<TOperations extends {
|
|
7
|
+
readonly [K in keyof TOperations]: OperationShape;
|
|
8
|
+
}, TId extends keyof TOperations> = TOperations[TId]["response"];
|
|
9
|
+
/** Builds the base query's request for one operation of a generated contract, by its id. */
|
|
10
|
+
export type ContractQuery<TOperations extends {
|
|
11
|
+
readonly [K in keyof TOperations]: OperationShape;
|
|
12
|
+
}> = <TId extends keyof TOperations & string>(id: TId, request: TOperations[TId]["request"], options?: ContractQueryOptions) => ApiRequest;
|
|
13
|
+
/**
|
|
14
|
+
* Builds `contractQuery` for one generated contract: an endpoint's `query` returns `contractQuery(id, request)`,
|
|
15
|
+
* and the shared base query sends it, so toasts, retry, silent and ETag meta work as for a hand-written endpoint.
|
|
16
|
+
*/
|
|
17
|
+
export declare const createContractQuery: <TOperations extends { readonly [K in keyof TOperations]: OperationShape; }>(operations: { readonly [K in keyof TOperations & string]: OperationEntry; }) => ContractQuery<TOperations>;
|
|
@@ -73,8 +73,11 @@ export interface InfiniteQueryResultLike<T> {
|
|
|
73
73
|
readonly isFetchingNextPage: boolean;
|
|
74
74
|
readonly hasNextPage: boolean;
|
|
75
75
|
readonly isError: boolean;
|
|
76
|
-
/**
|
|
77
|
-
|
|
76
|
+
/**
|
|
77
|
+
* True when the last next-page fetch failed; isError alone is also true for a failed refresh.
|
|
78
|
+
* Optional because RTK Query's hook result types do not declare it, though every hook result carries it; missing reads as false.
|
|
79
|
+
*/
|
|
80
|
+
readonly isFetchNextPageError?: boolean | undefined;
|
|
78
81
|
/** True while the query has never started, which for an RTK Query hook means it is skipped. */
|
|
79
82
|
readonly isUninitialized?: boolean | undefined;
|
|
80
83
|
readonly fulfilledTimeStamp?: number | undefined;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export type { ApiBaseQuery, ApiBaseQueryMeta, ApiBaseQueryOptions, ApiExtraOptions, ApiQueryArgs, ApiRequest, } from "./apiBaseQuery";
|
|
2
2
|
export { createApiBaseQuery } from "./apiBaseQuery";
|
|
3
|
+
export type { ContractQuery, ContractQueryOptions, ContractResponse } from "./contractQuery";
|
|
4
|
+
export { createContractQuery } from "./contractQuery";
|
|
3
5
|
export { APP_API_DEFAULTS, createAppApi } from "./createAppApi";
|
|
4
6
|
export type { DataState, DataStateOptions, InfiniteQueryResultLike, PagedListPaging, QueryResultLike } from "./dataState";
|
|
5
7
|
export { useDataState, useInfiniteDataState } from "./dataState";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/web-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.156.0",
|
|
4
4
|
"description": "Platform layer for Webority React web portals: HTTP clients with single-flight token refresh, auth store, API error extraction, RTK Query base query, logger, formatters, storage, version check and route guards. No UI.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
},
|
|
99
99
|
"sideEffects": false,
|
|
100
100
|
"dependencies": {
|
|
101
|
-
"@webority/api-contract": "0.
|
|
101
|
+
"@webority/api-contract": "0.156.0"
|
|
102
102
|
},
|
|
103
103
|
"peerDependencies": {
|
|
104
104
|
"@microsoft/applicationinsights-web": "^3.4.5",
|
|
@@ -120,7 +120,7 @@
|
|
|
120
120
|
"@types/node": "25.6.0",
|
|
121
121
|
"@types/react": "^19.3.0",
|
|
122
122
|
"@vitest/coverage-v8": "5.1.0",
|
|
123
|
-
"@webority/biome-config": "0.
|
|
123
|
+
"@webority/biome-config": "0.156.0",
|
|
124
124
|
"axios": "^1.18.0",
|
|
125
125
|
"jsdom": "30.1.1",
|
|
126
126
|
"react": "^19.3.1",
|