@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/client/request.ts CHANGED
@@ -1,18 +1,11 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
2
  import type { ServerErrorObj } from '@jsb188/app/types/app.d.ts';
3
- import {
4
- getAuthToken,
5
- managedAccessTokensShareBinding,
6
- normalizeServerError,
7
- } from '@jsb188/app/utils/api.ts';
8
- import { delay, makeVariablesKey } from '@jsb188/app/utils/logic.ts';
9
- import { setDataToCache } from '../cache/index.ts';
10
- import type {
11
- OnCompletedGQLFn,
12
- OnErrorGQLFn,
13
- UpdateObserversFn,
14
- } from '../types.d.ts';
3
+ import { getAuthToken, managedAccessTokensShareBinding, normalizeServerError } from '@jsb188/app/utils/api.ts';
4
+ import { delay, makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
5
+ import { getGraphQLCacheEpoch, setDataToCache } from '../cache/index.ts';
6
+ import type { OnCompletedGQLFn, OnErrorGQLFn, UpdateObserversFn } from '../types.d.ts';
15
7
  import { apiRequestHeaders, isServerErrorGQL } from '../utils.ts';
8
+ import { rethrowGraphQLFetchError } from './request.helpers.ts';
16
9
 
17
10
  /**
18
11
  * Types
@@ -32,16 +25,10 @@ type GraphQLMutationOptions = Partial<{
32
25
  initialError: any;
33
26
  onCompleted: OnCompletedGQLFn;
34
27
  onError: OnErrorGQLFn;
35
- shouldAcceptResult: (
36
- data: any,
37
- variables?: Record<string, any> | null,
38
- ) => boolean;
28
+ shouldAcceptResult: (data: any, variables?: Record<string, any> | null) => boolean;
39
29
  }>;
40
30
 
41
- export type GraphQLServerRequestOptions = Omit<
42
- GraphQLMutationOptions,
43
- 'cacheMap' | 'cachePolicy'
44
- > & {
31
+ export type GraphQLServerRequestOptions = Omit<GraphQLMutationOptions, 'cacheMap' | 'cachePolicy'> & {
45
32
  cacheResults?: boolean;
46
33
  cacheAccountId: string;
47
34
  cacheDuration?: number; // Milliseconds
@@ -53,32 +40,25 @@ type GraphQLServerRequestCacheEntry = {
53
40
  };
54
41
 
55
42
  type GraphQLSocketIdGetter = () => string | null | undefined;
56
- type GraphQLFormRespondentTokenGetter = () => string | null | undefined;
57
43
  export type GraphQLAccessTokenRefreshReason = 'PROACTIVE' | 'AUTH_FAILURE';
58
44
  export type GraphQLAccessTokenRefreshOutcome =
59
45
  | { status: 'CONTEXT_CHANGED' }
60
- | { status: 'REFRESHED'; accessToken: string }
46
+ | { status: 'REFRESHED'; accessToken: string; storageToken?: string }
61
47
  | { status: 'REJECTED' }
62
48
  | { status: 'UNAVAILABLE' };
63
49
  export type GraphQLAccessTokenRefreshHandler = (p: {
64
50
  accessToken: string;
65
51
  reason: GraphQLAccessTokenRefreshReason;
66
52
  }) => Promise<GraphQLAccessTokenRefreshOutcome>;
53
+ /** Signs the visitor IP a server render forwards to the API; null when it cannot. */
54
+ export type GraphQLClientIPSigner = (ipAddress: string) => Promise<string | null>;
67
55
 
68
56
  let GRAPHQL_SOCKET_ID_GETTER: GraphQLSocketIdGetter | null = null;
69
- let GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER: GraphQLFormRespondentTokenGetter | null =
70
- null;
71
- let GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER: GraphQLAccessTokenRefreshHandler | null =
72
- null;
57
+ let GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER: GraphQLAccessTokenRefreshHandler | null = null;
73
58
  let GRAPHQL_MANAGED_SESSION_VERSION: number | null = null;
74
- const GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES = new Map<
75
- string,
76
- Promise<GraphQLAccessTokenRefreshOutcome>
77
- >();
78
- const GRAPHQL_SERVER_REQUEST_CACHE = new Map<
79
- string,
80
- GraphQLServerRequestCacheEntry
81
- >();
59
+ let GRAPHQL_CLIENT_IP_SIGNER: GraphQLClientIPSigner | null = null;
60
+ const GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES = new Map<string, Promise<GraphQLAccessTokenRefreshOutcome>>();
61
+ const GRAPHQL_SERVER_REQUEST_CACHE = new Map<string, GraphQLServerRequestCacheEntry>();
82
62
  const GRAPHQL_SERVER_REQUEST_PROMISES = new Map<string, Promise<any>>();
83
63
  let GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT = 0;
84
64
 
@@ -146,30 +126,15 @@ function getHTTPErrorCode(statusCode: number): string {
146
126
  * Register a dynamic browser socket id getter for GraphQL request headers.
147
127
  */
148
128
 
149
- export function setGraphQLSocketIdGetter(
150
- socketIdGetter: GraphQLSocketIdGetter | null,
151
- ) {
129
+ export function setGraphQLSocketIdGetter(socketIdGetter: GraphQLSocketIdGetter | null) {
152
130
  GRAPHQL_SOCKET_ID_GETTER = socketIdGetter;
153
131
  }
154
132
 
155
- /**
156
- * Register a getter for the public web form respondent token (ANYONE-audience
157
- * forms authenticate with this verified-email token instead of an account).
158
- */
159
-
160
- export function setGraphQLFormRespondentTokenGetter(
161
- tokenGetter: GraphQLFormRespondentTokenGetter | null,
162
- ) {
163
- GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER = tokenGetter;
164
- }
165
-
166
133
  /**
167
134
  * Register the application-owned callback that exchanges its HttpOnly refresh
168
135
  * credential for a new GraphQL access token.
169
136
  */
170
- export function setGraphQLAccessTokenRefreshHandler(
171
- handler: GraphQLAccessTokenRefreshHandler | null,
172
- ) {
137
+ export function setGraphQLAccessTokenRefreshHandler(handler: GraphQLAccessTokenRefreshHandler | null) {
173
138
  GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER = handler;
174
139
  if (!handler) {
175
140
  GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES.clear();
@@ -184,6 +149,26 @@ export function setGraphQLManagedSessionVersion(version: number | null) {
184
149
  GRAPHQL_MANAGED_SESSION_VERSION = version === 1 ? 1 : null;
185
150
  }
186
151
 
152
+ /**
153
+ * Register the server-only signer that vouches for the visitor IP a server
154
+ * render forwards to the API (`x-ssr-ip`); the API ignores that IP unsigned.
155
+ */
156
+ export function setGraphQLClientIPSigner(signer: GraphQLClientIPSigner | null) {
157
+ GRAPHQL_CLIENT_IP_SIGNER = signer;
158
+ }
159
+
160
+ /**
161
+ * Sign the visitor IP a server render forwards, or null when there is none to
162
+ * sign or no signer (a browser); a failing signer never fails the request.
163
+ */
164
+ async function getGraphQLClientIPProof(ipAddress: string | null | undefined): Promise<string | null> {
165
+ if (!ipAddress || !GRAPHQL_CLIENT_IP_SIGNER) {
166
+ return null;
167
+ }
168
+
169
+ return await GRAPHQL_CLIENT_IP_SIGNER(ipAddress).catch(() => null);
170
+ }
171
+
187
172
  /**
188
173
  * Return the current browser socket id from the registered getter.
189
174
  */
@@ -204,6 +189,7 @@ function getGraphQLRequestHeaders(
204
189
  userAgent?: string | null,
205
190
  managedSessionVersion?: number | null,
206
191
  managedSessionBffProof?: string | null,
192
+ ipAddressProof?: string | null,
207
193
  ): Headers {
208
194
  const headers = apiRequestHeaders(authorization, ipAddress, userAgent);
209
195
  const socketId = getGraphQLSocketIdHeaderValue();
@@ -212,21 +198,17 @@ function getGraphQLRequestHeaders(
212
198
  headers.set('x-ws-socket-id', socketId);
213
199
  }
214
200
 
215
- const formRespondentToken = GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER?.();
216
- if (formRespondentToken) {
217
- headers.set('x-form-respondent', String(formRespondentToken));
218
- }
219
-
220
201
  const advertisedManagedSessionVersion =
221
- managedSessionVersion === undefined
222
- ? GRAPHQL_MANAGED_SESSION_VERSION
223
- : managedSessionVersion;
202
+ managedSessionVersion === undefined ? GRAPHQL_MANAGED_SESSION_VERSION : managedSessionVersion;
224
203
  if (advertisedManagedSessionVersion === 1) {
225
204
  headers.set('x-managed-session-version', '1');
226
205
  }
227
206
  if (managedSessionBffProof) {
228
207
  headers.set('x-managed-session-bff-proof', managedSessionBffProof);
229
208
  }
209
+ if (ipAddress && ipAddressProof) {
210
+ headers.set('x-ssr-ip-proof', ipAddressProof);
211
+ }
230
212
 
231
213
  return headers;
232
214
  }
@@ -266,9 +248,7 @@ function getAccessTokenRefreshMetadata(accessToken: string): {
266
248
  managed: boolean;
267
249
  } | null {
268
250
  try {
269
- const token = accessToken.startsWith('Bearer ')
270
- ? accessToken.slice('Bearer '.length)
271
- : accessToken;
251
+ const token = accessToken.startsWith('Bearer ') ? accessToken.slice('Bearer '.length) : accessToken;
272
252
  const encodedPayload = token.split('.')[1];
273
253
  if (!encodedPayload) {
274
254
  return null;
@@ -301,10 +281,7 @@ function shouldProactivelyRefreshAccessToken(accessToken: string): boolean {
301
281
  return false;
302
282
  }
303
283
 
304
- return (
305
- metadata.expiresAtSeconds - Date.now() / 1000 <=
306
- FILE_CONSTANTS.accessTokenRefreshWindowSeconds
307
- );
284
+ return metadata.expiresAtSeconds - Date.now() / 1000 <= FILE_CONSTANTS.accessTokenRefreshWindowSeconds;
308
285
  }
309
286
 
310
287
  /**
@@ -315,9 +292,7 @@ function isRefreshableAuthenticationFailure(data: any): boolean {
315
292
  const errors = Array.isArray(data?.errors) ? data.errors : [];
316
293
 
317
294
  return errors.some((error: any) => {
318
- const errorCode = String(
319
- error?.errorCode || error?.extensions?.errorCode || '',
320
- );
295
+ const errorCode = String(error?.errorCode || error?.extensions?.errorCode || '');
321
296
  return FILE_CONSTANTS.refreshableAuthErrorCodes.has(errorCode);
322
297
  });
323
298
  }
@@ -326,29 +301,19 @@ function isRefreshableAuthenticationFailure(data: any): boolean {
326
301
  * Return whether the request is using the application's current account token.
327
302
  */
328
303
  function canRefreshAccessToken(accessToken: string): boolean {
329
- return !!(
330
- getENVVariable('IS_BROWSER') &&
331
- GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER &&
332
- accessToken &&
333
- getAuthToken() === accessToken
334
- );
304
+ return !!(getENVVariable('IS_BROWSER') && GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER && accessToken && getAuthToken() === accessToken);
335
305
  }
336
306
 
337
307
  /**
338
308
  * Return a same-session replacement already installed by another refresh, or
339
309
  * report that the browser moved to a different account/session.
340
310
  */
341
- function getCurrentAccessTokenRefreshOutcome(
342
- accessToken: string,
343
- ): GraphQLAccessTokenRefreshOutcome | null {
311
+ function getCurrentAccessTokenRefreshOutcome(accessToken: string): GraphQLAccessTokenRefreshOutcome | null {
344
312
  const currentAccessToken = getAuthToken();
345
313
  if (currentAccessToken === accessToken) {
346
314
  return null;
347
315
  }
348
- if (
349
- currentAccessToken &&
350
- managedAccessTokensShareBinding(accessToken, currentAccessToken)
351
- ) {
316
+ if (currentAccessToken && managedAccessTokensShareBinding(accessToken, currentAccessToken)) {
352
317
  return {
353
318
  status: 'REFRESHED',
354
319
  accessToken: currentAccessToken,
@@ -366,8 +331,7 @@ function getCurrentAccessTokenRefreshOutcome(
366
331
  function createAuthenticationContextChangedError() {
367
332
  return {
368
333
  name: 'AbortError',
369
- message:
370
- 'GraphQL request was cancelled because the authentication context changed during refresh.',
334
+ message: 'GraphQL request was cancelled because the authentication context changed during refresh.',
371
335
  };
372
336
  }
373
337
 
@@ -428,8 +392,7 @@ async function refreshAccessToken(
428
392
  reason,
429
393
  })
430
394
  .then((outcome) =>
431
- outcome.status !== 'REFRESHED' ||
432
- managedAccessTokensShareBinding(accessToken, outcome.accessToken)
395
+ outcome.status !== 'REFRESHED' || managedAccessTokensShareBinding(accessToken, outcome.accessToken)
433
396
  ? outcome
434
397
  : { status: 'UNAVAILABLE' as const },
435
398
  )
@@ -449,14 +412,16 @@ async function refreshAccessToken(
449
412
  }
450
413
 
451
414
  /**
452
- * Refresh the browser's current managed access token for a non-HTTP transport.
415
+ * Refresh the browser's current managed access token for a browser request or socket.
453
416
  * The registered application handler still owns cookie rotation and app-state
454
417
  * replacement, while the shared single-flight prevents GraphQL/socket races.
455
418
  */
456
- export function refreshGraphQLRealtimeAccessToken(accessToken: string) {
419
+ export function refreshBrowserAccessToken(accessToken: string) {
457
420
  return refreshAccessToken(accessToken, 'AUTH_FAILURE');
458
421
  }
459
422
 
423
+ export { refreshBrowserAccessToken as refreshGraphQLRealtimeAccessToken };
424
+
460
425
  /**
461
426
  * Apply one managed-session refresh outcome to the request authorization or
462
427
  * throw the matching recoverable or terminal control-flow error.
@@ -495,6 +460,7 @@ async function executeGraphQLFetch(
495
460
  managedSessionBffProof: string | null | undefined,
496
461
  controllerSignal?: AbortSignal | null,
497
462
  ): Promise<any> {
463
+ const ipAddressProof = await getGraphQLClientIPProof(ipAddress);
498
464
  return fetch(getENVVariable('GQL_SERVER') as string, {
499
465
  signal: controllerSignal,
500
466
  method: 'POST',
@@ -504,13 +470,16 @@ async function executeGraphQLFetch(
504
470
  userAgent,
505
471
  managedSessionVersion,
506
472
  managedSessionBffProof,
473
+ ipAddressProof,
507
474
  ),
508
475
  body: JSON.stringify({
509
476
  query: gqlQuery?.loc?.source.body,
510
477
  variables,
511
478
  operationName,
512
479
  }),
513
- }).then(parseGraphQLResponse);
480
+ })
481
+ .catch(rethrowGraphQLFetchError)
482
+ .then(parseGraphQLResponse);
514
483
  }
515
484
 
516
485
  /**
@@ -530,22 +499,13 @@ async function executeGraphQLFetchWithRefresh(
530
499
  let authorization = initialAuthorization;
531
500
  let attemptedRefresh = false;
532
501
  let proactiveRefreshUnavailable = false;
533
- const refreshEligible =
534
- !!authorization && canRefreshAccessToken(authorization);
535
-
536
- if (
537
- authorization &&
538
- refreshEligible &&
539
- shouldProactivelyRefreshAccessToken(authorization)
540
- ) {
502
+ const refreshEligible = !!authorization && canRefreshAccessToken(authorization);
503
+
504
+ if (authorization && refreshEligible && shouldProactivelyRefreshAccessToken(authorization)) {
541
505
  attemptedRefresh = true;
542
506
  const refreshOutcome = await refreshAccessToken(authorization, 'PROACTIVE');
543
507
  proactiveRefreshUnavailable = refreshOutcome.status === 'UNAVAILABLE';
544
- authorization = resolveAuthorizationAfterRefresh(
545
- authorization,
546
- refreshOutcome,
547
- true,
548
- );
508
+ authorization = resolveAuthorizationAfterRefresh(authorization, refreshOutcome, true);
549
509
  }
550
510
 
551
511
  try {
@@ -561,24 +521,13 @@ async function executeGraphQLFetchWithRefresh(
561
521
  controllerSignal,
562
522
  );
563
523
 
564
- if (
565
- proactiveRefreshUnavailable &&
566
- isRefreshableAuthenticationFailure(data)
567
- ) {
524
+ if (proactiveRefreshUnavailable && isRefreshableAuthenticationFailure(data)) {
568
525
  throw createManagedSessionUnavailableError();
569
526
  }
570
527
 
571
- if (
572
- authorization &&
573
- !attemptedRefresh &&
574
- refreshEligible &&
575
- isRefreshableAuthenticationFailure(data)
576
- ) {
528
+ if (authorization && !attemptedRefresh && refreshEligible && isRefreshableAuthenticationFailure(data)) {
577
529
  attemptedRefresh = true;
578
- authorization = resolveAuthorizationAfterRefresh(
579
- authorization,
580
- await refreshAccessToken(authorization, 'AUTH_FAILURE'),
581
- );
530
+ authorization = resolveAuthorizationAfterRefresh(authorization, await refreshAccessToken(authorization, 'AUTH_FAILURE'));
582
531
  data = await executeGraphQLFetch(
583
532
  gqlQuery,
584
533
  variables,
@@ -594,19 +543,11 @@ async function executeGraphQLFetchWithRefresh(
594
543
 
595
544
  return data;
596
545
  } catch (error) {
597
- if (
598
- proactiveRefreshUnavailable &&
599
- isRefreshableAuthenticationFailure(error)
600
- ) {
546
+ if (proactiveRefreshUnavailable && isRefreshableAuthenticationFailure(error)) {
601
547
  throw createManagedSessionUnavailableError();
602
548
  }
603
549
 
604
- if (
605
- authorization &&
606
- !attemptedRefresh &&
607
- refreshEligible &&
608
- isRefreshableAuthenticationFailure(error)
609
- ) {
550
+ if (authorization && !attemptedRefresh && refreshEligible && isRefreshableAuthenticationFailure(error)) {
610
551
  const refreshedAuthorization = resolveAuthorizationAfterRefresh(
611
552
  authorization,
612
553
  await refreshAccessToken(authorization, 'AUTH_FAILURE'),
@@ -642,7 +583,8 @@ export async function graphqlRequestWithRetry(
642
583
  const { onCompleted, onError, openModalPopUp } = graphqlOptions;
643
584
 
644
585
  const apiResult = await graphqlRequest(gqlQuery, graphqlOptions?.variables, {
645
- openModalPopUp: retryCount >= triedCount ? openModalPopUp : undefined,
586
+ ...graphqlOptions,
587
+ openModalPopUp: triedCount >= retryCount ? openModalPopUp : undefined,
646
588
  onCompleted: (data: any | null, error: ServerErrorObj | null) => {
647
589
  if (onCompleted && data.data) {
648
590
  onCompleted(data.data, error, graphqlOptions?.variables);
@@ -666,9 +608,7 @@ export async function graphqlRequestWithRetry(
666
608
 
667
609
  return graphqlRequestWithRetry(gqlQuery, graphqlOptions, triedCount + 1);
668
610
  } else if (getENVVariable('NODE_ENV') === 'development') {
669
- console.log(
670
- `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
671
- );
611
+ console.log(`mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`);
672
612
  }
673
613
  }
674
614
 
@@ -707,15 +647,29 @@ export async function graphqlRequest(
707
647
  console.log(gqlQuery);
708
648
  }
709
649
 
710
- const operationName = gqlQuery?.definitions?.find(
711
- (def: any) => def.kind === 'OperationDefinition',
712
- )?.name?.value;
713
- const authorization =
714
- authToken || (getENVVariable('IS_BROWSER') ? getAuthToken() : null);
650
+ const operationName = gqlQuery?.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
651
+ const authorization = authToken || (getENVVariable('IS_BROWSER') ? getAuthToken() : null);
652
+ const requestCacheEpoch = getGraphQLCacheEpoch();
653
+ const browserAuthorization = getENVVariable('IS_BROWSER') ? getAuthToken() : null;
654
+ /* Reject late results after cancellation, sign-out or a cache authorization reset. */
655
+ const requestIsCurrent = () => {
656
+ const currentAuthorization = getENVVariable('IS_BROWSER') ? getAuthToken() : null;
657
+ return (
658
+ !controllerSignal?.aborted &&
659
+ requestCacheEpoch === getGraphQLCacheEpoch() &&
660
+ (browserAuthorization === currentAuthorization ||
661
+ Boolean(
662
+ browserAuthorization && currentAuthorization && managedAccessTokensShareBinding(browserAuthorization, currentAuthorization),
663
+ ))
664
+ );
665
+ };
715
666
 
716
667
  // Use this to check queries that are getting double-requested
717
668
  // doLog(gqlQuery, 'QUERYING... $0');
718
669
 
670
+ // Realtime changes that arrive after this moment are newer than the response (cache/realtime-fence.ts)
671
+ const requestStartedAt = Date.now();
672
+
719
673
  return executeGraphQLFetchWithRefresh(
720
674
  gqlQuery,
721
675
  variables,
@@ -728,10 +682,22 @@ export async function graphqlRequest(
728
682
  controllerSignal,
729
683
  )
730
684
  .then((data) => {
685
+ if (!requestIsCurrent()) return { aborted: true };
731
686
  let gqlError: ServerErrorObj | null = null;
732
687
  if (data.errors?.length) {
733
688
  gqlError = normalizeServerError(data);
689
+ }
734
690
 
691
+ // Partial data must pass scope/version guards even when GraphQL also returned errors.
692
+ const resultAccepted = !data.data || !shouldAcceptResult || shouldAcceptResult(data.data, variables);
693
+ if (!resultAccepted) {
694
+ return {
695
+ __clientResultRejected: true,
696
+ error: gqlError,
697
+ };
698
+ }
699
+
700
+ if (gqlError) {
735
701
  if (openModalPopUp) {
736
702
  openModalPopUp(null, gqlError);
737
703
  }
@@ -740,26 +706,11 @@ export async function graphqlRequest(
740
706
  onError(gqlError, variables);
741
707
  }
742
708
  }
743
-
744
- const resultAccepted =
745
- !!gqlError ||
746
- !shouldAcceptResult ||
747
- shouldAcceptResult(data.data, variables);
748
- if (!resultAccepted) {
749
- return {
750
- __clientResultRejected: true,
751
- error: null,
752
- };
753
- }
709
+ // A result/error callback can synchronously clear the authenticated cache.
710
+ if (!requestIsCurrent()) return { aborted: true };
754
711
 
755
712
  if (cachePolicy !== 'no-store') {
756
- setDataToCache(
757
- data.data,
758
- gqlQuery,
759
- variables,
760
- cacheMap,
761
- updateObservers,
762
- );
713
+ setDataToCache(data.data, gqlQuery, variables, cacheMap, updateObservers, !gqlError, requestStartedAt);
763
714
  }
764
715
 
765
716
  if (onCompleted) {
@@ -772,7 +723,7 @@ export async function graphqlRequest(
772
723
  };
773
724
  })
774
725
  .catch((err) => {
775
- if (err?.name === 'AbortError') {
726
+ if (err?.name === 'AbortError' || !requestIsCurrent()) {
776
727
  return { aborted: true };
777
728
  }
778
729
 
@@ -828,13 +779,9 @@ function assertGraphQLServerRequestRuntime() {
828
779
  * Return the single query operation from a server-cached GraphQL document.
829
780
  */
830
781
  function getGraphQLServerRequestOperation(gqlQuery: any) {
831
- const operation = gqlQuery?.definitions?.find(
832
- (definition: any) => definition.kind === 'OperationDefinition',
833
- );
782
+ const operation = gqlQuery?.definitions?.find((definition: any) => definition.kind === 'OperationDefinition');
834
783
  if (!operation || operation.operation !== 'query') {
835
- throw new Error(
836
- 'graphqlServerRequest() only supports GraphQL query operations.',
837
- );
784
+ throw new Error('graphqlServerRequest() only supports GraphQL query operations.');
838
785
  }
839
786
 
840
787
  return operation;
@@ -843,20 +790,11 @@ function getGraphQLServerRequestOperation(gqlQuery: any) {
843
790
  /**
844
791
  * Build one server cache key from account scope, query source, and variables.
845
792
  */
846
- function makeGraphQLServerRequestCacheKey(
847
- gqlQuery: any,
848
- variables: Record<string, any> | null | undefined,
849
- cacheAccountId: string,
850
- ) {
793
+ function makeGraphQLServerRequestCacheKey(gqlQuery: any, variables: Record<string, any> | null | undefined, cacheAccountId: string) {
851
794
  const operation = getGraphQLServerRequestOperation(gqlQuery);
852
- const queryIdentity =
853
- gqlQuery?.loc?.source?.body || operation.name?.value || '';
795
+ const queryIdentity = gqlQuery?.loc?.source?.body || operation.name?.value || '';
854
796
 
855
- return JSON.stringify([
856
- cacheAccountId,
857
- queryIdentity,
858
- makeVariablesKey(variables, true),
859
- ]);
797
+ return JSON.stringify([cacheAccountId, queryIdentity, makeGraphQLVariablesKey(variables)]);
860
798
  }
861
799
 
862
800
  /**
@@ -865,10 +803,7 @@ function makeGraphQLServerRequestCacheKey(
865
803
  * request; per-key expiry on read handles the keys in active use.
866
804
  */
867
805
  function pruneGraphQLServerRequestCache(currentTime: number) {
868
- if (
869
- currentTime - GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT <
870
- FILE_CONSTANTS.serverRequestCachePruneIntervalMs
871
- ) {
806
+ if (currentTime - GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT < FILE_CONSTANTS.serverRequestCachePruneIntervalMs) {
872
807
  return;
873
808
  }
874
809
  GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT = currentTime;
@@ -883,10 +818,7 @@ function pruneGraphQLServerRequestCache(currentTime: number) {
883
818
  /**
884
819
  * Return one live cached entry for a key, deleting it when expired.
885
820
  */
886
- function getLiveGraphQLServerRequestCacheEntry(
887
- cacheKey: string,
888
- currentTime: number,
889
- ) {
821
+ function getLiveGraphQLServerRequestCacheEntry(cacheKey: string, currentTime: number) {
890
822
  const cachedEntry = GRAPHQL_SERVER_REQUEST_CACHE.get(cacheKey);
891
823
  if (cachedEntry && cachedEntry.expiresAt <= currentTime) {
892
824
  GRAPHQL_SERVER_REQUEST_CACHE.delete(cacheKey);
@@ -900,23 +832,13 @@ function getLiveGraphQLServerRequestCacheEntry(
900
832
  * Return whether a GraphQL network result is safe to retain in server memory.
901
833
  */
902
834
  function graphQLServerRequestResultIsCacheable(result: any) {
903
- return (
904
- !!result &&
905
- !result.error &&
906
- !result.aborted &&
907
- !result.__clientResultRejected
908
- );
835
+ return !!result && !result.error && !result.aborted && !result.__clientResultRejected;
909
836
  }
910
837
 
911
838
  /**
912
839
  * Cache one successful server query result when the caller allows writes.
913
840
  */
914
- function cacheGraphQLServerRequestResult(
915
- cacheKey: string,
916
- result: any,
917
- cacheResults: boolean,
918
- cacheDuration: number,
919
- ) {
841
+ function cacheGraphQLServerRequestResult(cacheKey: string, result: any, cacheResults: boolean, cacheDuration: number) {
920
842
  if (cacheResults && graphQLServerRequestResultIsCacheable(result)) {
921
843
  GRAPHQL_SERVER_REQUEST_CACHE.set(cacheKey, {
922
844
  expiresAt: Date.now() + cacheDuration,
@@ -926,10 +848,7 @@ function cacheGraphQLServerRequestResult(
926
848
  // Hard cap: evict oldest-inserted entries first. Insertion order is a
927
849
  // good-enough recency proxy here because the TTL bounds staleness and a
928
850
  // crawler minting unique public-URL keys must never grow this unbounded.
929
- if (
930
- GRAPHQL_SERVER_REQUEST_CACHE.size >
931
- FILE_CONSTANTS.serverRequestCacheMaxEntries
932
- ) {
851
+ if (GRAPHQL_SERVER_REQUEST_CACHE.size > FILE_CONSTANTS.serverRequestCacheMaxEntries) {
933
852
  const oldestKey = GRAPHQL_SERVER_REQUEST_CACHE.keys().next().value;
934
853
  if (oldestKey !== undefined) {
935
854
  GRAPHQL_SERVER_REQUEST_CACHE.delete(oldestKey);
@@ -959,49 +878,27 @@ export function graphqlServerRequest(
959
878
  } = params;
960
879
 
961
880
  if (!cacheAccountId?.trim()) {
962
- throw new Error(
963
- 'graphqlServerRequest() requires cacheAccountId. Use "*" for a shared or guest cache scope.',
964
- );
881
+ throw new Error('graphqlServerRequest() requires cacheAccountId. Use "*" for a shared or guest cache scope.');
965
882
  }
966
883
  if (!Number.isFinite(cacheDuration) || cacheDuration < 0) {
967
- throw new Error(
968
- 'graphqlServerRequest() cacheDuration must be a non-negative finite number.',
969
- );
884
+ throw new Error('graphqlServerRequest() cacheDuration must be a non-negative finite number.');
970
885
  }
971
886
 
972
887
  const currentTime = Date.now();
973
- const cacheKey = makeGraphQLServerRequestCacheKey(
974
- gqlQuery,
975
- variables,
976
- cacheAccountId,
977
- );
888
+ const cacheKey = makeGraphQLServerRequestCacheKey(gqlQuery, variables, cacheAccountId);
978
889
  pruneGraphQLServerRequestCache(currentTime);
979
890
 
980
- const cachedEntry = getLiveGraphQLServerRequestCacheEntry(
981
- cacheKey,
982
- currentTime,
983
- );
891
+ const cachedEntry = getLiveGraphQLServerRequestCacheEntry(cacheKey, currentTime);
984
892
  if (cachedEntry) {
985
893
  return Promise.resolve(cachedEntry.result);
986
894
  }
987
895
 
988
896
  const pendingRequest = GRAPHQL_SERVER_REQUEST_PROMISES.get(cacheKey);
989
897
  if (pendingRequest) {
990
- return pendingRequest.then((result) =>
991
- cacheGraphQLServerRequestResult(
992
- cacheKey,
993
- result,
994
- cacheResults,
995
- cacheDuration,
996
- ),
997
- );
898
+ return pendingRequest.then((result) => cacheGraphQLServerRequestResult(cacheKey, result, cacheResults, cacheDuration));
998
899
  }
999
900
 
1000
- const requestPromise = graphqlRequestNoStore(
1001
- gqlQuery,
1002
- variables,
1003
- requestParams,
1004
- );
901
+ const requestPromise = graphqlRequestNoStore(gqlQuery, variables, requestParams);
1005
902
  GRAPHQL_SERVER_REQUEST_PROMISES.set(cacheKey, requestPromise);
1006
903
 
1007
904
  /**
@@ -1014,12 +911,5 @@ export function graphqlServerRequest(
1014
911
  };
1015
912
  requestPromise.then(clearPendingRequest, clearPendingRequest);
1016
913
 
1017
- return requestPromise.then((result) =>
1018
- cacheGraphQLServerRequestResult(
1019
- cacheKey,
1020
- result,
1021
- cacheResults,
1022
- cacheDuration,
1023
- ),
1024
- );
914
+ return requestPromise.then((result) => cacheGraphQLServerRequestResult(cacheKey, result, cacheResults, cacheDuration));
1025
915
  }