@jsb188/mday 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 (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -0,0 +1,601 @@
1
+ import type { RichTextDocument } from '@jsb188/mday/types/richText.d.ts';
2
+ import {
3
+ CAMPAIGN_EMAIL_ALIGNMENTS,
4
+ CAMPAIGN_EMAIL_BLOCK_TYPES,
5
+ CAMPAIGN_EMAIL_BUTTON_STYLES,
6
+ CAMPAIGN_EMAIL_DEFAULT_CONTENT_WIDTH,
7
+ CAMPAIGN_EMAIL_DOCUMENT_SCHEMA_VERSION,
8
+ CAMPAIGN_EMAIL_HEADING_LEVELS,
9
+ CAMPAIGN_EMAIL_INLINE_IMAGE_CONTENT_TYPES,
10
+ CAMPAIGN_EMAIL_MAX_COLUMNS_PER_ROW,
11
+ CAMPAIGN_EMAIL_MAX_CONTENT_WIDTH,
12
+ CAMPAIGN_EMAIL_MAX_INLINE_IMAGE_BYTES,
13
+ CAMPAIGN_EMAIL_MAX_INLINE_IMAGES,
14
+ CAMPAIGN_EMAIL_MAX_LINK_LABEL_LENGTH,
15
+ CAMPAIGN_EMAIL_MAX_LINK_URL_LENGTH,
16
+ CAMPAIGN_EMAIL_MAX_LINKS_PER_BLOCK,
17
+ CAMPAIGN_EMAIL_MIN_CONTENT_WIDTH,
18
+ } from '../constants/campaign.ts';
19
+ import type {
20
+ CampaignEmailAlignmentEnum,
21
+ CampaignEmailBlockContentObj,
22
+ CampaignEmailBlockObj,
23
+ CampaignEmailBlockSettingsObj,
24
+ CampaignEmailBlockStorageSettingsObj,
25
+ CampaignEmailBlockTypeEnum,
26
+ CampaignEmailButtonStyleEnum,
27
+ CampaignEmailDefinitionObj,
28
+ CampaignEmailDesignSettingsObj,
29
+ CampaignEmailHeadingLevelEnum,
30
+ CampaignEmailLinkObj,
31
+ CampaignEmailRowSettingsObj,
32
+ CampaignEmailRowStorageSettingsObj,
33
+ } from '../types/campaign.d.ts';
34
+ import { createEmptyNoteDoc, noteDocToPlainText, sanitizeNoteDoc } from './noteDoc.ts';
35
+
36
+ const FILE_CONSTANTS = {
37
+ defaultContentPadding: '0px',
38
+ emptyRichText: JSON.stringify(createEmptyNoteDoc()),
39
+ maxPadding: 200,
40
+ maxRichTextCacheEntries: 128,
41
+ };
42
+
43
+ /*
44
+ * Return whether one value is a safe one-to-four-value pixel padding
45
+ * shorthand accepted by email layout settings.
46
+ */
47
+ export function isCampaignEmailPaddingValid(value: unknown): value is string {
48
+ if (typeof value !== 'string') {
49
+ return false;
50
+ }
51
+
52
+ const values = value.trim().split(/\s+/);
53
+ return (
54
+ values.length >= 1 &&
55
+ values.length <= 4 &&
56
+ values.every((item) => {
57
+ if (!/^(?:0|\d+px)$/i.test(item)) {
58
+ return false;
59
+ }
60
+
61
+ return Number.parseInt(item, 10) <= FILE_CONSTANTS.maxPadding;
62
+ })
63
+ );
64
+ }
65
+
66
+ /*
67
+ * Normalize one safe CSS pixel padding shorthand or return its known-safe
68
+ * fallback without expanding the shorthand to four values.
69
+ */
70
+ export function getCampaignEmailPadding(value: unknown, fallback = FILE_CONSTANTS.defaultContentPadding): string {
71
+ const padding = isCampaignEmailPaddingValid(value)
72
+ ? value
73
+ : isCampaignEmailPaddingValid(fallback)
74
+ ? fallback
75
+ : FILE_CONSTANTS.defaultContentPadding;
76
+ return padding
77
+ .trim()
78
+ .split(/\s+/)
79
+ .map((item) => `${Number.parseInt(item, 10)}px`)
80
+ .join(' ');
81
+ }
82
+
83
+ const campaignEmailRichTextDocCache = new Map<string, RichTextDocument>();
84
+ const campaignEmailRichTextSerializationCache = new WeakMap<object, string>();
85
+
86
+ export type CampaignEmailValidationErrorCode =
87
+ | 'DUPLICATE_KEY'
88
+ | 'INVALID_COLUMN_WIDTH'
89
+ | 'INVALID_IMAGE_TYPE'
90
+ | 'INVALID_LINK'
91
+ | 'MISSING_IMAGE_SIZE'
92
+ | 'LINK_LABEL_TOO_LONG'
93
+ | 'LINK_URL_TOO_LONG'
94
+ | 'TOO_MANY_LINKS'
95
+ | 'TOO_MANY_INLINE_IMAGES'
96
+ | 'INLINE_IMAGES_TOO_LARGE'
97
+ | 'TOO_MANY_COLUMNS';
98
+
99
+ export interface CampaignEmailValidationError {
100
+ code: CampaignEmailValidationErrorCode;
101
+ rowKey?: string;
102
+ blockKey?: string;
103
+ }
104
+
105
+ /*
106
+ * Narrow one unknown value to an ordinary JSON object.
107
+ */
108
+ function isObjectRecord(value: unknown): value is Record<string, unknown> {
109
+ return !!value && typeof value === 'object' && !Array.isArray(value);
110
+ }
111
+
112
+ /*
113
+ * Read one finite integer and clamp it into the supplied inclusive range.
114
+ */
115
+ function getBoundedInteger(value: unknown, fallback: number, min: number, max: number): number {
116
+ return typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback;
117
+ }
118
+
119
+ /*
120
+ * Read one optional string without promoting non-string JSON values.
121
+ */
122
+ function getOptionalString(value: unknown): string | null {
123
+ return typeof value === 'string' ? value : null;
124
+ }
125
+
126
+ /*
127
+ * Read and refresh one canonical rich-text cache entry so recently edited
128
+ * blocks remain resident while older documents are evicted.
129
+ */
130
+ function getCachedCampaignEmailRichTextDoc(serialized: string): RichTextDocument | null {
131
+ const doc = campaignEmailRichTextDocCache.get(serialized);
132
+ if (!doc) {
133
+ return null;
134
+ }
135
+
136
+ campaignEmailRichTextDocCache.delete(serialized);
137
+ campaignEmailRichTextDocCache.set(serialized, doc);
138
+ return doc;
139
+ }
140
+
141
+ /*
142
+ * Cache one serialized RichTextDocument with a bounded least-recently-used policy.
143
+ */
144
+ function setCachedCampaignEmailRichTextDoc(serialized: string, doc: RichTextDocument): void {
145
+ campaignEmailRichTextDocCache.delete(serialized);
146
+ campaignEmailRichTextDocCache.set(serialized, doc);
147
+
148
+ while (campaignEmailRichTextDocCache.size > FILE_CONSTANTS.maxRichTextCacheEntries) {
149
+ const oldestKey = campaignEmailRichTextDocCache.keys().next().value;
150
+ if (typeof oldestKey !== 'string') {
151
+ break;
152
+ }
153
+ campaignEmailRichTextDocCache.delete(oldestKey);
154
+ }
155
+ }
156
+
157
+ /*
158
+ * Serialize one local rich-text editor document without its client-only
159
+ * identity keys so it can be compared with the sanitized persistence
160
+ * representation.
161
+ */
162
+ function getCampaignEmailLocalRichTextJSON(value: unknown): string | null {
163
+ if (!isObjectRecord(value)) {
164
+ return null;
165
+ }
166
+
167
+ try {
168
+ return JSON.stringify(value, (key, nestedValue) => (key === '_key' ? undefined : nestedValue));
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ /*
175
+ * Return whether one value is a supported email-builder block kind.
176
+ */
177
+ export function isCampaignEmailBlockType(value: unknown): value is CampaignEmailBlockTypeEnum {
178
+ return CAMPAIGN_EMAIL_BLOCK_TYPES.includes(value as CampaignEmailBlockTypeEnum);
179
+ }
180
+
181
+ /*
182
+ * Return whether one value is a supported email heading level.
183
+ */
184
+ export function isCampaignEmailHeadingLevel(value: unknown): value is CampaignEmailHeadingLevelEnum {
185
+ return CAMPAIGN_EMAIL_HEADING_LEVELS.includes(value as CampaignEmailHeadingLevelEnum);
186
+ }
187
+
188
+ /*
189
+ * Return whether one value is a supported email content alignment.
190
+ */
191
+ export function isCampaignEmailAlignment(value: unknown): value is CampaignEmailAlignmentEnum {
192
+ return CAMPAIGN_EMAIL_ALIGNMENTS.includes(value as CampaignEmailAlignmentEnum);
193
+ }
194
+
195
+ /*
196
+ * Return whether one value is a supported email button presentation.
197
+ */
198
+ export function isCampaignEmailButtonStyle(value: unknown): value is CampaignEmailButtonStyleEnum {
199
+ return CAMPAIGN_EMAIL_BUTTON_STYLES.includes(value as CampaignEmailButtonStyleEnum);
200
+ }
201
+
202
+ /*
203
+ * Parse and sanitize one serialized rich-text document. Invalid JSON becomes
204
+ * the ordinary empty RichTextDocument so callers never need a second fallback shape.
205
+ */
206
+ export function getCampaignEmailRichTextNoteDoc(value: unknown): RichTextDocument {
207
+ const source = typeof value === 'string' && value.trim() ? value : FILE_CONSTANTS.emptyRichText;
208
+ const cached = getCachedCampaignEmailRichTextDoc(source);
209
+ if (cached) {
210
+ return cached;
211
+ }
212
+
213
+ let sanitized: RichTextDocument;
214
+ try {
215
+ sanitized = sanitizeNoteDoc(JSON.parse(source));
216
+ } catch {
217
+ sanitized = createEmptyNoteDoc();
218
+ }
219
+
220
+ const serialized = JSON.stringify(sanitized);
221
+ const doc = getCachedCampaignEmailRichTextDoc(serialized) || sanitized;
222
+ setCachedCampaignEmailRichTextDoc(source, doc);
223
+ setCachedCampaignEmailRichTextDoc(serialized, doc);
224
+ campaignEmailRichTextSerializationCache.set(doc, serialized);
225
+ return doc;
226
+ }
227
+
228
+ /*
229
+ * Serialize one untrusted rich-text value through the canonical RichTextDocument
230
+ * sanitizer before it is persisted in an email block.
231
+ */
232
+ export function serializeCampaignEmailRichText(value: unknown): string {
233
+ if (isObjectRecord(value)) {
234
+ const cached = campaignEmailRichTextSerializationCache.get(value);
235
+ if (cached) {
236
+ return cached;
237
+ }
238
+ }
239
+
240
+ const sanitized = sanitizeNoteDoc(value);
241
+ const serialized = JSON.stringify(sanitized);
242
+ const doc = getCampaignEmailLocalRichTextJSON(value) === serialized ? (value as RichTextDocument) : sanitized;
243
+ setCachedCampaignEmailRichTextDoc(serialized, doc);
244
+ campaignEmailRichTextSerializationCache.set(doc, serialized);
245
+ return serialized;
246
+ }
247
+
248
+ /*
249
+ * Normalize one list of label-and-URL links while preserving draft strings
250
+ * for strict send validation to report to the editor.
251
+ */
252
+ function getCampaignEmailLinks(value: unknown): CampaignEmailLinkObj[] {
253
+ if (!Array.isArray(value)) {
254
+ return [];
255
+ }
256
+
257
+ return value.flatMap((link) => {
258
+ if (!isObjectRecord(link)) {
259
+ return [];
260
+ }
261
+
262
+ return [
263
+ {
264
+ label: typeof link.label === 'string' ? link.label : '',
265
+ url: typeof link.url === 'string' ? link.url : '',
266
+ },
267
+ ];
268
+ });
269
+ }
270
+
271
+ /*
272
+ * Normalize one email block's typed content, including canonical serialized
273
+ * rich text and an always-present links list.
274
+ */
275
+ export function getCampaignEmailBlockContent(value: unknown): CampaignEmailBlockContentObj {
276
+ const content = isObjectRecord(value) ? value : {};
277
+ const richText =
278
+ typeof content.richText === 'string' && content.richText.trim()
279
+ ? serializeCampaignEmailRichText(getCampaignEmailRichTextNoteDoc(content.richText))
280
+ : null;
281
+
282
+ return {
283
+ text: getOptionalString(content.text),
284
+ richText,
285
+ url: getOptionalString(content.url),
286
+ altText: getOptionalString(content.altText),
287
+ heading: getOptionalString(content.heading),
288
+ headingLevel: isCampaignEmailHeadingLevel(content.headingLevel) ? content.headingLevel : null,
289
+ buttonLabel: getOptionalString(content.buttonLabel),
290
+ buttonUrl: getOptionalString(content.buttonUrl),
291
+ links: getCampaignEmailLinks(content.links),
292
+ };
293
+ }
294
+
295
+ /*
296
+ * Normalize one email block's presentation with conservative email-client
297
+ * defaults and bounded spacing values.
298
+ */
299
+ export function getCampaignEmailBlockSettings(value: unknown): CampaignEmailBlockSettingsObj {
300
+ const settings = isObjectRecord(value) ? value : {};
301
+
302
+ return {
303
+ alignment: isCampaignEmailAlignment(settings.alignment) ? settings.alignment : 'LEFT',
304
+ textColor: getOptionalString(settings.textColor),
305
+ backgroundColor: getOptionalString(settings.backgroundColor),
306
+ fontSize:
307
+ typeof settings.fontSize === 'number' && Number.isFinite(settings.fontSize)
308
+ ? Math.min(96, Math.max(8, Math.round(settings.fontSize)))
309
+ : null,
310
+ padding: getCampaignEmailPadding(
311
+ settings.padding,
312
+ [settings.paddingTop, settings.paddingRight, settings.paddingBottom, settings.paddingLeft]
313
+ .map((padding) => `${getBoundedInteger(padding, 16, 0, FILE_CONSTANTS.maxPadding)}px`)
314
+ .join(' '),
315
+ ),
316
+ height:
317
+ typeof settings.height === 'number' && Number.isFinite(settings.height)
318
+ ? Math.min(1000, Math.max(0, Math.round(settings.height)))
319
+ : null,
320
+ buttonStyle: isCampaignEmailButtonStyle(settings.buttonStyle) ? settings.buttonStyle : null,
321
+ };
322
+ }
323
+
324
+ /*
325
+ * Normalize one email row's visual settings.
326
+ */
327
+ export function getCampaignEmailRowSettings(value: unknown): CampaignEmailRowSettingsObj {
328
+ const settings = isObjectRecord(value) ? value : {};
329
+
330
+ return {
331
+ backgroundColor: getOptionalString(settings.backgroundColor),
332
+ padding: getCampaignEmailPadding(
333
+ settings.padding,
334
+ `${getBoundedInteger(settings.paddingTop, 0, 0, FILE_CONSTANTS.maxPadding)}px 0px ${getBoundedInteger(settings.paddingBottom, 0, 0, FILE_CONSTANTS.maxPadding)}px 0px`,
335
+ ),
336
+ };
337
+ }
338
+
339
+ /*
340
+ * Normalize organization-wide email design settings used by every row and
341
+ * block unless a local setting overrides them.
342
+ */
343
+ export function getCampaignEmailDesignSettings(value: unknown): CampaignEmailDesignSettingsObj {
344
+ const settings = isObjectRecord(value) ? value : {};
345
+
346
+ return {
347
+ canvasColor: getOptionalString(settings.canvasColor),
348
+ contentColor: getOptionalString(settings.contentColor),
349
+ contentWidth: getBoundedInteger(
350
+ settings.contentWidth,
351
+ CAMPAIGN_EMAIL_DEFAULT_CONTENT_WIDTH,
352
+ CAMPAIGN_EMAIL_MIN_CONTENT_WIDTH,
353
+ CAMPAIGN_EMAIL_MAX_CONTENT_WIDTH,
354
+ ),
355
+ fontFamily: getOptionalString(settings.fontFamily),
356
+ textColor: getOptionalString(settings.textColor),
357
+ linkColor: getOptionalString(settings.linkColor),
358
+ padding: getCampaignEmailPadding(settings.padding, FILE_CONSTANTS.defaultContentPadding),
359
+ };
360
+ }
361
+
362
+ /*
363
+ * Normalize one persisted SECTION settings.emailRow value, retaining the
364
+ * stable column identities used by its child CONTENT blocks.
365
+ */
366
+ export function getCampaignEmailRowStorageSettings(value: unknown): CampaignEmailRowStorageSettingsObj | null {
367
+ const stored = isObjectRecord(value) ? value : null;
368
+ if (!stored || !Array.isArray(stored.columns)) {
369
+ return null;
370
+ }
371
+
372
+ const seen = new Set<string>();
373
+ const columns = stored.columns.flatMap((column, index) => {
374
+ if (!isObjectRecord(column) || typeof column.key !== 'string') {
375
+ return [];
376
+ }
377
+
378
+ const key = column.key.trim();
379
+ if (!key || seen.has(key)) {
380
+ return [];
381
+ }
382
+ seen.add(key);
383
+
384
+ return [
385
+ {
386
+ key,
387
+ order: getBoundedInteger(column.order, index, 0, 10000),
388
+ width: getBoundedInteger(column.width, 100, 1, 100),
389
+ },
390
+ ];
391
+ });
392
+
393
+ return columns.length
394
+ ? {
395
+ ...getCampaignEmailRowSettings(stored),
396
+ columns: columns.sort((a, b) => a.order - b.order),
397
+ }
398
+ : null;
399
+ }
400
+
401
+ /*
402
+ * Normalize one persisted CONTENT settings.emailBlock value.
403
+ */
404
+ export function getCampaignEmailBlockStorageSettings(value: unknown): CampaignEmailBlockStorageSettingsObj | null {
405
+ const stored = isObjectRecord(value) ? value : null;
406
+ if (!stored || typeof stored.columnKey !== 'string' || !stored.columnKey.trim() || !isCampaignEmailBlockType(stored.type)) {
407
+ return null;
408
+ }
409
+
410
+ return {
411
+ columnKey: stored.columnKey.trim(),
412
+ type: stored.type,
413
+ content: getCampaignEmailBlockContent(stored.content),
414
+ settings: getCampaignEmailBlockSettings(stored.settings),
415
+ };
416
+ }
417
+
418
+ /*
419
+ * Return whether one email destination is safe for a rendered link.
420
+ */
421
+ export function isCampaignEmailLink(value?: string | null): boolean {
422
+ return /^(https?:\/\/|mailto:)/i.test(String(value || '').trim());
423
+ }
424
+
425
+ /*
426
+ * Return whether one remote image source is safe for an email client.
427
+ */
428
+ export function isCampaignEmailImageURL(value?: string | null): boolean {
429
+ return /^https?:\/\//i.test(String(value || '').trim());
430
+ }
431
+
432
+ /*
433
+ * Return whether one destination was entered but cannot be rendered as a link.
434
+ * Empty destinations are not errors; the renderer simply skips them.
435
+ */
436
+ function isCampaignEmailBrokenLink(value: string | null | undefined, isValid: (value?: string | null) => boolean): boolean {
437
+ return !!String(value || '').trim() && !isValid(value);
438
+ }
439
+
440
+ /*
441
+ * Return the meaningful text carried by one block for validation and plain
442
+ * text preview decisions.
443
+ */
444
+ export function getCampaignEmailBlockText(block: CampaignEmailBlockObj): string {
445
+ if (block.type === 'RICH_TEXT' && block.content.richText) {
446
+ return noteDocToPlainText(getCampaignEmailRichTextNoteDoc(block.content.richText)).trim();
447
+ }
448
+
449
+ const content = block.content;
450
+ if (block.type === 'BUTTON') {
451
+ return [content.buttonLabel?.trim(), isCampaignEmailLink(content.buttonUrl) ? content.buttonUrl?.trim() : null]
452
+ .filter(Boolean)
453
+ .join(': ');
454
+ }
455
+ if (block.type === 'HERO') {
456
+ const button = [content.buttonLabel?.trim(), isCampaignEmailLink(content.buttonUrl) ? content.buttonUrl?.trim() : null]
457
+ .filter(Boolean)
458
+ .join(': ');
459
+ return [content.heading?.trim(), content.text?.trim(), button].filter(Boolean).join('\n\n');
460
+ }
461
+ if (block.type === 'SOCIAL' || block.type === 'MENU') {
462
+ return content.links
463
+ .filter((link) => link.label.trim() && isCampaignEmailLink(link.url))
464
+ .map((link) => `${link.label.trim()}: ${link.url.trim()}`)
465
+ .join('\n');
466
+ }
467
+ if (block.type === 'VIDEO' && isCampaignEmailLink(content.url)) {
468
+ return `${content.altText?.trim() || 'Watch video'}: ${content.url?.trim()}`;
469
+ }
470
+
471
+ return String(content.heading || content.text || '').trim();
472
+ }
473
+
474
+ /*
475
+ * Validate one normalized email definition for a send. Draft autosaves remain
476
+ * permissive; callers invoke this only before generation or delivery. Empty
477
+ * rows, columns, and blocks (a heading without text, an image without a
478
+ * source, a button without a label or destination) are allowed because the
479
+ * renderer skips them; only values that were entered but cannot render, unsafe
480
+ * images, and layouts that would render incorrectly block delivery.
481
+ */
482
+ export function getCampaignEmailValidationErrors(definition: CampaignEmailDefinitionObj): CampaignEmailValidationError[] {
483
+ const errors: CampaignEmailValidationError[] = [];
484
+ const keys = new Set<string>();
485
+ const inlineImageFiles = new Map<string, { contentType: string; size: number }>();
486
+
487
+ for (const row of definition.rows) {
488
+ if (keys.has(row.key)) {
489
+ errors.push({ code: 'DUPLICATE_KEY', rowKey: row.key });
490
+ }
491
+ keys.add(row.key);
492
+
493
+ if (row.columns.length > CAMPAIGN_EMAIL_MAX_COLUMNS_PER_ROW) {
494
+ errors.push({ code: 'TOO_MANY_COLUMNS', rowKey: row.key });
495
+ }
496
+ if (row.columns.some((column) => column.width < 1) || row.columns.reduce((sum, column) => sum + column.width, 0) !== 100) {
497
+ errors.push({ code: 'INVALID_COLUMN_WIDTH', rowKey: row.key });
498
+ }
499
+
500
+ for (const column of row.columns) {
501
+ if (keys.has(column.key)) {
502
+ errors.push({ code: 'DUPLICATE_KEY', rowKey: row.key });
503
+ }
504
+ keys.add(column.key);
505
+
506
+ for (const block of column.blocks) {
507
+ if (keys.has(block.key)) {
508
+ errors.push({ code: 'DUPLICATE_KEY', blockKey: block.key });
509
+ }
510
+ keys.add(block.key);
511
+ if (block.content.links.length > CAMPAIGN_EMAIL_MAX_LINKS_PER_BLOCK) {
512
+ errors.push({ code: 'TOO_MANY_LINKS', blockKey: block.key });
513
+ }
514
+ if (block.content.links.some((link) => link.label.length > CAMPAIGN_EMAIL_MAX_LINK_LABEL_LENGTH)) {
515
+ errors.push({ code: 'LINK_LABEL_TOO_LONG', blockKey: block.key });
516
+ }
517
+ if (block.content.links.some((link) => link.url.length > CAMPAIGN_EMAIL_MAX_LINK_URL_LENGTH)) {
518
+ errors.push({ code: 'LINK_URL_TOO_LONG', blockKey: block.key });
519
+ }
520
+ for (const file of block.files || []) {
521
+ const fileKey = file.id || file.uri || '';
522
+ if (!fileKey || inlineImageFiles.has(fileKey)) {
523
+ continue;
524
+ }
525
+
526
+ const contentType = String(file.contentType || '').toLowerCase();
527
+ const size = Number(file.size || 0);
528
+ inlineImageFiles.set(fileKey, { contentType, size });
529
+ if (!CAMPAIGN_EMAIL_INLINE_IMAGE_CONTENT_TYPES.some((allowedContentType) => allowedContentType === contentType)) {
530
+ errors.push({ code: 'INVALID_IMAGE_TYPE', blockKey: block.key });
531
+ }
532
+ if (!Number.isFinite(size) || size <= 0) {
533
+ errors.push({ code: 'MISSING_IMAGE_SIZE', blockKey: block.key });
534
+ }
535
+ }
536
+
537
+ const brokenButton =
538
+ (block.type === 'BUTTON' || block.type === 'HERO') &&
539
+ isCampaignEmailBrokenLink(block.content.buttonUrl, isCampaignEmailLink);
540
+ const brokenLinks = block.content.links.some((link) => isCampaignEmailBrokenLink(link.url, isCampaignEmailLink));
541
+ const brokenVideo = block.type === 'VIDEO' && isCampaignEmailBrokenLink(block.content.url, isCampaignEmailImageURL);
542
+ if (brokenButton || brokenLinks || brokenVideo) {
543
+ errors.push({ code: 'INVALID_LINK', blockKey: block.key });
544
+ }
545
+ }
546
+ }
547
+ }
548
+
549
+ if (inlineImageFiles.size > CAMPAIGN_EMAIL_MAX_INLINE_IMAGES) {
550
+ errors.push({ code: 'TOO_MANY_INLINE_IMAGES' });
551
+ }
552
+ if (
553
+ [...inlineImageFiles.values()].reduce((total, file) => total + Math.max(0, file.size), 0) > CAMPAIGN_EMAIL_MAX_INLINE_IMAGE_BYTES
554
+ ) {
555
+ errors.push({ code: 'INLINE_IMAGES_TOO_LARGE' });
556
+ }
557
+
558
+ return errors;
559
+ }
560
+
561
+ /*
562
+ * Return whether one authored font stack is safe for an inline CSS
563
+ * font-family declaration and fits the editor persistence limit.
564
+ */
565
+ export function isCampaignEmailFontFamilyValid(value: unknown): boolean {
566
+ const fontFamily = String(value || '').trim();
567
+ return fontFamily.length <= 200 && /^[a-z0-9\s,'"-]+$/i.test(fontFamily);
568
+ }
569
+
570
+ /*
571
+ * Resolve the first browser- or delivery-ready file URI attached to a block.
572
+ */
573
+ export function getCampaignEmailBlockFileURI(block: CampaignEmailBlockObj): string {
574
+ const files = isObjectRecord(block) && Array.isArray(block.files) ? block.files : [];
575
+ const file = files.find((value) => isObjectRecord(value) && typeof value.uri === 'string');
576
+ return isObjectRecord(file) && typeof file.uri === 'string' ? file.uri : '';
577
+ }
578
+
579
+ /*
580
+ * Resolve one heading level from either the HEADING block enum or a rich-text
581
+ * heading attribute, defaulting to the top level.
582
+ */
583
+ export function getCampaignEmailHeadingLevel(value: unknown): 1 | 2 | 3 {
584
+ if (value === 'H2' || value === 2) {
585
+ return 2;
586
+ }
587
+ if (value === 'H3' || value === 3) {
588
+ return 3;
589
+ }
590
+ return 1;
591
+ }
592
+
593
+ /*
594
+ * Build one empty canonical email definition for a new template or campaign.
595
+ */
596
+ export function createEmptyCampaignEmailDefinition(): CampaignEmailDefinitionObj {
597
+ return {
598
+ schemaVersion: CAMPAIGN_EMAIL_DOCUMENT_SCHEMA_VERSION,
599
+ rows: [],
600
+ };
601
+ }