@webority/web-core 0.149.0 → 0.150.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 +28 -6
- package/dist/api/blobErrorBody.js +1 -0
- package/dist/api/contractCaller.js +1 -0
- package/dist/api/crossTabRefreshLock.js +1 -1
- package/dist/api/designSample.js +1 -1
- package/dist/api/downloadFile.js +1 -0
- package/dist/api/index.js +1 -1
- package/dist/api/minAppVersion.js +1 -1
- package/dist/api/retry.js +1 -1
- package/dist/api/tokenRefresh.js +1 -1
- package/dist/api/userClient.js +1 -1
- package/dist/api/workspaceChanged.js +1 -1
- package/dist/api-contract/dist/call.js +1 -0
- package/dist/appInsights/appInsights.js +1 -0
- package/dist/appInsights/index.js +1 -0
- package/dist/auth/authStore.js +1 -1
- package/dist/auth/jwt.js +1 -1
- package/dist/errors/extractApiError.js +2 -2
- package/dist/errors/index.js +1 -1
- package/dist/errors/parseResponse.js +1 -0
- package/dist/errors/requestPlatform.js +1 -0
- package/dist/formatters/currency.js +1 -1
- package/dist/formatters/formatConfig.js +1 -1
- package/dist/formatters/house.js +1 -1
- package/dist/index.js +1 -1
- package/dist/india/gstStates.js +1 -0
- package/dist/india/index.js +1 -1
- package/dist/logger/logger.js +2 -2
- package/dist/logger/redact.js +1 -1
- package/dist/network/networkStatus.js +1 -1
- package/dist/query/apiBaseQuery.js +1 -1
- package/dist/query/createAppApi.js +1 -1
- package/dist/query/dataState.js +1 -0
- package/dist/query/index.js +1 -1
- package/dist/query/listQuery.js +1 -1
- package/dist/query/tags.js +1 -1
- package/dist/query/useListQuery.js +1 -1
- package/dist/redux/errorToastMiddleware.js +1 -1
- package/dist/redux/rootReducer.js +1 -1
- package/dist/router/chunkReload.js +1 -1
- package/dist/router/index.js +1 -1
- package/dist/router/returnTo.js +1 -1
- package/dist/router/routeTable.js +1 -0
- package/dist/storage/index.js +1 -1
- package/dist/types/api/blobErrorBody.d.ts +9 -0
- package/dist/types/api/contractCaller.d.ts +11 -0
- package/dist/types/api/downloadFile.d.ts +19 -0
- package/dist/types/api/index.d.ts +6 -0
- package/dist/types/api/tokenRefresh.d.ts +2 -1
- package/dist/types/appInsights/appInsights.d.ts +30 -0
- package/dist/types/appInsights/index.d.ts +3 -0
- package/dist/types/auth/authStore.d.ts +2 -1
- package/dist/types/auth/jwt.d.ts +11 -8
- package/dist/types/errors/extractApiError.d.ts +2 -15
- package/dist/types/errors/index.d.ts +2 -0
- package/dist/types/errors/parseResponse.d.ts +19 -0
- package/dist/types/errors/requestPlatform.d.ts +5 -0
- package/dist/types/formatters/formatConfig.d.ts +8 -6
- package/dist/types/formatters/house.d.ts +19 -20
- package/dist/types/formatters/intlCache.d.ts +1 -3
- package/dist/types/india/gstStates.d.ts +7 -0
- package/dist/types/india/gstStates.g.d.ts +1 -1
- package/dist/types/india/index.d.ts +1 -0
- package/dist/types/initUserAuth.d.ts +2 -1
- package/dist/types/logger/redact.d.ts +3 -1
- package/dist/types/query/apiBaseQuery.d.ts +1 -1
- package/dist/types/query/dataState.d.ts +38 -0
- package/dist/types/query/index.d.ts +2 -0
- package/dist/types/query/listQuery.d.ts +2 -2
- package/dist/types/query/useListQuery.d.ts +8 -6
- package/dist/types/redux/index.d.ts +1 -1
- package/dist/types/redux/rootReducer.d.ts +7 -2
- package/dist/types/router/chunkReload.d.ts +5 -2
- package/dist/types/router/index.d.ts +2 -0
- package/dist/types/router/routeTable.d.ts +66 -0
- package/dist/types/storage/index.d.ts +10 -8
- package/dist/versionCheck/deployedBuild.js +1 -1
- package/dist/vite/index.js +1 -1
- package/package.json +20 -5
package/README.md
CHANGED
|
@@ -14,6 +14,7 @@ store.
|
|
|
14
14
|
| Module | What it holds |
|
|
15
15
|
| --- | --- |
|
|
16
16
|
| `api` | `publicClient`, `userClient`, `initUserAuth`, single-flight token refresh, a cross-tab refresh lock, retry of safe requests, the client headers and the minimum-version header reader |
|
|
17
|
+
| `appInsights` | `initAppInsights`, imported from the subpath `@webority/web-core/appInsights`: starts Application Insights with one fixed policy (role and version on every item, correlation headers to the API host only, sign-in codes and tokens scrubbed from addresses, only failed or slow dependencies sent, no cookies until consent) and makes it the `Logger`'s remote sink. Needs the optional peer `@microsoft/applicationinsights-web`; an empty connection string or a test run starts nothing |
|
|
17
18
|
| `auth` | the token store (`getToken`, `storeToken`, `removeToken`), the synchronous `hasSession`, the session user, `clearSession` and `addSessionEndedListener`, `hasSessionEndedInTab`, JWT helpers, "keep me signed in" |
|
|
18
19
|
| `config` | `setConfig`, `getConfig`, `getConfigValue`: base URL, version, commit, build number, log settings, request timeout, retry count |
|
|
19
20
|
| `errors` | `extractApiError`: any thrown value to `{ code, message, fieldErrors, status, offline, traceId, diagnostic }`, with `code` `'network'`, `'timeout'` or `'offline'` when no answer arrived (`offline` is true for all three, and `'offline'` only when the browser reports no network); `apiErrorMessage(error, fallback)`; `isNoResponse` |
|
|
@@ -22,10 +23,10 @@ store.
|
|
|
22
23
|
| `logger` | levelled `Logger` with secret redaction, and `Logger.requestFailed` for a failed service call |
|
|
23
24
|
| `network` | `useNetworkStatus` and the online/offline listener |
|
|
24
25
|
| `query` | the RTK Query base query over `userClient`, the `createAppApi` preset, paged-list and tag helpers |
|
|
25
|
-
| `redux` | `errorToastMiddleware`, `createRootReducer` with `resetState` (clears every slice on sign-out), the serializable-check paths |
|
|
26
|
+
| `redux` | `errorToastMiddleware`, `createRootReducer` with `resetState` (clears every slice on sign-out; `resetState({ keep: ["account", "api"] })` keeps the named slices for that one reset, such as a workspace switch, and throws on a name that is no slice), the serializable-check paths. A slice that must land somewhere other than its initial state after a reset (a profile resolved as signed out, not loading) answers `resetState` in its own `extraReducers` |
|
|
26
27
|
| `router` | loader guards (`requireAuth`, `publicOnly`, `requirePermission`, `withGuards`), element guards (`RequireAuth`, `PublicOnly`, `RequirePermission`), chunk-reload retry with its shared window (`hasRecentlyReloaded`, `markReloaded`), route error classification |
|
|
27
28
|
| `static` | `staticUrl(key)`: the versioned address of an authored static file (a video, a sample document) listed in the `staticAssets.assets` object of the one deployable carrying `staticAssets` in the repo's `.webority/infra/deployables.json` |
|
|
28
|
-
| `storage` | `Storage` (async, the same API as mobile) and `syncStorage` (synchronous, web only) over `localStorage` |
|
|
29
|
+
| `storage` | `Storage` (async, the same API as mobile) and `syncStorage` / `syncSessionStorage` (synchronous, web only) over `localStorage` / `sessionStorage` |
|
|
29
30
|
| `versionCheck` | `useVersionCheck` and `installReloadOnNavigate`: tells the portal a newer build is live |
|
|
30
31
|
| `vite` | `weborityStatic`, a Vite plugin that compiles the `staticAssets` list of `.webority/infra/deployables.json` for `staticUrl` and can point the build's hashed files at a static host. Node only: import it in `vite.config`, never in app code |
|
|
31
32
|
|
|
@@ -280,8 +281,11 @@ Called with no options, the house formatters print (zone IST, locale en-IN, empt
|
|
|
280
281
|
|
|
281
282
|
`Storage` is async, the same API as mobile-core's, for code shared with an app. `syncStorage` is
|
|
282
283
|
web only: `getItem`, `setItem`, `removeItem`, `getJson`, `setJson` straight on `localStorage`, for a
|
|
283
|
-
preference a first render cannot wait for.
|
|
284
|
-
|
|
284
|
+
preference a first render cannot wait for. `syncSessionStorage` is the same API on `sessionStorage`,
|
|
285
|
+
for state that ends with the tab. None of them throws: a blocked store reads as empty and a
|
|
286
|
+
write returns `false`. Both `getJson(key, parse)` take a parse function that checks the stored
|
|
287
|
+
JSON and returns the caller's type; `getSessionUser(parse)` and `decodeJWT(token, parse?)` read the
|
|
288
|
+
same way.
|
|
285
289
|
|
|
286
290
|
## Static assets
|
|
287
291
|
|
|
@@ -298,8 +302,8 @@ staticUrl("samples/report.pdf"); // "/samples/report.pdf?v=0123456789ab"
|
|
|
298
302
|
throws on a key that is not in the list. A same-origin `authoredOrigin` of `"/"` gives `/samples/...`.
|
|
299
303
|
The list is compiled into the bundle by the Vite plugin:
|
|
300
304
|
|
|
301
|
-
```
|
|
302
|
-
// vite.config.
|
|
305
|
+
```ts
|
|
306
|
+
// vite.config.ts
|
|
303
307
|
import { weborityStatic } from "@webority/web-core/vite";
|
|
304
308
|
|
|
305
309
|
export default defineConfig({
|
|
@@ -379,6 +383,24 @@ the mode on, so the two checks are independent.
|
|
|
379
383
|
The design sample exists on the web only; `@webority/mobile-core` has no counterpart. This package stays
|
|
380
384
|
TypeScript, a recorded deviation from `react.md`, which asks for JavaScript.
|
|
381
385
|
|
|
386
|
+
## Contract caller
|
|
387
|
+
|
|
388
|
+
`createContractCaller` builds one typed caller from a generated contract (`@webority/api-contract`).
|
|
389
|
+
It takes the client and the contract's `operations` map, and calls an operation by its id with the
|
|
390
|
+
request the contract types for it. The reply is the response type of that operation.
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
import { createContractCaller, userClient } from "@webority/web-core";
|
|
394
|
+
import { operations, type Operations } from "./api/contract";
|
|
395
|
+
|
|
396
|
+
const call = createContractCaller<Operations>(userClient, operations);
|
|
397
|
+
|
|
398
|
+
const page = await call("Standards_List", { query: { page: 1 } }, { signal, timeout: 10000 });
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
The caller adds no catch: a failure reaches the caller as the client's curated error. `signal` and
|
|
402
|
+
`timeout` are optional and go to the request as they are.
|
|
403
|
+
|
|
382
404
|
## Develop
|
|
383
405
|
|
|
384
406
|
```bash
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=async e=>{if(typeof e!=`object`||!e||!(`response`in e))return;let t=e.response;if(typeof t!=`object`||!t||!(`data`in t))return;let n=t.data;if(typeof Blob>`u`||!(n instanceof Blob))return;let r=n.type.includes(`json`);if(!r&&!n.type.startsWith(`text/`))return;let i=await n.text();if(!r)t.data=i;else try{t.data=JSON.parse(i)}catch{t.data=i}};export{e as readBlobErrorBody};
|
|
@@ -0,0 +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,params:o.params,headers:o.headers,data:o.data,responseType:o.responseType,signal:a?.signal,timeout:a?.timeout})).data};export{t as createContractCaller};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`webority.token-refresh`,t=`${e}.lease`,n=1e4,r=3e3,i=150,a=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=()=>{let e=localStorage.getItem(t);if(!e)return null;try{let t=JSON.parse(e);return
|
|
1
|
+
var e=`webority.token-refresh`,t=`${e}.lease`,n=1e4,r=3e3,i=150,a=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=e=>typeof e==`object`&&!!e&&`id`in e&&`expiresAt`in e&&typeof e.id==`string`&&typeof e.expiresAt==`number`,s=()=>{let e=localStorage.getItem(t);if(!e)return null;try{let t=JSON.parse(e);return o(t)&&t.expiresAt>Date.now()?t:null}catch{return null}},c=e=>{localStorage.setItem(t,JSON.stringify({id:e,expiresAt:Date.now()+n}))},l=e=>!s()&&(c(e),s()?.id===e),u=()=>typeof BroadcastChannel>`u`?null:new BroadcastChannel(e),d=e=>new Promise(t=>{let n=()=>{clearInterval(a),e?.removeEventListener(`message`,r),t()},r=()=>n(),a=setInterval(()=>{s()||n()},i);e?.addEventListener(`message`,r)}),f=async e=>{let n=a();try{s()}catch{return e()}let i=u();try{for(;!l(n);)await d(i);let a=setInterval(()=>{s()?.id===n&&c(n)},r);try{return await e()}finally{clearInterval(a),s()?.id===n&&localStorage.removeItem(t),i?.postMessage({type:`released`})}}finally{i?.close()}},p=async t=>{let n=typeof navigator>`u`?void 0:navigator.locks;return n&&typeof n.request==`function`?await n.request(e,{mode:`exclusive`},()=>t()):f(t)};export{e as REFRESH_LOCK_NAME,p as withCrossTabRefreshLock};
|
package/dist/api/designSample.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getConfigValue as e}from"../config/index.js";var
|
|
1
|
+
import{getConfigValue as e}from"../config/index.js";import{syncSessionStorage as t}from"../storage/index.js";var n=`designSample`,r=`Design-Sample`,i=`webority.designSample`,a=!1,o=()=>{if(e(`environment`)===`Production`)return null;if(!a){a=!0;let e=new URLSearchParams(window.location.search).get(n);e&&t.setItem(i,e)}return t.getItem(i)},s=e=>{e.interceptors.request.use(e=>{let t=o();return t&&!e.headers.has(`Design-Sample`)&&e.headers.set(r,t),e})};export{r as DESIGN_SAMPLE_HEADER,n as DESIGN_SAMPLE_QUERY_KEY,i as DESIGN_SAMPLE_STORAGE_KEY,s as applyDesignSample,o as readDesignSampleTicket};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{extractApiError as e}from"../errors/extractApiError.js";import{readBlobErrorBody as t}from"./blobErrorBody.js";var n=/filename="((?:[^"\\]|\\.)*)"/i,r=/filename=([^;]+)/i,i=/filename\*=([^']*)'[^']*'([^;]+)/i,a=/%(?![0-9A-Fa-f]{2})/,o=/(?:%[0-9A-Fa-f]{2})+/g,s=e=>{if(a.test(e))return null;let t=!1,n=e.replace(o,e=>{let n=Uint8Array.from(e.slice(1).split(`%`),e=>Number.parseInt(e,16)),r=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}).decode(n);return new TextEncoder().encode(r).join(`,`)!==n.join(`,`)&&(t=!0),r});return t?null:n},c=e=>{let t=i.exec(e)?.[2]?.trim(),a=t?s(t):null;return a===null?(n.exec(e)?.[1]?.replace(/\\(.)/g,`$1`)??r.exec(e)?.[1]?.trim())||null:a},l=async(n,r)=>{let i,a;try{let e=await n.request({...r,responseType:`blob`});i=e.data,a=e.headers[`content-disposition`]}catch(n){throw await t(n),e(n)}if(!(i instanceof Blob))throw Error(`downloadFile: "${r.url??``}" answered without a file body.`);return{blob:i,fileName:typeof a==`string`?c(a):null}};export{c as contentDispositionFileName,l as downloadFile};
|
package/dist/api/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{initUserAuth as e}from"../initUserAuth.js";import{ACCOUNT_ID_HEADER as
|
|
1
|
+
import{initUserAuth as e}from"../initUserAuth.js";import{readBlobErrorBody as t}from"./blobErrorBody.js";import{ACCOUNT_ID_HEADER as n,CLIENT_BUILD_HEADER as r,CLIENT_KIND as i,CLIENT_KIND_HEADER as a,getClientBuild as o}from"./clientHeaders.js";import{createContractCaller as s}from"./contractCaller.js";import{REFRESH_LOCK_NAME as c,withCrossTabRefreshLock as l}from"./crossTabRefreshLock.js";import{DESIGN_SAMPLE_HEADER as u,DESIGN_SAMPLE_QUERY_KEY as d,DESIGN_SAMPLE_STORAGE_KEY as f,applyDesignSample as p,readDesignSampleTicket as m}from"./designSample.js";import{contentDispositionFileName as h,downloadFile as g}from"./downloadFile.js";import{MIN_APP_VERSION_HEADER as _,addMinAppVersionListener as v,getMinAppVersion as y}from"./minAppVersion.js";import b from"./publicClient.js";import{TRACEPARENT_HEADER as x,applyRequestDefaults as S,newTraceparent as C}from"./requestDefaults.js";import{IDEMPOTENCY_KEY_HEADER as w,attachRetry as T,isNeverSentError as E,isRetryableFailure as D,isRetryableStatus as O,retryAfterMs as k}from"./retry.js";import{SESSION_EXPIRED_CODE as A,SESSION_REVOKED_CODE as j,injectStore as M,injectUserAuth as N,refreshAccessToken as P,resetRefreshState as F}from"./tokenRefresh.js";import I,{RequestOfflineError as L}from"./userClient.js";import{WORKSPACE_CHANGED_CODE as R,WorkspaceChangedError as z,isWorkspaceChangedError as B}from"./workspaceChanged.js";export{n as ACCOUNT_ID_HEADER,r as CLIENT_BUILD_HEADER,i as CLIENT_KIND,a as CLIENT_KIND_HEADER,u as DESIGN_SAMPLE_HEADER,d as DESIGN_SAMPLE_QUERY_KEY,f as DESIGN_SAMPLE_STORAGE_KEY,w as IDEMPOTENCY_KEY_HEADER,_ as MIN_APP_VERSION_HEADER,c as REFRESH_LOCK_NAME,L as RequestOfflineError,A as SESSION_EXPIRED_CODE,j as SESSION_REVOKED_CODE,x as TRACEPARENT_HEADER,R as WORKSPACE_CHANGED_CODE,z as WorkspaceChangedError,v as addMinAppVersionListener,p as applyDesignSample,S as applyRequestDefaults,T as attachRetry,h as contentDispositionFileName,s as createContractCaller,g as downloadFile,o as getClientBuild,y as getMinAppVersion,e as initUserAuth,M as injectStore,N as injectUserAuth,E as isNeverSentError,D as isRetryableFailure,O as isRetryableStatus,B as isWorkspaceChangedError,C as newTraceparent,b as publicClient,t as readBlobErrorBody,m as readDesignSampleTicket,P as refreshAccessToken,F as resetRefreshState,k as retryAfterMs,I as userClient,l as withCrossTabRefreshLock};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger as e}from"../logger/logger.js";var t=`Min-App-Version`,n=null,r=/* @__PURE__ */ new Set,i=()=>n,a=e=>(r.add(e),n!==null&&e(n),()=>{r.delete(e)}),o=e=>{if(!e
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";var t=`Min-App-Version`,n=null,r=/* @__PURE__ */ new Set,i=()=>n,a=e=>(r.add(e),n!==null&&e(n),()=>{r.delete(e)}),o=e=>typeof e==`object`&&!!e,s=e=>{if(!o(e))return;let n=e.get;return typeof n==`function`?n.call(e,t):e[t.toLowerCase()]},c=i=>{let a=s(i);if(a==null||a===``)return;let o=String(a).trim();if(!/^\d+$/.test(o)){e.warn(`[minAppVersion] ignored a non-integer ${t}: ${o}`);return}let c=Number.parseInt(o,10);if(c!==n){n=c;for(let t of[...r])try{t(c)}catch(t){e.error(`[minAppVersion] a listener threw`,t)}}},l=e=>{e.interceptors.response.use(e=>(c(e.headers),e),e=>(c(o(e)&&o(e.response)?e.response.headers:void 0),Promise.reject(e)))};export{t as MIN_APP_VERSION_HEADER,a as addMinAppVersionListener,i as getMinAppVersion,l as readMinAppVersion};
|
package/dist/api/retry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getConfigValue as e}from"../config/index.js";import{isWorkspaceChangedResponse as t}from"./workspaceChanged.js";import n from"axios";var r=`Idempotency-Key`,i=e=>typeof e==`number`&&(e===429||e>=500&&e<=599),a=/* @__PURE__ */ new Set([`get`,`head`,`options`,`put`,`delete`]),o=/* @__PURE__ */ new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`ENETUNREACH`,`EHOSTUNREACH`]),s=e=>!e.response&&typeof e.code==`string`&&o.has(e.code),c=3e4,l=e=>{let t=e.response;if(!t)return null;let n=t.headers
|
|
1
|
+
import{getConfigValue as e}from"../config/index.js";import{isWorkspaceChangedResponse as t}from"./workspaceChanged.js";import n from"axios";var r=`Idempotency-Key`,i=e=>typeof e==`number`&&(e===429||e>=500&&e<=599),a=/* @__PURE__ */ new Set([`get`,`head`,`options`,`put`,`delete`]),o=/* @__PURE__ */ new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`ENETUNREACH`,`EHOSTUNREACH`]),s=e=>!e.response&&typeof e.code==`string`&&o.has(e.code),c=3e4,l=e=>typeof e==`object`&&!!e,u=(e,t)=>{if(!l(e))return;let n=e.get;return typeof n==`function`?n.call(e,t):e[t]},d=e=>{let t=e.response;if(!t)return null;let n=u(t.headers,`retry-after`),r=Number(n);return n!=null&&Number.isFinite(r)&&r>0?r*1e3:null},f=e=>{let t=u(e?.headers,r);return typeof t==`string`&&t!==``},p=e=>{if(n.isCancel(e)||e.code===`ERR_CANCELED`)return!1;if(s(e))return!0;let t=(e.config?.method??`get`).toLowerCase(),r=a.has(t),o=e.response?.status;if(o===void 0)return r;if(!i(o))return!1;let l=d(e);return l!==null&&l>c?!1:r||(o===429||o===503)&&f(e.config)},m={retryDelayMs:e=>e<=1?0:Math.random()*Math.min(3e4,1e3*2**e),shouldRetry:p,onRetry:()=>void 0},h=(e,t)=>new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener?.(`abort`,r),n(!0)},e);t?.addEventListener?.(`abort`,r,{once:!0})}),g=(r,i={})=>{r.interceptors.response.use(void 0,async a=>{if(!n.isAxiosError(a))return Promise.reject(a);let o=a,s=o.config;if(!s||s.retry===!1)return Promise.reject(a);let c=typeof s.retry==`object`?s.retry:{},l={...m,retries:e(`retries`),...i,...c},u=(s.__retryAttempt??0)+1;return t(o)||u>l.retries||!l.shouldRetry(o)||s.signal?.aborted||(s.__retryAttempt=u,s.transformRequest=[e=>e],l.onRetry(u,o),!await h(d(o)??l.retryDelayMs(u),s.signal))?Promise.reject(a):r.request(s)})};export{r as IDEMPOTENCY_KEY_HEADER,g as attachRetry,s as isNeverSentError,p as isRetryableFailure,i as isRetryableStatus,d as retryAfterMs};
|
package/dist/api/tokenRefresh.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACCESS_TOKEN_KEY as e,REFRESH_TOKEN_KEY as t,clearSession as n,getToken as r,storeToken as i}from"../auth/authStore.js";import{Logger as a}from"../logger/logger.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d=class e extends Error{constructor(t){super(t),this.name=`SessionEndedError`,Object.setPrototypeOf(this,e.prototype)}},f,p,m=e=>{f=e},h=e=>{p=e},g=null,_=[],v=(e,t=null)=>{_.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),_=[]},y=()=>{g=null,v(new d(`[@webority/web-core] Session ended`))},b=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,x=()=>{if(!f||!p)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:f,auth:p}},S=()=>p?.accountId,C=()=>p?.refresh.path,w=async()=>{let e=x();await e.store.dispatch(e.auth.logout())},T=async(e,t,r)=>{await n(e,{code:t,detail:r}),await w()},E=e=>{let t=e&&typeof e==`object
|
|
1
|
+
import{ACCESS_TOKEN_KEY as e,REFRESH_TOKEN_KEY as t,clearSession as n,getToken as r,storeToken as i}from"../auth/authStore.js";import{Logger as a}from"../logger/logger.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d=class e extends Error{constructor(t){super(t),this.name=`SessionEndedError`,Object.setPrototypeOf(this,e.prototype)}},f,p,m=e=>{f=e??void 0},h=e=>{p=e},g=null,_=[],v=(e,t=null)=>{_.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),_=[]},y=()=>{g=null,v(new d(`[@webority/web-core] Session ended`))},b=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,x=()=>{if(!f||!p)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:f,auth:p}},S=()=>p?.accountId,C=()=>p?.refresh.path,w=async()=>{let e=x();await e.store.dispatch(e.auth.logout())},T=async(e,t,r)=>{await n(e,{code:t,detail:r}),await w()},E=e=>{let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return t===`session_revoked`||t===`session_expired`?t:null},D=e=>{let t=e&&typeof e==`object`&&`detail`in e?e.detail:void 0;return typeof t==`string`&&t!==``&&E(e)!==null?t:null},O=e=>{if(!c.isAxiosError(e)||!e.response)return null;let t=e.response.data,n=t&&typeof t==`object`&&`code`in t?t.code:void 0;return typeof n==`string`&&p?.endSessionOn?.includes(n)?n:null},k=()=>g!==null,A=0,j=Promise.resolve(),M=null,N=()=>{A===0&&(j=new Promise(e=>{M=e})),A+=1;let e=!1;return()=>{e||(e=!0,--A,A===0&&(M?.(),M=null))}},P=()=>A===0?Promise.resolve():j,F=class e extends Error{constructor(t){super(`A session-replacing response carried no tokens: ${t}`),this.name=`ReplacementTokensMissingError`,Object.setPrototypeOf(this,e.prototype)}},I=async n=>{let r;try{r=(p?.refresh.readTokens??G)(n)}catch(e){throw new F(b(e))}await i(e,r.accessToken,r.accessTokenExpiry),await i(t,r.refreshToken,r.refreshTokenExpiry)},L=async e=>{let t=(await r(`accessToken`))?.token??null;return t!==null&&t!==e?t:null},R=()=>new Promise((e,t)=>{_.push({resolve:e,reject:t})}),z=e=>e instanceof d||c.isAxiosError(e)&&(e.response?.status===400||e.response?.status===401),B=e=>!c.isAxiosError(e)||e.response?.status!==401?null:E(e.response.data),V=e=>!c.isAxiosError(e)||e.response?.status!==401?null:D(e.response.data),H=e=>z(e)||O(e)!==null,U=e=>c.isAxiosError(e)?E(e.response?.data)??`status ${e.response?.status}`:b(e),W=(e,t)=>{if(typeof e!=`string`||e===``)throw Error(`The refresh response has no "${t}".`);return e},G=e=>{if(typeof e!=`object`||!e)throw Error(`The refresh response is not an object.`);return{accessToken:W(`accessToken`in e?e.accessToken:void 0,`accessToken`),accessTokenExpiry:W(`accessTokenExpiration`in e?e.accessTokenExpiration:void 0,`accessTokenExpiration`),refreshToken:W(`refreshToken`in e?e.refreshToken:void 0,`refreshToken`),refreshTokenExpiry:W(`refreshTokenExpiration`in e?e.refreshTokenExpiration:void 0,`refreshTokenExpiration`)}},K=async n=>{await P();let o=await r(t);if(!o?.token)throw new d(`No refresh token available`);if(Date.parse(o.expiry)<=Date.now())throw new d(`Refresh token expired`);let c={accessToken:(await r(`accessToken`))?.token??null,refreshToken:o.token},l=n.body?await n.body(c):c,u=n.headers?await n.headers():void 0;a.info(`Refreshing the access token`);let{data:f}=await s.post(n.path,l,{...u?{headers:u}:{},skipErrorLog:!0}),p=(n.readTokens??G)(f);await P();let m=(await r(`refreshToken`))?.token===o.token?null:await r(e);return m?.token?(a.info(`Keeping the session that replaced this one during the refresh`),m.token):(await i(e,p.accessToken,p.accessTokenExpiry),await i(t,p.refreshToken,p.refreshTokenExpiry),a.info(`Access token refreshed`),p.accessToken)},q=3e4,J=async(t,n)=>{let i=await r(e);return i?.token&&i.token!==n&&Date.parse(i.expiry)>Date.now()+q?(a.info(`Adopting the access token another tab refreshed`),i.token):K(t)},Y=()=>{if(g)return g;let e=(async()=>{let e=null;try{let{refresh:t}=x().auth;e=(await r(`accessToken`))?.token??null;let n=await o(()=>J(t,e));return v(null,n),n}catch(t){if(z(t)){await P();let t=null;try{t=await L(e)}catch(e){a.error(`Reading the stored token after a failed refresh failed:`,b(e))}if(t)return a.info(`The session was replaced during the refresh; continuing with the new one`),v(null,t),t}let n=O(t);if(n!==null)throw a.info(`Session ended, the refresh was refused: ${n}`),v(t,null),await T(`terminated`,n,D(c.isAxiosError(t)?t.response?.data:void 0)),t;let r=z(t);if(r)a.info(`Session ended, the refresh was refused:`,U(t));else{let e=c.isAxiosError(t)?t.response?.data:void 0;a.error(`Token refresh failed:`,e??b(t))}throw v(t,null),r&&await T(`rejected`,B(t),V(t)),t}})().finally(()=>{g===e&&(g=null)});return g=e,e};export{u as SESSION_EXPIRED_CODE,l as SESSION_REVOKED_CODE,d as SessionEndedError,N as beginSessionReplacement,L as currentTokenIfReplaced,w as dispatchLogout,T as endSessionAndLogout,O as endSessionCodeOf,S as getAccountIdProvider,b as getErrorMessage,C as getRefreshPath,m as injectStore,h as injectUserAuth,k as isRefreshInFlight,H as isSessionEnd,R as queueBehindRefresh,Y as refreshAccessToken,y as resetRefreshState,E as sessionCodeOf,D as sessionDetailOf,I as storeReplacementSession,P as waitForSessionReplacement};
|
package/dist/api/userClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACCESS_TOKEN_KEY as e,getToken as t}from"../auth/authStore.js";import{Logger as n}from"../logger/logger.js";import{getLastKnownNetworkStatus as r}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as i}from"./baseUrl.js";import{applyClientHeaders as a,readAccountId as o,stampAccountId as s}from"./clientHeaders.js";import{applyDesignSample as c}from"./designSample.js";import{readMinAppVersion as l}from"./minAppVersion.js";import{sendFormDataAsMultipart as u}from"./multipart.js";import{applyRequestDefaults as d}from"./requestDefaults.js";import{responseBodyText as f}from"./responseBodyText.js";import{attachRetry as p}from"./retry.js";import{SESSION_EXPIRED_CODE as m,SESSION_REVOKED_CODE as h,SessionEndedError as g,beginSessionReplacement as _,currentTokenIfReplaced as v,endSessionAndLogout as y,endSessionCodeOf as b,getAccountIdProvider as x,getErrorMessage as S,getRefreshPath as C,injectStore as w,injectUserAuth as T,isRefreshInFlight as E,isSessionEnd as D,queueBehindRefresh as O,refreshAccessToken as k,resetRefreshState as A,sessionCodeOf as j,sessionDetailOf as M,storeReplacementSession as N,waitForSessionReplacement as P}from"./tokenRefresh.js";import{WorkspaceChangedError as F,isWorkspaceChangedResponse as I,workspaceChangedFromResponse as L}from"./workspaceChanged.js";import R,{AxiosHeaders as z}from"axios";var B=class e extends Error{constructor(t=`Request blocked: device is offline`){super(t),this.name=`RequestOfflineError`,Object.setPrototypeOf(this,e.prototype)}},V=class e extends Error{constructor(){super(`No access token available`),this.name=`NoAccessTokenError`,Object.setPrototypeOf(this,e.prototype)}},H=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},U=e=>{let t=e.headers instanceof z?e.headers.get(`Authorization`):void 0;return typeof t==`string`&&t.startsWith(`Bearer `)?t.slice(7):null},
|
|
1
|
+
import{ACCESS_TOKEN_KEY as e,getToken as t}from"../auth/authStore.js";import{Logger as n}from"../logger/logger.js";import{getLastKnownNetworkStatus as r}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as i}from"./baseUrl.js";import{applyClientHeaders as a,readAccountId as o,stampAccountId as s}from"./clientHeaders.js";import{applyDesignSample as c}from"./designSample.js";import{readMinAppVersion as l}from"./minAppVersion.js";import{sendFormDataAsMultipart as u}from"./multipart.js";import{applyRequestDefaults as d}from"./requestDefaults.js";import{responseBodyText as f}from"./responseBodyText.js";import{attachRetry as p}from"./retry.js";import{SESSION_EXPIRED_CODE as m,SESSION_REVOKED_CODE as h,SessionEndedError as g,beginSessionReplacement as _,currentTokenIfReplaced as v,endSessionAndLogout as y,endSessionCodeOf as b,getAccountIdProvider as x,getErrorMessage as S,getRefreshPath as C,injectStore as w,injectUserAuth as T,isRefreshInFlight as E,isSessionEnd as D,queueBehindRefresh as O,refreshAccessToken as k,resetRefreshState as A,sessionCodeOf as j,sessionDetailOf as M,storeReplacementSession as N,waitForSessionReplacement as P}from"./tokenRefresh.js";import{WorkspaceChangedError as F,isWorkspaceChangedResponse as I,workspaceChangedFromResponse as L}from"./workspaceChanged.js";import R,{AxiosHeaders as z}from"axios";var B=class e extends Error{constructor(t=`Request blocked: device is offline`){super(t),this.name=`RequestOfflineError`,Object.setPrototypeOf(this,e.prototype)}},V=class e extends Error{constructor(){super(`No access token available`),this.name=`NoAccessTokenError`,Object.setPrototypeOf(this,e.prototype)}},H=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},U=e=>R.isAxiosError(e)||e instanceof F?e.config:void 0,W=e=>{let t=e.headers instanceof z?e.headers.get(`Authorization`):void 0;return typeof t==`string`&&t.startsWith(`Bearer `)?t.slice(7):null},G=R.create({headers:{"Content-Type":`application/json`}});l(G),p(G);var K=(e,t)=>{e.headers=z.from(e.headers).set(`Authorization`,`Bearer ${t}`)},q=e=>{let t=C();return!!t&&!!e?.includes(t)};i(G),d(G),u(G),a(G),c(G),G.interceptors.request.use(async i=>{let a=i;if(H(a),(await r()).isConnected===!1)return n.warn(`Request blocked: browser is offline. URL: ${i.url}`),Promise.reject(new B);try{if(q(i.url))return i;await s(a,x());let r=await t(e);if(!r?.token)throw new V;let o=Date.now();return Date.parse(r.expiry)<=o+3e4?(n.info(`Access token expired or about to expire, refreshing before request`),K(i,await k())):K(i,r.token),i.replacesSession&&(a._endReplacement=_()),i}catch(e){return e instanceof V?n.info(`Request not sent: signed out. URL: ${i.url}`):D(e)||n.error(`Failed to attach token:`,S(e)),Promise.reject(e)}},e=>(n.error(`Request error:`,S(e)),Promise.reject(e))),G.interceptors.response.use(async e=>{let t=e.config;if(t._endReplacement)try{await N(e.data)}finally{H(t)}return e},async e=>{if(H(U(e)),R.isCancel(e)||e instanceof B||e instanceof V||e instanceof g||e instanceof F)return Promise.reject(e);if(!R.isAxiosError(e))return n.error(`Non-axios error in response interceptor: ${S(e)}`),Promise.reject(e);let t=e,r=t.config;if(!t.response)return r?.skipErrorLog||n.error(`Network error or no response from server: ${t.message}, URL: ${r?.url}`),Promise.reject(e);if(I(t))return n.info(`Request refused: the workspace changed after it was made. URL: ${r?.url}`),Promise.reject(L(t));if(q(r?.url))return Promise.reject(e);if(t.response.status===401&&r&&!r._replayedWithCurrentToken&&!r.replacesSession&&(await P(),await v(W(r))))return(r._accountId??null)===await o(x())?(n.info(`Session changed while the request was in flight; sending it again. URL: ${r.url}`),r._replayedWithCurrentToken=!0,G(r)):(n.info(`Session moved to another workspace while the request was in flight; not sending it again. URL: ${r.url}`),Promise.reject(new F(void 0,{config:r,cause:e})));let i=b(t);if(i!==null)return n.warn(`Session ended by ${i}, logging out. URL: ${r?.url}`),A(),await y(`terminated`,i,M(t.response?.data)),Promise.reject(e);if(t.response.status===401&&r&&!r._retry){let i=j(t.response.data);if(i!==null)return n.warn(`Session ${i}, logging out without refresh. URL: ${r.url}`),A(),await y(`terminated`,i,M(t.response.data)),Promise.reject(e);if(n.warn(`Unauthorized URL: ${r.url}`),r._retry=!0,E())return O().then(e=>(n.info(`Retrying request after token refresh:`,r.url),K(r,e),G(r))).catch(e=>(!D(e)&&!(e instanceof F)&&n.error(`Failed to retry request after token refresh:`,S(e)),Promise.reject(e)));try{return K(r,await k()),G(r)}catch(e){return Promise.reject(e)}}if(!r?.skipErrorLog){let e=`Response error: ${f(t.response?.data,t.message)}, URL: ${r?.url}, Status: ${t.response.status}`;r?.expectedStatuses?.includes(t.response.status)?n.debug(e):n.error(e)}return Promise.reject(e)});export{B as RequestOfflineError,m as SESSION_EXPIRED_CODE,h as SESSION_REVOKED_CODE,G as default,w as injectStore,T as injectUserAuth,A as resetRefreshState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`workspace_changed`,t=e=>
|
|
1
|
+
var e=`workspace_changed`,t=e=>typeof e==`object`&&!!e&&!Array.isArray(e),n=e=>t(e)?e:null,r=class t extends Error{code=e;response;config;cause;constructor(e=`This was started in another workspace. Switch back to it and try again.`,n={}){super(e),this.name=`WorkspaceChangedError`,this.response=n.response??{status:409,data:{code:`workspace_changed`,detail:e},headers:{}},this.config=n.config,this.cause=n.cause,Object.setPrototypeOf(this,t.prototype)}},i=e=>e instanceof r||typeof e==`object`&&!!e&&(`name`in e&&e.name===`WorkspaceChangedError`||`code`in e&&e.code===`workspace_changed`),a=e=>e.response?.status===409&&n(e.response.data)?.code===`workspace_changed`,o=e=>{let t=n(e.response?.data)?.detail;return new r(typeof t==`string`&&t.trim()!==``?t:void 0,{response:e.response,config:e.config,cause:e})};export{e as WORKSPACE_CHANGED_CODE,r as WorkspaceChangedError,i as isWorkspaceChangedError,a as isWorkspaceChangedResponse,o as workspaceChangedFromResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g;function n(n,r){let i=n.path.replace(t,(t,i)=>{let a=r.path?.[i],o=a===void 0?``:String(a);if(o===``)throw new e(`${n.method} ${n.path} needs a non-empty path value for "${i}"`);if(o===`.`||o===`..`)throw new e(`${n.method} ${n.path} needs a path value for "${i}" other than "." or ".."`);return encodeURIComponent(o)});return{method:n.method,url:i,params:r.query,headers:r.headers,data:r.body,responseType:n.replyKind===`blob`?`blob`:`json`}}export{e as ContractCallError,n as buildContractRequest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{setRemoteLogger as e}from"../logger/logger.js";import{ApplicationInsights as t,SeverityLevel as n}from"@microsoft/applicationinsights-web";var r=500,i=/^(?:(\d+)\.)?(\d+):(\d+):(\d+(?:\.\d+)?)$/,a={info:n.Information,warn:n.Warning,error:n.Error},o=/* @__PURE__ */ new Map;function s(n){if(n.connectionString===``||c())return null;let i;try{i=new URL(n.apiBaseUrl).hostname}catch{throw Error(`initAppInsights: apiBaseUrl must be an absolute URL`)}let s=n.environment===``||n.environment===`Production`?n.cloudRole:`${n.cloudRole}-${n.environment.toLowerCase()}`,l=n.slowDependencyMs??r,d=new t({config:{connectionString:n.connectionString,extensions:n.extensions??[],enableAutoRouteTracking:!0,disableAjaxTracking:!1,autoTrackPageVisitTime:!1,enableCorsCorrelation:!0,enableRequestHeaderTracking:!1,enableResponseHeaderTracking:!1,correlationHeaderDomains:[i],disableCookiesUsage:!0,disablePageUnloadEvents:[`unload`]}});d.loadAppInsights(),d.addTelemetryInitializer(e=>{e.tags=e.tags??{},e.tags[`ai.cloud.role`]=s,e.tags[`ai.application.ver`]=n.version}),d.addTelemetryInitializer(C),d.addTelemetryInitializer(S),d.addTelemetryInitializer(e=>u(e,l)),d.addDependencyInitializer(e=>f(e,i));for(let e of n.initializers??[])d.addTelemetryInitializer(e);return w(d),e({log:(e,t)=>{e!==`debug`&&d.trackTrace({message:t,severityLevel:a[e]})},recordError:(e,t)=>{d.trackException({exception:e instanceof Error?e:Error(String(e))},t)},setUser:e=>{typeof e==`string`?d.setAuthenticatedUserContext(e):d.clearAuthenticatedUserContext()},setAttribute:(e,t)=>{o.set(e,t)}}),d}function c(){let e=Reflect.get(globalThis,`process`),t=typeof e==`object`&&e&&`env`in e?e.env:void 0;return typeof t==`object`&&!!t&&`VITEST`in t&&!!t.VITEST}function l(e){if(typeof e==`number`)return e;let t=typeof e==`string`?i.exec(e):null;if(!t)return;let[,n=`0`,r,a,o]=t;return(((Number(n)*24+Number(r))*60+Number(a))*60+Number(o))*1e3}function u(e,t=r){if(e.baseType===`MetricData`)return!1;if(e.baseType!==`RemoteDependencyData`||e.baseData?.success!==!0)return!0;let n=l(e.baseData.duration);return n===void 0||n>=t}function d(e){if(typeof e!=`string`||e===``)return``;try{return new URL(e.includes(`://`)?e:`https://${e}`).hostname}catch{return``}}function f({item:e},t){let n=Number(e?.responseCode);return n>0&&n<400?d(e.target)!==t:!0}var p=/* @__PURE__ */ new Set([`token`,`code`,`email`,`access_token`,`id_token`,`state`,`session_state`,`password`,`search`,`q`,`query`]),m=[`uri`,`refUri`,`url`],h=[`name`,`data`,`message`],g=/^(\/|https?:\/\/)/i;function _(e){if(typeof e!=`string`||e===``)return e;let t=e.indexOf(`#`),n=t===-1?e:e.slice(0,t),r=n.indexOf(`?`);if(r===-1)return n;let i=new URLSearchParams;for(let[e,t]of new URLSearchParams(n.slice(r+1)))p.has(e.toLowerCase())||i.append(e,g.test(t)?_(t):t);let a=i.toString();return a?`${n.slice(0,r)}?${a}`:n.slice(0,r)}var v=/[^\s"'<>]+/g,y=/https?:\/\/./i;function b(e){let t=e.search(y),n=e.indexOf(`/`),r=n!==-1&&n<e.lastIndexOf(`?`)?n:-1,i=t===-1?r:r===-1?t:Math.min(t,r);return i===-1?e:e.slice(0,i)+_(e.slice(i))}function x(e){return e.replace(v,e=>b(e))}function S(e){for(let t of[e.baseData,e.baseData?.properties,e.data])if(t){for(let e of m)typeof t[e]==`string`&&(t[e]=_(t[e]));for(let e of h)typeof t[e]==`string`&&(t[e]=x(t[e]))}}function C(e){e.data=e.data??{};for(let[t,n]of o)n===null?delete e.data[t]:e.data[t]=n}function w(e){window.history.state?.idx!=null&&e.trackPageView()}export{s as initAppInsights,u as keepFailedOrSlowDependency,x as scrubText,_ as scrubUrl};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{initAppInsights}from"./appInsights.js";
|
package/dist/auth/authStore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger as e}from"../logger/logger.js";import{getJWTExpiry as t}from"./jwt.js";var n=`accessToken`,r=`refreshToken`,i=`sessionUser`,a=2592e6,o=/* @__PURE__ */ new Set([n,r,i]),s=null,c=()=>globalThis.localStorage,l=()=>globalThis.sessionStorage,u=(e,t)=>{try{return e().getItem(t)}catch{return null}},d=(e,t)=>{try{e().removeItem(t)}catch{}},f=()=>s===null?u(c,`refreshToken`)!==null||u(c,`accessToken`)!==null:s,p=()=>f()?c:l,m=()=>f()?l:c,h=t=>{let n=s;s=t;let r=p(),i=m();for(let t of o){let a=u(i,t);if(a!==null)try{r().setItem(t,a),d(i,t)}catch(r){throw s=n,e.error(`[authStore] could not move "${t}" to the chosen store`,r),r}}},g=/* @__PURE__ */ new Set,_=`sessionEnded`,v=()=>u(l,_)!==null,y=(t,n)=>{try{l().setItem(_,t)}catch{}for(let r of[...g])try{r(t,n)}catch(t){e.error(`[authStore] a session-ended listener threw`,t)}},b=e=>{if(e.storageArea!==c())return;let t=e.key===`refreshToken`&&e.oldValue!==null&&e.newValue===null;(e.key===null||t)&&u(l,`refreshToken`)===null&&y(`otherTab`,{code:null,detail:null})},x=e=>(g.size===0&&typeof window<`u`&&window.addEventListener(`storage`,b),g.add(e),()=>{g.delete(e),g.size===0&&typeof window<`u`&&window.removeEventListener(`storage`,b)}),S=async(t,n,r)=>{try{p()().setItem(t,JSON.stringify({token:n,expiry:r})),d(m(),t),d(l,_)}catch(n){throw e.error(`Error storing token for key: ${t}`,n),n}},C=e=>{try{let t=JSON.parse(e);return t
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";import{getJWTExpiry as t}from"./jwt.js";var n=`accessToken`,r=`refreshToken`,i=`sessionUser`,a=2592e6,o=/* @__PURE__ */ new Set([n,r,i]),s=null,c=()=>globalThis.localStorage,l=()=>globalThis.sessionStorage,u=(e,t)=>{try{return e().getItem(t)}catch{return null}},d=(e,t)=>{try{e().removeItem(t)}catch{}},f=()=>s===null?u(c,`refreshToken`)!==null||u(c,`accessToken`)!==null:s,p=()=>f()?c:l,m=()=>f()?l:c,h=t=>{let n=s;s=t;let r=p(),i=m();for(let t of o){let a=u(i,t);if(a!==null)try{r().setItem(t,a),d(i,t)}catch(r){throw s=n,e.error(`[authStore] could not move "${t}" to the chosen store`,r),r}}},g=/* @__PURE__ */ new Set,_=`sessionEnded`,v=()=>u(l,_)!==null,y=(t,n)=>{try{l().setItem(_,t)}catch{}for(let r of[...g])try{r(t,n)}catch(t){e.error(`[authStore] a session-ended listener threw`,t)}},b=e=>{if(e.storageArea!==c())return;let t=e.key===`refreshToken`&&e.oldValue!==null&&e.newValue===null;(e.key===null||t)&&u(l,`refreshToken`)===null&&y(`otherTab`,{code:null,detail:null})},x=e=>(g.size===0&&typeof window<`u`&&window.addEventListener(`storage`,b),g.add(e),()=>{g.delete(e),g.size===0&&typeof window<`u`&&window.removeEventListener(`storage`,b)}),S=async(t,n,r)=>{try{p()().setItem(t,JSON.stringify({token:n,expiry:r})),d(m(),t),d(l,_)}catch(n){throw e.error(`Error storing token for key: ${t}`,n),n}},C=e=>typeof e==`object`&&!!e&&`token`in e&&typeof e.token==`string`&&`expiry`in e&&typeof e.expiry==`string`,w=e=>{try{let t=JSON.parse(e);return C(t)?t:null}catch{return null}},T=e=>u(l,e)??u(c,e),E=async t=>{let n=T(t);return n===null&&M(t)&&R()&&(n=T(t)),n===null?null:w(n)||(e.warn(`Stored credentials for key "${t}" are not a valid token; clearing them.`),M(t)?await z(`corrupt`,!0):await O(t),null)},D=()=>{T(`refreshToken`)===null&&T(`accessToken`)===null&&R();let e=T(r);if(e!==null&&w(e)!==null)return!0;let t=T(n),i=t===null?null:w(t);if(i===null)return!1;let a=Date.parse(i.expiry);return Number.isNaN(a)||a>Date.now()},O=async e=>{d(c,e),d(l,e)},k=async t=>{try{p()().setItem(i,JSON.stringify(t)),d(m(),i)}catch(t){throw e.error(`Error storing the session user`,t),t}},A=async t=>{let n=T(i);if(n===null)return null;let r;try{r=JSON.parse(n)}catch{return e.warn(`The stored session user is not valid JSON; clearing it.`),await j(),null}return r===null?null:t(r)},j=async()=>{d(c,i),d(l,i)},M=e=>e===`accessToken`||e===`refreshToken`,N=null,P=!1,F=e=>{N=e,P=!1},I=e=>{let t=w(e);if(t)return t;let n=e;try{let t=JSON.parse(e);typeof t==`string`&&(n=t)}catch{}return n.trim()===``?null:{token:n,expiry:null}},L=e=>e.split(`.`).length===3?t(e)?.toISOString()??null:null,R=()=>{if(!N||P)return!1;P=!0;let t=N,a=[c,l].every(e=>u(e,`accessToken`)===null&&u(e,`refreshToken`)===null),o=!1;for(let s of[c,l]){let l=u(s,t.accessToken),f=u(s,t.refreshToken),p=t.sessionUser?u(s,t.sessionUser):null,m=!1;if(a&&!o&&(l!==null||f!==null))try{let t=l===null?null:I(l),a=f===null?null:I(f);if(t){let e=t.expiry??L(t.token)??(/* @__PURE__ */ new Date()).toISOString();s().setItem(n,JSON.stringify({token:t.token,expiry:e}))}if(a){let e=a.expiry??L(a.token)??new Date(Date.now()+2592e6).toISOString();s().setItem(r,JSON.stringify({token:a.token,expiry:e}))}p!==null&&s().setItem(i,p),o=t!==null||a!==null,o&&e.breadcrumb(`[authStore] moved a session from the legacy token keys`,{store:s===c?`localStorage`:`sessionStorage`})}catch(t){m=!0,d(s,n),d(s,r),e.error(`[authStore] could not move the session from the legacy token keys`,t)}if(!m)for(let e of[t.accessToken,t.refreshToken,t.sessionUser])e&&d(s,e)}return o},z=async(e,t,i=null,a=null)=>{let o=t||await E(`accessToken`)!==null||await E(`refreshToken`)!==null;await O(n),await O(r),await j(),s=null,(o||t)&&y(e,{code:i,detail:a})},B=async(e=`signedOut`,t={})=>z(e,!1,t.code??null,t.detail??null);export{n as ACCESS_TOKEN_KEY,a as LEGACY_REFRESH_TOKEN_LIFETIME_MS,r as REFRESH_TOKEN_KEY,i as SESSION_USER_KEY,x as addSessionEndedListener,B as clearSession,f as getKeepSignedIn,A as getSessionUser,E as getToken,D as hasSession,v as hasSessionEndedInTab,j as removeSessionUser,O as removeToken,h as setKeepSignedIn,F as setLegacyTokenKeys,k as storeSessionUser,S as storeToken};
|
package/dist/auth/jwt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger as e}from"../logger/logger.js";var t=e=>(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=e=>{try{return decodeURIComponent(e.split(``).map(e=>`%${e.charCodeAt(0).toString(16).padStart(2,`0`)}`).join(``))}catch{return e}},r=r=>{if(!
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";var t=e=>(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=e=>{try{return decodeURIComponent(e.split(``).map(e=>`%${e.charCodeAt(0).toString(16).padStart(2,`0`)}`).join(``))}catch{return e}},r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),i=e=>typeof e==`string`,a=e=>typeof e==`number`,o=e=>i(e)||Array.isArray(e)&&e.every(i),s=(t,n,r)=>n===void 0||r(n)?!0:(e.warn(`[jwt] decodeJWT: claim "${t}" has the wrong type`),!1),c=e=>{let{sub:t,exp:n,iat:r,nbf:c,iss:l,aud:u,...d}=e;return!s(`sub`,t,i)||!s(`exp`,n,a)||!s(`iat`,r,a)||!s(`nbf`,c,a)||!s(`iss`,l,i)||!s(`aud`,u,o)?null:{sub:t,exp:n,iat:r,nbf:c,iss:l,aud:u,...d}},l=i=>{if(!i||typeof i!=`string`)return null;let a=i.split(`.`),o=a.length===3?a[1]:void 0;if(o===void 0)return e.warn(`[jwt] decodeJWT: token is not a valid JWT (expected 3 segments)`),null;let s;try{let e=n(atob(t(o)));s=JSON.parse(e)}catch(t){return e.warn(`[jwt] decodeJWT failed to parse payload`,t),null}return r(s)?c(s):(e.warn(`[jwt] decodeJWT: payload is not a JSON object`),null)};function u(e,t){let n=l(e);return n===null||t===void 0?n:t(n)}var d=(e,t=30)=>{let n=u(e);if(!n||typeof n.exp!=`number`)return!0;let r=Math.floor(Date.now()/1e3);return n.exp<=r+t},f=e=>{let t=u(e);return!t||typeof t.exp!=`number`?null:/* @__PURE__ */ new Date(t.exp*1e3)};export{u as decodeJWT,f as getJWTExpiry,d as isJWTExpired};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
at `)
|
|
1
|
+
import{isOfflineFailure as e}from"./requestPlatform.js";var t=`Something went wrong on our side. Please try again in a moment.`,n=`You appear to be offline. Check your connection and try again.`,r=`We couldn't reach the server. Check your connection and try again.`,i=`That took too long to respond. Check your connection and try again.`,a=`Something went wrong. Please try again.`,o=`request_canceled`,s=`contract_error`,c=`timeout`,l=`network`,u=`offline`,d=300,f=`internal_error`,p=e=>`Request failed (${e})`,m={401:{code:`unauthorized`,sentence:`Please sign in to continue.`},403:{code:`forbidden`,sentence:`You do not have access to this.`}},h=e=>typeof e==`object`&&!!e&&!Array.isArray(e),g=e=>typeof e==`string`&&e.trim().length>0?e:null,_=(e,t)=>{let n=m[e];if(n===void 0||t===null||t.code!==n.code)return null;let r=g(t.detail);return r===null||r===n.sentence?n.sentence:null},v=e=>e.length>d||/^\s*</.test(e)||e.includes(`
|
|
2
|
+
at `)||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),y=e=>{let t=g(e);return t!==null&&!v(t)?t:null},b=e=>e.replace(/^\$\.?/,``).split(`.`).map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(`.`),x=e=>{if(Array.isArray(e)){for(let t of e){let e=g(t);if(e!==null)return e}return null}return g(e)},S=(e,t,n)=>{let r=b(t);r===``?e.form??=n:r in e.fields||(e.fields[r]=n)},C=e=>{let t={fields:{},form:null};if(Array.isArray(e)){for(let n of e){if(!h(n))continue;let e=g(n.message);e!==null&&S(t,typeof n.field==`string`?n.field:``,e)}return t}if(!h(e))return t;for(let[n,r]of Object.entries(e)){let e=x(r);e!==null&&S(t,n,e)}return t},w=e=>h(e)&&typeof e.message==`string`&&typeof e.status==`number`&&typeof e.offline==`boolean`&&h(e.fieldErrors),T=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),E=e=>{let t=h(e.config)?e.config.headers:void 0;if(!h(t))return null;let n=typeof t.get==`function`?t.get(`traceparent`):t.traceparent??t.Traceparent;return(typeof n==`string`?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null)?.[1]??null},D=t=>{let s=g(t.code),d=g(t.name),f=g(t.message),p=E(t);return d===`CanceledError`||s===`ERR_CANCELED`?T({code:o,message:a,traceId:p,diagnostic:f}):s===`ECONNABORTED`||s===`ETIMEDOUT`?T({code:c,message:i,offline:!0,traceId:p,diagnostic:f}):d===`RequestOfflineError`||s===`ERR_NETWORK`||f===`Network Error`||f===`Network request failed`?e(t)?T({code:u,message:n,offline:!0,traceId:p,diagnostic:f}):T({code:l,message:r,offline:!0,traceId:p,diagnostic:f}):T({message:a,traceId:p,diagnostic:f})};function O(e){if(w(e))return e;if(typeof e==`string`)return T({message:y(e)??`Something went wrong. Please try again.`,diagnostic:e||null});if(!h(e))return T({message:a,diagnostic:e==null?null:String(e)});if(e.isContractError===!0)return T({code:s,message:y(e.message)??`Something went wrong. Please try again.`,diagnostic:g(e.message)});let t=h(e.response)?e.response:null,n=typeof t?.status==`number`?t.status:typeof e.status==`number`?e.status:0,r=t?t.data:e.body;if(n===0&&r==null)return D(e);let i=h(r)?r:null,{fields:o,form:c}=C(i?.errors),l=g(i?.code),u=g(i?.traceId)??E(e),d=g(i?.detail)??g(i?.title)??g(r)??g(e.message),m;return m=n>=500?(l!==null&&l!==f?y(i?.detail):null)??`Something went wrong on our side. Please try again in a moment.`:_(n,i)??y(Object.values(o)[0])??y(c)??y(i?.detail)??y(i?.title)??y(r)??(n?p(n):`Something went wrong. Please try again.`),T({code:l,message:m,fieldErrors:o,status:n,traceId:u,diagnostic:d})}var k=e=>O(e).offline;function A(e,t){let n=O(e);return n.offline||t!==null&&!t||n.status>=500&&n.message!==`Something went wrong on our side. Please try again in a moment.`?n.message:n.status>=500||n.code===`request_canceled`||n.message===`Something went wrong. Please try again.`||n.message===p(n.status)?t??null:n.message}export{s as CONTRACT_ERROR_CODE,l as NETWORK_CODE,u as OFFLINE_CODE,n as OFFLINE_MESSAGE,o as REQUEST_CANCELED_CODE,t as SERVER_FAILURE_MESSAGE,c as TIMEOUT_CODE,i as TIMEOUT_MESSAGE,a as UNEXPECTED_MESSAGE,r as UNREACHABLE_MESSAGE,A as apiErrorMessage,O as extractApiError,w as isApiError,k as isNoResponse,b as toFieldPath};
|
package/dist/errors/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{CONTRACT_ERROR_CODE as e,NETWORK_CODE as t,OFFLINE_CODE as n,OFFLINE_MESSAGE as r,REQUEST_CANCELED_CODE as i,SERVER_FAILURE_MESSAGE as a,TIMEOUT_CODE as o,TIMEOUT_MESSAGE as s,UNEXPECTED_MESSAGE as c,UNREACHABLE_MESSAGE as l,apiErrorMessage as u,extractApiError as d,isApiError as f,isNoResponse as p,toFieldPath as m}from"./extractApiError.js";import{parseResponse as h}from"./parseResponse.js";export{e as CONTRACT_ERROR_CODE,t as NETWORK_CODE,n as OFFLINE_CODE,r as OFFLINE_MESSAGE,i as REQUEST_CANCELED_CODE,a as SERVER_FAILURE_MESSAGE,o as TIMEOUT_CODE,s as TIMEOUT_MESSAGE,c as UNEXPECTED_MESSAGE,l as UNREACHABLE_MESSAGE,u as apiErrorMessage,d as extractApiError,f as isApiError,p as isNoResponse,h as parseResponse,m as toFieldPath};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";var t=`The server returned unexpected data. Please try again.`;function n(n,r,i){let a=n.safeParse(r);if(a.success)return a.data;throw e.error(`[contract] ${i} response failed validation`,a.error.issues),Object.assign(/* @__PURE__ */ Error(t),{isContractError:!0})}export{n as parseResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return typeof navigator<`u`&&navigator.onLine===!1}export{e as isOfflineFailure};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{configuredLocale as e,getFormatterConfig as t,isFormatterConfigured as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{numberFormat as a}from"./intlCache.js";var o=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,s=(e,t)=>{let{decimal:n,group:i}=r()??{decimal:`.`,group:`,`},a=e<0?`-`:``,[o
|
|
1
|
+
import{configuredLocale as e,getFormatterConfig as t,isFormatterConfigured as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{numberFormat as a}from"./intlCache.js";var o=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,s=(e,t)=>{let{decimal:n,group:i}=r()??{decimal:`.`,group:`,`},a=e<0?`-`:``,[o=`0`,s=``]=Math.abs(e).toFixed(t).split(`.`),c=o.length>3?o.slice(-3):o,l=o.length>3?o.slice(0,-3):``;return a+(l?l.replace(/\B(?=(\d{2})+(?!\d))/g,i)+i+c:c)+(s?`${n}${s}`:``)},c=e=>{if(e==null||typeof e==`string`&&e.trim()===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},l=(e,t)=>a(e,{style:`currency`,currency:t}).resolvedOptions().maximumFractionDigits??2,u=(r,u)=>{let{currency:d,locale:f=e()??`en-IN`,minimumFractionDigits:p,maximumFractionDigits:m,stripSymbol:h=!1,empty:g=n(`locale`)||n(`empty`)?t().empty:``,..._}=u;if(!d)throw TypeError(`[@webority/web-core] formatCurrency needs options.currency, an ISO 4217 code such as "INR".`);let v=c(r);if(v===null)return g;if(o())try{let e=m??l(f,d),t=p??(Number.isInteger(v)?0:e),n=i(a(f,{..._,style:`currency`,currency:d,minimumFractionDigits:t,maximumFractionDigits:Math.max(t,e)}),v);return h?n.replace(/[^\d,.\s\-+]/g,``).trim():n}catch(e){throw RangeError(`formatCurrency: currency "${d}" or locale "${f}" is not valid: ${e instanceof Error?e.message:String(e)}`)}let y=s(v,p??(Number.isInteger(v)?0:2));return h?y:d===`INR`?`₹${y}`:`${d} ${y}`};export{u as formatCurrency};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e={zone:`IST`,locale:`en-IN`,empty:`-`},t={PointWithCommaGroups:{decimal:`.`,group:`,`},CommaWithPointGroups:{decimal:`,`,group:`.`},CommaWithSpaceGroups:{decimal:`,`,group:`\xA0`},PointWithSpaceGroups:{decimal:`.`,group:`\xA0`}},n=[`DayMonthNameYear`,`DayMonthYear`,`MonthDayYear`,`YearMonthDay`],r={...e},
|
|
1
|
+
var e={zone:`IST`,locale:`en-IN`,empty:`-`},t={PointWithCommaGroups:{decimal:`.`,group:`,`},CommaWithPointGroups:{decimal:`,`,group:`.`},CommaWithSpaceGroups:{decimal:`,`,group:`\xA0`},PointWithSpaceGroups:{decimal:`.`,group:`\xA0`}},n=[`DayMonthNameYear`,`DayMonthYear`,`MonthDayYear`,`YearMonthDay`],r=e=>{if(e===`IST`||e===`viewer`||e===`UTC`)return!0;try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e}),!0}catch(e){if(e instanceof RangeError)return!1;throw e}},i=[`zone`,`locale`,`empty`,`numberStyle`,`dateOrder`],a=e=>i.some(t=>t===e),o={...e},s=/* @__PURE__ */ new Set,c=c=>{if(c===void 0)o={...e},s=/* @__PURE__ */ new Set;else{if(c.zone!==void 0&&!r(c.zone))throw RangeError(`Unknown zone "${c.zone}"; expected IST, viewer, UTC or an IANA zone name.`);if(c.numberStyle!==void 0&&!Object.hasOwn(t,c.numberStyle))throw RangeError(`Unknown number style "${c.numberStyle}"; expected one of ${Object.keys(t).join(`, `)}.`);if(c.dateOrder!==void 0&&!n.includes(c.dateOrder))throw RangeError(`Unknown date order "${c.dateOrder}"; expected one of ${n.join(`, `)}.`);for(let e of Object.keys(c)){if(!a(e))throw RangeError(`Unknown setting "${e}"; expected one of ${i.join(`, `)}.`);let t=c[e];t!==void 0&&(o={...o,[e]:t},s.add(e))}}},l=()=>({...o}),u=e=>s.has(e),d=()=>s.has(`locale`)?o.locale:null,f=e=>/-IN(?:-|$)/i.test(e)?`indian`:`international`,p=()=>o.numberStyle===void 0?null:t[o.numberStyle],m=/* @__PURE__ */ new Map,h=e=>{let t=new Intl.NumberFormat(e,{useGrouping:!1}),n=/* @__PURE__ */ new Set;for(let e=0;e<=9;e++)n.add(t.format(e));return n},g=(e,t)=>{let n=[],r=[],i=!1;for(let a of e)t.has(a)?(r.length>0&&(n.push(r),r=[]),i=!0):i&&r.push(a);return n},_=e=>{let t=m.get(e);if(t!==void 0)return t;let n=h(e),r=new Intl.NumberFormat(e,{useGrouping:!0,minimumFractionDigits:1,maximumFractionDigits:1}).format(11111.5),i=g(Array.from(r),n),a={digits:n,decimal:i.at(-1)??null,group:i.length>=2?i.at(0)??null:null};return m.set(e,a),a},v=(e,t,n)=>{let r=t>=0?e.at(t):void 0;return r!==void 0&&n.has(r)},y=(e,t,n)=>{let r=Array.from(e),i=``,a=0;for(;a<r.length;){let e=n.find(({mark:e})=>v(r,a-1,t)&&e.every((e,t)=>r[a+t]===e)&&v(r,a+e.length,t));e===void 0?(i+=r[a],a+=1):(i+=e.to,a+=e.mark.length)}return i},b=(e,t)=>{let n=p();if(n===null)return e.format(t);let{digits:r,decimal:i,group:a}=_(e.resolvedOptions().locale),o=[];return i!==null&&o.push({mark:i,to:n.decimal}),a!==null&&o.push({mark:a,to:n.group}),y(e.format(t),r,o)};export{c as configureFormatters,d as configuredLocale,l as getFormatterConfig,f as groupingForLocale,u as isFormatterConfigured,p as numberSeparators,b as styledNumber};
|
package/dist/formatters/house.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{configuredLocale as e,getFormatterConfig as t,groupingForLocale as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{dateTimeFormat as a,numberFormat as o,relativeTimeFormat as s}from"./intlCache.js";var c=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],l=330,u=[`IST`,`Asia/Kolkata`,`Asia/Calcutta`],d=/^\d{4}-\d{2}-\d{2}$/,f=e=>e<10?`0${e}`:`${e}`,p=e=>e??t().empty,m=e=>{if(e==null||e===``)return null;let t=e instanceof Date?e:new Date(typeof e==`string`?e.trim():e);return Number.isNaN(t.getTime())?null:t},h=e=>typeof e==`string`&&d.test(e.trim()),g=e=>{if(e===0)return`GMT`;let t=e>0?`+`:`-`,n=Math.abs(e),r=n%60;return`GMT${t}${Math.floor(n/60)}${r===0?``:`:${f(r)}`}`},_=(e,t,n)=>{let r=new Date(e.getTime()+t*6e4);return{year:r.getUTCFullYear(),month:r.getUTCMonth(),day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),label:n}},v=(e,t)=>{let n=a(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,hour12:!1}).formatToParts(e),r=e=>Number.parseInt(n.find(t=>t.type===e)?.value??``,10),i=r(`year`),o=r(`month`)-1,s=r(`day`),c=r(`hour`)%24,l=r(`minute`);return{year:i,month:o,day:s,hour:c,minute:l,label:g(Math.round((Date.UTC(i,o,s,c,l)-Math.floor(e.getTime()/6e4)*6e4)/6e4))}},y=(e,t)=>u.includes(t)?_(e,l,`IST`):t===`UTC`?_(e,0,`UTC`):t===`viewer`?{year:e.getFullYear(),month:e.getMonth(),day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),label:g(-e.getTimezoneOffset())}:v(e,t),b=e=>e.hourCycle??12,x=e=>`${f(e.day)}-${c[e.month]}-${e.year}`,S=(e,t)=>{let n=f(e.day),r=f(e.month+1),i=String(e.year).padStart(4,`0`);return t===`DayMonthYear`?`${n}/${r}/${i}`:t===`MonthDayYear`?`${r}/${n}/${i}`:`${i}-${r}-${n}`},C=(e,t)=>t===24?`${f(e.hour)}:${f(e.minute)}`:`${e.hour%12||12}:${f(e.minute)} ${e.hour<12?`AM`:`PM`}`,w=(e,t)=>t??!u.includes(e),T=(e,t,n,r)=>w(n,r)?`${e} ${t.label}`:e,E=e=>{if(e!==`viewer`)return u.includes(e)?`Asia/Kolkata`:e},D=(e,t,n)=>{let r=a(t,{day:`2-digit`,month:`short`,year:`numeric`,timeZone:n}).formatToParts(e),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`day`)}-${i(`month`).replace(`.`,``)}-${i(`year`)}`},O=(n,r)=>{let i=t().dateOrder??`DayMonthNameYear`;if(i!==`DayMonthNameYear`)return S(y(n,r),i);let a=e();return a?D(n,a,E(r)):x(y(n,r))},k=(e,t,n,r)=>a(t,{hour:`2-digit`,minute:`2-digit`,timeZone:E(n),timeZoneName:w(n,r.zoneLabel)?`short`:void 0,hourCycle:r.hourCycle===void 0?void 0:r.hourCycle===24?`h23`:`h12`}).format(e),A=(e,n={})=>{let r=m(e);return r?O(r,h(e)?`UTC`:n.zone??t().zone):p(n.empty)},ee=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return k(i,o,a,r);let s=y(i,a);return T(C(s,b(r)),s,a,r.zoneLabel)},te=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return`${O(i,a)}, ${k(i,o,a,r)}`;let s=y(i,a);return T(`${O(i,a)}, ${C(s,b(r))}`,s,a,r.zoneLabel)},j=1e3,M=60*j,N=60*M,P=24*N,F=7*P,I=30*P,L=365*P,R=[[`year`,L],[`month`,I],[`day`,P],[`hour`,N],[`minute`,M]],z=(n,r={})=>{let i=m(n),a=m(r.now??Date.now());if(!i||!a)return p(r.empty);let o=i.getTime()-a.getTime(),c=Math.abs(o),l=Intl.RelativeTimeFormat,u=e();if((u!==null||r.intl===!0)&&typeof l==`function`){let e=s(l,u??t().locale),[n,r]=R.find(([,e])=>c>=e)??[`second`,j];return e.format(Math.round(o/r),n)}if(c<M)return`just now`;let[d,f]=c<N?[`minute`,M]:c<P?[`hour`,N]:c<F?[`day`,P]:c<I?[`week`,F]:c<L?[`month`,I]:[`year`,L],h=Math.floor(c/f),g=`${h} ${d}${h===1?``:`s`}`;return o<0?`${g} ago`:`in ${g}`},B=e=>{if(e==null||typeof e==`string`&&e.trim()===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},V=e=>Math.min(20,Math.max(0,Math.trunc(e))),H=(e,t)=>/e/i.test(String(e))?e*10**t:Number(`${e}e${t}`),U=()=>r()??{decimal:`.`,group:`,`},W=(e,t,n)=>t===`none`||e.length<=3?e:t===`international`?e.replace(/\B(?=(\d{3})+(?!\d))/g,n):`${e.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,n)}${n}${e.slice(-3)}`,G=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,K=(e,t)=>{if(G())return o(`en-US`,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t}).format(e);let n=Math.min(t,15);return H(Math.round(H(e,n)),-n).toFixed(n)},q=(e,t,n,r)=>{let i=Math.max(V(n),V(t)),a=V(t),o=K(Math.abs(e),i),[s=`0`,c=``]=o.split(`.`),l=c.padEnd(a,`0`);for(;l.length>a&&l.endsWith(`0`);)l=l.slice(0,-1);let u=U(),d=W(s,r,u.group)+(l?`${u.decimal}${l}`:``);return e<0&&/[1-9]/.test(o)?`-${d}`:d},J=/* @__PURE__ */ new Set([`grouping`,`minimumFractionDigits`,`maximumFractionDigits`,`locale`,`empty`,`scale`]),Y=e=>{if(!Object.entries(e).some(([e,t])=>t!==void 0&&!J.has(e)))return null;let{grouping:t,locale:n,empty:r,scale:i,...a}=e;return t===`none`&&a.useGrouping===void 0?{...a,useGrouping:!1}:a},X=e=>e.locale??t().locale,Z=t=>{let n=e();return n===null||t.grouping===`indian`||t.grouping===`international`?null:t.locale??n},Q=(e,t)=>{let n=V(e);return{minimumFractionDigits:n,maximumFractionDigits:Math.max(n,V(t))}},$=e=>e===`none`?{useGrouping:!1}:{},ne=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a)return i(o(X(t),a),r);let s=Z(t);return s?i(o(s,{...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??3),...$(t.grouping)}),r):q(r,t.minimumFractionDigits??0,t.maximumFractionDigits??3,t.grouping??n(X(t)))},re=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a){let e=t.scale===`percent`?H(r,-2):r;return i(o(X(t),{style:`percent`,...a}),e)}let s=Z(t);if(s){let e=t.scale===`percent`?H(r,-2):r;return i(o(s,{style:`percent`,...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0),...$(t.grouping)}),e)}return`${q(t.scale===`percent`?r:H(r,2),t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0,t.grouping??n(X(t)))}%`},ie={INR:`₹`,USD:`$`,EUR:`€`,GBP:`£`},ae={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},oe=(e,t)=>{if(!t?.currency)throw TypeError(`formatMinor needs options.currency, an ISO 4217 code such as "INR".`);let n=B(e);if(n===null)return p(t.empty);let r=t.currency.toUpperCase(),a=ae[r]??2,s=Math.round(Math.abs(n)),c=String(s).padStart(a+1,`0`),l=c.slice(0,c.length-a),u=c.slice(c.length-a);t.dropZeroDecimals&&/^0*$/.test(u)&&(u=``);let d=Z({grouping:t.grouping});if(d)try{let e=Number(`${n<0&&s!==0?`-`:``}${l}.${c.slice(c.length-a)||`0`}`);return i(o(d,{...t.symbol===!1?{}:{style:`currency`,currency:r},...Q(u?a:0,a),...$(t.grouping)}),e)}catch(e){throw e instanceof RangeError?RangeError(`formatMinor rejected currency "${r}" or locale "${d}": ${e.message}`,{cause:e}):e}let f=t.grouping??(r===`INR`?`indian`:`international`),m=U(),h=W(l,f,m.group)+(u?`${m.decimal}${u}`:``),g=n<0&&s!==0?`-`:``;if(t.symbol===!1)return`${g}${h}`;let _=ie[r];return _?`${g}${_}${h}`:`${g}${r} ${h}`};export{A as formatDate,te as formatDateTime,oe as formatMinor,ne as formatNumber,re as formatPercent,z as formatRelative,ee as formatTime};
|
|
1
|
+
import{configuredLocale as e,getFormatterConfig as t,groupingForLocale as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{dateTimeFormat as a,numberFormat as o,relativeTimeFormat as s}from"./intlCache.js";var c=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],l=330,u=[`IST`,`Asia/Kolkata`,`Asia/Calcutta`],d=/^\d{4}-\d{2}-\d{2}$/,f=e=>e<10?`0${e}`:`${e}`,p=e=>e??t().empty,m=e=>{if(e==null||e===``)return null;let t=e instanceof Date?e:new Date(typeof e==`string`?e.trim():e);return Number.isNaN(t.getTime())?null:t},h=e=>typeof e==`string`&&d.test(e.trim()),g=e=>{if(e===0)return`GMT`;let t=e>0?`+`:`-`,n=Math.abs(e),r=n%60;return`GMT${t}${Math.floor(n/60)}${r===0?``:`:${f(r)}`}`},_=(e,t,n)=>{let r=new Date(e.getTime()+t*6e4);return{year:r.getUTCFullYear(),month:r.getUTCMonth(),day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),label:n}},v=(e,t)=>{let n=a(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,hour12:!1}).formatToParts(e),r=e=>Number.parseInt(n.find(t=>t.type===e)?.value??``,10),i=r(`year`),o=r(`month`)-1,s=r(`day`),c=r(`hour`)%24,l=r(`minute`);return{year:i,month:o,day:s,hour:c,minute:l,label:g(Math.round((Date.UTC(i,o,s,c,l)-Math.floor(e.getTime()/6e4)*6e4)/6e4))}},y=(e,t)=>u.includes(t)?_(e,l,`IST`):t===`UTC`?_(e,0,`UTC`):t===`viewer`?{year:e.getFullYear(),month:e.getMonth(),day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),label:g(-e.getTimezoneOffset())}:v(e,t),b=e=>e.hourCycle??12,x=e=>`${f(e.day)}-${c[e.month]}-${e.year}`,S=(e,t)=>{let n=f(e.day),r=f(e.month+1),i=String(e.year).padStart(4,`0`);return t===`DayMonthYear`?`${n}/${r}/${i}`:t===`MonthDayYear`?`${r}/${n}/${i}`:`${i}-${r}-${n}`},C=(e,t)=>t===24?`${f(e.hour)}:${f(e.minute)}`:`${e.hour%12||12}:${f(e.minute)} ${e.hour<12?`AM`:`PM`}`,w=(e,t)=>t??!u.includes(e),T=(e,t,n,r)=>w(n,r)?`${e} ${t.label}`:e,E=e=>{if(e!==`viewer`)return u.includes(e)?`Asia/Kolkata`:e},D=(e,t,n)=>{let r=a(t,{day:`2-digit`,month:`short`,year:`numeric`,timeZone:n}).formatToParts(e),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`day`)}-${i(`month`).replace(`.`,``)}-${i(`year`)}`},O=(n,r)=>{let i=t().dateOrder??`DayMonthNameYear`;if(i!==`DayMonthNameYear`)return S(y(n,r),i);let a=e();return a?D(n,a,E(r)):x(y(n,r))},k=(e,t,n,r)=>a(t,{hour:`2-digit`,minute:`2-digit`,timeZone:E(n),timeZoneName:w(n,r.zoneLabel)?`short`:void 0,hourCycle:r.hourCycle===void 0?void 0:r.hourCycle===24?`h23`:`h12`}).format(e),A=(e,n={})=>{let r=m(e);return r?O(r,h(e)?`UTC`:n.zone??t().zone):p(n.empty)},ee=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return k(i,o,a,r);let s=y(i,a);return T(C(s,b(r)),s,a,r.zoneLabel)},te=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return`${O(i,a)}, ${k(i,o,a,r)}`;let s=y(i,a);return T(`${O(i,a)}, ${C(s,b(r))}`,s,a,r.zoneLabel)},j=1e3,M=60*j,N=60*M,P=24*N,F=7*P,I=30*P,L=365*P,R=[[`year`,L],[`month`,I],[`day`,P],[`hour`,N],[`minute`,M]],z=(n,r={})=>{let i=m(n),a=m(r.now??Date.now());if(!i||!a)return p(r.empty);let o=i.getTime()-a.getTime(),c=Math.abs(o),l=typeof Intl.RelativeTimeFormat==`function`?Intl.RelativeTimeFormat:void 0,u=e();if((u!==null||r.intl===!0)&&typeof l==`function`){let e=s(l,u??t().locale),[n,r]=R.find(([,e])=>c>=e)??[`second`,j];return e.format(Math.round(o/r),n)}if(c<M)return`just now`;let[d,f]=c<N?[`minute`,M]:c<P?[`hour`,N]:c<F?[`day`,P]:c<I?[`week`,F]:c<L?[`month`,I]:[`year`,L],h=Math.floor(c/f),g=`${h} ${d}${h===1?``:`s`}`;return o<0?`${g} ago`:`in ${g}`},B=e=>{if(e==null||typeof e==`string`&&e.trim()===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},V=e=>Math.min(20,Math.max(0,Math.trunc(e))),H=(e,t)=>/e/i.test(String(e))?e*10**t:Number(`${e}e${t}`),U=()=>r()??{decimal:`.`,group:`,`},W=(e,t,n)=>t===`none`||e.length<=3?e:t===`international`?e.replace(/\B(?=(\d{3})+(?!\d))/g,n):`${e.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,n)}${n}${e.slice(-3)}`,G=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,K=(e,t)=>{if(G())return o(`en-US`,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t}).format(e);let n=Math.min(t,15);return H(Math.round(H(e,n)),-n).toFixed(n)},q=(e,t,n,r)=>{let i=Math.max(V(n),V(t)),a=V(t),o=K(Math.abs(e),i),[s=`0`,c=``]=o.split(`.`),l=c.padEnd(a,`0`);for(;l.length>a&&l.endsWith(`0`);)l=l.slice(0,-1);let u=U(),d=W(s,r,u.group)+(l?`${u.decimal}${l}`:``);return e<0&&/[1-9]/.test(o)?`-${d}`:d},J=/* @__PURE__ */ new Set([`grouping`,`minimumFractionDigits`,`maximumFractionDigits`,`locale`,`empty`,`scale`]),Y=e=>{if(!Object.entries(e).some(([e,t])=>t!==void 0&&!J.has(e)))return null;let{grouping:t,locale:n,empty:r,scale:i,...a}=e;return t===`none`&&a.useGrouping===void 0?{...a,useGrouping:!1}:a},X=e=>e.locale??t().locale,Z=t=>{let n=e();return n===null||t.grouping===`indian`||t.grouping===`international`?null:t.locale??n},Q=(e,t)=>{let n=V(e);return{minimumFractionDigits:n,maximumFractionDigits:Math.max(n,V(t))}},$=e=>e===`none`?{useGrouping:!1}:{},ne=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a)return i(o(X(t),a),r);let s=Z(t);return s?i(o(s,{...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??3),...$(t.grouping)}),r):q(r,t.minimumFractionDigits??0,t.maximumFractionDigits??3,t.grouping??n(X(t)))},re=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a){let e=t.scale===`percent`?H(r,-2):r;return i(o(X(t),{style:`percent`,...a}),e)}let s=Z(t);if(s){let e=t.scale===`percent`?H(r,-2):r;return i(o(s,{style:`percent`,...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0),...$(t.grouping)}),e)}return`${q(t.scale===`percent`?r:H(r,2),t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0,t.grouping??n(X(t)))}%`},ie={INR:`₹`,USD:`$`,EUR:`€`,GBP:`£`},ae={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},oe=(e,t)=>{if(!t?.currency)throw TypeError(`formatMinor needs options.currency, an ISO 4217 code such as "INR".`);let n=B(e);if(n===null)return p(t.empty);let r=t.currency.toUpperCase(),a=ae[r]??2,s=Math.round(Math.abs(n)),c=String(s).padStart(a+1,`0`),l=c.slice(0,c.length-a),u=c.slice(c.length-a);t.dropZeroDecimals&&/^0*$/.test(u)&&(u=``);let d=Z({grouping:t.grouping});if(d)try{let e=Number(`${n<0&&s!==0?`-`:``}${l}.${c.slice(c.length-a)||`0`}`);return i(o(d,{...t.symbol===!1?{}:{style:`currency`,currency:r},...Q(u?a:0,a),...$(t.grouping)}),e)}catch(e){throw e instanceof RangeError?RangeError(`formatMinor rejected currency "${r}" or locale "${d}": ${e.message}`,{cause:e}):e}let f=t.grouping??(r===`INR`?`indian`:`international`),m=U(),h=W(l,f,m.group)+(u?`${m.decimal}${u}`:``),g=n<0&&s!==0?`-`:``;if(t.symbol===!1)return`${g}${h}`;let _=ie[r];return _?`${g}${_}${h}`:`${g}${r} ${h}`};export{A as formatDate,te as formatDateTime,oe as formatMinor,ne as formatNumber,re as formatPercent,z as formatRelative,ee as formatTime};
|
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{DESIGN_SAMPLE_HEADER 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{configureFormatters as He,getFormatterConfig as Ue}from"./formatters/formatConfig.js";import{formatCurrency as We}from"./formatters/currency.js";import{addDays as Ge}from"./formatters/dateMath.js";import{formatDate as Ke,formatDateTime as qe,formatMinor as Je,formatNumber as Ye,formatPercent as Xe,formatRelative as Ze,formatTime as Qe}from"./formatters/house.js";import{staticUrl as $e}from"./static/index.js";import{createApiBaseQuery as et}from"./query/apiBaseQuery.js";import{APP_API_DEFAULTS as tt,createAppApi as nt}from"./query/createAppApi.js";import{useDataState as rt}from"./query/dataState.js";import{setupApiListeners as it}from"./query/listeners.js";import{LIST_QUERY_RESERVED as at,SEARCH_PARAM as ot,buildListQuery as st,emptyFacetValue as ct,isFacetActive as lt,listQueryParamNames as ut,parseListQuery as dt}from"./query/listQuery.js";import{getNextPageParam as ft,getPreviousPageParam as pt,hasNextPage as mt,hasPreviousPage as ht}from"./query/paging.js";import{LIST_TAG_ID as gt,itemTag as _t,listTag as vt,providesList as yt,providesPagedList as bt}from"./query/tags.js";import{useListQuery as xt}from"./query/useListQuery.js";import{errorToastMiddleware as St,isSilentRejection as Ct}from"./redux/errorToastMiddleware.js";import{createRootReducer as wt,resetState as Tt}from"./redux/rootReducer.js";import{SERIALIZABLE_IGNORED_ACTION_PATHS as Et}from"./redux/serializableCheck.js";import{hasRecentlyReloaded as Dt,importWithReload as Ot,isChunkLoadError as kt,lazyWithReload as At,markReloaded as jt}from"./router/chunkReload.js";import{classifyRouteError as Mt,useRouteErrorReport as Nt}from"./router/routeError.js";import{ErrorBoundary as Pt}from"./router/ErrorBoundary.js";import{hasPermission as Ft}from"./router/permissions.js";import{RETURN_TO_PARAM as It,buildLoginPath as Lt,getReturnTo as Rt,toSafeReturnTo as zt}from"./router/returnTo.js";import{PublicOnly as Bt,RequireAuth as Vt,RequirePermission as Ht}from"./router/guards.js";import{publicOnly as Ut,requireAuth as Wt,requirePermission as Gt,withGuards as Kt}from"./router/loaders.js";import{defineRouteTable as qt}from"./router/routeTable.js";import{Storage as Jt,isStorageAvailable as Yt,setStorageImplementation as Xt,syncSessionStorage as Zt,syncStorage as Qt}from"./storage/index.js";import{isBuildBelowMinimum as $t,parseBuildNumber as en}from"./versionCheck/buildNumber.js";import{addDeployedBuildListener as tn,getNewerDeployedBuild as nn,startDeployedBuildCheck as rn}from"./versionCheck/deployedBuild.js";import{installReloadOnNavigate as an,isUpdateAvailable as on,useVersionCheck as sn}from"./versionCheck/index.js";export{b as ACCESS_TOKEN_KEY,V as ACCOUNT_ID_HEADER,tt 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,Pt as ErrorBoundary,ie as IDEMPOTENCY_KEY_HEADER,x as LEGACY_REFRESH_TOKEN_LIFETIME_MS,at as LIST_QUERY_RESERVED,gt 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,Bt as PublicOnly,ue as REFRESH_LOCK_NAME,S as REFRESH_TOKEN_KEY,Oe as REQUEST_CANCELED_CODE,It as RETURN_TO_PARAM,be as RequestOfflineError,Vt as RequireAuth,Ht as RequirePermission,ot as SEARCH_PARAM,Et 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,Jt 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,Ge as addDays,tn as addDeployedBuildListener,$ as addMinAppVersionListener,L as addNetworkStatusListener,w as addSessionEndedListener,Pe as apiErrorMessage,X as applyDesignSample,u as applyRequestDefaults,ae as attachRetry,st as buildListQuery,Lt as buildLoginPath,Mt as classifyRouteError,T as clearSession,He as configureFormatters,p as configureLogger,Be as contentDispositionFileName,et as createApiBaseQuery,nt as createAppApi,Ce as createContractCaller,wt as createRootReducer,_ as decodeJWT,qt as defineRouteTable,Ve as downloadFile,ct as emptyFacetValue,St as errorToastMiddleware,Fe as extractApiError,We as formatCurrency,Ke as formatDate,qe as formatDateTime,Je as formatMinor,Ye as formatNumber,Xe as formatPercent,Ze as formatRelative,Qe as formatTime,G as getClientBuild,a as getConfig,o as getConfigValue,m as getDeviceContext,Ue as getFormatterConfig,v as getJWTExpiry,E as getKeepSignedIn,ee as getMinAppVersion,R as getNetworkStatus,nn as getNewerDeployedBuild,ft as getNextPageParam,pt as getPreviousPageParam,Rt as getReturnTo,D as getSessionUser,O as getToken,mt as hasNextPage,Ft as hasPermission,ht as hasPreviousPage,Dt as hasRecentlyReloaded,k as hasSession,A as hasSessionEndedInTab,Ot as importWithReload,xe as initUserAuth,K as initWebority,he as injectStore,ge as injectUserAuth,an as installReloadOnNavigate,Ie as isApiError,$t as isBuildBelowMinimum,kt as isChunkLoadError,lt as isFacetActive,y as isJWTExpired,oe as isNeverSentError,Le as isNoResponse,se as isRetryableFailure,ce as isRetryableStatus,Ct as isSilentRejection,Yt as isStorageAvailable,on as isUpdateAvailable,re as isWorkspaceChangedError,_t as itemTag,At as lazyWithReload,ut as listQueryParamNames,vt as listTag,jt as markReloaded,d as newTraceparent,en as parseBuildNumber,dt as parseListQuery,ze as parseResponse,yt as providesList,bt as providesPagedList,fe as publicClient,Ut as publicOnly,Se as readBlobErrorBody,Z as readDesignSampleTicket,_e as refreshAccessToken,j as removeSessionUser,M as removeToken,Wt as requireAuth,Gt as requirePermission,s as resetConfig,ve as resetRefreshState,Tt as resetState,le as retryAfterMs,c as setConfig,h as setDeviceContext,N as setKeepSignedIn,P as setLegacyTokenKeys,z as setNetworkStatusImplementation,g as setRemoteLogger,Xt as setStorageImplementation,it as setupApiListeners,rn as startDeployedBuildCheck,$e as staticUrl,F as storeSessionUser,I as storeToken,Zt as syncSessionStorage,Qt as syncStorage,Re as toFieldPath,zt as toSafeReturnTo,rt as useDataState,xt as useListQuery,B as useNetworkStatus,Nt as useRouteErrorReport,sn as useVersionCheck,ye as userClient,de as withCrossTabRefreshLock,Kt as withGuards};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{gstinState as e}from"./gstin.js";import{findGstState as t,gstStateByName as n}from"./gstStates.g.js";var r=n=>{let r=e(n);if(r===null)return null;if(r.status!==`Retired`||r.replacedByCode===void 0)return r;let i=t(r.replacedByCode);if(i===null)throw RangeError(`The GST state table names ${r.replacedByCode} as the successor of ${r.code} but has no such row.`);return i},i=e=>{if(typeof e!=`string`||e.trim()===``)return null;let r=e.lastIndexOf(` (`);return r>0&&e.endsWith(`)`)?t(e.slice(r+2,-1))??n(e.slice(0,r)):n(e)},a=e=>`${e.name} (${e.code})`;export{r as currentStateForGstin,i as gstStateFromPlaceOfSupply,a as placeOfSupplyLabel};
|
package/dist/india/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{aadhaarLastFour as e,isAadhaar as t,maskAadhaar as n,normalizeAadhaar as r}from"./aadhaar.js";import{currentFinancialYear as i,financialYearLabel as a,financialYearOf as o,parseFinancialYear as s,recentFinancialYears as c}from"./financialYear.js";import{gstinHolderPan as l,gstinProblem as u,gstinState as d,gstinStateCode as f,isGstin as p,normalizeGstin as m,sanitizeGstinInput as h}from"./gstin.js";import{
|
|
1
|
+
import{aadhaarLastFour as e,isAadhaar as t,maskAadhaar as n,normalizeAadhaar as r}from"./aadhaar.js";import{currentFinancialYear as i,financialYearLabel as a,financialYearOf as o,parseFinancialYear as s,recentFinancialYears as c}from"./financialYear.js";import{gstinHolderPan as l,gstinProblem as u,gstinState as d,gstinStateCode as f,isGstin as p,normalizeGstin as m,sanitizeGstinInput as h}from"./gstin.js";import{currentStateForGstin as g,gstStateFromPlaceOfSupply as _,placeOfSupplyLabel as v}from"./gstStates.js";import{isIfsc as y,normalizeIfsc as b}from"./ifsc.js";import{formatIndianMobile as x,isIndianMobile as S,normalizeIndianMobile as C}from"./indianMobile.js";import{istDateOf as w,istDayBoundsUtc as T,istToday as E}from"./indiaTime.js";import{PAISE_PER_RUPEE as D,formatPaise as O,formatRupees as k,paiseFromRupees as A}from"./paise.js";import{isPan as j,maskPan as M,normalizePan as N}from"./pan.js";import{isPincode as P,normalizePincode as F}from"./pincode.js";export{D as PAISE_PER_RUPEE,e as aadhaarLastFour,i as currentFinancialYear,g as currentStateForGstin,a as financialYearLabel,o as financialYearOf,x as formatIndianMobile,O as formatPaise,k as formatRupees,_ as gstStateFromPlaceOfSupply,l as gstinHolderPan,u as gstinProblem,d as gstinState,f as gstinStateCode,t as isAadhaar,p as isGstin,y as isIfsc,S as isIndianMobile,j as isPan,P as isPincode,w as istDateOf,T as istDayBoundsUtc,E as istToday,n as maskAadhaar,M as maskPan,r as normalizeAadhaar,m as normalizeGstin,b as normalizeIfsc,C as normalizeIndianMobile,N as normalizePan,F as normalizePincode,A as paiseFromRupees,s as parseFinancialYear,v as placeOfSupplyLabel,c as recentFinancialYears,h as sanitizeGstinInput};
|
package/dist/logger/logger.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"../api/requestDefaults.js";import{getConfigValue as e}from"../config/index.js";import{redact as t,redactError as n,redactString as
|
|
2
|
-
`)[1]?.trim();return t?`${e.message}::${t}`:e.message},
|
|
1
|
+
import"../api/requestDefaults.js";import{getConfigValue as e}from"../config/index.js";import{redact as t,redactError as n,redactRecord as r,redactString as i}from"./redact.js";var a=[`debug`,`info`,`warn`,`error`],o=t=>{let n=e(`logLevel`,`info`);return a.indexOf(t)>=a.indexOf(n)},s=()=>e(`loggingEnabled`,!0),c=null,l=e=>{c=e},u=e=>{if(e)try{e()}catch{}},d=null,f=e=>e==null?null:typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:String(e),p=e=>{if(d=e,e)for(let[t,n]of Object.entries(e))u(()=>c?.setAttribute?.(t,f(n)))},m=()=>d,h={dedupeWindowMs:5e3,dedupeMaxPerWindow:1,screenHistoryLimit:20},g=null,_=[],v=e=>{h={...h,...e},_.length>h.screenHistoryLimit&&(_=_.slice(_.length-h.screenHistoryLimit))},y=/* @__PURE__ */ new Map,b=200,x=e=>{let t=e.stack?.split(`
|
|
2
|
+
`)[1]?.trim();return t?`${e.message}::${t}`:e.message},S=()=>{for(;y.size>b;){let e=y.keys().next().value;if(e===void 0)return;y.delete(e)}},C=e=>{if(h.dedupeWindowMs<=0)return{forward:!0};let t=Date.now(),n=y.get(e);if(!n||t-n.windowStart>=h.dedupeWindowMs){let r=n?.suppressedCount??0;return y.set(e,{windowStart:t,count:1,suppressedCount:0}),S(),r>0?{forward:!0,suppressedCount:r}:{forward:!0}}return n.count+=1,n.count>h.dedupeMaxPerWindow?(n.suppressedCount+=1,{forward:!1}):{forward:!0}},w=(e,t)=>{let n={...d};return g!==null&&(n.screen=g),t&&(n.suppressedCount=t),{...n,...e}},T=(e,t)=>{let{forward:n,suppressedCount:r}=C(x(e));n&&u(()=>c?.recordError?.(e,w(t,r)))},E=e=>{let n=t(e);return Array.isArray(n)?n:[n]},D=(e,...t)=>{s()&&o(`debug`)&&console.debug(`[DEBUG]: ${i(e)}`,...E(t))},O=(e,...t)=>{let n=i(e),r=E(t);s()&&o(`info`)&&(console.info(`[INFO]: ${n}`,...r),u(()=>c?.log?.(`info`,n,r)))},k=(e,...t)=>{let n=i(e),r=E(t);s()&&o(`warn`)&&(console.warn(`[WARNING]: ${n}`,...r),u(()=>c?.log?.(`warn`,n,r)))},A=(e,...t)=>{let r=i(e),a=E(t);s()&&o(`error`)&&console.error(`[ERROR]: ${r}`,...a),u(()=>c?.log?.(`error`,r,a));let l=t[0];l!==void 0&&T(n(l),{source:`Logger.error`,message:r})},j=(e,t)=>{let n=i(e),a=t===void 0?void 0:r(t);s()&&o(`info`)&&console.info(`[BREADCRUMB]: ${n}`,a??``),u(()=>c?.breadcrumb?.(n,a))},M=(e,t)=>{let i=n(e),a=t===void 0?void 0:r(t);s()&&o(`error`)&&console.error(`[RECORDED]: ${i.message}`,a??``),T(i,a)},N=e=>typeof e==`object`&&!!e,P=e=>N(e)?e:null,F=(e,t)=>{let n=P(e);if(!n)return null;let r=n.get,i=typeof r==`function`?r.call(e,t):n[t]??n[t.toLowerCase()];return typeof i==`string`&&i!==``?i:null},I=e=>F(e,`traceparent`)?.split(`-`)[1]??null,L={debug:D,info:O,warn:k,error:A,breadcrumb:j,recordError:M,requestFailed:(e,t={})=>{let{label:n,expectedStatuses:a=[],...l}=t,d=P(e),f=P(d?.config),p=P(d?.response),m=P(p?.data),h=typeof p?.status==`number`?p.status:null,g=typeof f?.method==`string`?f.method.toUpperCase():null,_=typeof f?.url==`string`?f.url.split(`?`)[0]??null:null,v=n??([g,_].filter(Boolean).join(` `)||`Request`);if(d?.name===`CanceledError`||d?.code===`ERR_CANCELED`||d?.__CANCEL__===!0){O(`${v} canceled`);return}if(h!==null&&a.includes(h)){O(`${v} refused (${h})`);return}let y=typeof d?.message==`string`?d.message:e instanceof Error?e.message:null,b=i(h===null?`${v} failed`:`${v} failed (${h})`);s()&&o(`error`)&&console.error(`[ERROR]: ${b}`,i(y??``)),u(()=>c?.log?.(`error`,b,[]));let x=r({source:`Logger.requestFailed`,label:v,status:h,method:g,path:_,code:typeof m?.code==`string`?m.code:null,traceId:(typeof m?.traceId==`string`?m.traceId:null)??I(f?.headers),detail:y,...l});T(Error(b),x)},setUser:(e,t)=>{u(()=>c?.setUser?.(e,t))},setAttribute:(e,t)=>{u(()=>c?.setAttribute?.(e,t))},trackScreen:(e,t)=>{e!==g&&(g=e,_.push(e),_.length>h.screenHistoryLimit&&(_=_.slice(_.length-h.screenHistoryLimit)),j(`Screen: ${e}`,t))},getCurrentScreen:()=>g,getScreenHistory:()=>[..._]};export{L as Logger,v as configureLogger,m as getDeviceContext,p as setDeviceContext,l as setRemoteLogger};
|
package/dist/logger/redact.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`[REDACTED]`,t=/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi,n=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g,r=[`token`,`accesstoken`,`refreshtoken`,`password`,`authorization`,`cookie`,`setcookie`,`xapikey`,`apikey`,`secret`,`clientsecret`,`otp`,`pin`,`aadhaar`,`aadhaarnumber`,`pan`,`pannumber`,`accountnumber`,`cvv`,`cardnumber`],i=new Set(r),a=/* @__PURE__ */ new Set([`config`,`request`,`data`]),o=e=>e.toLowerCase().replace(/[-_]/g,``),s=RegExp(`(?<![a-z])(["']?(?:${r.map(e=>[...e].join(`[-_]?`)).join(`|`)})["']?\\s*[:=]\\s*)(?:"(?:[^"\\\\]|\\\\.)*"|'[^']*'|[^\\s,;&}]+)`,`gi`),c=r=>r.replace(t,`Bearer ${e}`).replace(n,e).replace(s,(t,n)=>`${n}"${e}"`),l=e=>typeof e==`object
|
|
1
|
+
var e=`[REDACTED]`,t=/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi,n=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g,r=[`token`,`accesstoken`,`refreshtoken`,`password`,`authorization`,`cookie`,`setcookie`,`xapikey`,`apikey`,`secret`,`clientsecret`,`otp`,`pin`,`aadhaar`,`aadhaarnumber`,`pan`,`pannumber`,`accountnumber`,`cvv`,`cardnumber`],i=new Set(r),a=/* @__PURE__ */ new Set([`config`,`request`,`data`]),o=e=>e.toLowerCase().replace(/[-_]/g,``),s=RegExp(`(?<![a-z])(["']?(?:${r.map(e=>[...e].join(`[-_]?`)).join(`|`)})["']?\\s*[:=]\\s*)(?:"(?:[^"\\\\]|\\\\.)*"|'[^']*'|[^\\s,;&}]+)`,`gi`),c=r=>r.replace(t,`Bearer ${e}`).replace(n,e).replace(s,(t,n)=>`${n}"${e}"`),l=e=>typeof e==`object`&&!!e,u=e=>l(e)?e:null,d=e=>e instanceof Error||e.isAxiosError===!0,f=e=>{let t=u(e.config),n=u(e.response);return{name:typeof e.name==`string`?e.name:`Error`,message:c(typeof e.message==`string`?e.message:``),stack:typeof e.stack==`string`?c(e.stack):null,code:typeof e.code==`string`?e.code:null,status:typeof n?.status==`number`?n.status:null,method:typeof t?.method==`string`?t.method.toUpperCase():null,url:typeof t?.url==`string`?t.url.split(/[?#]/)[0]??null:null}},p=(t,n,r)=>{if(typeof t==`string`)return c(t);if(!l(t))return t;if(d(t))return f(t);if(t instanceof Date)return t;if(r.has(t))return`[Circular]`;if(n>=6)return`[Truncated]`;r.add(t);try{if(Array.isArray(t))return t.map(e=>p(e,n+1,r));let s={};for(let[c,l]of Object.entries(t)){let t=o(c);s[c]=a.has(t)?`[OMITTED]`:i.has(t)?e:p(l,n+1,r)}return s}finally{r.delete(t)}},m=e=>p(e,0,/* @__PURE__ */ new Set),h=e=>{let t=p(e,0,/* @__PURE__ */ new Set);if(!l(t))throw Error(`[redact] a record came back as ${typeof t}`);return t},g=e=>{if(l(e)&&d(e)){let t=f(e),n=Error(t.message);return n.name=t.name,t.stack!==null&&(n.stack=t.stack),n}let t=m(e);if(typeof t==`string`)return Error(t);try{return Error(JSON.stringify(t))}catch{return Error(String(t))}};export{m as redact,g as redactError,h as redactRecord,c as redactString};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger as e}from"../logger/logger.js";import{useEffect as t,useState as n}from"react";var r={isConnected:!0,isInternetReachable:null,type:`unknown`},i=()=>{let e=typeof navigator>`u`||navigator.onLine!==!1;return{isConnected:e,isInternetReachable:null,type:e?`unknown`:`none`}},a={fetch:async()=>i(),addEventListener:e=>{if(typeof window>`u`)return()=>void 0;let t=()=>e(i());return window.addEventListener(`online`,t),window.addEventListener(`offline`,t),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,t)}}},o=null,s=e=>{o=e},c=()=>o??a,l=e=>e?{isConnected:e.isConnected!==!1,isInternetReachable:e.isInternetReachable,type:e.type
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";import{useEffect as t,useState as n}from"react";var r={isConnected:!0,isInternetReachable:null,type:`unknown`},i=()=>{let e=typeof navigator>`u`||navigator.onLine!==!1;return{isConnected:e,isInternetReachable:null,type:e?`unknown`:`none`}},a={fetch:async()=>i(),addEventListener:e=>{if(typeof window>`u`)return()=>void 0;let t=()=>e(i());return window.addEventListener(`online`,t),window.addEventListener(`offline`,t),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,t)}}},o=null,s=e=>{o=e},c=()=>o??a,l=[`unknown`,`none`,`wifi`,`cellular`,`bluetooth`,`ethernet`,`wimax`,`vpn`,`other`],u=e=>l.includes(e),d=e=>e?{isConnected:e.isConnected!==!1,isInternetReachable:e.isInternetReachable,type:e.type!==void 0&&u(e.type)?e.type:`unknown`}:r,f=async()=>{try{return d(await c().fetch())}catch(t){return e.error(`[network] getNetworkStatus failed`,t),r}},p=e=>c().addEventListener(t=>e(d(t))),m=()=>f(),h=()=>{let[e,a]=n(()=>o?r:d(i()));return t(()=>{let e=!0;f().then(t=>{e&&a(t)});let t=p(t=>{e&&a(t)});return()=>{e=!1,t()}},[]),e};export{p as addNetworkStatusListener,m as getLastKnownNetworkStatus,f as getNetworkStatus,s as setNetworkStatusImplementation,h as useNetworkStatus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractApiError as e}from"../errors/extractApiError.js";import{Logger as t}from"../logger/logger.js";import n from"axios";var r=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e)),i=e=>t=>{let n=[];for(let[i,a]of Object.entries(t)){if(a==null)continue;let t=encodeURIComponent(i);if(!Array.isArray(a))n.push(`${t}=${r(a)}`);else if(e===`comma`)n.push(`${t}=${a.map(r).join(`,`)}`);else{let i=e===`brackets`?`${t}[]`:t;for(let e of a)n.push(`${i}=${r(e)}`)}}return n.join(`&`)},a=({client:r,publicClient:a})=>async(o,{signal:s},c)=>{let l=typeof o==`string`?{url:o}:o,u=l.silent??c?.silent??!1,d=l.expectedStatuses??c?.expectedStatuses,f=l.paramsFormat??c?.paramsFormat
|
|
1
|
+
import{extractApiError as e}from"../errors/extractApiError.js";import{Logger as t}from"../logger/logger.js";import n from"axios";var r=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e)),i=e=>t=>{let n=[];for(let[i,a]of Object.entries(t)){if(a==null)continue;let t=encodeURIComponent(i);if(!Array.isArray(a))n.push(`${t}=${r(a)}`);else if(e===`comma`)n.push(`${t}=${a.map(r).join(`,`)}`);else{let i=e===`brackets`?`${t}[]`:t;for(let e of a)n.push(`${i}=${r(e)}`)}}return n.join(`&`)},a=({client:r,publicClient:a})=>async(o,{signal:s},c)=>{let l=typeof o==`string`?{url:o}:o,u=l.silent??c?.silent??!1,d=l.expectedStatuses??c?.expectedStatuses,f=l.paramsFormat??c?.paramsFormat,p=l.public?a:r;if(!p)throw Error(`createApiBaseQuery: "${l.url}" is marked public but no publicClient was passed.`);let m={url:l.url,method:l.method??`GET`,data:l.data,params:l.params,paramsSerializer:f?i(f):void 0,headers:l.headers,responseType:l.responseType,timeout:l.timeout,signal:s,skipErrorLog:!0};try{let e=await p.request(m);return{data:e.data,meta:{silent:u,status:e.status}}}catch(r){let i=e(r),a=n.isCancel(r);return a||t.requestFailed(r,{expectedStatuses:d}),{error:i,meta:{silent:u||a,status:i.status,...d&&{expectedStatuses:d}}}}};export{a as createApiBaseQuery};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createApi as e}from"@reduxjs/toolkit/query/react";var t={keepUnusedDataFor:60,refetchOnReconnect:!0,refetchOnFocus:!0},n=
|
|
1
|
+
import{createApi as e}from"@reduxjs/toolkit/query/react";var t={keepUnusedDataFor:60,refetchOnReconnect:!0,refetchOnFocus:!0},n=n=>e({...t,...n});export{t as APP_API_DEFAULTS,n as createAppApi};
|
|
@@ -0,0 +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,refetch:c}=n,l=i?.isEmpty??r;return t(()=>{let t=()=>{c()};return a===void 0?o===void 0?{status:`loading`}:{status:`error`,error:e(o),retry:t}:l(a)?{status:`empty`,refreshing:s,refresh:t}:{status:`data`,data:a,refreshing:s,refresh:t}},[a,o,s,c,l])}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;export{n as useDataState};
|
package/dist/query/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createApiBaseQuery as e}from"./apiBaseQuery.js";import{APP_API_DEFAULTS as t,createAppApi as n}from"./createAppApi.js";import{
|
|
1
|
+
import{createApiBaseQuery as e}from"./apiBaseQuery.js";import{APP_API_DEFAULTS as t,createAppApi as n}from"./createAppApi.js";import{useDataState as r}from"./dataState.js";import{setupApiListeners as i}from"./listeners.js";import{LIST_QUERY_RESERVED as a,SEARCH_PARAM as o,buildListQuery as s,emptyFacetValue as c,isFacetActive as l,listQueryParamNames as u,parseListQuery as d}from"./listQuery.js";import{getNextPageParam as f,getPreviousPageParam as p,hasNextPage as m,hasPreviousPage as h}from"./paging.js";import{LIST_TAG_ID as g,itemTag as _,listTag as v,providesList as y,providesPagedList as b}from"./tags.js";import{useListQuery as x}from"./useListQuery.js";export{t as APP_API_DEFAULTS,a as LIST_QUERY_RESERVED,g as LIST_TAG_ID,o as SEARCH_PARAM,s as buildListQuery,e as createApiBaseQuery,n as createAppApi,c as emptyFacetValue,f as getNextPageParam,p as getPreviousPageParam,m as hasNextPage,h as hasPreviousPage,l as isFacetActive,_ as itemTag,u as listQueryParamNames,v as listTag,d as parseListQuery,y as providesList,b as providesPagedList,i as setupApiListeners,r as useDataState,x as useListQuery};
|
package/dist/query/listQuery.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=Object.freeze([`page`,`pageSize`,`sortBy`,`sortOrder`,`search`]),t=`search`,n=[`asc`,`desc`],r=e=>n.
|
|
1
|
+
var e=Object.freeze([`page`,`pageSize`,`sortBy`,`sortOrder`,`search`]),t=`search`,n=[`asc`,`desc`],r=e=>n.some(t=>t===e),i=e=>e==null||e===``,a=e=>String(e).padStart(2,`0`),o=e=>e instanceof Date?`${e.getFullYear()}-${a(e.getMonth()+1)}-${a(e.getDate())}`:String(e);function s(t){if(e.includes(t))throw Error(`"${t}" is reserved by the list query (${e.join(`, `)}) and cannot name a filter.`)}var c=e=>typeof e==`object`&&!!e&&!(e instanceof Date);function l(e={}){let{page:n,pageSize:a,sortBy:l,sortOrder:u,search:d,filters:f}=e;if(!i(u)&&!r(u))throw Error(`sortOrder must be "asc" or "desc", got "${u}".`);let p=new URLSearchParams;i(n)||p.set(`page`,String(n)),i(a)||p.set(`pageSize`,String(a)),i(l)||(p.set(`sortBy`,l),p.set(`sortOrder`,u||`asc`));let m=i(d)?``:String(d).trim();m&&p.set(t,m);for(let[e,t]of Object.entries(f??{}))if(s(e),Array.isArray(t))for(let n of t)i(n)||p.append(e,o(n));else c(t)?(i(t.from)||p.set(`${e}From`,o(t.from)),i(t.to)||p.set(`${e}To`,o(t.to))):i(t)||p.set(e,o(t));return p}function u(e){return e.type===`multiEnum`?[]:e.type===`dateRange`?{from:``,to:``}:``}function d(e,t){return t==null?!1:e.type===`multiEnum`?Array.isArray(t)&&t.length>0:e.type===`dateRange`?c(t)?!!(t.from||t.to):!1:t!==``}function f(t=[]){let n=new Set(e);for(let{key:e,type:r}of t)r===`dateRange`?(n.add(`${e}From`),n.add(`${e}To`)):n.add(e);return n}var p=e=>{let t=Number(e);return Number.isInteger(t)&&t>=1?t:void 0};function m(e,t={}){let{facets:n=[],defaults:i={}}=t,a=typeof e==`string`?new URLSearchParams(e):e;for(let e of n)s(e.key);let o=f(n),c=[...a.keys()].some(e=>o.has(e)),l=a.get(`sortOrder`),d={};for(let e of n){let{key:t,type:n}=e,r;r=c?n===`multiEnum`?a.getAll(t).filter(Boolean):n===`dateRange`?{from:a.get(`${t}From`)??``,to:a.get(`${t}To`)??``}:a.get(t)??``:i.filters?.[t]??u(e),d[t]=r}return{page:p(a.get(`page`))??i.page??1,pageSize:p(a.get(`pageSize`))??i.pageSize,sortBy:a.get(`sortBy`)||i.sortBy,sortOrder:r(l)?l:i.sortOrder??`asc`,search:(a.get(`search`)??``).trim(),filters:d}}export{e as LIST_QUERY_RESERVED,t as SEARCH_PARAM,l as buildListQuery,u as emptyFacetValue,d as isFacetActive,f as listQueryParamNames,m as parseListQuery};
|
package/dist/query/tags.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`LIST`,t=e=>e.publicId,n=t=>({type:t,id:e}),r=(e,t)=>({type:e,id:t});function i(e,i,a){let o=a??t;return[n(e),...(i??[]).map(t=>r(e,o(t)))]}function a(e,n){let r=n??t;return t=>i(e,t?.items,r)}export{e as LIST_TAG_ID,r as itemTag,n as listTag,i as providesList,a as providesPagedList};
|
|
1
|
+
var e=`LIST`,t=e=>{if(typeof e==`object`&&e&&`publicId`in e&&typeof e.publicId==`string`)return e.publicId;throw Error(`A list item has no string publicId: pass selectId to name its tag id.`)},n=t=>({type:t,id:e}),r=(e,t)=>({type:e,id:t});function i(e,i,a){let o=a??t;return[n(e),...(i??[]).map(t=>r(e,o(t)))]}function a(e,n){let r=n??t;return t=>i(e,t?.items,r)}export{e as LIST_TAG_ID,r as itemTag,n as listTag,i as providesList,a as providesPagedList};
|