@jsb188/graphql 1.1.10 → 1.1.11

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 (116) hide show
  1. package/cache/config.ts +64 -50
  2. package/cache/index.test.ts +671 -109
  3. package/cache/index.ts +1700 -1240
  4. package/cache/persist.ts +721 -0
  5. package/cache/store.ts +437 -0
  6. package/client/data-table-realtime-subscriptions.test.ts +740 -0
  7. package/client/data-table-realtime-subscriptions.ts +955 -0
  8. package/client/data-table-realtime.test.ts +792 -0
  9. package/client/data-table-realtime.ts +1218 -0
  10. package/client/fragment-realtime-sequence.ts +52 -0
  11. package/client/index.ts +2 -0
  12. package/client/open-sheet.ts +137 -0
  13. package/client/request-managed-session.test.ts +574 -0
  14. package/client/request-no-store.test.ts +157 -0
  15. package/client/request.ts +954 -163
  16. package/client/sse-ticket.test.ts +26 -0
  17. package/deno.lock +170 -0
  18. package/deno.test.json +8 -4
  19. package/drafts/index.ts +149 -0
  20. package/drafts/store.ts +397 -0
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentDocFragments.ts +46 -0
  26. package/gql/fragments/agentMemoryFragments.ts +19 -0
  27. package/gql/fragments/aiChatFragments.ts +16 -0
  28. package/gql/fragments/billingFragments.ts +0 -11
  29. package/gql/fragments/campaignFragments.ts +277 -0
  30. package/gql/fragments/dataTableFragments.ts +18 -128
  31. package/gql/fragments/emailFragments.ts +19 -9
  32. package/gql/fragments/fieldDocFragments.ts +82 -0
  33. package/gql/fragments/logFragments.ts +20 -79
  34. package/gql/fragments/organizationFragments.ts +43 -5
  35. package/gql/fragments/scheduleFragments.ts +155 -0
  36. package/gql/fragments/sheetFragments.ts +552 -22
  37. package/gql/fragments/storageFragments.ts +21 -0
  38. package/gql/fragments/workflowFragments.ts +28 -4
  39. package/gql/mutations/accountMutations.ts +0 -2
  40. package/gql/mutations/agentDocMutations.ts +177 -0
  41. package/gql/mutations/agentMemoryMutations.ts +36 -0
  42. package/gql/mutations/aiChatMutations.ts +17 -4
  43. package/gql/mutations/authMutations.ts +158 -17
  44. package/gql/mutations/campaignMutations.ts +215 -0
  45. package/gql/mutations/dataTableMutations.ts +48 -26
  46. package/gql/mutations/fieldDocMutations.ts +24 -0
  47. package/gql/mutations/index.ts +6 -1
  48. package/gql/mutations/logMutations.ts +6 -29
  49. package/gql/mutations/organizationMutations.ts +13 -4
  50. package/gql/mutations/scheduleMutations.ts +423 -0
  51. package/gql/mutations/sheetMutations.ts +273 -56
  52. package/gql/mutations/storageMutations.ts +20 -0
  53. package/gql/mutations/workflowMutations.ts +42 -0
  54. package/gql/queries/agentDocQueries.ts +120 -0
  55. package/gql/queries/agentMemoryQueries.ts +22 -0
  56. package/gql/queries/aiChatQueries.ts +18 -2
  57. package/gql/queries/authQueries.ts +41 -0
  58. package/gql/queries/billingQueries.ts +23 -0
  59. package/gql/queries/campaignQueries.ts +127 -0
  60. package/gql/queries/dataTableQueries.ts +100 -11
  61. package/gql/queries/emailQueries.ts +55 -3
  62. package/gql/queries/fieldDocQueries.ts +158 -0
  63. package/gql/queries/index.ts +8 -2
  64. package/gql/queries/logQueries.ts +11 -28
  65. package/gql/queries/organizationQueries.ts +52 -1
  66. package/gql/queries/scheduleQueries.ts +315 -0
  67. package/gql/queries/sheetQueries.ts +336 -25
  68. package/gql/queries/storageQueries.ts +38 -0
  69. package/gql/queries/workflowQueries.ts +72 -3
  70. package/hooks/index.ts +2065 -971
  71. package/hooks/use-account-mtn.ts +76 -81
  72. package/hooks/use-agentDoc-mtn.ts +285 -0
  73. package/hooks/use-agentDoc-qry.ts +208 -0
  74. package/hooks/use-agentMemory-mtn.ts +73 -0
  75. package/hooks/use-agentMemory-qry.ts +44 -0
  76. package/hooks/use-aiChat-mtn.ts +232 -137
  77. package/hooks/use-aiChat-qry.ts +480 -222
  78. package/hooks/use-app-qry.ts +12 -9
  79. package/hooks/use-auth-mtn.ts +406 -252
  80. package/hooks/use-auth-qry.ts +51 -0
  81. package/hooks/use-campaign-mtn.ts +377 -0
  82. package/hooks/use-campaign-qry.ts +257 -0
  83. package/hooks/use-dataTable-mtn.ts +116 -33
  84. package/hooks/use-dataTable-qry.ts +859 -35
  85. package/hooks/use-email-qry.ts +194 -79
  86. package/hooks/use-fieldDoc-mtn.ts +50 -0
  87. package/hooks/use-fieldDoc-qry.ts +180 -0
  88. package/hooks/use-inboundContact-mtn.ts +19 -16
  89. package/hooks/use-inboundContact-qry.ts +63 -55
  90. package/hooks/use-integration-mtn.ts +56 -38
  91. package/hooks/use-integration-qry.ts +24 -9
  92. package/hooks/use-log-mtn.ts +72 -56
  93. package/hooks/use-log-qry.ts +93 -69
  94. package/hooks/use-organization-mtn.ts +334 -277
  95. package/hooks/use-organization-qry.ts +199 -129
  96. package/hooks/use-schedule-mtn.ts +416 -0
  97. package/hooks/use-schedule-qry.ts +157 -0
  98. package/hooks/use-sheet-mtn.ts +233 -47
  99. package/hooks/use-sheet-qry.ts +353 -70
  100. package/hooks/use-storage-mtn.ts +81 -41
  101. package/hooks/use-storage-qry.ts +104 -13
  102. package/hooks/use-workflow-mtn.ts +55 -0
  103. package/hooks/use-workflow-qry.ts +206 -48
  104. package/loaders/campaign.ts +137 -0
  105. package/package.json +94 -71
  106. package/sse.ts +157 -104
  107. package/tsconfig.json +11 -10
  108. package/types.d.ts +60 -30
  109. package/utils.ts +78 -49
  110. package/gql/fragments/productFragments.ts +0 -39
  111. package/gql/fragments/reportFragments.ts +0 -90
  112. package/gql/mutations/billingMutations.ts +0 -34
  113. package/gql/queries/productQueries.ts +0 -31
  114. package/gql/queries/reportQueries.ts +0 -134
  115. package/hooks/use-product-qry.ts +0 -67
  116. package/hooks/use-report-qry.ts +0 -153
package/hooks/index.ts CHANGED
@@ -1,48 +1,97 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
- import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d.ts';
3
- import { normalizeServerError } from '@jsb188/app/utils/api.ts';
2
+ import type {
3
+ ServerErrorObj,
4
+ SimpleErrorType,
5
+ } from '@jsb188/app/types/app.d.ts';
6
+ import {
7
+ getAuthToken,
8
+ managedAccessTokensShareBinding,
9
+ normalizeServerError,
10
+ } from '@jsb188/app/utils/api.ts';
4
11
  import { delay, makeVariablesKey } from '@jsb188/app/utils/logic.ts';
5
- import { isServerErrorGQL } from '@jsb188/graphql/utils';
6
- import { useConnectedToServerValue, useQueryObserverValue, useScreenIsFocusedValue, useSetFragmentObserver, useSetQueryObserver } from '@jsb188/react/states';
7
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
8
- import { checkDataCompleteness, clearQueryResetStatus, fetchCachedData, getQueryRefreshTime, loadDataFromCache, loadFragment, removeStaleCache } from '../cache/index.ts';
12
+ import {
13
+ queryCacheKeyMatchesResetTarget,
14
+ type QueryResetTarget,
15
+ } from '@jsb188/app/utils/queryReset.ts';
16
+ import {
17
+ isServerErrorGQL,
18
+ isTransientServerError,
19
+ } from '@jsb188/graphql/utils';
20
+ import {
21
+ useConnectedToServerValue,
22
+ useOptimisticConnectedToServerValue,
23
+ useScreenIsFocusedValue,
24
+ } from '@jsb188/react/states';
25
+ import {
26
+ useCallback,
27
+ useEffect,
28
+ useLayoutEffect,
29
+ useMemo,
30
+ useRef,
31
+ useState,
32
+ useSyncExternalStore,
33
+ } from 'react';
9
34
  import { QUERY_EXPIRE_TIMES } from '../cache/config.ts';
35
+ import { EAGER_QUERY_MAP } from '../gql/eagerQueryMap.ts';
36
+ import {
37
+ checkDataCompleteness,
38
+ clearQueryResetStatus,
39
+ fetchCachedData,
40
+ getFragmentVersionStamp,
41
+ getNextQueryLastUpdatedCount,
42
+ getQueryLastFetchedAt,
43
+ getQueryRefreshTime,
44
+ loadDataFromCache,
45
+ loadFragment,
46
+ removeStaleCache,
47
+ } from '../cache/index.ts';
10
48
  import { graphqlRequest } from '../client/request.ts';
11
- import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types.d.ts';
12
-
49
+ import type {
50
+ AnyModalPopUpFn,
51
+ GraphQLHandlers,
52
+ GraphQLQueryOptions,
53
+ OnCompletedGQLFn,
54
+ OnErrorGQLFn,
55
+ UpdateDataObserverArgs,
56
+ UpdateObserversFn,
57
+ } from '../types.d.ts';
13
58
 
14
59
  /**
15
60
  * Types; mutation
16
61
  */
17
62
 
18
- export type GraphQLMutationFn = (graphqlOptions?: GraphQLRequestOptions, triedCount?: number) => Promise<any>;
63
+ export type GraphQLMutationFn = (
64
+ graphqlOptions?: GraphQLRequestOptions,
65
+ triedCount?: number,
66
+ ) => Promise<any>;
19
67
 
20
68
  type GraphQLMutationOptions = Partial<{
21
- checkMountedBeforeCallback: boolean;
22
- authToken: string;
23
- retryCount: number;
24
- variables: Record<string, any> | null;
25
- cacheMap: any;
26
- openModalPopUp: AnyModalPopUpFn | null;
27
- initialError: any;
28
- onCompleted: OnCompletedGQLFn;
29
- onError: OnErrorGQLFn;
69
+ checkMountedBeforeCallback: boolean;
70
+ authToken: string;
71
+ retryCount: number;
72
+ variables: Record<string, any> | null;
73
+ cacheMap: any;
74
+ cachePolicy: 'default' | 'no-store';
75
+ openModalPopUp: AnyModalPopUpFn | null;
76
+ initialError: any;
77
+ onCompleted: OnCompletedGQLFn;
78
+ onError: OnErrorGQLFn;
30
79
  }>;
31
80
 
32
81
  type GraphQLMutationResult = {
33
- data: any | null;
34
- variables: Record<string, any> | null;
35
- saving: boolean;
36
- error: ServerErrorObj | null;
37
- mutationCount: number;
82
+ data: any | null;
83
+ variables: Record<string, any> | null;
84
+ saving: boolean;
85
+ error: ServerErrorObj | null;
86
+ mutationCount: number;
38
87
  };
39
88
 
40
89
  type GraphQLMutation = [
41
- GraphQLMutationFn,
42
- GraphQLMutationResult,
43
- GraphQLHandlers,
44
- UpdateObserversFn,
45
- React.MutableRefObject<Record<string, any>>
90
+ GraphQLMutationFn,
91
+ GraphQLMutationResult,
92
+ GraphQLHandlers,
93
+ UpdateObserversFn,
94
+ React.MutableRefObject<Record<string, any>>,
46
95
  ];
47
96
 
48
97
  /**
@@ -50,25 +99,41 @@ type GraphQLMutation = [
50
99
  */
51
100
 
52
101
  type GraphQLRequestOptions = {
53
- variables?: Record<string, any> | null;
102
+ variables?: Record<string, any> | null;
54
103
  };
55
104
 
56
105
  type GraphQLQueryResult = {
57
- data: any | null;
58
- variables?: Record<string, any> | null;
59
- loading: boolean;
60
- error: ServerErrorObj | null;
61
- refetch: () => void;
62
- fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
63
- queryName: string;
64
- queryKey: string;
65
- refreshTime: string;
66
- resetOnlyTime: string;
67
- variablesKey: string;
68
- updatedCount: number;
69
- updateObservers: UpdateObserversFn;
70
- connectedToServer: boolean;
71
- screenIsFocused: boolean;
106
+ data: any | null;
107
+ variables?: Record<string, any> | null;
108
+ loading: boolean;
109
+ error: ServerErrorObj | null;
110
+ refetch: () => void;
111
+ fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
112
+ queryName: string;
113
+ queryKey: string;
114
+ refreshTime: string;
115
+ resetOnlyTime: string;
116
+ variablesKey: string;
117
+ updatedCount: number;
118
+ updateObservers: UpdateObserversFn;
119
+ connectedToServer: boolean;
120
+ recovering: boolean;
121
+ screenIsFocused: boolean;
122
+ };
123
+
124
+ type GraphQLQueryValues = {
125
+ data: any;
126
+ variables?: Record<string, any> | null;
127
+ loading: boolean;
128
+ error: ServerErrorObj | null;
129
+ lastUpdatedCount: number;
130
+ lastRefreshTriggerTime: string;
131
+ };
132
+
133
+ type GraphQLQueryOutput = {
134
+ queryKey: string;
135
+ refreshTime: string;
136
+ data: any | null;
72
137
  };
73
138
 
74
139
  /**
@@ -76,16 +141,115 @@ type GraphQLQueryResult = {
76
141
  */
77
142
 
78
143
  const QRY_TRACKER = new Map();
79
- const FRAGMENT_OBSERVER_LISTENERS = new Map<string, Set<(fragmentIds: string[]) => void>>();
144
+ const QRY_PROMISES = new Map<string, Promise<any>>();
145
+ const FRAGMENT_OBSERVER_LISTENERS = new Map<
146
+ string,
147
+ Set<(fragmentIds: string[]) => void>
148
+ >();
149
+
150
+ /**
151
+ * Keyed query observer registry. Each mounted useQuery() subscribes with a
152
+ * match predicate for its own query keys, so a query event only re-renders
153
+ * the hooks it can actually affect (previously a single global Jotai atom
154
+ * re-rendered every mounted query hook on every event).
155
+ */
156
+
157
+ type QueryObserverEventObj = {
158
+ count: number;
159
+ eventSequence: number;
160
+ name: string;
161
+ // Present when the reset came from a structured target; matching uses this
162
+ // rather than the name, which is only a stable identity string
163
+ target?: QueryResetTarget | null;
164
+ forceRefetch: boolean;
165
+ resetOnly: boolean;
166
+ };
167
+
168
+ const QUERY_OBSERVER_LISTENERS = new Set<
169
+ (event: QueryObserverEventObj) => void
170
+ >();
171
+
172
+ // The last published event is retained so a hook mounting later still sees
173
+ // it on first render; this is what lets a freshly mounted query pick up a
174
+ // RESET_TIME entry that was set while it was unmounted.
175
+ let LAST_QUERY_OBSERVER_EVENT: QueryObserverEventObj = {
176
+ count: 0,
177
+ eventSequence: 0,
178
+ name: '',
179
+ target: null,
180
+ forceRefetch: false,
181
+ resetOnly: false,
182
+ };
183
+
184
+ const FILE_CONSTANTS = {
185
+ transientRetryBaseMs: 500,
186
+ transientRetryJitterMs: 250,
187
+ transientRetryMaximumMs: 10000,
188
+ };
189
+
190
+ /**
191
+ * Check whether one query's cached data is older than its freshness window
192
+ * (options.persistTime, falling back to the query's expire time). Data that
193
+ * never came from the network in this session or persisted snapshot is
194
+ * always stale.
195
+ */
196
+
197
+ function queryDataIsStale(
198
+ queryName: string,
199
+ queryKey: string,
200
+ persistTime?: number,
201
+ ): boolean {
202
+ const lastFetchedAt = getQueryLastFetchedAt(queryKey);
203
+
204
+ if (!lastFetchedAt) {
205
+ return true;
206
+ }
207
+
208
+ const freshnessWindow =
209
+ typeof persistTime === 'number'
210
+ ? persistTime
211
+ : QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
212
+
213
+ return Date.now() - lastFetchedAt > freshnessWindow;
214
+ }
215
+
216
+ /**
217
+ * Return a unique id for one mounted query hook instance.
218
+ */
219
+ function makeQueryHookId() {
220
+ return Date.now().toString(36) + Math.random().toString(36).substring(2);
221
+ }
222
+
223
+ /**
224
+ * Return GraphQL result data wrapped under its operation name.
225
+ */
226
+ function getQueryDataFromAPIResult(queryName: string, apiResult: any) {
227
+ if (
228
+ !apiResult ||
229
+ apiResult.aborted ||
230
+ apiResult.error ||
231
+ apiResult[queryName] === undefined
232
+ ) {
233
+ return null;
234
+ }
235
+
236
+ return {
237
+ [queryName]: apiResult[queryName],
238
+ };
239
+ }
80
240
 
81
241
  /**
82
242
  * Convert reactive fragment observe entries into exact fragment observer keys.
83
243
  */
84
244
 
85
- function getReactiveFragmentObserveKeys(observe: Array<string | [string, string | null]>) {
86
- return observe.map((key) => {
87
- return Array.isArray(key) ? key[0] : key;
88
- }).filter(Boolean);
245
+ function getReactiveFragmentObserveKeys(
246
+ observe: Array<string | [string, string | null]>,
247
+ ) {
248
+ return observe
249
+ .map((key) => {
250
+ return Array.isArray(key) ? key[0] : key;
251
+ })
252
+ .filter(Boolean);
89
253
  }
90
254
 
91
255
  /**
@@ -93,25 +257,39 @@ function getReactiveFragmentObserveKeys(observe: Array<string | [string, string
93
257
  */
94
258
 
95
259
  function subscribeFragmentObserverKeys(
96
- fragmentIds: string[],
97
- listener: (fragmentIds: string[]) => void,
260
+ fragmentIds: string[],
261
+ listener: (fragmentIds: string[]) => void,
262
+ ) {
263
+ for (const fragmentId of fragmentIds) {
264
+ const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId) || new Set();
265
+ listeners.add(listener);
266
+ FRAGMENT_OBSERVER_LISTENERS.set(fragmentId, listeners);
267
+ }
268
+
269
+ return () => {
270
+ for (const fragmentId of fragmentIds) {
271
+ const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
272
+ listeners?.delete(listener);
273
+
274
+ if (!listeners?.size) {
275
+ FRAGMENT_OBSERVER_LISTENERS.delete(fragmentId);
276
+ }
277
+ }
278
+ };
279
+ }
280
+
281
+ /**
282
+ * Subscribe to exact reactive fragment keys from outside the hook layer.
283
+ * Used by feature stores (e.g. the sheet cell store) that consume realtime
284
+ * fragment patches directly instead of through useReactiveFragment.
285
+ * Returns the unsubscribe function.
286
+ */
287
+
288
+ export function observeReactiveFragments(
289
+ fragmentIds: string[],
290
+ listener: (fragmentIds: string[]) => void,
98
291
  ) {
99
- for (const fragmentId of fragmentIds) {
100
- const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId) || new Set();
101
- listeners.add(listener);
102
- FRAGMENT_OBSERVER_LISTENERS.set(fragmentId, listeners);
103
- }
104
-
105
- return () => {
106
- for (const fragmentId of fragmentIds) {
107
- const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
108
- listeners?.delete(listener);
109
-
110
- if (!listeners?.size) {
111
- FRAGMENT_OBSERVER_LISTENERS.delete(fragmentId);
112
- }
113
- }
114
- };
292
+ return subscribeFragmentObserverKeys(fragmentIds, listener);
115
293
  }
116
294
 
117
295
  /**
@@ -119,42 +297,47 @@ function subscribeFragmentObserverKeys(
119
297
  */
120
298
 
121
299
  function notifyFragmentObserverListeners(fragmentIds: string[]) {
122
- const notifiedListeners = new Set<(fragmentIds: string[]) => void>();
123
-
124
- for (const fragmentId of fragmentIds) {
125
- const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
126
-
127
- listeners?.forEach((listener) => {
128
- if (!notifiedListeners.has(listener)) {
129
- notifiedListeners.add(listener);
130
- listener(fragmentIds);
131
- }
132
- });
133
- }
300
+ const notifiedListeners = new Set<(fragmentIds: string[]) => void>();
301
+
302
+ for (const fragmentId of fragmentIds) {
303
+ const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
304
+
305
+ listeners?.forEach((listener) => {
306
+ if (!notifiedListeners.has(listener)) {
307
+ notifiedListeners.add(listener);
308
+ listener(fragmentIds);
309
+ }
310
+ });
311
+ }
134
312
  }
135
313
 
136
314
  /**
137
315
  * Observe only the exact fragment keys needed by one reactive fragment hook.
138
316
  */
139
317
 
140
- function useFragmentKeyObserver(observe: Array<string | [string, string | null]>) {
141
- const observeStr = getReactiveFragmentObserveKeys(observe).join(',');
142
- const observeKeys = useMemo(() => observeStr.split(',').filter(Boolean), [observeStr]);
143
- const [fragmentObserver, setFragmentObserver] = useState({
144
- count: 0,
145
- list: [] as string[],
146
- });
147
-
148
- useEffect(() => {
149
- return subscribeFragmentObserverKeys(observeKeys, (fragmentIds) => {
150
- setFragmentObserver((prev) => ({
151
- count: prev.count + 1,
152
- list: fragmentIds,
153
- }));
154
- });
155
- }, [observeKeys]);
156
-
157
- return fragmentObserver;
318
+ function useFragmentKeyObserver(
319
+ observe: Array<string | [string, string | null]>,
320
+ ) {
321
+ const observeStr = getReactiveFragmentObserveKeys(observe).join(',');
322
+ const observeKeys = useMemo(
323
+ () => observeStr.split(',').filter(Boolean),
324
+ [observeStr],
325
+ );
326
+ const [fragmentObserver, setFragmentObserver] = useState({
327
+ count: 0,
328
+ list: [] as string[],
329
+ });
330
+
331
+ useEffect(() => {
332
+ return subscribeFragmentObserverKeys(observeKeys, (fragmentIds) => {
333
+ setFragmentObserver((prev) => ({
334
+ count: prev.count + 1,
335
+ list: fragmentIds,
336
+ }));
337
+ });
338
+ }, [observeKeys]);
339
+
340
+ return fragmentObserver;
158
341
  }
159
342
 
160
343
  /**
@@ -162,10 +345,10 @@ function useFragmentKeyObserver(observe: Array<string | [string, string | null]>
162
345
  */
163
346
 
164
347
  function unsetQueryTracker(queryName: string, unique: string | null) {
165
- const currentHookId = QRY_TRACKER.get(queryName);
166
- if (currentHookId === unique) {
167
- QRY_TRACKER.delete(queryName);
168
- }
348
+ const currentHookId = QRY_TRACKER.get(queryName);
349
+ if (currentHookId === unique) {
350
+ QRY_TRACKER.delete(queryName);
351
+ }
169
352
  }
170
353
 
171
354
  /**
@@ -173,35 +356,166 @@ function unsetQueryTracker(queryName: string, unique: string | null) {
173
356
  */
174
357
 
175
358
  function getRetryDelay(triedCount: number): number {
176
- return 1500 * Math.pow(2, triedCount);
359
+ return 1500 * Math.pow(2, triedCount);
360
+ }
361
+
362
+ /**
363
+ * Return a capped, jittered delay for retrying one temporary server failure.
364
+ */
365
+ function getTransientRetryDelay(attemptCount: number): number {
366
+ const exponentialDelay = Math.min(
367
+ FILE_CONSTANTS.transientRetryMaximumMs,
368
+ FILE_CONSTANTS.transientRetryBaseMs * 2 ** attemptCount,
369
+ );
370
+
371
+ return Math.min(
372
+ FILE_CONSTANTS.transientRetryMaximumMs,
373
+ exponentialDelay +
374
+ Math.floor(Math.random() * FILE_CONSTANTS.transientRetryJitterMs),
375
+ );
376
+ }
377
+
378
+ /**
379
+ * Return whether a delayed retry still belongs to the same browser login or
380
+ * to a refreshed token for that exact managed account session.
381
+ */
382
+ function authContextMatchesRetryToken(
383
+ retryToken: string | null,
384
+ currentToken: string | null,
385
+ ) {
386
+ return (
387
+ retryToken === currentToken ||
388
+ Boolean(
389
+ retryToken &&
390
+ currentToken &&
391
+ managedAccessTokensShareBinding(retryToken, currentToken),
392
+ )
393
+ );
394
+ }
395
+
396
+ /**
397
+ * Publish a data observer event to keyed query/fragment subscribers.
398
+ * Works outside React (websocket handlers, imperative cache updates).
399
+ */
400
+
401
+ export function updateDataObservers(args: UpdateDataObserverArgs) {
402
+ if (args.queryId) {
403
+ LAST_QUERY_OBSERVER_EVENT = {
404
+ count:
405
+ (LAST_QUERY_OBSERVER_EVENT.name === args.queryId
406
+ ? LAST_QUERY_OBSERVER_EVENT.count
407
+ : 0) + 1,
408
+ eventSequence: (LAST_QUERY_OBSERVER_EVENT.eventSequence || 0) + 1,
409
+ name: args.queryId as string,
410
+ target: args.queryTarget || null,
411
+ forceRefetch: !!args.forceRefetch,
412
+ resetOnly: !!args.resetOnly,
413
+ };
414
+
415
+ const event = LAST_QUERY_OBSERVER_EVENT;
416
+ QUERY_OBSERVER_LISTENERS.forEach((listener) => {
417
+ listener(event);
418
+ });
419
+ }
420
+
421
+ if (args.fragmentIds?.length) {
422
+ notifyFragmentObserverListeners(args.fragmentIds as string[]);
423
+ }
177
424
  }
178
425
 
179
426
  /**
180
427
  * Update data observer
428
+ * Kept as a hook for call-site compatibility; the returned function is the
429
+ * stable module-level publisher.
181
430
  */
182
431
 
183
432
  export function useUpdateObservers(): UpdateObserversFn {
184
- const setQueryObserver = useSetQueryObserver();
185
- const setFragmentObserver = useSetFragmentObserver();
186
-
187
- return (args: UpdateDataObserverArgs) => {
188
- if (args.queryId) {
189
- setQueryObserver((prev: any) => ({
190
- count: (prev.name === args.queryId ? prev.count : 0) + 1,
191
- name: args.queryId as string,
192
- forceRefetch: !!args.forceRefetch,
193
- resetOnly: !!args.resetOnly,
194
- }));
195
- }
196
-
197
- if (args.fragmentIds?.length) {
198
- setFragmentObserver((prev: any) => ({
199
- count: (prev.count || 0) + 1,
200
- list: args.fragmentIds as string[],
201
- }));
202
- notifyFragmentObserverListeners(args.fragmentIds as string[]);
203
- }
204
- };
433
+ return updateDataObservers;
434
+ }
435
+
436
+ /**
437
+ * Check whether one query observer event can affect a query hook mounted
438
+ * with the given document + variables key. Mirrors the matching rules in
439
+ * useWatchQuery(); slight over-matching is safe (it only re-runs the memo),
440
+ * under-matching would drop updates.
441
+ */
442
+
443
+ function queryObserverEventMatchesQuery(
444
+ event: QueryObserverEventObj,
445
+ query: any,
446
+ variablesKey: string,
447
+ ): boolean {
448
+ const eventName = event.name;
449
+ if (!eventName) {
450
+ return false;
451
+ }
452
+
453
+ const queryDefs = query.definitions.filter(
454
+ (d: any) => d.kind === 'OperationDefinition',
455
+ );
456
+
457
+ // A pending force-refetch reset for this query must always be picked up
458
+ const firstQueryName = queryDefs?.[0]?.name?.value;
459
+ if (firstQueryName && getQueryRefreshTime(firstQueryName, variablesKey)) {
460
+ return true;
461
+ }
462
+
463
+ return queryDefs.some((d: any) => {
464
+ const queryName = d.name.value;
465
+ const fullQueryKey = `#${queryName}:${variablesKey}`;
466
+
467
+ if (event.target) {
468
+ return queryCacheKeyMatchesResetTarget(fullQueryKey, event.target);
469
+ }
470
+
471
+ if (eventName.startsWith('^')) {
472
+ try {
473
+ return new RegExp(eventName).test(fullQueryKey);
474
+ } catch (_err) {
475
+ return false;
476
+ }
477
+ }
478
+
479
+ return (
480
+ eventName === fullQueryKey ||
481
+ eventName === `#${queryName}:` ||
482
+ fullQueryKey.startsWith(eventName)
483
+ );
484
+ });
485
+ }
486
+
487
+ /**
488
+ * Subscribe one query hook to only the observer events that match its query.
489
+ */
490
+
491
+ function useQueryObserverEvent(
492
+ query: any,
493
+ variablesKey: string,
494
+ ): QueryObserverEventObj {
495
+ const [event, setEvent] = useState(LAST_QUERY_OBSERVER_EVENT);
496
+
497
+ useEffect(() => {
498
+ const listener = (nextEvent: QueryObserverEventObj) => {
499
+ if (queryObserverEventMatchesQuery(nextEvent, query, variablesKey)) {
500
+ setEvent(nextEvent);
501
+ }
502
+ };
503
+
504
+ QUERY_OBSERVER_LISTENERS.add(listener);
505
+
506
+ // Deliver anything published between render and subscription
507
+ setEvent((currentEvent: QueryObserverEventObj) =>
508
+ currentEvent === LAST_QUERY_OBSERVER_EVENT
509
+ ? currentEvent
510
+ : LAST_QUERY_OBSERVER_EVENT,
511
+ );
512
+
513
+ return () => {
514
+ QUERY_OBSERVER_LISTENERS.delete(listener);
515
+ };
516
+ }, [variablesKey]);
517
+
518
+ return event;
205
519
  }
206
520
 
207
521
  /**
@@ -209,291 +523,318 @@ export function useUpdateObservers(): UpdateObserversFn {
209
523
  */
210
524
 
211
525
  export function useWatchQuery(
212
- query: any,
213
- variablesKey: string,
214
- lastUpdatedCount: number,
215
- loading: boolean,
526
+ query: any,
527
+ variablesKey: string,
528
+ lastUpdatedCount: number,
529
+ loading: boolean,
216
530
  ) {
531
+ const qryObserver = useQueryObserverEvent(query, variablesKey);
532
+ const [qryReset, setQryReset] = useState({
533
+ triggerTime: '',
534
+ refreshTime: '', // This value is fixed and never resets (this should be used as a tracker)
535
+ refreshTimeActive: '', // This value resets when loading starts
536
+ });
537
+
538
+ const queryWatcher = useMemo<[number, boolean, string, string]>(() => {
539
+ if (qryObserver.name) {
540
+ const queryDefs = query.definitions.filter(
541
+ (d: any) => d.kind === 'OperationDefinition',
542
+ );
543
+ const queryName = queryDefs?.[0]?.name?.value;
544
+
545
+ if (queryName) {
546
+ const qryTriggerTime = getQueryRefreshTime(queryName, variablesKey);
547
+
548
+ if (qryTriggerTime) {
549
+ clearQueryResetStatus(queryName, variablesKey);
550
+ console.dev(
551
+ `... (1) Query [${queryName}:${variablesKey}] is being force refetched via observer.`,
552
+ );
553
+ return [lastUpdatedCount + 1, true, qryTriggerTime, ''];
554
+ }
555
+ }
556
+
557
+ const matchedQry = queryDefs.find((d: any) => {
558
+ const queryName = d.name.value;
559
+ const fullQueryKey = `#${queryName}:${variablesKey}`;
560
+ const queryNameKey = `#${queryName}:`;
561
+
562
+ if (qryObserver.target) {
563
+ return queryCacheKeyMatchesResetTarget(
564
+ fullQueryKey,
565
+ qryObserver.target,
566
+ );
567
+ }
568
+
569
+ if (qryObserver.name.startsWith('^')) {
570
+ try {
571
+ return new RegExp(qryObserver.name).test(fullQueryKey);
572
+ } catch (_err) {
573
+ return false;
574
+ }
575
+ }
576
+
577
+ return (
578
+ qryObserver.name === fullQueryKey ||
579
+ qryObserver.name === queryNameKey ||
580
+ fullQueryKey.startsWith(qryObserver.name)
581
+ );
582
+ });
583
+
584
+ if (!matchedQry) {
585
+ return [lastUpdatedCount, false, '', ''];
586
+ }
587
+
588
+ const matchedQueryName = matchedQry.name.value;
589
+ const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
590
+ const forceRefetch = !!qryObserver.forceRefetch;
591
+ const resetOnlyTime = qryObserver.resetOnly
592
+ ? String(qryObserver.eventSequence)
593
+ : '';
594
+
595
+ let newUpdatedCount =
596
+ qryObserver.name === matchedQueryId || forceRefetch
597
+ ? qryObserver.count
598
+ : 0;
599
+ if (forceRefetch) {
600
+ newUpdatedCount += 1;
601
+ }
602
+
603
+ if (forceRefetch) {
604
+ console.dev(
605
+ `... (2) Query [${matchedQueryId}] is being force refetched via observer.`,
606
+ );
607
+ }
608
+
609
+ return [newUpdatedCount, forceRefetch, '', resetOnlyTime];
610
+ }
611
+
612
+ return [lastUpdatedCount, false, '', ''];
613
+ }, [lastUpdatedCount, qryObserver]);
614
+
615
+ useEffect(() => {
616
+ if (!loading) {
617
+ if (qryReset.triggerTime && qryReset.refreshTimeActive === '') {
618
+ setQryReset((prev) => ({
619
+ ...prev,
620
+ refreshTime: qryReset.triggerTime,
621
+ refreshTimeActive: qryReset.triggerTime,
622
+ }));
623
+ } else if (queryWatcher[2] && queryWatcher[2] !== qryReset.triggerTime) {
624
+ setQryReset((prev) => ({
625
+ ...prev,
626
+ triggerTime: queryWatcher[2],
627
+ }));
628
+ }
629
+ } else if (qryReset.refreshTimeActive) {
630
+ setQryReset((prev) => ({
631
+ ...prev,
632
+ triggerTime: '',
633
+ refreshTimeActive: '',
634
+ }));
635
+ }
636
+ }, [queryWatcher[2], loading]);
637
+
638
+ // console.log('refreshTime:', refreshTime + queryWatcher[0]);
639
+
640
+ return {
641
+ updatedCount: queryWatcher[0],
642
+ forceRefetch: queryWatcher[1],
643
+ resetOnlyTime: queryWatcher[3],
644
+ qryReset,
645
+ };
646
+ }
217
647
 
218
- const qryObserver = useQueryObserverValue();
219
- const [qryReset, setQryReset] = useState({
220
- triggerTime: '',
221
- refreshTime: '', // This value is fixed and never resets (this should be used as a tracker)
222
- refreshTimeActive: '', // This value resets when loading starts
223
- });
224
-
225
- const queryWatcher = useMemo<[number, boolean, string, string]>(() => {
226
- if (qryObserver.name) {
227
- const queryDefs = query.definitions.filter((d: any) => d.kind === 'OperationDefinition');
228
- const queryName = queryDefs?.[0]?.name?.value;
229
-
230
- if (queryName) {
231
- const qryTriggerTime = getQueryRefreshTime(queryName, variablesKey);
232
-
233
- if (qryTriggerTime) {
234
- clearQueryResetStatus(queryName, variablesKey);
235
- console.dev(`... (1) Query [${queryName}:${variablesKey}] is being force refetched via observer.`);
236
- return [lastUpdatedCount + 1, true, qryTriggerTime, ''];
237
- }
238
- }
239
-
240
- const matchedQry = queryDefs
241
- .find((d: any) => {
242
- const queryName = d.name.value;
243
- const fullQueryKey = `#${queryName}:${variablesKey}`;
244
- const queryNameKey = `#${queryName}:`;
245
-
246
- if (qryObserver.name.startsWith('^')) {
247
- try {
248
- return new RegExp(qryObserver.name).test(fullQueryKey);
249
- } catch (_err) {
250
- return false;
251
- }
252
- }
253
-
254
- return (
255
- qryObserver.name === fullQueryKey ||
256
- qryObserver.name === queryNameKey ||
257
- fullQueryKey.startsWith(qryObserver.name)
258
- );
259
- });
260
-
261
- if (!matchedQry) {
262
- return [0, false, '', ''];
263
- }
264
-
265
- const matchedQueryName = matchedQry.name.value;
266
- const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
267
- const forceRefetch = !!qryObserver.forceRefetch;
268
- const resetOnlyTime = qryObserver.resetOnly ? `${Date.now()}:${qryObserver.count}` : '';
269
-
270
- let newUpdatedCount = qryObserver.name === matchedQueryId || forceRefetch ? qryObserver.count : 0;
271
- if (forceRefetch) {
272
- newUpdatedCount += 1;
273
- }
274
-
275
- if (forceRefetch) {
276
- console.dev(`... (2) Query [${matchedQueryId}] is being force refetched via observer.`);
277
- }
278
-
279
- return [newUpdatedCount, forceRefetch, '', resetOnlyTime];
280
- }
281
-
282
- return [0, false, '', ''];
283
- }, [qryObserver]);
284
-
285
- useEffect(() => {
286
- if (!loading) {
287
- if (qryReset.triggerTime && qryReset.refreshTimeActive === '') {
288
- setQryReset((prev) => ({
289
- ...prev,
290
- refreshTime: qryReset.triggerTime,
291
- refreshTimeActive: qryReset.triggerTime,
292
- }));
293
- } else if (queryWatcher[2] && queryWatcher[2] !== qryReset.triggerTime) {
294
- setQryReset((prev) => ({
295
- ...prev,
296
- triggerTime: queryWatcher[2],
297
- }));
298
- }
299
- } else if (qryReset.refreshTimeActive) {
300
- setQryReset((prev) => ({
301
- ...prev,
302
- triggerTime: '',
303
- refreshTimeActive: '',
304
- }));
305
- }
306
- }, [queryWatcher[2], loading]);
307
-
308
- // console.log('refreshTime:', refreshTime + queryWatcher[0]);
309
-
310
- return {
311
- updatedCount: queryWatcher[0],
312
- forceRefetch: queryWatcher[1],
313
- resetOnlyTime: queryWatcher[3],
314
- qryReset
315
- };
648
+ /*
649
+ * Merge one current document with the latest values from its observed fragment
650
+ * keys. Fragment values win because websocket updates can be newer than the
651
+ * query result that supplied the document base.
652
+ */
653
+ function getReactiveFragmentData(
654
+ data: any,
655
+ observe: Array<string | [string, string | null]>,
656
+ mainPrioritizedFields?: string[],
657
+ ) {
658
+ let nextData = data;
659
+
660
+ observe.forEach((key) => {
661
+ const isMapped = Array.isArray(key);
662
+ const fragmentData = loadFragment(
663
+ isMapped ? key[0] : key,
664
+ mainPrioritizedFields,
665
+ );
666
+
667
+ if (!fragmentData) {
668
+ return;
669
+ }
670
+ if (isMapped) {
671
+ if (key[1]) {
672
+ nextData = {
673
+ ...nextData,
674
+ [key[1]]: fragmentData,
675
+ };
676
+ }
677
+ return;
678
+ }
679
+
680
+ nextData = {
681
+ ...nextData,
682
+ ...fragmentData,
683
+ };
684
+ });
685
+
686
+ return nextData;
316
687
  }
317
688
 
318
689
  /**
319
690
  * Hook for reactive fragment data
691
+ * This function will return the cached data if it exists, even if the `data` param is null.
320
692
  */
321
693
 
322
694
  export function useReactiveFragment(
323
- data: any,
324
- observe: Array<string | [string, string | null]>,
325
- qryObsCount?: number | boolean,
326
- otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
327
- mainPrioritizedFields?: string[],
328
- ignoreIDWarning?: boolean,
329
- isTest?: boolean
695
+ data: any,
696
+ observe: Array<string | [string, string | null]>,
697
+ qryObsCount?: number | boolean,
698
+ otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
699
+ mainPrioritizedFields?: string[],
700
+ ignoreIDWarning?: boolean,
701
+ isTest?: boolean,
330
702
  ) {
331
-
332
- const fragmentObserver = useFragmentKeyObserver(observe);
333
- const frgObsCount = fragmentObserver.count;
334
- const dataId = data?.id;
335
-
336
- const [changedData, setChangedData] = useState<any>(() => {
337
- // This allows initial data to *not* be null even when data param is null
338
- let initialData = data;
339
-
340
- observe.forEach((key) => {
341
- const isMapped = Array.isArray(key);
342
- const fragmentData = loadFragment(isMapped ? key[0] : key, mainPrioritizedFields);
343
-
344
- if (fragmentData) {
345
- if (isMapped) {
346
- if (key[1]) {
347
- initialData = {
348
- ...initialData!,
349
- [key[1]]: fragmentData,
350
- };
351
- }
352
- } else {
353
- initialData = {
354
- ...initialData!,
355
- ...fragmentData,
356
- };
357
- }
358
- }
359
- });
360
-
361
- return {
362
- fragmentUpdatedCount: frgObsCount,
363
- queryUpdatedCount: qryObsCount,
364
- data: initialData
365
- };
366
- });
367
-
368
- if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
369
- // this is fine because it will only run in development and never truly be conditional
370
- // eslint-disable-next-line react-hooks/rules-of-hooks
371
- useEffect(() => {
372
- if (
373
- // getENVVariable('NODE_ENV') === 'development' &&
374
- dataId && changedData.data?.id &&
375
- dataId !== changedData.data?.id
376
- ) {
377
- console.warn(`WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`);
378
- console.warn('This can result in invalid merged data. Use key={id} to avoid this error.');
379
- }
380
- }, [changedData.data?.id]);
381
- }
382
-
383
- useEffect(() => {
384
-
385
- // NOTE: I tried this with Preact's effect()
386
- // But that caused the render to happen 3 times more, I don't know why.
387
- // I only solved it by using useEffect()
388
- const idsChanged = (
389
- !dataId ||
390
- changedData.data?.id !== dataId ||
391
- (
392
- // This is absolutely needed for the chat clientId system to work properly;
393
- // Otherwise messages will be stuck in "not sent" state.
394
- changedData.data?.clientId &&
395
- changedData.data?.clientId !== data.clientId
396
- )
397
- );
398
-
399
- const forceReactive = otherCheck && otherCheck(changedData.data, fragmentObserver.list);
400
-
401
- if (
402
- idsChanged ||
403
- forceReactive || (
404
- (changedData.data || data) &&
405
- (
406
- frgObsCount !== changedData.fragmentUpdatedCount ||
407
- qryObsCount !== changedData.queryUpdatedCount
408
- )
409
- )
410
- ) {
411
-
412
- const dataUpdated = (
413
- idsChanged ||
414
- forceReactive ||
415
- observe.some((key) => {
416
- const isMapped = Array.isArray(key);
417
- return isMapped ? fragmentObserver.list.includes(key[0]) : fragmentObserver.list.includes(key);
418
- })
419
- )
420
-
421
- let newData;
422
- if (dataUpdated) {
423
- for (const key of observe) {
424
- const isMapped = Array.isArray(key);
425
-
426
- if (key) {
427
- if (!newData) {
428
- if (idsChanged) {
429
- newData = data;
430
- } else if (data) {
431
- newData = {
432
- ...data,
433
- ...changedData.data,
434
- };
435
- } else {
436
- newData = changedData.data;
437
- }
438
- }
439
-
440
- const fragmentData = loadFragment(isMapped ? key[0] : key, mainPrioritizedFields);
441
-
442
- // if (isTest) {
443
- // console.log('fragmentKey', key);
444
- // console.log('fragmentData', fragmentData);
445
- // }
446
-
447
- if (fragmentData) {
448
- if (isMapped) {
449
- if (key[1]) {
450
- newData = {
451
- ...newData,
452
- [key[1]]: fragmentData,
453
- };
454
- }
455
- } else {
456
- newData = {
457
- ...newData,
458
- ...fragmentData,
459
- };
460
- }
461
- }
462
- }
463
- }
464
- }
465
-
466
- if (newData) {
467
- setChangedData({
468
- data: newData,
469
- fragmentUpdatedCount: frgObsCount,
470
- queryUpdatedCount: qryObsCount,
471
- });
472
- }
473
- }
474
- }, [dataId, qryObsCount, frgObsCount]);
475
-
476
- // This is not needed now, I think
477
- // useEffect(() => {
478
- // if (updateQueryCount && queryKey) {
479
- // const updatedQueryData = loadQuery(queryKey);
480
- // setChangedData({
481
- // ...changedData,
482
- // data: {
483
- // ...changedData.data,
484
- // ...updatedQueryData,
485
- // },
486
- // });
487
- // }
488
- // }, [updateQueryCount]);
489
-
490
- // if (isTest) {
491
- // console.log('dataId', dataId);
492
- // console.log('1', changedData);
493
- // console.log('2', data);
494
- // }
495
-
496
- return changedData.data ?? null;
703
+ const fragmentObserver = useFragmentKeyObserver(observe);
704
+ const frgObsCount = fragmentObserver.count;
705
+ const dataId = data?.id;
706
+
707
+ // Version stamp of the observed fragments at the last rebuild; notifications
708
+ // that did not actually change any observed fragment are skipped without a
709
+ // state update (deep-equal cache writes never bump fragment versions).
710
+ const lastBuildStampRef = useRef('');
711
+
712
+ const [changedData, setChangedData] = useState<any>(() => {
713
+ return {
714
+ fragmentUpdatedCount: frgObsCount,
715
+ queryUpdatedCount: qryObsCount,
716
+ data: getReactiveFragmentData(data, observe, mainPrioritizedFields),
717
+ };
718
+ });
719
+
720
+ if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
721
+ // this is fine because it will only run in development and never truly be conditional
722
+ // eslint-disable-next-line react-hooks/rules-of-hooks
723
+ useEffect(() => {
724
+ if (
725
+ // getENVVariable('NODE_ENV') === 'development' &&
726
+ dataId &&
727
+ changedData.data?.id &&
728
+ dataId !== changedData.data?.id
729
+ ) {
730
+ console.warn(
731
+ `WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`,
732
+ );
733
+ console.warn(
734
+ 'This can result in invalid merged data. Use key={id} to avoid this error.',
735
+ );
736
+ }
737
+ }, [changedData.data?.id]);
738
+ }
739
+
740
+ useEffect(() => {
741
+ // NOTE: I tried this with Preact's effect()
742
+ // But that caused the render to happen 3 times more, I don't know why.
743
+ // I only solved it by using useEffect()
744
+ const idsChanged =
745
+ !dataId ||
746
+ changedData.data?.id !== dataId ||
747
+ // This is absolutely needed for the chat clientId system to work properly;
748
+ // Otherwise messages will be stuck in "not sent" state.
749
+ (changedData.data?.clientId &&
750
+ changedData.data?.clientId !== data.clientId);
751
+ const queryDataChanged = qryObsCount !== changedData.queryUpdatedCount;
752
+
753
+ const forceReactive = otherCheck?.(changedData.data, fragmentObserver.list);
754
+
755
+ if (
756
+ idsChanged ||
757
+ forceReactive ||
758
+ ((changedData.data || data) &&
759
+ (frgObsCount !== changedData.fragmentUpdatedCount || queryDataChanged))
760
+ ) {
761
+ // When only a fragment notification arrived, skip the rebuild if none
762
+ // of the observed fragments actually changed since the last build.
763
+ if (!idsChanged && !queryDataChanged && !forceReactive) {
764
+ const observedStamp = getFragmentVersionStamp(
765
+ getReactiveFragmentObserveKeys(observe),
766
+ );
767
+ if (observedStamp === lastBuildStampRef.current) {
768
+ return;
769
+ }
770
+ }
771
+
772
+ const dataUpdated =
773
+ idsChanged ||
774
+ queryDataChanged ||
775
+ forceReactive ||
776
+ observe.some((key) => {
777
+ const isMapped = Array.isArray(key);
778
+ return isMapped
779
+ ? fragmentObserver.list.includes(key[0])
780
+ : fragmentObserver.list.includes(key);
781
+ });
782
+
783
+ let newData: any;
784
+ if (dataUpdated) {
785
+ const baseData =
786
+ (idsChanged || queryDataChanged) && data
787
+ ? data
788
+ : data
789
+ ? { ...data, ...changedData.data }
790
+ : changedData.data;
791
+ newData = getReactiveFragmentData(
792
+ baseData,
793
+ observe,
794
+ mainPrioritizedFields,
795
+ );
796
+ }
797
+
798
+ if (newData) {
799
+ lastBuildStampRef.current = getFragmentVersionStamp(
800
+ getReactiveFragmentObserveKeys(observe),
801
+ );
802
+ setChangedData({
803
+ data: newData,
804
+ fragmentUpdatedCount: frgObsCount,
805
+ queryUpdatedCount: qryObsCount,
806
+ });
807
+ }
808
+ }
809
+ }, [dataId, qryObsCount, frgObsCount]);
810
+
811
+ // This is not needed now, I think
812
+ // useEffect(() => {
813
+ // if (updateQueryCount && queryKey) {
814
+ // const updatedQueryData = loadQuery(queryKey);
815
+ // setChangedData({
816
+ // ...changedData,
817
+ // data: {
818
+ // ...changedData.data,
819
+ // ...updatedQueryData,
820
+ // },
821
+ // });
822
+ // }
823
+ // }, [updateQueryCount]);
824
+
825
+ // if (isTest) {
826
+ // console.log('dataId', dataId);
827
+ // console.log('1', changedData);
828
+ // console.log('2', data);
829
+ // }
830
+
831
+ if (data && qryObsCount !== changedData.queryUpdatedCount) {
832
+ return (
833
+ getReactiveFragmentData(data, observe, mainPrioritizedFields) ?? null
834
+ );
835
+ }
836
+
837
+ return changedData.data ?? null;
497
838
  }
498
839
 
499
840
  /**
@@ -501,119 +842,151 @@ export function useReactiveFragment(
501
842
  */
502
843
 
503
844
  function getReactiveFragmentMapData(
504
- data: any[] | null,
505
- observe?: string[] | null,
845
+ data: any[] | null,
846
+ observe?: string[] | null,
506
847
  ) {
507
- if (!data || !observe?.length) {
508
- return data;
509
- }
510
-
511
- return data.map((item, i) => {
512
- const key = observe[i];
513
- if (!key) {
514
- return item;
515
- }
516
-
517
- const fragmentData = loadFragment(key);
518
- if (!fragmentData) {
519
- return item;
520
- }
521
-
522
- return {
523
- ...item,
524
- ...fragmentData,
525
- };
526
- });
848
+ if (!data || !observe?.length) {
849
+ return data;
850
+ }
851
+
852
+ return data.map((item, i) => {
853
+ const key = observe[i];
854
+ if (!key) {
855
+ return item;
856
+ }
857
+
858
+ const fragmentData = loadFragment(key);
859
+ if (!fragmentData) {
860
+ return item;
861
+ }
862
+
863
+ return {
864
+ ...item,
865
+ ...fragmentData,
866
+ };
867
+ });
527
868
  }
528
869
 
529
- /**
530
- * Observe query changes; but for Arrays
870
+ /*
871
+ * Observe fragment-backed arrays and synchronously rebase them when their
872
+ * owning query publishes a new same-shape result generation.
531
873
  */
532
874
 
533
875
  export function useReactiveFragmentMap(
534
- data: any[] | null,
535
- fragmentName_: string,
876
+ data: any[] | null,
877
+ fragmentName_: string,
878
+ qryObsCount?: number | boolean,
536
879
  ) {
537
- const fragmentName = `$${fragmentName_}`;
538
- const observeStr = useMemo<string>(() => data?.map((d) => fragmentName + ':' + d.id).join(',') || '', [data, fragmentName]);
539
- const observe = useMemo<string[]>(() => observeStr.split(',').filter(Boolean), [observeStr]);
540
- const observeIndex = useMemo<Map<string, number>>(() => {
541
- const indexMap = new Map<string, number>();
542
-
543
- observe.forEach((key: string, index: number) => {
544
- indexMap.set(key, index);
545
- });
546
-
547
- return indexMap;
548
- }, [observe]);
549
- const fragmentObserver = useFragmentKeyObserver(observe);
550
-
551
- const [changedData, setChangedData] = useState({
552
- count: fragmentObserver.count,
553
- lastObserveStr: observeStr,
554
- data: getReactiveFragmentMapData(data, observe)
555
- });
556
-
557
- useEffect(() => {
558
- // NOTE: I tried this with effect()
559
- // But that caused the render to happen 3 times more, I don't know why.
560
- // I only solved it by using useEffect()
561
-
562
- if (fragmentObserver.count !== changedData.count) {
563
- const dataToUpdate = changedData.data || data;
564
- let newData;
565
-
566
- for (const key of fragmentObserver.list) {
567
- const index = observeIndex.get(key);
568
- if (index === undefined || !dataToUpdate?.[index]) {
569
- continue;
570
- }
571
-
572
- const fragmentData = loadFragment(key);
573
- if (!fragmentData) {
574
- continue;
575
- }
576
-
577
- if (!newData) {
578
- newData = dataToUpdate.slice(0);
579
- }
580
-
581
- newData[index] = {
582
- ...newData[index],
583
- ...fragmentData,
584
- };
585
- }
586
-
587
- if (newData) {
588
- setChangedData({
589
- ...changedData,
590
- count: fragmentObserver.count,
591
- data: newData,
592
- });
593
- } else {
594
- setChangedData({
595
- ...changedData,
596
- count: fragmentObserver.count,
597
- });
598
- }
599
- }
600
- }, [fragmentObserver.count]);
601
-
602
- useEffect(() => {
603
- if (changedData.lastObserveStr !== observeStr) {
604
- setChangedData({
605
- ...changedData,
606
- data: getReactiveFragmentMapData(data, observe),
607
- lastObserveStr: observeStr,
608
- });
609
- }
610
- }, [observeStr]);
611
-
612
- if (changedData.lastObserveStr !== observeStr) {
613
- return getReactiveFragmentMapData(data, observe);
614
- }
615
-
616
- return changedData.data || data;
880
+ const fragmentName = `$${fragmentName_}`;
881
+ const observeStr = useMemo<string>(
882
+ () => data?.map((item) => `${fragmentName}:${item.id}`).join(',') || '',
883
+ [data, fragmentName],
884
+ );
885
+ const observe = useMemo<string[]>(
886
+ () => observeStr.split(',').filter(Boolean),
887
+ [observeStr],
888
+ );
889
+ const observeIndex = useMemo<Map<string, number>>(() => {
890
+ const indexMap = new Map<string, number>();
891
+
892
+ observe.forEach((key: string, index: number) => {
893
+ indexMap.set(key, index);
894
+ });
895
+
896
+ return indexMap;
897
+ }, [observe]);
898
+ const fragmentObserver = useFragmentKeyObserver(observe);
899
+
900
+ // Version stamp of the observed fragments at the last rebuild; see
901
+ // useReactiveFragment() for the rationale.
902
+ const lastBuildStampRef = useRef('');
903
+
904
+ const [changedData, setChangedData] = useState({
905
+ count: fragmentObserver.count,
906
+ lastObserveStr: observeStr,
907
+ queryUpdatedCount: qryObsCount,
908
+ data: getReactiveFragmentMapData(data, observe),
909
+ });
910
+
911
+ useEffect(() => {
912
+ // NOTE: I tried this with Preact's effect()
913
+ // But that caused the render to happen 3 times more, I don't know why.
914
+ // I only solved it by using useEffect()
915
+
916
+ const queryDataChanged = qryObsCount !== changedData.queryUpdatedCount;
917
+ const observedIdsChanged = changedData.lastObserveStr !== observeStr;
918
+ if (queryDataChanged || observedIdsChanged) {
919
+ lastBuildStampRef.current = getFragmentVersionStamp(observe);
920
+ setChangedData({
921
+ count: fragmentObserver.count,
922
+ data: getReactiveFragmentMapData(data, observe),
923
+ lastObserveStr: observeStr,
924
+ queryUpdatedCount: qryObsCount,
925
+ });
926
+ return;
927
+ }
928
+ if (fragmentObserver.count === changedData.count) {
929
+ return;
930
+ }
931
+
932
+ // Skip the rebuild when none of the observed fragments actually changed
933
+ // since the last build (e.g. a deep-equal realtime echo).
934
+ const observedStamp = getFragmentVersionStamp(observe);
935
+ if (observedStamp === lastBuildStampRef.current) {
936
+ return;
937
+ }
938
+
939
+ const dataToUpdate = changedData.data || data;
940
+ let newData: any;
941
+
942
+ for (const key of fragmentObserver.list) {
943
+ const index = observeIndex.get(key);
944
+ if (index === undefined || !dataToUpdate?.[index]) {
945
+ continue;
946
+ }
947
+
948
+ const fragmentData = loadFragment(key);
949
+ if (!fragmentData) {
950
+ continue;
951
+ }
952
+
953
+ if (!newData) {
954
+ newData = dataToUpdate.slice(0);
955
+ }
956
+
957
+ newData[index] = {
958
+ ...newData[index],
959
+ ...fragmentData,
960
+ };
961
+ }
962
+
963
+ lastBuildStampRef.current = observedStamp;
964
+
965
+ if (newData) {
966
+ setChangedData({
967
+ ...changedData,
968
+ count: fragmentObserver.count,
969
+ data: newData,
970
+ queryUpdatedCount: qryObsCount,
971
+ });
972
+ return;
973
+ }
974
+
975
+ setChangedData({
976
+ ...changedData,
977
+ count: fragmentObserver.count,
978
+ queryUpdatedCount: qryObsCount,
979
+ });
980
+ }, [fragmentObserver.count, observeStr, qryObsCount]);
981
+
982
+ if (
983
+ changedData.lastObserveStr !== observeStr ||
984
+ changedData.queryUpdatedCount !== qryObsCount
985
+ ) {
986
+ return getReactiveFragmentMapData(data, observe);
987
+ }
988
+
989
+ return changedData.data || data;
617
990
  }
618
991
 
619
992
  /**
@@ -621,170 +994,484 @@ export function useReactiveFragmentMap(
621
994
  */
622
995
 
623
996
  export function useMutation(
624
- mutation: any,
625
- options?: GraphQLMutationOptions,
997
+ mutation: any,
998
+ options?: GraphQLMutationOptions,
626
999
  ): GraphQLMutation {
1000
+ const {
1001
+ onCompleted,
1002
+ onError,
1003
+ openModalPopUp,
1004
+ initialError,
1005
+ checkMountedBeforeCallback,
1006
+ cachePolicy,
1007
+ } = options || {};
1008
+ const updateObservers = useUpdateObservers();
1009
+
1010
+ // No need to abort mutations
1011
+ // But bring it back if you want ability to "cancel"
1012
+ // const controller = useRef();
1013
+
1014
+ const tracker = useRef({
1015
+ mounted: true,
1016
+ timer: null as ReturnType<typeof setTimeout> | null,
1017
+ });
1018
+
1019
+ const [mtnValues, setMtnValues] = useState({
1020
+ variables: null as Record<string, any> | null,
1021
+ saving: false,
1022
+ data: null,
1023
+ error: initialError || (null as ServerErrorObj | null),
1024
+ mutationCount: 0,
1025
+ });
1026
+
1027
+ // Mounted hook
1028
+
1029
+ useEffect(() => {
1030
+ return () => {
1031
+ tracker.current.mounted = false;
1032
+ if (tracker.current.timer) {
1033
+ clearTimeout(tracker.current.timer);
1034
+ }
1035
+ };
1036
+ }, []);
1037
+
1038
+ // Mutate function for the client
1039
+
1040
+ const doMutate = async (
1041
+ graphqlOptions?: GraphQLRequestOptions,
1042
+ triedCount: number = 0,
1043
+ ) => {
1044
+ // No need to abort mutations
1045
+ // if (controller.current) {
1046
+ // controller.current.abort();
1047
+ // }
1048
+
1049
+ // No need to abort mutations
1050
+ // controller.current = new AbortController();
1051
+
1052
+ setMtnValues({
1053
+ ...mtnValues,
1054
+ variables: graphqlOptions?.variables || null,
1055
+ saving: true,
1056
+ });
1057
+
1058
+ const retryCount = options?.retryCount || 0;
1059
+ const retryDelay = getRetryDelay(triedCount);
1060
+
1061
+ const apiResult = await graphqlRequest(
1062
+ mutation,
1063
+ graphqlOptions?.variables,
1064
+ {
1065
+ cachePolicy,
1066
+ openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
1067
+ onCompleted: (data: any | null, error: ServerErrorObj | null) => {
1068
+ if (tracker.current.mounted) {
1069
+ setMtnValues({
1070
+ ...mtnValues,
1071
+ mutationCount: mtnValues.mutationCount + 1,
1072
+ saving: false,
1073
+ data: data.data || null,
1074
+ error,
1075
+ });
1076
+ }
1077
+
1078
+ if (data.data) {
1079
+ if (
1080
+ onCompleted &&
1081
+ (tracker.current.mounted || !checkMountedBeforeCallback)
1082
+ ) {
1083
+ // Do separate {mounted.current} check from outside
1084
+ onCompleted(data.data, error, graphqlOptions?.variables);
1085
+ }
1086
+ }
1087
+ },
1088
+ onError: (error: ServerErrorObj | null) => {
1089
+ if (tracker.current.mounted) {
1090
+ setMtnValues({
1091
+ ...mtnValues,
1092
+ saving: retryCount > triedCount,
1093
+ error,
1094
+ });
1095
+ }
1096
+
1097
+ if (
1098
+ onError &&
1099
+ retryCount <= triedCount &&
1100
+ (tracker.current.mounted || !checkMountedBeforeCallback)
1101
+ ) {
1102
+ onError(error, graphqlOptions?.variables);
1103
+ }
1104
+ },
1105
+ },
1106
+ null, // abort controller is not needed for mutations
1107
+ updateObservers,
1108
+ );
1109
+
1110
+ if (apiResult.aborted) {
1111
+ return apiResult;
1112
+ }
1113
+
1114
+ if (!apiResult.data && isServerErrorGQL(apiResult)) {
1115
+ if (retryCount > triedCount) {
1116
+ await delay(retryDelay);
1117
+ if (getENVVariable('NODE_ENV') === 'development') {
1118
+ console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
1119
+ }
1120
+
1121
+ return doMutate(graphqlOptions, triedCount + 1);
1122
+ } else if (getENVVariable('NODE_ENV') === 'development') {
1123
+ console.log(
1124
+ `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
1125
+ );
1126
+ }
1127
+ }
1128
+
1129
+ return apiResult;
1130
+ };
1131
+
1132
+ const mtnHandlers: GraphQLHandlers = {
1133
+ resetErrors: () => {
1134
+ setMtnValues({
1135
+ ...mtnValues,
1136
+ error: null,
1137
+ });
1138
+ },
1139
+ setError: (errorObj: SimpleErrorType) => {
1140
+ setMtnValues({
1141
+ ...mtnValues,
1142
+ error: {
1143
+ statusCode: 200,
1144
+ errorCode: 'custom_error',
1145
+ ...errorObj,
1146
+ },
1147
+ });
1148
+ },
1149
+ refetch: () => {
1150
+ const lastVariables = mtnValues.variables;
1151
+ return doMutate(lastVariables ? { variables: lastVariables } : undefined);
1152
+ },
1153
+ setSaving: (nextSaving: boolean, resetInMS?: number) => {
1154
+ setMtnValues({
1155
+ ...mtnValues,
1156
+ saving: nextSaving,
1157
+ });
1158
+
1159
+ if (nextSaving && resetInMS) {
1160
+ if (tracker.current.timer) {
1161
+ clearTimeout(tracker.current.timer);
1162
+ }
1163
+
1164
+ tracker.current.timer = setTimeout(() => {
1165
+ setMtnValues({
1166
+ ...mtnValues,
1167
+ saving: false,
1168
+ });
1169
+ }, resetInMS);
1170
+ }
1171
+ },
1172
+ };
1173
+
1174
+ return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
1175
+ }
1176
+
1177
+ /**
1178
+ * Imperatively warm the query cache for one query and variables pair.
1179
+ * Registers the in-flight promise in QRY_PROMISES under the same query key
1180
+ * useQuery() uses, so a hook mounting mid-flight awaits this request instead
1181
+ * of double-fetching. Prefetches are never aborted; a hook awaiting a shared
1182
+ * promise that resolves { aborted } would be left stuck in loading state.
1183
+ */
1184
+
1185
+ export function prefetchQuery(
1186
+ query: any,
1187
+ variables?: Record<string, any> | null,
1188
+ options?: {
1189
+ authToken?: string | null;
1190
+ updateObservers?: UpdateObserversFn;
1191
+ },
1192
+ ): Promise<any> {
1193
+ const queryName = query.definitions?.[0]?.name?.value;
1194
+ const variablesKey = makeVariablesKey(variables);
1195
+ const queryKey = `#${queryName}:${variablesKey}`;
1196
+
1197
+ // A complete cached result means there is nothing to warm
1198
+ const cachedResult = fetchCachedData(query, variablesKey);
1199
+ if (cachedResult) {
1200
+ return Promise.resolve(cachedResult);
1201
+ }
1202
+
1203
+ // A mounted hook or another prefetch already owns this request
1204
+ const pendingQuery = QRY_PROMISES.get(queryKey);
1205
+ if (pendingQuery) {
1206
+ return pendingQuery;
1207
+ }
1208
+
1209
+ const queryPromise = graphqlRequest(
1210
+ query,
1211
+ variables,
1212
+ {
1213
+ authToken: options?.authToken || undefined,
1214
+ },
1215
+ null,
1216
+ options?.updateObservers,
1217
+ );
1218
+ QRY_PROMISES.set(queryKey, queryPromise);
1219
+
1220
+ return queryPromise.finally(() => {
1221
+ if (QRY_PROMISES.get(queryKey) === queryPromise) {
1222
+ QRY_PROMISES.delete(queryKey);
1223
+ }
1224
+ });
1225
+ }
1226
+
1227
+ /**
1228
+ * Types; eager queries
1229
+ */
1230
+
1231
+ export interface EagerQueryInstruction {
1232
+ // Key in EAGER_QUERY_MAP; must equal the query's GraphQL operation name
1233
+ queryName: string;
1234
+ variables?: Record<string, any> | null;
1235
+ }
1236
+
1237
+ type EagerQueriesValues = {
1238
+ // True while an eager batch is being fetched
1239
+ loading: boolean;
1240
+ // True once at least one eager batch has finished
1241
+ done: boolean;
1242
+ // Raw results of the last finished batch, aligned with its instructions
1243
+ results: any[] | null;
1244
+ };
1245
+
1246
+ /**
1247
+ * Return the global tracking key for one eager query instruction; this is the
1248
+ * same "#queryName:variablesKey" key the query cache and QRY_PROMISES use.
1249
+ */
627
1250
 
628
- const { onCompleted, onError, openModalPopUp, initialError, checkMountedBeforeCallback } = options || {};
629
- const updateObservers = useUpdateObservers();
630
-
631
- // No need to abort mutations
632
- // But bring it back if you want ability to "cancel"
633
- // const controller = useRef();
634
-
635
- const tracker = useRef({
636
- mounted: true,
637
- timer: null as NodeJS.Timeout | null,
638
- });
639
-
640
- const [mtnValues, setMtnValues] = useState({
641
- variables: null as Record<string, any> | null,
642
- saving: false,
643
- data: null,
644
- error: initialError || null as ServerErrorObj | null,
645
- mutationCount: 0,
646
- });
647
-
648
- // Mounted hook
649
-
650
- useEffect(() => {
651
- return () => {
652
- tracker.current.mounted = false;
653
- if (tracker.current.timer) {
654
- clearTimeout(tracker.current.timer);
655
- }
656
- };
657
- }, []);
658
-
659
- // Mutate function for the client
660
-
661
- const doMutate = async (
662
- graphqlOptions?: GraphQLRequestOptions,
663
- triedCount: number = 0,
664
- ) => {
665
- // No need to abort mutations
666
- // if (controller.current) {
667
- // controller.current.abort();
668
- // }
669
-
670
- // No need to abort mutations
671
- // controller.current = new AbortController();
672
-
673
- setMtnValues({
674
- ...mtnValues,
675
- variables: graphqlOptions?.variables || null,
676
- saving: true,
677
- });
678
-
679
- const retryCount = options?.retryCount || 0;
680
- const retryDelay = getRetryDelay(triedCount);
681
-
682
- const apiResult = await graphqlRequest(
683
- mutation,
684
- graphqlOptions?.variables,
685
- {
686
- openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
687
- onCompleted: (data: any | null, error: ServerErrorObj | null) => {
688
- if (tracker.current.mounted) {
689
- setMtnValues({
690
- ...mtnValues,
691
- mutationCount: mtnValues.mutationCount + 1,
692
- saving: false,
693
- data: data.data || null,
694
- error,
695
- });
696
- }
697
-
698
- if (data.data) {
699
- if (onCompleted && (tracker.current.mounted || !checkMountedBeforeCallback)) {
700
- // Do separate {mounted.current} check from outside
701
- onCompleted(data.data, error, graphqlOptions?.variables);
702
- }
703
- }
704
- },
705
- onError: (error: ServerErrorObj | null) => {
706
- if (tracker.current.mounted) {
707
- setMtnValues({
708
- ...mtnValues,
709
- saving: retryCount > triedCount,
710
- error,
711
- });
712
- }
713
-
714
- if (onError && retryCount <= triedCount && (tracker.current.mounted || !checkMountedBeforeCallback)) {
715
- onError(error, graphqlOptions?.variables);
716
- }
717
- },
718
- },
719
- null, // abort controller is not needed for mutations
720
- updateObservers
721
- );
722
-
723
- if (apiResult.aborted) {
724
- return apiResult;
725
- }
726
-
727
- if (!apiResult.data && isServerErrorGQL(apiResult)) {
728
- if (retryCount > triedCount) {
729
- await delay(retryDelay);
730
- if (getENVVariable('NODE_ENV') === 'development') {
731
- console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
732
- }
733
-
734
- return doMutate(graphqlOptions, triedCount + 1);
735
- } else if (getENVVariable('NODE_ENV') === 'development') {
736
- console.log(
737
- `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
738
- );
739
- }
740
- }
741
-
742
- return apiResult;
743
- };
744
-
745
- const mtnHandlers: GraphQLHandlers = {
746
- resetErrors: () => {
747
- setMtnValues({
748
- ...mtnValues,
749
- error: null,
750
- });
751
- },
752
- setError: (errorObj: SimpleErrorType) => {
753
- setMtnValues({
754
- ...mtnValues,
755
- error: {
756
- statusCode: 200,
757
- errorCode: 'custom_error',
758
- ...errorObj,
759
- },
760
- });
761
- },
762
- refetch: () => {
763
- const lastVariables = mtnValues.variables;
764
- return doMutate(lastVariables ? { variables: lastVariables } : undefined);
765
- },
766
- setSaving: (nextSaving: boolean, resetInMS?: number) => {
767
- setMtnValues({
768
- ...mtnValues,
769
- saving: nextSaving,
770
- });
771
-
772
- if (nextSaving && resetInMS) {
773
- if (tracker.current.timer) {
774
- clearTimeout(tracker.current.timer);
775
- }
776
-
777
- tracker.current.timer = setTimeout(() => {
778
- setMtnValues({
779
- ...mtnValues,
780
- saving: false,
781
- });
782
- }, resetInMS);
783
- }
784
- }
785
- };
786
-
787
- return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
1251
+ function makeEagerQueryKey(instruction: EagerQueryInstruction) {
1252
+ return `#${instruction.queryName}:${makeVariablesKey(instruction.variables)}`;
1253
+ }
1254
+
1255
+ /**
1256
+ * Resolve one instruction's GQL query document from the eager query registry.
1257
+ */
1258
+
1259
+ function getEagerQuery(queryName: string) {
1260
+ const query = EAGER_QUERY_MAP[queryName];
1261
+
1262
+ if (getENVVariable('NODE_ENV') === 'development') {
1263
+ if (!query) {
1264
+ console.warn(
1265
+ `useEagerQueries() has no registered query named "${queryName}". Add it to EAGER_QUERY_MAP.`,
1266
+ );
1267
+ } else {
1268
+ const operationName = query.definitions?.find(
1269
+ (def: any) => def.kind === 'OperationDefinition',
1270
+ )?.name?.value;
1271
+
1272
+ if (operationName !== queryName) {
1273
+ console.warn(
1274
+ `useEagerQueries() registry key "${queryName}" does not match its GraphQL operation name "${operationName}"; ` +
1275
+ 'the warmed cache key will never be read by useQuery().',
1276
+ );
1277
+ }
1278
+ }
1279
+ }
1280
+
1281
+ return query || null;
1282
+ }
1283
+
1284
+ /**
1285
+ * Imperatively warm the query cache for one registered eager query by name.
1286
+ * Used by hover-style eager loaders (e.g. <EagerLoad>); shares the same
1287
+ * registry, cache checks and global in-flight tracking as useEagerQueries().
1288
+ * Returns null when the query name is not registered in EAGER_QUERY_MAP.
1289
+ */
1290
+
1291
+ export function prefetchEagerQuery(
1292
+ queryName: string,
1293
+ variables?: Record<string, any> | null,
1294
+ options?: {
1295
+ updateObservers?: UpdateObserversFn;
1296
+ },
1297
+ ): Promise<any> | null {
1298
+ const query = getEagerQuery(queryName);
1299
+
1300
+ if (!query) {
1301
+ return null;
1302
+ }
1303
+
1304
+ return prefetchQuery(query, variables, {
1305
+ updateObservers: options?.updateObservers,
1306
+ });
1307
+ }
1308
+
1309
+ /**
1310
+ * Eagerly fetch many queries by name so a later useQuery() mount with the
1311
+ * same query and variables resolves instantly from the query cache.
1312
+ *
1313
+ * Fetch-once semantics: while {counter} is nullish or 0, one eager batch runs
1314
+ * when {instructions} first becomes a non-empty array, and later instruction
1315
+ * changes never refetch. Advancing {counter} together with new instructions
1316
+ * allows one more batch, but only after the previous batch finished loading
1317
+ * (a counter change mid-flight is rejected, not queued).
1318
+ *
1319
+ * Global single-fetch guarantee: prefetchQuery() tracks every in-flight
1320
+ * request in QRY_PROMISES keyed by query name + variables, so a second
1321
+ * component eagerly fetching the same query joins the first component's
1322
+ * in-flight request instead of fetching again, an already-cached result is
1323
+ * returned without any request, and a useQuery() hook mounting for the same
1324
+ * key awaits the eager promise instead of double-fetching.
1325
+ *
1326
+ * The eager requests are intentionally NOT aborted on unmount: their results
1327
+ * must still land in the query cache after navigation.
1328
+ */
1329
+
1330
+ export function useEagerQueries(
1331
+ instructions?: EagerQueryInstruction[] | null,
1332
+ counter?: number | null,
1333
+ ): EagerQueriesValues {
1334
+ const updateObservers = useUpdateObservers();
1335
+ const tracker = useRef({
1336
+ mounted: true,
1337
+ started: false,
1338
+ loading: false,
1339
+ counter: 0,
1340
+ updateObservers,
1341
+ });
1342
+ tracker.current.updateObservers = updateObservers;
1343
+
1344
+ const [eagerValues, setEagerValues] = useState<EagerQueriesValues>({
1345
+ loading: false,
1346
+ done: false,
1347
+ results: null,
1348
+ });
1349
+
1350
+ // An empty batch means the caller's source data is not ready yet, so it
1351
+ // must not consume the once-only fetch
1352
+ const instructionsKey = instructions?.length
1353
+ ? instructions.map(makeEagerQueryKey).join('|')
1354
+ : '';
1355
+
1356
+ // Mounted hook; only state updates stop on unmount, never the fetches
1357
+
1358
+ useEffect(() => {
1359
+ tracker.current.mounted = true;
1360
+
1361
+ return () => {
1362
+ tracker.current.mounted = false;
1363
+ };
1364
+ }, []);
1365
+
1366
+ // Fetch when the first non-empty batch arrives, or when a later batch
1367
+ // arrives with an advanced counter
1368
+
1369
+ useEffect(() => {
1370
+ const counterValue = counter || 0;
1371
+
1372
+ if (!instructionsKey || !instructions?.length) {
1373
+ return;
1374
+ }
1375
+
1376
+ if (tracker.current.loading) {
1377
+ // The previous eager batch is still in flight; reject the new batch
1378
+ return;
1379
+ }
1380
+
1381
+ if (tracker.current.started && counterValue === tracker.current.counter) {
1382
+ // Without a counter change, eager fetching only ever happens once
1383
+ return;
1384
+ }
1385
+
1386
+ tracker.current.started = true;
1387
+ tracker.current.loading = true;
1388
+ tracker.current.counter = counterValue;
1389
+
1390
+ setEagerValues((currentValues: EagerQueriesValues) => ({
1391
+ ...currentValues,
1392
+ loading: true,
1393
+ }));
1394
+
1395
+ Promise.all(
1396
+ instructions.map((instruction) => {
1397
+ const query = getEagerQuery(instruction.queryName);
1398
+
1399
+ if (!query) {
1400
+ return Promise.resolve(null);
1401
+ }
1402
+
1403
+ return prefetchQuery(query, instruction.variables, {
1404
+ updateObservers: tracker.current.updateObservers,
1405
+ });
1406
+ }),
1407
+ ).then(
1408
+ (results) => {
1409
+ tracker.current.loading = false;
1410
+
1411
+ if (tracker.current.mounted) {
1412
+ setEagerValues({
1413
+ loading: false,
1414
+ done: true,
1415
+ results,
1416
+ });
1417
+ }
1418
+ },
1419
+ () => {
1420
+ // prefetchQuery() resolves errors into { error } and never rejects;
1421
+ // this only guards against the tracker being stuck in loading state
1422
+ tracker.current.loading = false;
1423
+
1424
+ if (tracker.current.mounted) {
1425
+ setEagerValues((currentValues: EagerQueriesValues) => ({
1426
+ ...currentValues,
1427
+ loading: false,
1428
+ }));
1429
+ }
1430
+ },
1431
+ );
1432
+ }, [instructionsKey, counter]);
1433
+
1434
+ return eagerValues;
1435
+ }
1436
+
1437
+ /**
1438
+ * Keep the hydration snapshot immutable. Query cache changes already reach
1439
+ * this hook through its keyed query observer and local request state; React's
1440
+ * external-store consistency pass is only needed to bridge SSR hydration.
1441
+ */
1442
+ function subscribeHydrationSafeQuerySnapshot(
1443
+ _onStoreChange: () => void,
1444
+ ): () => void {
1445
+ return () => {};
1446
+ }
1447
+
1448
+ /**
1449
+ * Report that browser cache reads are available outside hydration.
1450
+ */
1451
+ function getClientQuerySnapshotReady(): boolean {
1452
+ return true;
1453
+ }
1454
+
1455
+ /**
1456
+ * Keep server rendering and the first hydration render cache-free.
1457
+ */
1458
+ function getServerQuerySnapshotReady(): boolean {
1459
+ return false;
1460
+ }
1461
+
1462
+ /**
1463
+ * Read one validated query cache snapshot without exposing browser-restored
1464
+ * data until React has completed its hydration consistency check.
1465
+ */
1466
+ function useHydrationSafeQueryCacheSnapshot(query: any, variablesKey: string) {
1467
+ const ready = useSyncExternalStore(
1468
+ subscribeHydrationSafeQuerySnapshot,
1469
+ getClientQuerySnapshotReady,
1470
+ getServerQuerySnapshotReady,
1471
+ );
1472
+ const data = ready ? fetchCachedData(query, variablesKey) : null;
1473
+
1474
+ return { data, ready };
788
1475
  }
789
1476
 
790
1477
  /**
@@ -792,310 +1479,717 @@ export function useMutation(
792
1479
  */
793
1480
 
794
1481
  export function useQuery(
795
- query: any,
796
- options?: GraphQLQueryOptions,
1482
+ query: any,
1483
+ options?: GraphQLQueryOptions,
797
1484
  ): GraphQLQueryResult {
798
- const { onCompleted, onError, openModalPopUp, variables, cacheMap, skip, eagerFragmentKeyMap, doTest } = options || {};
799
- const variablesKey = makeVariablesKey(variables);
800
- const connectedToServer = useConnectedToServerValue();
801
- const screenIsFocused = useScreenIsFocusedValue();
802
- const updateObservers = useUpdateObservers();
803
-
804
- // useQuery() assumes query is a single graphql query (and not a multi/chain)
805
- // Multiple queries can be chained using this hook,
806
- // but only the first query is used for tracking reactivity.
807
- const queryName = query.definitions?.[0]?.name?.value;
808
- const queryKey = `#${queryName}:${variablesKey}`;
809
-
810
- const tracker = useRef({
811
- unique: null as string | null,
812
- abortCtrl: null as AbortController | null,
813
- reconnectedAt: null as number | null,
814
- json: '',
815
- init: false
816
- });
817
-
818
- // check if p.updatedCount is needed
819
-
820
- const [qryValues, setQryValues] = useState({
821
- data: null as any,
822
- variables,
823
- loading: false,
824
- error: null as ServerErrorObj | null,
825
- lastUpdatedCount: 0,
826
- lastRefreshTriggerTime: '',
827
- });
828
- const qryValuesVariablesKey = makeVariablesKey(qryValues.variables);
829
-
830
- const { updatedCount, forceRefetch, resetOnlyTime, qryReset: { triggerTime, refreshTime } } = useWatchQuery(
831
- query,
832
- variablesKey,
833
- qryValues.lastUpdatedCount,
834
- qryValues.loading
835
- );
836
-
837
- const [queryOutput, setQueryOutput] = useState({ queryKey, refreshTime, data: null });
838
-
839
- // Query function for the client
840
- // NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
841
-
842
- const doQuery = async (queryVariables?: any, triedCount: number = 0) => {
843
-
844
- const currentHookId = QRY_TRACKER.get(queryKey);
845
- if (!currentHookId) {
846
- QRY_TRACKER.set(queryKey, tracker.current.unique);
847
- } else if (currentHookId) {
848
- // This query is being fetched already, so do nothing
849
- // This can happen in 2 ways;
850
- // 1. This hook is used to doQuery() while doQuery() is alerady in progress (loading)
851
- // 2. useWatchQuery() caused 2 hooks with same query to be called at once
852
- return;
853
- }
854
-
855
- if (tracker.current.abortCtrl && qryValues.loading) {
856
- // doLog(query, 'Query component [$0] is being aborted before being refetched.');
857
- // console.log('ABORT:', queryKey, tracker.current.unique);
858
- tracker.current.abortCtrl.abort({
859
- name: 'AbortError',
860
- message: `Hook for ${queryKey} has aborted because the [query refetched before the previous one ended].`
861
- });
862
- }
863
-
864
- tracker.current.abortCtrl = new AbortController();
865
-
866
- setQryValues({
867
- ...qryValues,
868
- loading: true,
869
- });
870
-
871
- const retryCount = options?.retryCount || 0;
872
- const retryDelay = getRetryDelay(triedCount);
873
- const qryVariables = queryVariables || variables;
874
- // const qryName = query.definitions?.[0]?.name?.value;
875
-
876
- // doLog(query, 'Query component [$0] is being refetched.');
877
-
878
- const apiResult = await graphqlRequest(
879
- query,
880
- qryVariables,
881
- {
882
- openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
883
- cacheMap,
884
- onCompleted: (data: any | null, error: ServerErrorObj | null) => {
885
- if (data.data) {
886
- setQryValues({
887
- ...qryValues,
888
- variables: qryVariables,
889
- data: data.data,
890
- loading: false,
891
- error,
892
- });
893
-
894
- if (onCompleted) {
895
- onCompleted(data.data, error, qryVariables);
896
- }
897
-
898
- removeStaleCache();
899
- tracker.current.reconnectedAt = Date.now();
900
- }
901
-
902
- unsetQueryTracker(queryKey, tracker.current.unique);
903
- },
904
- onError: (error: ServerErrorObj | null) => {
905
- setQryValues({
906
- ...qryValues,
907
- variables: qryVariables,
908
- loading: retryCount > triedCount,
909
- error,
910
- });
911
-
912
- if (onError && retryCount <= triedCount) {
913
- onError(error, qryVariables);
914
- }
915
-
916
- unsetQueryTracker(queryKey, tracker.current.unique);
917
- },
918
- },
919
- tracker.current.abortCtrl.signal,
920
- updateObservers
921
- );
922
-
923
- if (apiResult.aborted) {
924
- return apiResult;
925
- }
926
-
927
- if (!apiResult.data && isServerErrorGQL(apiResult)) {
928
- if (retryCount > triedCount) {
929
- await delay(retryDelay);
930
- if (getENVVariable('NODE_ENV') === 'development') {
931
- console.log(`retrying query... ${triedCount + 1} / ${retryCount}`);
932
- }
933
-
934
- return doQuery(queryVariables, triedCount + 1);
935
- } else if (getENVVariable('NODE_ENV') === 'development') {
936
- console.log(
937
- `query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
938
- );
939
- }
940
- }
941
-
942
- return apiResult;
943
- };
944
-
945
- // Mount & unmount
946
-
947
- useEffect(() => {
948
- if (!tracker.current.unique) {
949
- tracker.current.unique = Date.now().toString(36) + Math.random().toString(36).substring(2);
950
- }
951
-
952
- return () => {
953
- unsetQueryTracker(queryKey, tracker.current.unique);
954
- };
955
- }, [queryKey]);
956
-
957
-
958
- useEffect(() => {
959
- return () => {
960
- if (tracker.current.abortCtrl) {
961
- // console.log('UMOUNTED:', queryKey, tracker.current.unique);
962
- tracker.current.abortCtrl.abort({
963
- name: 'AbortError',
964
- message: `Hook for ${queryKey} has aborted because [the component unmounted].`
965
- });
966
- }
967
- };
968
- }, []);
969
-
970
- // Refetch when variables, skip status or query observer changes
971
-
972
- // const isTest = queryName === 'logEntries';
973
-
974
- useEffect(() => {
975
- // isTest && console.log('useQuery check:', refreshTime, updatedCount, qryValues.lastUpdatedCount);
976
-
977
- if (
978
- !skip && (
979
- (triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime) ||
980
- updatedCount !== qryValues.lastUpdatedCount ||
981
- variablesKey !== qryValuesVariablesKey ||
982
- !checkDataCompleteness(qryValues.data, query)
983
- )
984
- ) {
985
- const cachedResult = fetchCachedData(query, variablesKey, updateObservers);
986
- if (cachedResult) {
987
- setQryValues({
988
- ...qryValues,
989
- variables,
990
- data: cachedResult,
991
- error: null,
992
- loading: false, // IMPORTANT: must be false here
993
- lastRefreshTriggerTime: triggerTime,
994
- lastUpdatedCount: updatedCount || 0,
995
- });
996
-
997
- if (forceRefetch && !qryValues.loading) {
998
- doQuery();
999
- // isTest && console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
1000
- // console.log('::', variablesKey, skip, updatedCount);
1001
- }
1002
-
1003
- } else if (!qryValues.loading) {
1004
- // isTest && console.log(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
1005
- doQuery();
1006
- }
1007
- }
1008
- }, [variablesKey, qryValuesVariablesKey, qryValues.loading, skip, updatedCount, triggerTime]);
1009
-
1010
- // Refetch when the app reconnects and has no data
1011
-
1012
- const withoutData = qryValues.data === null;
1013
- const reconnectedWithoutData = !skip && withoutData && !qryValues.loading && connectedToServer;
1014
-
1015
- useEffect(() => {
1016
- if (connectedToServer && screenIsFocused && !skip) {
1017
- const now = Date.now();
1018
-
1019
- let timeDiff, timeThresh;
1020
- if (reconnectedWithoutData) {
1021
- timeDiff = tracker.current.reconnectedAt ? now - tracker.current.reconnectedAt : Infinity;
1022
- timeThresh = 5000;
1023
- } else {
1024
- timeDiff = tracker.current.reconnectedAt ? now - tracker.current.reconnectedAt : -Infinity;
1025
- timeThresh = QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
1026
- }
1027
-
1028
- // console.log('>>', queryName, timeDiff, timeThresh, timeDiff > timeThresh);
1029
-
1030
- if (
1031
- tracker.current.init &&
1032
- timeDiff > timeThresh
1033
- ) {
1034
- // console.log('query again:', queryName, timeDiff);
1035
- // doLog(query, reconnectedWithoutData + ' / ' + skip + ' / ' + withoutData + ' / ' + !qryValues.loading);
1036
- tracker.current.reconnectedAt = now;
1037
- doQuery();
1038
- } else {
1039
- tracker.current.init = true;
1040
- }
1041
- }
1042
- }, [reconnectedWithoutData, screenIsFocused]);
1043
-
1044
- const refetch = useCallback(() => {
1045
- return doQuery();
1046
- }, [doQuery]);
1047
-
1048
- const fetchMore = useCallback(async(obj: GraphQLRequestOptions): Promise<any> => {
1049
- const result = await doQuery(obj?.variables);
1050
-
1051
- if (result.error) {
1052
- return {
1053
- ...result,
1054
- error: normalizeServerError(result.error),
1055
- };
1056
- }
1057
-
1058
- return result;
1059
- }, [doQuery, skip]);
1060
-
1061
- const qryValuesMatchVariables = variablesKey === qryValuesVariablesKey;
1062
- const queryData = loadDataFromCache(
1063
- qryValuesMatchVariables ? qryValues.data : null,
1064
- query,
1065
- variablesKey,
1066
- cacheMap,
1067
- eagerFragmentKeyMap,
1068
- );
1069
-
1070
- useEffect(() => {
1071
- const jsonStr = queryKey + '|' + JSON.stringify(queryData[queryName]);
1072
- if (tracker.current.json === jsonStr) {
1073
- return;
1074
- }
1075
-
1076
- tracker.current.json = jsonStr;
1077
-
1078
- // This makes queryKey and data always in sync
1079
- setQueryOutput({
1080
- queryKey,
1081
- refreshTime,
1082
- data: queryData,
1083
- });
1084
- }, [queryKey, refreshTime, queryData[queryName]]);
1085
-
1086
- return {
1087
- ...qryValues,
1088
- queryName,
1089
- queryKey: queryOutput.queryKey,
1090
- data: queryOutput.data || queryData,
1091
- refreshTime: queryOutput.refreshTime,
1092
- resetOnlyTime,
1093
- variablesKey,
1094
- refetch,
1095
- fetchMore,
1096
- updatedCount,
1097
- updateObservers,
1098
- connectedToServer,
1099
- screenIsFocused,
1100
- };
1485
+ const {
1486
+ authToken,
1487
+ onCompleted,
1488
+ onError,
1489
+ openModalPopUp,
1490
+ variables,
1491
+ cacheMap,
1492
+ skip,
1493
+ eagerFragmentKeyMap,
1494
+ shouldAcceptResult,
1495
+ persistTime,
1496
+ } = options || {};
1497
+ const variablesKey = makeVariablesKey(variables);
1498
+ const connectedToServer = useConnectedToServerValue();
1499
+ const optimisticConnectedToServer = useOptimisticConnectedToServerValue();
1500
+ const screenIsFocused = useScreenIsFocusedValue();
1501
+ const updateObservers = useUpdateObservers();
1502
+
1503
+ // useQuery() assumes query is a single graphql query (and not a multi/chain)
1504
+ // Multiple queries can be chained using this hook,
1505
+ // but only the first query is used for tracking reactivity.
1506
+ const queryName = query.definitions?.[0]?.name?.value;
1507
+ const queryKey = `#${queryName}:${variablesKey}`;
1508
+
1509
+ const tracker = useRef({
1510
+ unique: makeQueryHookId(),
1511
+ abortCtrl: null as AbortController | null,
1512
+ activeQueryKey: null as string | null,
1513
+ ownQueryObserverCount: 0,
1514
+ reconnectedAt: null as number | null,
1515
+ transientRetryAttemptCount: 0,
1516
+ mounted: true,
1517
+ init: false,
1518
+ });
1519
+ const trackedUpdateObservers = useCallback(
1520
+ (args: UpdateDataObserverArgs) => {
1521
+ if (
1522
+ args.queryId &&
1523
+ args.queryId === tracker.current.activeQueryKey &&
1524
+ !args.forceRefetch &&
1525
+ !args.resetOnly
1526
+ ) {
1527
+ tracker.current.ownQueryObserverCount += 1;
1528
+ }
1529
+
1530
+ updateObservers(args);
1531
+ },
1532
+ [updateObservers],
1533
+ );
1534
+
1535
+ // check if p.updatedCount is needed
1536
+
1537
+ const [qryValues, setQryValues] = useState<GraphQLQueryValues>({
1538
+ data: null as any,
1539
+ variables,
1540
+ loading: false,
1541
+ error: null as ServerErrorObj | null,
1542
+ lastUpdatedCount: 0,
1543
+ lastRefreshTriggerTime: '',
1544
+ });
1545
+
1546
+ const qryValuesVariablesKey = makeVariablesKey(qryValues.variables);
1547
+
1548
+ const {
1549
+ updatedCount,
1550
+ forceRefetch,
1551
+ resetOnlyTime,
1552
+ qryReset: { triggerTime, refreshTime },
1553
+ } = useWatchQuery(
1554
+ query,
1555
+ variablesKey,
1556
+ qryValues.lastUpdatedCount,
1557
+ qryValues.loading,
1558
+ );
1559
+ const { data: cachedQuerySnapshot, ready: queryCacheSnapshotReady } =
1560
+ useHydrationSafeQueryCacheSnapshot(query, variablesKey);
1561
+ const qryValuesMatchVariables = variablesKey === qryValuesVariablesKey;
1562
+ const effectiveQueryData =
1563
+ cachedQuerySnapshot || (qryValuesMatchVariables ? qryValues.data : null);
1564
+ const effectiveQueryDataIsComplete = checkDataCompleteness(
1565
+ effectiveQueryData,
1566
+ query,
1567
+ );
1568
+
1569
+ // Query function for the client
1570
+ // NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
1571
+
1572
+ const doQuery = async (
1573
+ queryVariables?: any,
1574
+ triedCount: number = 0,
1575
+ rejectedResultCount: number = 0,
1576
+ silentRevalidate?: boolean,
1577
+ ): Promise<any> => {
1578
+ const qryVariables = queryVariables || variables;
1579
+ const qryVariablesKey = makeVariablesKey(qryVariables);
1580
+ const qryQueryKey = `#${queryName}:${qryVariablesKey}`;
1581
+ const pendingQuery = QRY_PROMISES.get(qryQueryKey);
1582
+
1583
+ if (pendingQuery) {
1584
+ if (!silentRevalidate) {
1585
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1586
+ ...currentValues,
1587
+ loading: true,
1588
+ }));
1589
+ }
1590
+
1591
+ return pendingQuery.then((apiResult) => {
1592
+ if (apiResult?.aborted) {
1593
+ if (!tracker.current.mounted) {
1594
+ return apiResult;
1595
+ }
1596
+
1597
+ // Retire the aborted owner's global slots before retrying. A warm
1598
+ // cached result is complete, so no later state transition would
1599
+ // otherwise retrigger this silent stale-cache revalidation.
1600
+ if (QRY_PROMISES.get(qryQueryKey) === pendingQuery) {
1601
+ QRY_PROMISES.delete(qryQueryKey);
1602
+ QRY_TRACKER.delete(qryQueryKey);
1603
+ }
1604
+
1605
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1606
+ ...currentValues,
1607
+ loading: false,
1608
+ }));
1609
+
1610
+ return doQuery(
1611
+ queryVariables,
1612
+ triedCount,
1613
+ rejectedResultCount,
1614
+ silentRevalidate,
1615
+ );
1616
+ }
1617
+
1618
+ if (!tracker.current.mounted) {
1619
+ return apiResult;
1620
+ }
1621
+
1622
+ const cachedResult = fetchCachedData(query, qryVariablesKey);
1623
+ const data =
1624
+ cachedResult || getQueryDataFromAPIResult(queryName, apiResult);
1625
+
1626
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1627
+ ...currentValues,
1628
+ variables: qryVariables,
1629
+ data: data || currentValues.data,
1630
+ loading: false,
1631
+ error: apiResult?.error || null,
1632
+ lastUpdatedCount: getNextQueryLastUpdatedCount(
1633
+ currentValues.lastUpdatedCount,
1634
+ updatedCount,
1635
+ 0,
1636
+ ),
1637
+ lastRefreshTriggerTime:
1638
+ triggerTime || currentValues.lastRefreshTriggerTime,
1639
+ }));
1640
+
1641
+ return apiResult;
1642
+ });
1643
+ }
1644
+
1645
+ const currentHookId = QRY_TRACKER.get(qryQueryKey);
1646
+ if (!currentHookId) {
1647
+ QRY_TRACKER.set(qryQueryKey, tracker.current.unique);
1648
+ } else if (currentHookId) {
1649
+ // This query is being fetched already, so do nothing
1650
+ // This can happen in 2 ways;
1651
+ // 1. This hook is used to doQuery() while doQuery() is alerady in progress (loading)
1652
+ // 2. useWatchQuery() caused 2 hooks with same query to be called at once
1653
+ return { loading: true, skipped: true };
1654
+ }
1655
+
1656
+ if (tracker.current.abortCtrl && qryValues.loading) {
1657
+ // doLog(query, 'Query component [$0] is being aborted before being refetched.');
1658
+ // console.log('ABORT:', queryKey, tracker.current.unique);
1659
+ tracker.current.abortCtrl.abort({
1660
+ name: 'AbortError',
1661
+ message: `Hook for ${qryQueryKey} has aborted because the [query refetched before the previous one ended].`,
1662
+ });
1663
+ }
1664
+
1665
+ tracker.current.abortCtrl = new AbortController();
1666
+ tracker.current.activeQueryKey = qryQueryKey;
1667
+ tracker.current.ownQueryObserverCount = 0;
1668
+
1669
+ if (!silentRevalidate) {
1670
+ // Background stale-while-revalidate keeps loading=false so consumers
1671
+ // keep rendering the served cached data without spinners
1672
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1673
+ ...currentValues,
1674
+ loading: true,
1675
+ }));
1676
+ }
1677
+
1678
+ const retryCount = options?.retryCount || 0;
1679
+ const retryDelay = getRetryDelay(triedCount);
1680
+ // const qryName = query.definitions?.[0]?.name?.value;
1681
+
1682
+ // doLog(query, 'Query component [$0] is being refetched.');
1683
+
1684
+ const queryPromise = graphqlRequest(
1685
+ query,
1686
+ qryVariables,
1687
+ {
1688
+ authToken: authToken || undefined,
1689
+ openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
1690
+ cacheMap,
1691
+ onCompleted: (data: any | null, error: ServerErrorObj | null) => {
1692
+ if (data.data) {
1693
+ const ownQueryObserverCount = tracker.current.ownQueryObserverCount;
1694
+ const completedData =
1695
+ fetchCachedData(query, qryVariablesKey) || data.data;
1696
+ tracker.current.ownQueryObserverCount = 0;
1697
+
1698
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1699
+ ...currentValues,
1700
+ variables: qryVariables,
1701
+ // Prime and retain the validated normalized snapshot while the
1702
+ // network result is already off the navigation-critical path.
1703
+ data: completedData,
1704
+ loading: false,
1705
+ error,
1706
+ lastUpdatedCount: getNextQueryLastUpdatedCount(
1707
+ currentValues.lastUpdatedCount,
1708
+ updatedCount,
1709
+ ownQueryObserverCount,
1710
+ ),
1711
+ lastRefreshTriggerTime:
1712
+ triggerTime || currentValues.lastRefreshTriggerTime,
1713
+ }));
1714
+
1715
+ if (onCompleted) {
1716
+ onCompleted(data.data, error, qryVariables);
1717
+ }
1718
+
1719
+ removeStaleCache();
1720
+ tracker.current.reconnectedAt = Date.now();
1721
+ }
1722
+
1723
+ tracker.current.activeQueryKey = null;
1724
+ unsetQueryTracker(qryQueryKey, tracker.current.unique);
1725
+ },
1726
+ onError: (error: ServerErrorObj | null) => {
1727
+ tracker.current.activeQueryKey = null;
1728
+ tracker.current.ownQueryObserverCount = 0;
1729
+
1730
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1731
+ ...currentValues,
1732
+ variables: qryVariables,
1733
+ loading: retryCount > triedCount,
1734
+ error,
1735
+ lastUpdatedCount: getNextQueryLastUpdatedCount(
1736
+ currentValues.lastUpdatedCount,
1737
+ updatedCount,
1738
+ 0,
1739
+ ),
1740
+ lastRefreshTriggerTime:
1741
+ triggerTime || currentValues.lastRefreshTriggerTime,
1742
+ }));
1743
+
1744
+ if (onError && retryCount <= triedCount) {
1745
+ onError(error, qryVariables);
1746
+ }
1747
+
1748
+ unsetQueryTracker(qryQueryKey, tracker.current.unique);
1749
+ },
1750
+ shouldAcceptResult,
1751
+ },
1752
+ tracker.current.abortCtrl.signal,
1753
+ trackedUpdateObservers,
1754
+ );
1755
+ QRY_PROMISES.set(qryQueryKey, queryPromise);
1756
+
1757
+ let apiResult: any;
1758
+ try {
1759
+ apiResult = await queryPromise;
1760
+ } finally {
1761
+ if (QRY_PROMISES.get(qryQueryKey) === queryPromise) {
1762
+ QRY_PROMISES.delete(qryQueryKey);
1763
+ }
1764
+ }
1765
+
1766
+ if (apiResult.aborted) {
1767
+ tracker.current.activeQueryKey = null;
1768
+ tracker.current.ownQueryObserverCount = 0;
1769
+ unsetQueryTracker(qryQueryKey, tracker.current.unique);
1770
+ return apiResult;
1771
+ }
1772
+
1773
+ if (apiResult.__clientResultRejected) {
1774
+ tracker.current.activeQueryKey = null;
1775
+ tracker.current.ownQueryObserverCount = 0;
1776
+ unsetQueryTracker(qryQueryKey, tracker.current.unique);
1777
+ const rejectedResultRetryCount = Math.min(
1778
+ 2,
1779
+ Math.max(0, Math.floor(options?.rejectedResultRetryCount || 0)),
1780
+ );
1781
+ if (rejectedResultCount < rejectedResultRetryCount) {
1782
+ tracker.current.abortCtrl = null;
1783
+ return doQuery(queryVariables, triedCount, rejectedResultCount + 1);
1784
+ }
1785
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1786
+ ...currentValues,
1787
+ loading: false,
1788
+ lastUpdatedCount: getNextQueryLastUpdatedCount(
1789
+ currentValues.lastUpdatedCount,
1790
+ updatedCount,
1791
+ 0,
1792
+ ),
1793
+ }));
1794
+ return apiResult;
1795
+ }
1796
+
1797
+ if (!apiResult.data && isServerErrorGQL(apiResult)) {
1798
+ if (retryCount > triedCount) {
1799
+ await delay(retryDelay);
1800
+ if (getENVVariable('NODE_ENV') === 'development') {
1801
+ console.log(`retrying query... ${triedCount + 1} / ${retryCount}`);
1802
+ }
1803
+
1804
+ return doQuery(queryVariables, triedCount + 1);
1805
+ } else if (getENVVariable('NODE_ENV') === 'development') {
1806
+ console.log(
1807
+ `query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
1808
+ );
1809
+ }
1810
+ }
1811
+
1812
+ return apiResult;
1813
+ };
1814
+
1815
+ /*
1816
+ * Reassess hydration-safe warm snapshots when their activation inputs
1817
+ * change. The query-keyed promise registry deduplicates overlapping loads.
1818
+ */
1819
+ useEffect(() => {
1820
+ if (
1821
+ !queryCacheSnapshotReady ||
1822
+ !cachedQuerySnapshot ||
1823
+ skip ||
1824
+ !optimisticConnectedToServer
1825
+ ) {
1826
+ return;
1827
+ }
1828
+
1829
+ if (forceRefetch || resetOnlyTime || triggerTime) {
1830
+ return;
1831
+ }
1832
+
1833
+ if (
1834
+ updatedCount !== qryValues.lastUpdatedCount ||
1835
+ variablesKey !== qryValuesVariablesKey
1836
+ ) {
1837
+ return;
1838
+ }
1839
+
1840
+ tracker.current.reconnectedAt =
1841
+ getQueryLastFetchedAt(queryKey) || Date.now();
1842
+
1843
+ if (queryDataIsStale(queryName, queryKey, persistTime)) {
1844
+ void doQuery(undefined, 0, 0, true);
1845
+ }
1846
+ }, [
1847
+ cachedQuerySnapshot,
1848
+ forceRefetch,
1849
+ optimisticConnectedToServer,
1850
+ queryCacheSnapshotReady,
1851
+ queryKey,
1852
+ qryValues.lastUpdatedCount,
1853
+ qryValuesVariablesKey,
1854
+ resetOnlyTime,
1855
+ skip,
1856
+ triggerTime,
1857
+ updatedCount,
1858
+ variablesKey,
1859
+ ]);
1860
+
1861
+ // Mount & unmount
1862
+
1863
+ useEffect(() => {
1864
+ tracker.current.mounted = true;
1865
+
1866
+ return () => {
1867
+ tracker.current.mounted = false;
1868
+ unsetQueryTracker(queryKey, tracker.current.unique);
1869
+ };
1870
+ }, [queryKey]);
1871
+
1872
+ useEffect(() => {
1873
+ return () => {
1874
+ if (tracker.current.abortCtrl) {
1875
+ // console.log('UMOUNTED:', queryKey, tracker.current.unique);
1876
+ tracker.current.abortCtrl.abort({
1877
+ name: 'AbortError',
1878
+ message: `Hook for ${queryKey} has aborted because [the component unmounted].`,
1879
+ });
1880
+ }
1881
+ };
1882
+ }, []);
1883
+
1884
+ // Refetch when variables, skip status or query observer changes
1885
+
1886
+ // const isTest = queryName === 'logEntries';
1887
+
1888
+ useEffect(() => {
1889
+ // isTest && console.log('useQuery check:', refreshTime, updatedCount, qryValues.lastUpdatedCount);
1890
+
1891
+ if (
1892
+ queryCacheSnapshotReady &&
1893
+ !skip &&
1894
+ ((triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime) ||
1895
+ updatedCount !== qryValues.lastUpdatedCount ||
1896
+ variablesKey !== qryValuesVariablesKey ||
1897
+ (!qryValues.error && !effectiveQueryDataIsComplete))
1898
+ ) {
1899
+ const currentDataMatchesVariables =
1900
+ effectiveQueryDataIsComplete &&
1901
+ (!!cachedQuerySnapshot || variablesKey === qryValuesVariablesKey);
1902
+ const canAcknowledgeCurrentData =
1903
+ currentDataMatchesVariables &&
1904
+ !forceRefetch &&
1905
+ !resetOnlyTime &&
1906
+ !triggerTime;
1907
+
1908
+ if (canAcknowledgeCurrentData) {
1909
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1910
+ ...currentValues,
1911
+ variables,
1912
+ data: effectiveQueryData,
1913
+ lastUpdatedCount: updatedCount || 0,
1914
+ }));
1915
+ return;
1916
+ }
1917
+
1918
+ const cachedResult =
1919
+ cachedQuerySnapshot ||
1920
+ fetchCachedData(query, variablesKey, updateObservers);
1921
+ if (cachedResult) {
1922
+ setQryValues({
1923
+ ...qryValues,
1924
+ variables,
1925
+ data: cachedResult,
1926
+ error: null,
1927
+ loading: false, // IMPORTANT: must be false here
1928
+ lastRefreshTriggerTime: triggerTime,
1929
+ lastUpdatedCount: updatedCount || 0,
1930
+ });
1931
+
1932
+ // Anchor the focus/reconnect expiry logic to when this data was
1933
+ // actually fetched (hydrated snapshots would otherwise never expire)
1934
+ const lastFetchedAt = getQueryLastFetchedAt(queryKey);
1935
+ if (!tracker.current.reconnectedAt) {
1936
+ tracker.current.reconnectedAt = lastFetchedAt || Date.now();
1937
+ }
1938
+
1939
+ if (forceRefetch && !qryValues.loading) {
1940
+ // doLog(query, 'forceRefetchhing query at: $0|' + variablesKey + skip + updatedCount);
1941
+ doQuery();
1942
+ // isTest && console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
1943
+ // console.log('::', variablesKey, skip, updatedCount);
1944
+ } else if (
1945
+ !qryValues.loading &&
1946
+ connectedToServer &&
1947
+ queryDataIsStale(queryName, queryKey, persistTime)
1948
+ ) {
1949
+ // Cached data is served above; refresh it silently in the
1950
+ // background (stale-while-revalidate)
1951
+ doQuery(undefined, 0, 0, true);
1952
+ }
1953
+ } else if (!qryValues.loading) {
1954
+ // isTest && console.log(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
1955
+ // doLog(query, '!qryValues.loading, doing query at: $0|' + variablesKey + skip + updatedCount);
1956
+ // doLog(query, '1: ' + (triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime));
1957
+ // doLog(query, '2: ' + (updatedCount !== qryValues.lastUpdatedCount));
1958
+ // doLog(query, '3: ' + (variablesKey !== qryValuesVariablesKey));
1959
+ // doLog(query, '4: ' + (!qryValues.error && !checkDataCompleteness(qryValues.data, query)));
1960
+ // doLog(query, 'variablesKey 1: ' + variablesKey);
1961
+ // doLog(query, 'variablesKey 2: ' + qryValuesVariablesKey);
1962
+
1963
+ doQuery();
1964
+ }
1965
+ }
1966
+ }, [
1967
+ cachedQuerySnapshot,
1968
+ effectiveQueryDataIsComplete,
1969
+ queryCacheSnapshotReady,
1970
+ variablesKey,
1971
+ qryValuesVariablesKey,
1972
+ qryValues.loading,
1973
+ skip,
1974
+ updatedCount,
1975
+ triggerTime,
1976
+ ]);
1977
+
1978
+ // Refetch when the app reconnects and has no data
1979
+
1980
+ const withoutData = effectiveQueryData === null;
1981
+ const reconnectedWithoutData =
1982
+ queryCacheSnapshotReady &&
1983
+ !skip &&
1984
+ !qryValues.error &&
1985
+ withoutData &&
1986
+ !qryValues.loading &&
1987
+ connectedToServer;
1988
+
1989
+ useEffect(() => {
1990
+ if (
1991
+ queryCacheSnapshotReady &&
1992
+ connectedToServer &&
1993
+ screenIsFocused &&
1994
+ !skip &&
1995
+ !qryValues.error
1996
+ ) {
1997
+ const now = Date.now();
1998
+
1999
+ let timeDiff: number, timeThresh: number;
2000
+ if (reconnectedWithoutData) {
2001
+ timeDiff = tracker.current.reconnectedAt
2002
+ ? now - tracker.current.reconnectedAt
2003
+ : Infinity;
2004
+ timeThresh = 5000;
2005
+ } else {
2006
+ timeDiff = tracker.current.reconnectedAt
2007
+ ? now - tracker.current.reconnectedAt
2008
+ : -Infinity;
2009
+ timeThresh =
2010
+ QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
2011
+ }
2012
+
2013
+ // console.log('>>', queryName, timeDiff, timeThresh, timeDiff > timeThresh);
2014
+
2015
+ if (tracker.current.init && timeDiff > timeThresh) {
2016
+ // console.log('query again:', queryName, timeDiff);
2017
+ // doLog(query, reconnectedWithoutData + ' / ' + skip + ' / ' + withoutData + ' / ' + !qryValues.loading);
2018
+ tracker.current.reconnectedAt = now;
2019
+ doQuery();
2020
+ } else {
2021
+ tracker.current.init = true;
2022
+ }
2023
+ }
2024
+ }, [queryCacheSnapshotReady, reconnectedWithoutData, screenIsFocused]);
2025
+
2026
+ const transientError = isTransientServerError(qryValues.error);
2027
+
2028
+ /*
2029
+ * Keep the last successful result mounted while a deployment or temporary
2030
+ * transport outage is retried after the websocket reports connectivity.
2031
+ */
2032
+ useEffect(() => {
2033
+ if (!options?.retryTransientErrors || !transientError) {
2034
+ tracker.current.transientRetryAttemptCount = 0;
2035
+ return;
2036
+ }
2037
+ if (skip || qryValues.loading || !connectedToServer || !screenIsFocused) {
2038
+ return;
2039
+ }
2040
+
2041
+ const retryDelay = getTransientRetryDelay(
2042
+ tracker.current.transientRetryAttemptCount,
2043
+ );
2044
+ const retryAuthToken = getAuthToken();
2045
+ const timeoutId = globalThis.setTimeout(() => {
2046
+ if (!authContextMatchesRetryToken(retryAuthToken, getAuthToken())) {
2047
+ tracker.current.transientRetryAttemptCount = 0;
2048
+ return;
2049
+ }
2050
+ tracker.current.transientRetryAttemptCount += 1;
2051
+ void doQuery();
2052
+ }, retryDelay);
2053
+
2054
+ return () => {
2055
+ globalThis.clearTimeout(timeoutId);
2056
+ };
2057
+ }, [
2058
+ connectedToServer,
2059
+ qryValues.loading,
2060
+ screenIsFocused,
2061
+ skip,
2062
+ transientError,
2063
+ variablesKey,
2064
+ ]);
2065
+
2066
+ /*
2067
+ * Keep imperative refreshes behind the same skip boundary as effect-driven
2068
+ * loads so stale observers cannot send temporarily null required variables.
2069
+ */
2070
+ const queryRuntimeRef = useRef({ doQuery, skip });
2071
+
2072
+ /*
2073
+ * Publish only committed query variables to stable imperative callbacks.
2074
+ */
2075
+ useLayoutEffect(() => {
2076
+ queryRuntimeRef.current = { doQuery, skip };
2077
+ });
2078
+
2079
+ /*
2080
+ * Refetch with the latest render's query runtime while keeping the public
2081
+ * callback identity stable for memoized consumers.
2082
+ */
2083
+ const refetch = useCallback(() => {
2084
+ const queryRuntime = queryRuntimeRef.current;
2085
+ return queryRuntime.skip
2086
+ ? Promise.resolve({ skipped: true })
2087
+ : queryRuntime.doQuery();
2088
+ }, []);
2089
+
2090
+ /*
2091
+ * Fetch another variables page through the latest query runtime while
2092
+ * retaining a stable callback identity.
2093
+ */
2094
+ const fetchMore = useCallback(
2095
+ async (obj: GraphQLRequestOptions): Promise<any> => {
2096
+ const queryRuntime = queryRuntimeRef.current;
2097
+ if (queryRuntime.skip) {
2098
+ return { skipped: true };
2099
+ }
2100
+
2101
+ const result = await queryRuntime.doQuery(obj?.variables);
2102
+
2103
+ if (result.error) {
2104
+ return {
2105
+ ...result,
2106
+ error: normalizeServerError(result.error),
2107
+ };
2108
+ }
2109
+
2110
+ return result;
2111
+ },
2112
+ [],
2113
+ );
2114
+
2115
+ const queryData = useMemo(() => {
2116
+ if (!queryCacheSnapshotReady) {
2117
+ return {};
2118
+ }
2119
+
2120
+ return loadDataFromCache(
2121
+ effectiveQueryData,
2122
+ query,
2123
+ variablesKey,
2124
+ cacheMap,
2125
+ eagerFragmentKeyMap,
2126
+ false,
2127
+ );
2128
+ }, [
2129
+ cacheMap,
2130
+ eagerFragmentKeyMap,
2131
+ effectiveQueryData,
2132
+ query,
2133
+ queryCacheSnapshotReady,
2134
+ updatedCount,
2135
+ variablesKey,
2136
+ ]);
2137
+
2138
+ const resultData = queryData[queryName];
2139
+ const queryOutputRef = useRef<GraphQLQueryOutput>({
2140
+ queryKey,
2141
+ refreshTime,
2142
+ data: null,
2143
+ });
2144
+ const hasFreshData = resultData !== undefined;
2145
+
2146
+ /*
2147
+ * Retain the last committed complete output for uncached variable changes.
2148
+ */
2149
+ useEffect(() => {
2150
+ if (!hasFreshData) {
2151
+ return;
2152
+ }
2153
+
2154
+ queryOutputRef.current = {
2155
+ queryKey,
2156
+ refreshTime,
2157
+ data: queryData,
2158
+ };
2159
+ }, [hasFreshData, queryData, queryKey, refreshTime]);
2160
+
2161
+ // A null result still counts as data; only undefined means "not fetched yet".
2162
+ const queryOutput = queryOutputRef.current;
2163
+
2164
+ return {
2165
+ ...qryValues,
2166
+ queryName,
2167
+ queryKey: hasFreshData ? queryKey : queryOutput.queryKey,
2168
+ data: hasFreshData ? queryData : queryOutput.data || queryData,
2169
+ refreshTime: hasFreshData ? refreshTime : queryOutput.refreshTime,
2170
+ resetOnlyTime,
2171
+ variablesKey,
2172
+ refetch,
2173
+ fetchMore,
2174
+ updatedCount,
2175
+ updateObservers,
2176
+ connectedToServer,
2177
+ recovering: Boolean(options?.retryTransientErrors && transientError),
2178
+ screenIsFocused,
2179
+ };
1101
2180
  }
2181
+
2182
+ /**
2183
+ * Helper: For development purposes; do not remove.
2184
+ */
2185
+
2186
+ // function getQueryName(query: any) {
2187
+ // return query.definitions.filter((d: any) => d.kind === 'OperationDefinition').map(d => d.name.value).join(', ');
2188
+ // }
2189
+
2190
+ // function doLog(query: any, logStr: string) {
2191
+ // const queryName = getQueryName(query);
2192
+ // if (queryName === 'dataTableRowsForSheetRegions') {
2193
+ // console.log(logStr.replace(/\$0/gi, queryName));
2194
+ // }
2195
+ // }