@jsb188/graphql 1.1.10 → 1.1.12

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