@jsb188/graphql 1.1.10 → 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 (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  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 +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
@@ -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,26 @@
1
+ /*
2
+ * Assert one client-side SSE credential invariant with a useful failure.
3
+ */
4
+ function expect(value: unknown, message: string) {
5
+ if (!value) {
6
+ throw new Error(message);
7
+ }
8
+ }
9
+
10
+ Deno.test('AI chat EventSource URLs contain only the single-use SSE ticket', async () => {
11
+ const runtime = await Deno.readTextFile(
12
+ new URL('../hooks/use-aiChat-qry.ts', import.meta.url),
13
+ );
14
+ expect(
15
+ runtime.includes('session_key: sessionKey'),
16
+ 'AI chat SSE must send its one-time ticket',
17
+ );
18
+ expect(
19
+ !runtime.includes('auth_token'),
20
+ 'AI chat SSE URLs must never contain the reusable access JWT',
21
+ );
22
+ expect(
23
+ !runtime.includes('getAuthToken'),
24
+ 'AI chat SSE must not read a reusable bearer for EventSource query parameters',
25
+ );
26
+ });
@@ -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
+ });
@@ -0,0 +1,110 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import type { PublicCampaignSessionObj } from '@jsb188/mday/types/campaign.d.ts';
3
+ import { getRESTServer } from './rest.ts';
4
+
5
+ /*
6
+ * Read one campaign REST payload and preserve authorization status when the
7
+ * caller needs to distinguish an expired browser-held credential.
8
+ */
9
+ async function fetchCampaignREST<T>(
10
+ path: string,
11
+ headers?: Record<string, string>,
12
+ preserveErrorStatus = false,
13
+ ): Promise<T | null> {
14
+ const restServer = getRESTServer();
15
+ if (!restServer) {
16
+ return null;
17
+ }
18
+
19
+ let response: Response;
20
+ try {
21
+ response = await fetch(`${restServer}${path}`, {
22
+ method: 'GET',
23
+ cache: 'no-store',
24
+ headers: {
25
+ 'x-api-key': String(getENVVariable('GQL_API_KEY') || ''),
26
+ ...(headers || {}),
27
+ },
28
+ });
29
+ } catch {
30
+ throw new Response(null, { status: 500 });
31
+ }
32
+
33
+ if (response.status === 404) {
34
+ throw new Response(null, { status: 404 });
35
+ }
36
+ if (!response.ok) {
37
+ throw new Response(null, {
38
+ status: preserveErrorStatus ? response.status : 500,
39
+ });
40
+ }
41
+
42
+ try {
43
+ const json = await response.json();
44
+ return (json?.data as T) ?? null;
45
+ } catch {
46
+ throw new Response(null, { status: 500 });
47
+ }
48
+ }
49
+
50
+ export interface FetchPublicCampaignSessionOptions {
51
+ authToken?: string | null;
52
+ childOrgId?: string | null;
53
+ requireAccount?: boolean;
54
+ respondentToken?: string | null;
55
+ }
56
+
57
+ /**
58
+ * Fetch one atomic public-form session: campaign, access state, organization
59
+ * choice, and the matching saved response all come from one database snapshot.
60
+ *
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.
64
+ */
65
+ export async function fetchPublicCampaignSession(
66
+ publicId: string,
67
+ options: FetchPublicCampaignSessionOptions = {},
68
+ ): Promise<PublicCampaignSessionObj | null> {
69
+ if (!publicId) {
70
+ return null;
71
+ }
72
+
73
+ const organizationPath = options.childOrgId
74
+ ? `/${encodeURIComponent(options.childOrgId)}`
75
+ : '';
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;
85
+ try {
86
+ session = await fetchCampaignREST<PublicCampaignSessionObj>(
87
+ path,
88
+ headers,
89
+ !!options.authToken || !!options.respondentToken,
90
+ );
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 });
108
+ }
109
+ return session;
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
+ }