@mastra/temporal 0.0.0 → 0.1.0-alpha.1

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 (55) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE.md +30 -0
  3. package/README.md +104 -2
  4. package/dist/chunk-BF6TR7JX.js +9 -0
  5. package/dist/chunk-BF6TR7JX.js.map +1 -0
  6. package/dist/chunk-DYBSPLCJ.cjs +11 -0
  7. package/dist/chunk-DYBSPLCJ.cjs.map +1 -0
  8. package/dist/index.cjs +3 -946
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.ts +0 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -920
  13. package/dist/index.js.map +1 -1
  14. package/dist/mastra-deployer-UCBGECM5.js +39 -0
  15. package/dist/mastra-deployer-UCBGECM5.js.map +1 -0
  16. package/dist/mastra-deployer-YVT5GB5G.cjs +41 -0
  17. package/dist/mastra-deployer-YVT5GB5G.cjs.map +1 -0
  18. package/dist/mastra-deployer.d.ts +16 -0
  19. package/dist/mastra-deployer.d.ts.map +1 -0
  20. package/dist/plugin.d.ts +13 -15
  21. package/dist/plugin.d.ts.map +1 -1
  22. package/dist/temporal-workflow-runtime.mjs +295 -0
  23. package/dist/transforms/activities.d.ts +4 -3
  24. package/dist/transforms/activities.d.ts.map +1 -1
  25. package/dist/transforms/shared.d.ts +2 -7
  26. package/dist/transforms/shared.d.ts.map +1 -1
  27. package/dist/transforms/temporal-workflow-runtime.d.mts +7 -0
  28. package/dist/transforms/temporal-workflow-runtime.d.mts.map +1 -1
  29. package/dist/transforms/workflows.d.ts +3 -11
  30. package/dist/transforms/workflows.d.ts.map +1 -1
  31. package/dist/worker.cjs +1336 -0
  32. package/dist/worker.cjs.map +1 -0
  33. package/dist/worker.d.ts +2 -0
  34. package/dist/worker.d.ts.map +1 -0
  35. package/dist/worker.js +1310 -0
  36. package/dist/worker.js.map +1 -0
  37. package/package.json +30 -24
  38. package/dist/__tests__/__fixtures__/before/index.d.ts +0 -11
  39. package/dist/__tests__/__fixtures__/before/index.d.ts.map +0 -1
  40. package/dist/__tests__/__fixtures__/before/weather-workflow.d.ts +0 -8
  41. package/dist/__tests__/__fixtures__/before/weather-workflow.d.ts.map +0 -1
  42. package/dist/transforms/__fixtures__/activities/weather-workflow/input.d.ts +0 -8
  43. package/dist/transforms/__fixtures__/activities/weather-workflow/input.d.ts.map +0 -1
  44. package/dist/transforms/__fixtures__/activities/weather-workflow/output.d.ts +0 -3
  45. package/dist/transforms/__fixtures__/activities/weather-workflow/output.d.ts.map +0 -1
  46. package/dist/transforms/__fixtures__/workflow/weather-workflow/input.d.ts +0 -8
  47. package/dist/transforms/__fixtures__/workflow/weather-workflow/input.d.ts.map +0 -1
  48. package/dist/transforms/__fixtures__/workflow/weather-workflow/output.d.ts +0 -2
  49. package/dist/transforms/__fixtures__/workflow/weather-workflow/output.d.ts.map +0 -1
  50. package/dist/webpack-loader.cjs +0 -856
  51. package/dist/webpack-loader.cjs.map +0 -1
  52. package/dist/webpack-loader.d.ts +0 -8
  53. package/dist/webpack-loader.d.ts.map +0 -1
  54. package/dist/webpack-plugin.d.ts +0 -18
  55. package/dist/webpack-plugin.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,50 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var chunkDYBSPLCJ_cjs = require('./chunk-DYBSPLCJ.cjs');
3
4
  var workflows = require('@mastra/core/workflows');
4
- var fs = require('fs');
5
- var promises = require('fs/promises');
6
- var module$1 = require('module');
7
- var path4 = require('path');
8
- var url = require('url');
9
- var plugin = require('@temporalio/plugin');
10
- var generator = require('@babel/generator');
11
- var parser = require('@babel/parser');
12
- var t = require('@babel/types');
13
- var esbuild = require('esbuild');
14
5
 
15
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
17
-
18
- function _interopNamespace(e) {
19
- if (e && e.__esModule) return e;
20
- var n = Object.create(null);
21
- if (e) {
22
- Object.keys(e).forEach(function (k) {
23
- if (k !== 'default') {
24
- var d = Object.getOwnPropertyDescriptor(e, k);
25
- Object.defineProperty(n, k, d.get ? d : {
26
- enumerable: true,
27
- get: function () { return e[k]; }
28
- });
29
- }
30
- });
31
- }
32
- n.default = e;
33
- return Object.freeze(n);
34
- }
35
-
36
- var path4__default = /*#__PURE__*/_interopDefault(path4);
37
- var t__namespace = /*#__PURE__*/_interopNamespace(t);
38
-
39
- // src/workflow.ts
40
-
41
- // src/utils.ts
42
- function toWorkflowType(id) {
43
- const camelCased = id.replace(/[-_]+([a-zA-Z0-9])/g, (_, char) => char.toUpperCase());
44
- return camelCased.endsWith("Workflow") ? camelCased : `${camelCased}Workflow`;
45
- }
46
-
47
- // src/run.ts
48
6
  var TemporalRun = class extends workflows.Run {
49
7
  client;
50
8
  taskQueue;
@@ -58,7 +16,7 @@ var TemporalRun = class extends workflows.Run {
58
16
  const initialState = await this._validateInitialState(args.initialState);
59
17
  await this._validateRequestContext(args.requestContext);
60
18
  try {
61
- const handle = await this.client.workflow.start(toWorkflowType(this.workflowId), {
19
+ const handle = await this.client.workflow.start(chunkDYBSPLCJ_cjs.toWorkflowType(this.workflowId), {
62
20
  taskQueue: this.taskQueue,
63
21
  workflowId: this.runId,
64
22
  args: [
@@ -96,7 +54,7 @@ var TemporalRun = class extends workflows.Run {
96
54
  const input = await this._validateInput(args.inputData);
97
55
  const initialState = await this._validateInitialState(args.initialState);
98
56
  await this._validateRequestContext(args.requestContext);
99
- await this.client.workflow.start(toWorkflowType(this.workflowId), {
57
+ await this.client.workflow.start(chunkDYBSPLCJ_cjs.toWorkflowType(this.workflowId), {
100
58
  taskQueue: this.taskQueue,
101
59
  workflowId: this.runId,
102
60
  args: [
@@ -168,908 +126,7 @@ function init(temporalParams) {
168
126
  createStep: workflows.createStep
169
127
  };
170
128
  }
171
- var parserPlugins = [
172
- "typescript",
173
- "jsx",
174
- "classProperties",
175
- "classPrivateProperties",
176
- "classPrivateMethods",
177
- "topLevelAwait",
178
- "importAttributes",
179
- "decorators-legacy"
180
- ];
181
- function isIdentifierNamed(node, name) {
182
- return t__namespace.isIdentifier(node) && node.name === name;
183
- }
184
- function isTemporalHelperModule(source) {
185
- return typeof source === "string" && /(^|\/)temporal\.(ts|tsx|js|jsx|mts|mjs)?$/.test(source);
186
- }
187
- var strippedExternalModules = /* @__PURE__ */ new Set(["@temporalio/client", "@temporalio/envconfig"]);
188
- function isStrippedExternalModule(source) {
189
- return typeof source === "string" && strippedExternalModules.has(source);
190
- }
191
- function collectImportedNames(statement) {
192
- const names = /* @__PURE__ */ new Set();
193
- for (const specifier of statement.specifiers) {
194
- if (t__namespace.isImportDefaultSpecifier(specifier) || t__namespace.isImportNamespaceSpecifier(specifier) || t__namespace.isImportSpecifier(specifier)) {
195
- if (t__namespace.isIdentifier(specifier.local)) {
196
- names.add(specifier.local.name);
197
- }
198
- }
199
- }
200
- return names;
201
- }
202
- function nodeReferencesName(node, names) {
203
- let found = false;
204
- walk(node, (current) => {
205
- if (t__namespace.isIdentifier(current) && names.has(current.name)) {
206
- found = true;
207
- return false;
208
- }
209
- });
210
- return found;
211
- }
212
- function isWorkflowHelperDestructure(declaration) {
213
- if (!t__namespace.isObjectPattern(declaration.id)) {
214
- return false;
215
- }
216
- return declaration.id.properties.some(
217
- (property) => t__namespace.isObjectProperty(property) && !property.computed && t__namespace.isIdentifier(property.value) && (property.value.name === "createStep" || property.value.name === "createWorkflow")
218
- );
219
- }
220
- function isCreateWorkflowCall(node) {
221
- return t__namespace.isCallExpression(node) && isIdentifierNamed(node.callee, "createWorkflow");
222
- }
223
- function isCreateStepCall(node) {
224
- return t__namespace.isCallExpression(node) && isIdentifierNamed(node.callee, "createStep");
225
- }
226
- function getObjectPropertyName(property) {
227
- if (property.computed) {
228
- return null;
229
- }
230
- if (t__namespace.isIdentifier(property.key)) {
231
- return property.key.name;
232
- }
233
- if (t__namespace.isStringLiteral(property.key)) {
234
- return property.key.value;
235
- }
236
- return null;
237
- }
238
- function walk(node, visitor) {
239
- if (!node) {
240
- return;
241
- }
242
- const result = visitor(node);
243
- if (result === false) {
244
- return;
245
- }
246
- const keys = t__namespace.VISITOR_KEYS[node.type] ?? [];
247
- for (const key of keys) {
248
- const value = node[key];
249
- if (Array.isArray(value)) {
250
- for (const child of value) {
251
- if (child && typeof child.type === "string") {
252
- walk(child, visitor);
253
- }
254
- }
255
- continue;
256
- }
257
- if (value && typeof value.type === "string") {
258
- walk(value, visitor);
259
- }
260
- }
261
- }
262
- function hasCreateWorkflowCall(node) {
263
- let found = false;
264
- walk(node, (current) => {
265
- if (isCreateWorkflowCall(current)) {
266
- found = true;
267
- return false;
268
- }
269
- });
270
- return found;
271
- }
272
- function getStepNameFromCall(node) {
273
- const stepId = getCreateStepId(node);
274
- if (!stepId) {
275
- return null;
276
- }
277
- return stepId.replace(/[^a-zA-Z0-9]+(.)/g, (_match, char) => char.toUpperCase()).replace(/^[^a-zA-Z_$]+/, "").replace(/^(.)/, (char) => char.toLowerCase());
278
- }
279
- function createExportedStepStatement(name, initializer) {
280
- return t__namespace.exportNamedDeclaration(
281
- t__namespace.variableDeclaration("const", [t__namespace.variableDeclarator(t__namespace.identifier(name), t__namespace.cloneNode(initializer, true))])
282
- );
283
- }
284
- function collectInlineCreateSteps(node, seenNames, statements) {
285
- walk(node, (current) => {
286
- if (!isCreateStepCall(current)) {
287
- return;
288
- }
289
- const stepName = getStepNameFromCall(current);
290
- if (!stepName || seenNames.has(stepName)) {
291
- return false;
292
- }
293
- seenNames.add(stepName);
294
- statements.push(createExportedStepStatement(stepName, current));
295
- return false;
296
- });
297
- }
298
- async function transpileModule(sourceText, filePath) {
299
- const loader = path4__default.default.extname(filePath).slice(1) || "js";
300
- const { code } = await esbuild.transform(sourceText, {
301
- loader,
302
- format: "esm",
303
- platform: "node",
304
- target: "node22",
305
- sourcemap: false,
306
- sourcefile: filePath
307
- });
308
- return code ?? "";
309
- }
310
- function getCreateStepId(node) {
311
- if (!node || !isCreateStepCall(node)) {
312
- return null;
313
- }
314
- const [config] = node.arguments;
315
- if (!t__namespace.isObjectExpression(config)) {
316
- return null;
317
- }
318
- for (const property of config.properties) {
319
- if (!t__namespace.isObjectProperty(property) && !t__namespace.isObjectMethod(property)) {
320
- continue;
321
- }
322
- if (getObjectPropertyName(property) !== "id") {
323
- continue;
324
- }
325
- const value = t__namespace.isObjectMethod(property) ? null : property.value;
326
- return t__namespace.isStringLiteral(value) ? value.value : null;
327
- }
328
- return null;
329
- }
330
- function shouldCountIdentifierAsReference(parent, key) {
331
- if (!parent) {
332
- return true;
333
- }
334
- if ((t__namespace.isObjectProperty(parent) || t__namespace.isObjectMethod(parent)) && key === "key" && !parent.computed) {
335
- return false;
336
- }
337
- if (t__namespace.isMemberExpression(parent) && key === "property" && !parent.computed) {
338
- return false;
339
- }
340
- if (t__namespace.isVariableDeclarator(parent) && key === "id") {
341
- return false;
342
- }
343
- if ((t__namespace.isFunctionDeclaration(parent) || t__namespace.isFunctionExpression(parent) || t__namespace.isArrowFunctionExpression(parent)) && key === "params") {
344
- return false;
345
- }
346
- if ((t__namespace.isFunctionDeclaration(parent) || t__namespace.isFunctionExpression(parent) || t__namespace.isClassDeclaration(parent)) && key === "id") {
347
- return false;
348
- }
349
- if ((t__namespace.isImportSpecifier(parent) || t__namespace.isImportDefaultSpecifier(parent) || t__namespace.isImportNamespaceSpecifier(parent)) && (key === "local" || key === "imported")) {
350
- return false;
351
- }
352
- if (t__namespace.isExportSpecifier(parent) && key === "exported") {
353
- return false;
354
- }
355
- if (t__namespace.isLabeledStatement(parent) && key === "label") {
356
- return false;
357
- }
358
- if (t__namespace.isCatchClause(parent) && key === "param") {
359
- return false;
360
- }
361
- if (t__namespace.isRestElement(parent) && key === "argument") {
362
- return false;
363
- }
364
- if (t__namespace.isAssignmentPattern(parent) && key === "left") {
365
- return false;
366
- }
367
- if (t__namespace.isTSPropertySignature(parent) || t__namespace.isTSMethodSignature(parent) || t__namespace.isTSExpressionWithTypeArguments(parent)) {
368
- return false;
369
- }
370
- return true;
371
- }
372
- function collectRuntimeReferencedIdentifiers(node) {
373
- const refs = /* @__PURE__ */ new Set();
374
- const visit = (current, parent, key) => {
375
- if (!current) {
376
- return;
377
- }
378
- if (current.type.startsWith("TS")) {
379
- return;
380
- }
381
- if (t__namespace.isIdentifier(current)) {
382
- if (shouldCountIdentifierAsReference(parent, key)) {
383
- refs.add(current.name);
384
- }
385
- return;
386
- }
387
- for (const visitorKey of t__namespace.VISITOR_KEYS[current.type] ?? []) {
388
- const value = current[visitorKey];
389
- if (Array.isArray(value)) {
390
- value.forEach((child) => {
391
- if (t__namespace.isNode(child)) {
392
- visit(child, current, visitorKey);
393
- }
394
- });
395
- continue;
396
- }
397
- if (t__namespace.isNode(value)) {
398
- visit(value, current, visitorKey);
399
- }
400
- }
401
- };
402
- visit(node, null, null);
403
- return refs;
404
- }
405
- function pruneUnusedTopLevelBindings(statements) {
406
- const bindings = /* @__PURE__ */ new Map();
407
- const liveStatements = /* @__PURE__ */ new Set();
408
- const queue = [];
409
- const markLive = (statementIndex) => {
410
- if (liveStatements.has(statementIndex)) {
411
- return;
412
- }
413
- liveStatements.add(statementIndex);
414
- queue.push(statementIndex);
415
- };
416
- statements.forEach((statement, statementIndex) => {
417
- if (t__namespace.isImportDeclaration(statement)) {
418
- for (const specifier of statement.specifiers) {
419
- bindings.set(specifier.local.name, { refs: /* @__PURE__ */ new Set(), statementIndex });
420
- }
421
- return;
422
- }
423
- if (t__namespace.isVariableDeclaration(statement)) {
424
- for (const declaration of statement.declarations) {
425
- if (t__namespace.isIdentifier(declaration.id)) {
426
- bindings.set(declaration.id.name, {
427
- refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
428
- statementIndex
429
- });
430
- }
431
- }
432
- return;
433
- }
434
- if (t__namespace.isExportNamedDeclaration(statement) && t__namespace.isVariableDeclaration(statement.declaration)) {
435
- for (const declaration of statement.declaration.declarations) {
436
- if (t__namespace.isIdentifier(declaration.id)) {
437
- bindings.set(declaration.id.name, {
438
- refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
439
- statementIndex
440
- });
441
- }
442
- }
443
- markLive(statementIndex);
444
- return;
445
- }
446
- markLive(statementIndex);
447
- });
448
- while (queue.length > 0) {
449
- const statementIndex = queue.pop();
450
- const statement = statements[statementIndex];
451
- if (!statement) {
452
- continue;
453
- }
454
- const refs = /* @__PURE__ */ new Set();
455
- if (t__namespace.isImportDeclaration(statement)) {
456
- continue;
457
- }
458
- if (t__namespace.isVariableDeclaration(statement)) {
459
- for (const declaration of statement.declarations) {
460
- if (declaration.init) {
461
- for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) {
462
- refs.add(ref);
463
- }
464
- }
465
- }
466
- } else if (t__namespace.isExportNamedDeclaration(statement) && t__namespace.isVariableDeclaration(statement.declaration)) {
467
- for (const declaration of statement.declaration.declarations) {
468
- if (declaration.init) {
469
- for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) {
470
- refs.add(ref);
471
- }
472
- }
473
- }
474
- } else {
475
- for (const ref of collectRuntimeReferencedIdentifiers(statement)) {
476
- refs.add(ref);
477
- }
478
- }
479
- for (const ref of refs) {
480
- const binding = bindings.get(ref);
481
- if (binding) {
482
- markLive(binding.statementIndex);
483
- }
484
- }
485
- }
486
- const prunedStatements = [];
487
- statements.forEach((statement, statementIndex) => {
488
- if (!liveStatements.has(statementIndex)) {
489
- return;
490
- }
491
- if (t__namespace.isImportDeclaration(statement)) {
492
- const specifiers = statement.specifiers.filter(
493
- (specifier) => liveStatements.has(bindings.get(specifier.local.name)?.statementIndex ?? -1)
494
- );
495
- if (specifiers.length > 0) {
496
- prunedStatements.push(t__namespace.importDeclaration(specifiers, statement.source));
497
- }
498
- return;
499
- }
500
- if (t__namespace.isVariableDeclaration(statement)) {
501
- const declarations = statement.declarations.filter(
502
- (declaration) => !t__namespace.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1)
503
- );
504
- if (declarations.length > 0) {
505
- prunedStatements.push(t__namespace.variableDeclaration(statement.kind, declarations));
506
- }
507
- return;
508
- }
509
- if (t__namespace.isExportNamedDeclaration(statement) && t__namespace.isVariableDeclaration(statement.declaration)) {
510
- const declarations = statement.declaration.declarations.filter(
511
- (declaration) => !t__namespace.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1)
512
- );
513
- if (declarations.length > 0) {
514
- prunedStatements.push(
515
- t__namespace.exportNamedDeclaration(t__namespace.variableDeclaration(statement.declaration.kind, declarations))
516
- );
517
- }
518
- return;
519
- }
520
- prunedStatements.push(statement);
521
- });
522
- return prunedStatements;
523
- }
524
-
525
- // src/transforms/activities.ts
526
- function collectTemporalActivityBindings(sourceText, filePath) {
527
- const ast = parser.parse(sourceText, {
528
- sourceType: "module",
529
- plugins: parserPlugins,
530
- sourceFilename: filePath
531
- });
532
- const bindings = [];
533
- const seenNames = /* @__PURE__ */ new Set();
534
- const addBinding = (call) => {
535
- const exportName = getStepNameFromCall(call);
536
- const stepId = getCreateStepId(call);
537
- if (!exportName || !stepId || seenNames.has(exportName)) {
538
- return;
539
- }
540
- seenNames.add(exportName);
541
- bindings.push({ exportName, stepId });
542
- };
543
- const collectInlineBindings = (node) => {
544
- walk(node, (current) => {
545
- if (!isCreateStepCall(current)) {
546
- return;
547
- }
548
- addBinding(current);
549
- return false;
550
- });
551
- };
552
- for (const statement of ast.program.body) {
553
- if (t__namespace.isVariableDeclaration(statement) || t__namespace.isExportNamedDeclaration(statement) && t__namespace.isVariableDeclaration(statement.declaration)) {
554
- const declarationStatement = t__namespace.isVariableDeclaration(statement) ? statement : statement.declaration;
555
- for (const declaration of declarationStatement.declarations) {
556
- if (!declaration.init) {
557
- continue;
558
- }
559
- if (isCreateStepCall(declaration.init)) {
560
- addBinding(declaration.init);
561
- continue;
562
- }
563
- if (hasCreateWorkflowCall(declaration.init)) {
564
- collectInlineBindings(declaration.init);
565
- }
566
- }
567
- continue;
568
- }
569
- if (hasCreateWorkflowCall(statement)) {
570
- collectInlineBindings(statement);
571
- }
572
- }
573
- return bindings;
574
- }
575
- function createTemporalActivitiesHelperStatements(mastraImportPath = "./index") {
576
- const helperSource = `
577
- function createStep(args) {
578
- return async (params) => {
579
- const { mastra } = await import(${JSON.stringify(mastraImportPath)});
580
- return args.execute({ ...params, mastra });
581
- };
582
- }
583
- `;
584
- return parser.parse(helperSource, {
585
- sourceType: "module",
586
- plugins: parserPlugins
587
- }).program.body;
588
- }
589
- async function buildTemporalActivitiesModule(sourceText, filePath, options = {}) {
590
- const ast = parser.parse(sourceText, {
591
- sourceType: "module",
592
- plugins: parserPlugins,
593
- sourceFilename: filePath
594
- });
595
- const statements = [];
596
- const seenNames = /* @__PURE__ */ new Set();
597
- const strippedNames = /* @__PURE__ */ new Set();
598
- let helperInserted = false;
599
- const ensureHelperInserted = () => {
600
- if (helperInserted) {
601
- return;
602
- }
603
- statements.push(...createTemporalActivitiesHelperStatements(options.mastraImportPath));
604
- helperInserted = true;
605
- };
606
- for (const statement of ast.program.body) {
607
- if (t__namespace.isImportDeclaration(statement)) {
608
- if (statement.source.value === "@mastra/core/workflows") {
609
- const retainedSpecifiers = statement.specifiers.filter(
610
- (specifier) => !(t__namespace.isImportSpecifier(specifier) && t__namespace.isIdentifier(specifier.imported) && (specifier.imported.name === "createStep" || specifier.imported.name === "createWorkflow"))
611
- );
612
- if (retainedSpecifiers.length > 0) {
613
- statements.push(t__namespace.importDeclaration(retainedSpecifiers, t__namespace.stringLiteral(statement.source.value)));
614
- }
615
- continue;
616
- }
617
- if (isTemporalHelperModule(statement.source.value) || isStrippedExternalModule(statement.source.value)) {
618
- for (const name of collectImportedNames(statement)) {
619
- strippedNames.add(name);
620
- }
621
- continue;
622
- }
623
- statements.push(statement);
624
- continue;
625
- }
626
- if (t__namespace.isFunctionDeclaration(statement) || t__namespace.isClassDeclaration(statement) || t__namespace.isTSTypeAliasDeclaration(statement) || t__namespace.isTSInterfaceDeclaration(statement) || t__namespace.isTSEnumDeclaration(statement)) {
627
- ensureHelperInserted();
628
- statements.push(statement);
629
- continue;
630
- }
631
- if (t__namespace.isExpressionStatement(statement) && nodeReferencesName(statement, strippedNames)) {
632
- continue;
633
- }
634
- ensureHelperInserted();
635
- if (t__namespace.isVariableDeclaration(statement)) {
636
- const declarations = [];
637
- for (const declaration of statement.declarations) {
638
- if (isWorkflowHelperDestructure(declaration)) {
639
- continue;
640
- }
641
- if (declaration.init && nodeReferencesName(declaration.init, strippedNames)) {
642
- if (t__namespace.isIdentifier(declaration.id)) {
643
- strippedNames.add(declaration.id.name);
644
- }
645
- continue;
646
- }
647
- if (!t__namespace.isIdentifier(declaration.id) || !declaration.init) {
648
- declarations.push(declaration);
649
- continue;
650
- }
651
- if (isCreateStepCall(declaration.init)) {
652
- seenNames.add(declaration.id.name);
653
- statements.push(createExportedStepStatement(declaration.id.name, declaration.init));
654
- continue;
655
- }
656
- if (hasCreateWorkflowCall(declaration.init)) {
657
- collectInlineCreateSteps(declaration.init, seenNames, statements);
658
- continue;
659
- }
660
- declarations.push(declaration);
661
- }
662
- if (declarations.length > 0) {
663
- statements.push(
664
- t__namespace.variableDeclaration(
665
- statement.kind,
666
- declarations.map((declaration) => t__namespace.cloneNode(declaration, true))
667
- )
668
- );
669
- }
670
- continue;
671
- }
672
- if (t__namespace.isExportNamedDeclaration(statement) && t__namespace.isVariableDeclaration(statement.declaration)) {
673
- const declarations = [];
674
- for (const declaration of statement.declaration.declarations) {
675
- if (isWorkflowHelperDestructure(declaration)) {
676
- continue;
677
- }
678
- if (declaration.init && nodeReferencesName(declaration.init, strippedNames)) {
679
- if (t__namespace.isIdentifier(declaration.id)) {
680
- strippedNames.add(declaration.id.name);
681
- }
682
- continue;
683
- }
684
- if (!t__namespace.isIdentifier(declaration.id) || !declaration.init) {
685
- declarations.push(declaration);
686
- continue;
687
- }
688
- if (isCreateStepCall(declaration.init)) {
689
- seenNames.add(declaration.id.name);
690
- statements.push(createExportedStepStatement(declaration.id.name, declaration.init));
691
- continue;
692
- }
693
- if (hasCreateWorkflowCall(declaration.init)) {
694
- collectInlineCreateSteps(declaration.init, seenNames, statements);
695
- continue;
696
- }
697
- declarations.push(declaration);
698
- }
699
- if (declarations.length > 0) {
700
- statements.push(
701
- t__namespace.exportNamedDeclaration(
702
- t__namespace.variableDeclaration(
703
- statement.declaration.kind,
704
- declarations.map((declaration) => t__namespace.cloneNode(declaration, true))
705
- )
706
- )
707
- );
708
- }
709
- continue;
710
- }
711
- if (t__namespace.isExpressionStatement(statement) || t__namespace.isExportNamedDeclaration(statement) || t__namespace.isExportDefaultDeclaration(statement)) {
712
- collectInlineCreateSteps(statement, seenNames, statements);
713
- continue;
714
- }
715
- statements.push(statement);
716
- }
717
- ensureHelperInserted();
718
- const transformedSource = generator.generate(t__namespace.file(t__namespace.program(pruneUnusedTopLevelBindings(statements), [], "module")), {
719
- sourceMaps: false
720
- }).code;
721
- return transpileModule(transformedSource, filePath);
722
- }
723
- function getWorkflowImportBindings(program3) {
724
- const bindings = /* @__PURE__ */ new Map();
725
- for (const statement of program3.body) {
726
- if (!t__namespace.isImportDeclaration(statement)) {
727
- continue;
728
- }
729
- for (const specifier of statement.specifiers) {
730
- if (t__namespace.isImportSpecifier(specifier)) {
731
- bindings.set(specifier.local.name, {
732
- exportName: specifier.local.name,
733
- importedName: t__namespace.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value,
734
- source: statement.source.value
735
- });
736
- continue;
737
- }
738
- if (t__namespace.isImportDefaultSpecifier(specifier)) {
739
- bindings.set(specifier.local.name, {
740
- exportName: specifier.local.name,
741
- importedName: "default",
742
- source: statement.source.value
743
- });
744
- }
745
- }
746
- }
747
- return bindings;
748
- }
749
- function getWorkflowEntryBindings(program3) {
750
- const workflowBindings = /* @__PURE__ */ new Set();
751
- walk(program3, (node) => {
752
- if (!t__namespace.isNewExpression(node) || !isIdentifierNamed(node.callee, "Mastra")) {
753
- return;
754
- }
755
- const [config] = node.arguments;
756
- if (!t__namespace.isObjectExpression(config)) {
757
- return;
758
- }
759
- const workflowsProperty = config.properties.find(
760
- (property) => t__namespace.isObjectProperty(property) && getObjectPropertyName(property) === "workflows"
761
- );
762
- if (!workflowsProperty || !t__namespace.isObjectExpression(workflowsProperty.value)) {
763
- return;
764
- }
765
- for (const property of workflowsProperty.value.properties) {
766
- if (!t__namespace.isObjectProperty(property)) {
767
- continue;
768
- }
769
- if (property.shorthand && t__namespace.isIdentifier(property.key)) {
770
- workflowBindings.add(property.key.name);
771
- continue;
772
- }
773
- if (t__namespace.isIdentifier(property.value)) {
774
- workflowBindings.add(property.value.name);
775
- }
776
- }
777
- });
778
- return workflowBindings;
779
- }
780
- fs.readFileSync(new URL("./temporal-workflow-runtime.mjs", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))), "utf8");
781
- async function buildWorkflowEntryModuleFromRegistry(sourceText, filePath, registry) {
782
- const ast = parser.parse(sourceText, {
783
- sourceType: "module",
784
- plugins: parserPlugins,
785
- sourceFilename: filePath
786
- });
787
- const workflowBindings = getWorkflowEntryBindings(ast.program);
788
- const importBindings = getWorkflowImportBindings(ast.program);
789
- const exportStatements = [];
790
- const seenExports = /* @__PURE__ */ new Set();
791
- for (const workflowBinding of workflowBindings) {
792
- const importedBinding = importBindings.get(workflowBinding);
793
- if (!importedBinding) {
794
- throw new Error(`Unable to find an import for workflow '${workflowBinding}' in ${filePath}`);
795
- }
796
- const workflowPath = resolveWorkflowPathSync(importedBinding.source, filePath);
797
- const exportNames = registry.get(workflowPath);
798
- if (!exportNames || exportNames.length === 0) {
799
- throw new Error(`Unable to find registered workflow exports for ${workflowPath}`);
800
- }
801
- for (const exportName of exportNames) {
802
- const exportKey = `${importedBinding.source}:${exportName}`;
803
- if (seenExports.has(exportKey)) {
804
- continue;
805
- }
806
- seenExports.add(exportKey);
807
- exportStatements.push(
808
- t__namespace.exportNamedDeclaration(
809
- null,
810
- [t__namespace.exportSpecifier(t__namespace.identifier(exportName), t__namespace.identifier(exportName))],
811
- t__namespace.stringLiteral(importedBinding.source)
812
- )
813
- );
814
- }
815
- }
816
- return generator.generate(t__namespace.file(t__namespace.program(exportStatements, [], "module")), {
817
- sourceMaps: false
818
- }).code;
819
- }
820
- function getWorkflowImportSpecifiers(sourceText, filePath) {
821
- const ast = parser.parse(sourceText, {
822
- sourceType: "module",
823
- plugins: parserPlugins,
824
- sourceFilename: filePath
825
- });
826
- const workflowBindings = getWorkflowEntryBindings(ast.program);
827
- const importBindings = getWorkflowImportBindings(ast.program);
828
- const workflowSpecifiers = [];
829
- for (const workflowBinding of workflowBindings) {
830
- const importedBinding = importBindings.get(workflowBinding);
831
- if (!importedBinding) {
832
- throw new Error(`Unable to find an import for workflow '${workflowBinding}' in ${filePath}`);
833
- }
834
- workflowSpecifiers.push(importedBinding.source);
835
- }
836
- return [...new Set(workflowSpecifiers)];
837
- }
838
- function getWorkflowPathCandidates(specifier, importerPath) {
839
- const basePath = path4__default.default.resolve(path4__default.default.dirname(importerPath), specifier);
840
- return [
841
- basePath,
842
- `${basePath}.ts`,
843
- `${basePath}.tsx`,
844
- `${basePath}.js`,
845
- `${basePath}.jsx`,
846
- `${basePath}.mts`,
847
- `${basePath}.mjs`,
848
- path4__default.default.join(basePath, "index.ts"),
849
- path4__default.default.join(basePath, "index.tsx"),
850
- path4__default.default.join(basePath, "index.js"),
851
- path4__default.default.join(basePath, "index.jsx"),
852
- path4__default.default.join(basePath, "index.mts"),
853
- path4__default.default.join(basePath, "index.mjs")
854
- ];
855
- }
856
- function resolveWorkflowPathSync(specifier, importerPath) {
857
- for (const candidate of getWorkflowPathCandidates(specifier, importerPath)) {
858
- try {
859
- if (fs.statSync(candidate).isFile()) {
860
- return candidate;
861
- }
862
- } catch {
863
- }
864
- }
865
- throw new Error(`Unable to resolve workflow import '${specifier}' from ${importerPath}`);
866
- }
867
- function resolveWorkflowEntriesSync(sourceText, filePath) {
868
- return getWorkflowImportSpecifiers(sourceText, filePath).map(
869
- (specifier) => resolveWorkflowPathSync(specifier, filePath)
870
- );
871
- }
872
- function getModuleSource(module) {
873
- const source = module.originalSource?.() ?? module._source;
874
- if (!source) {
875
- return null;
876
- }
877
- return source.source().toString();
878
- }
879
- async function writeDebugEntryModule(entryFile, code, debugOutputDir) {
880
- if (!debugOutputDir) {
881
- return;
882
- }
883
- const baseDir = path4__default.default.dirname(entryFile);
884
- const relativePath = path4__default.default.relative(baseDir, entryFile);
885
- const safeRelativePath = relativePath.startsWith("..") ? path4__default.default.basename(entryFile) : relativePath;
886
- const outputPath = path4__default.default.join(debugOutputDir, "modules", safeRelativePath);
887
- await promises.mkdir(path4__default.default.dirname(outputPath), { recursive: true });
888
- await promises.writeFile(outputPath, code, "utf-8");
889
- }
890
- var WorkflowExportRegistry = class {
891
- exportsByFile = /* @__PURE__ */ new Map();
892
- register(filePath, exportNames) {
893
- if (exportNames.length === 0) {
894
- return;
895
- }
896
- this.exportsByFile.set(filePath, [...new Set(exportNames)]);
897
- }
898
- get(filePath) {
899
- return this.exportsByFile.get(filePath);
900
- }
901
- asMap() {
902
- return this.exportsByFile;
903
- }
904
- };
905
- var MastraWorkflowEntryPlugin = class {
906
- constructor(options) {
907
- this.options = options;
908
- }
909
- options;
910
- apply(compiler) {
911
- compiler.hooks.compilation.tap("MastraWorkflowEntryPlugin", (compilation) => {
912
- compilation.hooks.finishModules.tapPromise("MastraWorkflowEntryPlugin", async (modules) => {
913
- const entryModule = [...modules].find(
914
- (module) => "resource" in module && module.resource === this.options.entryFile
915
- );
916
- if (!entryModule) {
917
- return;
918
- }
919
- const source = getModuleSource(entryModule);
920
- if (!source) {
921
- return;
922
- }
923
- const code = await buildWorkflowEntryModuleFromRegistry(
924
- source,
925
- this.options.entryFile,
926
- this.options.registry.asMap()
927
- );
928
- entryModule._source = new compiler.webpack.sources.RawSource(code);
929
- entryModule._ast = null;
930
- entryModule._sourceSizes?.clear?.();
931
- await writeDebugEntryModule(this.options.entryFile, code, this.options.debugOutputDir);
932
- });
933
- });
934
- }
935
- };
936
-
937
- // src/plugin.ts
938
- function getDebugOutputDir() {
939
- return path4__default.default.resolve(process.cwd(), ".mastra/temporal");
940
- }
941
- function getGeneratedActivitiesModulePath(workflowPath) {
942
- const extension = path4__default.default.extname(workflowPath);
943
- const baseName = path4__default.default.basename(workflowPath, extension);
944
- return path4__default.default.join(path4__default.default.dirname(workflowPath), `.${baseName}.temporal.activities.mjs`);
945
- }
946
- function getMastraImportPath(workflowPath, entryFile) {
947
- const relativePath = path4__default.default.relative(path4__default.default.dirname(workflowPath), entryFile);
948
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
949
- }
950
- var WriteWebpackBundleDebugPlugin = class {
951
- constructor(outputDir) {
952
- this.outputDir = outputDir;
953
- }
954
- outputDir;
955
- apply(compiler) {
956
- compiler.hooks.assetEmitted.tapPromise(
957
- "MastraTemporalWriteWebpackBundleDebugPlugin",
958
- async (filename, { content }) => {
959
- const bundleDir = path4__default.default.join(this.outputDir, "bundle");
960
- const targetPath = path4__default.default.join(bundleDir, filename);
961
- await promises.mkdir(path4__default.default.dirname(targetPath), { recursive: true });
962
- await promises.writeFile(targetPath, content);
963
- }
964
- );
965
- }
966
- };
967
- var MastraPlugin = class extends plugin.SimplePlugin {
968
- src;
969
- debugOutputDir;
970
- compiledActivities = /* @__PURE__ */ new Map();
971
- constructor({ src, debug = false }) {
972
- super({
973
- name: "Mastra"
974
- });
975
- this.src = src.startsWith("file://") ? url.fileURLToPath(src) : src;
976
- this.debugOutputDir = debug ? getDebugOutputDir() : null;
977
- }
978
- loadWorkflowActivitiesModule(workflowPath) {
979
- const cachedModule = this.compiledActivities.get(workflowPath);
980
- if (cachedModule) {
981
- return cachedModule;
982
- }
983
- const modulePromise = (async () => {
984
- const sourceText = await promises.readFile(workflowPath, "utf8");
985
- const generatedModulePath = getGeneratedActivitiesModulePath(workflowPath);
986
- const transformedModule = await buildTemporalActivitiesModule(sourceText, workflowPath, {
987
- mastraImportPath: getMastraImportPath(workflowPath, this.src)
988
- });
989
- await promises.writeFile(generatedModulePath, transformedModule);
990
- const importedModule = await import(url.pathToFileURL(generatedModulePath).href);
991
- return importedModule;
992
- })();
993
- this.compiledActivities.set(workflowPath, modulePromise);
994
- return modulePromise;
995
- }
996
- configureWorker(options) {
997
- const entrySource = fs.readFileSync(this.src, "utf8");
998
- const workflowPaths = resolveWorkflowEntriesSync(entrySource, this.src);
999
- const generatedActivities = Object.assign({}, options.activities);
1000
- for (const workflowPath of workflowPaths) {
1001
- const workflowSource = fs.readFileSync(workflowPath, "utf8");
1002
- const activityBindings = collectTemporalActivityBindings(workflowSource, workflowPath);
1003
- for (const binding of activityBindings) {
1004
- if (generatedActivities[binding.stepId]) {
1005
- continue;
1006
- }
1007
- generatedActivities[binding.stepId] = async (...args) => {
1008
- const activityModule = await this.loadWorkflowActivitiesModule(workflowPath);
1009
- const activity = activityModule[binding.exportName];
1010
- if (typeof activity !== "function") {
1011
- throw new Error(`Unable to load activity '${binding.exportName}' from ${workflowPath}`);
1012
- }
1013
- return activity(...args);
1014
- };
1015
- }
1016
- }
1017
- return {
1018
- ...options,
1019
- workflowsPath: this.src,
1020
- activities: generatedActivities
1021
- };
1022
- }
1023
- configureBundler(options) {
1024
- const require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
1025
- const loader = require2.resolve("@mastra/temporal/webpack-loader");
1026
- const existingWebpackConfigHook = options.webpackConfigHook;
1027
- const registry = new WorkflowExportRegistry();
1028
- const webpackConfigHook = (config) => {
1029
- const nextConfig = existingWebpackConfigHook ? existingWebpackConfigHook(config) : config;
1030
- const rules = nextConfig.module?.rules ?? [];
1031
- const plugins = [
1032
- ...nextConfig.plugins ?? [],
1033
- new MastraWorkflowEntryPlugin({
1034
- entryFile: this.src,
1035
- registry,
1036
- debugOutputDir: this.debugOutputDir
1037
- })
1038
- ];
1039
- if (this.debugOutputDir) {
1040
- plugins.push(new WriteWebpackBundleDebugPlugin(this.debugOutputDir));
1041
- }
1042
- return {
1043
- ...nextConfig,
1044
- module: {
1045
- ...nextConfig.module,
1046
- rules: [
1047
- ...rules,
1048
- {
1049
- test: /\.(ts|tsx|js|jsx)$/,
1050
- exclude: /node_modules/,
1051
- use: {
1052
- loader,
1053
- options: {
1054
- entryFile: this.src,
1055
- debugOutputDir: this.debugOutputDir,
1056
- registry
1057
- }
1058
- }
1059
- }
1060
- ]
1061
- },
1062
- plugins
1063
- };
1064
- };
1065
- return {
1066
- ...options,
1067
- webpackConfigHook
1068
- };
1069
- }
1070
- };
1071
129
 
1072
- exports.MastraPlugin = MastraPlugin;
1073
130
  exports.init = init;
1074
131
  //# sourceMappingURL=index.cjs.map
1075
132
  //# sourceMappingURL=index.cjs.map