@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,99 @@
1
+ import type { SheetViewGQL } from '@jsb188/mday/types/sheet.d.ts';
2
+
3
+ /*
4
+ * Realtime SheetView routing (DESIGN §0 D13, §1.4): websocket
5
+ * `$sheetViewFragment` packets bypass the GraphQL fragment cache and go
6
+ * straight to the listeners of their sheet (the workbook sync's tab stores),
7
+ * which dedupe by (tab, toSeq) and reassemble chunks themselves.
8
+ */
9
+
10
+ export type SheetViewRealtimeListener = (packet: SheetViewGQL) => void;
11
+
12
+ /* One registration; the same function registered twice is two registrations. */
13
+ type SheetViewRealtimeRegistration = {
14
+ listener: SheetViewRealtimeListener;
15
+ };
16
+
17
+ const SHEET_VIEW_REALTIME_REGISTRATIONS = new Map<string, Set<SheetViewRealtimeRegistration>>();
18
+
19
+ /*
20
+ * Return whether one packet id is usable: a non-empty string, a finite number
21
+ * or a bigint.
22
+ */
23
+ function isSheetViewRealtimeId(value: unknown) {
24
+ return (
25
+ (typeof value === 'string' && value !== '') || (typeof value === 'number' && Number.isFinite(value)) || typeof value === 'bigint'
26
+ );
27
+ }
28
+
29
+ /*
30
+ * Return whether one websocket payload looks like a SheetView packet: an
31
+ * object carrying both its sheetId and its sheetTabId.
32
+ */
33
+ function isSheetViewRealtimePacket(packet: unknown): packet is SheetViewGQL {
34
+ if (!packet || typeof packet !== 'object' || Array.isArray(packet)) {
35
+ return false;
36
+ }
37
+
38
+ const { sheetId, sheetTabId } = packet as Record<string, unknown>;
39
+ return isSheetViewRealtimeId(sheetId) && isSheetViewRealtimeId(sheetTabId);
40
+ }
41
+
42
+ /*
43
+ * Register a listener for one sheet's packets. Several listeners may coexist,
44
+ * for the same sheet or others; returns the (idempotent) unregister function.
45
+ */
46
+ export function registerSheetViewRealtimeListener(sheetId: string, listener: SheetViewRealtimeListener): () => void {
47
+ const key = String(sheetId);
48
+ const registration: SheetViewRealtimeRegistration = { listener };
49
+ let registrations = SHEET_VIEW_REALTIME_REGISTRATIONS.get(key);
50
+ if (!registrations) {
51
+ registrations = new Set();
52
+ SHEET_VIEW_REALTIME_REGISTRATIONS.set(key, registrations);
53
+ }
54
+ registrations.add(registration);
55
+
56
+ return () => {
57
+ const current = SHEET_VIEW_REALTIME_REGISTRATIONS.get(key);
58
+ if (!current?.delete(registration)) {
59
+ return;
60
+ }
61
+ if (!current.size) {
62
+ SHEET_VIEW_REALTIME_REGISTRATIONS.delete(key);
63
+ }
64
+ };
65
+ }
66
+
67
+ /*
68
+ * Dispatch one websocket `$sheetViewFragment` payload to the listeners of
69
+ * String(packet.sheetId). Returns true when the payload looks like a
70
+ * SheetView (it is then consumed even when nobody listens) and false
71
+ * otherwise. A throwing listener is logged and never reaches the socket
72
+ * handler or the other listeners.
73
+ */
74
+ export function routeSheetViewRealtimePacket(packet: unknown): boolean {
75
+ if (!isSheetViewRealtimePacket(packet)) {
76
+ return false;
77
+ }
78
+
79
+ const sheetId = String(packet.sheetId);
80
+ const registrations = SHEET_VIEW_REALTIME_REGISTRATIONS.get(sheetId);
81
+ if (!registrations) {
82
+ return true;
83
+ }
84
+
85
+ // Registrations added during this dispatch wait for the next packet, and
86
+ // ones removed by an earlier listener are skipped.
87
+ for (const registration of [...registrations]) {
88
+ if (!registrations.has(registration)) {
89
+ continue;
90
+ }
91
+ try {
92
+ registration.listener(packet);
93
+ } catch (error) {
94
+ console.error(`Sheet realtime listener failed for sheet ${sheetId}; the packet was not applied by it.`, error);
95
+ }
96
+ }
97
+
98
+ return true;
99
+ }
@@ -0,0 +1,186 @@
1
+ import { registerENV } from '@jsb188/app';
2
+ import { fetchPublicCampaignSession } from './campaign.ts';
3
+
4
+ registerENV({
5
+ GQL_API_KEY: 'test-key',
6
+ GQL_SERVER: 'https://api.example.test/graphql',
7
+ });
8
+
9
+ function expectEqual(actual: unknown, expected: unknown, message: string) {
10
+ if (actual !== expected) {
11
+ throw new Error(
12
+ `${message}\nExpected: ${String(expected)}\nReceived: ${String(actual)}`,
13
+ );
14
+ }
15
+ }
16
+
17
+ function makeReadyResponse() {
18
+ return new Response(
19
+ JSON.stringify({
20
+ data: {
21
+ state: 'READY',
22
+ campaign: {
23
+ publicId: 'form/id',
24
+ publicationVersion: 1,
25
+ audience: 'ANYONE',
26
+ backgroundFillStyle: 'MEDIUM',
27
+ sections: [],
28
+ },
29
+ organizations: [],
30
+ organization: null,
31
+ response: null,
32
+ },
33
+ }),
34
+ {
35
+ status: 200,
36
+ headers: { 'content-type': 'application/json' },
37
+ },
38
+ );
39
+ }
40
+
41
+ Deno.test('public campaign session loader uses one encoded atomic route', async () => {
42
+ const originalFetch = globalThis.fetch;
43
+ let requestURL = '';
44
+ let requestHeaders: Headers | null = null;
45
+ let requestCache: RequestCache | null = null;
46
+
47
+ globalThis.fetch = (input, init) => {
48
+ requestURL = String(input);
49
+ requestHeaders = new Headers(init?.headers);
50
+ requestCache = init?.cache || null;
51
+ return Promise.resolve(makeReadyResponse());
52
+ };
53
+
54
+ try {
55
+ const session = await fetchPublicCampaignSession('form/id', {
56
+ authToken: 'account-token',
57
+ childOrgId: 'org/id',
58
+ });
59
+ const persistedHeaders = requestHeaders as Headers | null;
60
+ expectEqual(
61
+ session?.state,
62
+ 'READY',
63
+ 'The loader must return the atomic session payload.',
64
+ );
65
+ expectEqual(
66
+ requestURL,
67
+ 'https://api.example.test/api/campaigns/form%2Fid/session/org%2Fid',
68
+ 'Both public and organization ids must be encoded as path segments.',
69
+ );
70
+ expectEqual(
71
+ persistedHeaders?.get('authorization'),
72
+ 'account-token',
73
+ 'The account credential must be forwarded.',
74
+ );
75
+ expectEqual(
76
+ persistedHeaders?.get('x-api-key'),
77
+ 'test-key',
78
+ 'The application API key must be forwarded.',
79
+ );
80
+ expectEqual(
81
+ requestCache,
82
+ 'no-store',
83
+ 'Public campaign sessions must bypass stale browser response caches.',
84
+ );
85
+ } finally {
86
+ globalThis.fetch = originalFetch;
87
+ }
88
+ });
89
+
90
+ Deno.test('public campaign session loader retries only optional account bootstrap', async () => {
91
+ const originalFetch = globalThis.fetch;
92
+ let calls = 0;
93
+ const authorizations: Array<string | null> = [];
94
+
95
+ globalThis.fetch = (_input, init) => {
96
+ calls += 1;
97
+ authorizations.push(new Headers(init?.headers).get('authorization'));
98
+ return Promise.resolve(
99
+ calls === 1 ? new Response(null, { status: 403 }) : makeReadyResponse(),
100
+ );
101
+ };
102
+
103
+ try {
104
+ await fetchPublicCampaignSession('form', { authToken: 'expired' });
105
+ expectEqual(
106
+ calls,
107
+ 2,
108
+ 'An expired optional account bootstrap must retry once as a guest.',
109
+ );
110
+ expectEqual(
111
+ authorizations[0],
112
+ 'expired',
113
+ 'The first bootstrap uses the optional account token.',
114
+ );
115
+ expectEqual(
116
+ authorizations[1],
117
+ null,
118
+ 'The fallback bootstrap must not forward the expired token.',
119
+ );
120
+
121
+ calls = 0;
122
+ let selectionStatus = 0;
123
+ try {
124
+ await fetchPublicCampaignSession('form', {
125
+ authToken: 'expired',
126
+ childOrgId: 'selected-org',
127
+ });
128
+ } catch (error) {
129
+ selectionStatus = error instanceof Response ? error.status : 0;
130
+ }
131
+ expectEqual(
132
+ selectionStatus,
133
+ 403,
134
+ 'An explicit organization failure must preserve its authorization status.',
135
+ );
136
+ expectEqual(
137
+ calls,
138
+ 1,
139
+ 'An explicit organization selection must never retry as an unrelated guest.',
140
+ );
141
+
142
+ calls = 0;
143
+ let requiredAccountStatus = 0;
144
+ try {
145
+ await fetchPublicCampaignSession('form', {
146
+ authToken: 'expired',
147
+ requireAccount: true,
148
+ });
149
+ } catch (error) {
150
+ requiredAccountStatus = error instanceof Response ? error.status : 0;
151
+ }
152
+ expectEqual(
153
+ requiredAccountStatus,
154
+ 403,
155
+ 'An account-required refresh must preserve its authorization failure.',
156
+ );
157
+ expectEqual(
158
+ calls,
159
+ 1,
160
+ 'An account-required refresh must not replace account state with guest data.',
161
+ );
162
+ } finally {
163
+ globalThis.fetch = originalFetch;
164
+ }
165
+ });
166
+
167
+ Deno.test('public campaign session loader preserves respondent-token failures', async () => {
168
+ const originalFetch = globalThis.fetch;
169
+ globalThis.fetch = () => Promise.resolve(new Response(null, { status: 403 }));
170
+
171
+ try {
172
+ let status = 0;
173
+ try {
174
+ await fetchPublicCampaignSession('form', { respondentToken: 'expired' });
175
+ } catch (error) {
176
+ status = error instanceof Response ? error.status : 0;
177
+ }
178
+ expectEqual(
179
+ status,
180
+ 403,
181
+ 'The browser must be able to recognize and clear an invalid respondent token.',
182
+ );
183
+ } finally {
184
+ globalThis.fetch = originalFetch;
185
+ }
186
+ });
@@ -1,137 +1,110 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
- import type {
3
- CampaignAnswersObj,
4
- PublicCampaignObj,
5
- } from '@jsb188/mday/types/campaign.d.ts';
2
+ import type { PublicCampaignSessionObj } from '@jsb188/mday/types/campaign.d.ts';
3
+ import { getRESTServer } from './rest.ts';
6
4
 
7
5
  /*
8
- * The public campaign surface is REST rather than GraphQL: it is loaded by a
9
- * server loader for an anonymous visitor, so there is no viewer session to
10
- * carry a GraphQL context.
6
+ * Read one campaign REST payload and preserve authorization status when the
7
+ * caller needs to distinguish an expired browser-held credential.
11
8
  */
12
-
13
- function getRESTServer() {
14
- return String(getENVVariable('GQL_SERVER') || '').replace(
15
- /\/graphql\/?$/,
16
- '',
17
- );
18
- }
19
-
20
- /*
21
- * Read one campaign's REST payload, mapping transport failures onto the two
22
- * outcomes a route error boundary can act on: 404 (no such campaign) and 500
23
- * (anything else). A missing REST server or publicId returns null instead,
24
- * because that is a configuration edge case with nothing to render.
25
- */
26
-
27
9
  async function fetchCampaignREST<T>(
28
10
  path: string,
29
11
  headers?: Record<string, string>,
12
+ preserveErrorStatus = false,
30
13
  ): Promise<T | null> {
31
14
  const restServer = getRESTServer();
32
-
33
15
  if (!restServer) {
34
16
  return null;
35
17
  }
36
18
 
37
19
  let response: Response;
38
-
39
20
  try {
40
21
  response = await fetch(`${restServer}${path}`, {
41
22
  method: 'GET',
23
+ cache: 'no-store',
42
24
  headers: {
43
25
  'x-api-key': String(getENVVariable('GQL_API_KEY') || ''),
44
26
  ...(headers || {}),
45
27
  },
46
28
  });
47
29
  } catch {
48
- // Network-level failure (server unreachable etc.) is an internal error
49
30
  throw new Response(null, { status: 500 });
50
31
  }
51
32
 
52
33
  if (response.status === 404) {
53
34
  throw new Response(null, { status: 404 });
54
35
  }
55
-
56
36
  if (!response.ok) {
57
- throw new Response(null, { status: 500 });
37
+ throw new Response(null, {
38
+ status: preserveErrorStatus ? response.status : 500,
39
+ });
58
40
  }
59
41
 
60
42
  try {
61
43
  const json = await response.json();
62
44
  return (json?.data as T) ?? null;
63
- } catch (err) {
64
- if (err instanceof Response) {
65
- throw err;
66
- }
45
+ } catch {
67
46
  throw new Response(null, { status: 500 });
68
47
  }
69
48
  }
70
49
 
71
- /**
72
- * Fetch the sanitized public campaign definition for server rendering.
73
- *
74
- * A closed campaign still resolves, with metadata and `sections: null` - the
75
- * page renders a closed notice rather than a 404, because the link is valid
76
- * and the respondent should be told why they cannot answer.
77
- */
78
-
79
- export async function fetchPublicCampaign(
80
- publicId: string,
81
- ): Promise<PublicCampaignObj | null> {
82
- if (!publicId) {
83
- return null;
84
- }
85
-
86
- const campaign = await fetchCampaignREST<PublicCampaignObj>(
87
- `/api/campaigns/${encodeURIComponent(publicId)}`,
88
- );
89
-
90
- // A 200 with no payload means the campaign could not be resolved
91
- if (!campaign) {
92
- throw new Response(null, { status: 404 });
93
- }
94
-
95
- return campaign;
96
- }
97
-
98
- export interface CampaignRespondentContextData {
99
- respondentName?: string | null;
50
+ export interface FetchPublicCampaignSessionOptions {
51
+ authToken?: string | null;
100
52
  childOrgId?: string | null;
101
- responseId?: string | null;
102
- status?: 'DRAFT' | 'SUBMITTED' | null;
103
- answers?: CampaignAnswersObj;
104
- submittedAt?: string | null;
53
+ requireAccount?: boolean;
54
+ respondentToken?: string | null;
105
55
  }
106
56
 
107
57
  /**
108
- * Fetch one respondent's saved answers so a partly filled form reopens where
109
- * they left it.
58
+ * Fetch one atomic public-form session: campaign, access state, organization
59
+ * choice, and the matching saved response all come from one database snapshot.
110
60
  *
111
- * Only an account-authenticated viewer can be resolved server-side; a
112
- * token-authenticated respondent is client-only, so a failure here degrades to
113
- * null rather than failing the page.
61
+ * An invalid optional account session retries as a guest so an expired cookie
62
+ * cannot block an ANYONE form. Account-required refreshes and respondent-token
63
+ * failures preserve authorization status for their owning UI flows.
114
64
  */
115
-
116
- export async function fetchCampaignRespondentContext(
65
+ export async function fetchPublicCampaignSession(
117
66
  publicId: string,
118
- options: { authToken?: string | null; childOrgId?: string | null },
119
- ): Promise<CampaignRespondentContextData | null> {
120
- if (!publicId || !options.authToken) {
67
+ options: FetchPublicCampaignSessionOptions = {},
68
+ ): Promise<PublicCampaignSessionObj | null> {
69
+ if (!publicId) {
121
70
  return null;
122
71
  }
123
72
 
124
- const query = options.childOrgId
125
- ? `?childOrgId=${encodeURIComponent(options.childOrgId)}`
73
+ const organizationPath = options.childOrgId
74
+ ? `/${encodeURIComponent(options.childOrgId)}`
126
75
  : '';
127
-
76
+ const path = `/api/campaigns/${encodeURIComponent(publicId)}/session${organizationPath}`;
77
+ const headers = {
78
+ ...(options.authToken ? { authorization: options.authToken } : {}),
79
+ ...(options.respondentToken
80
+ ? { 'x-campaign-respondent': options.respondentToken }
81
+ : {}),
82
+ };
83
+
84
+ let session: PublicCampaignSessionObj | null;
128
85
  try {
129
- return await fetchCampaignREST<CampaignRespondentContextData>(
130
- `/api/campaigns/${encodeURIComponent(publicId)}/respondent${query}`,
131
- { authorization: options.authToken },
86
+ session = await fetchCampaignREST<PublicCampaignSessionObj>(
87
+ path,
88
+ headers,
89
+ !!options.authToken || !!options.respondentToken,
132
90
  );
133
- } catch {
134
- // The definition already loaded; a missing fill context is not fatal
135
- return null;
91
+ } catch (error) {
92
+ const canRetryAsGuest =
93
+ !!options.authToken &&
94
+ !options.requireAccount &&
95
+ !options.respondentToken &&
96
+ !options.childOrgId &&
97
+ error instanceof Response &&
98
+ (error.status === 401 || error.status === 403);
99
+ if (!canRetryAsGuest) {
100
+ throw error;
101
+ }
102
+
103
+ session = await fetchCampaignREST<PublicCampaignSessionObj>(path);
104
+ }
105
+
106
+ if (!session) {
107
+ throw new Response(null, { status: 404 });
136
108
  }
109
+ return session;
137
110
  }
@@ -0,0 +1,75 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import { getRESTServer } from './rest.ts';
3
+
4
+ export interface CampaignEmailPreferenceObj {
5
+ email: string;
6
+ organizationName: string;
7
+ unsubscribed: boolean;
8
+ }
9
+
10
+ export type CampaignEmailPreferenceAction = 'UNSUBSCRIBE' | 'RESUBSCRIBE';
11
+
12
+ /*
13
+ * Call the public email-preference REST API for one unsubscribe capability.
14
+ * The token alone names the mailbox and organization, so no account session
15
+ * is ever forwarded. A missing or invalid token surfaces as a 404 Response.
16
+ */
17
+ async function requestCampaignEmailPreference(
18
+ token: string,
19
+ body?: { action: CampaignEmailPreferenceAction },
20
+ ): Promise<CampaignEmailPreferenceObj> {
21
+ const restServer = getRESTServer();
22
+ if (!restServer || !token) {
23
+ throw new Response(null, { status: restServer ? 404 : 500 });
24
+ }
25
+
26
+ let response: Response;
27
+ try {
28
+ response = await fetch(
29
+ `${restServer}/api/email-preferences/${encodeURIComponent(token)}`,
30
+ {
31
+ method: body ? 'POST' : 'GET',
32
+ cache: 'no-store',
33
+ headers: {
34
+ 'x-api-key': String(getENVVariable('GQL_API_KEY') || ''),
35
+ ...(body ? { 'content-type': 'application/json' } : {}),
36
+ },
37
+ body: body ? JSON.stringify(body) : undefined,
38
+ },
39
+ );
40
+ } catch {
41
+ throw new Response(null, { status: 500 });
42
+ }
43
+
44
+ if (!response.ok) {
45
+ throw new Response(null, {
46
+ status: response.status === 404 ? 404 : 500,
47
+ });
48
+ }
49
+
50
+ const json = await response.json().catch(() => null);
51
+ if (!json?.data) {
52
+ throw new Response(null, { status: 500 });
53
+ }
54
+
55
+ return json.data as CampaignEmailPreferenceObj;
56
+ }
57
+
58
+ /**
59
+ * Read which mailbox and organization one unsubscribe link controls, and
60
+ * whether that mailbox is currently unsubscribed. Never changes state.
61
+ */
62
+ export function fetchCampaignEmailPreference(token: string) {
63
+ return requestCampaignEmailPreference(token);
64
+ }
65
+
66
+ /**
67
+ * Unsubscribe or resubscribe the mailbox named by one unsubscribe link and
68
+ * return its fresh state.
69
+ */
70
+ export function updateCampaignEmailPreference(
71
+ token: string,
72
+ action: CampaignEmailPreferenceAction,
73
+ ) {
74
+ return requestCampaignEmailPreference(token, { action });
75
+ }
@@ -0,0 +1,12 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+
3
+ /*
4
+ * Return the REST server origin. Public route loaders use REST because React
5
+ * Router loads them for anonymous visitors outside the GraphQL client.
6
+ */
7
+ export function getRESTServer() {
8
+ return String(getENVVariable('GQL_SERVER') || '').replace(
9
+ /\/graphql\/?$/,
10
+ '',
11
+ );
12
+ }