@data-client/vue 0.15.4 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +77 -0
- package/README.md +2 -2
- package/dist/index.js +27 -3
- package/dist/index.umd.min.js +1 -1
- package/lib/consumers/useFetch.d.ts +10 -2
- package/lib/consumers/useFetch.d.ts.map +1 -1
- package/lib/consumers/useFetch.js +27 -4
- package/package.json +4 -4
- package/src/__tests__/integration-garbage-collection.web.ts +8 -0
- package/src/__tests__/useCache.web.ts +8 -0
- package/src/__tests__/useDLE.web.ts +3 -0
- package/src/__tests__/useFetch.web.ts +90 -0
- package/src/__tests__/useLive.web.ts +8 -0
- package/src/__tests__/useQuery.web.ts +8 -0
- package/src/__tests__/useSubscription.web.ts +5 -0
- package/src/__tests__/useSuspense.web.ts +8 -0
- package/src/consumers/useFetch.ts +40 -8
- package/src/providers/__tests__/DataClientPlugin.test.ts +12 -7
- package/src/providers/__tests__/MockPlugin.test.ts +3 -0
- package/src/providers/__tests__/createDataClient.test.ts +15 -0
- package/src/test/__tests__/mountDataClient.test.ts +8 -0
- package/src/test/__tests__/renderDataCompose.test.ts +8 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,82 @@
|
|
|
1
1
|
# @data-client/vue
|
|
2
2
|
|
|
3
|
+
## 0.16.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [`fd64b41`](https://github.com/reactive/data-client/commit/fd64b41a9de266af51708622ea8991060fd788a5) - Include `@data-client/normalizr@0.16.6` performance improvements:
|
|
8
|
+
- [#3875](https://github.com/reactive/data-client/pull/3875) [`467a5f6`](https://github.com/reactive/data-client/commit/467a5f6f9d4cdaf0927fa7e22520c5d2c1462ff5) - Fix deepClone to only copy own properties
|
|
9
|
+
|
|
10
|
+
`deepClone` in the immutable store path now uses `Object.keys()` instead of `for...in`, preventing inherited properties from being copied into cloned state.
|
|
11
|
+
|
|
12
|
+
- [#3877](https://github.com/reactive/data-client/pull/3877) [`e9e96f1`](https://github.com/reactive/data-client/commit/e9e96f1751895c17e046461a1c38bb4bb093c141) - Replace megamorphic computed dispatch in getDependency with switch
|
|
13
|
+
|
|
14
|
+
`getDependency` used `delegate[array[index]](...spread)` which creates a temporary array, a computed property lookup, and a spread call on every invocation — a megamorphic pattern that prevents V8 from inlining or type-specializing the call site. Replaced with a `switch` on `path.length` for monomorphic dispatch.
|
|
15
|
+
|
|
16
|
+
- [#3876](https://github.com/reactive/data-client/pull/3876) [`7d28629`](https://github.com/reactive/data-client/commit/7d28629d07f6cade43e36f3cf1956f175f98d84f) - Improve denormalization performance by pre-allocating the dependency tracking slot
|
|
17
|
+
|
|
18
|
+
Replace `Array.prototype.unshift()` in `GlobalCache.getResults()` with a pre-allocated slot at index 0, avoiding O(n) element shifting on every cache-miss denormalization.
|
|
19
|
+
|
|
20
|
+
- [#3884](https://github.com/reactive/data-client/pull/3884) [`7df6a49`](https://github.com/reactive/data-client/commit/7df6a49ee9fcdac10f9f24ec48c4df0931efa0b0) - Move entity table POJO clone from getNewEntities to setEntity
|
|
21
|
+
|
|
22
|
+
Lazy-clone entity and meta tables on first write per entity type instead of eagerly in getNewEntities. This keeps getNewEntities as a pure Map operation, eliminating its V8 Maglev bailout ("Insufficient type feedback for generic named access" on `this.entities`).
|
|
23
|
+
|
|
24
|
+
- [#3878](https://github.com/reactive/data-client/pull/3878) [`98a7831`](https://github.com/reactive/data-client/commit/98a78318770feaa8433708693bec90b81cbcb1b2) - Avoid hidden class mutation in normalize() return object
|
|
25
|
+
|
|
26
|
+
The normalize result object was constructed with `result: '' as any` then mutated via `ret.result = visit(...)`, causing a V8 hidden class transition when the property type changed from string to the actual result type. Restructured to compute the result first and construct the final object in a single step.
|
|
27
|
+
|
|
28
|
+
- Updated dependencies [[`fd64b41`](https://github.com/reactive/data-client/commit/fd64b41a9de266af51708622ea8991060fd788a5)]:
|
|
29
|
+
- @data-client/core@0.16.7
|
|
30
|
+
|
|
31
|
+
## 0.16.0
|
|
32
|
+
|
|
33
|
+
### Minor Changes
|
|
34
|
+
|
|
35
|
+
- [#3752](https://github.com/reactive/data-client/pull/3752) [`3c3bfe8`](https://github.com/reactive/data-client/commit/3c3bfe81ff0c3a786d6804a61f9e7a4362947dcb) - BREAKING CHANGE: [useFetch()](/docs/api/useFetch) always returns a stable promise with a `.resolved` property, even when data is already cached.
|
|
36
|
+
|
|
37
|
+
#### before
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
const promise = useFetch(MyResource.get, { id });
|
|
41
|
+
if (promise) {
|
|
42
|
+
// fetch was triggered
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
#### after
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
const promise = useFetch(MyResource.get, { id });
|
|
50
|
+
if (!promise.resolved) {
|
|
51
|
+
// fetch is in-flight
|
|
52
|
+
}
|
|
53
|
+
use(promise); // works with React.use()
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Patch Changes
|
|
57
|
+
|
|
58
|
+
- [#3753](https://github.com/reactive/data-client/pull/3753) [`e54c9b6`](https://github.com/reactive/data-client/commit/e54c9b6e6a48939263f41496a90387ee614d35f5) - Add `globalThis.__DC_CONTROLLERS__` Map in dev mode for programmatic store access from browser DevTools MCP, React Native debuggers, and other development tooling.
|
|
59
|
+
|
|
60
|
+
Each [DataProvider](/docs/api/DataProvider) registers its [Controller](/docs/api/Controller) keyed by the devtools connection name, supporting multiple providers on the same page.
|
|
61
|
+
|
|
62
|
+
- [#3823](https://github.com/reactive/data-client/pull/3823) [`869f28f`](https://github.com/reactive/data-client/commit/869f28fc651ca5e8b0f935089fc0b8d8ce8585cb) - Fix stack overflow during denormalization of large bidirectional entity graphs.
|
|
63
|
+
|
|
64
|
+
Add entity depth limit (64) to prevent `RangeError: Maximum call stack size exceeded`
|
|
65
|
+
when denormalizing cross-type chains with thousands of unique entities
|
|
66
|
+
(e.g., Department → Building → Department → ...). Entities beyond the depth limit
|
|
67
|
+
are returned with unresolved ids instead of fully denormalized nested objects.
|
|
68
|
+
|
|
69
|
+
The limit can be configured per-Entity with [`static maxEntityDepth`](/rest/api/Entity#maxEntityDepth):
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
class Department extends Entity {
|
|
73
|
+
static maxEntityDepth = 16;
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- Updated dependencies [[`e54c9b6`](https://github.com/reactive/data-client/commit/e54c9b6e6a48939263f41496a90387ee614d35f5), [`869f28f`](https://github.com/reactive/data-client/commit/869f28fc651ca5e8b0f935089fc0b8d8ce8585cb), [`0e0ff1a`](https://github.com/reactive/data-client/commit/0e0ff1ab49b1a58477b07dba3dfc73df6d4af3f5)]:
|
|
78
|
+
- @data-client/core@0.16.0
|
|
79
|
+
|
|
3
80
|
## 0.15.4
|
|
4
81
|
|
|
5
82
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -21,10 +21,10 @@ Schema driven. Zero updater functions.
|
|
|
21
21
|
[](https://bundlephobia.com/result?p=@data-client/vue)
|
|
22
22
|
[](https://www.npmjs.com/package/@data-client/vue)
|
|
23
23
|
[](http://makeapullrequest.com)
|
|
24
|
-
[](https://skills.sh/reactive/data-client)
|
|
25
25
|
[](https://discord.gg/35nb8Mz)
|
|
26
26
|
|
|
27
|
-
**[📖Read The Docs](https://dataclient.io/docs)** | [🏁Getting Started](https://dataclient.io/docs/getting-started/installation) | [🤖
|
|
27
|
+
**[📖Read The Docs](https://dataclient.io/docs)** | [🏁Getting Started](https://dataclient.io/docs/getting-started/installation) | [🤖Agent Skills](https://skills.sh/reactive/data-client) | [🎮Todo Demo](https://stackblitz.com/github/reactive/data-client/tree/master/examples/vue-todo-app?file=src%2Fcomponents%2FTodoListContent.vue)
|
|
28
28
|
|
|
29
29
|
</div>
|
|
30
30
|
|
package/dist/index.js
CHANGED
|
@@ -246,6 +246,19 @@ function useDebounce(value, delay, updatable = true) {
|
|
|
246
246
|
return [debouncedValue, isPending];
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
+
const RESOLVED = Object.assign(Promise.resolve(), {
|
|
250
|
+
resolved: true
|
|
251
|
+
});
|
|
252
|
+
function trackPromise(promise) {
|
|
253
|
+
const p = promise;
|
|
254
|
+
p.resolved = false;
|
|
255
|
+
const r = () => {
|
|
256
|
+
p.resolved = true;
|
|
257
|
+
};
|
|
258
|
+
p.then(r, r);
|
|
259
|
+
return p;
|
|
260
|
+
}
|
|
261
|
+
|
|
249
262
|
/**
|
|
250
263
|
* Fetch an Endpoint if it is not in cache or stale.
|
|
251
264
|
* @see https://dataclient.io/docs/api/useFetch
|
|
@@ -266,12 +279,23 @@ function useFetch(endpoint, ...args) {
|
|
|
266
279
|
return controller.getResponseMeta(endpoint, ...resolvedArgs.value, stateRef.value);
|
|
267
280
|
});
|
|
268
281
|
const lastPromise = vue.ref(undefined);
|
|
282
|
+
let lastKey = '';
|
|
269
283
|
const maybeFetch = () => {
|
|
270
|
-
|
|
284
|
+
const key = argsKey.value;
|
|
285
|
+
if (!key) {
|
|
286
|
+
lastPromise.value = undefined;
|
|
287
|
+
lastKey = '';
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
271
290
|
const meta = responseMeta.value;
|
|
272
291
|
const forceFetch = meta.expiryStatus === core.ExpiryStatus.Invalid;
|
|
273
|
-
if (Date.now()
|
|
274
|
-
|
|
292
|
+
if (Date.now() > meta.expiresAt || forceFetch) {
|
|
293
|
+
lastPromise.value = trackPromise(controller.fetch(endpoint, ...resolvedArgs.value));
|
|
294
|
+
lastKey = key;
|
|
295
|
+
} else if (!lastPromise.value || lastKey !== key) {
|
|
296
|
+
lastPromise.value = RESOLVED;
|
|
297
|
+
lastKey = key;
|
|
298
|
+
}
|
|
275
299
|
};
|
|
276
300
|
|
|
277
301
|
// Trigger on initial call
|
package/dist/index.umd.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VDC={},e.Vue)}(this,(function(e,t){"use strict";class n{constructor(){this.localCache=new Map}getEntity(e,t,n,s){const i=t.key;this.localCache.has(i)||this.localCache.set(i,new Map);const r=this.localCache.get(i);return r.get(e)||s(r),r.get(e)}getResults(e,t,n){return{data:n(),paths:[]}}}const s=Symbol("INVALID"),i={};function r(e){return null!==e&&void 0!==e.pk}const a=e=>e[0],o=e=>void 0!==e&&"symbol"!=typeof e,c=(e,t,n,s,i,r)=>{e=a(e);const o=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(t);return o.map((t=>r(e,t,n,s,i)))},l=(e,t,n,s)=>(e=a(e),t.map?t.map((t=>s(e,t))).filter(o):t);function u(){}function h(){return h=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)({}).hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},h.apply(null,arguments)}const d=(e,t,n,s,i,r)=>{const a=h({},t),o=Object.keys(e);for(let n=0;n<o.length;n++){const s=o[n],c=r(e[s],t[s],t,s,i);void 0===c?delete a[s]:a[s]=c}return a},p=(e,t,n,i)=>{if(function(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}(t))return function(e,t,n,i){let r=!1;const a=Object.keys(e).reduce(((t,n)=>{const s=`${n}`,a=i(e[s],t.get(s));return"symbol"==typeof a&&(r=!0),t.has(s)?t.set(s,a):t}),t);return r?s:a}(e,t,0,i);const r=h({},t);let a=!1;const o=Object.keys(e);for(let t=0;t<o.length;t++){const n=o[t],s=i(e[n],r[n]);void 0!==r[n]&&(r[n]=s),"symbol"==typeof s&&(a=!0)}return a?s:r};function f(e,t,n,s){const i={};for(const r of Object.keys(e))i[r]=n(e[r],t,s);return i}const y=(e,t,n,s)=>function(r,a){const o="object"!=typeof a,c=o?e({key:r.key,pk:a}):a;if("symbol"==typeof c)return r.denormalize(c,n,s);if(void 0===c&&o&&""!==a&&"undefined"!==a)return t.getEntity(a,r,i,(e=>{e.set(a,void 0)}));if("object"!=typeof c||null===c)return c;let l=o?a:r.pk(c,void 0,void 0,n);return void 0===l||""===l||"undefined"===l?function(e){const t=new Map;return e(t),t.get("")}((e=>g(r,c,"",e,n,s))):("string"!=typeof l&&(l=`${l}`),t.getEntity(l,r,c,(e=>g(r,c,l,e,n,s))))};function g(e,t,n,i,r,a){const o=e.createIfValid(t);void 0===o?i.set(n,s):(i.set(n,o),i.set(n,e.denormalize(o,r,a)))}const v=(e,t,n)=>{const s=y(e,t,n,i);function i(e,t){if(!e)return t;if(null==t)return t;if("function"==typeof e.denormalize)return r(e)?s(e,t):e.denormalize(t,n,i);if("function"==typeof e)return e(t);if("object"==typeof e){return(Array.isArray(e)?l:p)(e,t,n,i)}return t}return(e,n)=>{const s=Object(n)===n&&Object(e)===e;return t.getResults(n,s,(()=>i(e,n)))}};class m{constructor({entities:e,indexes:t}){this.entities=e,this.indexes=t}tracked(e){const t=this,n=[{path:[""],entity:e}];return[{INVALID:s,getIndex(...e){const s=t.getIndex(...e);return n.push({path:e,entity:s}),t.getIndexEnd(s,e[2])},getEntity(...e){const s=t.getEntity(...e);return n.push({path:e,entity:s}),s},getEntities(e){const s=t.getEntitiesObject(e);return n.push({path:[e],entity:s}),t.getEntities(e)}},n]}}class w extends m{constructor(e){super(e)}getEntitiesObject(e){return this.entities[e]}getEntities(e){const t=this.entities[e];if(void 0!==t)return{keys:()=>Object.keys(t),entries:()=>Object.entries(t)}}getEntity(e,t){var n;return null==(n=this.entities[e])?void 0:n[t]}getIndex(e,t){var n;return null==(n=this.indexes[e])?void 0:n[t]}getIndexEnd(e,t){return null==e?void 0:e[t]}}const E={QueryDelegate:w,getEntities:e=>({key:t,pk:n})=>{var s;return null==(s=e[t])?void 0:s[n]}};class x{constructor(){this.next=new WeakMap,this.nextPath=void 0}get(e,t){let n=this.next.get(e);if(!n)return b;for(;n.nextPath;){var s;const e=null!=(s=t(n.nextPath))?s:i;if(n=n.next.get(e),!n)return b}return[n.value,n.journey]}set(e,t){if(e.length<1)throw new I;let n=this;for(const{path:t,entity:s}of e){let e=n.next.get(s);e||(e=new k,n.next.set(null!=s?s:i,e)),n.nextPath=t,n=e}n.nextPath=void 0,n.value=t,n.journey=e.map((e=>e.path))}}const b=[void 0,void 0];class k{constructor(){this.next=new WeakMap,this.nextPath=void 0,this.value=void 0,this.journey=[]}}class I extends Error{constructor(...e){super(...e),this.message="Keys must include at least one member"}}class L extends w{constructor(e,t){super(e),this.newEntities=new Map,this.newIndexes=new Map,this.entitiesMeta=e.entitiesMeta,this.meta=t,this.checkLoop=function(){const e=new Map;return function(t,n,s){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r=new Set,i.set(n,r)),!!r.has(s)||(r.add(s),!1)}}()}getNewEntity(e,t){return this.getNewEntities(e).get(t)}getNewEntities(e){return this.newEntities.has(e)||(this.newEntities.set(e,new Map),this.entities[e]=h({},this.entities[e]),this.entitiesMeta[e]=h({},this.entitiesMeta[e])),this.newEntities.get(e)}getNewIndexes(e){return this.newIndexes.has(e)||(this.newIndexes.set(e,new Map),this.indexes[e]=h({},this.indexes[e])),this.newIndexes.get(e)}mergeEntity(e,t,n){const s=e.key;let i=n,r=this.meta,a=this.getNewEntity(s,t);if(a)i=e.merge(a,n);else if(a=this.getEntity(s,t),a){const o=this.getMeta(s,t);i=e.mergeWithStore(o,r,a,n),r=e.mergeMetaWithStore(o,r,a,n)}this.setEntity(e,t,i,r)}setEntity(e,t,n,i=this.meta){const r=e.key,a=this.getNewEntities(r),o=!a.has(t);a.set(t,n),e.indexes&&function(e,t,n,i,r,a){for(const o of t){n.has(o)||n.set(o,i[o]={});const t=n.get(o);a[e]&&delete t[a[e][o]],a&&a[e]&&a[e][o]!==r[o]&&(t[a[e][o]]=s),o in r&&(t[r[o]]=e)}}(t,e.indexes,this.getNewIndexes(r),this.indexes[r],n,this.entities[r]),this._setEntity(r,t,n),o&&this._setMeta(r,t,i)}invalidate({key:e},t){this.setEntity({key:e},t,s)}_setEntity(e,t,n){this.entities[e][t]=n}_setMeta(e,t,n){this.entitiesMeta[e][t]=n}getMeta(e,t){return this.entitiesMeta[e][t]}}const S=(e,t,n=[],{entities:s,indexes:i,entitiesMeta:r}=A,a={fetchedAt:0,date:Date.now(),expiresAt:1/0})=>{if(null==e)return{result:t,entities:s,indexes:i,entitiesMeta:r};const o=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(e);if(null===t||typeof t!==o&&(void 0===e.key||void 0!==e.pk||"string"!=typeof t))throw new Error(`Unexpected input given to normalize. Expected type to be "${o}", found "${null===t?"null":typeof t}".`);const l={result:"",entities:h({},s),indexes:h({},i),entitiesMeta:h({},r)},u=(e=>{const t=(n,s,i,r,a)=>s&&n?n.normalize&&"function"==typeof n.normalize?"object"!=typeof s?n.pk?`${s}`:s:n.normalize(s,i,r,a,t,e):"object"!=typeof s||"object"!=typeof n?s:(Array.isArray(n)?c:d)(n,s,i,r,a,t):s;return t})(new L(l,a));return l.result=u(e,t,t,void 0,n),l};const A={entities:{},indexes:{},entitiesMeta:{}};class M{constructor(e,t,n){this.dependencies=[],this.cycleCache=new Map,this.cycleIndex=-1,this.localCache=new Map,this._getEntity=e,this._getCache=t,this._resultCache=n}getEntity(e,t,n,s){const i=t.key,{localCacheKey:r,cycleCacheKey:a}=this.getCacheKey(i);if(r.get(e))a.has(e)?this.cycleIndex=a.get(e):this.dependencies.push({path:{key:i,pk:e},entity:n});else{const o=this._getCache(e,t),[c,l]=o.get(n,this._getEntity);if(l)return r.set(e,c.value),this.dependencies.push(...c.dependencies),c.value;{const t=this.dependencies.length;a.set(e,t),this.dependencies.push({path:{key:i,pk:e},entity:n}),s(r),a.delete(e);const c=this.dependencies.slice(-1===this.cycleIndex?t:this.cycleIndex),l={dependencies:c,value:r.get(e)};o.set(c,l),this.cycleIndex===t&&(this.cycleIndex=-1)}}return r.get(e)}getCacheKey(e){this.localCache.has(e)||this.localCache.set(e,new Map),this.cycleCache.has(e)||this.cycleCache.set(e,new Map);return{localCacheKey:this.localCache.get(e),cycleCacheKey:this.cycleCache.get(e)}}getResults(e,t,n){if(!t)return{data:n(),paths:this.paths()};let[s,i]=this._resultCache.get(e,this._getEntity);return void 0===i?(s=n(),i=this.paths(),this.dependencies.unshift({path:{key:"",pk:""},entity:e}),this._resultCache.set(this.dependencies,s)):i.shift(),{data:s,paths:i}}paths(){return this.dependencies.map((e=>e.path))}}function R(e){return void 0!==e&&(!(e&&"object"==typeof e&&!Array.isArray(e))||Object.values(e).every(R))}class O{constructor(e=E){var t;this.endpoints=new x,this.queryKeys=new Map,this.policy=e,this._getCache=(t=new Map,(e,n)=>{var s;const i=n.key,r=null!=(s=n.cacheWith)?s:n;t.has(i)||t.set(i,new Map);const a=t.get(i);a.has(e)||a.set(e,new WeakMap);const o=a.get(e);let c=o.get(r);return c||(c=new x,o.set(r,c)),c})}denormalize(e,t,n,s=[]){if(void 0===e)return{data:t,paths:[]};if(void 0===t)return{data:void 0,paths:[]};const i=this.policy.getEntities(n);return v(i,new M(i,this._getCache,this.endpoints),s)(e,t)}query(e,t,n,s=JSON.stringify(t)){const i=this.buildQueryKey(e,t,n,s);return i?this.denormalize(e,i,n.entities,t):{data:void 0,paths:[]}}buildQueryKey(e,t,n,s=JSON.stringify(t)){if("object"!=typeof e&&"function"!=typeof e.queryKey||!e)return e;let i=this.queryKeys.get(s);i||(i=new x,this.queryKeys.set(s,i));const r=new this.policy.QueryDelegate(n);let[a,o]=i.get(e,(c=r,e=>c[["","getEntitiesObject","getEntity","getIndex"][e.length]](...e)));var c;if(!o){const[n,s]=r.tracked(e);a=function(e){return function t(n,s){return function(e){return!!e&&"function"==typeof e.queryKey}(n)?n.queryKey(s,t,e):"object"==typeof n&&n?(Array.isArray(n)?u:f)(n,s,t,e):n}}(n)(e,t),i.set(s,a)}return a}}var C={Invalid:1,InvalidIfStale:2,Valid:3};function P(e,t){const n=Date.now();return{fetchedAt:null!=t?t:n,date:n,expiresAt:n+e}}const _="rdc/fetch",j="rdc/set",D="rdc/setresponse",T="rdc/optimistic",q="rdc/reset",N="rdc/subscribe",K="rdc/unsubscribe",V="rdc/invalidate",H="rdc/invalidateall",z="rdc/expireall",F="rdc/gc",U=_,B=j,Y=D,Q=T,$=q,W=N,X=K,J=V,G=H,Z=z,ee=F;var te=Object.freeze({__proto__:null,EXPIREALL:z,EXPIREALL_TYPE:Z,FETCH:_,FETCH_TYPE:U,GC:F,GC_TYPE:ee,INVALIDATE:V,INVALIDATEALL:H,INVALIDATEALL_TYPE:G,INVALIDATE_TYPE:J,OPTIMISTIC:T,OPTIMISTIC_TYPE:Q,RESET:q,RESET_TYPE:$,SET:j,SET_RESPONSE:D,SET_RESPONSE_TYPE:Y,SET_TYPE:B,SUBSCRIBE:N,SUBSCRIBE_TYPE:W,UNSUBSCRIBE:K,UNSUBSCRIBE_TYPE:X});const ne="undefined"!=typeof FormData?e=>e instanceof FormData?Object.fromEntries(e.entries()):e:e=>e;function se(e,t){if(t.endpoint.getOptimisticResponse&&t.endpoint.sideEffect){const a=(n=t.endpoint,s=t.args,i=t.meta.fetchedAt,{type:T,key:n.key(...s),args:s.map(ne),endpoint:n,meta:P(null!=(r=n.dataExpiryLength)?r:6e4,i)});return h({},e,{optimistic:[...e.optimistic,a]})}var n,s,i,r;return e}class ie extends Error{}function re(e,t,n){return"AbortError"===n.name?h({},e,{optimistic:ae(e,t)}):h({},e,{meta:h({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,error:n,errorPolicy:null==t.endpoint.errorPolicy?void 0:t.endpoint.errorPolicy(n)}}),optimistic:ae(e,t)})}function ae(e,t){return e.optimistic.filter((e=>e.key!==t.key||(e.type===T?e.meta.fetchedAt!==t.meta.fetchedAt:e.meta.date>t.meta.date)))}function oe(e){return function(t,n){switch(t||(t=ce),n.type){case F:return n.entities.forEach((({key:e,pk:n})=>{var s,i;null==(s=t.entities[e])||delete s[n],null==(i=t.entitiesMeta[e])||delete i[n]})),n.endpoints.forEach((e=>{delete t.endpoints[e],delete t.meta[e]})),t;case _:return se(t,n);case T:case D:return function(e,t,n){if(t.error)return re(e,t,t.response);try{var s;let i;if(t.type===T){if(!t.endpoint.getOptimisticResponse)return e;try{i=t.endpoint.getOptimisticResponse.call(t.endpoint,n.snapshot(e,t.meta.fetchedAt),...t.args)}catch(t){if(t.constructor===ie)return e;throw t}}else i=t.response;const{result:r,entities:a,indexes:o,entitiesMeta:c}=S(t.endpoint.schema,i,t.args,e,t.meta),l=h({},e.endpoints,{[t.key]:r});try{if(t.endpoint.update){const e=t.endpoint.update(r,...t.args);Object.keys(e).forEach((t=>{l[t]=e[t](l[t])}))}}catch(e){console.error(`Endpoint.update() error: ${t.key}`),console.error(e)}return{entities:a,endpoints:l,indexes:o,meta:h({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,prevExpiresAt:null==(s=e.meta[t.key])?void 0:s.expiresAt}}),entitiesMeta:c,optimistic:ae(e,t),lastReset:e.lastReset}}catch(n){return"object"==typeof n&&(n.message=`Error processing ${t.key}\n\nFull Schema: ${JSON.stringify(t.endpoint.schema,void 0,2)}\n\nError:\n${n.message}`,"response"in t&&(n.response=t.response),n.status=400),re(e,t,n)}}(t,n,e);case j:return function(e,t,n){let s;if("function"==typeof t.value){const i=n.get(t.schema,...t.args,e);if(void 0===i)return e;s=t.value(i)}else s=t.value;try{const{entities:n,indexes:i,entitiesMeta:r}=S(t.schema,s,t.args,e,t.meta);return{entities:n,endpoints:e.endpoints,indexes:i,meta:e.meta,entitiesMeta:r,optimistic:e.optimistic,lastReset:e.lastReset}}catch(t){return e}}(t,n,e);case H:case V:return function(e,t){const n=h({},e.endpoints),s=h({},e.meta),i=e=>{delete n[e];const t=h({},s[e],{expiresAt:0,invalidated:!0});delete t.error,s[e]=t};return t.type===V?i(t.key):Object.keys(n).forEach((e=>{t.testKey(e)&&i(e)})),h({},e,{endpoints:n,meta:s})}(t,n);case z:return function(e,t){const n=h({},e.meta);return Object.keys(n).forEach((e=>{t.testKey(e)&&(n[e]=h({},n[e],{expiresAt:1}))})),h({},e,{meta:n})}(t,n);case q:return h({},ce,{lastReset:n.date});default:return t}}}const ce={entities:{},endpoints:{},indexes:{},meta:{},entitiesMeta:{},optimistic:[],lastReset:0};function le(e,{args:t,fetchedAt:n,response:s,error:i=!1}){var r,a;const o=i?null!=(r=e.errorExpiryLength)?r:1e3:null!=(a=e.dataExpiryLength)?a:6e4;return{type:D,key:e.key(...t),response:s,args:t.map(ne),endpoint:e,meta:P(o,n),error:i}}class ue{init(){}cleanup(){}createCountRef(){return()=>()=>{}}}function he(e,t){return e.meta[t]}const de=e=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},pe=()=>ce;class fe{constructor({dispatch:e=de,getState:t=pe,memo:s=new O,gcPolicy:i=new ue}={}){this.fetch=(e,...t)=>{const s=function(e,{args:t}){let n=0,s=0;const i=new Promise(((e,t)=>{[n,s]=[e,t]})),r={fetchedAt:Date.now(),resolve:n,reject:s,promise:i};return{type:_,key:e.key(...t),args:t,endpoint:e,meta:r}}(e,{args:t});return this.dispatch(s),e.schema?s.meta.promise.then((s=>function(e,t,s,i=[]){return void 0===e||void 0===t?t:v(E.getEntities(s),new n,i)(e,t).data}(e.schema,s,{},t))):s.meta.promise},this.fetchIfStale=(e,...t)=>{const{data:n,expiresAt:s,expiryStatus:i}=this.getResponseMeta(e,...t,this.getState());return i!==C.Invalid&&Date.now()<=s?n:this.fetch(e,...t)},this.invalidate=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:V,key:e.key(...t)}}(e,{args:t})):Promise.resolve(),this.invalidateAll=e=>this.dispatch({type:H,testKey:t=>e.testKey(t)}),this.expireAll=e=>this.dispatch({type:z,testKey:t=>e.testKey(t)}),this.resetEntireStore=()=>this.dispatch({type:q,date:Date.now()}),this.setResponse=(e,...t)=>{const n=t[t.length-1],s=le(e,{args:t.slice(0,t.length-1),response:n});return this.dispatch(s)},this.setError=(e,...t)=>{const n=t[t.length-1],s=le(e,{args:t.slice(0,t.length-1),response:n,error:!0});return this.dispatch(s)},this.resolve=(e,t)=>this.dispatch(le(e,t)),this.subscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:N,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.unsubscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:K,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.snapshot=(e,t)=>new ge(this,e,t),this._dispatch=e,this.getState=t,this.memo=s,this.gcPolicy=i}set dispatch(e){this._dispatch=e}get dispatch(){return this._dispatch}bindMiddleware({dispatch:e,getState:t}){this._dispatch=e,this.getState=t}set(e,...t){const n=t[t.length-1],s=function(e,{args:t,fetchedAt:n,value:s}){return{type:j,value:s,args:t.map(ne),schema:e,meta:P(6e4,n)}}(e,{args:t.slice(0,t.length-1),value:n});return this.dispatch(s)}getError(e,...t){if(null===t[0])return;const n=t[t.length-1],s=t.slice(0,t.length-1),i=e.key(...s),r=he(n,i);return void 0===n.endpoints[i]||"soft"!==(null==r?void 0:r.errorPolicy)?null==r?void 0:r.error:void 0}getResponse(e,...t){return this.getResponseMeta(e,...t)}getResponseMeta(e,...t){const[n,s]=ve(t),i=1!==s.length||null!==s[0],r=i?e.key(...s):"",a=i?n.endpoints[r]:void 0,o=e.schema,c=he(n,r);let l=null==c?void 0:c.expiresAt;const u=void 0===a&&void 0!==o,h=u?this.memo.buildQueryKey(o,s,n,r):a;if(!i)return{data:h,expiryStatus:C.Valid,expiresAt:1/0,countRef:()=>()=>{}};let d=!1;if(u)d=!R(h);else if(!o||!ye(o))return{data:a,expiryStatus:this.getExpiryStatus(!a,!!e.invalidIfStale,c),expiresAt:l||0,countRef:this.gcPolicy.createCountRef({key:r})};const{data:p,paths:f}=this.memo.denormalize(o,h,n.entities,s);return l||(l=d?1:function(e,t){let n=1/0;for(const{key:i,pk:r}of e){var s;const e=null==(s=t[i])||null==(s=s[r])?void 0:s.expiresAt;e<n&&(n=e)}return n}(f,n.entitiesMeta)),{data:p,expiryStatus:this.getExpiryStatus("symbol"==typeof p,!!e.invalidIfStale||d,c),expiresAt:l,countRef:this.gcPolicy.createCountRef({key:r,paths:f})}}get(e,...t){const[n,s]=ve(t),{data:i}=this.memo.query(e,s,n);return"symbol"==typeof i?void 0:i}getQueryMeta(e,...t){const[n,s]=ve(t),{data:i,paths:r}=this.memo.query(e,s,n);return{data:"symbol"==typeof i?void 0:i,countRef:this.gcPolicy.createCountRef({paths:r})}}getExpiryStatus(e,t,n={}){return n.invalidated||e&&!n.error?C.Invalid:e||t?C.InvalidIfStale:C.Valid}}function ye(e){if(r(e))return!0;if(Array.isArray(e))return 0!==e.length&&ye(e[0]);if(e&&("object"==typeof e||"function"==typeof e)){const t="schema"in e?e.schema:e;return"function"==typeof t?ye(t):Object.values(t).some((e=>ye(e)))}return!1}class ge{constructor(e,t,n=0){this.state=void 0,this.controller=void 0,this.fetchedAt=void 0,this.abort=ge.abort,this.state=t,this.controller=e,this.fetchedAt=n}getResponse(e,...t){return this.controller.getResponse(e,...t,this.state)}getResponseMeta(e,...t){return this.controller.getResponseMeta(e,...t,this.state)}getError(e,...t){return this.controller.getError(e,...t,this.state)}get(e,...t){return this.controller.get(e,...t,this.state)}getQueryMeta(e,...t){return this.controller.getQueryMeta(e,...t,this.state)}}function ve(e){const t=e.length,n=new Array(t-1);for(let s=0;s<t-1;s++)n[s]=ne(e[s]);return[e[t-1],n]}ge.abort=new ie;class me extends Error{constructor(){super("Aborted due to RESET"),this.name="ResetError"}}class we{constructor({dataExpiryLength:e=6e4,errorExpiryLength:t=1e3}={}){this.fetching=new Map,this.controller=new fe,this.middleware=e=>(this.controller=e,t=>n=>{switch(n.type){case _:return this.handleFetch(n),void 0!==n.endpoint.getOptimisticResponse&&n.endpoint.sideEffect?t(n):Promise.resolve();case D:return t(n).then((()=>{if(this.fetching.has(n.key)){var t;const s=null==(t=e.getState().meta[n.key])?void 0:t.error;s?this.handleSet(le(n.endpoint,{args:n.args,response:s,fetchedAt:n.meta.fetchedAt,error:!0})):this.handleSet(n)}}));case q:{const e=Array.from(this.fetching.values());return this.clearAll(),t(n).then((()=>{for(const{reject:t}of e)t(new me)}))}default:return t(n)}}),this.dataExpiryLength=e,this.errorExpiryLength=t}init(){delete this.cleanupDate}cleanup(){this.cleanupDate=Date.now()}skipLogging(e){return e.type===_&&this.fetching.has(e.key)}allSettled(){if(this.fetching.size)return Promise.allSettled(this.fetching.values().map((({promise:e})=>e)))}clearAll(){for(const e of this.fetching.keys())this.clear(e)}clear(e){this.fetching.has(e)&&(this.fetching.get(e).promise.catch((()=>{})),this.fetching.delete(e))}getLastReset(){return this.cleanupDate?this.cleanupDate:this.controller.getState().lastReset}handleFetch(e){const{resolve:t,reject:n,fetchedAt:s}=e.meta,i=!e.endpoint.sideEffect,r=()=>{let r=e.endpoint(...e.args);return i||(r=(e=>e.then((e=>(t(e),e))).catch((e=>{throw n(e),e})))(r)),r=r.then((t=>{let n=this.getLastReset();return s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s}),t})).catch((t=>{const n=this.getLastReset();throw s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s,error:!0}),t})),r};return i?this.throttle(e.key,r,s).then((e=>t(e))).catch((e=>n(e))):r().catch((()=>{}))}handleSet(e){if(this.fetching.has(e.key)){const{reject:t,resolve:n}=this.fetching.get(e.key);e.error?t(e.response):n(e.response),this.clear(e.key)}}throttle(e,t,n){const s=this.getLastReset();let i=this.fetching.get(e);return i&&i.fetchedAt>s||(i=function(e){const t={fetchedAt:e};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}(n),this.fetching.set(e,i),this.idleCallback((()=>{t().catch((()=>null))}),{timeout:500})),i.promise}idleCallback(e,t){e()}}class Ee{isOnline(){return void 0===navigator.onLine||navigator.onLine}addOnlineListener(e){addEventListener("online",e)}removeOnlineListener(e){removeEventListener("online",e)}addOfflineListener(e){addEventListener("offline",e)}removeOfflineListener(e){removeEventListener("offline",e)}}class xe{isOnline(){return!0}addOnlineListener(){}removeOnlineListener(){}addOfflineListener(){}removeOfflineListener(){}}e.DefaultConnectionListener=void 0,"undefined"!=typeof navigator&&"function"==typeof addEventListener?e.DefaultConnectionListener=Ee:e.DefaultConnectionListener=xe;class be{constructor(t,n,s){if(this.frequencyHistogram=new Map,this.offlineListener=()=>{this.cleanup(),this.connectionListener.addOnlineListener(this.onlineListener)},this.onlineListener=()=>{this.connectionListener.removeOnlineListener(this.onlineListener);const e=Date.now();this.startId=setTimeout((()=>{this.startId&&(delete this.startId,this.update(),this.run())}),Math.max(0,this.lastFetchTime()-e+this.frequency)),this.connectionListener.addOfflineListener(this.offlineListener)},void 0===t.endpoint.pollFrequency)throw new Error("frequency needed for polling subscription");this.endpoint=t.endpoint,this.frequency=t.endpoint.pollFrequency,this.args=t.args,this.key=t.key,this.frequencyHistogram.set(this.frequency,1),this.controller=n,this.connectionListener=s||new e.DefaultConnectionListener,this.connectionListener.isOnline()?this.onlineListener():this.offlineListener()}add(e){void 0!==e&&(this.frequencyHistogram.has(e)?this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)+1):(this.frequencyHistogram.set(e,1),e<this.frequency&&(this.frequency=e,this.run())))}remove(e){if(void 0===e)return!1;if(this.frequencyHistogram.has(e)&&(this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)-1),this.frequencyHistogram.get(e)<1)){if(this.frequencyHistogram.delete(e),0===this.frequencyHistogram.size)return this.cleanup(),!0;e<=this.frequency&&(this.frequency=Math.min(...this.frequencyHistogram.keys()),this.run())}return!1}cleanup(){this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId),this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.startId&&(clearTimeout(this.startId),delete this.startId),this.connectionListener.removeOnlineListener(this.onlineListener),this.connectionListener.removeOfflineListener(this.offlineListener)}update(){const e=this.endpoint,t=function(...t){return e.call(this,...t)};Object.assign(t,this.endpoint),t.dataExpiryLength=this.frequency/2,t.errorExpiryLength=this.frequency/10,t.errorPolicy=()=>"soft",t.key=()=>this.key,this.controller.fetch(t,...this.args).catch((()=>null))}run(){this.startId||(this.intervalId&&(this.lastIntervalId=this.intervalId),this.intervalId=setInterval((()=>{this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.intervalId&&this.update()}),this.frequency))}lastFetchTime(){var e,t;return null!=(e=null==(t=this.controller.getState().meta[this.key])?void 0:t.date)?e:0}}class ke{constructor(e){this.subscriptions={},this.controller=new fe,this.middleware=e=>(this.controller=e,e=>t=>{switch(t.type){case N:try{this.handleSubscribe(t)}catch(e){console.error(e)}return Promise.resolve();case K:return this.handleUnsubscribe(t),Promise.resolve();default:return e(t)}}),this.Subscription=e}cleanup(){for(const e in this.subscriptions)this.subscriptions[e].cleanup()}handleSubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].add(n)}else this.subscriptions[t]=new this.Subscription(e,this.controller)}handleUnsubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].remove(n)&&delete this.subscriptions[t]}}}let Ie={};class Le{constructor(e,t){this.started=!1,this.actions=[],this.maxBufferLength=100,this.devTools="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__.connect(h({},Ie,e)),null!=e&&e.maxAge&&(this.maxBufferLength=2*e.maxAge),t&&(this.skipLogging=t)}handleAction(e,t){this.started?this.devTools.send(e,t):(this.actions.length>this.maxBufferLength&&(this.actions=this.actions.slice(this.maxBufferLength/2)),this.actions.push([e,t]))}init(e){}cleanup(){}}Le.prototype.middleware=()=>e=>t=>e(t);const Se=Symbol("DataClientState"),Ae=Symbol("DataClientController"),Me=t.shallowRef(ce);function Re(){const e=t.inject(Ae,null);return e||new fe}function Oe(){const e=t.inject(Se,null);return e||Me}async function Ce(e,...n){const s=Oe(),i=Re(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=async()=>{if(!a.value)return;const t=o.value,n=t.expiryStatus===C.Invalid;Date.now()<=t.expiresAt&&!n||await i.fetch(e,...r.value)};return t.watch((()=>{const e=o.value;return[e.expiresAt,e.expiryStatus,s.value.lastReset,a.value]}),(()=>c())),t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>null==s?void 0:s()))}),{immediate:!0}),await c(),t.readonly(t.computed((()=>o.value.data)))}function Pe(e,...n){const s=Re(),i=t.computed((()=>n.map((e=>t.unref(e))))),r=t.computed((()=>null===i.value[0]?"":e.key(...i.value)));t.watch(r,((t,n,a)=>{if(!r.value)return;const o=i.value;s.subscribe(e,...o),a((()=>{s.unsubscribe(e,...o)}))}),{immediate:!0})}let _e=(e={})=>{const{networkManager:t,subscriptionManager:n=be}=e;return null===n?[je(we,null!=t?t:{})]:[je(we,null!=t?t:{}),je(ke,n)]};function je(e,t){return t instanceof e?t:new e(t)}function De(e={}){var n,s;const{Controller:i=fe,gcPolicy:r,app:a}=e,o=new i({gcPolicy:r}),c=null!=(n=e.managers)?n:_e(),l=null!=(s=e.initialState)?s:ce,u=function(e,t,n){return()=>(e.forEach((e=>{null==e.init||e.init(n)})),t.gcPolicy.init(t),()=>{e.forEach((e=>{e.cleanup()})),t.gcPolicy.cleanup()})}(c,o,l),h=function(e,t){return e.map(((e,n)=>(e.middleware||(e.middleware=null==e.getMiddleware?void 0:e.getMiddleware()),s=>(0===n&&t.bindMiddleware(s),e.middleware(t)))))}(c,o),d=oe(o),p=t.shallowRef(l),f=t.shallowRef(x(l));let y=null;const g=()=>p.value,v=h.map((e=>e({getState:g,dispatch:e=>m(e)}))),m=(w=v,e=>w.reduceRight(((e,t)=>t(e)),e))((async e=>{const t=new Promise((e=>{y=e}));return await(async e=>{const t=d(p.value,e);if(p.value=t,f.value=x(t),y){const e=y;y=null,e()}})(e),t}));var w;let E;o.bindMiddleware({getState:g,dispatch:e=>m(e)});return a?(a.provide(Se,f),a.provide(Ae,o)):(t.provide(Se,f),t.provide(Ae,o)),{controller:o,stateRef:f,start:()=>{E=u()},stop:()=>{E&&E()}};function x(e){return e.optimistic.reduce(d,e)}}const Te={install(e,t={}){const n=De(h({},t,{app:e}));return e.config.globalProperties.$dataClient=n.controller,n.start(),e.onUnmount((()=>{n.stop()})),n}};e.Controller=fe,e.DataClientPlugin=Te,e.DevToolsManager=Le,e.ExpiryStatus=C,e.LogoutManager=class{constructor({handleLogout:e,shouldLogout:t}={}){this.middleware=e=>t=>async n=>{await t(n),n.type===D&&n.error&&this.shouldLogout(n.response)&&this.handleLogout(e)},e&&(this.handleLogout=e),t&&(this.shouldLogout=t)}cleanup(){}shouldLogout(e){return 401===e.status}handleLogout(e){e.resetEntireStore()}},e.NetworkManager=we,e.PollingSubscription=be,e.SubscriptionManager=ke,e.actionTypes=te,e.createDataClient=De,e.getDefaultManagers=_e,e.useCache=function(e,...n){const s=Oe(),i=Re(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=t.computed((()=>o.value.expiryStatus===C.Invalid)),l=t.computed((()=>(Date.now()>o.value.expiresAt||c.value)&&a.value)),u=t.computed((()=>o.value.expiryStatus!==C.Valid&&l.value));return t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>s()))}),{immediate:!0}),t.computed((()=>{if(u.value){if(!e.schema)return;return i.getResponseMeta(e,...r.value,h({},s.value,{entities:{}})).data}return o.value.data}))},e.useController=Re,e.useDLE=function(e,...n){const s=Oe(),i=Re(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=t.computed((()=>o.value.expiryStatus===C.Invalid)),l=t.computed((()=>!(!(Date.now()>o.value.expiresAt||c.value)||!a.value))),u=t.computed((()=>!(o.value.expiryStatus===C.Valid||!l.value)));t.watch((()=>{const e=o.value;return[e.expiresAt,e.expiryStatus,s.value.lastReset,a.value]}),(async()=>{if(!a.value)return;const t=o.value,n=c.value;Date.now()<=t.expiresAt&&!n||await i.fetch(e,...r.value).catch((()=>{}))}),{immediate:!0}),t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>s()))}),{immediate:!0});const d=t.computed((()=>{if(u.value){if(!e.schema)return;return i.getResponseMeta(e,...r.value,h({},s.value,{entities:{}})).data}return o.value.data})),p=t.computed((()=>i.getError(e,...r.value,s.value)));return t.markRaw({data:d,loading:u,error:p})},e.useDebounce=function(e,n,s=!0){const i=t.ref("object"==typeof e&&null!==e&&"value"in e?e.value:e),r=t.ref(!1);let a=null;const o=()=>{null!==a&&(clearTimeout(a),a=null)};return t.watch([()=>"object"==typeof e&&null!==e&&"value"in e?e.value:e,()=>"object"==typeof s&&null!==s&&"value"in s?s.value:s,()=>n],(([e,t])=>{o(),t?(r.value=!0,a=setTimeout((()=>{i.value=e,r.value=!1,a=null}),n)):r.value=!1}),{immediate:!1}),t.onUnmounted((()=>{o()})),[i,r]},e.useFetch=function(e,...n){const s=Oe(),i=Re(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=t.ref(void 0),l=()=>{if(!a.value)return;const t=o.value,n=t.expiryStatus===C.Invalid;Date.now()<=t.expiresAt&&!n||(c.value=i.fetch(e,...r.value))};return l(),t.watch((()=>{const e=o.value;return[e.expiresAt,e.expiryStatus,s.value.lastReset,a.value]}),(()=>{l()})),c},e.useLive=async function(e,...t){return Pe(e,...t),Ce(e,...t)},e.useLoading=function(e){const n=t.ref(!1),s=t.ref(void 0),i=t.ref(!0);return t.onUnmounted((()=>{i.value=!1})),[async(...t)=>{let r;n.value=!0,s.value=void 0;try{r=await e(...t)}catch(e){s.value=e}finally{i.value&&(n.value=!1)}return r},n,s]},e.useQuery=function(e,...n){const s=Oe(),i=Re(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>i.getQueryMeta(e,...r.value,s.value)));return t.watch((()=>a.value.data),((e,t,n)=>{const s=a.value.countRef();n((()=>s()))}),{immediate:!0}),t.computed((()=>a.value.data))},e.useSubscription=Pe,e.useSuspense=Ce}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VDC={},e.Vue)}(this,(function(e,t){"use strict";class n{constructor(){this.localCache=new Map}getEntity(e,t,n,s){const i=t.key;this.localCache.has(i)||this.localCache.set(i,new Map);const r=this.localCache.get(i);return r.get(e)||s(r),r.get(e)}getResults(e,t,n){return{data:n(),paths:[]}}}const s=Symbol("INVALID"),i={};function r(e){return null!==e&&void 0!==e.pk}const a=e=>e[0],o=e=>void 0!==e&&"symbol"!=typeof e,c=(e,t,n,s,i,r)=>{e=a(e);const o=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(t);return o.map((t=>r(e,t,n,s,i)))},l=(e,t,n,s)=>(e=a(e),t.map?t.map((t=>s(e,t))).filter(o):t);function u(){}function h(){return h=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)({}).hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},h.apply(null,arguments)}const d=(e,t,n,s,i,r)=>{const a=h({},t),o=Object.keys(e);for(let n=0;n<o.length;n++){const s=o[n],c=r(e[s],t[s],t,s,i);void 0===c?delete a[s]:a[s]=c}return a},p=(e,t,n,i)=>{if(function(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}(t))return function(e,t,n,i){let r=!1;const a=Object.keys(e).reduce(((t,n)=>{const s=`${n}`,a=i(e[s],t.get(s));return"symbol"==typeof a&&(r=!0),t.has(s)?t.set(s,a):t}),t);return r?s:a}(e,t,0,i);const r=h({},t);let a=!1;const o=Object.keys(e);for(let t=0;t<o.length;t++){const n=o[t],s=i(e[n],r[n]);void 0!==r[n]&&(r[n]=s),"symbol"==typeof s&&(a=!0)}return a?s:r};function f(e,t,n,s){const i={};for(const r of Object.keys(e))i[r]=n(e[r],t,s);return i}const y=(e,t,n,s)=>function(r,a){const o="object"!=typeof a,c=o?e({key:r.key,pk:a}):a;if("symbol"==typeof c)return r.denormalize(c,n,s);if(void 0===c&&o&&""!==a&&"undefined"!==a)return t.getEntity(a,r,i,(e=>{e.set(a,void 0)}));if("object"!=typeof c||null===c)return c;let l=o?a:r.pk(c,void 0,void 0,n);return void 0===l||""===l||"undefined"===l?function(e){const t=new Map;return e(t),t.get("")}((e=>g(r,c,"",e,n,s))):("string"!=typeof l&&(l=`${l}`),t.getEntity(l,r,c,(e=>g(r,c,l,e,n,s))))};function g(e,t,n,i,r,a){const o=e.createIfValid(t);void 0===o?i.set(n,s):(i.set(n,o),i.set(n,e.denormalize(o,r,a)))}const v=(e,t,n)=>{let i=0;const a=y(e,t,n,o);function o(t,c){if(!t)return c;if(null==c)return c;if("function"==typeof t.denormalize){if(r(t)){var u;if(i>=(null!=(u=t.maxEntityDepth)?u:64))return function(e,t,n){var i;const r="object"!=typeof n?e({key:t.key,pk:n}):n;return"object"!=typeof r||null===r?r:null!=(i=t.createIfValid(r))?i:s}(e,t,c);i++;const n=a(t,c);return i--,n}return t.denormalize(c,n,o)}if("function"==typeof t)return t(c);if("object"==typeof t){return(Array.isArray(t)?l:p)(t,c,n,o)}return c}return(e,n)=>{const s=Object(n)===n&&Object(e)===e;return t.getResults(n,s,(()=>o(e,n)))}};class m{constructor({entities:e,indexes:t}){this.entities=e,this.indexes=t}tracked(e){const t=this,n=[{path:[""],entity:e}];return[{INVALID:s,getIndex(...e){const s=t.getIndex(...e);return n.push({path:e,entity:s}),t.getIndexEnd(s,e[2])},getEntity(...e){const s=t.getEntity(...e);return n.push({path:e,entity:s}),s},getEntities(e){const s=t.getEntitiesObject(e);return n.push({path:[e],entity:s}),t.getEntities(e)}},n]}}class w extends m{constructor(e){super(e)}getEntitiesObject(e){return this.entities[e]}getEntities(e){const t=this.entities[e];if(void 0!==t)return{keys:()=>Object.keys(t),entries:()=>Object.entries(t)}}getEntity(e,t){var n;return null==(n=this.entities[e])?void 0:n[t]}getIndex(e,t){var n;return null==(n=this.indexes[e])?void 0:n[t]}getIndexEnd(e,t){return null==e?void 0:e[t]}}const E={QueryDelegate:w,getEntities:e=>({key:t,pk:n})=>{var s;return null==(s=e[t])?void 0:s[n]}};class x{constructor(){this.next=new WeakMap,this.nextPath=void 0}get(e,t){let n=this.next.get(e);if(!n)return b;for(;n.nextPath;){var s;const e=null!=(s=t(n.nextPath))?s:i;if(n=n.next.get(e),!n)return b}return[n.value,n.journey]}set(e,t){if(e.length<1)throw new I;let n=this;for(const{path:t,entity:s}of e){let e=n.next.get(s);e||(e=new k,n.next.set(null!=s?s:i,e)),n.nextPath=t,n=e}n.nextPath=void 0,n.value=t,n.journey=e.map((e=>e.path))}}const b=[void 0,void 0];class k{constructor(){this.next=new WeakMap,this.nextPath=void 0,this.value=void 0,this.journey=[]}}class I extends Error{constructor(...e){super(...e),this.message="Keys must include at least one member"}}class L extends w{constructor(e,t){super(e),this.newEntities=new Map,this.newIndexes=new Map,this.entitiesMeta=e.entitiesMeta,this.meta=t,this.checkLoop=function(){const e=new Map;return function(t,n,s){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r=new Set,i.set(n,r)),!!r.has(s)||(r.add(s),!1)}}()}getNewEntity(e,t){return this.getNewEntities(e).get(t)}getNewEntities(e){let t=this.newEntities.get(e);return void 0===t&&(t=new Map,this.newEntities.set(e,t)),t}getNewIndexes(e){return this.newIndexes.has(e)||(this.newIndexes.set(e,new Map),this.indexes[e]=h({},this.indexes[e])),this.newIndexes.get(e)}mergeEntity(e,t,n){const s=e.key;let i=n,r=this.meta,a=this.getNewEntity(s,t);if(a)i=e.merge(a,n);else if(a=this.getEntity(s,t),a){const o=this.getMeta(s,t);i=e.mergeWithStore(o,r,a,n),r=e.mergeMetaWithStore(o,r,a,n)}this.setEntity(e,t,i,r)}setEntity(e,t,n,i=this.meta){const r=e.key,a=this.getNewEntities(r),o=!a.has(t);o&&0===a.size&&(this.entities[r]=h({},this.entities[r]),this.entitiesMeta[r]=h({},this.entitiesMeta[r])),a.set(t,n),e.indexes&&function(e,t,n,i,r,a){for(const o of t){n.has(o)||n.set(o,i[o]={});const t=n.get(o);a[e]&&delete t[a[e][o]],a&&a[e]&&a[e][o]!==r[o]&&(t[a[e][o]]=s),o in r&&(t[r[o]]=e)}}(t,e.indexes,this.getNewIndexes(r),this.indexes[r],n,this.entities[r]),this._setEntity(r,t,n),o&&this._setMeta(r,t,i)}invalidate({key:e},t){this.setEntity({key:e},t,s)}_setEntity(e,t,n){this.entities[e][t]=n}_setMeta(e,t,n){this.entitiesMeta[e][t]=n}getMeta(e,t){return this.entitiesMeta[e][t]}}const A=(e,t,n=[],{entities:s,indexes:i,entitiesMeta:r}=S,a={fetchedAt:0,date:Date.now(),expiresAt:1/0})=>{if(null==e)return{result:t,entities:s,indexes:i,entitiesMeta:r};const o=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(e);if(null===t||typeof t!==o&&(void 0===e.key||void 0!==e.pk||"string"!=typeof t))throw new Error(`Unexpected input given to normalize. Expected type to be "${o}", found "${null===t?"null":typeof t}".`);const l={entities:h({},s),indexes:h({},i),entitiesMeta:h({},r)},u=(e=>{const t=(n,s,i,r,a)=>s&&n?n.normalize&&"function"==typeof n.normalize?"object"!=typeof s?n.pk?`${s}`:s:n.normalize(s,i,r,a,t,e):"object"!=typeof s||"object"!=typeof n?s:(Array.isArray(n)?c:d)(n,s,i,r,a,t):s;return t})(new L(l,a));return{result:u(e,t,t,void 0,n),entities:l.entities,indexes:l.indexes,entitiesMeta:l.entitiesMeta}};const S={entities:{},indexes:{},entitiesMeta:{}},M={path:{key:"",pk:""},entity:void 0};class R{constructor(e,t,n){this.dependencies=[M],this.cycleCache=new Map,this.cycleIndex=-1,this.localCache=new Map,this._getEntity=e,this._getCache=t,this._resultCache=n}getEntity(e,t,n,s){const i=t.key,r=this.getOrCreateLocalCache(i);if(r.get(e)){const t=this.cycleCache.get(i);null!=t&&t.has(e)?this.cycleIndex=t.get(e):this.dependencies.push({path:{key:i,pk:e},entity:n})}else{const a=this._getCache(e,t),[o,c]=a.get(n,this._getEntity);if(c){r.set(e,o.value);const t=o.dependencies;for(let e=0;e<t.length;e++)this.dependencies.push(t[e]);return o.value}{const t=this.dependencies.length,o=this.getOrCreateCycleCache(i);o.set(e,t),this.dependencies.push({path:{key:i,pk:e},entity:n}),s(r),o.delete(e);const c=this.dependencies.slice(-1===this.cycleIndex?t:this.cycleIndex),l={dependencies:c,value:r.get(e)};a.set(c,l),this.cycleIndex===t&&(this.cycleIndex=-1)}}return r.get(e)}getOrCreateLocalCache(e){let t=this.localCache.get(e);return t||(t=new Map,this.localCache.set(e,t)),t}getOrCreateCycleCache(e){let t=this.cycleCache.get(e);return t||(t=new Map,this.cycleCache.set(e,t)),t}getResults(e,t,n){if(!t)return{data:n(),paths:this.paths()};let[s,i]=this._resultCache.get(e,this._getEntity);return void 0===i?(s=n(),i=this.paths(),this.dependencies[0]={path:{key:"",pk:""},entity:e},this._resultCache.set(this.dependencies,s)):i.shift(),{data:s,paths:i}}paths(){const e=this.dependencies,t=new Array(e.length-1);for(let n=1;n<e.length;n++)t[n-1]=e[n].path;return t}}function O(e){return void 0!==e&&(!(e&&"object"==typeof e&&!Array.isArray(e))||Object.values(e).every(O))}class C{constructor(e=E){var t;this.endpoints=new x,this.queryKeys=new Map,this.policy=e,this._getCache=(t=new Map,(e,n)=>{var s;const i=n.key,r=null!=(s=n.cacheWith)?s:n;t.has(i)||t.set(i,new Map);const a=t.get(i);a.has(e)||a.set(e,new WeakMap);const o=a.get(e);let c=o.get(r);return c||(c=new x,o.set(r,c)),c})}denormalize(e,t,n,s=[]){if(void 0===e)return{data:t,paths:[]};if(void 0===t)return{data:void 0,paths:[]};const i=this.policy.getEntities(n);return v(i,new R(i,this._getCache,this.endpoints),s)(e,t)}query(e,t,n,s=JSON.stringify(t)){const i=this.buildQueryKey(e,t,n,s);return i?this.denormalize(e,i,n.entities,t):{data:void 0,paths:[]}}buildQueryKey(e,t,n,s=JSON.stringify(t)){if("object"!=typeof e&&"function"!=typeof e.queryKey||!e)return e;let i=this.queryKeys.get(s);i||(i=new x,this.queryKeys.set(s,i));const r=new this.policy.QueryDelegate(n);let[a,o]=i.get(e,(c=r,e=>{switch(e.length){case 1:return c.getEntitiesObject(e[0]);case 2:return c.getEntity(e[0],e[1]);case 3:return c.getIndex(e[0],e[1],e[2])}}));var c;if(!o){const[n,s]=r.tracked(e);a=function(e){return function t(n,s){return function(e){return!!e&&"function"==typeof e.queryKey}(n)?n.queryKey(s,t,e):"object"==typeof n&&n?(Array.isArray(n)?u:f)(n,s,t,e):n}}(n)(e,t),i.set(s,a)}return a}}var P={Invalid:1,InvalidIfStale:2,Valid:3};function j(e,t){const n=Date.now();return{fetchedAt:null!=t?t:n,date:n,expiresAt:n+e}}const _="rdc/fetch",D="rdc/set",T="rdc/setresponse",q="rdc/optimistic",N="rdc/reset",V="rdc/subscribe",K="rdc/unsubscribe",z="rdc/invalidate",H="rdc/invalidateall",F="rdc/expireall",U="rdc/gc",B=_,Y=D,$=T,Q=q,W=N,X=V,J=K,G=z,Z=H,ee=F,te=U;var ne=Object.freeze({__proto__:null,EXPIREALL:F,EXPIREALL_TYPE:ee,FETCH:_,FETCH_TYPE:B,GC:U,GC_TYPE:te,INVALIDATE:z,INVALIDATEALL:H,INVALIDATEALL_TYPE:Z,INVALIDATE_TYPE:G,OPTIMISTIC:q,OPTIMISTIC_TYPE:Q,RESET:N,RESET_TYPE:W,SET:D,SET_RESPONSE:T,SET_RESPONSE_TYPE:$,SET_TYPE:Y,SUBSCRIBE:V,SUBSCRIBE_TYPE:X,UNSUBSCRIBE:K,UNSUBSCRIBE_TYPE:J});const se="undefined"!=typeof FormData?e=>e instanceof FormData?Object.fromEntries(e.entries()):e:e=>e;function ie(e,t){if(t.endpoint.getOptimisticResponse&&t.endpoint.sideEffect){const a=(n=t.endpoint,s=t.args,i=t.meta.fetchedAt,{type:q,key:n.key(...s),args:s.map(se),endpoint:n,meta:j(null!=(r=n.dataExpiryLength)?r:6e4,i)});return h({},e,{optimistic:[...e.optimistic,a]})}var n,s,i,r;return e}class re extends Error{}function ae(e,t,n){return"AbortError"===n.name?h({},e,{optimistic:oe(e,t)}):h({},e,{meta:h({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,error:n,errorPolicy:null==t.endpoint.errorPolicy?void 0:t.endpoint.errorPolicy(n)}}),optimistic:oe(e,t)})}function oe(e,t){return e.optimistic.filter((e=>e.key!==t.key||(e.type===q?e.meta.fetchedAt!==t.meta.fetchedAt:e.meta.date>t.meta.date)))}function ce(e){return function(t,n){switch(t||(t=le),n.type){case U:return n.entities.forEach((({key:e,pk:n})=>{var s,i;null==(s=t.entities[e])||delete s[n],null==(i=t.entitiesMeta[e])||delete i[n]})),n.endpoints.forEach((e=>{delete t.endpoints[e],delete t.meta[e]})),t;case _:return ie(t,n);case q:case T:return function(e,t,n){if(t.error)return ae(e,t,t.response);try{var s;let i;if(t.type===q){if(!t.endpoint.getOptimisticResponse)return e;try{i=t.endpoint.getOptimisticResponse.call(t.endpoint,n.snapshot(e,t.meta.fetchedAt),...t.args)}catch(t){if(t.constructor===re)return e;throw t}}else i=t.response;const{result:r,entities:a,indexes:o,entitiesMeta:c}=A(t.endpoint.schema,i,t.args,e,t.meta),l=h({},e.endpoints,{[t.key]:r});try{if(t.endpoint.update){const e=t.endpoint.update(r,...t.args);Object.keys(e).forEach((t=>{l[t]=e[t](l[t])}))}}catch(e){console.error(`Endpoint.update() error: ${t.key}`),console.error(e)}return{entities:a,endpoints:l,indexes:o,meta:h({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,prevExpiresAt:null==(s=e.meta[t.key])?void 0:s.expiresAt}}),entitiesMeta:c,optimistic:oe(e,t),lastReset:e.lastReset}}catch(n){return"object"==typeof n&&(n.message=`Error processing ${t.key}\n\nFull Schema: ${JSON.stringify(t.endpoint.schema,void 0,2)}\n\nError:\n${n.message}`,"response"in t&&(n.response=t.response),n.status=400),ae(e,t,n)}}(t,n,e);case D:return function(e,t,n){let s;if("function"==typeof t.value){const i=n.get(t.schema,...t.args,e);if(void 0===i)return e;s=t.value(i)}else s=t.value;try{const{entities:n,indexes:i,entitiesMeta:r}=A(t.schema,s,t.args,e,t.meta);return{entities:n,endpoints:e.endpoints,indexes:i,meta:e.meta,entitiesMeta:r,optimistic:e.optimistic,lastReset:e.lastReset}}catch(t){return e}}(t,n,e);case H:case z:return function(e,t){const n=h({},e.endpoints),s=h({},e.meta),i=e=>{delete n[e];const t=h({},s[e],{expiresAt:0,invalidated:!0});delete t.error,s[e]=t};return t.type===z?i(t.key):Object.keys(n).forEach((e=>{t.testKey(e)&&i(e)})),h({},e,{endpoints:n,meta:s})}(t,n);case F:return function(e,t){const n=h({},e.meta);return Object.keys(n).forEach((e=>{t.testKey(e)&&(n[e]=h({},n[e],{expiresAt:1}))})),h({},e,{meta:n})}(t,n);case N:return h({},le,{lastReset:n.date});default:return t}}}const le={entities:{},endpoints:{},indexes:{},meta:{},entitiesMeta:{},optimistic:[],lastReset:0};function ue(e,{args:t,fetchedAt:n,response:s,error:i=!1}){var r,a;const o=i?null!=(r=e.errorExpiryLength)?r:1e3:null!=(a=e.dataExpiryLength)?a:6e4;return{type:T,key:e.key(...t),response:s,args:t.map(se),endpoint:e,meta:j(o,n),error:i}}class he{init(){}cleanup(){}createCountRef(){return()=>()=>{}}}function de(e,t){return e.meta[t]}const pe=e=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},fe=()=>le;class ye{constructor({dispatch:e=pe,getState:t=fe,memo:s=new C,gcPolicy:i=new he}={}){this.fetch=(e,...t)=>{const s=function(e,{args:t}){let n=0,s=0;const i=new Promise(((e,t)=>{[n,s]=[e,t]})),r={fetchedAt:Date.now(),resolve:n,reject:s,promise:i};return{type:_,key:e.key(...t),args:t,endpoint:e,meta:r}}(e,{args:t});return this.dispatch(s),e.schema?s.meta.promise.then((s=>function(e,t,s,i=[]){return void 0===e||void 0===t?t:v(E.getEntities(s),new n,i)(e,t).data}(e.schema,s,{},t))):s.meta.promise},this.fetchIfStale=(e,...t)=>{const{data:n,expiresAt:s,expiryStatus:i}=this.getResponseMeta(e,...t,this.getState());return i!==P.Invalid&&Date.now()<=s?n:this.fetch(e,...t)},this.invalidate=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:z,key:e.key(...t)}}(e,{args:t})):Promise.resolve(),this.invalidateAll=e=>this.dispatch({type:H,testKey:t=>e.testKey(t)}),this.expireAll=e=>this.dispatch({type:F,testKey:t=>e.testKey(t)}),this.resetEntireStore=()=>this.dispatch({type:N,date:Date.now()}),this.setResponse=(e,...t)=>{const n=t[t.length-1],s=ue(e,{args:t.slice(0,t.length-1),response:n});return this.dispatch(s)},this.setError=(e,...t)=>{const n=t[t.length-1],s=ue(e,{args:t.slice(0,t.length-1),response:n,error:!0});return this.dispatch(s)},this.resolve=(e,t)=>this.dispatch(ue(e,t)),this.subscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:V,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.unsubscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:K,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.snapshot=(e,t)=>new ve(this,e,t),this._dispatch=e,this.getState=t,this.memo=s,this.gcPolicy=i}set dispatch(e){this._dispatch=e}get dispatch(){return this._dispatch}bindMiddleware({dispatch:e,getState:t}){this._dispatch=e,this.getState=t}set(e,...t){const n=t[t.length-1],s=function(e,{args:t,fetchedAt:n,value:s}){return{type:D,value:s,args:t.map(se),schema:e,meta:j(6e4,n)}}(e,{args:t.slice(0,t.length-1),value:n});return this.dispatch(s)}getError(e,...t){if(null===t[0])return;const n=t[t.length-1],s=t.slice(0,t.length-1),i=e.key(...s),r=de(n,i);return void 0===n.endpoints[i]||"soft"!==(null==r?void 0:r.errorPolicy)?null==r?void 0:r.error:void 0}getResponse(e,...t){return this.getResponseMeta(e,...t)}getResponseMeta(e,...t){const[n,s]=me(t),i=1!==s.length||null!==s[0],r=i?e.key(...s):"",a=i?n.endpoints[r]:void 0,o=e.schema,c=de(n,r);let l=null==c?void 0:c.expiresAt;const u=void 0===a&&void 0!==o,h=u?this.memo.buildQueryKey(o,s,n,r):a;if(!i)return{data:h,expiryStatus:P.Valid,expiresAt:1/0,countRef:()=>()=>{}};let d=!1;if(u)d=!O(h);else if(!o||!ge(o))return{data:a,expiryStatus:this.getExpiryStatus(!a,!!e.invalidIfStale,c),expiresAt:l||0,countRef:this.gcPolicy.createCountRef({key:r})};const{data:p,paths:f}=this.memo.denormalize(o,h,n.entities,s);return l||(l=d?1:function(e,t){let n=1/0;for(const{key:i,pk:r}of e){var s;const e=null==(s=t[i])||null==(s=s[r])?void 0:s.expiresAt;e<n&&(n=e)}return n}(f,n.entitiesMeta)),{data:p,expiryStatus:this.getExpiryStatus("symbol"==typeof p,!!e.invalidIfStale||d,c),expiresAt:l,countRef:this.gcPolicy.createCountRef({key:r,paths:f})}}get(e,...t){const[n,s]=me(t),{data:i}=this.memo.query(e,s,n);return"symbol"==typeof i?void 0:i}getQueryMeta(e,...t){const[n,s]=me(t),{data:i,paths:r}=this.memo.query(e,s,n);return{data:"symbol"==typeof i?void 0:i,countRef:this.gcPolicy.createCountRef({paths:r})}}getExpiryStatus(e,t,n={}){return n.invalidated||e&&!n.error?P.Invalid:e||t?P.InvalidIfStale:P.Valid}}function ge(e){if(r(e))return!0;if(Array.isArray(e))return 0!==e.length&&ge(e[0]);if(e&&("object"==typeof e||"function"==typeof e)){const t="schema"in e?e.schema:e;return"function"==typeof t?ge(t):Object.values(t).some((e=>ge(e)))}return!1}class ve{constructor(e,t,n=0){this.state=void 0,this.controller=void 0,this.fetchedAt=void 0,this.abort=ve.abort,this.state=t,this.controller=e,this.fetchedAt=n}getResponse(e,...t){return this.controller.getResponse(e,...t,this.state)}getResponseMeta(e,...t){return this.controller.getResponseMeta(e,...t,this.state)}getError(e,...t){return this.controller.getError(e,...t,this.state)}get(e,...t){return this.controller.get(e,...t,this.state)}getQueryMeta(e,...t){return this.controller.getQueryMeta(e,...t,this.state)}}function me(e){const t=e.length,n=new Array(t-1);for(let s=0;s<t-1;s++)n[s]=se(e[s]);return[e[t-1],n]}ve.abort=new re;class we extends Error{constructor(){super("Aborted due to RESET"),this.name="ResetError"}}class Ee{constructor({dataExpiryLength:e=6e4,errorExpiryLength:t=1e3}={}){this.fetching=new Map,this.controller=new ye,this.middleware=e=>(this.controller=e,t=>n=>{switch(n.type){case _:return this.handleFetch(n),void 0!==n.endpoint.getOptimisticResponse&&n.endpoint.sideEffect?t(n):Promise.resolve();case T:return t(n).then((()=>{if(this.fetching.has(n.key)){var t;const s=null==(t=e.getState().meta[n.key])?void 0:t.error;s?this.handleSet(ue(n.endpoint,{args:n.args,response:s,fetchedAt:n.meta.fetchedAt,error:!0})):this.handleSet(n)}}));case N:{const e=Array.from(this.fetching.values());return this.clearAll(),t(n).then((()=>{for(const{reject:t}of e)t(new we)}))}default:return t(n)}}),this.dataExpiryLength=e,this.errorExpiryLength=t}init(){delete this.cleanupDate}cleanup(){this.cleanupDate=Date.now()}skipLogging(e){return e.type===_&&this.fetching.has(e.key)}allSettled(){if(this.fetching.size)return Promise.allSettled(this.fetching.values().map((({promise:e})=>e)))}clearAll(){for(const e of this.fetching.keys())this.clear(e)}clear(e){this.fetching.has(e)&&(this.fetching.get(e).promise.catch((()=>{})),this.fetching.delete(e))}getLastReset(){return this.cleanupDate?this.cleanupDate:this.controller.getState().lastReset}handleFetch(e){const{resolve:t,reject:n,fetchedAt:s}=e.meta,i=!e.endpoint.sideEffect,r=()=>{let r=e.endpoint(...e.args);return i||(r=(e=>e.then((e=>(t(e),e))).catch((e=>{throw n(e),e})))(r)),r=r.then((t=>{let n=this.getLastReset();return s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s}),t})).catch((t=>{const n=this.getLastReset();throw s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s,error:!0}),t})),r};return i?this.throttle(e.key,r,s).then((e=>t(e))).catch((e=>n(e))):r().catch((()=>{}))}handleSet(e){if(this.fetching.has(e.key)){const{reject:t,resolve:n}=this.fetching.get(e.key);e.error?t(e.response):n(e.response),this.clear(e.key)}}throttle(e,t,n){const s=this.getLastReset();let i=this.fetching.get(e);return i&&i.fetchedAt>s||(i=function(e){const t={fetchedAt:e};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}(n),this.fetching.set(e,i),this.idleCallback((()=>{t().catch((()=>null))}),{timeout:500})),i.promise}idleCallback(e,t){e()}}class xe{isOnline(){return void 0===navigator.onLine||navigator.onLine}addOnlineListener(e){addEventListener("online",e)}removeOnlineListener(e){removeEventListener("online",e)}addOfflineListener(e){addEventListener("offline",e)}removeOfflineListener(e){removeEventListener("offline",e)}}class be{isOnline(){return!0}addOnlineListener(){}removeOnlineListener(){}addOfflineListener(){}removeOfflineListener(){}}e.DefaultConnectionListener=void 0,"undefined"!=typeof navigator&&"function"==typeof addEventListener?e.DefaultConnectionListener=xe:e.DefaultConnectionListener=be;class ke{constructor(t,n,s){if(this.frequencyHistogram=new Map,this.offlineListener=()=>{this.cleanup(),this.connectionListener.addOnlineListener(this.onlineListener)},this.onlineListener=()=>{this.connectionListener.removeOnlineListener(this.onlineListener);const e=Date.now();this.startId=setTimeout((()=>{this.startId&&(delete this.startId,this.update(),this.run())}),Math.max(0,this.lastFetchTime()-e+this.frequency)),this.connectionListener.addOfflineListener(this.offlineListener)},void 0===t.endpoint.pollFrequency)throw new Error("frequency needed for polling subscription");this.endpoint=t.endpoint,this.frequency=t.endpoint.pollFrequency,this.args=t.args,this.key=t.key,this.frequencyHistogram.set(this.frequency,1),this.controller=n,this.connectionListener=s||new e.DefaultConnectionListener,this.connectionListener.isOnline()?this.onlineListener():this.offlineListener()}add(e){void 0!==e&&(this.frequencyHistogram.has(e)?this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)+1):(this.frequencyHistogram.set(e,1),e<this.frequency&&(this.frequency=e,this.run())))}remove(e){if(void 0===e)return!1;if(this.frequencyHistogram.has(e)&&(this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)-1),this.frequencyHistogram.get(e)<1)){if(this.frequencyHistogram.delete(e),0===this.frequencyHistogram.size)return this.cleanup(),!0;e<=this.frequency&&(this.frequency=Math.min(...this.frequencyHistogram.keys()),this.run())}return!1}cleanup(){this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId),this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.startId&&(clearTimeout(this.startId),delete this.startId),this.connectionListener.removeOnlineListener(this.onlineListener),this.connectionListener.removeOfflineListener(this.offlineListener)}update(){const e=this.endpoint,t=function(...t){return e.call(this,...t)};Object.assign(t,this.endpoint),t.dataExpiryLength=this.frequency/2,t.errorExpiryLength=this.frequency/10,t.errorPolicy=()=>"soft",t.key=()=>this.key,this.controller.fetch(t,...this.args).catch((()=>null))}run(){this.startId||(this.intervalId&&(this.lastIntervalId=this.intervalId),this.intervalId=setInterval((()=>{this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.intervalId&&this.update()}),this.frequency))}lastFetchTime(){var e,t;return null!=(e=null==(t=this.controller.getState().meta[this.key])?void 0:t.date)?e:0}}class Ie{constructor(e){this.subscriptions={},this.controller=new ye,this.middleware=e=>(this.controller=e,e=>t=>{switch(t.type){case V:try{this.handleSubscribe(t)}catch(e){console.error(e)}return Promise.resolve();case K:return this.handleUnsubscribe(t),Promise.resolve();default:return e(t)}}),this.Subscription=e}cleanup(){for(const e in this.subscriptions)this.subscriptions[e].cleanup()}handleSubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].add(n)}else this.subscriptions[t]=new this.Subscription(e,this.controller)}handleUnsubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].remove(n)&&delete this.subscriptions[t]}}}let Le={};class Ae{constructor(e,t){var n,s;this.started=!1,this.actions=[],this.maxBufferLength=100;const i=h({},Le,e);this.devtoolsName=null!=(n=i.name)?n:`Data Client: ${null==(s=globalThis.document)?void 0:s.title}`,this.devTools="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__.connect(i),null!=e&&e.maxAge&&(this.maxBufferLength=2*e.maxAge),t&&(this.skipLogging=t)}handleAction(e,t){this.started?this.devTools.send(e,t):(this.actions.length>this.maxBufferLength&&(this.actions=this.actions.slice(this.maxBufferLength/2)),this.actions.push([e,t]))}init(e){}cleanup(){}}Ae.prototype.middleware=()=>e=>t=>e(t);const Se=Symbol("DataClientState"),Me=Symbol("DataClientController"),Re=t.shallowRef(le);function Oe(){const e=t.inject(Me,null);return e||new ye}function Ce(){const e=t.inject(Se,null);return e||Re}async function Pe(e,...n){const s=Ce(),i=Oe(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=async()=>{if(!a.value)return;const t=o.value,n=t.expiryStatus===P.Invalid;Date.now()<=t.expiresAt&&!n||await i.fetch(e,...r.value)};return t.watch((()=>{const e=o.value;return[e.expiresAt,e.expiryStatus,s.value.lastReset,a.value]}),(()=>c())),t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>null==s?void 0:s()))}),{immediate:!0}),await c(),t.readonly(t.computed((()=>o.value.data)))}function je(e,...n){const s=Oe(),i=t.computed((()=>n.map((e=>t.unref(e))))),r=t.computed((()=>null===i.value[0]?"":e.key(...i.value)));t.watch(r,((t,n,a)=>{if(!r.value)return;const o=i.value;s.subscribe(e,...o),a((()=>{s.unsubscribe(e,...o)}))}),{immediate:!0})}const _e=Object.assign(Promise.resolve(),{resolved:!0});let De=(e={})=>{const{networkManager:t,subscriptionManager:n=ke}=e;return null===n?[Te(Ee,null!=t?t:{})]:[Te(Ee,null!=t?t:{}),Te(Ie,n)]};function Te(e,t){return t instanceof e?t:new e(t)}function qe(e={}){var n,s;const{Controller:i=ye,gcPolicy:r,app:a}=e,o=new i({gcPolicy:r}),c=null!=(n=e.managers)?n:De(),l=null!=(s=e.initialState)?s:le,u=function(e,t,n){return()=>(e.forEach((e=>{null==e.init||e.init(n)})),t.gcPolicy.init(t),()=>{e.forEach((e=>{e.cleanup()})),t.gcPolicy.cleanup()})}(c,o,l),h=function(e,t){return e.map(((e,n)=>(e.middleware||(e.middleware=null==e.getMiddleware?void 0:e.getMiddleware()),s=>(0===n&&t.bindMiddleware(s),e.middleware(t)))))}(c,o),d=ce(o),p=t.shallowRef(l),f=t.shallowRef(x(l));let y=null;const g=()=>p.value,v=h.map((e=>e({getState:g,dispatch:e=>m(e)}))),m=(w=v,e=>w.reduceRight(((e,t)=>t(e)),e))((async e=>{const t=new Promise((e=>{y=e}));return await(async e=>{const t=d(p.value,e);if(p.value=t,f.value=x(t),y){const e=y;y=null,e()}})(e),t}));var w;let E;o.bindMiddleware({getState:g,dispatch:e=>m(e)});return a?(a.provide(Se,f),a.provide(Me,o)):(t.provide(Se,f),t.provide(Me,o)),{controller:o,stateRef:f,start:()=>{E=u()},stop:()=>{E&&E()}};function x(e){return e.optimistic.reduce(d,e)}}const Ne={install(e,t={}){const n=qe(h({},t,{app:e}));return e.config.globalProperties.$dataClient=n.controller,n.start(),e.onUnmount((()=>{n.stop()})),n}};e.Controller=ye,e.DataClientPlugin=Ne,e.DevToolsManager=Ae,e.ExpiryStatus=P,e.LogoutManager=class{constructor({handleLogout:e,shouldLogout:t}={}){this.middleware=e=>t=>async n=>{await t(n),n.type===T&&n.error&&this.shouldLogout(n.response)&&this.handleLogout(e)},e&&(this.handleLogout=e),t&&(this.shouldLogout=t)}cleanup(){}shouldLogout(e){return 401===e.status}handleLogout(e){e.resetEntireStore()}},e.NetworkManager=Ee,e.PollingSubscription=ke,e.SubscriptionManager=Ie,e.actionTypes=ne,e.createDataClient=qe,e.getDefaultManagers=De,e.useCache=function(e,...n){const s=Ce(),i=Oe(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=t.computed((()=>o.value.expiryStatus===P.Invalid)),l=t.computed((()=>(Date.now()>o.value.expiresAt||c.value)&&a.value)),u=t.computed((()=>o.value.expiryStatus!==P.Valid&&l.value));return t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>s()))}),{immediate:!0}),t.computed((()=>{if(u.value){if(!e.schema)return;return i.getResponseMeta(e,...r.value,h({},s.value,{entities:{}})).data}return o.value.data}))},e.useController=Oe,e.useDLE=function(e,...n){const s=Ce(),i=Oe(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=t.computed((()=>o.value.expiryStatus===P.Invalid)),l=t.computed((()=>!(!(Date.now()>o.value.expiresAt||c.value)||!a.value))),u=t.computed((()=>!(o.value.expiryStatus===P.Valid||!l.value)));t.watch((()=>{const e=o.value;return[e.expiresAt,e.expiryStatus,s.value.lastReset,a.value]}),(async()=>{if(!a.value)return;const t=o.value,n=c.value;Date.now()<=t.expiresAt&&!n||await i.fetch(e,...r.value).catch((()=>{}))}),{immediate:!0}),t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>s()))}),{immediate:!0});const d=t.computed((()=>{if(u.value){if(!e.schema)return;return i.getResponseMeta(e,...r.value,h({},s.value,{entities:{}})).data}return o.value.data})),p=t.computed((()=>i.getError(e,...r.value,s.value)));return t.markRaw({data:d,loading:u,error:p})},e.useDebounce=function(e,n,s=!0){const i=t.ref("object"==typeof e&&null!==e&&"value"in e?e.value:e),r=t.ref(!1);let a=null;const o=()=>{null!==a&&(clearTimeout(a),a=null)};return t.watch([()=>"object"==typeof e&&null!==e&&"value"in e?e.value:e,()=>"object"==typeof s&&null!==s&&"value"in s?s.value:s,()=>n],(([e,t])=>{o(),t?(r.value=!0,a=setTimeout((()=>{i.value=e,r.value=!1,a=null}),n)):r.value=!1}),{immediate:!1}),t.onUnmounted((()=>{o()})),[i,r]},e.useFetch=function(e,...n){const s=Ce(),i=Oe(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>null!==r.value[0]?e.key(...r.value):"")),o=t.computed((()=>i.getResponseMeta(e,...r.value,s.value))),c=t.ref(void 0);let l="";const u=()=>{const t=a.value;if(!t)return c.value=void 0,void(l="");const n=o.value,s=n.expiryStatus===P.Invalid;Date.now()>n.expiresAt||s?(c.value=function(e){const t=e;t.resolved=!1;const n=()=>{t.resolved=!0};return t.then(n,n),t}(i.fetch(e,...r.value)),l=t):c.value&&l===t||(c.value=_e,l=t)};return u(),t.watch((()=>{const e=o.value;return[e.expiresAt,e.expiryStatus,s.value.lastReset,a.value]}),(()=>{u()})),c},e.useLive=async function(e,...t){return je(e,...t),Pe(e,...t)},e.useLoading=function(e){const n=t.ref(!1),s=t.ref(void 0),i=t.ref(!0);return t.onUnmounted((()=>{i.value=!1})),[async(...t)=>{let r;n.value=!0,s.value=void 0;try{r=await e(...t)}catch(e){s.value=e}finally{i.value&&(n.value=!1)}return r},n,s]},e.useQuery=function(e,...n){const s=Ce(),i=Oe(),r=t.computed((()=>n.map((e=>t.unref(e))))),a=t.computed((()=>i.getQueryMeta(e,...r.value,s.value)));return t.watch((()=>a.value.data),((e,t,n)=>{const s=a.value.countRef();n((()=>s()))}),{immediate:!0}),t.computed((()=>a.value.data))},e.useSubscription=je,e.useSuspense=Pe}));
|
|
@@ -4,6 +4,14 @@ import type { MaybeRefsOrGetters, MaybeRefsOrGettersNullable } from '../types.js
|
|
|
4
4
|
* Fetch an Endpoint if it is not in cache or stale.
|
|
5
5
|
* @see https://dataclient.io/docs/api/useFetch
|
|
6
6
|
*/
|
|
7
|
-
export default function useFetch<E extends EndpointInterface<FetchFunction, Schema | undefined, undefined | false>>(endpoint: E, ...args: MaybeRefsOrGetters<Parameters<E>>): E['schema'] extends undefined | null ? ReturnType<E>
|
|
8
|
-
|
|
7
|
+
export default function useFetch<E extends EndpointInterface<FetchFunction, Schema | undefined, undefined | false>>(endpoint: E, ...args: MaybeRefsOrGetters<Parameters<E>>): E['schema'] extends undefined | null ? ReturnType<E> & {
|
|
8
|
+
resolved: boolean;
|
|
9
|
+
} : Promise<Denormalize<E['schema']>> & {
|
|
10
|
+
resolved: boolean;
|
|
11
|
+
};
|
|
12
|
+
export default function useFetch<E extends EndpointInterface<FetchFunction, Schema | undefined, undefined | false>>(endpoint: E, ...args: MaybeRefsOrGettersNullable<Parameters<E>> | readonly [null]): E['schema'] extends undefined | null ? (ReturnType<E> & {
|
|
13
|
+
resolved: boolean;
|
|
14
|
+
}) | undefined : (Promise<DenormalizeNullable<E['schema']>> & {
|
|
15
|
+
resolved: boolean;
|
|
16
|
+
}) | undefined;
|
|
9
17
|
//# sourceMappingURL=useFetch.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useFetch.d.ts","sourceRoot":"","sources":["../../src/consumers/useFetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,WAAW,EACX,MAAM,EACN,aAAa,EACb,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAI3B,OAAO,KAAK,EACV,kBAAkB,EAClB,0BAA0B,EAC3B,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"useFetch.d.ts","sourceRoot":"","sources":["../../src/consumers/useFetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,WAAW,EACX,MAAM,EACN,aAAa,EACb,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAI3B,OAAO,KAAK,EACV,kBAAkB,EAClB,0BAA0B,EAC3B,MAAM,aAAa,CAAC;AAkBrB;;;GAGG;AACH,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,CAAC,SAAS,iBAAiB,CACzB,aAAa,EACb,MAAM,GAAG,SAAS,EAClB,SAAS,GAAG,KAAK,CAClB,EAED,QAAQ,EAAE,CAAC,EACX,GAAG,IAAI,EAAE,kBAAkB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GACzC,CAAC,CAAC,QAAQ,CAAC,SAAS,SAAS,GAAG,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,EAAE,OAAO,CAAA;CAAE,GAC7E,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAC;AAE5D,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,CAAC,SAAS,iBAAiB,CACzB,aAAa,EACb,MAAM,GAAG,SAAS,EAClB,SAAS,GAAG,KAAK,CAClB,EAED,QAAQ,EAAE,CAAC,EACX,GAAG,IAAI,EAAE,0BAA0B,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,GACnE,CAAC,CAAC,QAAQ,CAAC,SAAS,SAAS,GAAG,IAAI,GACrC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAC,GAAG,SAAS,GACjD,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAC,GACnE,SAAS,CAAC"}
|
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
import { ExpiryStatus } from '@data-client/core';
|
|
2
2
|
import { computed, watch, ref, unref } from 'vue';
|
|
3
3
|
import { useController, injectState } from '../context.js';
|
|
4
|
+
const RESOLVED = Object.assign(Promise.resolve(), {
|
|
5
|
+
resolved: true
|
|
6
|
+
});
|
|
7
|
+
function trackPromise(promise) {
|
|
8
|
+
const p = promise;
|
|
9
|
+
p.resolved = false;
|
|
10
|
+
const r = () => {
|
|
11
|
+
p.resolved = true;
|
|
12
|
+
};
|
|
13
|
+
p.then(r, r);
|
|
14
|
+
return p;
|
|
15
|
+
}
|
|
4
16
|
|
|
5
17
|
/**
|
|
6
18
|
* Fetch an Endpoint if it is not in cache or stale.
|
|
@@ -22,12 +34,23 @@ export default function useFetch(endpoint, ...args) {
|
|
|
22
34
|
return controller.getResponseMeta(endpoint, ...resolvedArgs.value, stateRef.value);
|
|
23
35
|
});
|
|
24
36
|
const lastPromise = ref(undefined);
|
|
37
|
+
let lastKey = '';
|
|
25
38
|
const maybeFetch = () => {
|
|
26
|
-
|
|
39
|
+
const key = argsKey.value;
|
|
40
|
+
if (!key) {
|
|
41
|
+
lastPromise.value = undefined;
|
|
42
|
+
lastKey = '';
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
27
45
|
const meta = responseMeta.value;
|
|
28
46
|
const forceFetch = meta.expiryStatus === ExpiryStatus.Invalid;
|
|
29
|
-
if (Date.now()
|
|
30
|
-
|
|
47
|
+
if (Date.now() > meta.expiresAt || forceFetch) {
|
|
48
|
+
lastPromise.value = trackPromise(controller.fetch(endpoint, ...resolvedArgs.value));
|
|
49
|
+
lastKey = key;
|
|
50
|
+
} else if (!lastPromise.value || lastKey !== key) {
|
|
51
|
+
lastPromise.value = RESOLVED;
|
|
52
|
+
lastKey = key;
|
|
53
|
+
}
|
|
31
54
|
};
|
|
32
55
|
|
|
33
56
|
// Trigger on initial call
|
|
@@ -42,4 +65,4 @@ export default function useFetch(endpoint, ...args) {
|
|
|
42
65
|
});
|
|
43
66
|
return lastPromise;
|
|
44
67
|
}
|
|
45
|
-
//# sourceMappingURL=data:application/json;charset=utf-8;base64,
|
|
68
|
+
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFeHBpcnlTdGF0dXMiLCJjb21wdXRlZCIsIndhdGNoIiwicmVmIiwidW5yZWYiLCJ1c2VDb250cm9sbGVyIiwiaW5qZWN0U3RhdGUiLCJSRVNPTFZFRCIsIk9iamVjdCIsImFzc2lnbiIsIlByb21pc2UiLCJyZXNvbHZlIiwicmVzb2x2ZWQiLCJ0cmFja1Byb21pc2UiLCJwcm9taXNlIiwicCIsInIiLCJ0aGVuIiwidXNlRmV0Y2giLCJlbmRwb2ludCIsImFyZ3MiLCJzdGF0ZVJlZiIsImNvbnRyb2xsZXIiLCJyZXNvbHZlZEFyZ3MiLCJtYXAiLCJhIiwiYXJnc0tleSIsInZhbHVlIiwia2V5IiwicmVzcG9uc2VNZXRhIiwiZ2V0UmVzcG9uc2VNZXRhIiwibGFzdFByb21pc2UiLCJ1bmRlZmluZWQiLCJsYXN0S2V5IiwibWF5YmVGZXRjaCIsIm1ldGEiLCJmb3JjZUZldGNoIiwiZXh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0MsS0FBSyxDQUNkO0VBQ0gsQ0FBQyxFQUNELE1BQU07SUFDSk8sVUFBVSxDQUFDLENBQUM7RUFDZCxDQUNGLENBQUM7RUFFRCxPQUFPSCxXQUFXO0FBQ3BCIiwiaWdub3JlTGlzdCI6W119
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@data-client/vue",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.1",
|
|
4
4
|
"description": "Async State Management without the Management. REST, GraphQL, SSE, Websockets, Fetch",
|
|
5
5
|
"homepage": "https://dataclient.io",
|
|
6
6
|
"repository": {
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
"license": "Apache-2.0",
|
|
95
95
|
"dependencies": {
|
|
96
96
|
"@babel/runtime": "^7.20.0",
|
|
97
|
-
"@data-client/core": "^0.
|
|
97
|
+
"@data-client/core": "^0.16.7"
|
|
98
98
|
},
|
|
99
99
|
"peerDependencies": {
|
|
100
100
|
"@types/vue": "^3.0.0",
|
|
@@ -111,9 +111,8 @@
|
|
|
111
111
|
},
|
|
112
112
|
"devDependencies": {
|
|
113
113
|
"@anansi/browserslist-config": "^1.4.2",
|
|
114
|
-
"@data-client/rest": "0.
|
|
114
|
+
"@data-client/rest": "0.16.6",
|
|
115
115
|
"@jest/globals": "^30.0.0",
|
|
116
|
-
"@js-temporal/polyfill": "^0.5.0",
|
|
117
116
|
"@types/jest": "30.0.0",
|
|
118
117
|
"@types/node": "^24.0.0",
|
|
119
118
|
"@vue/test-utils": "^2.4.0",
|
|
@@ -121,6 +120,7 @@
|
|
|
121
120
|
"jest-mock": "^30.0.0",
|
|
122
121
|
"nock": "13.3.1",
|
|
123
122
|
"rollup-plugins": "1.0.0",
|
|
123
|
+
"temporal-polyfill": "^0.3.0",
|
|
124
124
|
"vue": "^3.4.0"
|
|
125
125
|
}
|
|
126
126
|
}
|
|
@@ -9,6 +9,14 @@ import { renderDataCompose, mountDataClient } from '../test';
|
|
|
9
9
|
const GC_INTERVAL = 100; // Use short interval for faster tests
|
|
10
10
|
|
|
11
11
|
describe('Integration Garbage Collection Web (Vue)', () => {
|
|
12
|
+
let infoSpy: jest.SpyInstance;
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
15
|
+
});
|
|
16
|
+
afterEach(() => {
|
|
17
|
+
infoSpy.mockRestore();
|
|
18
|
+
});
|
|
19
|
+
|
|
12
20
|
it('should initialize with GCPolicy', () => {
|
|
13
21
|
const gcPolicy = new GCPolicy({
|
|
14
22
|
intervalMS: GC_INTERVAL,
|
|
@@ -21,6 +21,14 @@ const payload2 = {
|
|
|
21
21
|
};
|
|
22
22
|
|
|
23
23
|
describe('vue useCache()', () => {
|
|
24
|
+
let infoSpy: jest.SpyInstance;
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
27
|
+
});
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
infoSpy.mockRestore();
|
|
30
|
+
});
|
|
31
|
+
|
|
24
32
|
async function flushUntil(
|
|
25
33
|
wrapper: any,
|
|
26
34
|
predicate: () => boolean,
|
|
@@ -55,7 +55,9 @@ const nested = [
|
|
|
55
55
|
];
|
|
56
56
|
|
|
57
57
|
describe('vue useDLE()', () => {
|
|
58
|
+
let infoSpy: jest.SpyInstance;
|
|
58
59
|
beforeAll(() => {
|
|
60
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
59
61
|
nock(/.*/)
|
|
60
62
|
.persist()
|
|
61
63
|
.defaultReplyHeaders({
|
|
@@ -87,6 +89,7 @@ describe('vue useDLE()', () => {
|
|
|
87
89
|
});
|
|
88
90
|
|
|
89
91
|
afterAll(() => {
|
|
92
|
+
infoSpy.mockRestore();
|
|
90
93
|
nock.cleanAll();
|
|
91
94
|
});
|
|
92
95
|
|
|
@@ -295,6 +295,96 @@ describe('vue useFetch()', () => {
|
|
|
295
295
|
global.Date.now = originalDateNow;
|
|
296
296
|
});
|
|
297
297
|
|
|
298
|
+
it('should return a promise with resolved=false when fetching', async () => {
|
|
299
|
+
const fetchMock = jest.fn(() => payload);
|
|
300
|
+
mynock.get(`/article-cooler/${payload.id}`).reply(200, fetchMock);
|
|
301
|
+
|
|
302
|
+
let promiseRef: any;
|
|
303
|
+
const Comp = defineComponent({
|
|
304
|
+
name: 'FetchTesterResolved',
|
|
305
|
+
setup() {
|
|
306
|
+
const p = useFetch(CoolerArticleResource.get, { id: payload.id });
|
|
307
|
+
promiseRef = p;
|
|
308
|
+
return () => h('div');
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
mount(TestWrapper, {
|
|
313
|
+
slots: { default: () => h(Comp) },
|
|
314
|
+
global: {
|
|
315
|
+
plugins: [[DataClientPlugin]],
|
|
316
|
+
},
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
expect(promiseRef.value).toBeInstanceOf(Promise);
|
|
320
|
+
expect(promiseRef.value.resolved).toBe(false);
|
|
321
|
+
|
|
322
|
+
await flushUntil({} as any, () => fetchMock.mock.calls.length > 0);
|
|
323
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it('should return resolved promise when data is fresh', async () => {
|
|
327
|
+
const fetchMock = jest.fn(() => payload);
|
|
328
|
+
mynock.get(`/article-cooler/${payload.id}`).reply(200, fetchMock);
|
|
329
|
+
|
|
330
|
+
// Create wrapper with initial cached data
|
|
331
|
+
const WrapperWithFixture = defineComponent({
|
|
332
|
+
name: 'TestWrapperWithFixture',
|
|
333
|
+
setup(_props, { slots, expose }) {
|
|
334
|
+
const controller = inject(ControllerKey)!;
|
|
335
|
+
controller.setResponse(
|
|
336
|
+
CoolerArticleResource.get,
|
|
337
|
+
{ id: payload.id },
|
|
338
|
+
payload,
|
|
339
|
+
);
|
|
340
|
+
expose({ controller });
|
|
341
|
+
return () => (slots.default ? slots.default() : h('div'));
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
let promiseRef: any;
|
|
346
|
+
const Comp = defineComponent({
|
|
347
|
+
name: 'FetchTesterFresh',
|
|
348
|
+
setup() {
|
|
349
|
+
const p = useFetch(CoolerArticleResource.get, { id: payload.id });
|
|
350
|
+
promiseRef = p;
|
|
351
|
+
return () => h('div');
|
|
352
|
+
},
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
mount(WrapperWithFixture, {
|
|
356
|
+
slots: { default: () => h(Comp) },
|
|
357
|
+
global: {
|
|
358
|
+
plugins: [[DataClientPlugin]],
|
|
359
|
+
},
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
expect(promiseRef.value).toBeInstanceOf(Promise);
|
|
363
|
+
expect(promiseRef.value.resolved).toBe(true);
|
|
364
|
+
expect(fetchMock).toHaveBeenCalledTimes(0);
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
it('should return undefined with null params', () => {
|
|
368
|
+
let promiseRef: any;
|
|
369
|
+
const Comp = defineComponent({
|
|
370
|
+
name: 'FetchTesterNull',
|
|
371
|
+
setup() {
|
|
372
|
+
const p = useFetch(CoolerArticleResource.get as any, null);
|
|
373
|
+
promiseRef = p;
|
|
374
|
+
return () => h('div');
|
|
375
|
+
},
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
mount(TestWrapper, {
|
|
379
|
+
slots: { default: () => h(Comp) },
|
|
380
|
+
global: {
|
|
381
|
+
plugins: [[DataClientPlugin]],
|
|
382
|
+
},
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
expect(promiseRef.value).toBeUndefined();
|
|
386
|
+
});
|
|
387
|
+
|
|
298
388
|
it('should re-fetch when props change', async () => {
|
|
299
389
|
const fetchMock1 = jest.fn(() => payload);
|
|
300
390
|
const fetchMock2 = jest.fn(() => payload2);
|
|
@@ -19,6 +19,14 @@ const payload = {
|
|
|
19
19
|
let currentPollingPayload: typeof payload = { ...payload };
|
|
20
20
|
|
|
21
21
|
describe('vue useLive()', () => {
|
|
22
|
+
let infoSpy: jest.SpyInstance;
|
|
23
|
+
beforeEach(() => {
|
|
24
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
25
|
+
});
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
infoSpy.mockRestore();
|
|
28
|
+
});
|
|
29
|
+
|
|
22
30
|
async function flushUntil(
|
|
23
31
|
wrapper: any,
|
|
24
32
|
predicate: () => boolean,
|
|
@@ -48,6 +48,14 @@ const nested = [
|
|
|
48
48
|
];
|
|
49
49
|
|
|
50
50
|
describe('vue useQuery()', () => {
|
|
51
|
+
let infoSpy: jest.SpyInstance;
|
|
52
|
+
beforeEach(() => {
|
|
53
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
54
|
+
});
|
|
55
|
+
afterEach(() => {
|
|
56
|
+
infoSpy.mockRestore();
|
|
57
|
+
});
|
|
58
|
+
|
|
51
59
|
it('should be undefined with empty state', async () => {
|
|
52
60
|
const { result } = await renderDataCompose(() => {
|
|
53
61
|
return useQuery(ArticleWithSlug, { id: payloadSlug.id });
|
|
@@ -28,7 +28,12 @@ describe('vue useSubscription()', () => {
|
|
|
28
28
|
tags: ['a', 'best', 'react'],
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
let infoSpy: jest.SpyInstance;
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
34
|
+
});
|
|
31
35
|
afterEach(() => {
|
|
36
|
+
infoSpy.mockRestore();
|
|
32
37
|
jest.useRealTimers();
|
|
33
38
|
});
|
|
34
39
|
|
|
@@ -25,6 +25,14 @@ const payload2 = {
|
|
|
25
25
|
};
|
|
26
26
|
|
|
27
27
|
describe('vue useSuspense()', () => {
|
|
28
|
+
let infoSpy: jest.SpyInstance;
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
31
|
+
});
|
|
32
|
+
afterEach(() => {
|
|
33
|
+
infoSpy.mockRestore();
|
|
34
|
+
});
|
|
35
|
+
|
|
28
36
|
async function flushUntil(
|
|
29
37
|
wrapper: any,
|
|
30
38
|
predicate: () => boolean,
|
|
@@ -14,6 +14,22 @@ import type {
|
|
|
14
14
|
MaybeRefsOrGettersNullable,
|
|
15
15
|
} from '../types.js';
|
|
16
16
|
|
|
17
|
+
type FetchPromise = Promise<any> & { resolved: boolean };
|
|
18
|
+
|
|
19
|
+
const RESOLVED = Object.assign(Promise.resolve(), {
|
|
20
|
+
resolved: true,
|
|
21
|
+
}) as FetchPromise;
|
|
22
|
+
|
|
23
|
+
function trackPromise(promise: Promise<any>): FetchPromise {
|
|
24
|
+
const p = promise as FetchPromise;
|
|
25
|
+
p.resolved = false;
|
|
26
|
+
const r = () => {
|
|
27
|
+
p.resolved = true;
|
|
28
|
+
};
|
|
29
|
+
p.then(r, r);
|
|
30
|
+
return p;
|
|
31
|
+
}
|
|
32
|
+
|
|
17
33
|
/**
|
|
18
34
|
* Fetch an Endpoint if it is not in cache or stale.
|
|
19
35
|
* @see https://dataclient.io/docs/api/useFetch
|
|
@@ -27,8 +43,8 @@ export default function useFetch<
|
|
|
27
43
|
>(
|
|
28
44
|
endpoint: E,
|
|
29
45
|
...args: MaybeRefsOrGetters<Parameters<E>>
|
|
30
|
-
): E['schema'] extends undefined | null ? ReturnType<E>
|
|
31
|
-
: Promise<Denormalize<E['schema']
|
|
46
|
+
): E['schema'] extends undefined | null ? ReturnType<E> & { resolved: boolean }
|
|
47
|
+
: Promise<Denormalize<E['schema']>> & { resolved: boolean };
|
|
32
48
|
|
|
33
49
|
export default function useFetch<
|
|
34
50
|
E extends EndpointInterface<
|
|
@@ -39,8 +55,10 @@ export default function useFetch<
|
|
|
39
55
|
>(
|
|
40
56
|
endpoint: E,
|
|
41
57
|
...args: MaybeRefsOrGettersNullable<Parameters<E>> | readonly [null]
|
|
42
|
-
): E['schema'] extends undefined | null ?
|
|
43
|
-
|
|
58
|
+
): E['schema'] extends undefined | null ?
|
|
59
|
+
(ReturnType<E> & { resolved: boolean }) | undefined
|
|
60
|
+
: | (Promise<DenormalizeNullable<E['schema']>> & { resolved: boolean })
|
|
61
|
+
| undefined;
|
|
44
62
|
|
|
45
63
|
export default function useFetch(endpoint: any, ...args: any[]): any {
|
|
46
64
|
const stateRef = injectState();
|
|
@@ -63,14 +81,28 @@ export default function useFetch(endpoint: any, ...args: any[]): any {
|
|
|
63
81
|
);
|
|
64
82
|
});
|
|
65
83
|
|
|
66
|
-
const lastPromise = ref<
|
|
84
|
+
const lastPromise = ref<FetchPromise | undefined>(undefined);
|
|
85
|
+
let lastKey = '';
|
|
67
86
|
|
|
68
87
|
const maybeFetch = () => {
|
|
69
|
-
|
|
88
|
+
const key = argsKey.value;
|
|
89
|
+
if (!key) {
|
|
90
|
+
lastPromise.value = undefined;
|
|
91
|
+
lastKey = '';
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
70
94
|
const meta = responseMeta.value;
|
|
71
95
|
const forceFetch = meta.expiryStatus === ExpiryStatus.Invalid;
|
|
72
|
-
|
|
73
|
-
|
|
96
|
+
|
|
97
|
+
if (Date.now() > meta.expiresAt || forceFetch) {
|
|
98
|
+
lastPromise.value = trackPromise(
|
|
99
|
+
controller.fetch(endpoint, ...resolvedArgs.value),
|
|
100
|
+
);
|
|
101
|
+
lastKey = key;
|
|
102
|
+
} else if (!lastPromise.value || lastKey !== key) {
|
|
103
|
+
lastPromise.value = RESOLVED;
|
|
104
|
+
lastKey = key;
|
|
105
|
+
}
|
|
74
106
|
};
|
|
75
107
|
|
|
76
108
|
// Trigger on initial call
|
|
@@ -5,7 +5,14 @@ import {
|
|
|
5
5
|
SubscriptionManager,
|
|
6
6
|
} from '@data-client/core';
|
|
7
7
|
import type { State } from '@data-client/core';
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
describe,
|
|
10
|
+
it,
|
|
11
|
+
expect,
|
|
12
|
+
jest,
|
|
13
|
+
beforeEach,
|
|
14
|
+
afterEach,
|
|
15
|
+
} from '@jest/globals';
|
|
9
16
|
import { mount } from '@vue/test-utils';
|
|
10
17
|
import { defineComponent, h, inject } from 'vue';
|
|
11
18
|
|
|
@@ -17,6 +24,10 @@ describe('DataClientPlugin', () => {
|
|
|
17
24
|
jest.clearAllMocks();
|
|
18
25
|
});
|
|
19
26
|
|
|
27
|
+
afterEach(() => {
|
|
28
|
+
jest.restoreAllMocks();
|
|
29
|
+
});
|
|
30
|
+
|
|
20
31
|
it('should install plugin with default options', () => {
|
|
21
32
|
const TestComponent = defineComponent({
|
|
22
33
|
name: 'TestComponent',
|
|
@@ -198,7 +209,6 @@ describe('DataClientPlugin', () => {
|
|
|
198
209
|
expect(startSpy).toHaveBeenCalledTimes(1);
|
|
199
210
|
|
|
200
211
|
wrapper.unmount();
|
|
201
|
-
jest.restoreAllMocks();
|
|
202
212
|
});
|
|
203
213
|
|
|
204
214
|
it('should call stop ONCE on app unmount (plugin lifecycle)', () => {
|
|
@@ -241,8 +251,6 @@ describe('DataClientPlugin', () => {
|
|
|
241
251
|
|
|
242
252
|
// Stop should be called exactly once when app unmounts
|
|
243
253
|
expect(stopSpy).toHaveBeenCalledTimes(1);
|
|
244
|
-
|
|
245
|
-
jest.restoreAllMocks();
|
|
246
254
|
});
|
|
247
255
|
|
|
248
256
|
it('should work with multiple components', () => {
|
|
@@ -348,7 +356,6 @@ describe('DataClientPlugin', () => {
|
|
|
348
356
|
expect(startSpy).toHaveBeenCalledTimes(1);
|
|
349
357
|
|
|
350
358
|
wrapper.unmount();
|
|
351
|
-
jest.restoreAllMocks();
|
|
352
359
|
});
|
|
353
360
|
|
|
354
361
|
it('should NOT call stop for individual component unmount - only on app unmount', () => {
|
|
@@ -420,8 +427,6 @@ describe('DataClientPlugin', () => {
|
|
|
420
427
|
// Stop should be called exactly ONCE when app unmounts
|
|
421
428
|
// (not once per component - only once for the app)
|
|
422
429
|
expect(stopSpy).toHaveBeenCalledTimes(1);
|
|
423
|
-
|
|
424
|
-
jest.restoreAllMocks();
|
|
425
430
|
});
|
|
426
431
|
|
|
427
432
|
it('should maintain same controller/state instance across all components', () => {
|
|
@@ -24,11 +24,14 @@ import { MockPlugin } from '../../test/MockPlugin';
|
|
|
24
24
|
import { DataClientPlugin } from '../DataClientPlugin';
|
|
25
25
|
|
|
26
26
|
describe('MockPlugin', () => {
|
|
27
|
+
let warnSpy: jest.Spied<typeof console.warn>;
|
|
27
28
|
beforeEach(() => {
|
|
28
29
|
jest.clearAllMocks();
|
|
30
|
+
warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
|
|
29
31
|
});
|
|
30
32
|
|
|
31
33
|
afterEach(() => {
|
|
34
|
+
warnSpy.mockRestore();
|
|
32
35
|
jest.restoreAllMocks();
|
|
33
36
|
});
|
|
34
37
|
|
|
@@ -30,12 +30,16 @@ describe('createDataClient', () => {
|
|
|
30
30
|
expect(provider.stateRef).toBeDefined();
|
|
31
31
|
expect(typeof provider.start).toBe('function');
|
|
32
32
|
expect(typeof provider.stop).toBe('function');
|
|
33
|
+
|
|
34
|
+
provider.stop();
|
|
33
35
|
});
|
|
34
36
|
|
|
35
37
|
it('should create data client with custom Controller', () => {
|
|
36
38
|
const provider = createDataClient({ Controller: Controller });
|
|
37
39
|
|
|
38
40
|
expect(provider.controller).toBeInstanceOf(Controller);
|
|
41
|
+
|
|
42
|
+
provider.stop();
|
|
39
43
|
});
|
|
40
44
|
|
|
41
45
|
it('should create data client with custom managers', () => {
|
|
@@ -49,6 +53,8 @@ describe('createDataClient', () => {
|
|
|
49
53
|
|
|
50
54
|
expect(provider.controller).toBeInstanceOf(Controller);
|
|
51
55
|
expect(provider.stateRef).toBeDefined();
|
|
56
|
+
|
|
57
|
+
provider.stop();
|
|
52
58
|
});
|
|
53
59
|
|
|
54
60
|
it('should create data client with custom initialState', () => {
|
|
@@ -65,6 +71,8 @@ describe('createDataClient', () => {
|
|
|
65
71
|
const provider = createDataClient({ initialState: customState });
|
|
66
72
|
|
|
67
73
|
expect(provider.stateRef.value.lastReset).toBe(12345);
|
|
74
|
+
|
|
75
|
+
provider.stop();
|
|
68
76
|
});
|
|
69
77
|
|
|
70
78
|
it('should handle actions through middleware chain', async () => {
|
|
@@ -190,6 +198,8 @@ describe('createDataClient', () => {
|
|
|
190
198
|
ControllerKey,
|
|
191
199
|
provider.controller,
|
|
192
200
|
);
|
|
201
|
+
|
|
202
|
+
provider.stop();
|
|
193
203
|
});
|
|
194
204
|
|
|
195
205
|
it('should accept custom gcPolicy', () => {
|
|
@@ -200,6 +210,8 @@ describe('createDataClient', () => {
|
|
|
200
210
|
const provider = createDataClient({ gcPolicy: customGcPolicy });
|
|
201
211
|
|
|
202
212
|
expect(provider.controller).toBeInstanceOf(Controller);
|
|
213
|
+
|
|
214
|
+
provider.stop();
|
|
203
215
|
});
|
|
204
216
|
|
|
205
217
|
it('should maintain stable controller and manager instances', () => {
|
|
@@ -212,6 +224,9 @@ describe('createDataClient', () => {
|
|
|
212
224
|
// Same provider should maintain stable controller
|
|
213
225
|
const controller1 = provider1.controller;
|
|
214
226
|
expect(provider1.controller).toBe(controller1);
|
|
227
|
+
|
|
228
|
+
provider1.stop();
|
|
229
|
+
provider2.stop();
|
|
215
230
|
});
|
|
216
231
|
|
|
217
232
|
it('should handle sequential dispatches correctly', async () => {
|
|
@@ -4,6 +4,14 @@ import { CoolerArticleResource } from '../../../../../__tests__/new';
|
|
|
4
4
|
import { mountDataClient } from '../mountDataClient';
|
|
5
5
|
|
|
6
6
|
describe('mountDataClient', () => {
|
|
7
|
+
let infoSpy: jest.SpyInstance;
|
|
8
|
+
beforeEach(() => {
|
|
9
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
10
|
+
});
|
|
11
|
+
afterEach(() => {
|
|
12
|
+
infoSpy.mockRestore();
|
|
13
|
+
});
|
|
14
|
+
|
|
7
15
|
const payload = {
|
|
8
16
|
id: 5,
|
|
9
17
|
title: 'hi ho',
|
|
@@ -4,6 +4,14 @@ import { CoolerArticleResource } from '../../../../../__tests__/new';
|
|
|
4
4
|
import { renderDataCompose } from '../renderDataCompose';
|
|
5
5
|
|
|
6
6
|
describe('renderDataCompose', () => {
|
|
7
|
+
let infoSpy: jest.SpyInstance;
|
|
8
|
+
beforeEach(() => {
|
|
9
|
+
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
|
10
|
+
});
|
|
11
|
+
afterEach(() => {
|
|
12
|
+
infoSpy.mockRestore();
|
|
13
|
+
});
|
|
14
|
+
|
|
7
15
|
const payload = {
|
|
8
16
|
id: 5,
|
|
9
17
|
title: 'hi ho',
|