@jsb188/graphql 1.1.10 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/cache/config.ts +64 -50
  2. package/cache/index.test.ts +671 -109
  3. package/cache/index.ts +1700 -1240
  4. package/cache/persist.ts +721 -0
  5. package/cache/store.ts +437 -0
  6. package/client/data-table-realtime-subscriptions.test.ts +740 -0
  7. package/client/data-table-realtime-subscriptions.ts +955 -0
  8. package/client/data-table-realtime.test.ts +792 -0
  9. package/client/data-table-realtime.ts +1218 -0
  10. package/client/fragment-realtime-sequence.ts +52 -0
  11. package/client/index.ts +2 -0
  12. package/client/open-sheet.ts +137 -0
  13. package/client/request-managed-session.test.ts +574 -0
  14. package/client/request-no-store.test.ts +157 -0
  15. package/client/request.ts +954 -163
  16. package/client/sse-ticket.test.ts +26 -0
  17. package/deno.lock +170 -0
  18. package/deno.test.json +8 -4
  19. package/drafts/index.ts +149 -0
  20. package/drafts/store.ts +397 -0
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentDocFragments.ts +46 -0
  26. package/gql/fragments/agentMemoryFragments.ts +19 -0
  27. package/gql/fragments/aiChatFragments.ts +16 -0
  28. package/gql/fragments/billingFragments.ts +0 -11
  29. package/gql/fragments/campaignFragments.ts +277 -0
  30. package/gql/fragments/dataTableFragments.ts +18 -128
  31. package/gql/fragments/emailFragments.ts +19 -9
  32. package/gql/fragments/fieldDocFragments.ts +82 -0
  33. package/gql/fragments/logFragments.ts +20 -79
  34. package/gql/fragments/organizationFragments.ts +43 -5
  35. package/gql/fragments/scheduleFragments.ts +155 -0
  36. package/gql/fragments/sheetFragments.ts +552 -22
  37. package/gql/fragments/storageFragments.ts +21 -0
  38. package/gql/fragments/workflowFragments.ts +28 -4
  39. package/gql/mutations/accountMutations.ts +0 -2
  40. package/gql/mutations/agentDocMutations.ts +177 -0
  41. package/gql/mutations/agentMemoryMutations.ts +36 -0
  42. package/gql/mutations/aiChatMutations.ts +17 -4
  43. package/gql/mutations/authMutations.ts +158 -17
  44. package/gql/mutations/campaignMutations.ts +215 -0
  45. package/gql/mutations/dataTableMutations.ts +48 -26
  46. package/gql/mutations/fieldDocMutations.ts +24 -0
  47. package/gql/mutations/index.ts +6 -1
  48. package/gql/mutations/logMutations.ts +6 -29
  49. package/gql/mutations/organizationMutations.ts +13 -4
  50. package/gql/mutations/scheduleMutations.ts +423 -0
  51. package/gql/mutations/sheetMutations.ts +273 -56
  52. package/gql/mutations/storageMutations.ts +20 -0
  53. package/gql/mutations/workflowMutations.ts +42 -0
  54. package/gql/queries/agentDocQueries.ts +120 -0
  55. package/gql/queries/agentMemoryQueries.ts +22 -0
  56. package/gql/queries/aiChatQueries.ts +18 -2
  57. package/gql/queries/authQueries.ts +41 -0
  58. package/gql/queries/billingQueries.ts +23 -0
  59. package/gql/queries/campaignQueries.ts +127 -0
  60. package/gql/queries/dataTableQueries.ts +100 -11
  61. package/gql/queries/emailQueries.ts +55 -3
  62. package/gql/queries/fieldDocQueries.ts +158 -0
  63. package/gql/queries/index.ts +8 -2
  64. package/gql/queries/logQueries.ts +11 -28
  65. package/gql/queries/organizationQueries.ts +52 -1
  66. package/gql/queries/scheduleQueries.ts +315 -0
  67. package/gql/queries/sheetQueries.ts +336 -25
  68. package/gql/queries/storageQueries.ts +38 -0
  69. package/gql/queries/workflowQueries.ts +72 -3
  70. package/hooks/index.ts +2065 -971
  71. package/hooks/use-account-mtn.ts +76 -81
  72. package/hooks/use-agentDoc-mtn.ts +285 -0
  73. package/hooks/use-agentDoc-qry.ts +208 -0
  74. package/hooks/use-agentMemory-mtn.ts +73 -0
  75. package/hooks/use-agentMemory-qry.ts +44 -0
  76. package/hooks/use-aiChat-mtn.ts +232 -137
  77. package/hooks/use-aiChat-qry.ts +480 -222
  78. package/hooks/use-app-qry.ts +12 -9
  79. package/hooks/use-auth-mtn.ts +406 -252
  80. package/hooks/use-auth-qry.ts +51 -0
  81. package/hooks/use-campaign-mtn.ts +377 -0
  82. package/hooks/use-campaign-qry.ts +257 -0
  83. package/hooks/use-dataTable-mtn.ts +116 -33
  84. package/hooks/use-dataTable-qry.ts +859 -35
  85. package/hooks/use-email-qry.ts +194 -79
  86. package/hooks/use-fieldDoc-mtn.ts +50 -0
  87. package/hooks/use-fieldDoc-qry.ts +180 -0
  88. package/hooks/use-inboundContact-mtn.ts +19 -16
  89. package/hooks/use-inboundContact-qry.ts +63 -55
  90. package/hooks/use-integration-mtn.ts +56 -38
  91. package/hooks/use-integration-qry.ts +24 -9
  92. package/hooks/use-log-mtn.ts +72 -56
  93. package/hooks/use-log-qry.ts +93 -69
  94. package/hooks/use-organization-mtn.ts +334 -277
  95. package/hooks/use-organization-qry.ts +199 -129
  96. package/hooks/use-schedule-mtn.ts +416 -0
  97. package/hooks/use-schedule-qry.ts +157 -0
  98. package/hooks/use-sheet-mtn.ts +233 -47
  99. package/hooks/use-sheet-qry.ts +353 -70
  100. package/hooks/use-storage-mtn.ts +81 -41
  101. package/hooks/use-storage-qry.ts +104 -13
  102. package/hooks/use-workflow-mtn.ts +55 -0
  103. package/hooks/use-workflow-qry.ts +206 -48
  104. package/loaders/campaign.ts +137 -0
  105. package/package.json +94 -71
  106. package/sse.ts +157 -104
  107. package/tsconfig.json +11 -10
  108. package/types.d.ts +60 -30
  109. package/utils.ts +78 -49
  110. package/gql/fragments/productFragments.ts +0 -39
  111. package/gql/fragments/reportFragments.ts +0 -90
  112. package/gql/mutations/billingMutations.ts +0 -34
  113. package/gql/queries/productQueries.ts +0 -31
  114. package/gql/queries/reportQueries.ts +0 -134
  115. package/hooks/use-product-qry.ts +0 -67
  116. package/hooks/use-report-qry.ts +0 -153
package/cache/index.ts CHANGED
@@ -1,11 +1,59 @@
1
1
  import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
2
- import { cloneArrayLike, mapArrayLikeObjects, uniq } from '@jsb188/app/utils/object.ts';
2
+ import {
3
+ cloneArrayLike,
4
+ mapArrayLikeObjects,
5
+ uniq,
6
+ } from '@jsb188/app/utils/object.ts';
7
+ import {
8
+ getQueryResetTargetId,
9
+ queryCacheKeyMatchesResetTarget,
10
+ type QueryResetTarget,
11
+ } from '@jsb188/app/utils/queryReset.ts';
3
12
  import type { UpdateObserversFn } from '../types.d.ts';
4
- import { PARTIALS_MAP, RULES } from './config.ts';
5
-
6
- const QUERIES = new Map();
7
- const FRAGMENTS = new Map();
13
+ import { PARTIAL_NULL_PRESERVE_FIELDS, PARTIALS_MAP, RULES } from './config.ts';
14
+ import { cacheStore } from './store.ts';
15
+ import { clearGraphQLCachePersistence } from './persist.ts';
16
+ import { clearAllDrafts } from '../drafts/index.ts';
17
+
18
+ export {
19
+ initGraphQLCachePersistence,
20
+ isGraphQLCachePersistenceEnabled,
21
+ } from './persist.ts';
22
+
23
+ // Versioned store namespaces (Map-compatible facades): reads record memo
24
+ // dependencies + LRU stamps, writes bump versions only on real data changes
25
+ // and notify persistence subscribers.
26
+ const QUERIES = cacheStore.queries;
27
+ const FRAGMENTS = cacheStore.fragments;
8
28
  const RESET_TIME = new Map();
29
+ const QUERY_DOCUMENT_CACHE_IDS = new WeakMap<object, number>();
30
+ let NEXT_QUERY_DOCUMENT_CACHE_ID = 1;
31
+
32
+ /**
33
+ * Return a stable runtime id for one parsed GraphQL document.
34
+ */
35
+ function getQueryDocumentCacheId(gqlQuery: any): number {
36
+ if (!gqlQuery || typeof gqlQuery !== 'object') {
37
+ return 0;
38
+ }
39
+
40
+ const currentId = QUERY_DOCUMENT_CACHE_IDS.get(gqlQuery);
41
+ if (currentId) {
42
+ return currentId;
43
+ }
44
+
45
+ const nextId = NEXT_QUERY_DOCUMENT_CACHE_ID;
46
+ NEXT_QUERY_DOCUMENT_CACHE_ID += 1;
47
+ QUERY_DOCUMENT_CACHE_IDS.set(gqlQuery, nextId);
48
+ return nextId;
49
+ }
50
+
51
+ /*
52
+ * Return the response key for a GraphQL field, honoring root aliases.
53
+ */
54
+ function getGraphQLSelectionResponseName(selection: any) {
55
+ return selection.alias?.value || selection.name?.value;
56
+ }
9
57
 
10
58
  /**
11
59
  * JS Map will sometimes convert nested Array into Array-like Object
@@ -17,23 +65,26 @@ const RESET_TIME = new Map();
17
65
  */
18
66
 
19
67
  function enforceArrayType(obj: any): any {
20
- if (obj && typeof obj === 'object') {
21
- if (Array.isArray(obj)) {
22
- return obj.map(enforceArrayType);
23
- }
24
-
25
- const keys = Object.keys(obj);
26
- if (keys.every((key, i) => key === i.toString())) {
27
- return keys.map((key) => obj[key]);
28
- }
29
-
30
- for (const key in obj) {
31
- if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === 'object') {
32
- obj[key] = enforceArrayType(obj[key]);
33
- }
34
- }
35
- }
36
- return obj;
68
+ if (obj && typeof obj === 'object') {
69
+ if (Array.isArray(obj)) {
70
+ return obj.map(enforceArrayType);
71
+ }
72
+
73
+ const keys = Object.keys(obj);
74
+ if (keys.every((key, i) => key === i.toString())) {
75
+ return keys.map((key) => obj[key]);
76
+ }
77
+
78
+ for (const key in obj) {
79
+ if (
80
+ Object.prototype.hasOwnProperty.call(obj, key) &&
81
+ typeof obj[key] === 'object'
82
+ ) {
83
+ obj[key] = enforceArrayType(obj[key]);
84
+ }
85
+ }
86
+ }
87
+ return obj;
37
88
  }
38
89
 
39
90
  /**
@@ -41,38 +92,66 @@ function enforceArrayType(obj: any): any {
41
92
  */
42
93
 
43
94
  function mergeNestedObjects(obj1: any, obj2: any) {
44
- if (Array.isArray(obj1) || Array.isArray(obj2)) {
45
- if (Array.isArray(obj2)) {
46
- return [...obj2];
47
- }
48
-
49
- if (Array.isArray(obj1)) {
50
- return [...obj1];
51
- }
52
-
53
- return obj2;
54
- }
55
-
56
- if (!obj1) {
57
- if (!obj2 || typeof obj2 !== 'object') {
58
- return obj2;
59
- }
60
-
61
- return { ...obj2 };
62
- }
63
-
64
- const newObj = { ...obj1 };
65
- for (const key in obj2) {
66
- if (Object.prototype.hasOwnProperty.call(obj2, key)) {
67
- if (typeof obj2[key] === 'object' && obj2[key] !== null) {
68
- newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
69
- } else {
70
- newObj[key] = obj2[key];
71
- }
72
- }
73
- }
74
-
75
- return newObj;
95
+ if (Array.isArray(obj1) || Array.isArray(obj2)) {
96
+ if (Array.isArray(obj2)) {
97
+ return [...obj2];
98
+ }
99
+
100
+ if (Array.isArray(obj1)) {
101
+ return [...obj1];
102
+ }
103
+
104
+ return obj2;
105
+ }
106
+
107
+ if (!obj1) {
108
+ if (!obj2 || typeof obj2 !== 'object') {
109
+ return obj2;
110
+ }
111
+
112
+ return { ...obj2 };
113
+ }
114
+
115
+ const newObj = { ...obj1 };
116
+ for (const key in obj2) {
117
+ if (Object.prototype.hasOwnProperty.call(obj2, key)) {
118
+ if (typeof obj2[key] === 'object' && obj2[key] !== null) {
119
+ newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
120
+ } else {
121
+ newObj[key] = obj2[key];
122
+ }
123
+ }
124
+ }
125
+
126
+ return newObj;
127
+ }
128
+
129
+ /*
130
+ * Omit configured null state fields from partial-fragment writes while
131
+ * retaining nulls for volatile fields that must clear stale one-shot data.
132
+ */
133
+ function getPartialFragmentMergeData(
134
+ fragmentName: string | undefined,
135
+ data: any,
136
+ ) {
137
+ const preserveFields = fragmentName
138
+ ? PARTIAL_NULL_PRESERVE_FIELDS[fragmentName]
139
+ : null;
140
+ if (!preserveFields?.length || !data || typeof data !== 'object') {
141
+ return data;
142
+ }
143
+
144
+ let mergeData = data;
145
+ preserveFields.forEach((fieldName) => {
146
+ if (data[fieldName] !== null) {
147
+ return;
148
+ }
149
+ if (mergeData === data) {
150
+ mergeData = { ...data };
151
+ }
152
+ delete mergeData[fieldName];
153
+ });
154
+ return mergeData;
76
155
  }
77
156
 
78
157
  /**
@@ -80,7 +159,98 @@ function mergeNestedObjects(obj1: any, obj2: any) {
80
159
  */
81
160
 
82
161
  function isPlainObject(value: any) {
83
- return !!value && typeof value === 'object' && !Array.isArray(value);
162
+ return !!value && typeof value === 'object' && !Array.isArray(value);
163
+ }
164
+
165
+ /**
166
+ * Return whether one object is an optimistic UI placeholder.
167
+ */
168
+
169
+ function isOptimisticUIObject(value: any) {
170
+ return isPlainObject(value) && value.__optimisticUI === true;
171
+ }
172
+
173
+ /**
174
+ * Return one object's comparable id key, when it has an id.
175
+ */
176
+
177
+ function getObjectIdKey(value: any) {
178
+ if (!isPlainObject(value) || value.id === undefined || value.id === null) {
179
+ return null;
180
+ }
181
+
182
+ return String(value.id);
183
+ }
184
+
185
+ /**
186
+ * Return a copy of one top-level array without optimistic UI objects.
187
+ */
188
+
189
+ function removeOptimisticUIObjectsFromArray(value: any[]) {
190
+ return value.filter((item) => !isOptimisticUIObject(item));
191
+ }
192
+
193
+ /**
194
+ * Return a fragment with optimistic UI objects removed from top-level arrays.
195
+ */
196
+
197
+ function removeOptimisticUIObjectsFromArrayFields(fragment: any) {
198
+ if (!isPlainObject(fragment)) {
199
+ return fragment;
200
+ }
201
+
202
+ let nextFragment: Record<string, any> | null = null;
203
+
204
+ for (const key in fragment) {
205
+ if (
206
+ !Object.prototype.hasOwnProperty.call(fragment, key) ||
207
+ !Array.isArray(fragment[key])
208
+ ) {
209
+ continue;
210
+ }
211
+
212
+ const cleanedArray = removeOptimisticUIObjectsFromArray(fragment[key]);
213
+ if (cleanedArray.length === fragment[key].length) {
214
+ continue;
215
+ }
216
+
217
+ const writableFragment: Record<string, any> = nextFragment ?? {
218
+ ...fragment,
219
+ };
220
+ writableFragment[key] = cleanedArray;
221
+ nextFragment = writableFragment;
222
+ }
223
+
224
+ return nextFragment || fragment;
225
+ }
226
+
227
+ /**
228
+ * Return spread-backed array data plus unmatched optimistic UI objects.
229
+ */
230
+
231
+ function mergeSpreadBackedArrayWithOptimisticUIObjects(
232
+ spreadData: any[],
233
+ fragmentData: any[],
234
+ ) {
235
+ const spreadIds = new Set(
236
+ spreadData.map(getObjectIdKey).filter((id): id is string => id !== null),
237
+ );
238
+ const mergedData = [...spreadData];
239
+
240
+ fragmentData.forEach((item, index) => {
241
+ if (!isOptimisticUIObject(item)) {
242
+ return;
243
+ }
244
+
245
+ const itemId = getObjectIdKey(item);
246
+ if (itemId !== null && spreadIds.has(itemId)) {
247
+ return;
248
+ }
249
+
250
+ mergedData.splice(Math.min(index, mergedData.length), 0, item);
251
+ });
252
+
253
+ return mergedData;
84
254
  }
85
255
 
86
256
  /**
@@ -88,61 +258,72 @@ function isPlainObject(value: any) {
88
258
  */
89
259
 
90
260
  function makePrioritizedFieldTree(fields: string[]) {
91
- const priorityTree: Record<string, any> = {};
261
+ const priorityTree: Record<string, any> = {};
92
262
 
93
- for (const fieldPath of fields) {
94
- if (!fieldPath || typeof fieldPath !== 'string') {
95
- continue;
96
- }
263
+ for (const fieldPath of fields) {
264
+ if (!fieldPath || typeof fieldPath !== 'string') {
265
+ continue;
266
+ }
97
267
 
98
- const pathParts = fieldPath.split('.').filter(Boolean);
99
- if (pathParts.length === 0) {
100
- continue;
101
- }
268
+ const pathParts = fieldPath.split('.').filter(Boolean);
269
+ if (pathParts.length === 0) {
270
+ continue;
271
+ }
102
272
 
103
- let currentNode = priorityTree;
104
- for (const part of pathParts) {
105
- currentNode[part] = currentNode[part] || {};
106
- currentNode = currentNode[part];
107
- }
273
+ let currentNode = priorityTree;
274
+ for (const part of pathParts) {
275
+ currentNode[part] = currentNode[part] || {};
276
+ currentNode = currentNode[part];
277
+ }
108
278
 
109
- currentNode.__self = true;
110
- }
279
+ currentNode.__self = true;
280
+ }
111
281
 
112
- return priorityTree;
282
+ return priorityTree;
113
283
  }
114
284
 
115
285
  /**
116
286
  * Merge values while prioritizing main fragment data for selected field paths.
117
287
  */
118
288
 
119
- function mergeWithPriorityPaths(innerValue: any, mainValue: any, priorityNode: any) {
120
- if (!priorityNode) {
121
- return innerValue;
122
- }
123
-
124
- if (priorityNode.__self) {
125
- if (isPlainObject(innerValue) && isPlainObject(mainValue)) {
126
- return mergeNestedObjects(innerValue, mainValue);
127
- }
128
-
129
- return mainValue;
130
- }
131
-
132
- if (!isPlainObject(innerValue) || !isPlainObject(mainValue)) {
133
- return innerValue;
134
- }
135
-
136
- const mergedValue = { ...innerValue };
137
- for (const key in priorityNode) {
138
- if (key !== '__self' && Object.prototype.hasOwnProperty.call(priorityNode, key)) {
139
- if (mainValue[key] !== undefined) {
140
- mergedValue[key] = mergeWithPriorityPaths(innerValue[key], mainValue[key], priorityNode[key]);
141
- }
142
- }
143
- }
144
-
145
- return mergedValue;
289
+ function mergeWithPriorityPaths(
290
+ innerValue: any,
291
+ mainValue: any,
292
+ priorityNode: any,
293
+ ) {
294
+ if (!priorityNode) {
295
+ return innerValue;
296
+ }
297
+
298
+ if (priorityNode.__self) {
299
+ if (isPlainObject(innerValue) && isPlainObject(mainValue)) {
300
+ return mergeNestedObjects(innerValue, mainValue);
301
+ }
302
+
303
+ return mainValue;
304
+ }
305
+
306
+ if (!isPlainObject(innerValue) || !isPlainObject(mainValue)) {
307
+ return innerValue;
308
+ }
309
+
310
+ const mergedValue = { ...innerValue };
311
+ for (const key in priorityNode) {
312
+ if (
313
+ key !== '__self' &&
314
+ Object.prototype.hasOwnProperty.call(priorityNode, key)
315
+ ) {
316
+ if (mainValue[key] !== undefined) {
317
+ mergedValue[key] = mergeWithPriorityPaths(
318
+ innerValue[key],
319
+ mainValue[key],
320
+ priorityNode[key],
321
+ );
322
+ }
323
+ }
324
+ }
325
+
326
+ return mergedValue;
146
327
  }
147
328
 
148
329
  /**
@@ -150,23 +331,23 @@ function mergeWithPriorityPaths(innerValue: any, mainValue: any, priorityNode: a
150
331
  */
151
332
 
152
333
  function getSpreadValueScore(spreadValue: any) {
153
- if (!spreadValue) {
154
- return 0;
155
- }
334
+ if (!spreadValue) {
335
+ return 0;
336
+ }
156
337
 
157
- if (typeof spreadValue === 'string') {
158
- return 1;
159
- }
338
+ if (typeof spreadValue === 'string') {
339
+ return 1;
340
+ }
160
341
 
161
- if (Array.isArray(spreadValue)) {
162
- return spreadValue.length;
163
- }
342
+ if (Array.isArray(spreadValue)) {
343
+ return spreadValue.length;
344
+ }
164
345
 
165
- if (spreadValue?.__list && Array.isArray(spreadValue.data)) {
166
- return spreadValue.data.length;
167
- }
346
+ if (spreadValue?.__list && Array.isArray(spreadValue.data)) {
347
+ return spreadValue.data.length;
348
+ }
168
349
 
169
- return 0;
350
+ return 0;
170
351
  }
171
352
 
172
353
  /**
@@ -174,22 +355,22 @@ function getSpreadValueScore(spreadValue: any) {
174
355
  */
175
356
 
176
357
  function mergeSpreadValue(currentValue: any, nextValue: any) {
177
- if (!currentValue) {
178
- return nextValue;
179
- }
358
+ if (!currentValue) {
359
+ return nextValue;
360
+ }
180
361
 
181
- if (!nextValue) {
182
- return currentValue;
183
- }
362
+ if (!nextValue) {
363
+ return currentValue;
364
+ }
184
365
 
185
- const currentScore = getSpreadValueScore(currentValue);
186
- const nextScore = getSpreadValueScore(nextValue);
366
+ const currentScore = getSpreadValueScore(currentValue);
367
+ const nextScore = getSpreadValueScore(nextValue);
187
368
 
188
- if (nextScore >= currentScore) {
189
- return nextValue;
190
- }
369
+ if (nextScore >= currentScore) {
370
+ return nextValue;
371
+ }
191
372
 
192
- return currentValue;
373
+ return currentValue;
193
374
  }
194
375
 
195
376
  /**
@@ -197,52 +378,56 @@ function mergeSpreadValue(currentValue: any, nextValue: any) {
197
378
  */
198
379
 
199
380
  function mergeSpreads(currentSpreads: any, nextSpreads: any) {
200
- if (!currentSpreads) {
201
- return nextSpreads;
202
- }
203
-
204
- if (!nextSpreads) {
205
- return currentSpreads;
206
- }
207
-
208
- const mergedSpreads = { ...currentSpreads };
209
- for (const key in nextSpreads) {
210
- if (Object.prototype.hasOwnProperty.call(nextSpreads, key)) {
211
- mergedSpreads[key] = mergeSpreadValue(currentSpreads[key], nextSpreads[key]);
212
- }
213
- }
214
-
215
- return mergedSpreads;
381
+ if (!currentSpreads) {
382
+ return nextSpreads;
383
+ }
384
+
385
+ if (!nextSpreads) {
386
+ return currentSpreads;
387
+ }
388
+
389
+ const mergedSpreads = { ...currentSpreads };
390
+ for (const key in nextSpreads) {
391
+ if (Object.prototype.hasOwnProperty.call(nextSpreads, key)) {
392
+ mergedSpreads[key] = mergeSpreadValue(
393
+ currentSpreads[key],
394
+ nextSpreads[key],
395
+ );
396
+ }
397
+ }
398
+
399
+ return mergedSpreads;
216
400
  }
217
401
 
218
402
  /**
219
403
  * Make Object for fragment, omitting what you don't need
220
404
  */
221
405
 
222
- function extractFragment(dataObj: any, innerSelection: any[], isTest?: boolean) {
223
- if (innerSelection.length <= 1) {
224
- return dataObj;
225
- }
226
-
227
- const fragmentObj = { ...dataObj };
228
- for (const sel of innerSelection) {
229
- if (sel.kind === 'Field') {
230
- delete fragmentObj[sel.name.value];
231
- }
232
- }
233
-
234
- return fragmentObj;
406
+ function extractFragment(
407
+ dataObj: any,
408
+ innerSelection: any[],
409
+ isTest?: boolean,
410
+ ) {
411
+ if (innerSelection.length <= 1) {
412
+ return dataObj;
413
+ }
414
+
415
+ const fragmentObj = { ...dataObj };
416
+ for (const sel of innerSelection) {
417
+ if (sel.kind === 'Field') {
418
+ delete fragmentObj[sel.name.value];
419
+ }
420
+ }
421
+
422
+ return fragmentObj;
235
423
  }
236
424
 
237
425
  /**
238
426
  * Build a stable cache scope for fragment data that may not have an id.
239
427
  */
240
428
 
241
- function getFragmentCacheScope(
242
- data: any,
243
- fallbackScope?: string,
244
- ) {
245
- return data?.id || fallbackScope || 'none';
429
+ function getFragmentCacheScope(data: any, fallbackScope?: string) {
430
+ return data?.id || fallbackScope || 'none';
246
431
  }
247
432
 
248
433
  /**
@@ -250,11 +435,11 @@ function getFragmentCacheScope(
250
435
  */
251
436
 
252
437
  function makeFragmentCacheKey(
253
- fragmentName: string,
254
- data: any,
255
- fallbackScope?: string,
438
+ fragmentName: string,
439
+ data: any,
440
+ fallbackScope?: string,
256
441
  ) {
257
- return `$${fragmentName}:${getFragmentCacheScope(data, fallbackScope)}`;
442
+ return `$${fragmentName}:${getFragmentCacheScope(data, fallbackScope)}`;
258
443
  }
259
444
 
260
445
  /**
@@ -262,66 +447,67 @@ function makeFragmentCacheKey(
262
447
  */
263
448
 
264
449
  function mapCachedListItem(
265
- cachedItemData: any[],
266
- loadFragmentData: (fragmentKey: string) => any,
450
+ cachedItemData: any[],
451
+ loadFragmentData: (fragmentKey: string) => any,
267
452
  ) {
268
- let item: Record<string, any> = {};
269
- let cacheIsValid = true;
270
-
271
- cachedItemData.forEach((cachedValue: any) => {
272
- let mapCacheId;
273
- if (Array.isArray(cachedValue)) {
274
- if (cachedValue.length === 1 && cachedValue?.[0]?.startsWith('$')) {
275
- mapCacheId = cachedValue[0];
276
- } else if (Array.isArray(cachedValue[1])) {
277
- item[cachedValue[0]] = cachedValue[1].map((value: any) => {
278
- if (value?.__reactiveFragmentName) {
279
- const clientReactiveFragmentKey = `${value.__reactiveFragmentName}:${value.id}`;
280
- return FRAGMENTS.get(clientReactiveFragmentKey) || value;
281
- }
282
-
283
- return value;
284
- });
285
- return;
286
- } else if (cachedValue[1]?.__reactiveFragmentName) {
287
- const clientReactiveFragmentKey = `${cachedValue[1].__reactiveFragmentName}:${cachedValue[1].id}`;
288
- item[cachedValue[0]] = FRAGMENTS.get(clientReactiveFragmentKey) || cachedValue[1];
289
- return;
290
- } else {
291
- item[cachedValue[0]] = cachedValue[1];
292
- return;
293
- }
294
- } else if (typeof cachedValue === 'string') {
295
- mapCacheId = cachedValue;
296
- }
297
-
298
- if (!mapCacheId) {
299
- return;
300
- }
301
-
302
- const frgIndex = mapCacheId.indexOf(':');
303
- const frgName = mapCacheId.substring(1, frgIndex);
304
- const frgMap = PARTIALS_MAP[frgName];
305
- const fragmentKey = frgMap
306
- ? `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}`
307
- : mapCacheId;
308
-
309
- const cachedFragment = loadFragmentData(fragmentKey);
310
- if (cachedFragment) {
311
- item = {
312
- ...item,
313
- ...cachedFragment,
314
- };
315
- } else {
316
- cacheIsValid = false;
317
- }
318
- });
319
-
320
- if (!cacheIsValid) {
321
- return null;
322
- }
323
-
324
- return item;
453
+ let item: Record<string, any> = {};
454
+ let cacheIsValid = true;
455
+
456
+ cachedItemData.forEach((cachedValue: any) => {
457
+ let mapCacheId;
458
+ if (Array.isArray(cachedValue)) {
459
+ if (cachedValue.length === 1 && cachedValue?.[0]?.startsWith('$')) {
460
+ mapCacheId = cachedValue[0];
461
+ } else if (Array.isArray(cachedValue[1])) {
462
+ item[cachedValue[0]] = cachedValue[1].map((value: any) => {
463
+ if (value?.__reactiveFragmentName) {
464
+ const clientReactiveFragmentKey = `${value.__reactiveFragmentName}:${value.id}`;
465
+ return FRAGMENTS.get(clientReactiveFragmentKey) || value;
466
+ }
467
+
468
+ return value;
469
+ });
470
+ return;
471
+ } else if (cachedValue[1]?.__reactiveFragmentName) {
472
+ const clientReactiveFragmentKey = `${cachedValue[1].__reactiveFragmentName}:${cachedValue[1].id}`;
473
+ item[cachedValue[0]] =
474
+ FRAGMENTS.get(clientReactiveFragmentKey) || cachedValue[1];
475
+ return;
476
+ } else {
477
+ item[cachedValue[0]] = cachedValue[1];
478
+ return;
479
+ }
480
+ } else if (typeof cachedValue === 'string') {
481
+ mapCacheId = cachedValue;
482
+ }
483
+
484
+ if (!mapCacheId) {
485
+ return;
486
+ }
487
+
488
+ const frgIndex = mapCacheId.indexOf(':');
489
+ const frgName = mapCacheId.substring(1, frgIndex);
490
+ const frgMap = PARTIALS_MAP[frgName];
491
+ const fragmentKey = frgMap
492
+ ? `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}`
493
+ : mapCacheId;
494
+
495
+ const cachedFragment = loadFragmentData(fragmentKey);
496
+ if (cachedFragment) {
497
+ item = {
498
+ ...item,
499
+ ...cachedFragment,
500
+ };
501
+ } else {
502
+ cacheIsValid = false;
503
+ }
504
+ });
505
+
506
+ if (!cacheIsValid) {
507
+ return null;
508
+ }
509
+
510
+ return item;
325
511
  }
326
512
 
327
513
  /**
@@ -329,48 +515,68 @@ function mapCachedListItem(
329
515
  */
330
516
 
331
517
  export function loadQuery(queryKey: string, referencesOnly?: boolean) {
332
- const references = QUERIES.get(queryKey);
333
-
334
- // if (testMode) {
335
- // console.log('references>>>>:', references);
336
- // }
337
-
338
- if (referencesOnly) {
339
- return references;
340
- } else if (!references) {
341
- // This is important, not returning null will cause infinite loop
342
- return null;
343
- }
344
-
345
- if (Array.isArray(references)) {
346
- const mappedCache = references.map((cacheObj) => appendFragmentToCache(cacheObj));
347
- if (mappedCache.some((c) => !c)) {
348
- return undefined;
349
- }
350
-
351
- // let hasInvalidatedCache = false;
352
- // const mappedCache = references.map((cacheObj) => {
353
- // if (!hasInvalidatedCache) {
354
- // const singleCache = appendFragmentToCache(cacheObj);
355
-
356
- // if (singleCache) {
357
- // return singleCache;
358
- // } else {
359
- // hasInvalidatedCache = true;
360
- // }
361
- // }
362
- // });
363
- // if (!hasInvalidatedCache) {
364
- // return mappedCache;
365
- // }
366
-
367
- return mappedCache;
368
- } else if (references) {
369
- // console.log('references single:', references);
370
- const singleCacheData = appendFragmentToCache(references, true);
371
- // console.log('singleCacheData >>>>:', singleCacheData);
372
- return singleCacheData;
373
- }
518
+ if (referencesOnly) {
519
+ return QUERIES.get(queryKey);
520
+ }
521
+
522
+ // Memoized: while the query references and every fragment they touch are
523
+ // unchanged, the exact same assembled object reference is returned.
524
+ return cacheStore.memoizeRead(`Q|${queryKey}`, () =>
525
+ loadQueryInternal(queryKey),
526
+ );
527
+ }
528
+
529
+ /**
530
+ * Assemble one cached query result from its stored fragment references.
531
+ */
532
+
533
+ function loadQueryInternal(queryKey: string) {
534
+ const references = QUERIES.get(queryKey);
535
+
536
+ if (!references) {
537
+ // This is important, not returning null will cause infinite loop
538
+ return null;
539
+ }
540
+
541
+ // Lets nested spread lists be compared against this query cache entry's own
542
+ // write recency instead of always losing to the flat fragment copy
543
+ const queryVersion = QUERIES.version(queryKey);
544
+
545
+ if (Array.isArray(references)) {
546
+ const mappedCache = references.map((cacheObj) =>
547
+ appendFragmentToCache(cacheObj, false, queryVersion),
548
+ );
549
+ if (mappedCache.some((c) => !c)) {
550
+ return undefined;
551
+ }
552
+
553
+ // let hasInvalidatedCache = false;
554
+ // const mappedCache = references.map((cacheObj) => {
555
+ // if (!hasInvalidatedCache) {
556
+ // const singleCache = appendFragmentToCache(cacheObj);
557
+
558
+ // if (singleCache) {
559
+ // return singleCache;
560
+ // } else {
561
+ // hasInvalidatedCache = true;
562
+ // }
563
+ // }
564
+ // });
565
+ // if (!hasInvalidatedCache) {
566
+ // return mappedCache;
567
+ // }
568
+
569
+ return mappedCache;
570
+ } else if (references) {
571
+ // console.log('references single:', references);
572
+ const singleCacheData = appendFragmentToCache(
573
+ references,
574
+ true,
575
+ queryVersion,
576
+ );
577
+ // console.log('singleCacheData >>>>:', singleCacheData);
578
+ return singleCacheData;
579
+ }
374
580
  }
375
581
 
376
582
  /**
@@ -378,103 +584,129 @@ export function loadQuery(queryKey: string, referencesOnly?: boolean) {
378
584
  */
379
585
 
380
586
  export function loadFragment(id: string, mainPrioritizedFields: string[] = []) {
381
- // console.log('load fragment:', id, FRAGMENTS.get(id));
382
-
383
- const fragment = enforceArrayType(FRAGMENTS.get(id));
384
- if (!fragment) {
385
- return null;
386
- }
387
-
388
- const spreads = FRAGMENTS.get(`${id}.spreads`);
389
- if (!spreads) {
390
- return fragment;
391
- }
392
-
393
- // const isTest = id.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193');
394
- // if (isTest) {
395
- // ..
396
- // }
397
-
398
- let fragmentWithSpreads = { ...fragment };
399
- const prioritizedFieldTree = makePrioritizedFieldTree(mainPrioritizedFields);
400
- for (const key in spreads) {
401
-
402
- if (Object.prototype.hasOwnProperty.call(spreads, key)) {
403
- const spreadValue = spreads[key];
404
-
405
- // if (isInnerTest) {
406
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
407
- // }
408
-
409
- // if (isTest) {
410
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
411
- // }
412
-
413
- let spreadData;
414
- if (typeof spreadValue === 'string') {
415
- spreadData = enforceArrayType(FRAGMENTS.get(spreadValue));
416
- } else if (Array.isArray(spreadValue)) {
417
- spreadData = spreadValue.reduce((acc, value) => {
418
-
419
- // if (isTest) {
420
- // console.log('????', value);
421
- // }
422
-
423
-
424
- if (typeof value === 'string') {
425
- const fragmentData = enforceArrayType(FRAGMENTS.get(value));
426
-
427
- // if (isTest) {
428
- // console.log('1:', value, fragmentData);
429
- // }
430
-
431
- return {
432
- ...acc,
433
- ...fragmentData,
434
- };
435
- } else if (Array.isArray(value)) {
436
- const [namespace, innerValue] = value;
437
- return {
438
- ...acc,
439
- [namespace]: innerValue,
440
- };
441
- }
442
-
443
- return acc;
444
- }, {});
445
- } else if (spreadValue?.__list === true) {
446
- spreadData = spreadValue.data.map((val: any) => {
447
- if (typeof val === 'string') {
448
- return loadFragment(val);
449
- } else if (Array.isArray(val)) {
450
- return mapCachedListItem(val, loadFragment);
451
- }
452
-
453
- return null;
454
- }).filter(Boolean);
455
- }
456
-
457
- if (spreadData) {
458
- const priorityNode = prioritizedFieldTree[key];
459
- if (priorityNode && fragmentWithSpreads[key] !== undefined) {
460
- fragmentWithSpreads[key] = mergeWithPriorityPaths(
461
- spreadData,
462
- fragmentWithSpreads[key],
463
- priorityNode
464
- );
465
- } else if (fragmentWithSpreads[key] !== undefined) {
466
- fragmentWithSpreads[key] = mergeNestedObjects(
467
- spreadData,
468
- fragmentWithSpreads[key],
469
- );
470
- } else {
471
- fragmentWithSpreads[key] = spreadData;
472
- }
473
- }
474
- }
475
- }
476
-
477
- return fragmentWithSpreads;
587
+ // Memoized with automatic dependency tracking: while this fragment, its
588
+ // spreads and every transitively loaded fragment are unchanged, the exact
589
+ // same assembled object reference is returned (structural sharing).
590
+ const memoKey = mainPrioritizedFields.length
591
+ ? `${id}|${mainPrioritizedFields.join(',')}`
592
+ : id;
593
+
594
+ return cacheStore.memoizeRead(memoKey, () =>
595
+ loadFragmentInternal(id, mainPrioritizedFields),
596
+ );
597
+ }
598
+
599
+ /**
600
+ * Assemble one fragment with its spreads (uncached implementation).
601
+ */
602
+
603
+ function loadFragmentInternal(
604
+ id: string,
605
+ mainPrioritizedFields: string[] = [],
606
+ ) {
607
+ // console.log('load fragment:', id, FRAGMENTS.get(id));
608
+
609
+ const fragment = enforceArrayType(FRAGMENTS.get(id));
610
+ if (!fragment) {
611
+ return null;
612
+ }
613
+
614
+ const spreads = FRAGMENTS.get(`${id}.spreads`);
615
+ if (!spreads) {
616
+ return fragment;
617
+ }
618
+
619
+ // const isTest = id.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193');
620
+ // if (isTest) {
621
+ // ..
622
+ // }
623
+
624
+ let fragmentWithSpreads = { ...fragment };
625
+ const prioritizedFieldTree = makePrioritizedFieldTree(mainPrioritizedFields);
626
+ for (const key in spreads) {
627
+ if (Object.prototype.hasOwnProperty.call(spreads, key)) {
628
+ const spreadValue = spreads[key];
629
+
630
+ // if (isInnerTest) {
631
+ // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
632
+ // }
633
+
634
+ // if (isTest) {
635
+ // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
636
+ // }
637
+
638
+ let spreadData;
639
+ if (typeof spreadValue === 'string') {
640
+ spreadData = enforceArrayType(FRAGMENTS.get(spreadValue));
641
+ } else if (Array.isArray(spreadValue)) {
642
+ spreadData = spreadValue.reduce((acc, value) => {
643
+ // if (isTest) {
644
+ // console.log('????', value);
645
+ // }
646
+
647
+ if (typeof value === 'string') {
648
+ const fragmentData = enforceArrayType(FRAGMENTS.get(value));
649
+
650
+ // if (isTest) {
651
+ // console.log('1:', value, fragmentData);
652
+ // }
653
+
654
+ return {
655
+ ...acc,
656
+ ...fragmentData,
657
+ };
658
+ } else if (Array.isArray(value)) {
659
+ const [namespace, innerValue] = value;
660
+ return {
661
+ ...acc,
662
+ [namespace]: innerValue,
663
+ };
664
+ }
665
+
666
+ return acc;
667
+ }, {});
668
+ } else if (spreadValue?.__list === true) {
669
+ spreadData = spreadValue.data
670
+ .map((val: any) => {
671
+ if (typeof val === 'string') {
672
+ return loadFragment(val);
673
+ } else if (Array.isArray(val)) {
674
+ return mapCachedListItem(val, loadFragment);
675
+ }
676
+
677
+ return null;
678
+ })
679
+ .filter(Boolean);
680
+ }
681
+
682
+ if (spreadData) {
683
+ const spreadDataWithOptimisticUI =
684
+ Array.isArray(spreadData) && Array.isArray(fragmentWithSpreads[key])
685
+ ? mergeSpreadBackedArrayWithOptimisticUIObjects(
686
+ spreadData,
687
+ fragmentWithSpreads[key],
688
+ )
689
+ : spreadData;
690
+ const priorityNode = prioritizedFieldTree[key];
691
+ if (priorityNode && fragmentWithSpreads[key] !== undefined) {
692
+ fragmentWithSpreads[key] = mergeWithPriorityPaths(
693
+ spreadDataWithOptimisticUI,
694
+ fragmentWithSpreads[key],
695
+ priorityNode,
696
+ );
697
+ } else if (fragmentWithSpreads[key] !== undefined) {
698
+ fragmentWithSpreads[key] = mergeNestedObjects(
699
+ fragmentWithSpreads[key],
700
+ spreadDataWithOptimisticUI,
701
+ );
702
+ } else {
703
+ fragmentWithSpreads[key] = spreadDataWithOptimisticUI;
704
+ }
705
+ }
706
+ }
707
+ }
708
+
709
+ return fragmentWithSpreads;
478
710
  }
479
711
 
480
712
  /**
@@ -482,232 +714,285 @@ export function loadFragment(id: string, mainPrioritizedFields: string[] = []) {
482
714
  */
483
715
 
484
716
  function mapSelections(
485
- data: any,
486
- innerSelections: any[],
487
- updatedKeys: string[] = [],
488
- fallbackScope?: string,
717
+ data: any,
718
+ innerSelections: any[],
719
+ updatedKeys: string[] = [],
720
+ fallbackScope?: string,
489
721
  ) {
490
-
491
- return innerSelections.map((inner) => {
492
-
493
- let fragmentKey;
494
- if (inner.kind === 'FragmentSpread') {
495
- // These are fragment spreads
496
- const frgName = inner.name.value;
497
- const frgMap = PARTIALS_MAP[frgName];
498
-
499
- fragmentKey = makeFragmentCacheKey(frgMap || frgName, data, fallbackScope);
500
-
501
- } else if (inner.kind === 'Field' && inner.selectionSet && inner.selectionSet.selections?.length) {
502
-
503
- // These are nested fragments, they need to be cached as a fragment
504
-
505
- const innerData = data?.[inner.name.value];
506
- const innerSelections = inner.selectionSet.selections?.filter((sel: any) => sel.kind === 'FragmentSpread');
507
-
508
- if (innerData && Array.isArray(innerSelections)) {
509
- if (Array.isArray(innerData)) {
510
- const parentScope = getFragmentCacheScope(data, fallbackScope);
511
- for (const [itemIndex, item] of innerData.entries()) {
512
- mapSelections(
513
- item,
514
- inner.selectionSet.selections,
515
- updatedKeys,
516
- `${parentScope}.${inner.name.value}.${itemIndex}`,
517
- );
518
- }
519
- } else {
520
- mapSelections(
521
- innerData,
522
- inner.selectionSet.selections,
523
- updatedKeys,
524
- `${getFragmentCacheScope(data, fallbackScope)}.${inner.name.value}`,
525
- );
526
- }
527
- }
528
-
529
- } else if (inner.kind === 'InlineFragment') {
530
- // This is Union, etc
531
- const frgNamesJoined = inner.selectionSet.selections.map((sel: any) => PARTIALS_MAP[sel.name.value] || sel.name.value).join('.');
532
-
533
- if (frgNamesJoined.toLowerCase().indexOf(data.__typename.toLowerCase()) < 0) {
534
- // This is untested, but should be fine
535
- return null;
536
- }
537
-
538
- fragmentKey = makeFragmentCacheKey(frgNamesJoined, data, fallbackScope);
539
- }
540
-
541
- if (fragmentKey) {
542
- // Whether fragment is partial or not, always merge data;
543
- // Because partials might have data that's not in the main fragment
544
- const currentData = loadFragment(fragmentKey);
545
-
546
- // console.log(fragmentKey);
547
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
548
- // console.log('>>>>');
549
- // console.log('>>>>');
550
- // console.log('>>>>');
551
- // console.log('>>>>');
552
- // console.log(currentData);
553
- // console.log(data);
554
- // console.log(extractFragment(data, innerSelections));
555
- // }
556
-
557
- const fragmentFromData = extractFragment(data, innerSelections);
558
- FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, fragmentFromData));
559
- updatedKeys.push(fragmentKey);
560
-
561
- return fragmentKey;
562
- }
563
-
564
- // These are non-fragment fields
565
- return [
566
- inner.name.value,
567
- data?.[inner.name.value]
568
- ];
569
- // return {
570
- // name: inner.name.value,
571
- // value: data[key]?.[inner.name.value]
572
- // };
573
- }).filter(Boolean);
722
+ return innerSelections
723
+ .map((inner) => {
724
+ let fragmentKey;
725
+ let sourceFragmentName: string | undefined;
726
+ if (inner.kind === 'FragmentSpread') {
727
+ // These are fragment spreads
728
+ const frgName = inner.name.value;
729
+ sourceFragmentName = frgName;
730
+ const frgMap = PARTIALS_MAP[frgName];
731
+
732
+ fragmentKey = makeFragmentCacheKey(
733
+ frgMap || frgName,
734
+ data,
735
+ fallbackScope,
736
+ );
737
+ } else if (
738
+ inner.kind === 'Field' &&
739
+ inner.selectionSet &&
740
+ inner.selectionSet.selections?.length
741
+ ) {
742
+ // These are nested fragments, they need to be cached as a fragment
743
+
744
+ const innerData = data?.[inner.name.value];
745
+ const innerSelections = inner.selectionSet.selections?.filter(
746
+ (sel: any) => sel.kind === 'FragmentSpread',
747
+ );
748
+
749
+ if (innerData && Array.isArray(innerSelections)) {
750
+ if (Array.isArray(innerData)) {
751
+ const parentScope = getFragmentCacheScope(data, fallbackScope);
752
+ for (const [itemIndex, item] of innerData.entries()) {
753
+ mapSelections(
754
+ item,
755
+ inner.selectionSet.selections,
756
+ updatedKeys,
757
+ `${parentScope}.${inner.name.value}.${itemIndex}`,
758
+ );
759
+ }
760
+ } else {
761
+ mapSelections(
762
+ innerData,
763
+ inner.selectionSet.selections,
764
+ updatedKeys,
765
+ `${getFragmentCacheScope(data, fallbackScope)}.${inner.name.value}`,
766
+ );
767
+ }
768
+ }
769
+ } else if (inner.kind === 'InlineFragment') {
770
+ // This is Union, etc
771
+ const frgNamesJoined = inner.selectionSet.selections
772
+ .map((sel: any) => PARTIALS_MAP[sel.name.value] || sel.name.value)
773
+ .join('.');
774
+
775
+ if (
776
+ frgNamesJoined.toLowerCase().indexOf(data.__typename.toLowerCase()) <
777
+ 0
778
+ ) {
779
+ // This is untested, but should be fine
780
+ return null;
781
+ }
782
+
783
+ fragmentKey = makeFragmentCacheKey(frgNamesJoined, data, fallbackScope);
784
+ }
785
+
786
+ if (fragmentKey) {
787
+ // Whether fragment is partial or not, always merge data;
788
+ // Because partials might have data that's not in the main fragment
789
+ const currentData = loadFragment(fragmentKey);
790
+
791
+ // console.log(fragmentKey);
792
+ // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
793
+ // console.log('>>>>');
794
+ // console.log('>>>>');
795
+ // console.log('>>>>');
796
+ // console.log('>>>>');
797
+ // console.log(currentData);
798
+ // console.log(data);
799
+ // console.log(extractFragment(data, innerSelections));
800
+ // }
801
+
802
+ const fragmentFromData = getPartialFragmentMergeData(
803
+ sourceFragmentName,
804
+ extractFragment(data, innerSelections),
805
+ );
806
+ FRAGMENTS.set(
807
+ fragmentKey,
808
+ mergeNestedObjects(
809
+ removeOptimisticUIObjectsFromArrayFields(currentData),
810
+ fragmentFromData,
811
+ ),
812
+ );
813
+ updatedKeys.push(fragmentKey);
814
+
815
+ return fragmentKey;
816
+ }
817
+
818
+ // These are non-fragment fields
819
+ return [inner.name.value, data?.[inner.name.value]];
820
+ // return {
821
+ // name: inner.name.value,
822
+ // value: data[key]?.[inner.name.value]
823
+ // };
824
+ })
825
+ .filter(Boolean);
574
826
  }
575
827
 
576
828
  /**
577
829
  * Make cache object from data and selection object
578
830
  */
579
831
 
580
- function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap?: any) {
581
- const cacheObj: Record<string, any> = {};
582
- const updatedKeys: string[] = [];
583
-
584
- for (const sel of selections) {
585
- const key = sel.name.value;
586
- if (data[key] === undefined && sel.kind !== 'FragmentSpread') {
587
- // console.log('~~~', key, sel.kind);
588
- continue;
589
- }
590
-
591
- switch (sel.kind) {
592
- case 'Field':
593
- {
594
- const innerSelections = sel.selectionSet?.selections;
595
- if (innerSelections) {
596
- if (Array.isArray(data[key])) {
597
- cacheObj[key] = {
598
- __cache: true,
599
- __list: true,
600
- data: data[key].map((item, itemIndex) =>
601
- mapSelections(item, innerSelections, updatedKeys, `${key}.${itemIndex}`)
602
- ),
603
- };
604
- } else {
605
- cacheObj[key] = {
606
- __cache: true,
607
- data: mapSelections(data[key], innerSelections, updatedKeys, key),
608
- };
609
- }
610
- } else {
611
- cacheObj[key] = data[key];
612
- }
613
- }
614
- break;
615
- case 'FragmentSpread':
616
- {
617
- const frgName = sel.name.value;
618
- const frgMap = PARTIALS_MAP[frgName];
619
- const fragmentKey = makeFragmentCacheKey(frgMap || frgName, data);
620
-
621
- if (RULES[frgName] !== false) {
622
- // if (testMode) {
623
- // console.log('Array.isArray(data)');
624
- // console.log(Array.isArray(data));
625
- // console.log(data);
626
- // console.log(extractFragment(data, selections));
627
- // }
628
-
629
- // Whether fragment is partial or not, always merge data;
630
- // Because partials might have data that's not in the main fragment
631
- const currentData = loadFragment(fragmentKey);
632
-
633
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
634
- // console.log('>>>>');
635
- // console.log('>>>>');
636
- // console.log('>>>>');
637
- // console.log('>>>>');
638
- // console.log(currentData);
639
- // console.log(data);
640
- // }
641
-
642
- // console.log('>>>>', fragmentKey);
643
- FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, extractFragment(data, selections)));
644
- updatedKeys.push(fragmentKey);
645
- }
646
-
647
- cacheObj.__flat = {
648
- __cache: true,
649
- data: [fragmentKey],
650
- };
651
- }
652
- break;
653
- default:
654
- }
655
-
656
- // If there's a cache map, return a custom value
657
- // This will make the cache object NOT get set into the query cache
658
- // This means that cache IS handled but the values will be invalid
659
- // so cacheMap has to handle the cache object itself
660
-
661
- if (cacheMap?.[key]) {
662
- const customCacheData = cacheMap[key](data[key], cacheObj[key], sel, variables);
663
- cacheObj[key] = typeof customCacheData === 'undefined' ? null : customCacheData;
664
- continue;
665
- }
666
- }
667
-
668
- if (cacheObj.__flat?.data?.[0]) {
669
- const spreadsFragmentKey = `${cacheObj.__flat.data[0]}.spreads`;
670
-
671
- let spreads: Record<string, any> | undefined;
672
- for (const cKey in cacheObj) {
673
- if (
674
- cKey !== '__flat' &&
675
- Object.prototype.hasOwnProperty.call(cacheObj, cKey)
676
- ) {
677
- if (!spreads) {
678
- spreads = {};
679
- }
680
-
681
- // Spreads here
682
-
683
- if (cacheObj[cKey]?.data?.length === 1 && typeof cacheObj[cKey]?.data?.[0] === 'string') {
684
- // Single spread with single fragment
685
- spreads[cKey] = cacheObj[cKey].data[0];
686
- } else if (cacheObj[cKey].__list === true) {
687
- // List of spreads
688
- spreads[cKey] = {
689
- __list: true,
690
- data: cacheObj[cKey].data
691
- };
692
- } else if (Array.isArray(cacheObj[cKey]?.data)) {
693
- // Spread with more spreads inside
694
- spreads[cKey] = cacheObj[cKey].data;
695
- }
696
- }
697
- }
698
-
699
- if (spreads) {
700
- // if (spreadsFragmentKey.startsWith('$emailFragment:')) {
701
- // console.log('>>>>', spreadsFragmentKey);
702
- // console.log(data);
703
- // console.log(spreads);
704
- // }
705
- const currentSpreads = FRAGMENTS.get(spreadsFragmentKey);
706
- FRAGMENTS.set(spreadsFragmentKey, mergeSpreads(currentSpreads, spreads));
707
- }
708
- }
709
-
710
- return [cacheObj, updatedKeys];
832
+ function makeCacheObject(
833
+ data: any,
834
+ selections: any[],
835
+ variables?: any,
836
+ cacheMap?: any,
837
+ ) {
838
+ const cacheObj: Record<string, any> = {};
839
+ const updatedKeys: string[] = [];
840
+
841
+ for (const sel of selections) {
842
+ const key = sel.name.value;
843
+ if (data[key] === undefined && sel.kind !== 'FragmentSpread') {
844
+ // console.log('~~~', key, sel.kind);
845
+ continue;
846
+ }
847
+
848
+ switch (sel.kind) {
849
+ case 'Field':
850
+ {
851
+ const innerSelections = sel.selectionSet?.selections;
852
+ if (innerSelections) {
853
+ if (Array.isArray(data[key])) {
854
+ cacheObj[key] = {
855
+ __cache: true,
856
+ __list: true,
857
+ data: data[key].map((item, itemIndex) =>
858
+ mapSelections(
859
+ item,
860
+ innerSelections,
861
+ updatedKeys,
862
+ `${key}.${itemIndex}`,
863
+ ),
864
+ ),
865
+ };
866
+ } else {
867
+ cacheObj[key] = {
868
+ __cache: true,
869
+ data: mapSelections(
870
+ data[key],
871
+ innerSelections,
872
+ updatedKeys,
873
+ key,
874
+ ),
875
+ };
876
+ }
877
+ } else {
878
+ cacheObj[key] = data[key];
879
+ }
880
+ }
881
+ break;
882
+ case 'FragmentSpread':
883
+ {
884
+ const frgName = sel.name.value;
885
+ const frgMap = PARTIALS_MAP[frgName];
886
+ const fragmentKey = makeFragmentCacheKey(frgMap || frgName, data);
887
+
888
+ if (RULES[frgName] !== false) {
889
+ // if (testMode) {
890
+ // console.log('Array.isArray(data)');
891
+ // console.log(Array.isArray(data));
892
+ // console.log(data);
893
+ // console.log(extractFragment(data, selections));
894
+ // }
895
+
896
+ // Whether fragment is partial or not, always merge data;
897
+ // Because partials might have data that's not in the main fragment
898
+ const currentData = loadFragment(fragmentKey);
899
+
900
+ // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
901
+ // console.log('>>>>');
902
+ // console.log('>>>>');
903
+ // console.log('>>>>');
904
+ // console.log('>>>>');
905
+ // console.log(currentData);
906
+ // console.log(data);
907
+ // }
908
+
909
+ // console.log('>>>>', fragmentKey);
910
+ FRAGMENTS.set(
911
+ fragmentKey,
912
+ mergeNestedObjects(
913
+ removeOptimisticUIObjectsFromArrayFields(currentData),
914
+ getPartialFragmentMergeData(
915
+ frgName,
916
+ extractFragment(data, selections),
917
+ ),
918
+ ),
919
+ );
920
+ updatedKeys.push(fragmentKey);
921
+ }
922
+
923
+ cacheObj.__flat = {
924
+ __cache: true,
925
+ data: [fragmentKey],
926
+ };
927
+ }
928
+ break;
929
+ default:
930
+ }
931
+
932
+ // If there's a cache map, return a custom value
933
+ // This will make the cache object NOT get set into the query cache
934
+ // This means that cache IS handled but the values will be invalid
935
+ // so cacheMap has to handle the cache object itself
936
+
937
+ if (cacheMap?.[key]) {
938
+ const customCacheData = cacheMap[key](
939
+ data[key],
940
+ cacheObj[key],
941
+ sel,
942
+ variables,
943
+ );
944
+ cacheObj[key] =
945
+ typeof customCacheData === 'undefined' ? null : customCacheData;
946
+ continue;
947
+ }
948
+ }
949
+
950
+ if (cacheObj.__flat?.data?.[0]) {
951
+ const spreadsFragmentKey = `${cacheObj.__flat.data[0]}.spreads`;
952
+
953
+ let spreads: Record<string, any> | undefined;
954
+ for (const cKey in cacheObj) {
955
+ if (
956
+ cKey !== '__flat' &&
957
+ Object.prototype.hasOwnProperty.call(cacheObj, cKey)
958
+ ) {
959
+ if (!spreads) {
960
+ spreads = {};
961
+ }
962
+
963
+ // Spreads here
964
+
965
+ if (
966
+ cacheObj[cKey]?.data?.length === 1 &&
967
+ typeof cacheObj[cKey]?.data?.[0] === 'string'
968
+ ) {
969
+ // Single spread with single fragment
970
+ spreads[cKey] = cacheObj[cKey].data[0];
971
+ } else if (cacheObj[cKey].__list === true) {
972
+ // List of spreads
973
+ spreads[cKey] = {
974
+ __list: true,
975
+ data: cacheObj[cKey].data,
976
+ };
977
+ } else if (Array.isArray(cacheObj[cKey]?.data)) {
978
+ // Spread with more spreads inside
979
+ spreads[cKey] = cacheObj[cKey].data;
980
+ }
981
+ }
982
+ }
983
+
984
+ if (spreads) {
985
+ // if (spreadsFragmentKey.startsWith('$emailFragment:')) {
986
+ // console.log('>>>>', spreadsFragmentKey);
987
+ // console.log(data);
988
+ // console.log(spreads);
989
+ // }
990
+ const currentSpreads = FRAGMENTS.get(spreadsFragmentKey);
991
+ FRAGMENTS.set(spreadsFragmentKey, mergeSpreads(currentSpreads, spreads));
992
+ }
993
+ }
994
+
995
+ return [cacheObj, updatedKeys];
711
996
  }
712
997
 
713
998
  /**
@@ -715,90 +1000,106 @@ function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap
715
1000
  */
716
1001
 
717
1002
  function saveQueryToMemory(
718
- requestData: any,
719
- selection: any,
720
- variables: any,
721
- variablesKey: string,
722
- cacheMap?: any,
723
- saveQueryToCache?: boolean,
724
- updateObservers?: UpdateObserversFn,
1003
+ requestData: any,
1004
+ selection: any,
1005
+ variables: any,
1006
+ variablesKey: string,
1007
+ cacheMap?: any,
1008
+ saveQueryToCache?: boolean,
1009
+ updateObservers?: UpdateObserversFn,
725
1010
  ) {
726
- const qryName = selection.name.value;
727
- if (!requestData) {
728
- return;
729
- }
730
-
731
- // IMPORTANT NOTE:
732
- // Queries are never cached unless they are manually set in [./config.ts]
733
-
734
- const data = requestData[qryName];
735
- const queryId = `#${qryName}:${variablesKey}`;
736
- const selections = selection?.selectionSet?.selections;
737
-
738
- if (!selections) {
739
- return;
740
- }
741
-
742
- if (data) {
743
- // console.log('=====');
744
- // console.log(requestData);
745
- // console.log(queryId);
746
- // console.log(data);
747
- // console.log('=====');
748
-
749
- const cacheMapObj = typeof cacheMap === 'function' ? null : cacheMap;
750
-
751
- let cacheData;
752
- let updatedFragmentIds;
753
- if (Array.isArray(data)) {
754
- const result = data.map((dataObj) => makeCacheObject(dataObj, selections, variables, cacheMapObj));
755
- cacheData = result.map((r) => r[0]);
756
- updatedFragmentIds = result.reduce((acc, r) => acc.concat(r[1]), []);
757
- } else {
758
- [cacheData, updatedFragmentIds] = makeCacheObject(data, selections, variables, cacheMapObj);
759
- }
760
-
761
- // console.log(updatedFragmentIds);
762
- // console.log(cacheData);
763
-
764
- if (typeof cacheMap === 'function') {
765
- // cacheMap[key](data[key], cacheObj[key], sel, variables);
766
- if (saveQueryToCache) {
767
- const customCacheData = cacheMap(data, cacheData, selections, variables);
768
- // console.log('1--->', queryId);
769
- // console.log('UPDATING (1):', typeof customCacheData === 'undefined' ? null : customCacheData);
770
- QUERIES.set(queryId, typeof customCacheData === 'undefined' ? null : customCacheData);
771
-
772
- if (updateObservers) {
773
- updateObservers({
774
- queryId
775
- });
776
- }
777
- }
778
- } else {
779
- if (saveQueryToCache) {
780
- // console.log('2--->', queryId);
781
- // console.log('2--->', cacheData);
782
- // console.log('UPDATING (2):', cacheData);
783
- QUERIES.set(queryId, cacheData);
784
- }
785
-
786
- if (updateObservers) {
787
- updateObservers({
788
- queryId: saveQueryToCache ? queryId : null,
789
- fragmentIds: updatedFragmentIds as string[],
790
- });
791
- }
792
-
793
- // I don't think observer is needed for custom cache maps, but if it does, bring it up
794
- // FRAGMENT_OBSERVER.value = {
795
- // count: FRAGMENT_OBSERVER.value.count + 1,
796
- // list: updatedFragmentIds,
797
- // };
798
- }
799
-
800
- return updatedFragmentIds;
801
- }
1011
+ const qryName = getGraphQLSelectionResponseName(selection);
1012
+ if (!requestData) {
1013
+ return;
1014
+ }
1015
+
1016
+ // IMPORTANT NOTE:
1017
+ // Queries are never cached unless they are manually set in [./config.ts]
1018
+
1019
+ const data = requestData[qryName];
1020
+ const queryId = `#${qryName}:${variablesKey}`;
1021
+ const selections = selection?.selectionSet?.selections;
1022
+
1023
+ if (!selections) {
1024
+ return;
1025
+ }
1026
+
1027
+ if (data) {
1028
+ // console.log('=====');
1029
+ // console.log(requestData);
1030
+ // console.log(queryId);
1031
+ // console.log(data);
1032
+ // console.log('=====');
1033
+
1034
+ const cacheMapObj = typeof cacheMap === 'function' ? null : cacheMap;
1035
+
1036
+ let cacheData;
1037
+ let updatedFragmentIds;
1038
+ if (Array.isArray(data)) {
1039
+ const result = data.map((dataObj) =>
1040
+ makeCacheObject(dataObj, selections, variables, cacheMapObj),
1041
+ );
1042
+ cacheData = result.map((r) => r[0]);
1043
+ updatedFragmentIds = result.reduce((acc, r) => acc.concat(r[1]), []);
1044
+ } else {
1045
+ [cacheData, updatedFragmentIds] = makeCacheObject(
1046
+ data,
1047
+ selections,
1048
+ variables,
1049
+ cacheMapObj,
1050
+ );
1051
+ }
1052
+
1053
+ // console.log(updatedFragmentIds);
1054
+ // console.log(cacheData);
1055
+
1056
+ if (typeof cacheMap === 'function') {
1057
+ // cacheMap[key](data[key], cacheObj[key], sel, variables);
1058
+ if (saveQueryToCache) {
1059
+ const customCacheData = cacheMap(
1060
+ data,
1061
+ cacheData,
1062
+ selections,
1063
+ variables,
1064
+ );
1065
+ // console.log('1--->', queryId);
1066
+ // console.log('UPDATING (1):', typeof customCacheData === 'undefined' ? null : customCacheData);
1067
+ QUERIES.set(
1068
+ queryId,
1069
+ typeof customCacheData === 'undefined' ? null : customCacheData,
1070
+ );
1071
+ cacheStore.setQueryFetchTime(queryId, Date.now());
1072
+
1073
+ if (updateObservers) {
1074
+ updateObservers({
1075
+ queryId,
1076
+ });
1077
+ }
1078
+ }
1079
+ } else {
1080
+ if (saveQueryToCache) {
1081
+ // console.log('2--->', queryId);
1082
+ // console.log('2--->', cacheData);
1083
+ // console.log('UPDATING (2):', cacheData);
1084
+ QUERIES.set(queryId, cacheData);
1085
+ cacheStore.setQueryFetchTime(queryId, Date.now());
1086
+ }
1087
+
1088
+ if (updateObservers) {
1089
+ updateObservers({
1090
+ fragmentIds: updatedFragmentIds as string[],
1091
+ });
1092
+ }
1093
+
1094
+ // I don't think observer is needed for custom cache maps, but if it does, bring it up
1095
+ // FRAGMENT_OBSERVER.value = {
1096
+ // count: FRAGMENT_OBSERVER.value.count + 1,
1097
+ // list: updatedFragmentIds,
1098
+ // };
1099
+ }
1100
+
1101
+ return updatedFragmentIds;
1102
+ }
802
1103
  }
803
1104
 
804
1105
  /**
@@ -810,168 +1111,205 @@ function saveQueryToMemory(
810
1111
  */
811
1112
 
812
1113
  export function setDataToCache(
813
- requestData: any,
814
- gqlQuery: any,
815
- variables?: any,
816
- cacheMap?: any,
817
- updateObservers?: UpdateObserversFn,
1114
+ requestData: any,
1115
+ gqlQuery: any,
1116
+ variables?: any,
1117
+ cacheMap?: any,
1118
+ updateObservers?: UpdateObserversFn,
818
1119
  ) {
819
- // query[variablesKey] = cache;
820
- const definitions = gqlQuery.definitions;
821
- const variablesKey = makeVariablesKey(variables);
822
-
823
- for (const def of definitions) {
824
- if (def.kind === 'OperationDefinition') {
825
- def?.selectionSet?.selections.forEach((selection: any) => {
826
- const qryName = selection.name?.value;
827
- saveQueryToMemory(
828
- requestData,
829
- selection,
830
- variables,
831
- variablesKey,
832
- cacheMap,
833
- !!RULES[qryName],
834
- updateObservers
835
- );
836
- });
837
- }
838
- }
1120
+ // query[variablesKey] = cache;
1121
+ const definitions = gqlQuery.definitions;
1122
+ const variablesKey = makeVariablesKey(variables);
1123
+
1124
+ for (const def of definitions) {
1125
+ if (def.kind === 'OperationDefinition') {
1126
+ def?.selectionSet?.selections.forEach((selection: any) => {
1127
+ const qryName = selection.name?.value;
1128
+ saveQueryToMemory(
1129
+ requestData,
1130
+ selection,
1131
+ variables,
1132
+ variablesKey,
1133
+ cacheMap,
1134
+ RULES[qryName] !== false,
1135
+ updateObservers,
1136
+ );
1137
+ });
1138
+ }
1139
+ }
839
1140
  }
840
1141
 
841
1142
  /**
842
1143
  * Append fragment to cache
843
1144
  */
844
1145
 
845
- export function appendFragmentToCache(cacheData: any, testMode?: boolean) {
846
- let newObj = cloneArrayLike(cacheData);
847
- let flatObj: any;
848
-
849
- // if (testMode) {
850
- // console.log('appendFragmentToCache:', newObj);
851
- // }
852
-
853
- for (const key in newObj) {
854
-
855
- // if (testMode) {
856
- // console.log('******* key:', key);
857
- // console.log('******* ??:', newObj[key]);
858
- // }
859
-
860
- if (newObj[key] && typeof newObj[key] === 'object') {
861
- const isFlat = key === '__flat';
862
- const isCache = newObj[key].__cache && newObj[key].data;
863
-
864
- if (isCache) {
865
- let cachedObj: any = {};
866
- let cacheIsValid = true;
867
-
868
- if (newObj[key].__list) {
869
- cachedObj = newObj[key].data.map((di: any[]) => {
870
- const item = mapCachedListItem(di, loadFragment);
871
- if (!item) {
872
- cacheIsValid = false;
873
- return {};
874
- }
875
-
876
- return item;
877
- });
878
- } else {
879
- newObj[key].data.forEach((d: any) => {
880
-
881
- // if (testMode) {
882
- // console.log('cachedObj', cachedObj);
883
- // console.log('key', key);
884
- // console.log('d', d);
885
- // console.log('d', typeof d);
886
- // }
887
-
888
- if (Array.isArray(d)) {
889
- cachedObj[d[0]] = d[1];
890
- } else if (typeof d === 'string') {
891
- const frgIndex = d.indexOf(':');
892
- const frgName = d.substring(1, frgIndex);
893
- const frgMap = PARTIALS_MAP[frgName];
894
-
895
- let fragmentKey;
896
- if (frgMap) {
897
- fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
898
- } else {
899
- fragmentKey = d;
900
- }
901
-
902
- const cachedFragment = loadFragment(fragmentKey);
903
-
904
- if (cachedFragment) {
905
- if (isFlat) {
906
- // if (testMode) {
907
- // console.log('///////');
908
- // console.log('///////');
909
- // console.log('newObj before:', newObj);
910
- // console.log('fragmentKey:', fragmentKey);
911
- // console.log('cachedFragment:', cachedFragment);
912
- // }
913
-
914
- // newObj = {
915
- // ...newObj,
916
- // ...cachedFragment,
917
- // };
918
-
919
- flatObj = cachedFragment,
920
- delete newObj.__flat;
921
- } else {
922
- cachedObj = {
923
- ...cachedObj,
924
- ...cachedFragment,
925
- };
926
- }
927
- } else {
928
- // Cache was invalidated
929
- cacheIsValid = false;
930
- }
931
- }
932
- });
933
- }
934
-
935
- if (!cacheIsValid) {
936
- return null;
937
- }
938
-
939
- if (!isFlat) {
940
- newObj[key] = cachedObj;
941
- }
942
- } else {
943
-
944
- // Fragment spreads recursively loads the fragment data
945
- // So we have to get the non-spread fields from query cache
946
-
947
- const cacheInfo = cacheData[key];
948
- if (newObj[key] && typeof newObj[key] === 'object' && cacheInfo?.__cache && cacheInfo.data) {
949
- cacheInfo.data.forEach((di: any) => {
950
- if (
951
- Array.isArray(di) &&
952
- di.length === 2 &&
953
- !di?.[0]?.startsWith('$')
954
- ) {
955
- newObj[key][di[0]] = di[1];
956
- }
957
- });
958
- }
959
- }
960
- }
961
- }
962
-
963
- // Merge flat data
964
-
965
- if (flatObj) {
966
- for (const key in flatObj) {
967
- // console.log('FLAT:', key, flatObj[key], newObj[key]);
968
- if (newObj[key] === undefined) {
969
- newObj[key] = flatObj[key];
970
- }
971
- }
972
- }
973
-
974
- return newObj;
1146
+ export function appendFragmentToCache(
1147
+ cacheData: any,
1148
+ testMode?: boolean,
1149
+ queryVersion = 0,
1150
+ ) {
1151
+ let newObj = cloneArrayLike(cacheData);
1152
+ let flatObj: any;
1153
+ const flatSpreadKeys = new Set<string>();
1154
+
1155
+ // Keys assembled from a list stored in the query cache, plus how recently the
1156
+ // flat fragment's own spread copy was written. Both sides can hold the newest
1157
+ // list (a mutation writes the fragment spread; append/prepend writes grow the
1158
+ // query list), so the more recent write wins. Version stamps come from one
1159
+ // monotonic counter, which makes them directly comparable.
1160
+ const queryListKeys = new Set<string>();
1161
+ let flatSpreadVersion = 0;
1162
+
1163
+ // if (testMode) {
1164
+ // console.log('appendFragmentToCache:', newObj);
1165
+ // }
1166
+
1167
+ for (const key in newObj) {
1168
+ // if (testMode) {
1169
+ // console.log('******* key:', key);
1170
+ // console.log('******* ??:', newObj[key]);
1171
+ // }
1172
+
1173
+ if (newObj[key] && typeof newObj[key] === 'object') {
1174
+ const isFlat = key === '__flat';
1175
+ const isCache = newObj[key].__cache && newObj[key].data;
1176
+
1177
+ if (isCache) {
1178
+ let cachedObj: any = {};
1179
+ let cacheIsValid = true;
1180
+
1181
+ if (newObj[key].__list) {
1182
+ if (!isFlat) {
1183
+ queryListKeys.add(key);
1184
+ }
1185
+
1186
+ cachedObj = newObj[key].data.map((di: any[]) => {
1187
+ const item = mapCachedListItem(di, loadFragment);
1188
+ if (!item) {
1189
+ cacheIsValid = false;
1190
+ return {};
1191
+ }
1192
+
1193
+ return item;
1194
+ });
1195
+ } else {
1196
+ newObj[key].data.forEach((d: any) => {
1197
+ // if (testMode) {
1198
+ // console.log('cachedObj', cachedObj);
1199
+ // console.log('key', key);
1200
+ // console.log('d', d);
1201
+ // console.log('d', typeof d);
1202
+ // }
1203
+
1204
+ if (Array.isArray(d)) {
1205
+ cachedObj[d[0]] = d[1];
1206
+ } else if (typeof d === 'string') {
1207
+ const frgIndex = d.indexOf(':');
1208
+ const frgName = d.substring(1, frgIndex);
1209
+ const frgMap = PARTIALS_MAP[frgName];
1210
+
1211
+ let fragmentKey;
1212
+ if (frgMap) {
1213
+ fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
1214
+ } else {
1215
+ fragmentKey = d;
1216
+ }
1217
+
1218
+ const cachedFragment = loadFragment(fragmentKey);
1219
+
1220
+ if (cachedFragment) {
1221
+ if (isFlat) {
1222
+ // if (testMode) {
1223
+ // console.log('///////');
1224
+ // console.log('///////');
1225
+ // console.log('newObj before:', newObj);
1226
+ // console.log('fragmentKey:', fragmentKey);
1227
+ // console.log('cachedFragment:', cachedFragment);
1228
+ // }
1229
+
1230
+ // newObj = {
1231
+ // ...newObj,
1232
+ // ...cachedFragment,
1233
+ // };
1234
+
1235
+ flatObj = cachedFragment;
1236
+ flatSpreadVersion = Math.max(
1237
+ FRAGMENTS.version(fragmentKey),
1238
+ FRAGMENTS.version(`${fragmentKey}.spreads`),
1239
+ );
1240
+ Object.keys(
1241
+ FRAGMENTS.get(`${fragmentKey}.spreads`) || {},
1242
+ ).forEach((spreadKey) => {
1243
+ flatSpreadKeys.add(spreadKey);
1244
+ });
1245
+ delete newObj.__flat;
1246
+ } else {
1247
+ cachedObj = {
1248
+ ...cachedObj,
1249
+ ...cachedFragment,
1250
+ };
1251
+ }
1252
+ } else {
1253
+ // Cache was invalidated
1254
+ cacheIsValid = false;
1255
+ }
1256
+ }
1257
+ });
1258
+ }
1259
+
1260
+ if (!cacheIsValid) {
1261
+ return null;
1262
+ }
1263
+
1264
+ if (!isFlat) {
1265
+ newObj[key] = cachedObj;
1266
+ }
1267
+ } else {
1268
+ // Fragment spreads recursively loads the fragment data
1269
+ // So we have to get the non-spread fields from query cache
1270
+
1271
+ const cacheInfo = cacheData[key];
1272
+ if (
1273
+ newObj[key] &&
1274
+ typeof newObj[key] === 'object' &&
1275
+ cacheInfo?.__cache &&
1276
+ cacheInfo.data
1277
+ ) {
1278
+ cacheInfo.data.forEach((di: any) => {
1279
+ if (
1280
+ Array.isArray(di) &&
1281
+ di.length === 2 &&
1282
+ !di?.[0]?.startsWith('$')
1283
+ ) {
1284
+ newObj[key][di[0]] = di[1];
1285
+ }
1286
+ });
1287
+ }
1288
+ }
1289
+ }
1290
+ }
1291
+
1292
+ // Merge flat data
1293
+
1294
+ if (flatObj) {
1295
+ for (const key in flatObj) {
1296
+ // console.log('FLAT:', key, flatObj[key], newObj[key]);
1297
+ // Spread-backed fields can be refreshed by mutation writes even when the query cache is stale.
1298
+ // A query-cache list is the one contested case: it holds every item appended
1299
+ // since the fragment was written, so the flat copy may only replace it when
1300
+ // that copy is the newer write. Otherwise the list truncates back to
1301
+ // whatever the last full response happened to contain.
1302
+ const flatCopyWins =
1303
+ flatSpreadKeys.has(key) &&
1304
+ (!queryListKeys.has(key) || flatSpreadVersion > queryVersion);
1305
+
1306
+ if (newObj[key] === undefined || flatCopyWins) {
1307
+ newObj[key] = flatObj[key];
1308
+ }
1309
+ }
1310
+ }
1311
+
1312
+ return newObj;
975
1313
  }
976
1314
 
977
1315
  /**
@@ -979,91 +1317,100 @@ export function appendFragmentToCache(cacheData: any, testMode?: boolean) {
979
1317
  */
980
1318
 
981
1319
  export function loadDataFromCache(
982
- requestData: any | null,
983
- gqlQuery: any,
984
- variablesKey: string,
985
- cacheMap?: any,
986
- eagerFragmentKeyMap?: any,
987
- testMode?: boolean,
1320
+ requestData: any | null,
1321
+ gqlQuery: any,
1322
+ variablesKey: string,
1323
+ cacheMap?: any,
1324
+ eagerFragmentKeyMap?: any,
1325
+ allowQueryCacheFallback = true,
988
1326
  ) {
989
- // return query[variablesKey];
990
- const data = { ...requestData };
991
- const definitions = gqlQuery.definitions;
992
-
993
- for (const def of definitions) {
994
- if (def.kind === 'OperationDefinition') {
995
- def?.selectionSet?.selections.forEach((selection: any) => {
996
- const qryName = selection.name?.value;
997
- if (!data[qryName]) {
998
- const cacheKey = `#${qryName}:${variablesKey}`;
999
- const cachedData = loadQuery(cacheKey);
1000
-
1001
- if (cachedData) {
1002
- data[qryName] = cachedData;
1003
- }
1004
-
1005
- // const cacheData = QUERIES.get(cacheKey);
1006
-
1007
- // if (Array.isArray(cacheData)) {
1008
- // let hasInvalidatedCache = false;
1009
- // const mappedCache = cacheData.map((cacheObj, i) => {
1010
- // if (!hasInvalidatedCache) {
1011
- // const singleCache = appendFragmentToCache(cacheObj);
1012
-
1013
- // if (singleCache) {
1014
- // return singleCache;
1015
- // } else {
1016
- // hasInvalidatedCache = true;
1017
- // }
1018
- // }
1019
- // });
1020
-
1021
- // if (!hasInvalidatedCache) {
1022
- // data[qryName] = mappedCache;
1023
- // }
1024
- // } else if (cacheData) {
1025
- // const singleCacheData = appendFragmentToCache(cacheData);
1026
-
1027
- // if (singleCacheData) {
1028
- // data[qryName] = singleCacheData;
1029
- // }
1030
- // }
1031
- }
1032
-
1033
- // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
1034
-
1035
- if (data[qryName]) {
1036
- if (typeof cacheMap === 'function') {
1037
- data[qryName] = true;
1038
- } else if (cacheMap) {
1039
- for (const key in cacheMap) {
1040
- if (cacheMap?.[key] && data[qryName]?.[key] !== undefined) {
1041
- data[qryName][key] = true;
1042
- }
1043
- }
1044
- }
1045
- } else if (eagerFragmentKeyMap?.[qryName]) {
1046
- const fragmentKey = eagerFragmentKeyMap[qryName];
1047
- const cachedFragment = loadFragment(fragmentKey);
1048
-
1049
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
1050
- // console.log('>>>>');
1051
- // console.log('>>>>');
1052
- // console.log('>>>>');
1053
- // console.log('>>>>');
1054
- // console.log(cachedFragment);
1055
- // console.log(data);
1056
- // }
1057
-
1058
- if (cachedFragment) {
1059
- data[qryName] = cachedFragment;
1060
- }
1061
- }
1062
- });
1063
- }
1064
- }
1065
-
1066
- return data;
1327
+ // return query[variablesKey];
1328
+ const data = { ...requestData };
1329
+ const definitions = gqlQuery.definitions;
1330
+
1331
+ for (const def of definitions) {
1332
+ if (def.kind === 'OperationDefinition') {
1333
+ def?.selectionSet?.selections.forEach((selection: any) => {
1334
+ const qryName = getGraphQLSelectionResponseName(selection);
1335
+ if (!data[qryName] && allowQueryCacheFallback) {
1336
+ const cacheKey = `#${qryName}:${variablesKey}`;
1337
+ const cachedData = loadQuery(cacheKey);
1338
+
1339
+ if (cachedData) {
1340
+ data[qryName] = cachedData;
1341
+ }
1342
+
1343
+ // const cacheData = QUERIES.get(cacheKey);
1344
+
1345
+ // if (Array.isArray(cacheData)) {
1346
+ // let hasInvalidatedCache = false;
1347
+ // const mappedCache = cacheData.map((cacheObj, i) => {
1348
+ // if (!hasInvalidatedCache) {
1349
+ // const singleCache = appendFragmentToCache(cacheObj);
1350
+
1351
+ // if (singleCache) {
1352
+ // return singleCache;
1353
+ // } else {
1354
+ // hasInvalidatedCache = true;
1355
+ // }
1356
+ // }
1357
+ // });
1358
+
1359
+ // if (!hasInvalidatedCache) {
1360
+ // data[qryName] = mappedCache;
1361
+ // }
1362
+ // } else if (cacheData) {
1363
+ // const singleCacheData = appendFragmentToCache(cacheData);
1364
+
1365
+ // if (singleCacheData) {
1366
+ // data[qryName] = singleCacheData;
1367
+ // }
1368
+ // }
1369
+ }
1370
+
1371
+ // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
1372
+
1373
+ if (data[qryName]) {
1374
+ if (typeof cacheMap === 'function') {
1375
+ data[qryName] = true;
1376
+ } else if (cacheMap) {
1377
+ for (const key in cacheMap) {
1378
+ if (
1379
+ cacheMap?.[key] &&
1380
+ data[qryName]?.[key] !== undefined &&
1381
+ data[qryName][key] !== true
1382
+ ) {
1383
+ // Clone before stamping; the source object may be a shared
1384
+ // memoized cache assembly that must stay unmutated.
1385
+ data[qryName] = {
1386
+ ...data[qryName],
1387
+ [key]: true,
1388
+ };
1389
+ }
1390
+ }
1391
+ }
1392
+ } else if (eagerFragmentKeyMap?.[qryName]) {
1393
+ const fragmentKey = eagerFragmentKeyMap[qryName];
1394
+ const cachedFragment = loadFragment(fragmentKey);
1395
+
1396
+ // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
1397
+ // console.log('>>>>');
1398
+ // console.log('>>>>');
1399
+ // console.log('>>>>');
1400
+ // console.log('>>>>');
1401
+ // console.log(cachedFragment);
1402
+ // console.log(data);
1403
+ // }
1404
+
1405
+ if (cachedFragment) {
1406
+ data[qryName] = cachedFragment;
1407
+ }
1408
+ }
1409
+ });
1410
+ }
1411
+ }
1412
+
1413
+ return data;
1067
1414
  }
1068
1415
 
1069
1416
  /**
@@ -1071,25 +1418,29 @@ export function loadDataFromCache(
1071
1418
  */
1072
1419
 
1073
1420
  export function checkDataCompleteness(requestData: any, gqlQuery: any) {
1074
- if (!requestData) {
1075
- return false;
1076
- }
1077
-
1078
- const definitions = gqlQuery.definitions;
1079
- for (const def of definitions) {
1080
- if (def.kind === 'OperationDefinition') {
1081
- const selections = def?.selectionSet?.selections;
1082
- for (const selection of selections) {
1083
- const qryName = selection.name?.value;
1084
- const value = requestData[qryName];
1085
- if (!value && value !== false && value !== 0) {
1086
- return false;
1087
- }
1088
- }
1089
- }
1090
- }
1091
-
1092
- return true;
1421
+ if (!requestData) {
1422
+ return false;
1423
+ }
1424
+
1425
+ const definitions = gqlQuery.definitions;
1426
+ for (const def of definitions) {
1427
+ if (def.kind === 'OperationDefinition') {
1428
+ const selections = def?.selectionSet?.selections;
1429
+ for (const selection of selections) {
1430
+ const qryName = getGraphQLSelectionResponseName(selection);
1431
+ const value = requestData[qryName];
1432
+ // An explicit null is a complete server answer (e.g. a deleted or
1433
+ // invalid id); only a missing key means the field was never fetched.
1434
+ // This must match hasCompleteSelectionSetData()'s null handling, or
1435
+ // useQuery() refetches null results forever.
1436
+ if (value === undefined) {
1437
+ return false;
1438
+ }
1439
+ }
1440
+ }
1441
+ }
1442
+
1443
+ return true;
1093
1444
  }
1094
1445
 
1095
1446
  /**
@@ -1097,38 +1448,48 @@ export function checkDataCompleteness(requestData: any, gqlQuery: any) {
1097
1448
  */
1098
1449
 
1099
1450
  export function removeStaleCache() {
1100
- // function getByteSize(oMap){
1101
- // function replacer(key, value) {
1102
- // if(value instanceof Map) {
1103
- // return {
1104
- // dataType: 'Map',
1105
- // value: [...value],
1106
- // };
1107
- // } else {
1108
- // return value;
1109
- // }
1110
- // }
1111
- // return JSON.stringify(oMap, replacer).length;
1112
- // }
1113
-
1114
- // console.log(' Queries cache size (count):', QUERIES.size);
1115
- // console.log(' Queries cache size (bytes):', getByteSize(QUERIES));
1116
- // console.log('Fragments cache size (count):', FRAGMENTS.size);
1117
- // console.log('Fragments cache size (bytes):', getByteSize(FRAGMENTS));
1118
-
1119
- if (FRAGMENTS.size > RULES.__limit) {
1120
- const keys = Array.from(FRAGMENTS.keys());
1121
- const numToEvict = keys.length - RULES.__limit;
1122
-
1123
- if (numToEvict > 0) {
1124
- const keysToEvict = keys.slice(0, numToEvict);
1125
-
1126
- for (const key of keysToEvict) {
1127
- FRAGMENTS.delete(key);
1128
- FRAGMENTS.delete(`${key}.spreads`);
1129
- }
1130
- }
1131
- }
1451
+ // function getByteSize(oMap){
1452
+ // function replacer(key, value) {
1453
+ // if(value instanceof Map) {
1454
+ // return {
1455
+ // dataType: 'Map',
1456
+ // value: [...value],
1457
+ // };
1458
+ // } else {
1459
+ // return value;
1460
+ // }
1461
+ // }
1462
+ // return JSON.stringify(oMap, replacer).length;
1463
+ // }
1464
+
1465
+ // console.log(' Queries cache size (count):', QUERIES.size);
1466
+ // console.log(' Queries cache size (bytes):', getByteSize(QUERIES));
1467
+ // console.log('Fragments cache size (count):', FRAGMENTS.size);
1468
+ // console.log('Fragments cache size (bytes):', getByteSize(FRAGMENTS));
1469
+
1470
+ if (FRAGMENTS.size > RULES.__limit) {
1471
+ const numToEvict = FRAGMENTS.size - RULES.__limit;
1472
+
1473
+ // Least-recently-accessed fragments go first; a fragment and its spreads
1474
+ // sidecar are always evicted together.
1475
+ const lruKeys = FRAGMENTS.keysByLeastRecentAccess(
1476
+ (key) => !key.endsWith('.spreads'),
1477
+ );
1478
+
1479
+ let evictedCount = 0;
1480
+ for (const key of lruKeys) {
1481
+ if (evictedCount >= numToEvict) {
1482
+ break;
1483
+ }
1484
+
1485
+ FRAGMENTS.delete(key);
1486
+ evictedCount += 1;
1487
+
1488
+ if (FRAGMENTS.delete(`${key}.spreads`)) {
1489
+ evictedCount += 1;
1490
+ }
1491
+ }
1492
+ }
1132
1493
  }
1133
1494
 
1134
1495
  /**
@@ -1136,28 +1497,28 @@ export function removeStaleCache() {
1136
1497
  */
1137
1498
 
1138
1499
  function makeFragmentDefinitionMap(definitions: any[]) {
1139
- return definitions.reduce((acc, def) => {
1140
- if (def.kind === 'FragmentDefinition' && def.name?.value) {
1141
- acc[def.name.value] = def;
1142
- }
1143
-
1144
- return acc;
1145
- }, {} as Record<string, any>);
1500
+ return definitions.reduce(
1501
+ (acc, def) => {
1502
+ if (def.kind === 'FragmentDefinition' && def.name?.value) {
1503
+ acc[def.name.value] = def;
1504
+ }
1505
+
1506
+ return acc;
1507
+ },
1508
+ {} as Record<string, any>,
1509
+ );
1146
1510
  }
1147
1511
 
1148
1512
  /**
1149
1513
  * Check whether an inline fragment applies to the current cached object type.
1150
1514
  */
1151
- function inlineFragmentMatchesCachedType(
1152
- value: any,
1153
- selection: any,
1154
- ) {
1155
- const typeName = selection.typeCondition?.name?.value;
1156
- if (!typeName || !value?.__typename) {
1157
- return true;
1158
- }
1515
+ function inlineFragmentMatchesCachedType(value: any, selection: any) {
1516
+ const typeName = selection.typeCondition?.name?.value;
1517
+ if (!typeName || !value?.__typename) {
1518
+ return true;
1519
+ }
1159
1520
 
1160
- return value.__typename === typeName;
1521
+ return value.__typename === typeName;
1161
1522
  }
1162
1523
 
1163
1524
  /**
@@ -1165,67 +1526,67 @@ function inlineFragmentMatchesCachedType(
1165
1526
  */
1166
1527
 
1167
1528
  function hasCompleteSelectionData(
1168
- value: any,
1169
- selection: any,
1170
- fragmentDefinitions: Record<string, any>,
1529
+ value: any,
1530
+ selection: any,
1531
+ fragmentDefinitions: Record<string, any>,
1171
1532
  ): boolean {
1172
- if (value === null) {
1173
- return true;
1174
- }
1175
-
1176
- if (value === undefined) {
1177
- return false;
1178
- }
1179
-
1180
- if (selection.kind === 'FragmentSpread') {
1181
- const fragmentDef = fragmentDefinitions[selection.name?.value];
1182
- return fragmentDef
1183
- ? hasCompleteSelectionSetData(
1184
- value,
1185
- fragmentDef.selectionSet?.selections || [],
1186
- fragmentDefinitions,
1187
- )
1188
- : true;
1189
- }
1190
-
1191
- if (selection.kind === 'InlineFragment') {
1192
- if (!inlineFragmentMatchesCachedType(value, selection)) {
1193
- return true;
1194
- }
1195
-
1196
- return hasCompleteSelectionSetData(
1197
- value,
1198
- selection.selectionSet?.selections || [],
1199
- fragmentDefinitions,
1200
- );
1201
- }
1202
-
1203
- if (selection.kind !== 'Field') {
1204
- return true;
1205
- }
1206
-
1207
- const fieldName = selection.name?.value;
1208
- const fieldValue = value?.[fieldName];
1209
- if (fieldValue === undefined) {
1210
- return false;
1211
- }
1212
-
1213
- const selections = selection.selectionSet?.selections;
1214
- if (!selections || fieldValue === null) {
1215
- return true;
1216
- }
1217
-
1218
- if (Array.isArray(fieldValue)) {
1219
- return fieldValue.every((item) =>
1220
- hasCompleteSelectionSetData(item, selections, fragmentDefinitions)
1221
- );
1222
- }
1223
-
1224
- return hasCompleteSelectionSetData(
1225
- fieldValue,
1226
- selections,
1227
- fragmentDefinitions,
1228
- );
1533
+ if (value === null) {
1534
+ return true;
1535
+ }
1536
+
1537
+ if (value === undefined) {
1538
+ return false;
1539
+ }
1540
+
1541
+ if (selection.kind === 'FragmentSpread') {
1542
+ const fragmentDef = fragmentDefinitions[selection.name?.value];
1543
+ return fragmentDef
1544
+ ? hasCompleteSelectionSetData(
1545
+ value,
1546
+ fragmentDef.selectionSet?.selections || [],
1547
+ fragmentDefinitions,
1548
+ )
1549
+ : true;
1550
+ }
1551
+
1552
+ if (selection.kind === 'InlineFragment') {
1553
+ if (!inlineFragmentMatchesCachedType(value, selection)) {
1554
+ return true;
1555
+ }
1556
+
1557
+ return hasCompleteSelectionSetData(
1558
+ value,
1559
+ selection.selectionSet?.selections || [],
1560
+ fragmentDefinitions,
1561
+ );
1562
+ }
1563
+
1564
+ if (selection.kind !== 'Field') {
1565
+ return true;
1566
+ }
1567
+
1568
+ const fieldName = getGraphQLSelectionResponseName(selection);
1569
+ const fieldValue = value?.[fieldName];
1570
+ if (fieldValue === undefined) {
1571
+ return false;
1572
+ }
1573
+
1574
+ const selections = selection.selectionSet?.selections;
1575
+ if (!selections || fieldValue === null) {
1576
+ return true;
1577
+ }
1578
+
1579
+ if (Array.isArray(fieldValue)) {
1580
+ return fieldValue.every((item) =>
1581
+ hasCompleteSelectionSetData(item, selections, fragmentDefinitions),
1582
+ );
1583
+ }
1584
+
1585
+ return hasCompleteSelectionSetData(
1586
+ fieldValue,
1587
+ selections,
1588
+ fragmentDefinitions,
1589
+ );
1229
1590
  }
1230
1591
 
1231
1592
  /**
@@ -1233,78 +1594,136 @@ function hasCompleteSelectionData(
1233
1594
  */
1234
1595
 
1235
1596
  function hasCompleteSelectionSetData(
1236
- value: any,
1237
- selections: any[],
1238
- fragmentDefinitions: Record<string, any>,
1597
+ value: any,
1598
+ selections: any[],
1599
+ fragmentDefinitions: Record<string, any>,
1239
1600
  ): boolean {
1240
- if (value === null) {
1241
- return true;
1242
- }
1601
+ if (value === null) {
1602
+ return true;
1603
+ }
1243
1604
 
1244
- if (value === undefined) {
1245
- return false;
1246
- }
1605
+ if (value === undefined) {
1606
+ return false;
1607
+ }
1247
1608
 
1248
- return selections.every((selection) =>
1249
- hasCompleteSelectionData(value, selection, fragmentDefinitions)
1250
- );
1609
+ return selections.every((selection) =>
1610
+ hasCompleteSelectionData(value, selection, fragmentDefinitions),
1611
+ );
1251
1612
  }
1252
1613
 
1253
1614
  /**
1254
1615
  * Check if there is cache
1255
1616
  */
1256
1617
 
1257
- export function fetchCachedData(gqlQuery: any, variablesKey: string, updateObservers: UpdateObserversFn) {
1258
- const definitions = gqlQuery.definitions;
1259
- const fragmentDefinitions = makeFragmentDefinitionMap(definitions);
1260
-
1261
- for (const def of definitions) {
1262
- if (def.kind === 'OperationDefinition') {
1263
- const selections = def?.selectionSet?.selections;
1264
- for (const selection of selections) {
1265
- const qryName = selection.name?.value;
1266
- const queryId = `#${qryName}:${variablesKey}`;
1267
-
1268
- const cachedData = loadQuery(queryId);
1269
- if (cachedData === null) {
1270
- return null;
1271
- }
1272
-
1273
- if (!cachedData) {
1274
- QUERIES.delete(queryId);
1275
-
1276
- updateObservers({
1277
- queryId
1278
- });
1279
-
1280
- return null;
1281
- }
1618
+ export function fetchCachedData(
1619
+ gqlQuery: any,
1620
+ variablesKey: string,
1621
+ _updateObservers?: UpdateObserversFn,
1622
+ ) {
1623
+ const definitions = gqlQuery.definitions;
1624
+ const fragmentDefinitions = makeFragmentDefinitionMap(definitions);
1625
+ const queryDocumentCacheId = getQueryDocumentCacheId(gqlQuery);
1626
+
1627
+ for (const def of definitions) {
1628
+ if (def.kind === 'OperationDefinition') {
1629
+ const selections = def?.selectionSet?.selections;
1630
+ for (const selection of selections) {
1631
+ const qryName = getGraphQLSelectionResponseName(selection);
1632
+ const queryId = `#${qryName}:${variablesKey}`;
1633
+
1634
+ // Completeness validation walks the full selected result tree. Cache
1635
+ // that validated snapshot against the normalized query/fragment
1636
+ // versions so warm route mounts reuse both the work and reference.
1637
+ return cacheStore.memoizeRead(
1638
+ `VQ|${queryDocumentCacheId}|${queryId}`,
1639
+ () => {
1640
+ const cachedData = loadQuery(queryId);
1641
+ if (cachedData === null) {
1642
+ return null;
1643
+ }
1644
+
1645
+ if (!cachedData) {
1646
+ return null;
1647
+ }
1648
+
1649
+ if (
1650
+ !hasCompleteSelectionData(
1651
+ { [qryName]: cachedData },
1652
+ selection,
1653
+ fragmentDefinitions,
1654
+ )
1655
+ ) {
1656
+ return null;
1657
+ }
1658
+
1659
+ return { [qryName]: cachedData };
1660
+ },
1661
+ );
1662
+ }
1663
+ }
1664
+ }
1665
+
1666
+ return null;
1667
+ }
1282
1668
 
1283
- if (!hasCompleteSelectionData({ [qryName]: cachedData }, selection, fragmentDefinitions)) {
1284
- QUERIES.delete(queryId);
1669
+ /**
1670
+ * Clear all cache
1671
+ */
1285
1672
 
1286
- updateObservers({
1287
- queryId,
1288
- });
1673
+ export function clearGraphQLClientCache() {
1674
+ cacheStore.clearAll();
1675
+ RESET_TIME.clear();
1676
+ clearGraphQLCachePersistence();
1289
1677
 
1290
- return null;
1291
- }
1678
+ // Locally persisted drafts hold content the user typed; a shared machine
1679
+ // must not keep it after sign-out or an access change
1680
+ clearAllDrafts();
1681
+ }
1292
1682
 
1293
- return { [qryName]: cachedData };
1294
- }
1295
- }
1296
- }
1683
+ /**
1684
+ * Return when one query's cached data last came from the network (ms epoch),
1685
+ * or undefined when it never did in this session or persisted snapshot.
1686
+ */
1297
1687
 
1298
- return null;
1688
+ export function getQueryLastFetchedAt(queryKey: string): number | undefined {
1689
+ return cacheStore.getQueryFetchTime(queryKey);
1299
1690
  }
1300
1691
 
1301
1692
  /**
1302
- * Clear all cache
1693
+ * Build a combined version stamp for fragment keys (and their spreads).
1694
+ * Hooks compare stamps to skip rebuilding merged data when an observer
1695
+ * notification did not actually change any observed fragment.
1303
1696
  */
1304
1697
 
1305
- export function clearGraphQLClientCache() {
1306
- QUERIES.clear();
1307
- FRAGMENTS.clear();
1698
+ export function getFragmentVersionStamp(fragmentKeys: string[]): string {
1699
+ return cacheStore.getFragmentVersionStamp(fragmentKeys);
1700
+ }
1701
+
1702
+ /*
1703
+ * Return the query observer count a hook should acknowledge after a network
1704
+ * attempt. External force-refetch observers must be acknowledged even when no
1705
+ * cached result existed before the request, otherwise the hook sees the same
1706
+ * observer count again and repeats the request.
1707
+ */
1708
+ export function getNextQueryLastUpdatedCount(
1709
+ currentLastUpdatedCount: number,
1710
+ observedUpdatedCount: number,
1711
+ ownQueryObserverCount: number,
1712
+ ) {
1713
+ const acknowledgedUpdatedCount = Math.max(
1714
+ currentLastUpdatedCount || 0,
1715
+ observedUpdatedCount || 0,
1716
+ );
1717
+
1718
+ if (!ownQueryObserverCount) {
1719
+ return acknowledgedUpdatedCount;
1720
+ }
1721
+
1722
+ return Math.max(
1723
+ acknowledgedUpdatedCount,
1724
+ (observedUpdatedCount || currentLastUpdatedCount || 0) +
1725
+ ownQueryObserverCount,
1726
+ );
1308
1727
  }
1309
1728
 
1310
1729
  /**
@@ -1312,16 +1731,16 @@ export function clearGraphQLClientCache() {
1312
1731
  */
1313
1732
 
1314
1733
  export function getQueryRefreshTime(queryName: string, variablesKey: string) {
1315
- // if (RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`)) {
1316
- // console.log(`#${queryName}:${variablesKey}`);
1317
- // console.log('1 >>>>>>>', RESET_TIME.get(`#${queryName}:`));
1318
- // console.log('2 >>>>>>>', RESET_TIME.get(`#${queryName}:${variablesKey}`));
1319
- // }
1320
-
1321
- return (
1322
- RESET_TIME.get(`#${queryName}:`) ||
1323
- RESET_TIME.get(`#${queryName}:${variablesKey}`)
1324
- );
1734
+ // if (RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`)) {
1735
+ // console.log(`#${queryName}:${variablesKey}`);
1736
+ // console.log('1 >>>>>>>', RESET_TIME.get(`#${queryName}:`));
1737
+ // console.log('2 >>>>>>>', RESET_TIME.get(`#${queryName}:${variablesKey}`));
1738
+ // }
1739
+
1740
+ return (
1741
+ RESET_TIME.get(`#${queryName}:`) ||
1742
+ RESET_TIME.get(`#${queryName}:${variablesKey}`)
1743
+ );
1325
1744
  }
1326
1745
 
1327
1746
  /**
@@ -1329,8 +1748,8 @@ export function getQueryRefreshTime(queryName: string, variablesKey: string) {
1329
1748
  */
1330
1749
 
1331
1750
  export function clearQueryResetStatus(queryName: string, variablesKey: string) {
1332
- RESET_TIME.delete(`#${queryName}:`);
1333
- RESET_TIME.delete(`#${queryName}:${variablesKey}`);
1751
+ RESET_TIME.delete(`#${queryName}:`);
1752
+ RESET_TIME.delete(`#${queryName}:${variablesKey}`);
1334
1753
  }
1335
1754
 
1336
1755
  /**
@@ -1338,30 +1757,69 @@ export function clearQueryResetStatus(queryName: string, variablesKey: string) {
1338
1757
  */
1339
1758
 
1340
1759
  function deleteMatchingQueryCache(queryId: string) {
1341
- if (queryId.startsWith('^')) {
1342
- const regex = new RegExp(queryId);
1343
-
1344
- for (const key of QUERIES.keys()) {
1345
- if (regex.test(key)) {
1346
- QUERIES.delete(key);
1347
- console.dev('✅ RESET ONLY ->', key);
1348
- }
1349
- }
1350
- return;
1351
- }
1352
-
1353
- if (queryId.endsWith(':')) {
1354
- for (const key of QUERIES.keys()) {
1355
- if (key.startsWith(queryId)) {
1356
- QUERIES.delete(key);
1357
- console.dev('✅ RESET ONLY ->', key);
1358
- }
1359
- }
1360
- return;
1361
- }
1362
-
1363
- QUERIES.delete(queryId);
1364
- console.dev('✅ RESET ONLY ->', queryId);
1760
+ if (queryId.endsWith(':')) {
1761
+ for (const key of QUERIES.keys()) {
1762
+ if (key.startsWith(queryId)) {
1763
+ QUERIES.delete(key);
1764
+ console.dev('✅ RESET ONLY ->', key);
1765
+ }
1766
+ }
1767
+ return;
1768
+ }
1769
+
1770
+ QUERIES.delete(queryId);
1771
+ console.dev('✅ RESET ONLY ->', queryId);
1772
+ }
1773
+
1774
+ /**
1775
+ * Clear query cache for one structured reset target.
1776
+ *
1777
+ * An unconstrained target is exactly the plain '#queryName:' reset key and is
1778
+ * routed through it deliberately: that path records the reset against the query
1779
+ * name, so a page mounting later still observes it. Only a target that narrows
1780
+ * on variables walks the matching cached pages.
1781
+ */
1782
+
1783
+ export function resetQueryByTarget(
1784
+ target: QueryResetTarget,
1785
+ forceRefetch?: boolean,
1786
+ updateObservers?: UpdateObserversFn,
1787
+ resetOnly?: boolean,
1788
+ ) {
1789
+ if (!target.match || !Object.keys(target.match).length) {
1790
+ resetQuery(`#${target.name}:`, forceRefetch, updateObservers, resetOnly);
1791
+ return;
1792
+ }
1793
+
1794
+ if (resetOnly) {
1795
+ for (const key of QUERIES.keys()) {
1796
+ if (queryCacheKeyMatchesResetTarget(key, target)) {
1797
+ QUERIES.delete(key);
1798
+ console.dev('✅ RESET ONLY ->', key);
1799
+ }
1800
+ }
1801
+
1802
+ updateObservers?.({
1803
+ queryId: getQueryResetTargetId(target),
1804
+ queryTarget: target,
1805
+ forceRefetch,
1806
+ resetOnly,
1807
+ });
1808
+ return;
1809
+ }
1810
+
1811
+ if (updateObservers) {
1812
+ for (const key of QUERIES.keys()) {
1813
+ if (queryCacheKeyMatchesResetTarget(key, target)) {
1814
+ RESET_TIME.set(key, Date.now());
1815
+ console.dev('✅ RESET ->', key);
1816
+ updateObservers({
1817
+ queryId: key,
1818
+ forceRefetch,
1819
+ });
1820
+ }
1821
+ }
1822
+ }
1365
1823
  }
1366
1824
 
1367
1825
  /**
@@ -1370,48 +1828,36 @@ function deleteMatchingQueryCache(queryId: string) {
1370
1828
  * it will reset all queries everywhere for the same GraphQL query.
1371
1829
  */
1372
1830
 
1373
- export function resetQuery(queryId: string, forceRefetch?: boolean, updateObservers?: UpdateObserversFn, resetOnly?: boolean) {
1374
- // if (forceRefetch) {
1375
- // QUERIES.delete(queryId);
1376
- // }
1377
-
1378
- if (resetOnly) {
1379
- deleteMatchingQueryCache(queryId);
1380
- updateObservers?.({
1381
- queryId,
1382
- forceRefetch,
1383
- resetOnly,
1384
- });
1385
- return;
1386
- }
1387
-
1388
- if (updateObservers) {
1389
- if (queryId.startsWith('^')) {
1390
- // Reset using regex
1391
- const regex = new RegExp(queryId);
1392
-
1393
- // Loop for each of QUERIES map keys
1394
- for (const key of QUERIES.keys()) {
1395
- if (regex.test(key)) {
1396
- RESET_TIME.set(key, Date.now());
1397
- console.dev('✅ RESET ->', key);
1398
- updateObservers({
1399
- queryId: key,
1400
- forceRefetch,
1401
- });
1402
- }
1403
- }
1404
- } else {
1405
- // Reset specific query
1406
- RESET_TIME.set(queryId, Date.now());
1407
- console.dev('✅ RESET ->', queryId);
1408
- updateObservers({
1409
- queryId,
1410
- forceRefetch,
1411
- });
1412
- }
1413
- // console.log('SETTING ->', queryId, RESET_TIME.get(queryId));
1414
- }
1831
+ export function resetQuery(
1832
+ queryId: string,
1833
+ forceRefetch?: boolean,
1834
+ updateObservers?: UpdateObserversFn,
1835
+ resetOnly?: boolean,
1836
+ ) {
1837
+ // if (forceRefetch) {
1838
+ // QUERIES.delete(queryId);
1839
+ // }
1840
+
1841
+ if (resetOnly) {
1842
+ deleteMatchingQueryCache(queryId);
1843
+ updateObservers?.({
1844
+ queryId,
1845
+ forceRefetch,
1846
+ resetOnly,
1847
+ });
1848
+ return;
1849
+ }
1850
+
1851
+ if (updateObservers) {
1852
+ // Reset one exact cache key or an unconstrained query prefix
1853
+ RESET_TIME.set(queryId, Date.now());
1854
+ console.dev('✅ RESET ->', queryId);
1855
+ updateObservers({
1856
+ queryId,
1857
+ forceRefetch,
1858
+ });
1859
+ // console.log('SETTING ->', queryId, RESET_TIME.get(queryId));
1860
+ }
1415
1861
  }
1416
1862
 
1417
1863
  /**
@@ -1419,50 +1865,57 @@ export function resetQuery(queryId: string, forceRefetch?: boolean, updateObserv
1419
1865
  */
1420
1866
 
1421
1867
  export function updateFragment(
1422
- updateFragmentKey: string,
1423
- update: any | ((cache: any) => any),
1424
- replacementFragmentKey?: string | null,
1425
- doNotTriggerObserver?: boolean,
1426
- updateObservers?: UpdateObserversFn,
1427
- otherUpdatedFragmentKeys?: string[],
1868
+ updateFragmentKey: string,
1869
+ update: any | ((cache: any) => any),
1870
+ replacementFragmentKey?: string | null,
1871
+ doNotTriggerObserver?: boolean,
1872
+ updateObservers?: UpdateObserversFn,
1873
+ otherUpdatedFragmentKeys?: string[],
1428
1874
  ) {
1429
- const cache = loadFragment(updateFragmentKey);
1430
-
1431
- if (cache && update) {
1432
- let updateObj;
1433
- if (typeof update === 'function') {
1434
- updateObj = update(mapArrayLikeObjects(cache));
1435
- } else {
1436
- updateObj = update;
1437
- }
1438
-
1439
- const newUpdatedObj = { ...cache, ...updateObj };
1440
-
1441
- FRAGMENTS.set(updateFragmentKey, newUpdatedObj);
1442
- console.dev('✅ FRAGMENT UPDATED ->', updateFragmentKey, newUpdatedObj);
1443
-
1444
- if (replacementFragmentKey && replacementFragmentKey !== updateFragmentKey) {
1445
- FRAGMENTS.set(replacementFragmentKey, newUpdatedObj);
1446
- }
1447
-
1448
- if (!doNotTriggerObserver && updateObservers) {
1449
- let observingFragmentIds = [updateFragmentKey];
1450
- if (Array.isArray(otherUpdatedFragmentKeys)) {
1451
- observingFragmentIds = uniq(observingFragmentIds.concat(otherUpdatedFragmentKeys));
1452
- }
1453
-
1454
- updateObservers({
1455
- fragmentIds: observingFragmentIds,
1456
- });
1457
-
1458
- // FRAGMENT_OBSERVER.value = {
1459
- // count: FRAGMENT_OBSERVER.value.count + 1,
1460
- // list: [updateFragmentKey],
1461
- // };
1462
- }
1463
- return updateFragmentKey || null;
1464
- }
1465
- return null;
1875
+ const cache = loadFragment(updateFragmentKey);
1876
+
1877
+ if (cache && update) {
1878
+ const cacheWithoutOptimisticUI =
1879
+ removeOptimisticUIObjectsFromArrayFields(cache);
1880
+ let updateObj;
1881
+ if (typeof update === 'function') {
1882
+ updateObj = update(mapArrayLikeObjects(cacheWithoutOptimisticUI));
1883
+ } else {
1884
+ updateObj = update;
1885
+ }
1886
+
1887
+ const newUpdatedObj = { ...cacheWithoutOptimisticUI, ...updateObj };
1888
+
1889
+ FRAGMENTS.set(updateFragmentKey, newUpdatedObj);
1890
+ console.dev('✅ FRAGMENT UPDATED ->', updateFragmentKey, newUpdatedObj);
1891
+
1892
+ if (
1893
+ replacementFragmentKey &&
1894
+ replacementFragmentKey !== updateFragmentKey
1895
+ ) {
1896
+ FRAGMENTS.set(replacementFragmentKey, newUpdatedObj);
1897
+ }
1898
+
1899
+ if (!doNotTriggerObserver && updateObservers) {
1900
+ let observingFragmentIds = [updateFragmentKey];
1901
+ if (Array.isArray(otherUpdatedFragmentKeys)) {
1902
+ observingFragmentIds = uniq(
1903
+ observingFragmentIds.concat(otherUpdatedFragmentKeys),
1904
+ );
1905
+ }
1906
+
1907
+ updateObservers({
1908
+ fragmentIds: observingFragmentIds,
1909
+ });
1910
+
1911
+ // FRAGMENT_OBSERVER.value = {
1912
+ // count: FRAGMENT_OBSERVER.value.count + 1,
1913
+ // list: [updateFragmentKey],
1914
+ // };
1915
+ }
1916
+ return updateFragmentKey || null;
1917
+ }
1918
+ return null;
1466
1919
  }
1467
1920
 
1468
1921
  /**
@@ -1470,33 +1923,35 @@ export function updateFragment(
1470
1923
  */
1471
1924
 
1472
1925
  export function updateQuery(
1473
- queryId: string,
1474
- update: any | ((cache: any) => any),
1475
- doNotTriggerObserver?: boolean,
1476
- updateObservers?: UpdateObserversFn,
1926
+ queryId: string,
1927
+ update: any | ((cache: any) => any),
1928
+ doNotTriggerObserver?: boolean,
1929
+ updateObservers?: UpdateObserversFn,
1477
1930
  ) {
1478
- const cache = loadQuery(queryId, true);
1479
- if (cache && update) {
1480
- let updateObj;
1481
- if (typeof update === 'function') {
1482
- updateObj = update(mapArrayLikeObjects(cache));
1483
- } else {
1484
- updateObj = update;
1485
- }
1486
-
1487
- const newUpdatedObj = Array.isArray(updateObj) ? updateObj : { ...cache, ...updateObj };
1488
-
1489
- // console.log('UPDATING (3):', updateObj);
1490
- QUERIES.set(queryId, newUpdatedObj);
1491
-
1492
- if (!doNotTriggerObserver && updateObservers) {
1493
- updateObservers({
1494
- queryId,
1495
- });
1496
- }
1497
- return updateObj || null;
1498
- }
1499
- return null;
1931
+ const cache = loadQuery(queryId, true);
1932
+ if (cache && update) {
1933
+ let updateObj;
1934
+ if (typeof update === 'function') {
1935
+ updateObj = update(mapArrayLikeObjects(cache));
1936
+ } else {
1937
+ updateObj = update;
1938
+ }
1939
+
1940
+ const newUpdatedObj = Array.isArray(updateObj)
1941
+ ? updateObj
1942
+ : { ...cache, ...updateObj };
1943
+
1944
+ // console.log('UPDATING (3):', updateObj);
1945
+ QUERIES.set(queryId, newUpdatedObj);
1946
+
1947
+ if (!doNotTriggerObserver && updateObservers) {
1948
+ updateObservers({
1949
+ queryId,
1950
+ });
1951
+ }
1952
+ return updateObj || null;
1953
+ }
1954
+ return null;
1500
1955
  }
1501
1956
 
1502
1957
  /**
@@ -1505,17 +1960,22 @@ export function updateQuery(
1505
1960
  * This will make observer NOT work.
1506
1961
  */
1507
1962
 
1508
- export function triggerObserver(ids: (string | null)[], updateObservers?: UpdateObserversFn) {
1509
- if (updateObservers) {
1510
- const observerListIds = ids.filter((id) => id);
1511
- if (observerListIds.length) {
1512
- updateObservers({
1513
- fragmentIds: observerListIds,
1514
- });
1515
- }
1516
- } else {
1517
- console.warn('trigerObserver() was called without updateObservers(); This does nothing.');
1518
- }
1963
+ export function triggerObserver(
1964
+ ids: (string | null)[],
1965
+ updateObservers?: UpdateObserversFn,
1966
+ ) {
1967
+ if (updateObservers) {
1968
+ const observerListIds = ids.filter((id) => id);
1969
+ if (observerListIds.length) {
1970
+ updateObservers({
1971
+ fragmentIds: observerListIds,
1972
+ });
1973
+ }
1974
+ } else {
1975
+ console.warn(
1976
+ 'trigerObserver() was called without updateObservers(); This does nothing.',
1977
+ );
1978
+ }
1519
1979
  }
1520
1980
 
1521
1981
  /**
@@ -1523,5 +1983,5 @@ export function triggerObserver(ids: (string | null)[], updateObservers?: Update
1523
1983
  */
1524
1984
 
1525
1985
  export function addFragmentToCache(id: string, obj: any) {
1526
- FRAGMENTS.set(id, obj);
1986
+ FRAGMENTS.set(id, obj);
1527
1987
  }