@jsb188/mday 1.1.2

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 (202) hide show
  1. package/package.json +142 -0
  2. package/src/constants/agentMemory.ts +166 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +22 -0
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +146 -0
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/inboundContact.ts +8 -0
  17. package/src/constants/integration.ts +13 -0
  18. package/src/constants/log.ts +21 -0
  19. package/src/constants/logDisplay/README.md +88 -0
  20. package/src/constants/logDisplay/defaults.ts +39 -0
  21. package/src/constants/logDisplay/index.ts +27 -0
  22. package/src/constants/logDisplay/operations/arable.ts +16 -0
  23. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  24. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  25. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  26. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  27. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  28. package/src/constants/logTaxonomy.generated.ts +2199 -0
  29. package/src/constants/noteDoc.ts +77 -0
  30. package/src/constants/organization.ts +60 -0
  31. package/src/constants/pageRoute.ts +23 -0
  32. package/src/constants/qrCode.ts +30 -0
  33. package/src/constants/sheet.ts +132 -0
  34. package/src/constants/sms.ts +18 -0
  35. package/src/constants/square.ts +16 -0
  36. package/src/constants/storage.ts +85 -0
  37. package/src/constants/usage.ts +82 -0
  38. package/src/constants/workflowSteps.ts +60 -0
  39. package/src/schemas/editLogEntry.ts +879 -0
  40. package/src/schemas/inboundContact.ts +77 -0
  41. package/src/schemas/logsQuery.ts +93 -0
  42. package/src/types/account.d.ts +81 -0
  43. package/src/types/agentMemory.d.ts +100 -0
  44. package/src/types/agentNote.d.ts +441 -0
  45. package/src/types/billing.d.ts +537 -0
  46. package/src/types/campaign.d.ts +1533 -0
  47. package/src/types/contact.d.ts +15 -0
  48. package/src/types/csvExport.d.ts +213 -0
  49. package/src/types/dataAnalysis.d.ts +44 -0
  50. package/src/types/dataTable.d.ts +159 -0
  51. package/src/types/definitionElement.d.ts +35 -0
  52. package/src/types/docAccess.d.ts +96 -0
  53. package/src/types/dt.d.ts +257 -0
  54. package/src/types/email.d.ts +231 -0
  55. package/src/types/emailReplyReport.d.ts +76 -0
  56. package/src/types/fieldDoc.d.ts +702 -0
  57. package/src/types/fieldDocContract.d.ts +90 -0
  58. package/src/types/inboundContact.d.ts +65 -0
  59. package/src/types/integration.d.ts +42 -0
  60. package/src/types/log.d.ts +338 -0
  61. package/src/types/logDisplay.types.ts +85 -0
  62. package/src/types/organization.d.ts +350 -0
  63. package/src/types/pageRoute.d.ts +48 -0
  64. package/src/types/qrCode.d.ts +96 -0
  65. package/src/types/richText.d.ts +81 -0
  66. package/src/types/sheet.d.ts +847 -0
  67. package/src/types/sms.d.ts +38 -0
  68. package/src/types/storage.d.ts +481 -0
  69. package/src/types/usage.d.ts +106 -0
  70. package/src/types/workflow.d.ts +435 -0
  71. package/src/utils/agentMemory.ts +15 -0
  72. package/src/utils/agentNote.ts +850 -0
  73. package/src/utils/aiChat.ts +43 -0
  74. package/src/utils/aiChatWork.ts +64 -0
  75. package/src/utils/billing.ts +37 -0
  76. package/src/utils/campaign.ts +1173 -0
  77. package/src/utils/campaignAI.ts +72 -0
  78. package/src/utils/campaignAccess.ts +239 -0
  79. package/src/utils/campaignEmail.ts +601 -0
  80. package/src/utils/campaignEmailCompiler.ts +372 -0
  81. package/src/utils/campaignEmailImages.ts +60 -0
  82. package/src/utils/campaignEmailStyles.ts +544 -0
  83. package/src/utils/campaignLifecycle.ts +104 -0
  84. package/src/utils/campaignPreview.ts +285 -0
  85. package/src/utils/contact.ts +50 -0
  86. package/src/utils/csvExport.ts +19 -0
  87. package/src/utils/dataTable.ts +311 -0
  88. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  89. package/src/utils/dataTableRelativeDate.ts +447 -0
  90. package/src/utils/definitionElement.ts +84 -0
  91. package/src/utils/docAccess.ts +383 -0
  92. package/src/utils/documentName.ts +53 -0
  93. package/src/utils/email.ts +379 -0
  94. package/src/utils/emailReplyReport.test.ts +187 -0
  95. package/src/utils/emailReplyReport.ts +143 -0
  96. package/src/utils/fieldDoc.ts +157 -0
  97. package/src/utils/fieldDocAnswers.ts +128 -0
  98. package/src/utils/fieldDocDefaults.ts +36 -0
  99. package/src/utils/fieldDocProgram.ts +36 -0
  100. package/src/utils/fieldDocSummary.ts +30 -0
  101. package/src/utils/log.ts +357 -0
  102. package/src/utils/logDisplay.helpers.ts +177 -0
  103. package/src/utils/logDisplay.ts +87 -0
  104. package/src/utils/logRegistryValue.ts +90 -0
  105. package/src/utils/logStoreRead.ts +262 -0
  106. package/src/utils/logTaxonomy.helpers.ts +17 -0
  107. package/src/utils/logTaxonomy.ts +76 -0
  108. package/src/utils/logTaxonomyDisplay.ts +395 -0
  109. package/src/utils/noteDoc.ts +609 -0
  110. package/src/utils/organization.ts +669 -0
  111. package/src/utils/pageRoute.ts +71 -0
  112. package/src/utils/qrCode.helpers.ts +189 -0
  113. package/src/utils/qrCode.test.ts +519 -0
  114. package/src/utils/qrCode.ts +273 -0
  115. package/src/utils/richTextHTML.ts +385 -0
  116. package/src/utils/sheet.ts +262 -0
  117. package/src/utils/sheetAxisMove.ts +616 -0
  118. package/src/utils/sheetBootstrap.ts +1402 -0
  119. package/src/utils/sheetCellLiteral.ts +101 -0
  120. package/src/utils/sheetCommand.ts +358 -0
  121. package/src/utils/sheetDesign.ts +705 -0
  122. package/src/utils/sheetExport.ts +186 -0
  123. package/src/utils/sheetFeatureReference.ts +183 -0
  124. package/src/utils/sheetFormulaArgs.ts +168 -0
  125. package/src/utils/sheetFormulaCompile.ts +475 -0
  126. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  127. package/src/utils/sheetFormulaCriteria.ts +656 -0
  128. package/src/utils/sheetFormulaDate.ts +444 -0
  129. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  130. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  131. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  132. package/src/utils/sheetFormulaLogical.ts +116 -0
  133. package/src/utils/sheetFormulaLookup.ts +488 -0
  134. package/src/utils/sheetFormulaMath.ts +48 -0
  135. package/src/utils/sheetFormulaParser.ts +729 -0
  136. package/src/utils/sheetFormulaRange.ts +330 -0
  137. package/src/utils/sheetFormulaReference.ts +703 -0
  138. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  139. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  140. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  141. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  142. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  143. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  144. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  145. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  146. package/src/utils/sheetFormulaText.ts +430 -0
  147. package/src/utils/sheetJournal.ts +200 -0
  148. package/src/utils/sheetNumberFormat.ts +1012 -0
  149. package/src/utils/sheetPreview.ts +68 -0
  150. package/src/utils/sheetSequence.ts +118 -0
  151. package/src/utils/sheetSnapshot.ts +739 -0
  152. package/src/utils/sheetStructureEdit.ts +914 -0
  153. package/src/utils/sheetStructureReferences.ts +389 -0
  154. package/src/utils/square.ts +32 -0
  155. package/src/utils/storage.ts +198 -0
  156. package/src/utils/table-route.ts +262 -0
  157. package/src/utils/time.ts +12 -0
  158. package/src/utils/workflow.ts +506 -0
  159. package/src/utils/workflowLogFingerprint.ts +302 -0
  160. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  161. package/src/utils/workflowProgress.ts +280 -0
  162. package/src/utils/workflowTriggers.ts +61 -0
  163. package/tests/agentNote.test.ts +395 -0
  164. package/tests/campaignAI.test.ts +119 -0
  165. package/tests/campaignAccess.test.ts +239 -0
  166. package/tests/campaignEmail.test.ts +441 -0
  167. package/tests/campaignLifecycle.test.ts +134 -0
  168. package/tests/campaignPublication.test.ts +309 -0
  169. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  170. package/tests/dataTableRelativeDate.test.ts +412 -0
  171. package/tests/docAccess.test.ts +525 -0
  172. package/tests/editLogEntry.test.ts +112 -0
  173. package/tests/email.test.ts +39 -0
  174. package/tests/fieldDocProgram.test.ts +114 -0
  175. package/tests/logDisplay.fixtures.ts +67 -0
  176. package/tests/logDisplay.test.ts +227 -0
  177. package/tests/noteDoc.test.ts +514 -0
  178. package/tests/richTextHTML.test.ts +185 -0
  179. package/tests/sheetAxisMove.test.ts +352 -0
  180. package/tests/sheetBootstrap.test.ts +1967 -0
  181. package/tests/sheetFeatureReference.test.ts +22 -0
  182. package/tests/sheetFormulaCriteria.test.ts +269 -0
  183. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  184. package/tests/sheetFormulaFunctions.test.ts +538 -0
  185. package/tests/sheetFormulaLanguage.test.ts +361 -0
  186. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  187. package/tests/sheetFormulaParity.test.ts +188 -0
  188. package/tests/sheetFormulaRange.test.ts +167 -0
  189. package/tests/sheetFormulaReference.test.ts +78 -0
  190. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  191. package/tests/sheetFormulaTextDate.test.ts +512 -0
  192. package/tests/sheetSequence.test.ts +22 -0
  193. package/tests/sheetSnapshot.test.ts +134 -0
  194. package/tests/sheetStructureEdit.test.ts +537 -0
  195. package/tests/sheetStructureReferences.test.ts +589 -0
  196. package/tests/workflowLifecycleStatus.test.ts +60 -0
  197. package/tests/workflowLogFingerprint.test.ts +203 -0
  198. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  199. package/tests/workflowProgress.test.ts +180 -0
  200. package/tests/workflowTriggers.test.ts +29 -0
  201. package/tsconfig.json +12 -0
  202. package/vitest.config.ts +8 -0
@@ -0,0 +1,379 @@
1
+ import { convertHTMLToMarkdown } from '../../../@jsb188:react-web/utils/markdown.ts';
2
+ import { EMAIL_STATUS_GROUP_STATUSES } from '../constants/email.ts';
3
+ import type {
4
+ EmailDirectionEnum,
5
+ EmailStatusGroupEnum,
6
+ InboundEmailBodyFormatEnum,
7
+ OutboundEmailData,
8
+ OutboundEmailStatusEnum,
9
+ } from '../types/email.d.ts';
10
+
11
+ type PostmarkInboundPayloadLike = {
12
+ HtmlBody?: string | null;
13
+ TextBody?: string | null;
14
+ StrippedTextReply?: string | null;
15
+ };
16
+
17
+ const INBOUND_EMAIL_PAYLOAD_OMIT_KEYS = [
18
+ 'HtmlBody',
19
+ 'Attachments',
20
+ // These keys are server-owned processing metadata, never provider input.
21
+ 'storedAttachments',
22
+ 'queuePublishedAt',
23
+ 'processingReadyAt',
24
+ 'processingQueueSuffix',
25
+ 'processingRetryNotBefore',
26
+ 'postmasterMutationCheckpoint',
27
+ 'postmasterTransientFailures',
28
+ ];
29
+ const INBOUND_EMAIL_DEFAULT_BODY_LENGTH = 12000;
30
+ const INBOUND_EMAIL_PREVIEW_LENGTH = 240;
31
+
32
+ /*
33
+ * Return the delivery status callers should present for one outbound row;
34
+ * Postmark spam complaints are stored alongside SENT but are terminal BLOCKED
35
+ * evidence for any future retry decision.
36
+ */
37
+ export function getOutboundEmailEffectiveDeliveryStatus(
38
+ value:
39
+ | OutboundEmailStatusEnum
40
+ | 'BLOCKED'
41
+ | Pick<OutboundEmailData, 'status' | 'spamComplaintAt'>,
42
+ ) {
43
+ return typeof value !== 'string' && value.spamComplaintAt
44
+ ? ('BLOCKED' as const)
45
+ : typeof value === 'string'
46
+ ? value
47
+ : value.status;
48
+ }
49
+
50
+ /*
51
+ * Classify one durable outbound-email row before a caller publishes a broker
52
+ * wake, so terminal or already accepted sends are never blindly requeued.
53
+ */
54
+ export function getOutboundEmailQueueDisposition(
55
+ value:
56
+ | OutboundEmailStatusEnum
57
+ | 'BLOCKED'
58
+ | Pick<OutboundEmailData, 'status' | 'spamComplaintAt'>,
59
+ ) {
60
+ const status = getOutboundEmailEffectiveDeliveryStatus(value);
61
+ switch (status) {
62
+ case 'QUEUED':
63
+ case 'ERRORED':
64
+ return 'QUEUE' as const;
65
+ case 'PROCESSING':
66
+ return 'PENDING' as const;
67
+ case 'SENT':
68
+ return 'ACCEPTED' as const;
69
+ case 'BOUNCED':
70
+ case 'DELIVERY_UNKNOWN':
71
+ case 'SUPPRESSED':
72
+ case 'BLOCKED':
73
+ return 'TERMINAL_FAILURE' as const;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Return a Postmark inbound payload safe to store on the email row.
79
+ */
80
+ export function getInboundEmailPayloadForStorage(payload?: object | null) {
81
+ const storagePayload: Record<string, unknown> = { ...(payload || {}) };
82
+ const hasTextBody =
83
+ typeof storagePayload.TextBody === 'string' && !!storagePayload.TextBody;
84
+ const hasStrippedTextReply =
85
+ typeof storagePayload.StrippedTextReply === 'string' &&
86
+ !!storagePayload.StrippedTextReply;
87
+ const htmlBodyMarkdown = getInboundEmailPayloadHtmlMarkdownText(
88
+ storagePayload as PostmarkInboundPayloadLike,
89
+ );
90
+
91
+ if (!hasTextBody && !hasStrippedTextReply && htmlBodyMarkdown) {
92
+ storagePayload.TextBody = htmlBodyMarkdown;
93
+ }
94
+
95
+ for (const key of INBOUND_EMAIL_PAYLOAD_OMIT_KEYS) {
96
+ delete storagePayload[key];
97
+ }
98
+
99
+ return storagePayload;
100
+ }
101
+
102
+ /**
103
+ * Limit optional Postmark text fields before displaying them.
104
+ */
105
+ export function limitInboundEmailTextValue(
106
+ value: string | null | undefined,
107
+ maxLength: number,
108
+ ): string | null {
109
+ return value ? value.substring(0, maxLength) : null;
110
+ }
111
+
112
+ /**
113
+ * Replace ASCII control characters in provider-owned email metadata.
114
+ */
115
+ export function replaceEmailControlCharacters(
116
+ value: string,
117
+ replacement: string,
118
+ ) {
119
+ return Array.from(value, (character) => {
120
+ const characterCode = character.charCodeAt(0);
121
+ return characterCode <= 31 || characterCode === 127
122
+ ? replacement
123
+ : character;
124
+ }).join('');
125
+ }
126
+
127
+ /**
128
+ * Return one limited Postmark text payload field.
129
+ */
130
+ function getInboundEmailPayloadTextValue(
131
+ payload: PostmarkInboundPayloadLike | null | undefined,
132
+ key: keyof PostmarkInboundPayloadLike,
133
+ maxLength: number,
134
+ ) {
135
+ return limitInboundEmailTextValue(
136
+ typeof payload?.[key] === 'string' ? payload[key] : null,
137
+ maxLength,
138
+ );
139
+ }
140
+
141
+ /**
142
+ * Return markdown converted from one HTML email body.
143
+ */
144
+ function getInboundEmailPayloadHtmlMarkdownText(
145
+ payload?: PostmarkInboundPayloadLike | null,
146
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
147
+ ) {
148
+ return limitInboundEmailTextValue(
149
+ typeof payload?.HtmlBody === 'string'
150
+ ? convertHTMLToMarkdown(payload.HtmlBody)
151
+ : null,
152
+ maxBodyLength,
153
+ );
154
+ }
155
+
156
+ /**
157
+ * Return the preferred raw text source from a saved inbound email payload.
158
+ */
159
+ export function getInboundEmailPayloadTextBody(
160
+ payload?: PostmarkInboundPayloadLike | null,
161
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
162
+ ): string | null {
163
+ return (
164
+ getInboundEmailPayloadTextValue(
165
+ payload,
166
+ 'StrippedTextReply',
167
+ maxBodyLength,
168
+ ) ||
169
+ getInboundEmailPayloadTextValue(payload, 'TextBody', maxBodyLength) ||
170
+ getInboundEmailPayloadHtmlMarkdownText(payload, maxBodyLength)
171
+ );
172
+ }
173
+
174
+ /**
175
+ * Return role-safe plain text for an inbound email agent message. Campaign
176
+ * replies never fall back to TextBody because it can contain the quoted
177
+ * organization-authored campaign that belongs in the assistant message.
178
+ */
179
+ export function getInboundEmailAgentBodyText(
180
+ payload: PostmarkInboundPayloadLike | null | undefined,
181
+ options: { campaignReply: boolean },
182
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
183
+ ): string {
184
+ const strippedReply =
185
+ typeof payload?.StrippedTextReply === 'string'
186
+ ? payload.StrippedTextReply.trim()
187
+ : '';
188
+ const textBody =
189
+ !options.campaignReply && typeof payload?.TextBody === 'string'
190
+ ? payload.TextBody.trim()
191
+ : '';
192
+
193
+ return (strippedReply || textBody).substring(0, maxBodyLength);
194
+ }
195
+
196
+ /**
197
+ * Return the display body format derived from a saved inbound email payload.
198
+ */
199
+ export function getInboundEmailBodyFormat(
200
+ payload?: PostmarkInboundPayloadLike | null,
201
+ ): InboundEmailBodyFormatEnum | null {
202
+ if (getInboundEmailPayloadTextBody(payload)) {
203
+ return 'TEXT';
204
+ }
205
+
206
+ return null;
207
+ }
208
+
209
+ /**
210
+ * Return the display body text derived from a saved inbound email payload.
211
+ */
212
+ export function getInboundEmailBodyText(
213
+ payload?: PostmarkInboundPayloadLike | null,
214
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
215
+ ): string {
216
+ return getInboundEmailPayloadTextBody(payload, maxBodyLength) || '';
217
+ }
218
+
219
+ /**
220
+ * Return a compact preview text derived from a saved inbound email payload.
221
+ */
222
+ export function getInboundEmailPreviewText(
223
+ payload?: PostmarkInboundPayloadLike | null,
224
+ ): string {
225
+ return getInboundEmailBodyText(payload, INBOUND_EMAIL_PREVIEW_LENGTH)
226
+ .replace(/\s+/g, ' ')
227
+ .trim();
228
+ }
229
+
230
+ /**
231
+ * Return a compact preview text from an outbound email's plain-text body.
232
+ */
233
+ export function getOutboundEmailPreviewText(body?: string | null): string {
234
+ return (body || '')
235
+ .slice(0, INBOUND_EMAIL_PREVIEW_LENGTH * 4)
236
+ .replace(/\s+/g, ' ')
237
+ .trim()
238
+ .slice(0, INBOUND_EMAIL_PREVIEW_LENGTH);
239
+ }
240
+
241
+ /*
242
+ * Build the direction-scoped email message id. Inbound and outbound rows live in
243
+ * separate tables whose ids overlap, so the direction is part of the identity.
244
+ */
245
+ export function makeEmailMessageId(
246
+ direction: EmailDirectionEnum,
247
+ emailId: string,
248
+ ): string {
249
+ return `${direction === 'INBOUND' ? 'in' : 'out'}_${emailId}`;
250
+ }
251
+
252
+ /*
253
+ * Split an email message id into its direction and serialized table row id.
254
+ */
255
+ export function parseEmailMessageId(
256
+ emailMessageId: string | null | undefined,
257
+ ): { direction: EmailDirectionEnum; emailId: string } | null {
258
+ const match = /^(in|out)_(\d+)$/.exec(emailMessageId || '');
259
+ if (!match) {
260
+ return null;
261
+ }
262
+
263
+ return {
264
+ direction: match[1] === 'in' ? 'INBOUND' : 'OUTBOUND',
265
+ emailId: match[2],
266
+ };
267
+ }
268
+
269
+ /*
270
+ * Return the direction-neutral status group for one raw email status.
271
+ */
272
+ export function getEmailStatusGroup(
273
+ direction: EmailDirectionEnum,
274
+ status: string | null | undefined,
275
+ ): EmailStatusGroupEnum {
276
+ const groups = EMAIL_STATUS_GROUP_STATUSES[direction];
277
+ for (const group of Object.keys(groups) as EmailStatusGroupEnum[]) {
278
+ if ((groups[group] as readonly string[]).includes(status || '')) {
279
+ return group;
280
+ }
281
+ }
282
+
283
+ return 'PENDING';
284
+ }
285
+
286
+ /*
287
+ * Split an RFC-style address list while keeping commas inside quoted display
288
+ * names, angle brackets, and comments within their recipient entry.
289
+ */
290
+ function splitEmailAddressListEntries(value: string): string[] {
291
+ const entries: string[] = [];
292
+ let current = '';
293
+ let angleDepth = 0;
294
+ let commentDepth = 0;
295
+ let quoted = false;
296
+ let escaped = false;
297
+
298
+ for (const character of value) {
299
+ if (escaped) {
300
+ current += character;
301
+ escaped = false;
302
+ continue;
303
+ }
304
+ if (quoted && character === '\\') {
305
+ current += character;
306
+ escaped = true;
307
+ continue;
308
+ }
309
+ if (character === '"' && commentDepth === 0) {
310
+ quoted = !quoted;
311
+ current += character;
312
+ continue;
313
+ }
314
+ if (!quoted) {
315
+ if (character === '<') {
316
+ angleDepth += 1;
317
+ } else if (character === '>' && angleDepth > 0) {
318
+ angleDepth -= 1;
319
+ } else if (character === '(' && angleDepth === 0) {
320
+ commentDepth += 1;
321
+ } else if (character === ')' && commentDepth > 0) {
322
+ commentDepth -= 1;
323
+ } else if (character === ',' && angleDepth === 0 && commentDepth === 0) {
324
+ entries.push(current);
325
+ current = '';
326
+ continue;
327
+ }
328
+ }
329
+
330
+ current += character;
331
+ }
332
+ entries.push(current);
333
+ return entries.map((entry) => entry.trim());
334
+ }
335
+
336
+ /*
337
+ * Extract and normalize the mailbox from one RFC-style recipient entry.
338
+ */
339
+ function getEmailAddressListEntryMailbox(entry: string): string | null {
340
+ const matches =
341
+ entry.match(
342
+ /[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+/gi,
343
+ ) || [];
344
+ const mailboxes = [
345
+ ...new Set(matches.map((mailbox) => mailbox.trim().toLowerCase())),
346
+ ];
347
+ return mailboxes.length === 1 ? mailboxes[0] : null;
348
+ }
349
+
350
+ /*
351
+ * Parse normalized mailboxes and retain invalid recipient entries so callers
352
+ * that perform side effects can fail closed instead of silently dropping one.
353
+ */
354
+ export function parseEmailAddressList(value: string): {
355
+ mailboxes: string[];
356
+ invalidEntries: string[];
357
+ } {
358
+ const mailboxes: string[] = [];
359
+ const invalidEntries: string[] = [];
360
+
361
+ for (const entry of splitEmailAddressListEntries(value)) {
362
+ const mailbox = getEmailAddressListEntryMailbox(entry);
363
+ if (mailbox) {
364
+ mailboxes.push(mailbox);
365
+ } else {
366
+ invalidEntries.push(entry);
367
+ }
368
+ }
369
+
370
+ return { mailboxes, invalidEntries };
371
+ }
372
+
373
+ /*
374
+ * Extract normalized mailboxes from an RFC-style address list while keeping
375
+ * commas inside quoted display names, angle brackets, and comments intact.
376
+ */
377
+ export function getEmailAddressListMailboxes(value: string): string[] {
378
+ return parseEmailAddressList(value).mailboxes;
379
+ }
@@ -0,0 +1,187 @@
1
+ import { deepStrictEqual, equal, throws } from 'node:assert/strict';
2
+ import { escapeCSVValue, isCSVFormulaLikeValue } from '@jsb188/app/utils/csv.ts';
3
+ import type { EmailCampaignReplyReportGQL } from '../types/emailReplyReport.d.ts';
4
+ import {
5
+ buildEmailCampaignReplyCSV,
6
+ type EmailCampaignReplyCSVLabels,
7
+ makeEmailCampaignReplyCSVFilename,
8
+ } from './emailReplyReport.ts';
9
+
10
+ const FILE_CONSTANTS = {
11
+ labels: {
12
+ email: 'Email',
13
+ name: 'Name',
14
+ replies: 'Replies',
15
+ lastReply: 'Last reply',
16
+ analysis: 'Analysis',
17
+ fieldUnit: (label: string) => `${label} unit`,
18
+ fieldStatus: (label: string) => `${label} status`,
19
+ answerStatus: {
20
+ ANSWERED: 'Answered',
21
+ UNCLEAR: 'Unclear',
22
+ WITHDRAWN: 'Withdrawn',
23
+ MISSING: 'Missing',
24
+ },
25
+ captureState: {
26
+ CAPTURED: 'Captured',
27
+ PROCESSING: 'Processing',
28
+ NOT_CAPTURED: 'Not captured',
29
+ },
30
+ notAnalyzed: 'Not analyzed yet',
31
+ withWarning: (label: string) => `${label} (later reply not captured)`,
32
+ yes: 'Yes',
33
+ no: 'No',
34
+ } satisfies EmailCampaignReplyCSVLabels,
35
+ };
36
+
37
+ /* Build a current snapshot with numeric zero, Boolean false, and untrusted text. */
38
+ function makeReport(): EmailCampaignReplyReportGQL {
39
+ return {
40
+ organizationId: 'organization',
41
+ campaignId: 'campaign',
42
+ campaignTitle: 'Reply report',
43
+ readAt: '2026-11-06T05:00:00.000Z',
44
+ availability: 'READY',
45
+ definitionReason: null,
46
+ limitReason: null,
47
+ instructions: null,
48
+ coverage: {
49
+ linkedReplyCount: 2,
50
+ spamReplyCount: 0,
51
+ nonRecipientReplyCount: 0,
52
+ replyCount: 2,
53
+ respondentCount: 2,
54
+ capturedReplyCount: 1,
55
+ capturedRespondentCount: 1,
56
+ processingReplyCount: 1,
57
+ notCapturedReplyCount: 0,
58
+ },
59
+ fields: (['NUMBER', 'BOOLEAN', 'TEXT'] as const).map((type, index) => ({
60
+ key: `f${index + 1}`,
61
+ label: index === 2 ? '=Question' : 'Answer',
62
+ type,
63
+ answeredCount: 1,
64
+ unclearCount: 0,
65
+ withdrawnCount: 0,
66
+ missingCount: 1,
67
+ unitGroupCount: 0,
68
+ omittedUnitGroups: 0,
69
+ numeric: [],
70
+ boolean: null,
71
+ })),
72
+ respondents: [
73
+ {
74
+ email: 'one@example.test',
75
+ displayName: '=HYPERLINK("evil")',
76
+ replyCount: 1,
77
+ lastReplyAt: '2026-11-06T05:00:00.000Z',
78
+ lastReplyEmailMessageId: 'source-one',
79
+ captureState: 'CAPTURED',
80
+ newerUncapturedReplyAt: '2026-11-06T06:00:00.000Z',
81
+ answers: ['f1', 'f2', 'f3'].map((fieldKey, index) => ({
82
+ fieldKey,
83
+ status: 'ANSWERED',
84
+ numberValue: index === 0 ? 0 : null,
85
+ booleanValue: index === 1 ? false : null,
86
+ textValue: index === 2 ? '"雪",\n=untrusted' : null,
87
+ unit: index === 0 ? 'people' : null,
88
+ receivedAt: '2026-11-06T05:00:00.000Z',
89
+ sourceEmailMessageId: `secret-${fieldKey}`,
90
+ hasNewerUncapturedReply: index === 0,
91
+ })),
92
+ },
93
+ {
94
+ email: 'two@example.test',
95
+ displayName: null,
96
+ replyCount: 1,
97
+ lastReplyAt: '2026-11-06T05:00:00.000Z',
98
+ lastReplyEmailMessageId: 'source-two',
99
+ captureState: 'PROCESSING',
100
+ newerUncapturedReplyAt: null,
101
+ answers: [],
102
+ },
103
+ ],
104
+ };
105
+ }
106
+
107
+ Deno.test('shared CSV escaping protects text and headers without changing signed numbers or phone-like values', () => {
108
+ for (const value of [
109
+ '=SUM(1,2)',
110
+ '@SUM(A1)',
111
+ '+cmd|evil',
112
+ '-cmd|evil',
113
+ '-1e-7+HYPERLINK("evil")',
114
+ '-1E9|cmd',
115
+ '\t=1',
116
+ '\r=1',
117
+ '\n=1',
118
+ ]) {
119
+ equal(isCSVFormulaLikeValue(value), true);
120
+ equal(escapeCSVValue(value).replace(/^"/, '').startsWith("'"), true);
121
+ }
122
+ for (const value of ['-12.50', '-1e-7', '-2E+21', '+1.25e3', '+14155550101', '0', 'plain text']) {
123
+ equal(escapeCSVValue(value), value);
124
+ }
125
+ equal(escapeCSVValue('"雪",\nvalue'), '"""雪"",\nvalue"');
126
+ deepStrictEqual([null, undefined, 0, false].map(escapeCSVValue), ['', '', '0', 'false']);
127
+ });
128
+
129
+ Deno.test('wide reply CSV preserves typed values, coverage warnings, text, and unique formula-safe headers', () => {
130
+ const report = makeReport();
131
+ const csv = buildEmailCampaignReplyCSV(report, {
132
+ labels: FILE_CONSTANTS.labels,
133
+ });
134
+ equal(
135
+ csv.split('\r\n')[0],
136
+ "Email,Name,Replies,Last reply,Analysis,Answer,Answer unit,Answer status,Answer (f2),Answer status (f2),'=Question,'=Question status",
137
+ );
138
+ equal(csv.includes(',0,people,Answered (later reply not captured),No,Answered,'), true);
139
+ equal(csv.includes('"\'=HYPERLINK(""evil"")"'), true);
140
+ equal(csv.includes('"""雪"",\n=untrusted"'), true);
141
+ equal(
142
+ csv.includes('two@example.test,,1,2026-11-06T05:00:00.000Z,Processing,,,Not analyzed yet,,Not analyzed yet,,Not analyzed yet'),
143
+ true,
144
+ );
145
+ equal(/secret-|source-one|source-two|organization/.test(csv), false);
146
+ });
147
+
148
+ Deno.test('CSV headers stay unique after formula neutralization and scientific numbers retain their value', () => {
149
+ const report = makeReport();
150
+ report.fields[0].label = '=Question';
151
+ report.fields[1].label = "'=Question";
152
+ report.fields[2].label = "'=Question (f2)";
153
+ report.respondents[0].answers[0].numberValue = -1e-7;
154
+ const csv = buildEmailCampaignReplyCSV(report, { labels: FILE_CONSTANTS.labels });
155
+ const headers = csv.split('\r\n')[0].split(',');
156
+ equal(new Set(headers).size, headers.length);
157
+ equal(csv.includes(',-1e-7,people,'), true);
158
+ });
159
+
160
+ Deno.test('CSV row selection uses the loaded snapshot and oversized reports cannot become partial files', () => {
161
+ const report = makeReport();
162
+ const selected = {
163
+ ...report.respondents[0],
164
+ displayName: 'Substituted stale value',
165
+ };
166
+ const csv = buildEmailCampaignReplyCSV(report, {
167
+ respondents: [selected, selected],
168
+ labels: FILE_CONSTANTS.labels,
169
+ });
170
+ equal(csv.includes('two@example.test'), false);
171
+ equal(csv.includes('Substituted stale value'), false);
172
+ equal(csv.match(/one@example.test/g)?.length, 1);
173
+ throws(
174
+ () =>
175
+ buildEmailCampaignReplyCSV(
176
+ { ...report, availability: 'TOO_LARGE' },
177
+ {
178
+ labels: FILE_CONSTANTS.labels,
179
+ },
180
+ ),
181
+ RangeError,
182
+ );
183
+ equal(
184
+ makeEmailCampaignReplyCSVFilename('A/B: replies', new Date('2026-11-06T05:00:00Z')),
185
+ 'A_B_ replies 2026-11-06T05-00-00-000Z.csv',
186
+ );
187
+ });
@@ -0,0 +1,143 @@
1
+ import { escapeCSVValue } from '@jsb188/app/utils/csv.ts';
2
+ import type {
3
+ EmailCampaignReplyAnswerGQL,
4
+ EmailCampaignReplyAnswerStatus,
5
+ EmailCampaignReplyCaptureState,
6
+ EmailCampaignReplyFieldGQL,
7
+ EmailCampaignReplyReportGQL,
8
+ EmailCampaignReplyRespondentGQL,
9
+ } from '../types/emailReplyReport.d.ts';
10
+
11
+ export interface EmailCampaignReplyCSVLabels {
12
+ email: string;
13
+ name: string;
14
+ replies: string;
15
+ lastReply: string;
16
+ analysis: string;
17
+ fieldUnit: (label: string) => string;
18
+ fieldStatus: (label: string) => string;
19
+ answerStatus: Record<EmailCampaignReplyAnswerStatus | 'MISSING', string>;
20
+ captureState: Record<EmailCampaignReplyCaptureState, string>;
21
+ notAnalyzed: string;
22
+ withWarning: (label: string) => string;
23
+ yes: string;
24
+ no: string;
25
+ }
26
+
27
+ /* Format finite report values consistently in the table, totals, and CSV. */
28
+ export function formatEmailReplyReportNumber(value: number | null | undefined) {
29
+ return value != null && Number.isFinite(value) ? String(value) : '';
30
+ }
31
+
32
+ /* Return a current answer's display value without inventing zero or Boolean false. */
33
+ export function getEmailCampaignReplyAnswerValue(
34
+ field: EmailCampaignReplyFieldGQL,
35
+ answer: EmailCampaignReplyAnswerGQL | undefined,
36
+ labels: Pick<EmailCampaignReplyCSVLabels, 'yes' | 'no'>,
37
+ ) {
38
+ if (answer?.status !== 'ANSWERED') return '';
39
+ if (field.type === 'NUMBER') {
40
+ return formatEmailReplyReportNumber(answer.numberValue);
41
+ }
42
+ if (field.type === 'BOOLEAN') {
43
+ return answer.booleanValue == null ? '' : answer.booleanValue ? labels.yes : labels.no;
44
+ }
45
+ return answer.textValue ?? '';
46
+ }
47
+
48
+ /* Distinguish an absent captured answer from an email that has not been analyzed. */
49
+ export function getEmailCampaignReplyAnswerStatus(
50
+ respondent: EmailCampaignReplyRespondentGQL,
51
+ answer: EmailCampaignReplyAnswerGQL | undefined,
52
+ labels: Pick<EmailCampaignReplyCSVLabels, 'answerStatus' | 'captureState' | 'notAnalyzed' | 'withWarning'>,
53
+ ) {
54
+ const status = answer
55
+ ? labels.answerStatus[answer.status]
56
+ : respondent.captureState === 'PROCESSING'
57
+ ? labels.notAnalyzed
58
+ : respondent.captureState === 'NOT_CAPTURED'
59
+ ? labels.captureState.NOT_CAPTURED
60
+ : labels.answerStatus.MISSING;
61
+ return answer?.hasNewerUncapturedReply ? labels.withWarning(status) : status;
62
+ }
63
+
64
+ /* Keep serialized headers unique after formula protection, including collisions with base columns or suffixes. */
65
+ function getUniqueEmailReplyCSVHeader(label: string, key: string, used: Set<string>) {
66
+ let unique = label;
67
+ let suffix = 1;
68
+ while (used.has(escapeCSVValue(unique))) {
69
+ unique = `${label} (${key}${suffix > 1 ? `-${suffix}` : ''})`;
70
+ suffix++;
71
+ }
72
+ used.add(escapeCSVValue(unique));
73
+ return unique;
74
+ }
75
+
76
+ /* Select rows from this exact loaded snapshot in the displayed order, never substituted row values. */
77
+ function getEmailReplyCSVRespondents(report: EmailCampaignReplyReportGQL, respondents: EmailCampaignReplyRespondentGQL[] | undefined) {
78
+ if (!respondents) return report.respondents;
79
+ const rows = new Map(report.respondents.map((row) => [row.email, row]));
80
+ const seen = new Set<string>();
81
+ return respondents.flatMap((selected) => {
82
+ const row = rows.get(selected.email);
83
+ if (!row || seen.has(row.email)) return [];
84
+ seen.add(row.email);
85
+ return [row];
86
+ });
87
+ }
88
+
89
+ /* Build one formula-safe, wide CSV from the displayed report snapshot and optional local row selection. */
90
+ export function buildEmailCampaignReplyCSV(
91
+ report: EmailCampaignReplyReportGQL,
92
+ options: {
93
+ respondents?: EmailCampaignReplyRespondentGQL[];
94
+ labels: EmailCampaignReplyCSVLabels;
95
+ },
96
+ ) {
97
+ if (report.availability === 'TOO_LARGE') {
98
+ throw new RangeError('An incomplete reply report cannot be exported.');
99
+ }
100
+ const { labels } = options;
101
+ const used = new Set<string>();
102
+ const headers = [labels.email, labels.name, labels.replies, labels.lastReply, labels.analysis].map((label, index) =>
103
+ getUniqueEmailReplyCSVHeader(label, String(index + 1), used),
104
+ );
105
+ for (const field of report.fields) {
106
+ headers.push(getUniqueEmailReplyCSVHeader(field.label, field.key, used));
107
+ if (field.type === 'NUMBER') {
108
+ headers.push(getUniqueEmailReplyCSVHeader(labels.fieldUnit(field.label), field.key, used));
109
+ }
110
+ headers.push(getUniqueEmailReplyCSVHeader(labels.fieldStatus(field.label), field.key, used));
111
+ }
112
+ const lines = [headers.map(escapeCSVValue).join(',')];
113
+ for (const respondent of getEmailReplyCSVRespondents(report, options.respondents)) {
114
+ const analysis = labels.captureState[respondent.captureState];
115
+ const values: unknown[] = [
116
+ respondent.email,
117
+ respondent.displayName,
118
+ respondent.replyCount,
119
+ new Date(respondent.lastReplyAt).toISOString(),
120
+ respondent.newerUncapturedReplyAt ? labels.withWarning(analysis) : analysis,
121
+ ];
122
+ const answers = new Map(respondent.answers.map((answer) => [answer.fieldKey, answer]));
123
+ for (const field of report.fields) {
124
+ const answer = answers.get(field.key);
125
+ values.push(getEmailCampaignReplyAnswerValue(field, answer, labels));
126
+ if (field.type === 'NUMBER') {
127
+ values.push(answer?.status === 'ANSWERED' ? answer.unit : '');
128
+ }
129
+ values.push(getEmailCampaignReplyAnswerStatus(respondent, answer, labels));
130
+ }
131
+ lines.push(values.map(escapeCSVValue).join(','));
132
+ }
133
+ return lines.join('\r\n') + '\r\n';
134
+ }
135
+
136
+ /* Produce a filesystem-safe campaign CSV name with an explicit UTC generation timestamp. */
137
+ export function makeEmailCampaignReplyCSVFilename(campaignTitle: string | null, generatedAt = new Date(), fallbackTitle = 'replies') {
138
+ const title = (campaignTitle?.trim() || fallbackTitle)
139
+ .replace(/[\u0000-\u001f\u007f/\\:*?"<>|]/g, '_')
140
+ .replace(/[. ]+$/g, '')
141
+ .slice(0, 100);
142
+ return `${title || fallbackTitle} ${generatedAt.toISOString().replace(/[:.]/g, '-')}.csv`;
143
+ }