@mastra/temporal 0.4.6-alpha.8 → 0.4.6

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.
@@ -11,6 +11,12 @@ export class TemporalExecutionEngine {
11
11
 
12
12
  async execute(params) {
13
13
  this.initData = params.input;
14
+ this.executionContext = {
15
+ ...(params.requestContext !== undefined && { requestContext: params.requestContext }),
16
+ ...(params.runId !== undefined && { runId: params.runId }),
17
+ ...(params.resourceId !== undefined && { resourceId: params.resourceId }),
18
+ workflowId: params.workflowId,
19
+ };
14
20
  let result = params.input;
15
21
  const stepResults = {};
16
22
 
@@ -27,18 +33,26 @@ export class TemporalExecutionEngine {
27
33
  };
28
34
  }
29
35
 
36
+ activityParams(inputData, extra = {}) {
37
+ return { inputData, ...extra, ...this.executionContext };
38
+ }
39
+
30
40
  async executeEntry(entry, inputData, stepResults) {
31
41
  switch (entry.type) {
32
42
  case 'step': {
33
43
  log.info('step', { stepId: entry.step.id });
34
- const out = await this.activityHandle[entry.step.id]({ inputData });
44
+ const out = await this.activityHandle[entry.step.id](
45
+ this.activityParams(inputData, { initData: this.initData }),
46
+ );
35
47
  stepResults[entry.step.id] = out;
36
48
  return out;
37
49
  }
38
50
 
39
51
  case 'childWorkflow': {
40
52
  log.info('childWorkflow', { workflowType: entry.workflowType });
41
- const childResult = await executeChild(entry.workflowType, { args: [{ inputData }] });
53
+ const childResult = await executeChild(entry.workflowType, {
54
+ args: [{ inputData, ...this.executionContext }],
55
+ });
42
56
  const out = childResult?.result ?? childResult;
43
57
  stepResults[entry.workflowType] = out;
44
58
  return out;
@@ -46,13 +60,14 @@ export class TemporalExecutionEngine {
46
60
 
47
61
  case 'mapping': {
48
62
  log.info('mapping', { mappingId: entry.id });
49
- const out = await this.activityHandle[entry.id]({ inputData, initData: this.initData });
63
+ const out = await this.activityHandle[entry.id](this.activityParams(inputData, { initData: this.initData }));
50
64
  stepResults[entry.id] = out;
51
65
  return out;
52
66
  }
53
67
 
54
68
  case 'sleep': {
55
- const duration = entry.duration ?? (entry.fn ? await this.activityHandle[entry.fn]({ inputData }) : 0);
69
+ const duration =
70
+ entry.duration ?? (entry.fn ? await this.activityHandle[entry.fn](this.activityParams(inputData)) : 0);
56
71
  log.info('sleep', { id: entry.id, duration });
57
72
  await sleep(duration);
58
73
  return inputData;
@@ -63,7 +78,7 @@ export class TemporalExecutionEngine {
63
78
  entry.date != null
64
79
  ? new Date(entry.date)
65
80
  : entry.fn
66
- ? new Date(await this.activityHandle[entry.fn]({ inputData }))
81
+ ? new Date(await this.activityHandle[entry.fn](this.activityParams(inputData)))
67
82
  : new Date();
68
83
  log.info('sleepUntil', { id: entry.id, date: date.toISOString() });
69
84
  const duration = Math.max(0, date.getTime() - Date.now());
@@ -90,14 +105,16 @@ export class TemporalExecutionEngine {
90
105
  conditions: entry.serializedConditions.map(condition => condition.id),
91
106
  });
92
107
  const condResults = await Promise.all(
93
- entry.serializedConditions.map(condition => this.activityHandle[condition.id]({ inputData })),
108
+ entry.serializedConditions.map(condition =>
109
+ this.activityHandle[condition.id](this.activityParams(inputData)),
110
+ ),
94
111
  );
95
112
  const out = {};
96
113
 
97
114
  for (let i = 0; i < entry.steps.length; i++) {
98
115
  if (condResults[i]) {
99
116
  const stepId = entry.steps[i].step.id;
100
- const res = await this.activityHandle[stepId]({ inputData });
117
+ const res = await this.activityHandle[stepId](this.activityParams(inputData, { initData: this.initData }));
101
118
  out[stepId] = res;
102
119
  stepResults[stepId] = res;
103
120
  }
@@ -111,10 +128,10 @@ export class TemporalExecutionEngine {
111
128
  let current = inputData;
112
129
 
113
130
  while (true) {
114
- current = await this.activityHandle[entry.step.id]({ inputData: current });
131
+ current = await this.activityHandle[entry.step.id](this.activityParams(current, { initData: this.initData }));
115
132
  stepResults[entry.step.id] = current;
116
133
  const shouldContinue = Boolean(
117
- await this.activityHandle[entry.serializedCondition.id]({ inputData: current }),
134
+ await this.activityHandle[entry.serializedCondition.id](this.activityParams(current)),
118
135
  );
119
136
 
120
137
  if (entry.loopType === 'dowhile' ? !shouldContinue : shouldContinue) {
@@ -142,7 +159,9 @@ export class TemporalExecutionEngine {
142
159
  if (i >= items.length) {
143
160
  break;
144
161
  }
145
- results[i] = await this.activityHandle[entry.step.id]({ inputData: items[i] });
162
+ results[i] = await this.activityHandle[entry.step.id](
163
+ this.activityParams(items[i], { initData: this.initData }),
164
+ );
146
165
  }
147
166
  });
148
167
 
@@ -169,6 +188,7 @@ export function createWorkflow(workflowId, options) {
169
188
  workflowId,
170
189
  runId: startArgs?.runId,
171
190
  resourceId: startArgs?.resourceId,
191
+ requestContext: startArgs?.requestContext,
172
192
  graph: {
173
193
  id: workflowId,
174
194
  steps: stepFlow,
@@ -1 +1 @@
1
- {"version":3,"file":"activities.d.ts","sourceRoot":"","sources":["../../src/transforms/activities.ts"],"names":[],"mappings":"AA0BA,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mCAAmC;IAClD,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,uBAAuB,EAAE,CAAC;CAC7C;AAED,wBAAgB,+BAA+B,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,uBAAuB,EAAE,CAmE/G;AAmRD,wBAAsB,6BAA6B,CACjD,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,mCAAmC,CAAC,CAoY9C"}
1
+ {"version":3,"file":"activities.d.ts","sourceRoot":"","sources":["../../src/transforms/activities.ts"],"names":[],"mappings":"AA0BA,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mCAAmC;IAClD,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,uBAAuB,EAAE,CAAC;CAC7C;AAED,wBAAgB,+BAA+B,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,uBAAuB,EAAE,CAmE/G;AA2SD,wBAAsB,6BAA6B,CACjD,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,mCAAmC,CAAC,CAoZ9C"}
@@ -1,5 +1,11 @@
1
1
  export declare class TemporalExecutionEngine {
2
2
  initData: any;
3
+ executionContext: {
4
+ requestContext?: any;
5
+ runId?: any;
6
+ resourceId?: any;
7
+ workflowId: any;
8
+ } | undefined;
3
9
  startToCloseTimeout: any;
4
10
  activityHandle: import("@temporalio/workflow").ActivityInterfaceFor<import("@temporalio/workflow").UntypedActivities>;
5
11
  constructor(params: any);
@@ -10,6 +16,13 @@ export declare class TemporalExecutionEngine {
10
16
  state: any;
11
17
  steps: {};
12
18
  }>;
19
+ activityParams(inputData: any, extra?: {}): {
20
+ requestContext?: any;
21
+ runId?: any;
22
+ resourceId?: any;
23
+ workflowId?: any;
24
+ inputData: any;
25
+ };
13
26
  executeEntry(entry: any, inputData: any, stepResults: any): Promise<any>;
14
27
  }
15
28
  export declare function createWorkflow(workflowId: any, options: any): ((startArgs: any) => Promise<{
@@ -1 +1 @@
1
- {"version":3,"file":"temporal-workflow-runtime.d.mts","sourceRoot":"","sources":["../../src/transforms/temporal-workflow-runtime.mjs"],"names":[],"mappings":"AAEA,qBAAa,uBAAuB;IAU3B,QAAQ;IATf,mBAAmB,MAAC;IACpB,cAAc,wGAAC;IAEf,YAAY,MAAM,KAAA,EAGjB;IAEK,OAAO,CAAC,MAAM,KAAA;;;;;;OAgBnB;IAEK,YAAY,CAAC,KAAK,KAAA,EAAE,SAAS,KAAA,EAAE,WAAW,KAAA,gBA+H/C;CACF;AAED,wBAAgB,cAAc,CAAC,UAAU,KAAA,EAAE,OAAO,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmJjD"}
1
+ {"version":3,"file":"temporal-workflow-runtime.d.mts","sourceRoot":"","sources":["../../src/transforms/temporal-workflow-runtime.mjs"],"names":[],"mappings":"AAEA,qBAAa,uBAAuB;IAU3B,QAAQ;IACR,gBAAgB;;;;;;IAVvB,mBAAmB,MAAC;IACpB,cAAc,wGAAC;IAEf,YAAY,MAAM,KAAA,EAGjB;IAEK,OAAO,CAAC,MAAM,KAAA;;;;;;OAsBnB;IAED,cAAc,CAAC,SAAS,KAAA,EAAE,KAAK,KAAK;;;;;;MAEnC;IAEK,YAAY,CAAC,KAAK,KAAA,EAAE,SAAS,KAAA,EAAE,WAAW,KAAA,gBAwI/C;CACF;AAED,wBAAgB,cAAc,CAAC,UAAU,KAAA,EAAE,OAAO,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoJjD"}
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.d.ts","sourceRoot":"","sources":["../../src/transforms/workflows.ts"],"names":[],"mappings":"AAufA,MAAM,WAAW,4BAA4B;CAE5C;AAED,MAAM,WAAW,sBAAsB;IACrC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,sBAAsB,EAAE,CAAC;CACrC;AAyUD;;;;;GAKG;AACH,wBAAsB,2BAA2B,CAC/C,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CAwCjC"}
1
+ {"version":3,"file":"workflows.d.ts","sourceRoot":"","sources":["../../src/transforms/workflows.ts"],"names":[],"mappings":"AAwfA,MAAM,WAAW,4BAA4B;CAE5C;AAED,MAAM,WAAW,sBAAsB;IACrC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,sBAAsB,EAAE,CAAC;CACrC;AA+UD;;;;;GAKG;AACH,wBAAsB,2BAA2B,CAC/C,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CAsDjC"}
package/dist/worker.cjs CHANGED
@@ -32,6 +32,7 @@ let _babel_parser = require("@babel/parser");
32
32
  let _babel_types = require("@babel/types");
33
33
  _babel_types = __toESM(_babel_types, 1);
34
34
  let rollup = require("rollup");
35
+ let module$1 = require("module");
35
36
  //#region src/transforms/shared.ts
36
37
  const parserPlugins = [
37
38
  "typescript",
@@ -349,7 +350,7 @@ function collectTopLevelBindingNames(program) {
349
350
  for (const statement of program.body) for (const name of Object.keys(_babel_types.getBindingIdentifiers(statement))) bindings.add(name);
350
351
  return bindings;
351
352
  }
352
- function createMappingActivityStatements(workflowExpression, filePath, staticFunctionBindings, usedExportNames, addBinding) {
353
+ function createMappingActivityStatements(workflowExpression, filePath, staticFunctionBindings, usedExportNames, requestContextClassName, addBinding) {
353
354
  const chain = parseWorkflowChain$1(workflowExpression);
354
355
  if (!chain) return [];
355
356
  const workflowId = getStaticWorkflowId(chain.createWorkflowCall, filePath);
@@ -366,8 +367,23 @@ function createMappingActivityStatements(workflowExpression, filePath, staticFun
366
367
  let exportSuffix = 1;
367
368
  while (usedExportNames.has(exportName)) exportName = `${baseExportName}${exportSuffix++}`;
368
369
  usedExportNames.add(exportName);
369
- const params = _babel_types.objectPattern([_babel_types.objectProperty(_babel_types.identifier("inputData"), _babel_types.identifier("inputData"), false, true), _babel_types.objectProperty(_babel_types.identifier("initData"), _babel_types.identifier("initData"), false, true)]);
370
- const callbackContext = _babel_types.objectExpression([_babel_types.objectProperty(_babel_types.identifier("inputData"), _babel_types.identifier("inputData"), false, true), _babel_types.objectProperty(_babel_types.identifier("getInitData"), _babel_types.arrowFunctionExpression([], _babel_types.identifier("initData")))]);
370
+ const contextNames = [
371
+ "requestContext",
372
+ "runId",
373
+ "resourceId",
374
+ "workflowId"
375
+ ];
376
+ const params = _babel_types.objectPattern([
377
+ _babel_types.objectProperty(_babel_types.identifier("inputData"), _babel_types.identifier("inputData"), false, true),
378
+ _babel_types.objectProperty(_babel_types.identifier("initData"), _babel_types.identifier("initData"), false, true),
379
+ ...contextNames.map((name) => _babel_types.objectProperty(_babel_types.identifier(name), _babel_types.identifier(name), false, true))
380
+ ]);
381
+ const callbackContext = _babel_types.objectExpression([
382
+ _babel_types.objectProperty(_babel_types.identifier("inputData"), _babel_types.identifier("inputData"), false, true),
383
+ _babel_types.objectProperty(_babel_types.identifier("getInitData"), _babel_types.arrowFunctionExpression([], _babel_types.identifier("initData"))),
384
+ _babel_types.objectProperty(_babel_types.identifier("requestContext"), _babel_types.newExpression(_babel_types.identifier(requestContextClassName), [_babel_types.identifier("requestContext")])),
385
+ ...contextNames.filter((name) => name !== "requestContext").map((name) => _babel_types.objectProperty(_babel_types.identifier(name), _babel_types.identifier(name), false, true))
386
+ ]);
371
387
  const callbackExpression = _babel_types.cloneNode(callback, true);
372
388
  const body = _babel_types.callExpression(callbackExpression, [callbackContext]);
373
389
  statements.push(_babel_types.exportNamedDeclaration(_babel_types.variableDeclaration("const", [_babel_types.variableDeclarator(_babel_types.identifier(exportName), _babel_types.arrowFunctionExpression([params], body, true))])));
@@ -406,27 +422,38 @@ function hasLocalMastraBinding(ast) {
406
422
  return declaration.declarations.some((declarator) => _babel_types.isIdentifier(declarator.id, { name: "mastra" }));
407
423
  });
408
424
  }
409
- function createTemporalActivitiesHelperStatements(mastraImportPath, hasMastraBinding) {
410
- return (0, _babel_parser.parse)(mastraImportPath ? `
411
- function createStep(args) {
412
- return async (params) => {
413
- const { mastra } = await import(${JSON.stringify(mastraImportPath)});
414
- return args.execute({ ...params, mastra });
415
- };
416
- }
417
- ` : hasMastraBinding ? `
418
- function createStep(args) {
419
- return async (params) => {
420
- return args.execute({ ...params, mastra });
421
- };
422
- }
423
- ` : `
424
- function createStep(args) {
425
- return async (params) => {
426
- return args.execute(params);
427
- };
428
- }
429
- `, {
425
+ function createTemporalActivitiesHelperStatements(mastraImportPath, hasMastraBinding, requestContextClassName) {
426
+ return (0, _babel_parser.parse)(`
427
+ function withRequestContext(params) {
428
+ const { requestContext, initData, ...rest } = params;
429
+ return {
430
+ ...rest,
431
+ requestContext: new ${requestContextClassName}(requestContext),
432
+ getInitData: () => initData,
433
+ };
434
+ }
435
+
436
+ ${mastraImportPath ? `
437
+ function createStep(args) {
438
+ return async (params) => {
439
+ const { mastra } = await import(${JSON.stringify(mastraImportPath)});
440
+ return args.execute({ ...withRequestContext(params), mastra });
441
+ };
442
+ }
443
+ ` : hasMastraBinding ? `
444
+ function createStep(args) {
445
+ return async (params) => {
446
+ return args.execute({ ...withRequestContext(params), mastra });
447
+ };
448
+ }
449
+ ` : `
450
+ function createStep(args) {
451
+ return async (params) => {
452
+ return args.execute(withRequestContext(params));
453
+ };
454
+ }
455
+ `}
456
+ `, {
430
457
  sourceType: "module",
431
458
  plugins: parserPlugins
432
459
  }).program.body;
@@ -458,19 +485,23 @@ async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputF
458
485
  plugins: parserPlugins,
459
486
  sourceFilename: id
460
487
  });
461
- const statements = [];
488
+ const usedExportNames = collectTopLevelBindingNames(ast.program);
489
+ let requestContextClassName = "TemporalRequestContext";
490
+ let requestContextSuffix = 1;
491
+ while (usedExportNames.has(requestContextClassName)) requestContextClassName = `TemporalRequestContext${requestContextSuffix++}`;
492
+ usedExportNames.add(requestContextClassName);
493
+ const statements = [_babel_types.importDeclaration([_babel_types.importSpecifier(_babel_types.identifier(requestContextClassName), _babel_types.identifier("RequestContext"))], _babel_types.stringLiteral("@mastra/core/di"))];
462
494
  const seenNames = /* @__PURE__ */ new Set();
463
495
  const strippedNames = /* @__PURE__ */ new Set();
464
496
  const workflowBindingNames = collectWorkflowBindingNames(ast);
465
497
  const stepFactoryBindings = collectCreateStepFactoryBindings(ast.program);
466
498
  const staticFunctionBindings = collectStaticFunctionBindings(ast.program);
467
- const usedExportNames = collectTopLevelBindingNames(ast.program);
468
499
  const sourceFilePath = id;
469
500
  const hasMastraBinding = hasLocalMastraBinding(ast);
470
501
  let helperInserted = false;
471
502
  const ensureHelperInserted = () => {
472
503
  if (helperInserted) return;
473
- statements.push(...createTemporalActivitiesHelperStatements(null, hasMastraBinding));
504
+ statements.push(...createTemporalActivitiesHelperStatements(null, hasMastraBinding, requestContextClassName));
474
505
  helperInserted = true;
475
506
  };
476
507
  for (const statement of ast.program.body) {
@@ -526,7 +557,7 @@ async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputF
526
557
  if (hasCreateWorkflowCall(declaration.init)) {
527
558
  workflowBindingNames.add(declaration.id.name);
528
559
  strippedNames.add(declaration.id.name);
529
- statements.push(...createMappingActivityStatements(declaration.init, sourceFilePath, staticFunctionBindings, usedExportNames, addGeneratedActivityBinding));
560
+ statements.push(...createMappingActivityStatements(declaration.init, sourceFilePath, staticFunctionBindings, usedExportNames, requestContextClassName, addGeneratedActivityBinding));
530
561
  collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
531
562
  continue;
532
563
  }
@@ -566,7 +597,7 @@ async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputF
566
597
  if (hasCreateWorkflowCall(declaration.init)) {
567
598
  workflowBindingNames.add(declaration.id.name);
568
599
  strippedNames.add(declaration.id.name);
569
- statements.push(...createMappingActivityStatements(declaration.init, sourceFilePath, staticFunctionBindings, usedExportNames, addGeneratedActivityBinding));
600
+ statements.push(...createMappingActivityStatements(declaration.init, sourceFilePath, staticFunctionBindings, usedExportNames, requestContextClassName, addGeneratedActivityBinding));
570
601
  collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
571
602
  continue;
572
603
  }
@@ -901,6 +932,10 @@ function getCommittedWorkflowName(statement) {
901
932
  if (!_babel_types.isCallExpression(expression) || !_babel_types.isMemberExpression(expression.callee) || expression.callee.computed || !isIdentifierNamed(expression.callee.property, "commit") || !_babel_types.isIdentifier(expression.callee.object)) return null;
902
933
  return expression.callee.object.name;
903
934
  }
935
+ const nodeBuiltinModules = new Set(module$1.builtinModules.flatMap((moduleName) => [moduleName, `node:${moduleName}`]));
936
+ function isNodeBuiltinModule(moduleId) {
937
+ return nodeBuiltinModules.has(moduleId);
938
+ }
904
939
  function createWorkflowTransformState(program, filePath) {
905
940
  return {
906
941
  statements: [...createTemporalWorkflowHelperStatements()],
@@ -1060,14 +1095,16 @@ async function buildTemporalWorkflowModule(entryFile, outputDirectory, outputFil
1060
1095
  }]
1061
1096
  });
1062
1097
  try {
1063
- const baseName = (0, path.basename)(outputFileName);
1064
- const { output } = await bundle.write({
1098
+ const outputOptions = {
1065
1099
  dir: outputDirectory,
1066
1100
  entryFileNames: outputFileName,
1067
- chunkFileNames: `${baseName}-[hash].mjs`,
1101
+ chunkFileNames: `${(0, path.basename)(outputFileName)}-[hash].mjs`,
1068
1102
  format: "esm",
1069
1103
  sourcemap: "inline"
1070
- });
1104
+ };
1105
+ const forbiddenImport = (await bundle.generate(outputOptions)).output.filter((output) => output.type === "chunk").flatMap((chunk) => [...chunk.imports, ...chunk.dynamicImports]).find(isNodeBuiltinModule);
1106
+ if (forbiddenImport) throw new Error(`Temporal workflow bundle cannot depend on Node.js builtin '${forbiddenImport}'. Move the dependency into an activity or remove it from workflow initialization.`);
1107
+ const { output } = await bundle.write(outputOptions);
1071
1108
  return { outputPath: (0, path.join)(outputDirectory, output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName) };
1072
1109
  } finally {
1073
1110
  await bundle.close();