@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,506 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { normalizeArrayLikeValue } from '@jsb188/app/utils/object.ts';
3
+ import { buildSingleText, type BuildSingleTextLine } from '@jsb188/app/utils/string.ts';
4
+ import { hhmmFromDateOrTime } from '@jsb188/app/utils/timeZone.ts';
5
+ import { CronExpressionParser } from 'cron-parser';
6
+ import type {
7
+ WorkflowData,
8
+ WorkflowGQL,
9
+ WorkflowLifecycleStatusEnum,
10
+ WorkflowRunData,
11
+ WorkflowStatusEnum,
12
+ } from '../types/workflow.d.ts';
13
+ import { getTaxonomyActivityLabel, getTaxonomyGroupLabel, humanizeRegistryKey } from './logTaxonomyDisplay.ts';
14
+ import { getWorkflowTriggerActivity, isWorkflowTriggerKeyAllowed } from './workflowTriggers.ts';
15
+
16
+ const DEFAULT_SCHEDULE_WINDOW_MS = 24 * 60 * 60 * 1000; // once per day
17
+
18
+ /**
19
+ * Normalize workflow log types from database, cache, or API-shaped values.
20
+ */
21
+
22
+ export function normalizeWorkflowLogTypes(logTypes: unknown): string[] | null {
23
+ const rawLogTypes = normalizeArrayLikeValue(logTypes);
24
+
25
+ const normalizedLogTypes = (rawLogTypes || [])
26
+ .map((logType) => (typeof logType === 'string' ? logType.trim() : ''))
27
+ .filter((logType) => !!logType && logType.toUpperCase() !== 'NULL');
28
+
29
+ return normalizedLogTypes.length ? normalizedLogTypes : null;
30
+ }
31
+
32
+ /**
33
+ * Resolve a workflow group or activity label with a registry-key fallback.
34
+ */
35
+
36
+ export function getWorkflowLogTypeLabel(logType: string, short: boolean = false, operation?: string | null): string {
37
+ const activity = getWorkflowTriggerActivity(logType);
38
+ if (activity !== null)
39
+ return short && i18n.has(`log.activity_short.${activity}`)
40
+ ? i18n.t(`log.activity_short.${activity}`)
41
+ : getTaxonomyActivityLabel(null, activity);
42
+ if (logType === 'MARKET_OPERATION' || (logType === 'OPERATION' && operation === 'FARMERS_MARKET'))
43
+ return getTaxonomyGroupLabel(null, logType, operation, short);
44
+ const i18nKey = `log.type${short ? '_short' : ''}.${logType}`;
45
+ if (i18n.has(i18nKey)) {
46
+ return i18n.t(i18nKey);
47
+ }
48
+ if (!short && i18n.has(`log.type_short.${logType}`)) {
49
+ return i18n.t(`log.type_short.${logType}`);
50
+ }
51
+ return humanizeRegistryKey(logType);
52
+ }
53
+
54
+ /**
55
+ * Get the short workflow label used in cards and headers.
56
+ */
57
+
58
+ export function getWorkflowShortLabel(workflow: Pick<WorkflowGQL, 'logTypes'>, operation?: string | null) {
59
+ const firstLogType = workflow.logTypes?.[0];
60
+
61
+ return firstLogType ? getWorkflowLogTypeLabel(firstLogType, true, operation) : i18n.t('c.workflow');
62
+ }
63
+
64
+ /**
65
+ * Check whether a workflow has an active trigger target. App interaction
66
+ * subscriptions never match a log, so they are not a target. A workflow an
67
+ * agent note manages (an insight tracker) always has one: its log triggers,
68
+ * or the web form campaigns it is bound to.
69
+ */
70
+
71
+ export function hasWorkflowActiveTarget(
72
+ workflow: Pick<WorkflowGQL, 'logTypes' | 'fieldDocId' | 'nextAt'> & Partial<Pick<WorkflowGQL, 'agentNoteId'>>,
73
+ ) {
74
+ return (
75
+ !!workflow.nextAt || !!workflow.logTypes?.some(isWorkflowTriggerKeyAllowed) || !!workflow.fieldDocId || !!workflow.agentNoteId
76
+ );
77
+ }
78
+
79
+ /**
80
+ * Check whether a workflow should display as active.
81
+ */
82
+
83
+ export function isWorkflowActive(
84
+ workflow: Pick<WorkflowGQL, 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'> & Partial<Pick<WorkflowGQL, 'agentNoteId'>>,
85
+ ) {
86
+ return !!workflow.active && hasWorkflowActiveTarget(workflow);
87
+ }
88
+
89
+ /**
90
+ * Check whether a workflow row is a reminder (kind=REMINDER).
91
+ */
92
+
93
+ export function isReminder(workflow: Pick<WorkflowGQL, 'kind'>) {
94
+ return workflow.kind === 'REMINDER';
95
+ }
96
+
97
+ /**
98
+ * Check whether a reminder is still actionable (cancelable): scheduled to
99
+ * fire, or already fired with its run still ongoing. Completed and canceled
100
+ * reminders are not active.
101
+ */
102
+
103
+ export function isReminderActive(reminder: Pick<WorkflowGQL, 'status'>) {
104
+ return reminder.status === 'SCHEDULED' || reminder.status === 'IN_PROGRESS';
105
+ }
106
+
107
+ /**
108
+ * Derive the lifecycle status for a workflow or reminder.
109
+ * `active` is pure user intent (enabled vs canceled/paused); everything
110
+ * time- or run-dependent is derived at read time so it can never go stale.
111
+ * An inactive reminder whose terminal record (values.reminderEnd) says
112
+ * COMPLETED is COMPLETED; every other inactive reminder is INACTIVE.
113
+ * For a fired one-time reminder the latest run decides ongoing vs completed;
114
+ * pass `latestRun` as undefined when the run state is unknown, and the
115
+ * result is undefined too (callers omit the field instead of guessing).
116
+ */
117
+
118
+ export function getWorkflowLifecycleStatus(
119
+ workflow: Pick<WorkflowGQL, 'kind' | 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'> &
120
+ Partial<Pick<WorkflowGQL, 'agentNoteId'>> &
121
+ Partial<Pick<WorkflowData, 'values'>>,
122
+ latestRun?: {
123
+ status: WorkflowStatusEnum;
124
+ followUpAt: Date | string | null;
125
+ } | null,
126
+ now = new Date(),
127
+ ): WorkflowLifecycleStatusEnum | undefined {
128
+ if (!isReminder(workflow)) {
129
+ return isWorkflowActive(workflow) ? 'ACTIVE' : 'INACTIVE';
130
+ }
131
+
132
+ if (!workflow.active) {
133
+ return workflow.values?.reminderEnd?.outcome === 'COMPLETED' ? 'COMPLETED' : 'INACTIVE';
134
+ }
135
+
136
+ if (workflow.nextAt || workflow.values?.agentTask?.trigger === 'SOURCE_CHANGE') {
137
+ return 'SCHEDULED';
138
+ }
139
+
140
+ // Fired one-time reminder; the latest run decides ongoing vs completed
141
+
142
+ if (latestRun === undefined) {
143
+ return undefined;
144
+ }
145
+
146
+ return isWorkflowRunSettled(latestRun, now) ? 'COMPLETED' : 'IN_PROGRESS';
147
+ }
148
+
149
+ /**
150
+ * Check whether a workflow run is settled (no further automatic action will occur).
151
+ * An open run counts as ongoing only while it has a future resume point;
152
+ * both reply waits and scheduled follow-ups set followUpAt on the run.
153
+ */
154
+
155
+ export function isWorkflowRunSettled(
156
+ workflowRun:
157
+ | {
158
+ status: WorkflowStatusEnum;
159
+ followUpAt: Date | string | null;
160
+ }
161
+ | null
162
+ | undefined,
163
+ now = new Date(),
164
+ ) {
165
+ if (!workflowRun) {
166
+ return true;
167
+ }
168
+
169
+ if (!['QUEUED', 'STARTED'].includes(workflowRun.status)) {
170
+ return true;
171
+ }
172
+
173
+ return !workflowRun.followUpAt || new Date(workflowRun.followUpAt) <= now;
174
+ }
175
+
176
+ /**
177
+ * Check whether a reminder repeats on a cron schedule.
178
+ */
179
+
180
+ export function isRecurringReminder(workflow: Pick<WorkflowGQL, 'triggerType'>) {
181
+ return workflow.triggerType === 'SCHEDULE';
182
+ }
183
+
184
+ /**
185
+ * Replace workflow template values in text using {{key}} placeholders
186
+ */
187
+
188
+ export function replaceWorkflowTemplateValues(text: string, values?: Record<string, any> | null, timeZone: string | null = null) {
189
+ if (!text || !values || typeof values !== 'object' || Array.isArray(values)) {
190
+ return text;
191
+ }
192
+
193
+ return text.replace(/{{(.*?)}}/g, (_match, rawKey) => {
194
+ const key = String(rawKey).trim();
195
+ const value = values[key];
196
+
197
+ switch (key) {
198
+ case 'endTime': {
199
+ if (!value) {
200
+ break;
201
+ }
202
+
203
+ const normalized = String(value).replace(':', '');
204
+ if (!/^[0-9]{3,4}$/.test(normalized)) {
205
+ break;
206
+ }
207
+
208
+ return hhmmFromDateOrTime(normalized, null, true, timeZone, true) || String(value);
209
+ }
210
+ }
211
+
212
+ if (value === undefined || value === null || String(value) === '') {
213
+ return `{{${key}}}`;
214
+ }
215
+
216
+ return String(value);
217
+ });
218
+ }
219
+
220
+ /**
221
+ * Render one workflow instruction section with the same truthy config and placeholder rules.
222
+ * A null config enables no conditional keys and leaves every placeholder unchanged.
223
+ */
224
+
225
+ export function renderWorkflowInstruction(
226
+ instruction: string | BuildSingleTextLine[] | null | undefined,
227
+ config: Record<string, any> | null = {},
228
+ timeZone: string | null = null,
229
+ ) {
230
+ const text =
231
+ typeof instruction === 'string'
232
+ ? instruction
233
+ : buildSingleText(
234
+ instruction || [],
235
+ ' ',
236
+ Object.keys(config || {}).filter((key) => config?.[key]),
237
+ );
238
+ return replaceWorkflowTemplateValues(text, config, timeZone);
239
+ }
240
+
241
+ /*
242
+ * Render a reminder's main content, omitting unread columns from partial realtime updates.
243
+ */
244
+ export function getReminderContent(workflow: Pick<WorkflowData, 'kind' | 'instructions' | 'values'>, timeZone: string | null = null) {
245
+ if (workflow.kind === undefined || workflow.instructions === undefined) return undefined;
246
+ if (workflow.kind !== 'REMINDER') return null;
247
+ return renderWorkflowInstruction(workflow.instructions?.main, workflow.values?.config, timeZone).trim() || null;
248
+ }
249
+
250
+ /**
251
+ * Compose a program-managed workflow's catalog instructions with the organization's user instructions.
252
+ * Blank user instructions leave the catalog text unchanged; otherwise they follow it under a "User instructions:" heading.
253
+ */
254
+
255
+ export function composeWorkflowUserInstructions(catalogText: string, userInstructions: string | null | undefined): string {
256
+ const user = userInstructions?.trim();
257
+ if (!user) return catalogText;
258
+ return [catalogText.trim(), `User instructions:\n${user}`].filter(Boolean).join('\n');
259
+ }
260
+
261
+ /**
262
+ * Return the first plain-text line of a workflow instruction (e.g. a reminder task).
263
+ * A string instruction is returned whole instead of its first character.
264
+ */
265
+
266
+ export function getWorkflowInstructionFirstLine(instruction: string | BuildSingleTextLine[] | null | undefined) {
267
+ if (typeof instruction === 'string') {
268
+ return instruction;
269
+ }
270
+ return Array.isArray(instruction) && typeof instruction[0] === 'string' ? instruction[0] : null;
271
+ }
272
+
273
+ /**
274
+ * Build special step template values that are not stored in workflow config.
275
+ */
276
+
277
+ export function makeWorkflowDataTableVariableValues(dataTableNames: string[] | null | undefined) {
278
+ return dataTableNames?.length ? { data_table_names: dataTableNames.join(', ') } : null;
279
+ }
280
+
281
+ /**
282
+ * Resolve required config keys for one conditional step override.
283
+ * Without an explicit list, placeholders in the override value are required.
284
+ */
285
+
286
+ function getRequiredWorkflowConfigKeys(required: unknown, value: unknown) {
287
+ if (Array.isArray(required)) {
288
+ return required as unknown[];
289
+ } else if (typeof value !== 'string' || !value) {
290
+ return [];
291
+ }
292
+
293
+ const templateKeys = new Set<string>();
294
+ for (const match of value.matchAll(/{{(.*?)}}/g)) {
295
+ const key = String(match[1] || '').trim();
296
+ if (key) {
297
+ templateKeys.add(key);
298
+ }
299
+ }
300
+
301
+ return Array.from(templateKeys);
302
+ }
303
+
304
+ /**
305
+ * Check whether all required config keys exist and are non-falsy (the string '0' counts as falsy).
306
+ */
307
+
308
+ function hasRequiredWorkflowConfigValues(config: unknown, required: unknown, value: unknown) {
309
+ const requiredKeys = getRequiredWorkflowConfigKeys(required, value);
310
+ if (!requiredKeys.length) {
311
+ return true;
312
+ }
313
+
314
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
315
+ return false;
316
+ }
317
+
318
+ const values = config as Record<string, unknown>;
319
+ return requiredKeys.every((key) => typeof key === 'string' && key in values && !!values[key] && values[key] !== '0');
320
+ }
321
+
322
+ /**
323
+ * Find the first conditional step override whose required config values are satisfied.
324
+ */
325
+
326
+ function findWorkflowConditionalStep(step: any, config: unknown) {
327
+ if (!step || typeof step !== 'object' || !Array.isArray(step.conditional)) {
328
+ return null;
329
+ }
330
+
331
+ return (
332
+ step.conditional.find(
333
+ (conditionalStep: any) =>
334
+ conditionalStep &&
335
+ typeof conditionalStep === 'object' &&
336
+ hasRequiredWorkflowConfigValues(config, conditionalStep.required, conditionalStep.value),
337
+ ) || null
338
+ );
339
+ }
340
+
341
+ /**
342
+ * Merge one workflow step with its first matching conditional override and render its value.
343
+ */
344
+
345
+ function resolveWorkflowStep(step: any, config: Record<string, any> | null, timeZone: string | null = null) {
346
+ if (!step || typeof step !== 'object') {
347
+ return step;
348
+ }
349
+
350
+ const conditionalStep = findWorkflowConditionalStep(step, config);
351
+ const { required: _required, ...conditionalStepValues } = conditionalStep || {};
352
+ const mappedStep = conditionalStep ? { ...step, ...conditionalStepValues } : step;
353
+
354
+ return {
355
+ label: mappedStep.label,
356
+ value: typeof mappedStep.value === 'string' ? replaceWorkflowTemplateValues(mappedStep.value, config, timeZone) : undefined,
357
+ };
358
+ }
359
+
360
+ /**
361
+ * Check whether one resolved workflow step has visible text.
362
+ */
363
+
364
+ function hasWorkflowStepValue(step: any) {
365
+ return !!step && typeof step.value === 'string' && step.value.trim() !== '';
366
+ }
367
+
368
+ /**
369
+ * Resolve ordered conditional overrides and placeholders for every workflow step.
370
+ * Steps left without visible text are dropped. Runtime reads and authoring previews share this.
371
+ */
372
+
373
+ export function resolveWorkflowSteps(steps: unknown, config: Record<string, any> | null, timeZone: string | null = null): any[] {
374
+ return (Array.isArray(steps) ? steps : [])
375
+ .map((step) => resolveWorkflowStep(step, config, timeZone))
376
+ .filter((step) => hasWorkflowStepValue(step));
377
+ }
378
+
379
+ /**
380
+ * Get window for workflow schedule
381
+ */
382
+
383
+ function getScheduleWindowMs(schedule: string | null | undefined, nextAt: Date) {
384
+ if (!schedule) {
385
+ return DEFAULT_SCHEDULE_WINDOW_MS;
386
+ }
387
+
388
+ try {
389
+ const nextMs = CronExpressionParser.parse(schedule, { currentDate: nextAt }).next().toDate().getTime();
390
+ const diffMs = nextMs - nextAt.getTime();
391
+
392
+ return Number.isFinite(diffMs) && diffMs > 0 ? diffMs : DEFAULT_SCHEDULE_WINDOW_MS;
393
+ } catch {
394
+ return DEFAULT_SCHEDULE_WINDOW_MS;
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Check if current date is within workflow's schedule window
400
+ */
401
+
402
+ export function isWithinScheduleWindow(nextAt: Date | string | null | undefined, schedule?: string | null, now = new Date()) {
403
+ const nextAtDate = nextAt ? new Date(nextAt) : null;
404
+ if (!nextAtDate) {
405
+ return false;
406
+ }
407
+
408
+ const nextAtMs = nextAtDate.getTime();
409
+ if (!Number.isFinite(nextAtMs)) {
410
+ return false;
411
+ }
412
+
413
+ const nowMs = now.getTime();
414
+ if (!Number.isFinite(nowMs)) {
415
+ return false;
416
+ }
417
+
418
+ const windowMs = getScheduleWindowMs(schedule, nextAtDate);
419
+ const windowEndMs = nextAtMs + windowMs;
420
+
421
+ return nowMs >= nextAtMs && nowMs <= windowEndMs;
422
+ }
423
+
424
+ /**
425
+ * Get next workflow schedule date from cron expression.
426
+ */
427
+
428
+ /**
429
+ * Normalize workflow schedule interval into a valid positive integer.
430
+ */
431
+
432
+ function normalizeScheduleInterval(scheduleInterval: number | null | undefined) {
433
+ if (!Number.isFinite(scheduleInterval)) {
434
+ return 1;
435
+ }
436
+
437
+ const normalized = Math.floor(Number(scheduleInterval));
438
+ return normalized > 0 ? normalized : 1;
439
+ }
440
+
441
+ /**
442
+ * Get next workflow schedule date from cron expression and interval.
443
+ */
444
+
445
+ export function getNextWorkflowScheduleDate(
446
+ schedule: string | null | undefined,
447
+ scheduleInterval: number | null | undefined = 1,
448
+ currentDate: Date | string = new Date(),
449
+ timeZone: string | null = null,
450
+ ) {
451
+ if (!schedule) {
452
+ return null;
453
+ }
454
+
455
+ const current = new Date(currentDate);
456
+ if (!Number.isFinite(current.getTime())) {
457
+ return null;
458
+ }
459
+
460
+ try {
461
+ const interval = normalizeScheduleInterval(scheduleInterval);
462
+ const parsed = CronExpressionParser.parse(schedule, {
463
+ currentDate: current,
464
+ ...(timeZone ? { tz: timeZone } : {}),
465
+ });
466
+ let nextDate: Date | null = null;
467
+
468
+ for (let i = 0; i < interval; i += 1) {
469
+ nextDate = parsed.next().toDate();
470
+ }
471
+
472
+ return nextDate;
473
+ } catch {
474
+ return null;
475
+ }
476
+ }
477
+
478
+ /**
479
+ * Helper; check if workflow run is still active based on next follow-up time.
480
+ */
481
+
482
+ export function isWorkflowRunActive(workflowRun: WorkflowRunData | null, isFollowUp: boolean = false) {
483
+ if (!workflowRun) {
484
+ return false;
485
+ }
486
+
487
+ const nextFollowUpAt = workflowRun.followUpAt;
488
+ if (!nextFollowUpAt) {
489
+ if (['COMPLETED', 'ERRORED', 'CANCELED'].includes(workflowRun.status)) {
490
+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
491
+ return workflowRun.activityAt > oneDayAgo;
492
+ }
493
+
494
+ return true;
495
+ }
496
+
497
+ if (isFollowUp) {
498
+ const now = new Date();
499
+ const followUpWindowStart = new Date(nextFollowUpAt.getTime() - 10 * 60 * 1000);
500
+
501
+ // Allow follow-up run only after entering the 10-minute pre-follow-up window.
502
+ return now >= followUpWindowStart;
503
+ }
504
+
505
+ return nextFollowUpAt > new Date();
506
+ }