@jsb188/graphql 1.1.11 → 1.1.13

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 (174) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +205 -0
  3. package/cache/config.ts +65 -28
  4. package/cache/index.helpers.ts +96 -0
  5. package/cache/index.ts +364 -808
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/optimistic-ui-runtime.ts +46 -0
  8. package/cache/optimistic-ui.ts +401 -0
  9. package/cache/persist.ts +107 -22
  10. package/cache/realtime-fence.ts +47 -0
  11. package/cache/realtime-live.ts +17 -0
  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} +13 -39
  16. package/client/index.ts +4 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +122 -232
  19. package/client/storage-asset.ts +58 -0
  20. package/gql/fragments/accountAuthFragments.ts +0 -4
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +156 -0
  23. package/gql/fragments/aiChatFragments.ts +35 -11
  24. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  25. package/gql/fragments/audienceFragments.ts +76 -0
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +49 -21
  28. package/gql/fragments/emailOutreachFragments.ts +281 -0
  29. package/gql/fragments/fieldDocFragments.ts +222 -40
  30. package/gql/fragments/inboundContactFragments.ts +2 -0
  31. package/gql/fragments/libraryFragments.ts +120 -0
  32. package/gql/fragments/logFragments.ts +93 -2
  33. package/gql/fragments/organizationFragments.ts +12 -0
  34. package/gql/fragments/qrCodeFragments.ts +29 -0
  35. package/gql/fragments/scheduleFragments.ts +574 -145
  36. package/gql/fragments/sheetFragments.ts +86 -424
  37. package/gql/fragments/storageFragments.ts +25 -1
  38. package/gql/fragments/workWaitFragments.ts +13 -0
  39. package/gql/fragments/workflowFragments.ts +32 -4
  40. package/gql/mutations/agentMemoryMutations.ts +32 -0
  41. package/gql/mutations/agentNoteMutations.ts +64 -0
  42. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  43. package/gql/mutations/aiChatMutations.ts +34 -4
  44. package/gql/mutations/audienceMutations.ts +58 -0
  45. package/gql/mutations/authMutations.ts +24 -28
  46. package/gql/mutations/billingMutations.ts +24 -0
  47. package/gql/mutations/contactMutations.ts +23 -0
  48. package/gql/mutations/dataTableMutations.ts +18 -75
  49. package/gql/mutations/emailMutations.ts +22 -0
  50. package/gql/mutations/emailOutreachMutations.ts +139 -0
  51. package/gql/mutations/fieldDocMutations.ts +162 -13
  52. package/gql/mutations/index.ts +10 -5
  53. package/gql/mutations/organizationMutations.ts +6 -0
  54. package/gql/mutations/qrCodeMutations.ts +20 -0
  55. package/gql/mutations/scheduleMutations.ts +389 -417
  56. package/gql/mutations/sheetMutations.ts +62 -118
  57. package/gql/mutations/storageMutations.ts +1 -1
  58. package/gql/mutations/workflowMutations.ts +94 -0
  59. package/gql/queries/agentMemoryQueries.ts +12 -2
  60. package/gql/queries/agentNoteQueries.ts +86 -0
  61. package/gql/queries/aiChatQueries.ts +63 -12
  62. package/gql/queries/audienceQueries.ts +104 -0
  63. package/gql/queries/authQueries.ts +20 -4
  64. package/gql/queries/billingQueries.ts +114 -9
  65. package/gql/queries/dataTableQueries.ts +43 -75
  66. package/gql/queries/emailOutreachQueries.ts +282 -0
  67. package/gql/queries/emailQueries.ts +48 -64
  68. package/gql/queries/emailReplyReportQueries.ts +127 -0
  69. package/gql/queries/fieldDocQueries.ts +128 -98
  70. package/gql/queries/inboundContactQueries.ts +15 -4
  71. package/gql/queries/index.ts +5 -3
  72. package/gql/queries/libraryQueries.ts +112 -0
  73. package/gql/queries/logQueries.ts +86 -12
  74. package/gql/queries/organizationQueries.ts +44 -12
  75. package/gql/queries/qrCodeQueries.ts +27 -0
  76. package/gql/queries/scheduleQueries.ts +401 -278
  77. package/gql/queries/sheetQueries.ts +94 -165
  78. package/gql/queries/storageQueries.ts +11 -4
  79. package/gql/queries/workflowQueries.ts +61 -12
  80. package/gql/reactivity.ts +98 -0
  81. package/gql/recordReads.ts +171 -0
  82. package/hooks/index.helpers.ts +52 -0
  83. package/hooks/index.ts +920 -715
  84. package/hooks/use-agentMemory-mtn.ts +29 -31
  85. package/hooks/use-agentMemory-qry.ts +15 -3
  86. package/hooks/use-agentNote-mtn.ts +89 -0
  87. package/hooks/use-agentNote-qry.ts +162 -0
  88. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  89. package/hooks/use-agentNote-recovery.ts +57 -0
  90. package/hooks/use-aiChat-mtn.ts +104 -115
  91. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  92. package/hooks/use-aiChat-qry.ts +254 -387
  93. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  94. package/hooks/use-audience-mtn.ts +170 -0
  95. package/hooks/use-audience-qry.helpers.ts +39 -0
  96. package/hooks/use-audience-qry.ts +245 -0
  97. package/hooks/use-auth-mtn.ts +30 -1
  98. package/hooks/use-billing-mtn.ts +31 -0
  99. package/hooks/use-billing-qry.ts +76 -0
  100. package/hooks/use-dataTable-mtn.ts +23 -115
  101. package/hooks/use-dataTable-qry.ts +69 -914
  102. package/hooks/use-email-mtn.ts +26 -0
  103. package/hooks/use-email-qry.helpers.ts +37 -0
  104. package/hooks/use-email-qry.ts +44 -174
  105. package/hooks/use-emailOutreach-mtn.ts +211 -0
  106. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  107. package/hooks/use-emailOutreach-qry.ts +367 -0
  108. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  109. package/hooks/use-fieldDoc-mtn.ts +244 -32
  110. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  111. package/hooks/use-fieldDoc-qry.ts +134 -102
  112. package/hooks/use-inboundContact-qry.ts +7 -9
  113. package/hooks/use-library-qry.ts +233 -0
  114. package/hooks/use-log-mtn.ts +25 -12
  115. package/hooks/use-log-qry.ts +99 -46
  116. package/hooks/use-organization-qry.ts +16 -60
  117. package/hooks/use-qrCode-mtn.ts +40 -0
  118. package/hooks/use-qrCode-qry.ts +78 -0
  119. package/hooks/use-schedule-mtn.ts +231 -348
  120. package/hooks/use-schedule-qry.ts +208 -139
  121. package/hooks/use-schedule-reactive.ts +218 -0
  122. package/hooks/use-sheet-mtn.ts +91 -199
  123. package/hooks/use-sheet-qry.ts +88 -237
  124. package/hooks/use-storage-qry.ts +84 -61
  125. package/hooks/use-workflow-mtn.ts +84 -23
  126. package/hooks/use-workflow-qry.ts +60 -61
  127. package/libs/ai-chat-link-events.ts +78 -0
  128. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  129. package/libs/ai-chat-outgoing.ts +11 -0
  130. package/libs/ai-chat-outgoing.types.ts +25 -0
  131. package/libs/ai-chat-run-realtime.ts +20 -0
  132. package/libs/ai-chat-submission-realtime.ts +150 -0
  133. package/libs/data-changes.helpers.ts +161 -0
  134. package/libs/data-changes.ts +382 -0
  135. package/libs/fragment-realtime-sequence.ts +55 -0
  136. package/libs/open-sheet.ts +138 -0
  137. package/libs/record-read.ts +327 -0
  138. package/libs/sheet-command-batch.ts +45 -0
  139. package/libs/sheet-realtime-packet.ts +53 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/emailPreference.ts +69 -0
  142. package/loaders/rest.ts +12 -0
  143. package/package.json +77 -25
  144. package/schedule.d.ts +1183 -0
  145. package/sse.helpers.ts +19 -0
  146. package/sse.ts +26 -115
  147. package/types.d.ts +48 -25
  148. package/cache/index.test.ts +0 -881
  149. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  150. package/client/data-table-realtime-subscriptions.ts +0 -955
  151. package/client/data-table-realtime.test.ts +0 -792
  152. package/client/data-table-realtime.ts +0 -1218
  153. package/client/fragment-realtime-sequence.ts +0 -52
  154. package/client/open-sheet.ts +0 -137
  155. package/client/request-managed-session.test.ts +0 -574
  156. package/client/request-no-store.test.ts +0 -157
  157. package/client/sse-ticket.test.ts +0 -26
  158. package/deno.lock +0 -170
  159. package/deno.test.json +0 -10
  160. package/gql/fragments/agentDocFragments.ts +0 -46
  161. package/gql/fragments/billingFragments.ts +0 -14
  162. package/gql/fragments/campaignFragments.ts +0 -277
  163. package/gql/mutations/agentDocMutations.ts +0 -177
  164. package/gql/mutations/campaignMutations.ts +0 -215
  165. package/gql/queries/agentDocQueries.ts +0 -120
  166. package/gql/queries/appQueries.ts +0 -14
  167. package/gql/queries/campaignQueries.ts +0 -127
  168. package/hooks/use-agentDoc-mtn.ts +0 -285
  169. package/hooks/use-agentDoc-qry.ts +0 -208
  170. package/hooks/use-app-qry.ts +0 -22
  171. package/hooks/use-campaign-mtn.ts +0 -377
  172. package/hooks/use-campaign-qry.ts +0 -257
  173. package/loaders/campaign.ts +0 -137
  174. package/tsconfig.json +0 -13
package/cache/persist.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { CACHE_SCHEMA_VERSION, RULES } from './config.ts';
1
+ import { CACHE_SCHEMA_VERSION, MEMORY_ONLY_QUERY_NAMES, 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,10 +69,11 @@ 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
73
- * and deno tests import this module through cache/index.ts and must no-op).
76
+ * and bun tests import this module through cache/index.ts and must no-op).
74
77
  */
75
78
 
76
79
  function isIndexedDBAvailable(): boolean {
@@ -109,6 +112,12 @@ function fragmentKeyIsPersistable(fragmentKey: string): boolean {
109
112
  return RULES[fragmentName] !== false;
110
113
  }
111
114
 
115
+ /* Keep memory-only query results out of the persisted cache. */
116
+ function queryKeyIsPersistable(queryKey: string): boolean {
117
+ const nameEnd = queryKey.indexOf(':');
118
+ return nameEnd < 0 || !MEMORY_ONLY_QUERY_NAMES.has(queryKey.slice(1, nameEnd));
119
+ }
120
+
112
121
  /**
113
122
  * Return the parent fragment key for a ".spreads" sidecar key, or the key
114
123
  * itself when it is not a sidecar.
@@ -155,7 +164,7 @@ function persistedFragmentRecordIsDeleted(record: any): boolean {
155
164
 
156
165
  /**
157
166
  * Return a copy of one fragment value safe for storage: top-level arrays are
158
- * stripped of transient optimistic UI placeholders.
167
+ * stripped of transient optimistic placeholders.
159
168
  */
160
169
 
161
170
  function sanitizeValueForStorage(value: any) {
@@ -174,7 +183,11 @@ function sanitizeValueForStorage(value: any) {
174
183
 
175
184
  const cleanedArray = value[key].filter(
176
185
  (item: any) =>
177
- !(item && typeof item === 'object' && item.__optimisticUI === true),
186
+ !(
187
+ item &&
188
+ typeof item === 'object' &&
189
+ item.__optimisticPlaceholder === true
190
+ ),
178
191
  );
179
192
  if (cleanedArray.length !== value[key].length) {
180
193
  if (sanitized === value) {
@@ -322,11 +335,8 @@ function clearAllStores(db: IDBDatabase): Promise<void> {
322
335
  * hydrated writes never echo back into the dirty buffer.
323
336
  */
324
337
 
325
- async function hydrateFromDatabase(db: IDBDatabase): Promise<string[]> {
326
- const tx = db.transaction(
327
- [PERSIST_CONSTANTS.fragmentsStore, PERSIST_CONSTANTS.queriesStore],
328
- 'readonly',
329
- );
338
+ async function hydrateFromDatabase(db: IDBDatabase, isCurrent: () => boolean): Promise<string[]> {
339
+ const tx = db.transaction([PERSIST_CONSTANTS.fragmentsStore, PERSIST_CONSTANTS.queriesStore], 'readonly');
330
340
 
331
341
  const [fragmentRecords, queryRecords] = await Promise.all([
332
342
  requestAsPromise<any[]>(
@@ -336,6 +346,8 @@ async function hydrateFromDatabase(db: IDBDatabase): Promise<string[]> {
336
346
  tx.objectStore(PERSIST_CONSTANTS.queriesStore).getAll(),
337
347
  ),
338
348
  ]);
349
+ // IndexedDB reads may finish after logout or another context starts loading.
350
+ if (!isCurrent()) return [];
339
351
 
340
352
  const hydratedFragmentKeys: string[] = [];
341
353
 
@@ -367,9 +379,7 @@ async function hydrateFromDatabase(db: IDBDatabase): Promise<string[]> {
367
379
  }
368
380
 
369
381
  for (const record of queryRecords) {
370
- if (record?.k) {
371
- cacheStore.queries.hydrate(record.k, record.d);
372
-
382
+ if (record?.k && queryKeyIsPersistable(record.k) && cacheStore.queries.hydrate(record.k, record.d)) {
373
383
  if (typeof record.t === 'number') {
374
384
  cacheStore.hydrateQueryFetchTime(record.k, record.t);
375
385
  }
@@ -437,7 +447,9 @@ function flushDirtyKeys() {
437
447
  return;
438
448
  }
439
449
 
440
- const fragmentKeys = Array.from(DIRTY_FRAGMENT_KEYS);
450
+ const fragmentKeys = Array.from(DIRTY_FRAGMENT_KEYS).filter(
451
+ (key) => !isOptimisticUIFragmentActive(key),
452
+ );
441
453
  const queryKeys = Array.from(DIRTY_QUERY_KEYS);
442
454
  DIRTY_FRAGMENT_KEYS.clear();
443
455
  DIRTY_QUERY_KEYS.clear();
@@ -487,7 +499,7 @@ function flushDirtyKeys() {
487
499
 
488
500
  for (const key of queryKeys) {
489
501
  const value = cacheStore.queries.peek(key);
490
- if (value === undefined) {
502
+ if (value === undefined || !queryKeyIsPersistable(key)) {
491
503
  queriesStore.delete(key);
492
504
  continue;
493
505
  }
@@ -509,6 +521,10 @@ function flushDirtyKeys() {
509
521
 
510
522
  tx.onerror = () => disablePersistence(tx.error);
511
523
  tx.onabort = () => disablePersistence(tx.error || 'transaction aborted');
524
+
525
+ // Commit now instead of at the end of the task, so a flush started while
526
+ // the page unloads still reaches disk
527
+ tx.commit?.();
512
528
  } catch (err) {
513
529
  disablePersistence(err);
514
530
  }
@@ -537,6 +553,42 @@ function scheduleFlush() {
537
553
  FLUSH_TIMER = setTimeout(flushDirtyKeys, delay);
538
554
  }
539
555
 
556
+ /**
557
+ * Flush buffered dirty keys immediately when the page is hidden or unloads.
558
+ * A reload inside the debounce window would otherwise drop the pending write
559
+ * and hydrate the previous snapshot, which still looks fresh by fetch time.
560
+ */
561
+
562
+ function flushDirtyKeysOnPageHide(event: Event) {
563
+ if (
564
+ event.type === 'visibilitychange' &&
565
+ document.visibilityState !== 'hidden'
566
+ ) {
567
+ return;
568
+ }
569
+
570
+ if (FLUSH_TIMER) {
571
+ clearTimeout(FLUSH_TIMER);
572
+ }
573
+
574
+ flushDirtyKeys();
575
+ }
576
+
577
+ /**
578
+ * Bind the page-hide flush once per page; flushDirtyKeys() no-ops while
579
+ * persistence is disabled, so the listeners never need removing.
580
+ */
581
+
582
+ function bindPageHideFlush() {
583
+ if (PAGE_HIDE_FLUSH_BOUND || typeof document === 'undefined') {
584
+ return;
585
+ }
586
+
587
+ PAGE_HIDE_FLUSH_BOUND = true;
588
+ globalThis.addEventListener('pagehide', flushDirtyKeysOnPageHide);
589
+ document.addEventListener('visibilitychange', flushDirtyKeysOnPageHide);
590
+ }
591
+
540
592
  /**
541
593
  * Store subscription: buffer dirty keys and schedule a flush.
542
594
  */
@@ -549,8 +601,14 @@ function onStoreDirty(dirty: {
549
601
  return;
550
602
  }
551
603
 
552
- dirty.fragmentKeys.forEach((key) => DIRTY_FRAGMENT_KEYS.add(key));
553
- dirty.queryKeys.forEach((key) => DIRTY_QUERY_KEYS.add(key));
604
+ dirty.fragmentKeys.forEach((key) => {
605
+ if (!isOptimisticUIFragmentActive(key)) {
606
+ DIRTY_FRAGMENT_KEYS.add(key);
607
+ }
608
+ });
609
+ dirty.queryKeys.forEach((key) => {
610
+ DIRTY_QUERY_KEYS.add(key);
611
+ });
554
612
 
555
613
  if (DIRTY_FRAGMENT_KEYS.size || DIRTY_QUERY_KEYS.size) {
556
614
  scheduleFlush();
@@ -575,6 +633,7 @@ function metaMatchesContext(
575
633
  (meta.cacheAuthorizationEpoch ?? null) ===
576
634
  (context.cacheAuthorizationEpoch ?? null) &&
577
635
  typeof meta.savedAt === 'number' &&
636
+ meta.savedAt <= Date.now() &&
578
637
  Date.now() - meta.savedAt < PERSIST_CONSTANTS.maxSnapshotAgeMs,
579
638
  );
580
639
  }
@@ -617,8 +676,9 @@ export function initGraphQLCachePersistence(
617
676
  // hydrated keys to this caller's observer too. Duplicate notifications
618
677
  // are cheap; fragment hooks are version-stamp guarded.
619
678
  if (onHydrated) {
679
+ const generation = PERSISTENCE_GENERATION;
620
680
  INIT_PROMISE.then(() => {
621
- if (LAST_HYDRATED_FRAGMENT_KEYS.length) {
681
+ if (generation === PERSISTENCE_GENERATION && LAST_HYDRATED_FRAGMENT_KEYS.length) {
622
682
  onHydrated(LAST_HYDRATED_FRAGMENT_KEYS);
623
683
  }
624
684
  });
@@ -634,35 +694,53 @@ export function initGraphQLCachePersistence(
634
694
  }
635
695
 
636
696
  ACTIVE_CONTEXT = context;
697
+ const generation = ++PERSISTENCE_GENERATION;
698
+ /* Check ownership after every asynchronous storage boundary. */
699
+ const isCurrent = () => generation === PERSISTENCE_GENERATION;
637
700
  INIT_PROMISE = (async () => {
701
+ let db: IDBDatabase | null = null;
638
702
  try {
639
- const db = await openDatabase();
703
+ db = await openDatabase();
704
+ if (!isCurrent()) {
705
+ db.close();
706
+ return false;
707
+ }
640
708
  const metaTx = db.transaction(PERSIST_CONSTANTS.metaStore, 'readonly');
641
709
  const meta = await requestAsPromise<PersistedMeta | undefined>(
642
710
  metaTx
643
711
  .objectStore(PERSIST_CONSTANTS.metaStore)
644
712
  .get(PERSIST_CONSTANTS.metaKey),
645
713
  );
714
+ if (!isCurrent()) {
715
+ db.close();
716
+ return false;
717
+ }
646
718
 
647
719
  let hydratedFragmentKeys: string[] = [];
648
720
  const matched = metaMatchesContext(meta, context);
649
721
 
650
722
  if (matched) {
651
- hydratedFragmentKeys = await hydrateFromDatabase(db);
723
+ hydratedFragmentKeys = await hydrateFromDatabase(db, isCurrent);
652
724
  } else {
653
725
  // Different account/org/schema/build or stale snapshot: wipe
654
726
  await clearAllStores(db);
655
727
  }
728
+ if (!isCurrent()) {
729
+ db.close();
730
+ return false;
731
+ }
656
732
 
657
733
  LAST_HYDRATED_FRAGMENT_KEYS = hydratedFragmentKeys;
658
734
 
659
735
  DB = db;
660
736
  ENABLED = true;
661
737
  UNSUBSCRIBE_STORE = cacheStore.subscribe(onStoreDirty);
738
+ bindPageHideFlush();
662
739
 
663
740
  db.onversionchange = () => {
664
741
  // Another tab upgraded/deleted the database; step aside
665
- disablePersistence('database version change');
742
+ if (isCurrent()) disablePersistence('database version change');
743
+ else db?.close();
666
744
  };
667
745
 
668
746
  if (hydratedFragmentKeys.length && onHydrated) {
@@ -671,7 +749,8 @@ export function initGraphQLCachePersistence(
671
749
 
672
750
  return hydratedFragmentKeys.length > 0;
673
751
  } catch (err) {
674
- disablePersistence(err);
752
+ if (isCurrent()) disablePersistence(err);
753
+ else db?.close();
675
754
  return false;
676
755
  }
677
756
  })();
@@ -686,6 +765,10 @@ export function initGraphQLCachePersistence(
686
765
  */
687
766
 
688
767
  export function clearGraphQLCachePersistence() {
768
+ PERSISTENCE_GENERATION += 1;
769
+ INIT_PROMISE = null;
770
+ ACTIVE_CONTEXT = null;
771
+ LAST_HYDRATED_FRAGMENT_KEYS = [];
689
772
  if (!isIndexedDBAvailable()) {
690
773
  return;
691
774
  }
@@ -700,7 +783,9 @@ export function clearGraphQLCachePersistence() {
700
783
  }
701
784
 
702
785
  if (DB) {
703
- clearAllStores(DB).catch((err) => disablePersistence(err));
786
+ // Start the clear transaction before closing this context's connection.
787
+ void clearAllStores(DB).catch(() => {});
788
+ disablePersistence('cache cleared');
704
789
  return;
705
790
  }
706
791
 
@@ -0,0 +1,47 @@
1
+ // Fragment key → the fields realtime changes wrote to that record, and when the last one arrived
2
+ const REALTIME_WRITES = new Map<string, { at: number; data: Record<string, unknown> }>();
3
+ const FILE_CONSTANTS = { keepMs: 120_000, pruneAbove: 2_000 };
4
+
5
+ /*
6
+ * Remember which fields a realtime change wrote to a record, and when. Also
7
+ * called for records that are not cached, so a deletion still reaches a
8
+ * response that was in flight when it arrived.
9
+ */
10
+ export function noteRealtimeWrite(fragmentKey: string, data: Record<string, unknown>, at = Date.now()) {
11
+ const previous = REALTIME_WRITES.get(fragmentKey);
12
+ REALTIME_WRITES.set(fragmentKey, {
13
+ at,
14
+ data: previous && at - previous.at < FILE_CONSTANTS.keepMs ? { ...previous.data, ...data } : data,
15
+ });
16
+ if (REALTIME_WRITES.size > FILE_CONSTANTS.pruneAbove) {
17
+ for (const [key, write] of REALTIME_WRITES) {
18
+ if (at - write.at > FILE_CONSTANTS.keepMs) REALTIME_WRITES.delete(key);
19
+ }
20
+ }
21
+ }
22
+
23
+ /*
24
+ * Keep the fields that a realtime change wrote after this response's request
25
+ * began; every other field comes from the response (design 8.3).
26
+ */
27
+ export function keepNewerRealtimeFields(fragmentKey: string, incoming: any, current: any, requestStartedAt: number) {
28
+ const write = REALTIME_WRITES.get(fragmentKey);
29
+ if (!write || !requestStartedAt || write.at < requestStartedAt || !incoming || typeof incoming !== 'object') return incoming;
30
+ let result = incoming;
31
+ for (const field of Object.keys(write.data)) {
32
+ // A response never selects __deleted, so the marker is always carried over; other fields only when the response has them
33
+ if (field !== '__deleted' && !Object.hasOwn(incoming, field)) continue;
34
+ const value = current && Object.hasOwn(current, field) ? current[field] : write.data[field];
35
+ if (incoming[field] === value) continue;
36
+ if (result === incoming) result = { ...incoming };
37
+ result[field] = value;
38
+ }
39
+ return result;
40
+ }
41
+
42
+ /*
43
+ * Forget every remembered realtime write (sign-out, cache reset).
44
+ */
45
+ export function clearRealtimeWrites() {
46
+ REALTIME_WRITES.clear();
47
+ }
@@ -0,0 +1,17 @@
1
+ // Page load: results restored from IndexedDB are older than this, so they refetch on their first mount
2
+ let realtimeLiveSince = Date.now();
3
+
4
+ /*
5
+ * Record that realtime delivery resumed after a gap; query results fetched
6
+ * before now are no longer trusted and refetch through the stale checks.
7
+ */
8
+ export function markRealtimeResumed() {
9
+ realtimeLiveSince = Date.now();
10
+ }
11
+
12
+ /*
13
+ * Return the time since which this tab's realtime delivery has been continuous.
14
+ */
15
+ export function getRealtimeLiveSince() {
16
+ return realtimeLiveSince;
17
+ }
package/cache/store.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { graphQLValuesEqual } from './value.helpers.ts';
2
+
1
3
  /**
2
4
  * Versioned normalized store core for the GraphQL client cache.
3
5
  *
@@ -59,64 +61,6 @@ function mergeIntoActiveCapture(deps: Map<string, number>) {
59
61
  }
60
62
  }
61
63
 
62
- /**
63
- * Fast deep equality with reference short-circuit; used to skip version bumps
64
- * for writes that re-assert identical data (common with realtime echoes and
65
- * refetches), which keeps memoized reads and downstream renders stable.
66
- */
67
-
68
- function deepEqual(a: any, b: any): boolean {
69
- if (a === b) {
70
- return true;
71
- }
72
-
73
- if (
74
- typeof a !== typeof b ||
75
- a === null ||
76
- b === null ||
77
- typeof a !== 'object'
78
- ) {
79
- // NaN never equals itself, but the cache never stores NaN meaningfully
80
- return false;
81
- }
82
-
83
- const aIsArray = Array.isArray(a);
84
- if (aIsArray !== Array.isArray(b)) {
85
- return false;
86
- }
87
-
88
- if (aIsArray) {
89
- if (a.length !== b.length) {
90
- return false;
91
- }
92
-
93
- for (let i = 0; i < a.length; i++) {
94
- if (!deepEqual(a[i], b[i])) {
95
- return false;
96
- }
97
- }
98
-
99
- return true;
100
- }
101
-
102
- const aKeys = Object.keys(a);
103
- const bKeys = Object.keys(b);
104
- if (aKeys.length !== bKeys.length) {
105
- return false;
106
- }
107
-
108
- for (const key of aKeys) {
109
- if (
110
- !Object.prototype.hasOwnProperty.call(b, key) ||
111
- !deepEqual(a[key], b[key])
112
- ) {
113
- return false;
114
- }
115
- }
116
-
117
- return true;
118
- }
119
-
120
64
  /**
121
65
  * Map-compatible facade over a versioned entry map. get() records a memo
122
66
  * dependency and touches the LRU stamp; set() bumps the version only when the
@@ -172,7 +116,7 @@ export class VersionedKeyMap {
172
116
  const entry = this.entries.get(key);
173
117
 
174
118
  if (entry) {
175
- if (deepEqual(entry.data, data)) {
119
+ if (graphQLValuesEqual(entry.data, data)) {
176
120
  // Keep the previously stored reference so memoized assemblies built
177
121
  // from it remain valid; the write changes nothing observable.
178
122
  entry.at = nextTick();
@@ -307,6 +251,19 @@ class GraphQLCacheStore {
307
251
  return this.queryFetchTimes.get(queryKey);
308
252
  }
309
253
 
254
+ /* A partial/error response may update visible fields but cannot certify freshness. */
255
+ clearQueryFetchTime(queryKey: string): void {
256
+ if (this.queryFetchTimes.delete(queryKey)) this.queueDirty(this.dirtyQueryKeys, queryKey);
257
+ }
258
+
259
+ /**
260
+ * Re-emit one fragment dirty notification without changing its cache version.
261
+ * This lets transient memory-only writes persist their settled final value.
262
+ */
263
+ markFragmentDirty(fragmentKey: string): void {
264
+ this.queueDirty(this.dirtyFragmentKeys, fragmentKey);
265
+ }
266
+
310
267
  /** Restore one persisted fetch stamp at boot (never marks dirty). */
311
268
  hydrateQueryFetchTime(queryKey: string, fetchedAt: number): void {
312
269
  if (!this.queryFetchTimes.has(queryKey)) {
@@ -410,11 +367,12 @@ class GraphQLCacheStore {
410
367
  let stamp = '';
411
368
 
412
369
  for (const key of fragmentKeys) {
413
- stamp +=
414
- this.fragments.version(key) +
415
- '.' +
416
- this.fragments.version(`${key}.spreads`) +
417
- '|';
370
+ stamp += this.fragments.version(key) + '.' + this.fragments.version(`${key}.spreads`) + '|';
371
+ // A parent can assemble nested references without its own record
372
+ // changing. Include those dependencies when checking a notification.
373
+ for (const dependency of MEMO.get(key)?.deps.keys() || []) {
374
+ stamp += this.versionOfNamespacedKey(dependency) + '.';
375
+ }
418
376
  }
419
377
 
420
378
  return stamp;
@@ -0,0 +1,17 @@
1
+ /*
2
+ * Compare JSON-shaped GraphQL values without serializing or depending on key
3
+ * insertion order. Missing fields remain distinct from explicit undefined/null.
4
+ */
5
+ export function graphQLValuesEqual(left: any, right: any): boolean {
6
+ if (left === right) return true;
7
+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') return false;
8
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
9
+ if (Array.isArray(left)) {
10
+ return left.length === right.length && left.every((value, index) => graphQLValuesEqual(value, right[index]));
11
+ }
12
+ const keys = Object.keys(left);
13
+ return (
14
+ keys.length === Object.keys(right).length &&
15
+ keys.every((key) => Object.hasOwn(right, key) && graphQLValuesEqual(left[key], right[key]))
16
+ );
17
+ }
@@ -229,17 +229,21 @@ function openDatabase(): Promise<IDBDatabase | null> {
229
229
  /**
230
230
  * Read one record, honoring the reader's TTL. Expired records resolve null and
231
231
  * are removed. The in-memory mirror answers first so a read that follows a
232
- * write in the same session never races the disk transaction.
232
+ * write in the same session never races the disk transaction. A fresh read
233
+ * skips the mirror to see what other tabs wrote since, unless IndexedDB is
234
+ * unusable (then the mirror is all there is).
233
235
  */
234
236
 
235
237
  export async function readDraftRecord(
236
238
  key: string,
237
239
  ttlHours: number,
240
+ fresh = false,
238
241
  ): Promise<DraftRecord | null> {
239
242
  const now = Date.now();
240
243
  const memoryRecord = MEMORY_RECORDS.get(key);
244
+ const freshDb = fresh ? await openDatabase() : null;
241
245
 
242
- if (memoryRecord) {
246
+ if (memoryRecord && !freshDb) {
243
247
  if (getRecordExpiresAt(memoryRecord, ttlHours) > now) {
244
248
  return memoryRecord;
245
249
  }
@@ -249,7 +253,7 @@ export async function readDraftRecord(
249
253
  return null;
250
254
  }
251
255
 
252
- const db = await openDatabase();
256
+ const db = freshDb || (await openDatabase());
253
257
  if (!db) {
254
258
  return null;
255
259
  }
@@ -361,6 +365,18 @@ export async function deleteDraftRecord(key: string): Promise<void> {
361
365
  try {
362
366
  const tx = db.transaction(STORE_CONSTANTS.draftsStore, 'readwrite');
363
367
  tx.objectStore(STORE_CONSTANTS.draftsStore).delete(key);
368
+
369
+ await new Promise<void>((resolve) => {
370
+ tx.oncomplete = () => resolve();
371
+ tx.onerror = () => {
372
+ disableDatabase(tx.error);
373
+ resolve();
374
+ };
375
+ tx.onabort = () => {
376
+ disableDatabase(tx.error || 'transaction aborted');
377
+ resolve();
378
+ };
379
+ });
364
380
  } catch (err) {
365
381
  disableDatabase(err);
366
382
  }
@@ -1,15 +1,11 @@
1
- import {
2
- type DraftSchema,
3
- mergeSchemaDefaults,
4
- pruneToSchema,
5
- } from '@jsb188/app/utils/schema.ts';
1
+ import { type DraftSchema, mergeSchemaDefaults, pruneToSchema } from '@jsb188/app/utils/schema.ts';
6
2
  import {
7
3
  deleteAllDraftRecords,
8
4
  deleteDraftRecord,
9
5
  peekDraftRecord,
10
6
  readDraftRecord,
11
7
  writeDraftRecord,
12
- } from './store.ts';
8
+ } from './draft-persistence-indexed-db.ts';
13
9
 
14
10
  /**
15
11
  * Expiring local objects ("drafts").
@@ -20,7 +16,7 @@ import {
20
16
  * server-side entity: composer text, selected uploads, form-in-progress.
21
17
  *
22
18
  * Keys are namespaced by the caller. The convention is
23
- * "feature:version:scopeId", e.g. `createCampaignTemplate:v1:${orgId}` — the
19
+ * "feature:version:scopeId", e.g. `editDocument:v1:${documentId}` — the
24
20
  * scope segment keeps one organization's draft out of another's, and the
25
21
  * version segment is the escape hatch for a shape change the schema cannot
26
22
  * catch (a field that keeps its type but changes its meaning).
@@ -40,6 +36,8 @@ export interface DraftOptions<T> {
40
36
  schema?: DraftSchema;
41
37
  /* Read: how old a record may be. Write: the sweep hint stored with it */
42
38
  ttlHours?: number;
39
+ /* Read only: skip this tab's session mirror to see other tabs' writes */
40
+ fresh?: boolean;
43
41
  }
44
42
 
45
43
  export const DRAFT_TTL_HOURS_DEFAULT = 24;
@@ -48,14 +46,9 @@ export const DRAFT_TTL_HOURS_DEFAULT = 24;
48
46
  * Apply the schema (when given) and merge the result over the default value.
49
47
  */
50
48
 
51
- function resolveDraftValue<T>(
52
- value: unknown,
53
- options?: DraftOptions<T>,
54
- ): T | null {
49
+ function resolveDraftValue<T>(value: unknown, options?: DraftOptions<T>): T | null {
55
50
  const defaultValue = options?.defaultValue ?? null;
56
- const prunedValue = options?.schema
57
- ? pruneToSchema(value, options.schema)
58
- : value;
51
+ const prunedValue = options?.schema ? pruneToSchema(value, options.schema) : value;
59
52
 
60
53
  if (prunedValue === null || prunedValue === undefined) {
61
54
  return defaultValue;
@@ -76,14 +69,8 @@ function resolveDraftValue<T>(
76
69
  * removed as part of the read.
77
70
  */
78
71
 
79
- export async function getDraft<T>(
80
- key: string,
81
- options?: DraftOptions<T>,
82
- ): Promise<T | null> {
83
- const record = await readDraftRecord(
84
- key,
85
- options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT,
86
- );
72
+ export async function getDraft<T>(key: string, options?: DraftOptions<T>): Promise<T | null> {
73
+ const record = await readDraftRecord(key, options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT, options?.fresh);
87
74
  return resolveDraftValue<T>(record?.d, options);
88
75
  }
89
76
 
@@ -96,10 +83,7 @@ export async function getDraft<T>(
96
83
  */
97
84
 
98
85
  export function peekDraft<T>(key: string, options?: DraftOptions<T>): T | null {
99
- const record = peekDraftRecord(
100
- key,
101
- options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT,
102
- );
86
+ const record = peekDraftRecord(key, options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT);
103
87
  return resolveDraftValue<T>(record?.d, options);
104
88
  }
105
89
 
@@ -110,14 +94,8 @@ export function peekDraft<T>(key: string, options?: DraftOptions<T>): T | null {
110
94
  * immediate, so a caller writing on every keystroke should debounce.
111
95
  */
112
96
 
113
- export async function setDraft<T>(
114
- key: string,
115
- value: T,
116
- options?: DraftOptions<T>,
117
- ): Promise<void> {
118
- const prunedValue = options?.schema
119
- ? pruneToSchema(value, options.schema)
120
- : value;
97
+ export async function setDraft<T>(key: string, value: T, options?: DraftOptions<T>): Promise<void> {
98
+ const prunedValue = options?.schema ? pruneToSchema(value, options.schema) : value;
121
99
  if (prunedValue === null || prunedValue === undefined) {
122
100
  // Nothing survived the schema; a stored draft would only resurrect a
123
101
  // shape the caller no longer holds
@@ -125,11 +103,7 @@ export async function setDraft<T>(
125
103
  return;
126
104
  }
127
105
 
128
- await writeDraftRecord(
129
- key,
130
- prunedValue,
131
- options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT,
132
- );
106
+ await writeDraftRecord(key, prunedValue, options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT);
133
107
  }
134
108
 
135
109
  /**
package/client/index.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from '../hooks/index.ts';
2
- export * from './fragment-realtime-sequence.ts';
3
- export * from './open-sheet.ts';
2
+ export * from '../libs/fragment-realtime-sequence.ts';
3
+ export * from '../libs/record-read.ts';
4
+ export * from '../libs/open-sheet.ts';
4
5
  export * from './request.ts';
6
+ export * from './storage-asset.ts';
@@ -0,0 +1,14 @@
1
+ /*
2
+ * Convert native fetch TypeError rejections to the shared network-error shape.
3
+ * Call only at the fetch boundary so parsing and application failures keep
4
+ * their original classification; cancellation and other errors pass through.
5
+ */
6
+ export function rethrowGraphQLFetchError(error: unknown): never {
7
+ if (error instanceof TypeError) {
8
+ throw {
9
+ errors: [{ errorCode: 'network_error', statusCode: 500 }],
10
+ };
11
+ }
12
+
13
+ throw error;
14
+ }