@jsb188/graphql 1.1.10 → 1.1.11

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 (116) hide show
  1. package/cache/config.ts +64 -50
  2. package/cache/index.test.ts +671 -109
  3. package/cache/index.ts +1700 -1240
  4. package/cache/persist.ts +721 -0
  5. package/cache/store.ts +437 -0
  6. package/client/data-table-realtime-subscriptions.test.ts +740 -0
  7. package/client/data-table-realtime-subscriptions.ts +955 -0
  8. package/client/data-table-realtime.test.ts +792 -0
  9. package/client/data-table-realtime.ts +1218 -0
  10. package/client/fragment-realtime-sequence.ts +52 -0
  11. package/client/index.ts +2 -0
  12. package/client/open-sheet.ts +137 -0
  13. package/client/request-managed-session.test.ts +574 -0
  14. package/client/request-no-store.test.ts +157 -0
  15. package/client/request.ts +954 -163
  16. package/client/sse-ticket.test.ts +26 -0
  17. package/deno.lock +170 -0
  18. package/deno.test.json +8 -4
  19. package/drafts/index.ts +149 -0
  20. package/drafts/store.ts +397 -0
  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/agentDocFragments.ts +46 -0
  26. package/gql/fragments/agentMemoryFragments.ts +19 -0
  27. package/gql/fragments/aiChatFragments.ts +16 -0
  28. package/gql/fragments/billingFragments.ts +0 -11
  29. package/gql/fragments/campaignFragments.ts +277 -0
  30. package/gql/fragments/dataTableFragments.ts +18 -128
  31. package/gql/fragments/emailFragments.ts +19 -9
  32. package/gql/fragments/fieldDocFragments.ts +82 -0
  33. package/gql/fragments/logFragments.ts +20 -79
  34. package/gql/fragments/organizationFragments.ts +43 -5
  35. package/gql/fragments/scheduleFragments.ts +155 -0
  36. package/gql/fragments/sheetFragments.ts +552 -22
  37. package/gql/fragments/storageFragments.ts +21 -0
  38. package/gql/fragments/workflowFragments.ts +28 -4
  39. package/gql/mutations/accountMutations.ts +0 -2
  40. package/gql/mutations/agentDocMutations.ts +177 -0
  41. package/gql/mutations/agentMemoryMutations.ts +36 -0
  42. package/gql/mutations/aiChatMutations.ts +17 -4
  43. package/gql/mutations/authMutations.ts +158 -17
  44. package/gql/mutations/campaignMutations.ts +215 -0
  45. package/gql/mutations/dataTableMutations.ts +48 -26
  46. package/gql/mutations/fieldDocMutations.ts +24 -0
  47. package/gql/mutations/index.ts +6 -1
  48. package/gql/mutations/logMutations.ts +6 -29
  49. package/gql/mutations/organizationMutations.ts +13 -4
  50. package/gql/mutations/scheduleMutations.ts +423 -0
  51. package/gql/mutations/sheetMutations.ts +273 -56
  52. package/gql/mutations/storageMutations.ts +20 -0
  53. package/gql/mutations/workflowMutations.ts +42 -0
  54. package/gql/queries/agentDocQueries.ts +120 -0
  55. package/gql/queries/agentMemoryQueries.ts +22 -0
  56. package/gql/queries/aiChatQueries.ts +18 -2
  57. package/gql/queries/authQueries.ts +41 -0
  58. package/gql/queries/billingQueries.ts +23 -0
  59. package/gql/queries/campaignQueries.ts +127 -0
  60. package/gql/queries/dataTableQueries.ts +100 -11
  61. package/gql/queries/emailQueries.ts +55 -3
  62. package/gql/queries/fieldDocQueries.ts +158 -0
  63. package/gql/queries/index.ts +8 -2
  64. package/gql/queries/logQueries.ts +11 -28
  65. package/gql/queries/organizationQueries.ts +52 -1
  66. package/gql/queries/scheduleQueries.ts +315 -0
  67. package/gql/queries/sheetQueries.ts +336 -25
  68. package/gql/queries/storageQueries.ts +38 -0
  69. package/gql/queries/workflowQueries.ts +72 -3
  70. package/hooks/index.ts +2065 -971
  71. package/hooks/use-account-mtn.ts +76 -81
  72. package/hooks/use-agentDoc-mtn.ts +285 -0
  73. package/hooks/use-agentDoc-qry.ts +208 -0
  74. package/hooks/use-agentMemory-mtn.ts +73 -0
  75. package/hooks/use-agentMemory-qry.ts +44 -0
  76. package/hooks/use-aiChat-mtn.ts +232 -137
  77. package/hooks/use-aiChat-qry.ts +480 -222
  78. package/hooks/use-app-qry.ts +12 -9
  79. package/hooks/use-auth-mtn.ts +406 -252
  80. package/hooks/use-auth-qry.ts +51 -0
  81. package/hooks/use-campaign-mtn.ts +377 -0
  82. package/hooks/use-campaign-qry.ts +257 -0
  83. package/hooks/use-dataTable-mtn.ts +116 -33
  84. package/hooks/use-dataTable-qry.ts +859 -35
  85. package/hooks/use-email-qry.ts +194 -79
  86. package/hooks/use-fieldDoc-mtn.ts +50 -0
  87. package/hooks/use-fieldDoc-qry.ts +180 -0
  88. package/hooks/use-inboundContact-mtn.ts +19 -16
  89. package/hooks/use-inboundContact-qry.ts +63 -55
  90. package/hooks/use-integration-mtn.ts +56 -38
  91. package/hooks/use-integration-qry.ts +24 -9
  92. package/hooks/use-log-mtn.ts +72 -56
  93. package/hooks/use-log-qry.ts +93 -69
  94. package/hooks/use-organization-mtn.ts +334 -277
  95. package/hooks/use-organization-qry.ts +199 -129
  96. package/hooks/use-schedule-mtn.ts +416 -0
  97. package/hooks/use-schedule-qry.ts +157 -0
  98. package/hooks/use-sheet-mtn.ts +233 -47
  99. package/hooks/use-sheet-qry.ts +353 -70
  100. package/hooks/use-storage-mtn.ts +81 -41
  101. package/hooks/use-storage-qry.ts +104 -13
  102. package/hooks/use-workflow-mtn.ts +55 -0
  103. package/hooks/use-workflow-qry.ts +206 -48
  104. package/loaders/campaign.ts +137 -0
  105. package/package.json +94 -71
  106. package/sse.ts +157 -104
  107. package/tsconfig.json +11 -10
  108. package/types.d.ts +60 -30
  109. package/utils.ts +78 -49
  110. package/gql/fragments/productFragments.ts +0 -39
  111. package/gql/fragments/reportFragments.ts +0 -90
  112. package/gql/mutations/billingMutations.ts +0 -34
  113. package/gql/queries/productQueries.ts +0 -31
  114. package/gql/queries/reportQueries.ts +0 -134
  115. package/hooks/use-product-qry.ts +0 -67
  116. package/hooks/use-report-qry.ts +0 -153
@@ -1,21 +1,112 @@
1
- import { useReactiveFragment } from '../client/index.ts';
1
+ import type { GeneratedFileGQL } from '@jsb188/mday/types/storage.d.ts';
2
+ import {
3
+ FRAGMENT_NAMES,
4
+ makeFragmentKey,
5
+ } from '@jsb188/mday/constants/graphqlReactivity.ts';
6
+ import {
7
+ generatedFileQry,
8
+ generatedFilesQry,
9
+ } from '../gql/queries/storageQueries.ts';
10
+ import { useQuery, useReactiveFragment } from '../client/index.ts';
11
+ import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
12
+
13
+ /**
14
+ * Constants
15
+ */
16
+
17
+ const GENERATED_FILES_LIST_LIMIT = 100;
2
18
 
3
19
  /**
4
20
  * Get reactive log fragment
5
21
  */
6
22
 
7
- export function useReactiveStorageFragment(storageId: string, currentData?: any, queryCount?: number) {
8
- return useReactiveFragment(
9
- currentData,
10
- [
11
- `$storageFileFragment:${storageId}`,
23
+ export function useReactiveStorageFragment(
24
+ storageId: string,
25
+ currentData?: any,
26
+ queryCount?: number,
27
+ ) {
28
+ return useReactiveFragment(
29
+ currentData,
30
+ [makeFragmentKey(FRAGMENT_NAMES.storageFile, storageId)],
31
+ queryCount,
32
+ );
33
+ }
34
+
35
+ /**
36
+ * Get reactive generated file fragment (AI CSV exports).
37
+ */
38
+
39
+ export function useReactiveGeneratedFileFragment(
40
+ code: string,
41
+ currentData?: any,
42
+ queryCount?: number,
43
+ ) {
44
+ return useReactiveFragment(
45
+ currentData,
46
+ [makeFragmentKey(FRAGMENT_NAMES.generatedFile, code)],
47
+ queryCount,
48
+ );
49
+ }
50
+
51
+ /**
52
+ * Fetch generated files (AI CSV exports) for one organization.
53
+ */
54
+
55
+ export function useGeneratedFiles(
56
+ variables: PaginationArgs & {
57
+ organizationId?: string | null;
58
+ },
59
+ params: UseQueryParams = {},
60
+ ) {
61
+ const { data, ...rest } = useQuery(generatedFilesQry, {
62
+ ...params,
63
+ variables: {
64
+ ...variables,
65
+ cursor: null,
66
+ after: true,
67
+ limit: GENERATED_FILES_LIST_LIMIT,
68
+ },
69
+ skip: !variables.organizationId || params.skip,
70
+ });
71
+
72
+ return {
73
+ generatedFiles: data?.generatedFiles as GeneratedFileGQL[] | undefined,
74
+ ...rest,
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Fetch one generated file; serves reactive cache data first so a deep link
80
+ * that arrives after the list loaded does not refetch.
81
+ */
12
82
 
13
- // By having the second paramter as null, we only observe the reactive changes without setting the data
14
- // [`$logArableFragment:${storageId}`, null],
83
+ export function useGeneratedFile(
84
+ variables: {
85
+ organizationId?: string | null;
86
+ code?: string | null;
87
+ },
88
+ params: UseQueryParams = {},
89
+ ) {
90
+ const cachedGeneratedFile = useReactiveGeneratedFileFragment(
91
+ variables.code || '',
92
+ null,
93
+ );
94
+ const shouldFetchGeneratedFile =
95
+ !!variables.organizationId &&
96
+ !!variables.code &&
97
+ !cachedGeneratedFile &&
98
+ !params.skip;
99
+ const { data, ...rest } = useQuery(generatedFileQry, {
100
+ ...params,
101
+ variables,
102
+ skip: !shouldFetchGeneratedFile,
103
+ });
15
104
 
16
- // This is not needed because $logEntryFragment has spread data
17
- // [`$accountFragment:${storageId}`, 'account']
18
- ],
19
- queryCount,
20
- );
105
+ return {
106
+ generatedFile: (cachedGeneratedFile || data?.generatedFile) as
107
+ | GeneratedFileGQL
108
+ | undefined,
109
+ initialLoading: shouldFetchGeneratedFile && !data,
110
+ ...rest,
111
+ };
21
112
  }
@@ -0,0 +1,55 @@
1
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
+ import { OpenModalPopUpFn } from '@jsb188/react/states';
3
+ import {
4
+ cancelReminderMtn,
5
+ updateReminderMtn,
6
+ } from '../gql/mutations/workflowMutations.ts';
7
+ import { useMutation } from './index.ts';
8
+
9
+ /**
10
+ * Cancel one reminder (deactivates it and stops open runs);
11
+ * cache updates arrive via the server's realtime fragment emit
12
+ */
13
+
14
+ export function useCancelReminder(
15
+ params: UseMutationParams = {},
16
+ openModalPopUp?: OpenModalPopUpFn,
17
+ ) {
18
+ const [cancelReminder, mtnValues, mtnHandlers] = useMutation(
19
+ cancelReminderMtn,
20
+ {
21
+ openModalPopUp,
22
+ ...params,
23
+ },
24
+ );
25
+
26
+ return {
27
+ cancelReminder,
28
+ ...mtnValues,
29
+ ...mtnHandlers,
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Update one reminder's title/schedule;
35
+ * cache updates arrive via the server's realtime fragment emit
36
+ */
37
+
38
+ export function useUpdateReminder(
39
+ params: UseMutationParams = {},
40
+ openModalPopUp?: OpenModalPopUpFn,
41
+ ) {
42
+ const [updateReminder, mtnValues, mtnHandlers] = useMutation(
43
+ updateReminderMtn,
44
+ {
45
+ openModalPopUp,
46
+ ...params,
47
+ },
48
+ );
49
+
50
+ return {
51
+ updateReminder,
52
+ ...mtnValues,
53
+ ...mtnHandlers,
54
+ };
55
+ }
@@ -1,72 +1,230 @@
1
- import { useQuery, useReactiveFragment } from '@jsb188/graphql/client';
2
- import { workflowRunsQry, workflowsQry } from '../gql/queries/workflowQueries.ts';
1
+ import {
2
+ useQuery,
3
+ useReactiveFragment,
4
+ useReactiveFragmentMap,
5
+ } from '@jsb188/graphql/client';
6
+ import type {
7
+ WorkflowRunsFilterGQL,
8
+ WorkflowsFilterGQL,
9
+ } from '@jsb188/mday/types/workflow.d.ts';
10
+ import {
11
+ FRAGMENT_NAMES,
12
+ getFragmentBaseName,
13
+ makeFragmentKey,
14
+ } from '@jsb188/mday/constants/graphqlReactivity.ts';
15
+ import { useCallback } from 'react';
16
+ import {
17
+ workflowRunQry,
18
+ workflowRunsQry,
19
+ workflowsQry,
20
+ } from '../gql/queries/workflowQueries.ts';
3
21
  import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
4
22
 
5
23
  /**
6
24
  * Constants
7
25
  */
8
26
 
9
- const WORKFLOWS_LIST_LIMIT = 250;
27
+ const WORKFLOW_LISTS_LIMIT = 60;
10
28
 
11
29
  /**
12
- * Fetch workflows for an organization
30
+ * Keep workflow list filters aligned with the WorkflowsFilter input shape
31
+ * (route table filters carry extra URL-only keys)
32
+ */
33
+
34
+ function normalizeWorkflowsFilter(
35
+ filter?: Record<string, any> | null,
36
+ ): WorkflowsFilterGQL {
37
+ return {
38
+ kind: filter?.kind || null,
39
+ startDate: filter?.startDate || null,
40
+ endDate: filter?.endDate || null,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Keep run list filters aligned with the WorkflowRunsFilter input shape
46
+ */
47
+
48
+ function normalizeWorkflowRunsFilter(
49
+ filter?: Record<string, any> | null,
50
+ ): WorkflowRunsFilterGQL {
51
+ return {
52
+ workflowId: filter?.workflowId || null,
53
+ kind: filter?.kind || null,
54
+ statuses: filter?.statuses || null,
55
+ startDate: filter?.startDate || null,
56
+ endDate: filter?.endDate || null,
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Wrap a query's fetchMore so pagination calls re-normalize route filters;
62
+ * the route table rebuilds fetchMore variables from the raw route filter state
63
+ */
64
+
65
+ function useNormalizedFilterFetchMore(
66
+ fetchMore: (options: any) => Promise<any>,
67
+ normalizeFilter: (filter?: Record<string, any> | null) => Record<string, any>,
68
+ ) {
69
+ return useCallback(
70
+ (options: any) => {
71
+ if (!options?.variables?.filter) {
72
+ return fetchMore(options);
73
+ }
74
+
75
+ return fetchMore({
76
+ ...options,
77
+ variables: {
78
+ ...options.variables,
79
+ filter: normalizeFilter(options.variables.filter),
80
+ },
81
+ });
82
+ },
83
+ [fetchMore, normalizeFilter],
84
+ );
85
+ }
86
+
87
+ /**
88
+ * Fetch the merged paginated workflows list (workflows + reminders) for an organization
13
89
  */
14
90
 
15
91
  export function useWorkflows(
16
- variablesOrOrganizationId?: string | null | (PaginationArgs & {
17
- organizationId?: string | null;
18
- }),
19
- params: UseQueryParams = {},
92
+ variables: PaginationArgs & {
93
+ organizationId?: string | null;
94
+ filter?: WorkflowsFilterGQL | Record<string, any> | null;
95
+ sort?: string | null;
96
+ },
97
+ params: UseQueryParams = {},
98
+ ) {
99
+ const { data, fetchMore, ...rest } = useQuery(workflowsQry, {
100
+ ...params,
101
+ variables: {
102
+ ...variables,
103
+ filter: normalizeWorkflowsFilter(variables.filter),
104
+ cursor: null,
105
+ after: true,
106
+ limit: variables.limit ?? WORKFLOW_LISTS_LIMIT,
107
+ },
108
+ skip: !variables.organizationId || params.skip,
109
+ });
110
+
111
+ const fetchMoreWorkflows = useNormalizedFilterFetchMore(
112
+ fetchMore,
113
+ normalizeWorkflowsFilter,
114
+ );
115
+
116
+ return {
117
+ workflows: data?.workflows,
118
+ fetchMore: fetchMoreWorkflows,
119
+ ...rest,
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Fetch the paginated runs list for an organization,
125
+ * optionally scoped to one workflow via filter.workflowId
126
+ */
127
+
128
+ export function useWorkflowRuns(
129
+ variables: PaginationArgs & {
130
+ organizationId?: string | null;
131
+ filter?: WorkflowRunsFilterGQL | Record<string, any> | null;
132
+ sort?: string | null;
133
+ },
134
+ params: UseQueryParams = {},
20
135
  ) {
21
- const usesPaginationVariables = typeof variablesOrOrganizationId === 'object' && variablesOrOrganizationId !== null;
22
- const variables = usesPaginationVariables
23
- ? variablesOrOrganizationId
24
- : { organizationId: variablesOrOrganizationId };
25
-
26
- const { data, ...rest } = useQuery(workflowsQry, {
27
- variables: usesPaginationVariables ? {
28
- ...variables,
29
- cursor: null,
30
- after: true,
31
- limit: WORKFLOWS_LIST_LIMIT,
32
- } : variables,
33
- skip: !variables.organizationId,
34
- ...params,
35
- });
36
-
37
- return {
38
- workflows: data?.workflows,
39
- ...rest
40
- };
136
+ const { data, fetchMore, ...rest } = useQuery(workflowRunsQry, {
137
+ ...params,
138
+ variables: {
139
+ ...variables,
140
+ filter: normalizeWorkflowRunsFilter(variables.filter),
141
+ cursor: null,
142
+ after: true,
143
+ limit: variables.limit ?? WORKFLOW_LISTS_LIMIT,
144
+ },
145
+ skip: !variables.organizationId || params.skip,
146
+ });
147
+
148
+ const fetchMoreWorkflowRuns = useNormalizedFilterFetchMore(
149
+ fetchMore,
150
+ normalizeWorkflowRunsFilter,
151
+ );
152
+
153
+ return {
154
+ workflowRuns: data?.workflowRuns,
155
+ fetchMore: fetchMoreWorkflowRuns,
156
+ ...rest,
157
+ };
41
158
  }
42
159
 
43
160
  /**
44
- * Fetch runs for a workflow
161
+ * Fetch one workflow run (for the run detail modal), merged with live fragment updates
45
162
  */
46
163
 
47
- export function useWorkflowRuns(workflowId?: string | null, params: UseQueryParams = {}) {
48
- const { data, ...rest } = useQuery(workflowRunsQry, {
49
- variables: {
50
- workflowId,
51
- },
52
- skip: !workflowId,
53
- ...params,
54
- });
55
-
56
- return {
57
- workflowRuns: data?.workflowRuns,
58
- ...rest
59
- };
164
+ export function useWorkflowRun(
165
+ variables: {
166
+ organizationId?: string | null;
167
+ workflowRunId?: string | null;
168
+ },
169
+ params: UseQueryParams = {},
170
+ ) {
171
+ const { data, ...rest } = useQuery(workflowRunQry, {
172
+ ...params,
173
+ variables,
174
+ skip: !variables.organizationId || !variables.workflowRunId || params.skip,
175
+ });
176
+
177
+ // Always query; the cached list fragment does not carry the nested workflow
178
+ const reactiveWorkflowRun = useReactiveWorkflowRunFragment(
179
+ variables.workflowRunId || '',
180
+ data?.workflowRun ?? null,
181
+ );
182
+
183
+ return {
184
+ workflowRun: reactiveWorkflowRun || data?.workflowRun,
185
+ ...rest,
186
+ };
60
187
  }
61
188
 
62
189
  /**
63
190
  * Get reactive workflow fragment
64
191
  */
65
192
 
66
- export function useReactiveWorkflowFragment(workflowId: string, currentData?: any, queryCount?: number) {
67
- return useReactiveFragment(
68
- currentData,
69
- [`$workflowFragment:${workflowId}`],
70
- queryCount,
71
- );
193
+ export function useReactiveWorkflowFragment(
194
+ workflowId: string,
195
+ currentData?: any,
196
+ queryCount?: number,
197
+ ) {
198
+ return useReactiveFragment(
199
+ currentData,
200
+ [makeFragmentKey(FRAGMENT_NAMES.workflow, workflowId)],
201
+ queryCount,
202
+ );
203
+ }
204
+
205
+ /**
206
+ * Get reactive workflow run fragment for a single run
207
+ */
208
+
209
+ export function useReactiveWorkflowRunFragment(
210
+ workflowRunId: string,
211
+ currentData?: any,
212
+ queryCount?: number,
213
+ ) {
214
+ return useReactiveFragment(
215
+ currentData,
216
+ [makeFragmentKey(FRAGMENT_NAMES.workflowRun, workflowRunId)],
217
+ queryCount,
218
+ );
219
+ }
220
+
221
+ /**
222
+ * Get reactive workflow run fragments for a list of runs (run history)
223
+ */
224
+
225
+ export function useReactiveWorkflowRunFragmentMap(workflowRuns?: any[] | null) {
226
+ return useReactiveFragmentMap(
227
+ workflowRuns || null,
228
+ getFragmentBaseName(FRAGMENT_NAMES.workflowRun),
229
+ );
72
230
  }
@@ -0,0 +1,137 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import type {
3
+ CampaignAnswersObj,
4
+ PublicCampaignObj,
5
+ } from '@jsb188/mday/types/campaign.d.ts';
6
+
7
+ /*
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.
11
+ */
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
+ async function fetchCampaignREST<T>(
28
+ path: string,
29
+ headers?: Record<string, string>,
30
+ ): Promise<T | null> {
31
+ const restServer = getRESTServer();
32
+
33
+ if (!restServer) {
34
+ return null;
35
+ }
36
+
37
+ let response: Response;
38
+
39
+ try {
40
+ response = await fetch(`${restServer}${path}`, {
41
+ method: 'GET',
42
+ headers: {
43
+ 'x-api-key': String(getENVVariable('GQL_API_KEY') || ''),
44
+ ...(headers || {}),
45
+ },
46
+ });
47
+ } catch {
48
+ // Network-level failure (server unreachable etc.) is an internal error
49
+ throw new Response(null, { status: 500 });
50
+ }
51
+
52
+ if (response.status === 404) {
53
+ throw new Response(null, { status: 404 });
54
+ }
55
+
56
+ if (!response.ok) {
57
+ throw new Response(null, { status: 500 });
58
+ }
59
+
60
+ try {
61
+ const json = await response.json();
62
+ return (json?.data as T) ?? null;
63
+ } catch (err) {
64
+ if (err instanceof Response) {
65
+ throw err;
66
+ }
67
+ throw new Response(null, { status: 500 });
68
+ }
69
+ }
70
+
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;
100
+ childOrgId?: string | null;
101
+ responseId?: string | null;
102
+ status?: 'DRAFT' | 'SUBMITTED' | null;
103
+ answers?: CampaignAnswersObj;
104
+ submittedAt?: string | null;
105
+ }
106
+
107
+ /**
108
+ * Fetch one respondent's saved answers so a partly filled form reopens where
109
+ * they left it.
110
+ *
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.
114
+ */
115
+
116
+ export async function fetchCampaignRespondentContext(
117
+ publicId: string,
118
+ options: { authToken?: string | null; childOrgId?: string | null },
119
+ ): Promise<CampaignRespondentContextData | null> {
120
+ if (!publicId || !options.authToken) {
121
+ return null;
122
+ }
123
+
124
+ const query = options.childOrgId
125
+ ? `?childOrgId=${encodeURIComponent(options.childOrgId)}`
126
+ : '';
127
+
128
+ try {
129
+ return await fetchCampaignREST<CampaignRespondentContextData>(
130
+ `/api/campaigns/${encodeURIComponent(publicId)}/respondent${query}`,
131
+ { authorization: options.authToken },
132
+ );
133
+ } catch {
134
+ // The definition already loaded; a missing fill context is not fatal
135
+ return null;
136
+ }
137
+ }