ai-workflows 2.1.3 → 2.4.0

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 (188) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +14 -1
  3. package/README.md +2 -0
  4. package/dist/barrier.d.ts +6 -0
  5. package/dist/barrier.d.ts.map +1 -1
  6. package/dist/barrier.js +45 -7
  7. package/dist/barrier.js.map +1 -1
  8. package/dist/cascade-context.d.ts.map +1 -1
  9. package/dist/cascade-context.js +25 -25
  10. package/dist/cascade-context.js.map +1 -1
  11. package/dist/cascade-executor.d.ts.map +1 -1
  12. package/dist/cascade-executor.js +1 -1
  13. package/dist/cascade-executor.js.map +1 -1
  14. package/dist/context.d.ts.map +1 -1
  15. package/dist/context.js +23 -7
  16. package/dist/context.js.map +1 -1
  17. package/dist/cron-parser.d.ts +65 -0
  18. package/dist/cron-parser.d.ts.map +1 -0
  19. package/dist/cron-parser.js +294 -0
  20. package/dist/cron-parser.js.map +1 -0
  21. package/dist/cron-scheduler.d.ts +117 -0
  22. package/dist/cron-scheduler.d.ts.map +1 -0
  23. package/dist/cron-scheduler.js +176 -0
  24. package/dist/cron-scheduler.js.map +1 -0
  25. package/dist/database-context.d.ts +184 -0
  26. package/dist/database-context.d.ts.map +1 -0
  27. package/dist/database-context.js +428 -0
  28. package/dist/database-context.js.map +1 -0
  29. package/dist/digital-objects-adapter.d.ts +159 -0
  30. package/dist/digital-objects-adapter.d.ts.map +1 -0
  31. package/dist/digital-objects-adapter.js +229 -0
  32. package/dist/digital-objects-adapter.js.map +1 -0
  33. package/dist/durable-execution-cloudflare.d.ts +427 -0
  34. package/dist/durable-execution-cloudflare.d.ts.map +1 -0
  35. package/dist/durable-execution-cloudflare.js +510 -0
  36. package/dist/durable-execution-cloudflare.js.map +1 -0
  37. package/dist/durable-execution.d.ts +482 -0
  38. package/dist/durable-execution.d.ts.map +1 -0
  39. package/dist/durable-execution.js +594 -0
  40. package/dist/durable-execution.js.map +1 -0
  41. package/dist/durable-workflow.d.ts +176 -0
  42. package/dist/durable-workflow.d.ts.map +1 -0
  43. package/dist/durable-workflow.js +552 -0
  44. package/dist/durable-workflow.js.map +1 -0
  45. package/dist/graph/topological-sort.d.ts.map +1 -1
  46. package/dist/graph/topological-sort.js +5 -5
  47. package/dist/graph/topological-sort.js.map +1 -1
  48. package/dist/index.d.ts +4 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +15 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/logger.d.ts +101 -0
  53. package/dist/logger.d.ts.map +1 -0
  54. package/dist/logger.js +115 -0
  55. package/dist/logger.js.map +1 -0
  56. package/dist/on.d.ts.map +1 -1
  57. package/dist/on.js +3 -3
  58. package/dist/on.js.map +1 -1
  59. package/dist/runtime.d.ts +169 -0
  60. package/dist/runtime.d.ts.map +1 -0
  61. package/dist/runtime.js +275 -0
  62. package/dist/runtime.js.map +1 -0
  63. package/dist/send.d.ts.map +1 -1
  64. package/dist/send.js +4 -3
  65. package/dist/send.js.map +1 -1
  66. package/dist/telemetry.d.ts +150 -0
  67. package/dist/telemetry.d.ts.map +1 -0
  68. package/dist/telemetry.js +388 -0
  69. package/dist/telemetry.js.map +1 -0
  70. package/dist/timer-registry.d.ts +25 -0
  71. package/dist/timer-registry.d.ts.map +1 -1
  72. package/dist/timer-registry.js +42 -8
  73. package/dist/timer-registry.js.map +1 -1
  74. package/dist/types.d.ts +17 -6
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js +1 -1
  77. package/dist/types.js.map +1 -1
  78. package/dist/worker/durable-step.d.ts +481 -0
  79. package/dist/worker/durable-step.d.ts.map +1 -0
  80. package/dist/worker/durable-step.js +606 -0
  81. package/dist/worker/durable-step.js.map +1 -0
  82. package/dist/worker/index.d.ts +106 -0
  83. package/dist/worker/index.d.ts.map +1 -0
  84. package/dist/worker/index.js +124 -0
  85. package/dist/worker/index.js.map +1 -0
  86. package/dist/worker/state-adapter.d.ts +230 -0
  87. package/dist/worker/state-adapter.d.ts.map +1 -0
  88. package/dist/worker/state-adapter.js +409 -0
  89. package/dist/worker/state-adapter.js.map +1 -0
  90. package/dist/worker/topological-executor.d.ts +282 -0
  91. package/dist/worker/topological-executor.d.ts.map +1 -0
  92. package/dist/worker/topological-executor.js +396 -0
  93. package/dist/worker/topological-executor.js.map +1 -0
  94. package/dist/worker/workflow-builder.d.ts +286 -0
  95. package/dist/worker/workflow-builder.d.ts.map +1 -0
  96. package/dist/worker/workflow-builder.js +565 -0
  97. package/dist/worker/workflow-builder.js.map +1 -0
  98. package/dist/worker.d.ts +800 -0
  99. package/dist/worker.d.ts.map +1 -0
  100. package/dist/worker.js +2428 -0
  101. package/dist/worker.js.map +1 -0
  102. package/dist/workflow-builder.d.ts +287 -0
  103. package/dist/workflow-builder.d.ts.map +1 -0
  104. package/dist/workflow-builder.js +762 -0
  105. package/dist/workflow-builder.js.map +1 -0
  106. package/dist/workflow.d.ts +14 -30
  107. package/dist/workflow.d.ts.map +1 -1
  108. package/dist/workflow.js +132 -292
  109. package/dist/workflow.js.map +1 -1
  110. package/examples/01-ecommerce-order-pipeline.ts +358 -0
  111. package/examples/02-content-moderation-cascade.ts +454 -0
  112. package/examples/03-scheduled-reporting-dependencies.ts +479 -0
  113. package/examples/04-database-persistence.ts +518 -0
  114. package/examples/README.md +173 -0
  115. package/package.json +30 -13
  116. package/src/__tests__/digital-objects-adapter.test.ts +274 -0
  117. package/src/__tests__/durable-workflow.test.ts +297 -0
  118. package/src/barrier.ts +48 -7
  119. package/src/cascade-context.ts +36 -29
  120. package/src/cascade-executor.ts +3 -2
  121. package/src/context.ts +41 -12
  122. package/src/cron-parser.ts +347 -0
  123. package/src/cron-scheduler.ts +239 -0
  124. package/src/database-context.ts +658 -0
  125. package/src/digital-objects-adapter.ts +351 -0
  126. package/src/durable-execution-cloudflare.ts +855 -0
  127. package/src/durable-execution.ts +1042 -0
  128. package/src/durable-workflow.ts +717 -0
  129. package/src/graph/topological-sort.ts +6 -8
  130. package/src/index.ts +69 -0
  131. package/src/logger.ts +148 -0
  132. package/src/on.ts +8 -9
  133. package/src/runtime.ts +436 -0
  134. package/src/send.ts +4 -5
  135. package/src/telemetry.ts +577 -0
  136. package/src/timer-registry.ts +44 -10
  137. package/src/types.ts +32 -17
  138. package/src/worker/durable-step.ts +976 -0
  139. package/src/worker/index.ts +216 -0
  140. package/src/worker/state-adapter.ts +589 -0
  141. package/src/worker/topological-executor.ts +625 -0
  142. package/src/worker/workflow-builder.ts +871 -0
  143. package/src/worker.ts +2906 -0
  144. package/src/workflow-builder.ts +1068 -0
  145. package/src/workflow.ts +188 -351
  146. package/test/barrier-join.test.ts +32 -24
  147. package/test/cascade-executor.test.ts +9 -16
  148. package/test/cron-parser.test.ts +314 -0
  149. package/test/cron-scheduler.test.ts +291 -0
  150. package/test/database-context.test.ts +770 -0
  151. package/test/db-provider-adapter.test.ts +862 -0
  152. package/test/durable-execution-cloudflare.test.ts +606 -0
  153. package/test/durable-execution-in-process.test.ts +286 -0
  154. package/test/durable-execution.test.ts +247 -0
  155. package/test/e2e/workflow-scenarios.e2e.test.ts +1039 -0
  156. package/test/integration.test.ts +442 -0
  157. package/test/rpc-surface.test.ts +946 -0
  158. package/test/runtime.test.ts +262 -0
  159. package/test/schedule-timer-cleanup.test.ts +30 -21
  160. package/test/send-race-conditions.test.ts +30 -40
  161. package/test/worker/durable-cascade.test.ts +1117 -0
  162. package/test/worker/durable-step.test.ts +723 -0
  163. package/test/worker/topological-executor.test.ts +1240 -0
  164. package/test/worker/workflow-builder.test.ts +1067 -0
  165. package/test/worker.test.ts +608 -0
  166. package/test/workflow-builder.test.ts +1670 -0
  167. package/test/workflow-cron.test.ts +256 -0
  168. package/test/workflow-state-adapter.test.ts +923 -0
  169. package/test/workflow.test.ts +25 -22
  170. package/tsconfig.json +3 -1
  171. package/vitest.config.ts +38 -1
  172. package/vitest.workers.config.ts +44 -0
  173. package/wrangler.jsonc +22 -0
  174. package/.turbo/turbo-test.log +0 -169
  175. package/LICENSE +0 -21
  176. package/src/context.js +0 -83
  177. package/src/every.js +0 -267
  178. package/src/index.js +0 -71
  179. package/src/on.js +0 -79
  180. package/src/send.js +0 -111
  181. package/src/types.js +0 -4
  182. package/src/workflow.js +0 -455
  183. package/test/context.test.js +0 -116
  184. package/test/every.test.js +0 -282
  185. package/test/on.test.js +0 -80
  186. package/test/send.test.js +0 -89
  187. package/test/workflow.test.js +0 -224
  188. package/vitest.config.js +0 -7
package/src/workflow.js DELETED
@@ -1,455 +0,0 @@
1
- /**
2
- * Unified Workflow API
3
- *
4
- * Usage:
5
- * Workflow($ => {
6
- * $.on.Customer.created(async (customer, $) => {
7
- * $.log('Customer created', customer)
8
- * await $.send('Email.welcome', { to: customer.email })
9
- * })
10
- *
11
- * $.every.Monday.at9am(async ($) => {
12
- * $.log('Weekly standup reminder')
13
- * })
14
- * })
15
- */
16
- /**
17
- * Well-known cron patterns for common schedules
18
- */
19
- const KNOWN_PATTERNS = {
20
- second: '* * * * * *',
21
- minute: '* * * * *',
22
- hour: '0 * * * *',
23
- day: '0 0 * * *',
24
- week: '0 0 * * 0',
25
- month: '0 0 1 * *',
26
- year: '0 0 1 1 *',
27
- Monday: '0 0 * * 1',
28
- Tuesday: '0 0 * * 2',
29
- Wednesday: '0 0 * * 3',
30
- Thursday: '0 0 * * 4',
31
- Friday: '0 0 * * 5',
32
- Saturday: '0 0 * * 6',
33
- Sunday: '0 0 * * 0',
34
- weekday: '0 0 * * 1-5',
35
- weekend: '0 0 * * 0,6',
36
- midnight: '0 0 * * *',
37
- noon: '0 12 * * *',
38
- };
39
- /**
40
- * Time suffixes for day-based schedules
41
- */
42
- const TIME_PATTERNS = {
43
- at6am: { hour: 6, minute: 0 },
44
- at7am: { hour: 7, minute: 0 },
45
- at8am: { hour: 8, minute: 0 },
46
- at9am: { hour: 9, minute: 0 },
47
- at10am: { hour: 10, minute: 0 },
48
- at11am: { hour: 11, minute: 0 },
49
- at12pm: { hour: 12, minute: 0 },
50
- atnoon: { hour: 12, minute: 0 },
51
- at1pm: { hour: 13, minute: 0 },
52
- at2pm: { hour: 14, minute: 0 },
53
- at3pm: { hour: 15, minute: 0 },
54
- at4pm: { hour: 16, minute: 0 },
55
- at5pm: { hour: 17, minute: 0 },
56
- at6pm: { hour: 18, minute: 0 },
57
- at7pm: { hour: 19, minute: 0 },
58
- at8pm: { hour: 20, minute: 0 },
59
- at9pm: { hour: 21, minute: 0 },
60
- atmidnight: { hour: 0, minute: 0 },
61
- };
62
- /**
63
- * Combine a day pattern with a time pattern
64
- */
65
- function combineWithTime(baseCron, time) {
66
- const parts = baseCron.split(' ');
67
- parts[0] = String(time.minute);
68
- parts[1] = String(time.hour);
69
- return parts.join(' ');
70
- }
71
- /**
72
- * Parse event string into noun and event
73
- */
74
- export function parseEvent(event) {
75
- const parts = event.split('.');
76
- if (parts.length !== 2) {
77
- return null;
78
- }
79
- const [noun, eventName] = parts;
80
- if (!noun || !eventName) {
81
- return null;
82
- }
83
- return { noun, event: eventName };
84
- }
85
- /**
86
- * Create a workflow with the $ context
87
- *
88
- * @example
89
- * ```ts
90
- * const workflow = Workflow($ => {
91
- * $.on.Customer.created(async (customer, $) => {
92
- * $.log('New customer:', customer.name)
93
- * await $.send('Email.welcome', { to: customer.email })
94
- * })
95
- *
96
- * $.every.hour(async ($) => {
97
- * $.log('Hourly check')
98
- * })
99
- *
100
- * $.every.Monday.at9am(async ($) => {
101
- * $.log('Weekly standup')
102
- * })
103
- *
104
- * $.every('first Monday of the month', async ($) => {
105
- * $.log('Monthly report')
106
- * })
107
- * })
108
- *
109
- * await workflow.start()
110
- * await workflow.send('Customer.created', { name: 'John', email: 'john@example.com' })
111
- * ```
112
- */
113
- export function Workflow(setup, options = {}) {
114
- // Registries for handlers captured during setup
115
- const eventRegistry = [];
116
- const scheduleRegistry = [];
117
- // State
118
- const state = {
119
- context: { ...options.context },
120
- history: [],
121
- };
122
- // Schedule timers
123
- let scheduleTimers = [];
124
- /**
125
- * Add to history
126
- */
127
- const addHistory = (entry) => {
128
- state.history.push({
129
- ...entry,
130
- timestamp: Date.now(),
131
- });
132
- };
133
- /**
134
- * Register an event handler
135
- */
136
- const registerEventHandler = (noun, event, handler) => {
137
- eventRegistry.push({
138
- noun,
139
- event,
140
- handler,
141
- source: handler.toString(),
142
- });
143
- };
144
- /**
145
- * Register a schedule handler
146
- */
147
- const registerScheduleHandler = (interval, handler) => {
148
- scheduleRegistry.push({
149
- interval,
150
- handler,
151
- source: handler.toString(),
152
- });
153
- };
154
- /**
155
- * Create the $.on proxy
156
- */
157
- const createOnProxy = () => {
158
- return new Proxy({}, {
159
- get(_target, noun) {
160
- return new Proxy({}, {
161
- get(_eventTarget, event) {
162
- return (handler) => {
163
- registerEventHandler(noun, event, handler);
164
- };
165
- }
166
- });
167
- }
168
- });
169
- };
170
- /**
171
- * Create the $.every proxy
172
- */
173
- const createEveryProxy = () => {
174
- const handler = {
175
- get(_target, prop) {
176
- const pattern = KNOWN_PATTERNS[prop];
177
- if (pattern) {
178
- const result = (handlerFn) => {
179
- registerScheduleHandler({ type: 'cron', expression: pattern, natural: prop }, handlerFn);
180
- };
181
- return new Proxy(result, {
182
- get(_t, timeKey) {
183
- const time = TIME_PATTERNS[timeKey];
184
- if (time) {
185
- const cron = combineWithTime(pattern, time);
186
- return (handlerFn) => {
187
- registerScheduleHandler({ type: 'cron', expression: cron, natural: `${prop}.${timeKey}` }, handlerFn);
188
- };
189
- }
190
- return undefined;
191
- },
192
- apply(_t, _thisArg, args) {
193
- registerScheduleHandler({ type: 'cron', expression: pattern, natural: prop }, args[0]);
194
- }
195
- });
196
- }
197
- // Plural units (seconds, minutes, hours, days, weeks)
198
- const pluralUnits = {
199
- seconds: 'second',
200
- minutes: 'minute',
201
- hours: 'hour',
202
- days: 'day',
203
- weeks: 'week',
204
- };
205
- if (pluralUnits[prop]) {
206
- return (value) => (handlerFn) => {
207
- registerScheduleHandler({ type: pluralUnits[prop], value, natural: `${value} ${prop}` }, handlerFn);
208
- };
209
- }
210
- return undefined;
211
- },
212
- apply(_target, _thisArg, args) {
213
- const [description, handler] = args;
214
- if (typeof description === 'string' && typeof handler === 'function') {
215
- registerScheduleHandler({ type: 'natural', description }, handler);
216
- }
217
- }
218
- };
219
- return new Proxy(function () { }, handler);
220
- };
221
- /**
222
- * Deliver an event to matching handlers (fire and forget)
223
- */
224
- const deliverEvent = async (event, data) => {
225
- const parsed = parseEvent(event);
226
- if (!parsed) {
227
- console.warn(`Invalid event format: ${event}. Expected Noun.event`);
228
- return;
229
- }
230
- const matching = eventRegistry.filter(h => h.noun === parsed.noun && h.event === parsed.event);
231
- if (matching.length === 0) {
232
- return;
233
- }
234
- await Promise.all(matching.map(async ({ handler }) => {
235
- try {
236
- await handler(data, $);
237
- }
238
- catch (error) {
239
- console.error(`Error in handler for ${event}:`, error);
240
- }
241
- }));
242
- };
243
- /**
244
- * Execute an event and wait for result from first matching handler
245
- */
246
- const executeEvent = async (event, data, durable) => {
247
- const parsed = parseEvent(event);
248
- if (!parsed) {
249
- throw new Error(`Invalid event format: ${event}. Expected Noun.event`);
250
- }
251
- const matching = eventRegistry.filter(h => h.noun === parsed.noun && h.event === parsed.event);
252
- if (matching.length === 0) {
253
- throw new Error(`No handler registered for ${event}`);
254
- }
255
- // Use first matching handler for result
256
- const { handler } = matching[0];
257
- if (durable && options.db) {
258
- // Create action for durability tracking
259
- await options.db.createAction({
260
- actor: 'workflow',
261
- object: event,
262
- action: 'execute',
263
- metadata: { data },
264
- });
265
- }
266
- try {
267
- const result = await handler(data, $);
268
- return result;
269
- }
270
- catch (error) {
271
- if (durable) {
272
- // Could implement retry logic here
273
- console.error(`[workflow] Durable action failed for ${event}:`, error);
274
- }
275
- throw error;
276
- }
277
- };
278
- /**
279
- * Create the $ context
280
- */
281
- const $ = {
282
- async send(event, data) {
283
- addHistory({ type: 'event', name: event, data });
284
- // Record to database if connected (durable)
285
- if (options.db) {
286
- await options.db.recordEvent(event, data);
287
- }
288
- await deliverEvent(event, data);
289
- },
290
- async do(event, data) {
291
- addHistory({ type: 'action', name: `do:${event}`, data });
292
- // Record to database (durable)
293
- if (options.db) {
294
- await options.db.recordEvent(event, data);
295
- }
296
- return executeEvent(event, data, true);
297
- },
298
- async try(event, data) {
299
- addHistory({ type: 'action', name: `try:${event}`, data });
300
- // Non-durable - no database recording
301
- return executeEvent(event, data, false);
302
- },
303
- on: createOnProxy(),
304
- every: createEveryProxy(),
305
- // Direct access to state context
306
- state: state.context,
307
- getState() {
308
- // Return a deep copy to prevent mutation
309
- return {
310
- current: state.current,
311
- context: { ...state.context },
312
- history: [...state.history],
313
- };
314
- },
315
- set(key, value) {
316
- state.context[key] = value;
317
- },
318
- get(key) {
319
- return state.context[key];
320
- },
321
- log(message, data) {
322
- addHistory({ type: 'action', name: 'log', data: { message, data } });
323
- console.log(`[workflow] ${message}`, data ?? '');
324
- },
325
- db: options.db,
326
- };
327
- // Run setup to capture handlers
328
- setup($);
329
- /**
330
- * Start schedule handlers
331
- */
332
- const startSchedules = async () => {
333
- for (const schedule of scheduleRegistry) {
334
- const { interval, handler } = schedule;
335
- let ms = 0;
336
- switch (interval.type) {
337
- case 'second':
338
- ms = (interval.value ?? 1) * 1000;
339
- break;
340
- case 'minute':
341
- ms = (interval.value ?? 1) * 60 * 1000;
342
- break;
343
- case 'hour':
344
- ms = (interval.value ?? 1) * 60 * 60 * 1000;
345
- break;
346
- case 'day':
347
- ms = (interval.value ?? 1) * 24 * 60 * 60 * 1000;
348
- break;
349
- case 'week':
350
- ms = (interval.value ?? 1) * 7 * 24 * 60 * 60 * 1000;
351
- break;
352
- case 'cron':
353
- case 'natural':
354
- // Cron/natural need special handling
355
- console.log(`[workflow] Cron/natural scheduling not yet implemented: ${interval.type === 'cron' ? interval.expression : interval.description}`);
356
- continue;
357
- }
358
- if (ms > 0) {
359
- const timer = setInterval(async () => {
360
- try {
361
- addHistory({ type: 'schedule', name: interval.natural ?? interval.type });
362
- await handler($);
363
- }
364
- catch (error) {
365
- console.error('[workflow] Schedule handler error:', error);
366
- }
367
- }, ms);
368
- scheduleTimers.push(timer);
369
- }
370
- }
371
- };
372
- const instance = {
373
- definition: {
374
- name: 'workflow',
375
- events: eventRegistry,
376
- schedules: scheduleRegistry,
377
- initialContext: options.context,
378
- },
379
- get state() {
380
- return state;
381
- },
382
- $,
383
- async send(event, data) {
384
- await $.send(event, data);
385
- },
386
- async start() {
387
- console.log(`[workflow] Starting with ${eventRegistry.length} event handlers and ${scheduleRegistry.length} schedules`);
388
- await startSchedules();
389
- },
390
- async stop() {
391
- console.log('[workflow] Stopping');
392
- for (const timer of scheduleTimers) {
393
- clearInterval(timer);
394
- }
395
- scheduleTimers = [];
396
- },
397
- };
398
- return instance;
399
- }
400
- /**
401
- * Create an isolated $ context for testing
402
- */
403
- export function createTestContext() {
404
- const emittedEvents = [];
405
- const stateContext = {};
406
- const history = [];
407
- const $ = {
408
- emittedEvents,
409
- async send(event, data) {
410
- emittedEvents.push({ event, data });
411
- },
412
- async do(_event, _data) {
413
- throw new Error('$.do not implemented in test context - register handlers via Workflow()');
414
- },
415
- async try(_event, _data) {
416
- throw new Error('$.try not implemented in test context - register handlers via Workflow()');
417
- },
418
- on: new Proxy({}, {
419
- get() {
420
- return new Proxy({}, {
421
- get() {
422
- return () => { }; // No-op for testing
423
- }
424
- });
425
- }
426
- }),
427
- every: new Proxy(function () { }, {
428
- get() {
429
- return () => () => { }; // No-op for testing
430
- },
431
- apply() { }
432
- }),
433
- state: stateContext,
434
- getState() {
435
- return {
436
- context: { ...stateContext },
437
- history: [...history],
438
- };
439
- },
440
- set(key, value) {
441
- stateContext[key] = value;
442
- },
443
- get(key) {
444
- return stateContext[key];
445
- },
446
- log(message, data) {
447
- console.log(`[test] ${message}`, data ?? '');
448
- },
449
- };
450
- return $;
451
- }
452
- // Also export standalone on/every for import { on, every } usage
453
- export { on, registerEventHandler, getEventHandlers, clearEventHandlers } from './on.js';
454
- export { every, registerScheduleHandler, getScheduleHandlers, clearScheduleHandlers, toCron, intervalToMs, formatInterval, setCronConverter } from './every.js';
455
- export { send } from './send.js';
@@ -1,116 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import { createWorkflowContext, createIsolatedContext } from '../src/context.js';
3
- describe('context - workflow context', () => {
4
- describe('createWorkflowContext', () => {
5
- it('should create a context with all required methods', () => {
6
- const eventBus = { emit: vi.fn() };
7
- const ctx = createWorkflowContext(eventBus);
8
- expect(ctx).toHaveProperty('send');
9
- expect(ctx).toHaveProperty('getState');
10
- expect(ctx).toHaveProperty('set');
11
- expect(ctx).toHaveProperty('get');
12
- expect(ctx).toHaveProperty('log');
13
- });
14
- it('should emit events through the event bus', async () => {
15
- const eventBus = { emit: vi.fn() };
16
- const ctx = createWorkflowContext(eventBus);
17
- await ctx.send('Customer.created', { id: '123' });
18
- expect(eventBus.emit).toHaveBeenCalledWith('Customer.created', { id: '123' });
19
- });
20
- it('should track events in history', async () => {
21
- const eventBus = { emit: vi.fn() };
22
- const ctx = createWorkflowContext(eventBus);
23
- await ctx.send('Customer.created', { id: '123' });
24
- const state = ctx.getState();
25
- expect(state.history).toHaveLength(1);
26
- expect(state.history[0]).toMatchObject({
27
- type: 'event',
28
- name: 'Customer.created',
29
- data: { id: '123' },
30
- });
31
- expect(state.history[0]?.timestamp).toBeGreaterThan(0);
32
- });
33
- it('should store and retrieve context data', () => {
34
- const eventBus = { emit: vi.fn() };
35
- const ctx = createWorkflowContext(eventBus);
36
- ctx.set('userId', '123');
37
- ctx.set('counter', 42);
38
- expect(ctx.get('userId')).toBe('123');
39
- expect(ctx.get('counter')).toBe(42);
40
- expect(ctx.get('nonexistent')).toBeUndefined();
41
- });
42
- it('should return typed values from get', () => {
43
- const eventBus = { emit: vi.fn() };
44
- const ctx = createWorkflowContext(eventBus);
45
- ctx.set('user', { name: 'John', age: 30 });
46
- const user = ctx.get('user');
47
- expect(user?.name).toBe('John');
48
- expect(user?.age).toBe(30);
49
- });
50
- it('should include context data in state', () => {
51
- const eventBus = { emit: vi.fn() };
52
- const ctx = createWorkflowContext(eventBus);
53
- ctx.set('key1', 'value1');
54
- ctx.set('key2', 'value2');
55
- const state = ctx.getState();
56
- expect(state.context).toEqual({
57
- key1: 'value1',
58
- key2: 'value2',
59
- });
60
- });
61
- it('should return a copy of state to prevent mutation', () => {
62
- const eventBus = { emit: vi.fn() };
63
- const ctx = createWorkflowContext(eventBus);
64
- ctx.set('key', 'original');
65
- const state1 = ctx.getState();
66
- state1.context.key = 'mutated';
67
- const state2 = ctx.getState();
68
- expect(state2.context.key).toBe('original');
69
- });
70
- it('should log messages with history tracking', () => {
71
- const eventBus = { emit: vi.fn() };
72
- const ctx = createWorkflowContext(eventBus);
73
- const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => { });
74
- ctx.log('Test message', { extra: 'data' });
75
- expect(consoleSpy).toHaveBeenCalled();
76
- const state = ctx.getState();
77
- expect(state.history).toHaveLength(1);
78
- expect(state.history[0]).toMatchObject({
79
- type: 'action',
80
- name: 'log',
81
- data: { message: 'Test message', data: { extra: 'data' } },
82
- });
83
- consoleSpy.mockRestore();
84
- });
85
- });
86
- describe('createIsolatedContext', () => {
87
- it('should create a context not connected to real event bus', async () => {
88
- const ctx = createIsolatedContext();
89
- // Should not throw
90
- await ctx.send('Test.event', { data: 'test' });
91
- // Should track the event
92
- const emittedEvents = ctx.getEmittedEvents();
93
- expect(emittedEvents).toHaveLength(1);
94
- expect(emittedEvents[0]).toEqual({
95
- event: 'Test.event',
96
- data: { data: 'test' },
97
- });
98
- });
99
- it('should track multiple emitted events', async () => {
100
- const ctx = createIsolatedContext();
101
- await ctx.send('Event1', { a: 1 });
102
- await ctx.send('Event2', { b: 2 });
103
- await ctx.send('Event3', { c: 3 });
104
- const emittedEvents = ctx.getEmittedEvents();
105
- expect(emittedEvents).toHaveLength(3);
106
- });
107
- it('should have all standard context methods', () => {
108
- const ctx = createIsolatedContext();
109
- expect(typeof ctx.send).toBe('function');
110
- expect(typeof ctx.getState).toBe('function');
111
- expect(typeof ctx.set).toBe('function');
112
- expect(typeof ctx.get).toBe('function');
113
- expect(typeof ctx.log).toBe('function');
114
- });
115
- });
116
- });