tsdf 8.0.0-beta.1 → 8.0.0-beta.10

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.
Files changed (57) hide show
  1. package/dist/main.cjs +1846 -0
  2. package/dist/main.d.ts +291 -0
  3. package/dist/main.js +1811 -0
  4. package/package.json +6 -2
  5. package/.eslintignore +0 -3
  6. package/.eslintrc.cjs +0 -119
  7. package/.gitattributes +0 -22
  8. package/.prettierrc +0 -6
  9. package/.vscode/settings.json +0 -3
  10. package/.vscode/tasks.json +0 -35
  11. package/fetch-orquestrator-scenarios.excalidraw +0 -10115
  12. package/scripts/check-if-is-sync.sh +0 -6
  13. package/src/collectionFetchOrquestrator.ts +0 -23
  14. package/src/collectionStore.ts +0 -608
  15. package/src/documentStore.ts +0 -272
  16. package/src/fetchOrquestrator.ts +0 -335
  17. package/src/listQueryStore.ts +0 -1190
  18. package/src/main.ts +0 -22
  19. package/src/storeShared.ts +0 -5
  20. package/src/useEnsureIsLoaded.ts +0 -50
  21. package/src/utils/filterAndMap.ts +0 -20
  22. package/src/utils/getCacheId.ts +0 -19
  23. package/src/utils/hooks.ts +0 -110
  24. package/src/utils/isObject.ts +0 -3
  25. package/src/utils/math.ts +0 -7
  26. package/src/utils/serializableClone.ts +0 -3
  27. package/src/utils/useLatestValue.ts +0 -16
  28. package/test/__snapshots__/listQueryStore.test.ts.snap +0 -146
  29. package/test/__snapshots__/listQueryStoreHooks.test.ts.snap +0 -9
  30. package/test/collectionStore.test.ts +0 -523
  31. package/test/collectionStoreHooks.test.tsx +0 -651
  32. package/test/documentStore.test.ts +0 -183
  33. package/test/documentStoreHooks.test.tsx +0 -857
  34. package/test/fetchOrquestrator.test.ts +0 -913
  35. package/test/listQueryStore.test.ts +0 -1158
  36. package/test/listQueryStoreHooks.test.tsx +0 -662
  37. package/test/listQueryStoreHooks2.test.tsx +0 -483
  38. package/test/listQueryStoreHooksMutations.test.tsx +0 -764
  39. package/test/mocks/fetchMock.ts +0 -296
  40. package/test/mocks/fetchOrquestratorEnv.ts +0 -370
  41. package/test/setup/setup.ts +0 -109
  42. package/test/testHelpers.test.ts +0 -88
  43. package/test/utils/RenderObjValues.tsx +0 -23
  44. package/test/utils/arrayUtils.ts +0 -13
  45. package/test/utils/createDefaultListQueryStore.ts +0 -275
  46. package/test/utils/createOrVariations.ts +0 -48
  47. package/test/utils/dedent.ts +0 -50
  48. package/test/utils/delayCall.ts +0 -25
  49. package/test/utils/math.ts +0 -3
  50. package/test/utils/objectUtils.ts +0 -18
  51. package/test/utils/range.ts +0 -19
  52. package/test/utils/sleep.ts +0 -3
  53. package/test/utils/storeUtils.ts +0 -460
  54. package/tsconfig.json +0 -24
  55. package/tsconfig.prod.json +0 -9
  56. package/tsup.config.ts +0 -12
  57. package/vitest.config.ts +0 -10
@@ -1,6 +0,0 @@
1
- if [[ `git status --porcelain` ]]; then
2
- echo "Commit you changes before publish"
3
- exit 1
4
- else
5
- exit 0
6
- fi
@@ -1,23 +0,0 @@
1
- import {
2
- createFetchOrquestrator,
3
- CreateFetchOrquestratorOptions,
4
- FetchOrquestrator,
5
- } from './fetchOrquestrator';
6
-
7
- export function createCollectionFetchOrquestrator<T>(
8
- props: CreateFetchOrquestratorOptions<T>,
9
- ) {
10
- const fetchOrquestrators = new Map<string, FetchOrquestrator<T>>();
11
-
12
- function getFetchOrquestrator(key: string): FetchOrquestrator<T> {
13
- if (!fetchOrquestrators.has(key)) {
14
- fetchOrquestrators.set(key, createFetchOrquestrator(props));
15
- }
16
-
17
- return fetchOrquestrators.get(key)!;
18
- }
19
-
20
- return {
21
- get: getFetchOrquestrator,
22
- };
23
- }
@@ -1,608 +0,0 @@
1
- import mitt from 'mitt';
2
- import { useCallback, useEffect, useMemo } from 'react';
3
- import { deepEqual, Store, useSubscribeToStore } from 't-state';
4
- import { createCollectionFetchOrquestrator } from './collectionFetchOrquestrator';
5
- import {
6
- FetchType,
7
- ScheduleFetchResults,
8
- FetchContext,
9
- } from './fetchOrquestrator';
10
- import { Status, ValidPayload, ValidStoreState } from './storeShared';
11
- import { useEnsureIsLoaded } from './useEnsureIsLoaded';
12
- import { filterAndMap } from './utils/filterAndMap';
13
- import { getCacheId } from './utils/getCacheId';
14
- import { useDeepMemo, useOnMittEvent } from './utils/hooks';
15
- import { serializableClone } from './utils/serializableClone';
16
-
17
- type CollectionItemStatus = Status;
18
-
19
- export type TSFDCollectionItem<
20
- ItemState extends ValidStoreState,
21
- ItemPayload extends ValidPayload,
22
- NError,
23
- > = {
24
- data: ItemState | null;
25
- error: NError | null;
26
- status: CollectionItemStatus;
27
- payload: ItemPayload;
28
- refetchOnMount: false | FetchType;
29
- wasLoaded: boolean;
30
- };
31
-
32
- export type TSFDCollectionState<
33
- ItemState extends ValidStoreState,
34
- ItemPayload extends ValidPayload,
35
- NError,
36
- > = Record<string, TSFDCollectionItem<ItemState, ItemPayload, NError> | null>;
37
-
38
- export type TSFDUseCollectionItemReturn<Selected, ItemPayload, NError> = {
39
- data: Selected;
40
- status: CollectionItemStatus | 'idle' | 'deleted';
41
- payload: ItemPayload | undefined;
42
- error: NError | null;
43
- itemStateKey: string;
44
- isLoading: boolean;
45
- };
46
-
47
- export function newTSDFCollectionStore<
48
- ItemState extends ValidStoreState,
49
- NError,
50
- ItemPayload extends ValidPayload,
51
- >({
52
- debugName,
53
- fetchFn,
54
- disableRefetchOnWindowFocus,
55
- lowPriorityThrottleMs,
56
- errorNormalizer,
57
- mediumPriorityThrottleMs,
58
- disableRefetchOnMount: globalDisableRefetchOnMount,
59
- dynamicRealtimeThrottleMs,
60
- getCollectionItemKey: filterCollectionItemObjKey,
61
- }: {
62
- debugName?: string;
63
- fetchFn: (params: ItemPayload) => Promise<ItemState>;
64
- getCollectionItemKey?: (params: ItemPayload) => ValidPayload | any[];
65
- errorNormalizer: (exception: unknown) => NError;
66
- disableRefetchOnWindowFocus?: boolean;
67
- disableRefetchOnMount?: boolean;
68
- lowPriorityThrottleMs?: number;
69
- mediumPriorityThrottleMs?: number;
70
- dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
71
- }) {
72
- type CollectionState = TSFDCollectionState<ItemState, ItemPayload, NError>;
73
- type CollectionItem = TSFDCollectionItem<ItemState, ItemPayload, NError>;
74
-
75
- const store = new Store<CollectionState>({
76
- debugName,
77
- state: {},
78
- });
79
-
80
- function getItemKey(params: ItemPayload): string {
81
- return getCacheId(
82
- filterCollectionItemObjKey ? filterCollectionItemObjKey(params) : params,
83
- );
84
- }
85
-
86
- async function fetch(
87
- fetchCtx: FetchContext,
88
- itemPayload: ItemPayload,
89
- ): Promise<boolean> {
90
- const itemId = getItemKey(itemPayload);
91
- const payload = serializableClone(itemPayload);
92
-
93
- const itemState = store.state[itemId];
94
-
95
- store.produceState(
96
- (draft) => {
97
- const item = draft[itemId];
98
-
99
- if (!item) {
100
- draft[itemId] = {
101
- data: null,
102
- error: null,
103
- status: 'loading',
104
- payload,
105
- refetchOnMount: false,
106
- wasLoaded: false,
107
- };
108
-
109
- return;
110
- }
111
-
112
- item.status = item.data !== null ? 'refetching' : 'loading';
113
- item.payload = payload;
114
- item.error = null;
115
- item.refetchOnMount = false;
116
- },
117
- {
118
- equalityCheck: deepEqual,
119
- action: {
120
- type: !itemState?.data
121
- ? 'fetch-start-loading'
122
- : 'fetch-start-refetching',
123
- payload,
124
- },
125
- },
126
- );
127
-
128
- try {
129
- const data = await fetchFn(payload);
130
-
131
- if (fetchCtx.shouldAbort()) return false;
132
-
133
- store.produceState(
134
- (draft) => {
135
- const item = draft[itemId];
136
-
137
- if (!item) return;
138
-
139
- item.data = data;
140
- item.status = 'success';
141
- item.wasLoaded = true;
142
- },
143
- { action: { type: 'fetch-success', payload } },
144
- );
145
-
146
- return true;
147
- } catch (exception) {
148
- if (fetchCtx.shouldAbort()) return false;
149
-
150
- const error = errorNormalizer(exception);
151
-
152
- store.produceState(
153
- (draft) => {
154
- const item = draft[itemId];
155
-
156
- if (!item) return;
157
-
158
- item.error = error;
159
- item.status = 'error';
160
- },
161
- { action: { type: 'fetch-error', payload, error } },
162
- );
163
-
164
- return false;
165
- }
166
- }
167
-
168
- const fetchOrquestrator = createCollectionFetchOrquestrator({
169
- fetchFn: fetch,
170
- lowPriorityThrottleMs,
171
- dynamicRealtimeThrottleMs,
172
- mediumPriorityThrottleMs,
173
- });
174
-
175
- type FilterItemsFn = (params: ItemPayload, data: ItemState | null) => boolean;
176
-
177
- function scheduleFetch(
178
- fetchType: FetchType,
179
- payload: ItemPayload,
180
- ): ScheduleFetchResults;
181
- function scheduleFetch(
182
- fetchType: FetchType,
183
- payload: ItemPayload[],
184
- ): ScheduleFetchResults[];
185
- function scheduleFetch(
186
- fetchType: FetchType,
187
- payload: ItemPayload | ItemPayload[],
188
- ): ScheduleFetchResults | ScheduleFetchResults[] {
189
- const multiplePayloads = Array.isArray(payload);
190
-
191
- const payloads = multiplePayloads ? payload : [payload];
192
-
193
- const results: ScheduleFetchResults[] = [];
194
-
195
- for (const param of payloads) {
196
- const itemKey = getItemKey(param);
197
-
198
- results.push(
199
- fetchOrquestrator.get(itemKey).scheduleFetch(fetchType, param),
200
- );
201
- }
202
-
203
- return multiplePayloads ? results : results[0]!;
204
- }
205
-
206
- async function awaitFetch(
207
- params: ItemPayload,
208
- ): Promise<{ data: null; error: NError } | { data: ItemState; error: null }> {
209
- const itemId = getItemKey(params);
210
-
211
- const wasAborted = await fetchOrquestrator.get(itemId).awaitFetch(params);
212
-
213
- if (wasAborted) {
214
- return { data: null, error: errorNormalizer(new Error('Aborted')) };
215
- }
216
-
217
- const item = store.state[itemId];
218
-
219
- if (!item?.data) {
220
- return { data: null, error: errorNormalizer(new Error('Not found')) };
221
- }
222
-
223
- return item.error
224
- ? { data: null, error: item.error }
225
- : { data: item.data, error: null };
226
- }
227
-
228
- function getItemsKeyArray(
229
- params: ItemPayload[] | FilterItemsFn | ItemPayload,
230
- ): string[] {
231
- const items = store.state;
232
-
233
- if (Array.isArray(params)) {
234
- return params.map(getItemKey);
235
- } else if (typeof params === 'function') {
236
- return filterAndMap(Object.entries(items), ([itemKey, item], ignore) => {
237
- return item && params(item.payload, item.data) ? itemKey : ignore;
238
- });
239
- } else {
240
- return [getItemKey(params)];
241
- }
242
- }
243
-
244
- const storeEvents = mitt<{
245
- invalidateData: { priority: FetchType; itemKey: string };
246
- }>();
247
-
248
- const invalidationWasTriggered = new Set<string>();
249
-
250
- function invalidateItem(
251
- itemPayload: ItemPayload | ItemPayload[] | FilterItemsFn,
252
- priority: FetchType = 'highPriority',
253
- ) {
254
- const itemsKey = getItemsKeyArray(itemPayload);
255
-
256
- for (const itemKey of itemsKey) {
257
- store.produceState(
258
- (draft) => {
259
- const item = draft[itemKey];
260
-
261
- if (!item) return;
262
-
263
- item.refetchOnMount = priority;
264
- },
265
- { action: { type: 'invalidate-data', itemKey } },
266
- );
267
-
268
- invalidationWasTriggered.delete(itemKey);
269
- storeEvents.emit('invalidateData', { priority, itemKey });
270
- }
271
- }
272
-
273
- function getItemState(
274
- fetchParam: ItemPayload,
275
- ): CollectionItem | undefined | null;
276
- function getItemState(
277
- fetchParams: ItemPayload[] | FilterItemsFn,
278
- ): CollectionItem[];
279
- function getItemState(
280
- params: ItemPayload | ItemPayload[] | FilterItemsFn,
281
- ): CollectionItem | CollectionItem[] | undefined | null {
282
- if (typeof params === 'function' || Array.isArray(params)) {
283
- const itemsId = getItemsKeyArray(params);
284
-
285
- return filterAndMap(itemsId, (itemId, ignore) => {
286
- return store.state[itemId] || ignore;
287
- });
288
- }
289
-
290
- return store.state[getItemKey(params)];
291
- }
292
-
293
- function useMultipleItems<Selected = ItemState | null>(
294
- queries: readonly ItemPayload[],
295
- {
296
- selector,
297
- omitPayload,
298
- returnIdleStatus,
299
- returnRefetchingStatus,
300
- disableRefetchOnMount = globalDisableRefetchOnMount,
301
- }: {
302
- selector?: (data: ItemState | null) => Selected;
303
- omitPayload?: boolean;
304
- disableRefetchOnMount?: boolean;
305
- returnIdleStatus?: boolean;
306
- returnRefetchingStatus?: boolean;
307
- } = {},
308
- ) {
309
- type QueryWithId = {
310
- itemKey: string;
311
- payload: ItemPayload;
312
- };
313
-
314
- const queriesWithId = useDeepMemo((): QueryWithId[] => {
315
- return queries.map((payload) => {
316
- return { itemKey: getItemKey(payload), payload };
317
- });
318
- }, [queries]);
319
-
320
- const dataSelector = useCallback((itemState: ItemState | null) => {
321
- if (selector) return selector(itemState);
322
-
323
- return itemState as Selected;
324
- // eslint-disable-next-line react-hooks/exhaustive-deps
325
- }, []);
326
-
327
- const resultSelector = useCallback(
328
- (state: CollectionState) => {
329
- return queriesWithId.map(
330
- ({
331
- itemKey,
332
- payload,
333
- }): TSFDUseCollectionItemReturn<Selected, ItemPayload, NError> => {
334
- const item = state[itemKey];
335
-
336
- if (item === null) {
337
- return {
338
- itemStateKey: itemKey,
339
- status: 'deleted',
340
- data: dataSelector(null),
341
- error: null,
342
- payload: omitPayload ? undefined : payload,
343
- isLoading: false,
344
- };
345
- }
346
-
347
- if (!item) {
348
- return {
349
- itemStateKey: itemKey,
350
- status: returnIdleStatus ? 'idle' : 'loading',
351
- data: dataSelector(null),
352
- error: null,
353
- payload: omitPayload ? undefined : payload,
354
- isLoading: returnIdleStatus ? false : true,
355
- };
356
- }
357
-
358
- let status = item.status;
359
-
360
- if (!returnRefetchingStatus && item.status === 'refetching') {
361
- status = 'success';
362
- }
363
-
364
- return {
365
- itemStateKey: itemKey,
366
- status,
367
- data: dataSelector(item.data),
368
- error: item.error,
369
- isLoading: status === 'loading',
370
- payload: omitPayload ? undefined : item.payload,
371
- };
372
- },
373
- );
374
- },
375
- [
376
- dataSelector,
377
- omitPayload,
378
- queriesWithId,
379
- returnIdleStatus,
380
- returnRefetchingStatus,
381
- ],
382
- );
383
-
384
- const storeState = store.useSelector(resultSelector, {
385
- equalityFn: deepEqual,
386
- useExternalDeps: true,
387
- });
388
-
389
- useOnMittEvent(storeEvents, 'invalidateData', (event) => {
390
- for (const { itemKey, payload } of queriesWithId) {
391
- if (itemKey !== event.itemKey) continue;
392
-
393
- if (!invalidationWasTriggered.has(itemKey)) {
394
- scheduleFetch(event.priority, payload);
395
- invalidationWasTriggered.add(itemKey);
396
- }
397
- }
398
- });
399
-
400
- useEffect(() => {
401
- for (const { itemKey: itemId, payload } of queriesWithId) {
402
- if (itemId) {
403
- if (disableRefetchOnMount) {
404
- const itemState = getItemState(payload);
405
-
406
- const shouldFetch =
407
- !itemState?.wasLoaded || itemState.refetchOnMount;
408
-
409
- if (shouldFetch) {
410
- scheduleFetch(
411
- itemState?.refetchOnMount || 'lowPriority',
412
- payload,
413
- );
414
- return;
415
- }
416
- } else {
417
- scheduleFetch('lowPriority', payload);
418
- }
419
- }
420
- }
421
- }, [disableRefetchOnMount, queriesWithId]);
422
-
423
- return storeState;
424
- }
425
-
426
- function useItem<Selected = ItemState | null>(
427
- payload: ItemPayload | undefined | false | null,
428
- options: {
429
- selector?: (data: ItemState | null) => Selected;
430
- omitPayload?: boolean;
431
- returnRefetchingStatus?: boolean;
432
- disableRefetchOnMount?: boolean;
433
- ensureIsLoaded?: boolean;
434
- } = {},
435
- ) {
436
- const { selector, ensureIsLoaded } = options;
437
-
438
- const query = useMemo(
439
- () =>
440
- payload === false || payload === null || payload === undefined
441
- ? []
442
- : [payload],
443
- [payload],
444
- );
445
-
446
- const item = useMultipleItems(query, options);
447
-
448
- const result = useMemo(
449
- (): TSFDUseCollectionItemReturn<Selected, ItemPayload, NError> =>
450
- item[0] ?? {
451
- payload: undefined,
452
- data: selector ? selector(null) : (null as Selected),
453
- error: null,
454
- status: 'idle',
455
- itemStateKey: '',
456
- isLoading: false,
457
- },
458
- // eslint-disable-next-line react-hooks/exhaustive-deps
459
- [item],
460
- );
461
-
462
- const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
463
- ensureIsLoaded,
464
- !!payload,
465
- () => {
466
- if (payload) {
467
- scheduleFetch('highPriority', payload);
468
- }
469
- },
470
- );
471
-
472
- useSubscribeToStore(store, ({ observe }) => {
473
- if (!ensureIsLoaded) return;
474
-
475
- observe
476
- .ifSelector((state) => state[result.itemStateKey]?.status)
477
- .change.then(({ current }) => {
478
- if (current === 'success' || current === 'error') {
479
- emitIsLoadedEvt('isLoaded', true);
480
- }
481
- });
482
- });
483
-
484
- return useModifyResult(result);
485
- }
486
-
487
- function startMutation(
488
- fetchParams: ItemPayload | ItemPayload[] | FilterItemsFn,
489
- ) {
490
- const itemKeys = getItemsKeyArray(fetchParams);
491
-
492
- const endMutations: (() => boolean)[] = [];
493
-
494
- for (const itemKey of itemKeys) {
495
- endMutations.push(fetchOrquestrator.get(itemKey).startMutation());
496
- }
497
-
498
- return () => {
499
- for (const endMutation of endMutations) {
500
- endMutation();
501
- }
502
- };
503
- }
504
-
505
- function addItemToState(fetchParams: ItemPayload, data: ItemState) {
506
- const itemKey = getItemKey(fetchParams);
507
-
508
- store.produceState(
509
- (draftState) => {
510
- draftState[itemKey] = {
511
- data,
512
- status: 'success',
513
- wasLoaded: true,
514
- refetchOnMount: false,
515
- error: null,
516
- payload: serializableClone(fetchParams),
517
- };
518
- },
519
- { action: { type: 'create-item-state', payload: fetchParams } },
520
- );
521
- }
522
-
523
- function deleteItemState(
524
- fetchParams: ItemPayload | ItemPayload[] | FilterItemsFn,
525
- ) {
526
- const itemKeys = getItemsKeyArray(fetchParams);
527
-
528
- store.produceState(
529
- (draftState) => {
530
- for (const itemKey of itemKeys) {
531
- draftState[itemKey] = null;
532
- }
533
- },
534
- { action: { type: 'delete-item-state', payload: fetchParams } },
535
- );
536
- }
537
-
538
- function updateItemState(
539
- fetchParams: ItemPayload | ItemPayload[] | FilterItemsFn,
540
- produceNewData: (
541
- draftData: ItemState,
542
- collectionItem: CollectionItem,
543
- ) => void | ItemState,
544
- ifNothingWasUpdated?: () => void,
545
- ): boolean {
546
- const itemKeys = getItemsKeyArray(fetchParams);
547
-
548
- let someItemWasUpdated = false as boolean;
549
-
550
- store.batch(
551
- () => {
552
- store.produceState((draftState) => {
553
- for (const itemKey of itemKeys) {
554
- const item = draftState[itemKey];
555
-
556
- if (!item) continue;
557
-
558
- if (item.data) {
559
- someItemWasUpdated = true;
560
- const newData = produceNewData(item.data, item);
561
-
562
- if (newData) {
563
- item.data = newData;
564
- }
565
- }
566
- }
567
- });
568
-
569
- if (ifNothingWasUpdated && !someItemWasUpdated) {
570
- ifNothingWasUpdated();
571
- }
572
- },
573
- { type: 'update-item-state', item: itemKeys },
574
- );
575
-
576
- return someItemWasUpdated;
577
- }
578
-
579
- if (!disableRefetchOnWindowFocus) {
580
- function handleFocus() {
581
- invalidateItem(() => true, 'lowPriority');
582
- }
583
-
584
- window.addEventListener('focus', handleFocus);
585
- window.addEventListener('visibilitychange', handleFocus);
586
- }
587
-
588
- return {
589
- store,
590
- scheduleFetch,
591
- awaitFetch,
592
- useMultipleItems,
593
- useItem,
594
- getItemKey,
595
- getItemState,
596
- startMutation,
597
- invalidateItem,
598
- updateItemState,
599
- addItemToState,
600
- deleteItemState,
601
- };
602
- }
603
-
604
- export type TSDFCollectionStore<
605
- ItemState extends ValidStoreState,
606
- NError,
607
- FetchParams extends ValidPayload,
608
- > = ReturnType<typeof newTSDFCollectionStore<ItemState, NError, FetchParams>>;