@jsb188/graphql 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +58 -24
  3. package/cache/index.chat-activity.test.ts +119 -0
  4. package/cache/index.chat.test.ts +92 -0
  5. package/cache/index.helpers.ts +96 -0
  6. package/cache/index.regression.test.ts +149 -0
  7. package/cache/index.test.ts +370 -42
  8. package/cache/index.ts +326 -799
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +98 -19
  12. package/cache/store.ts +22 -64
  13. package/cache/value.helpers.ts +17 -0
  14. package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
  15. package/{drafts/index.ts → client/draft-persistence.ts} +5 -2
  16. package/client/index.ts +3 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +130 -215
  19. package/deno.lock +17 -0
  20. package/deno.test.json +2 -0
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +150 -0
  23. package/gql/fragments/aiChatFragments.ts +36 -10
  24. package/gql/fragments/audienceFragments.ts +141 -0
  25. package/gql/fragments/campaignFragments.ts +415 -126
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +28 -23
  28. package/gql/fragments/fieldDocFragments.ts +222 -40
  29. package/gql/fragments/inboundContactFragments.ts +2 -0
  30. package/gql/fragments/logFragments.ts +93 -2
  31. package/gql/fragments/organizationFragments.ts +10 -0
  32. package/gql/fragments/qrCodeFragments.ts +29 -0
  33. package/gql/fragments/scheduleFragments.ts +652 -140
  34. package/gql/fragments/sheetFragments.ts +84 -373
  35. package/gql/fragments/storageFragments.ts +25 -1
  36. package/gql/fragments/workflowFragments.ts +13 -1
  37. package/gql/mutations/agentMemoryMutations.ts +32 -0
  38. package/gql/mutations/agentNoteMutations.ts +62 -0
  39. package/gql/mutations/aiChatMutations.ts +36 -4
  40. package/gql/mutations/audienceMutations.ts +71 -0
  41. package/gql/mutations/authMutations.ts +45 -1
  42. package/gql/mutations/billingMutations.ts +24 -0
  43. package/gql/mutations/campaignMutations.ts +170 -127
  44. package/gql/mutations/contactMutations.ts +23 -0
  45. package/gql/mutations/dataTableMutations.ts +18 -75
  46. package/gql/mutations/fieldDocMutations.ts +162 -13
  47. package/gql/mutations/index.ts +8 -5
  48. package/gql/mutations/organizationMutations.ts +6 -0
  49. package/gql/mutations/qrCodeMutations.ts +20 -0
  50. package/gql/mutations/scheduleMutations.ts +1052 -354
  51. package/gql/mutations/sheetMutations.ts +62 -118
  52. package/gql/mutations/storageMutations.ts +0 -1
  53. package/gql/mutations/workflowMutations.ts +18 -0
  54. package/gql/queries/agentMemoryQueries.ts +6 -0
  55. package/gql/queries/agentNoteQueries.ts +89 -0
  56. package/gql/queries/aiChatQueries.ts +56 -4
  57. package/gql/queries/audienceQueries.ts +128 -0
  58. package/gql/queries/authQueries.ts +6 -0
  59. package/gql/queries/billingQueries.ts +95 -6
  60. package/gql/queries/campaignQueries.ts +132 -23
  61. package/gql/queries/dataTableQueries.ts +24 -65
  62. package/gql/queries/emailQueries.ts +18 -61
  63. package/gql/queries/emailReplyReportQueries.ts +76 -0
  64. package/gql/queries/fieldDocQueries.ts +100 -92
  65. package/gql/queries/inboundContactQueries.ts +4 -0
  66. package/gql/queries/index.ts +3 -1
  67. package/gql/queries/logQueries.ts +62 -7
  68. package/gql/queries/organizationQueries.ts +13 -0
  69. package/gql/queries/qrCodeQueries.ts +20 -0
  70. package/gql/queries/scheduleQueries.ts +633 -257
  71. package/gql/queries/sheetQueries.ts +59 -152
  72. package/gql/queries/workflowQueries.ts +10 -4
  73. package/hooks/index.helpers.test.ts +50 -0
  74. package/hooks/index.helpers.ts +52 -0
  75. package/hooks/index.ts +863 -685
  76. package/hooks/use-agentMemory-mtn.ts +29 -31
  77. package/hooks/use-agentMemory-qry.ts +15 -3
  78. package/hooks/use-agentNote-mtn.ts +82 -0
  79. package/hooks/use-agentNote-qry.ts +190 -0
  80. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  81. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  82. package/hooks/use-agentNote-recovery.ts +72 -0
  83. package/hooks/use-aiChat-mtn.ts +96 -112
  84. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  85. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  86. package/hooks/use-aiChat-qry.ts +229 -383
  87. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  88. package/hooks/use-audience-mtn.ts +194 -0
  89. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  90. package/hooks/use-audience-qry.helpers.ts +63 -0
  91. package/hooks/use-audience-qry.ts +330 -0
  92. package/hooks/use-auth-mtn.ts +30 -1
  93. package/hooks/use-billing-mtn.ts +31 -0
  94. package/hooks/use-billing-qry.ts +76 -0
  95. package/hooks/use-campaign-generation-recovery.ts +53 -0
  96. package/hooks/use-campaign-mtn.ts +224 -165
  97. package/hooks/use-campaign-qry.helpers.ts +40 -0
  98. package/hooks/use-campaign-qry.ts +631 -54
  99. package/hooks/use-dataTable-mtn.ts +23 -115
  100. package/hooks/use-dataTable-qry.ts +66 -916
  101. package/hooks/use-email-qry.helpers.ts +37 -0
  102. package/hooks/use-email-qry.ts +33 -178
  103. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  104. package/hooks/use-fieldDoc-mtn.ts +244 -32
  105. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  106. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  107. package/hooks/use-fieldDoc-qry.ts +134 -102
  108. package/hooks/use-inboundContact-qry.ts +7 -9
  109. package/hooks/use-log-mtn.ts +25 -12
  110. package/hooks/use-log-qry.ts +99 -46
  111. package/hooks/use-organization-qry.ts +16 -60
  112. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  113. package/hooks/use-qrCode-mtn.ts +40 -0
  114. package/hooks/use-qrCode-qry.ts +78 -0
  115. package/hooks/use-schedule-mtn.ts +506 -333
  116. package/hooks/use-schedule-qry.ts +682 -101
  117. package/hooks/use-schedule-reactive.ts +486 -0
  118. package/hooks/use-sheet-mtn.ts +91 -199
  119. package/hooks/use-sheet-qry.ts +84 -238
  120. package/hooks/use-storage-qry.ts +84 -61
  121. package/hooks/use-workflow-mtn.ts +39 -22
  122. package/hooks/use-workflow-qry.ts +40 -61
  123. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  124. package/libs/ai-chat-outgoing.ts +11 -0
  125. package/libs/ai-chat-outgoing.types.ts +25 -0
  126. package/libs/ai-chat-run-realtime.ts +20 -0
  127. package/libs/ai-chat-submission-realtime.ts +150 -0
  128. package/libs/fragment-realtime-sequence.ts +55 -0
  129. package/libs/fragment-recovery.test.ts +326 -0
  130. package/libs/fragment-recovery.ts +325 -0
  131. package/libs/open-sheet.ts +138 -0
  132. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  133. package/libs/orchestrator-realtime.helpers.ts +317 -0
  134. package/libs/orchestrator-realtime.ts +433 -0
  135. package/libs/request-cache-regression.test.ts +122 -0
  136. package/{client → libs}/request-managed-session.test.ts +1 -1
  137. package/libs/request-no-store.test.ts +419 -0
  138. package/libs/sheet-command-batch.ts +44 -0
  139. package/libs/sheet-view-realtime-router.test.ts +214 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/campaign.test.ts +186 -0
  142. package/loaders/campaign.ts +56 -83
  143. package/loaders/emailPreference.ts +75 -0
  144. package/loaders/rest.ts +12 -0
  145. package/package.json +42 -17
  146. package/schedule.d.ts +1790 -0
  147. package/sse.helpers.ts +19 -0
  148. package/sse.ts +26 -115
  149. package/tests/agent-note-detail-cache.test.ts +120 -0
  150. package/tests/agent-note-search.test.ts +444 -0
  151. package/types.d.ts +46 -25
  152. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  153. package/client/data-table-realtime-subscriptions.ts +0 -955
  154. package/client/data-table-realtime.test.ts +0 -792
  155. package/client/data-table-realtime.ts +0 -1218
  156. package/client/fragment-realtime-sequence.ts +0 -52
  157. package/client/open-sheet.ts +0 -137
  158. package/client/request-no-store.test.ts +0 -157
  159. package/gql/fragments/agentDocFragments.ts +0 -46
  160. package/gql/fragments/billingFragments.ts +0 -14
  161. package/gql/mutations/agentDocMutations.ts +0 -177
  162. package/gql/queries/agentDocQueries.ts +0 -120
  163. package/hooks/use-agentDoc-mtn.ts +0 -285
  164. package/hooks/use-agentDoc-qry.ts +0 -208
  165. /package/{client → libs}/sse-ticket.test.ts +0 -0
@@ -0,0 +1,46 @@
1
+ const OPTIMISTIC_UI_RUNTIME = {
2
+ activeFragmentKeys: new Set<string>(),
3
+ nextTransactionId: 0,
4
+ };
5
+
6
+ /*
7
+ * Return one unique client-only token for an optimistic transaction.
8
+ */
9
+ export function getOptimisticUITransactionId() {
10
+ OPTIMISTIC_UI_RUNTIME.nextTransactionId += 1;
11
+ return `optimistic-${OPTIMISTIC_UI_RUNTIME.nextTransactionId}`;
12
+ }
13
+
14
+ /*
15
+ * Acquire a complete set of fragment keys when none are already optimistic.
16
+ */
17
+ export function acquireOptimisticUIFragmentKeys(fragmentKeys: string[]) {
18
+ if (
19
+ fragmentKeys.some((fragmentKey) =>
20
+ OPTIMISTIC_UI_RUNTIME.activeFragmentKeys.has(fragmentKey),
21
+ )
22
+ ) {
23
+ return false;
24
+ }
25
+
26
+ fragmentKeys.forEach((fragmentKey) => {
27
+ OPTIMISTIC_UI_RUNTIME.activeFragmentKeys.add(fragmentKey);
28
+ });
29
+ return true;
30
+ }
31
+
32
+ /*
33
+ * Release fragment keys after their optimistic transaction settles.
34
+ */
35
+ export function releaseOptimisticUIFragmentKeys(fragmentKeys: string[]) {
36
+ fragmentKeys.forEach((fragmentKey) => {
37
+ OPTIMISTIC_UI_RUNTIME.activeFragmentKeys.delete(fragmentKey);
38
+ });
39
+ }
40
+
41
+ /*
42
+ * Return whether one fragment currently belongs to an optimistic transaction.
43
+ */
44
+ export function isOptimisticUIFragmentActive(fragmentKey: string) {
45
+ return OPTIMISTIC_UI_RUNTIME.activeFragmentKeys.has(fragmentKey);
46
+ }
@@ -0,0 +1,401 @@
1
+ import { graphQLValuesEqual } from './value.helpers.ts';
2
+ import type { OptimisticUI, OptimisticUIOperation, UpdateObserversFn } from '../types.d.ts';
3
+ import { addFragmentToCache, loadFragment, triggerObserver } from './index.ts';
4
+ import {
5
+ acquireOptimisticUIFragmentKeys,
6
+ getOptimisticUITransactionId,
7
+ releaseOptimisticUIFragmentKeys,
8
+ } from './optimistic-ui-runtime.ts';
9
+ import { cacheStore } from './store.ts';
10
+
11
+ interface OptimisticPreviousField {
12
+ exists: boolean;
13
+ value: any;
14
+ }
15
+
16
+ interface OptimisticPlaceholderState {
17
+ field: string;
18
+ token: string;
19
+ }
20
+
21
+ interface OptimisticFragmentPlan {
22
+ baseFragment: Record<string, any>;
23
+ fragmentKey: string;
24
+ nextFragment: Record<string, any>;
25
+ optimisticFields: Map<string, any>;
26
+ placeholders: OptimisticPlaceholderState[];
27
+ previousFields: Map<string, OptimisticPreviousField>;
28
+ }
29
+
30
+ export interface OptimisticUITransaction {
31
+ commit: () => void;
32
+ fragmentKeys: string[];
33
+ rollback: () => void;
34
+ }
35
+
36
+ export type OptimisticUITransactionResult =
37
+ | { status: 'applied'; transaction: OptimisticUITransaction }
38
+ | { status: 'conflict'; transaction: null }
39
+ | { status: 'noop'; transaction: null };
40
+
41
+ /*
42
+ * Normalize one optimistic operation or operation list into an array.
43
+ */
44
+ function getOptimisticUIOperations(optimisticUI: OptimisticUI) {
45
+ return Array.isArray(optimisticUI)
46
+ ? [...optimisticUI]
47
+ : [optimisticUI as OptimisticUIOperation];
48
+ }
49
+
50
+ /*
51
+ * Return the normalized fragment key targeted by one optimistic operation.
52
+ */
53
+ function getOptimisticUIOperationFragmentKey(operation: OptimisticUIOperation) {
54
+ return operation.action === 'update'
55
+ ? operation.fragmentKey
56
+ : operation.parentFragmentKey;
57
+ }
58
+
59
+ /*
60
+ * Return or initialize one fragment plan without mutating the cache.
61
+ */
62
+ function getOptimisticFragmentPlan(
63
+ plans: Map<string, OptimisticFragmentPlan>,
64
+ fragmentKey: string,
65
+ ) {
66
+ const currentPlan = plans.get(fragmentKey);
67
+ if (currentPlan) {
68
+ return currentPlan;
69
+ }
70
+
71
+ const fragment = loadFragment(fragmentKey);
72
+ if (!fragment || typeof fragment !== 'object' || Array.isArray(fragment)) {
73
+ return null;
74
+ }
75
+
76
+ const plan: OptimisticFragmentPlan = {
77
+ baseFragment: fragment,
78
+ fragmentKey,
79
+ nextFragment: { ...fragment },
80
+ optimisticFields: new Map(),
81
+ placeholders: [],
82
+ previousFields: new Map(),
83
+ };
84
+ plans.set(fragmentKey, plan);
85
+ return plan;
86
+ }
87
+
88
+ /*
89
+ * Apply one existing-fragment patch to an in-memory transaction plan.
90
+ */
91
+ function applyOptimisticUpdateToPlan(
92
+ plan: OptimisticFragmentPlan,
93
+ operation: Extract<OptimisticUIOperation, { action: 'update' }>,
94
+ ) {
95
+ const update =
96
+ typeof operation.update === 'function'
97
+ ? operation.update({ ...plan.nextFragment })
98
+ : operation.update;
99
+
100
+ if (!update || typeof update !== 'object' || Array.isArray(update)) {
101
+ return;
102
+ }
103
+
104
+ Object.keys(update).forEach((field) => {
105
+ if (!plan.previousFields.has(field)) {
106
+ plan.previousFields.set(field, {
107
+ exists: Object.hasOwn(plan.baseFragment, field),
108
+ value: plan.baseFragment[field],
109
+ });
110
+ }
111
+
112
+ plan.nextFragment[field] = update[field];
113
+ plan.optimisticFields.set(field, update[field]);
114
+ });
115
+ }
116
+
117
+ /*
118
+ * Insert one marked temporary collection object into an in-memory plan.
119
+ */
120
+ function applyOptimisticPlaceholderToPlan(
121
+ plan: OptimisticFragmentPlan,
122
+ operation: Extract<OptimisticUIOperation, { action: 'create-placeholder' }>,
123
+ token: string,
124
+ ) {
125
+ const currentCollection = plan.nextFragment[operation.field];
126
+ if (!Array.isArray(currentCollection)) {
127
+ return;
128
+ }
129
+
130
+ const placeholder = {
131
+ ...operation.data,
132
+ __optimisticPlaceholder: true,
133
+ __optimisticTransactionId: token,
134
+ };
135
+ plan.nextFragment[operation.field] =
136
+ operation.position === 'start'
137
+ ? [placeholder, ...currentCollection]
138
+ : [...currentCollection, placeholder];
139
+ plan.placeholders.push({ field: operation.field, token });
140
+ }
141
+
142
+ /*
143
+ * Build all fragment plans before acquiring locks or writing cache state.
144
+ */
145
+ function getOptimisticFragmentPlans(optimisticUI: OptimisticUI) {
146
+ const plans = new Map<string, OptimisticFragmentPlan>();
147
+ const transactionId = getOptimisticUITransactionId();
148
+
149
+ getOptimisticUIOperations(optimisticUI).forEach((operation, index) => {
150
+ const fragmentKey = getOptimisticUIOperationFragmentKey(operation);
151
+ if (!fragmentKey) {
152
+ return;
153
+ }
154
+
155
+ const plan = getOptimisticFragmentPlan(plans, fragmentKey);
156
+ if (!plan) {
157
+ return;
158
+ }
159
+
160
+ if (operation.action === 'update') {
161
+ applyOptimisticUpdateToPlan(plan, operation);
162
+ return;
163
+ }
164
+
165
+ applyOptimisticPlaceholderToPlan(
166
+ plan,
167
+ operation,
168
+ `${transactionId}-${index}`,
169
+ );
170
+ });
171
+
172
+ return [...plans.values()].filter((plan) => !graphQLValuesEqual(plan.baseFragment, plan.nextFragment));
173
+ }
174
+
175
+ /*
176
+ * Acquire every affected fragment together so overlapping optimistic mutations
177
+ * can be rejected before either request races authoritative cache writes.
178
+ */
179
+ function acquireOptimisticFragmentPlans(plans: OptimisticFragmentPlan[]) {
180
+ return acquireOptimisticUIFragmentKeys(plans.map((plan) => plan.fragmentKey));
181
+ }
182
+
183
+ /*
184
+ * Release every fragment owned by a completed optimistic transaction.
185
+ */
186
+ function releaseOptimisticFragmentPlans(plans: OptimisticFragmentPlan[]) {
187
+ releaseOptimisticUIFragmentKeys(plans.map((plan) => plan.fragmentKey));
188
+ }
189
+
190
+ /*
191
+ * Queue each settled fragment for persistence after releasing its transient lock.
192
+ */
193
+ function persistSettledOptimisticFragmentPlans(
194
+ plans: OptimisticFragmentPlan[],
195
+ ) {
196
+ plans.forEach((plan) => {
197
+ cacheStore.markFragmentDirty(plan.fragmentKey);
198
+ });
199
+ }
200
+
201
+ /*
202
+ * Remove only placeholders created by one transaction from a fragment.
203
+ */
204
+ function removeTransactionPlaceholders(
205
+ fragment: Record<string, any>,
206
+ placeholders: OptimisticPlaceholderState[],
207
+ ) {
208
+ let nextFragment = fragment;
209
+ let changed = false;
210
+
211
+ placeholders.forEach(({ field, token }) => {
212
+ const collection = nextFragment[field];
213
+ if (!Array.isArray(collection)) {
214
+ return;
215
+ }
216
+
217
+ const nextCollection = collection.filter(
218
+ (item) => item?.__optimisticTransactionId !== token,
219
+ );
220
+ if (nextCollection.length === collection.length) {
221
+ return;
222
+ }
223
+
224
+ if (!changed) {
225
+ nextFragment = { ...nextFragment };
226
+ }
227
+ nextFragment[field] = nextCollection;
228
+ changed = true;
229
+ });
230
+
231
+ return changed ? nextFragment : null;
232
+ }
233
+
234
+ /*
235
+ * Remove settled placeholders while retaining authoritative collection data.
236
+ */
237
+ function commitOptimisticFragmentPlans(plans: OptimisticFragmentPlan[]) {
238
+ const updatedFragmentKeys: string[] = [];
239
+
240
+ plans.forEach((plan) => {
241
+ if (!plan.placeholders.length) {
242
+ return;
243
+ }
244
+
245
+ const currentFragment = loadFragment(plan.fragmentKey);
246
+ if (!currentFragment) {
247
+ return;
248
+ }
249
+
250
+ const nextFragment = removeTransactionPlaceholders(
251
+ currentFragment,
252
+ plan.placeholders,
253
+ );
254
+ if (!nextFragment) {
255
+ return;
256
+ }
257
+
258
+ addFragmentToCache(plan.fragmentKey, nextFragment);
259
+ updatedFragmentKeys.push(plan.fragmentKey);
260
+ });
261
+
262
+ return updatedFragmentKeys;
263
+ }
264
+
265
+ /*
266
+ * Conditionally restore optimistic fields and remove transaction placeholders.
267
+ */
268
+ function rollbackOptimisticFragmentPlans(plans: OptimisticFragmentPlan[]) {
269
+ const updatedFragmentKeys: string[] = [];
270
+
271
+ plans.forEach((plan) => {
272
+ const currentFragment = loadFragment(plan.fragmentKey);
273
+ if (!currentFragment) {
274
+ return;
275
+ }
276
+
277
+ const fragmentWithoutPlaceholders = removeTransactionPlaceholders(
278
+ currentFragment,
279
+ plan.placeholders,
280
+ );
281
+ const plannedFragmentWithoutPlaceholders =
282
+ removeTransactionPlaceholders(plan.nextFragment, plan.placeholders) ||
283
+ plan.nextFragment;
284
+ let nextFragment = fragmentWithoutPlaceholders || currentFragment;
285
+ let changed = Boolean(fragmentWithoutPlaceholders);
286
+ plan.optimisticFields.forEach((_optimisticValue, field) => {
287
+ if (!graphQLValuesEqual(nextFragment[field], plannedFragmentWithoutPlaceholders[field])) {
288
+ return;
289
+ }
290
+
291
+ if (!changed) {
292
+ nextFragment = { ...nextFragment };
293
+ }
294
+ const previousField = plan.previousFields.get(field);
295
+ if (previousField?.exists) {
296
+ nextFragment[field] = previousField.value;
297
+ } else {
298
+ delete nextFragment[field];
299
+ }
300
+ changed = true;
301
+ });
302
+
303
+ if (!changed) {
304
+ return;
305
+ }
306
+
307
+ addFragmentToCache(plan.fragmentKey, nextFragment);
308
+ updatedFragmentKeys.push(plan.fragmentKey);
309
+ });
310
+
311
+ return updatedFragmentKeys;
312
+ }
313
+
314
+ /*
315
+ * Settle one optimistic transaction, release its locks, and publish final state.
316
+ */
317
+ function settleOptimisticUITransaction(
318
+ plans: OptimisticFragmentPlan[],
319
+ settlePlans: (plans: OptimisticFragmentPlan[]) => string[],
320
+ updateObservers?: UpdateObserversFn,
321
+ ) {
322
+ let updatedFragmentKeys: string[] = [];
323
+
324
+ try {
325
+ updatedFragmentKeys = settlePlans(plans);
326
+ } finally {
327
+ releaseOptimisticFragmentPlans(plans);
328
+ persistSettledOptimisticFragmentPlans(plans);
329
+ }
330
+
331
+ triggerObserver(updatedFragmentKeys, updateObservers);
332
+ }
333
+
334
+ /*
335
+ * Apply one optimistic mutation transaction and return its settlement handlers.
336
+ */
337
+ export function beginOptimisticUITransaction(
338
+ optimisticUI: OptimisticUI | null | undefined,
339
+ updateObservers?: UpdateObserversFn,
340
+ ): OptimisticUITransactionResult {
341
+ if (!optimisticUI) {
342
+ return { status: 'noop', transaction: null };
343
+ }
344
+
345
+ const plans = getOptimisticFragmentPlans(optimisticUI);
346
+ if (!plans.length) {
347
+ return { status: 'noop', transaction: null };
348
+ }
349
+ if (!acquireOptimisticFragmentPlans(plans)) {
350
+ return { status: 'conflict', transaction: null };
351
+ }
352
+
353
+ const fragmentKeys = plans.map((plan) => plan.fragmentKey);
354
+ try {
355
+ plans.forEach((plan) => {
356
+ addFragmentToCache(plan.fragmentKey, plan.nextFragment);
357
+ });
358
+ triggerObserver(fragmentKeys, updateObservers);
359
+ } catch (error) {
360
+ try {
361
+ rollbackOptimisticFragmentPlans(plans);
362
+ } finally {
363
+ releaseOptimisticFragmentPlans(plans);
364
+ persistSettledOptimisticFragmentPlans(plans);
365
+ }
366
+ throw error;
367
+ }
368
+
369
+ let settled = false;
370
+
371
+ return {
372
+ status: 'applied',
373
+ transaction: {
374
+ fragmentKeys,
375
+ commit: () => {
376
+ if (settled) {
377
+ return;
378
+ }
379
+
380
+ settled = true;
381
+ settleOptimisticUITransaction(
382
+ plans,
383
+ commitOptimisticFragmentPlans,
384
+ updateObservers,
385
+ );
386
+ },
387
+ rollback: () => {
388
+ if (settled) {
389
+ return;
390
+ }
391
+
392
+ settled = true;
393
+ settleOptimisticUITransaction(
394
+ plans,
395
+ rollbackOptimisticFragmentPlans,
396
+ updateObservers,
397
+ );
398
+ },
399
+ },
400
+ };
401
+ }
package/cache/persist.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { CACHE_SCHEMA_VERSION, RULES } from './config.ts';
2
+ import { isOptimisticUIFragmentActive } from './optimistic-ui-runtime.ts';
2
3
  import { cacheStore } from './store.ts';
3
4
 
4
5
  /**
@@ -59,6 +60,7 @@ let DB: IDBDatabase | null = null;
59
60
  let ENABLED = false;
60
61
  let INIT_PROMISE: Promise<boolean> | null = null;
61
62
  let ACTIVE_CONTEXT: PersistenceContext | null = null;
63
+ let PERSISTENCE_GENERATION = 0;
62
64
  let UNSUBSCRIBE_STORE: (() => void) | null = null;
63
65
 
64
66
  let LAST_HYDRATED_FRAGMENT_KEYS: string[] = [];
@@ -67,6 +69,7 @@ const DIRTY_FRAGMENT_KEYS = new Set<string>();
67
69
  const DIRTY_QUERY_KEYS = new Set<string>();
68
70
  let FLUSH_TIMER: ReturnType<typeof setTimeout> | null = null;
69
71
  let FLUSH_DEADLINE = 0;
72
+ let PAGE_HIDE_FLUSH_BOUND = false;
70
73
 
71
74
  /**
72
75
  * Check whether IndexedDB exists in this runtime (browser only; entry.server
@@ -155,7 +158,7 @@ function persistedFragmentRecordIsDeleted(record: any): boolean {
155
158
 
156
159
  /**
157
160
  * Return a copy of one fragment value safe for storage: top-level arrays are
158
- * stripped of transient optimistic UI placeholders.
161
+ * stripped of transient optimistic placeholders.
159
162
  */
160
163
 
161
164
  function sanitizeValueForStorage(value: any) {
@@ -174,7 +177,11 @@ function sanitizeValueForStorage(value: any) {
174
177
 
175
178
  const cleanedArray = value[key].filter(
176
179
  (item: any) =>
177
- !(item && typeof item === 'object' && item.__optimisticUI === true),
180
+ !(
181
+ item &&
182
+ typeof item === 'object' &&
183
+ item.__optimisticPlaceholder === true
184
+ ),
178
185
  );
179
186
  if (cleanedArray.length !== value[key].length) {
180
187
  if (sanitized === value) {
@@ -322,11 +329,8 @@ function clearAllStores(db: IDBDatabase): Promise<void> {
322
329
  * hydrated writes never echo back into the dirty buffer.
323
330
  */
324
331
 
325
- async function hydrateFromDatabase(db: IDBDatabase): Promise<string[]> {
326
- const tx = db.transaction(
327
- [PERSIST_CONSTANTS.fragmentsStore, PERSIST_CONSTANTS.queriesStore],
328
- 'readonly',
329
- );
332
+ async function hydrateFromDatabase(db: IDBDatabase, isCurrent: () => boolean): Promise<string[]> {
333
+ const tx = db.transaction([PERSIST_CONSTANTS.fragmentsStore, PERSIST_CONSTANTS.queriesStore], 'readonly');
330
334
 
331
335
  const [fragmentRecords, queryRecords] = await Promise.all([
332
336
  requestAsPromise<any[]>(
@@ -336,6 +340,8 @@ async function hydrateFromDatabase(db: IDBDatabase): Promise<string[]> {
336
340
  tx.objectStore(PERSIST_CONSTANTS.queriesStore).getAll(),
337
341
  ),
338
342
  ]);
343
+ // IndexedDB reads may finish after logout or another context starts loading.
344
+ if (!isCurrent()) return [];
339
345
 
340
346
  const hydratedFragmentKeys: string[] = [];
341
347
 
@@ -367,9 +373,7 @@ async function hydrateFromDatabase(db: IDBDatabase): Promise<string[]> {
367
373
  }
368
374
 
369
375
  for (const record of queryRecords) {
370
- if (record?.k) {
371
- cacheStore.queries.hydrate(record.k, record.d);
372
-
376
+ if (record?.k && cacheStore.queries.hydrate(record.k, record.d)) {
373
377
  if (typeof record.t === 'number') {
374
378
  cacheStore.hydrateQueryFetchTime(record.k, record.t);
375
379
  }
@@ -437,7 +441,9 @@ function flushDirtyKeys() {
437
441
  return;
438
442
  }
439
443
 
440
- const fragmentKeys = Array.from(DIRTY_FRAGMENT_KEYS);
444
+ const fragmentKeys = Array.from(DIRTY_FRAGMENT_KEYS).filter(
445
+ (key) => !isOptimisticUIFragmentActive(key),
446
+ );
441
447
  const queryKeys = Array.from(DIRTY_QUERY_KEYS);
442
448
  DIRTY_FRAGMENT_KEYS.clear();
443
449
  DIRTY_QUERY_KEYS.clear();
@@ -509,6 +515,10 @@ function flushDirtyKeys() {
509
515
 
510
516
  tx.onerror = () => disablePersistence(tx.error);
511
517
  tx.onabort = () => disablePersistence(tx.error || 'transaction aborted');
518
+
519
+ // Commit now instead of at the end of the task, so a flush started while
520
+ // the page unloads still reaches disk
521
+ tx.commit?.();
512
522
  } catch (err) {
513
523
  disablePersistence(err);
514
524
  }
@@ -537,6 +547,42 @@ function scheduleFlush() {
537
547
  FLUSH_TIMER = setTimeout(flushDirtyKeys, delay);
538
548
  }
539
549
 
550
+ /**
551
+ * Flush buffered dirty keys immediately when the page is hidden or unloads.
552
+ * A reload inside the debounce window would otherwise drop the pending write
553
+ * and hydrate the previous snapshot, which still looks fresh by fetch time.
554
+ */
555
+
556
+ function flushDirtyKeysOnPageHide(event: Event) {
557
+ if (
558
+ event.type === 'visibilitychange' &&
559
+ document.visibilityState !== 'hidden'
560
+ ) {
561
+ return;
562
+ }
563
+
564
+ if (FLUSH_TIMER) {
565
+ clearTimeout(FLUSH_TIMER);
566
+ }
567
+
568
+ flushDirtyKeys();
569
+ }
570
+
571
+ /**
572
+ * Bind the page-hide flush once per page; flushDirtyKeys() no-ops while
573
+ * persistence is disabled, so the listeners never need removing.
574
+ */
575
+
576
+ function bindPageHideFlush() {
577
+ if (PAGE_HIDE_FLUSH_BOUND || typeof document === 'undefined') {
578
+ return;
579
+ }
580
+
581
+ PAGE_HIDE_FLUSH_BOUND = true;
582
+ globalThis.addEventListener('pagehide', flushDirtyKeysOnPageHide);
583
+ document.addEventListener('visibilitychange', flushDirtyKeysOnPageHide);
584
+ }
585
+
540
586
  /**
541
587
  * Store subscription: buffer dirty keys and schedule a flush.
542
588
  */
@@ -549,8 +595,14 @@ function onStoreDirty(dirty: {
549
595
  return;
550
596
  }
551
597
 
552
- dirty.fragmentKeys.forEach((key) => DIRTY_FRAGMENT_KEYS.add(key));
553
- dirty.queryKeys.forEach((key) => DIRTY_QUERY_KEYS.add(key));
598
+ dirty.fragmentKeys.forEach((key) => {
599
+ if (!isOptimisticUIFragmentActive(key)) {
600
+ DIRTY_FRAGMENT_KEYS.add(key);
601
+ }
602
+ });
603
+ dirty.queryKeys.forEach((key) => {
604
+ DIRTY_QUERY_KEYS.add(key);
605
+ });
554
606
 
555
607
  if (DIRTY_FRAGMENT_KEYS.size || DIRTY_QUERY_KEYS.size) {
556
608
  scheduleFlush();
@@ -575,6 +627,7 @@ function metaMatchesContext(
575
627
  (meta.cacheAuthorizationEpoch ?? null) ===
576
628
  (context.cacheAuthorizationEpoch ?? null) &&
577
629
  typeof meta.savedAt === 'number' &&
630
+ meta.savedAt <= Date.now() &&
578
631
  Date.now() - meta.savedAt < PERSIST_CONSTANTS.maxSnapshotAgeMs,
579
632
  );
580
633
  }
@@ -617,8 +670,9 @@ export function initGraphQLCachePersistence(
617
670
  // hydrated keys to this caller's observer too. Duplicate notifications
618
671
  // are cheap; fragment hooks are version-stamp guarded.
619
672
  if (onHydrated) {
673
+ const generation = PERSISTENCE_GENERATION;
620
674
  INIT_PROMISE.then(() => {
621
- if (LAST_HYDRATED_FRAGMENT_KEYS.length) {
675
+ if (generation === PERSISTENCE_GENERATION && LAST_HYDRATED_FRAGMENT_KEYS.length) {
622
676
  onHydrated(LAST_HYDRATED_FRAGMENT_KEYS);
623
677
  }
624
678
  });
@@ -634,35 +688,53 @@ export function initGraphQLCachePersistence(
634
688
  }
635
689
 
636
690
  ACTIVE_CONTEXT = context;
691
+ const generation = ++PERSISTENCE_GENERATION;
692
+ /* Check ownership after every asynchronous storage boundary. */
693
+ const isCurrent = () => generation === PERSISTENCE_GENERATION;
637
694
  INIT_PROMISE = (async () => {
695
+ let db: IDBDatabase | null = null;
638
696
  try {
639
- const db = await openDatabase();
697
+ db = await openDatabase();
698
+ if (!isCurrent()) {
699
+ db.close();
700
+ return false;
701
+ }
640
702
  const metaTx = db.transaction(PERSIST_CONSTANTS.metaStore, 'readonly');
641
703
  const meta = await requestAsPromise<PersistedMeta | undefined>(
642
704
  metaTx
643
705
  .objectStore(PERSIST_CONSTANTS.metaStore)
644
706
  .get(PERSIST_CONSTANTS.metaKey),
645
707
  );
708
+ if (!isCurrent()) {
709
+ db.close();
710
+ return false;
711
+ }
646
712
 
647
713
  let hydratedFragmentKeys: string[] = [];
648
714
  const matched = metaMatchesContext(meta, context);
649
715
 
650
716
  if (matched) {
651
- hydratedFragmentKeys = await hydrateFromDatabase(db);
717
+ hydratedFragmentKeys = await hydrateFromDatabase(db, isCurrent);
652
718
  } else {
653
719
  // Different account/org/schema/build or stale snapshot: wipe
654
720
  await clearAllStores(db);
655
721
  }
722
+ if (!isCurrent()) {
723
+ db.close();
724
+ return false;
725
+ }
656
726
 
657
727
  LAST_HYDRATED_FRAGMENT_KEYS = hydratedFragmentKeys;
658
728
 
659
729
  DB = db;
660
730
  ENABLED = true;
661
731
  UNSUBSCRIBE_STORE = cacheStore.subscribe(onStoreDirty);
732
+ bindPageHideFlush();
662
733
 
663
734
  db.onversionchange = () => {
664
735
  // Another tab upgraded/deleted the database; step aside
665
- disablePersistence('database version change');
736
+ if (isCurrent()) disablePersistence('database version change');
737
+ else db?.close();
666
738
  };
667
739
 
668
740
  if (hydratedFragmentKeys.length && onHydrated) {
@@ -671,7 +743,8 @@ export function initGraphQLCachePersistence(
671
743
 
672
744
  return hydratedFragmentKeys.length > 0;
673
745
  } catch (err) {
674
- disablePersistence(err);
746
+ if (isCurrent()) disablePersistence(err);
747
+ else db?.close();
675
748
  return false;
676
749
  }
677
750
  })();
@@ -686,6 +759,10 @@ export function initGraphQLCachePersistence(
686
759
  */
687
760
 
688
761
  export function clearGraphQLCachePersistence() {
762
+ PERSISTENCE_GENERATION += 1;
763
+ INIT_PROMISE = null;
764
+ ACTIVE_CONTEXT = null;
765
+ LAST_HYDRATED_FRAGMENT_KEYS = [];
689
766
  if (!isIndexedDBAvailable()) {
690
767
  return;
691
768
  }
@@ -700,7 +777,9 @@ export function clearGraphQLCachePersistence() {
700
777
  }
701
778
 
702
779
  if (DB) {
703
- clearAllStores(DB).catch((err) => disablePersistence(err));
780
+ // Start the clear transaction before closing this context's connection.
781
+ void clearAllStores(DB).catch(() => {});
782
+ disablePersistence('cache cleared');
704
783
  return;
705
784
  }
706
785