-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathbase-builder.ts
More file actions
1468 lines (1342 loc) · 49.4 KB
/
base-builder.ts
File metadata and controls
1468 lines (1342 loc) · 49.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, realpath, rename, writeFile } from 'node:fs/promises';
import { basename, dirname, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
import { pluralize, usesVercelWorld } from '@workflow/utils';
import chalk from 'chalk';
import enhancedResolveOriginal from 'enhanced-resolve';
import * as esbuild from 'esbuild';
import { findUp } from 'find-up';
import { glob } from 'tinyglobby';
import {
applySwcTransform,
type WorkflowManifest,
} from './apply-swc-transform.js';
import { createDiscoverEntriesPlugin } from './discover-entries-esbuild-plugin.js';
import { getEsbuildTsconfigOptions } from './esbuild-tsconfig.js';
import { getImportPath } from './module-specifier.js';
import { createNodeModuleErrorPlugin } from './node-module-esbuild-plugin.js';
import { createPseudoPackagePlugin } from './pseudo-package-esbuild-plugin.js';
import { createSwcPlugin } from './swc-esbuild-plugin.js';
import type { WorkflowConfig } from './types.js';
import { extractWorkflowGraphs } from './workflows-extractor.js';
const enhancedResolve = promisify(enhancedResolveOriginal);
const EMIT_SOURCEMAPS_FOR_DEBUGGING =
process.env.WORKFLOW_EMIT_SOURCEMAPS_FOR_DEBUGGING === '1';
/**
* Normalize an array of file paths by appending the `realpath()` of each entry
* (to handle symlinks, e.g. pnpm/workspace layouts) and deduplicating.
*/
async function withRealpaths(entries: string[]): Promise<string[]> {
return Array.from(
new Set(
(
await Promise.all(
entries.map(async (entry) => {
const resolved = await realpath(entry).catch(() => undefined);
return resolved ? [entry, resolved] : [entry];
})
)
).flat()
)
);
}
export interface DiscoveredEntries {
discoveredSteps: Set<string>;
discoveredWorkflows: Set<string>;
discoveredSerdeFiles: Set<string>;
}
/**
* Base class for workflow builders. Provides common build logic for transforming
* workflow source files into deployable bundles using esbuild and SWC.
*
* Subclasses must implement the build() method to define builder-specific logic.
*/
export abstract class BaseBuilder {
protected config: WorkflowConfig;
constructor(config: WorkflowConfig) {
this.config = config;
}
protected get transformProjectRoot(): string {
return this.config.projectRoot || this.config.workingDir;
}
/**
* Whether informational BaseBuilder logs should be printed.
* Subclasses can override this to silence progress logs while keeping warnings/errors.
*/
protected get shouldLogBaseBuilderInfo(): boolean {
return true;
}
protected logBaseBuilderInfo(...args: unknown[]): void {
if (this.shouldLogBaseBuilderInfo) {
console.log(...args);
}
}
private logCreateWorkflowsBundleInfo(...args: unknown[]): void {
if (!this.config.suppressCreateWorkflowsBundleLogs) {
this.logBaseBuilderInfo(...args);
}
}
private logCreateWebhookBundleInfo(...args: unknown[]): void {
if (!this.config.suppressCreateWebhookBundleLogs) {
this.logBaseBuilderInfo(...args);
}
}
private logCreateManifestInfo(...args: unknown[]): void {
if (!this.config.suppressCreateManifestLogs) {
this.logBaseBuilderInfo(...args);
}
}
/**
* When outputting CJS, esbuild replaces `import.meta` with an empty object,
* making `import.meta.url` (and `import.meta.resolve`) undefined. This method
* returns banner code and `define` entries that polyfill them using CJS
* equivalents (`__filename`, `require.resolve`) so user code (e.g. Prisma)
* that relies on `import.meta.url` works correctly in bundled CJS output.
*/
private getCjsImportMetaPolyfill(format: string): {
banner: string;
define: Record<string, string>;
} {
if (format !== 'cjs') return { banner: '', define: {} };
return {
banner:
'var __import_meta_url = typeof __filename !== "undefined" ? require("url").pathToFileURL(__filename).href : undefined;\n' +
'var __import_meta_resolve = typeof require !== "undefined" && typeof __filename !== "undefined" ' +
'? (s) => require("url").pathToFileURL(require.resolve(s)).href : undefined;\n',
define: {
'import.meta.url': '__import_meta_url',
'import.meta.resolve': '__import_meta_resolve',
},
};
}
/**
* When outputting fully-bundled ESM, CJS dependencies that call require()
* for Node.js builtins (e.g. debug → require('tty')) break because esbuild's
* CJS-to-ESM __require shim doesn't have access to a real require function.
* This banner provides one via createRequire so bundled CJS code works in ESM.
*/
private getEsmRequireBanner(format: string): string {
if (format !== 'esm') return '';
return 'import { createRequire as __createRequire } from "node:module";\nvar require = __createRequire(import.meta.url);\n';
}
/**
* Performs the complete build process for workflows.
* Subclasses must implement this to define their specific build steps.
*/
abstract build(): Promise<void>;
/**
* Finds tsconfig.json/jsconfig.json for the project.
* Used by esbuild to properly resolve module imports during bundling.
*/
protected async findTsConfigPath(): Promise<string | undefined> {
const cwd = this.config.workingDir || process.cwd();
return findUp(['tsconfig.json', 'jsconfig.json'], { cwd });
}
/**
* Discovers all source files in the configured directories.
* Searches for TypeScript and JavaScript files while excluding common build
* and dependency directories.
*/
protected async getInputFiles(): Promise<string[]> {
const ignore = [
'**/node_modules/**',
'**/.git/**',
'**/.next/**',
'**/.nuxt/**',
'**/.output/**',
'**/.vercel/**',
'**/.workflow-data/**',
'**/.workflow-vitest/**',
'**/.well-known/workflow/**',
'**/.svelte-kit/**',
'**/.turbo/**',
'**/.cache/**',
'**/.yarn/**',
'**/.pnpm-store/**',
];
// Use relative patterns with `cwd` per directory so that `dot: true`
// applies consistently to both the search pattern *and* the ignore
// patterns. When absolute patterns are used with tinyglobby, the `**`
// in ignore patterns does not match dot-prefixed path segments.
const results = await Promise.all(
this.config.dirs.map((dir) => {
const cwd = resolve(this.config.workingDir, dir);
return glob(['**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}'], {
cwd,
ignore,
absolute: true,
dot: true,
});
})
);
return results.flat();
}
/**
* Caches discovered workflow entries by input array reference.
* Uses WeakMap to allow garbage collection when input arrays are no longer referenced.
* This cache is invalidated automatically when the inputs array reference changes
* (e.g., when files are added/removed during watch mode).
*/
private discoveredEntries: WeakMap<string[], DiscoveredEntries> =
new WeakMap();
protected async discoverEntries(
inputs: string[],
outdir: string,
tsconfigPath?: string
): Promise<DiscoveredEntries> {
const previousResult = this.discoveredEntries.get(inputs);
if (previousResult) {
return previousResult;
}
const state: DiscoveredEntries = {
discoveredSteps: new Set(),
discoveredWorkflows: new Set(),
discoveredSerdeFiles: new Set(),
};
const discoverStart = Date.now();
const effectiveTsconfigPath =
tsconfigPath ?? (await this.findTsConfigPath());
const esbuildTsconfigOptions = await getEsbuildTsconfigOptions(
effectiveTsconfigPath
);
try {
await esbuild.build({
treeShaking: true,
entryPoints: inputs,
plugins: [
createDiscoverEntriesPlugin(state, this.transformProjectRoot),
],
platform: 'node',
write: false,
outdir,
bundle: true,
sourcemap: false,
absWorkingDir: this.config.workingDir,
logLevel: 'silent',
...esbuildTsconfigOptions,
// External packages that should not be bundled during discovery
external: this.config.externalPackages || [],
});
} catch (_) {}
this.logBaseBuilderInfo(
`Discovering workflow directives`,
`${Date.now() - discoverStart}ms`
);
this.discoveredEntries.set(inputs, state);
return state;
}
/**
* Writes debug information to a JSON file for troubleshooting build issues.
* Uses atomic write (temp file + rename) to prevent race conditions when
* multiple builds run concurrently.
*/
private async writeDebugFile(
outfile: string,
debugData: object,
merge?: boolean
): Promise<void> {
const prefix = this.config.debugFilePrefix || '';
const targetPath = `${dirname(outfile)}/${prefix}${basename(outfile)}.debug.json`;
let existing = {};
try {
if (merge) {
try {
const content = await readFile(targetPath, 'utf8');
existing = JSON.parse(content);
} catch (e) {
// File doesn't exist yet or is corrupted - start fresh.
// Don't log error for ENOENT (file not found) as that's expected on first run.
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('Error reading debug file, starting fresh:', e);
}
}
}
const mergedData = JSON.stringify(
{
...existing,
...debugData,
},
null,
2
);
// Write atomically: write to temp file, then rename.
// rename() is atomic on POSIX systems and provides best-effort atomicity on Windows.
// Prevents race conditions where concurrent builds read partially-written files.
const tempPath = `${targetPath}.${randomUUID()}.tmp`;
await writeFile(tempPath, mergedData);
await rename(tempPath, targetPath);
} catch (error: unknown) {
console.warn('Failed to write debug file:', error);
}
}
/**
* Logs and optionally throws on esbuild errors and warnings.
* @param throwOnError - If true, throws an error when esbuild errors are present
*/
private logEsbuildMessages(
result: { errors?: any[]; warnings?: any[] },
phase: string,
throwOnError = true,
options?: {
suppressWarnings?: boolean;
}
): void {
if (result.errors && result.errors.length > 0) {
console.error(`❌ esbuild errors in ${phase}:`);
const errorMessages: string[] = [];
for (const error of result.errors) {
console.error(` ${error.text}`);
errorMessages.push(error.text);
if (error.location) {
const location = ` at ${error.location.file}:${error.location.line}:${error.location.column}`;
console.error(location);
errorMessages.push(location);
}
}
if (throwOnError) {
throw new Error(
`Build failed during ${phase}:\n${errorMessages.join('\n')}`
);
}
}
if (
!options?.suppressWarnings &&
result.warnings &&
result.warnings.length > 0
) {
console.warn(`! esbuild warnings in ${phase}:`);
for (const warning of result.warnings) {
console.warn(` ${warning.text}`);
if (warning.location) {
console.warn(
` at ${warning.location.file}:${warning.location.line}:${warning.location.column}`
);
}
}
}
}
/**
* Converts an absolute file path to a normalized relative path for the manifest.
*/
private getRelativeFilepath(absolutePath: string): string {
const normalizedFile = absolutePath.replace(/\\/g, '/');
const normalizedWorkingDir = this.config.workingDir.replace(/\\/g, '/');
let relativePath = relative(normalizedWorkingDir, normalizedFile).replace(
/\\/g,
'/'
);
// Handle files discovered outside the working directory
if (relativePath.startsWith('../')) {
relativePath = relativePath
.split('/')
.filter((part) => part !== '..')
.join('/');
}
return relativePath;
}
/**
* Creates a bundle for workflow step functions.
* Steps have full Node.js runtime access and handle side effects, API calls, etc.
*
* @param externalizeNonSteps - If true, only bundles step entry points and externalizes other code
* @returns Build context (for watch mode) and the collected workflow manifest
*/
protected async createStepsBundle({
inputFiles,
format = 'esm',
outfile,
externalizeNonSteps,
rewriteTsExtensions,
tsconfigPath,
discoveredEntries,
}: {
tsconfigPath?: string;
inputFiles: string[];
outfile: string;
format?: 'cjs' | 'esm';
externalizeNonSteps?: boolean;
rewriteTsExtensions?: boolean;
discoveredEntries?: DiscoveredEntries;
}): Promise<{
context: esbuild.BuildContext | undefined;
manifest: WorkflowManifest;
}> {
// These need to handle watching for dev to scan for
// new entries and changes to existing ones
const discovered =
discoveredEntries ??
(await this.discoverEntries(inputFiles, dirname(outfile), tsconfigPath));
const stepFiles = [...discovered.discoveredSteps].sort();
const workflowFiles = [...discovered.discoveredWorkflows].sort();
const serdeFiles = [...discovered.discoveredSerdeFiles].sort();
// Include serde files that aren't already step files for cross-context class registration.
// Classes need to be registered in the step bundle so they can be deserialized
// when receiving data from workflows and serialized when returning data to workflows.
const stepFilesSet = new Set(stepFiles);
const serdeOnlyFiles = serdeFiles.filter((f) => !stepFilesSet.has(f));
// log the step files for debugging
await this.writeDebugFile(outfile, {
stepFiles,
workflowFiles,
serdeOnlyFiles,
});
const stepsBundleStart = Date.now();
const workflowManifest: WorkflowManifest = {};
const builtInSteps = 'workflow/internal/builtins';
const resolvedBuiltInSteps = await enhancedResolve(
dirname(outfile),
'workflow/internal/builtins'
).catch((err) => {
throw new Error(
[
chalk.red('Failed to resolve built-in steps sources.'),
`${chalk.yellow.bold('hint:')} run \`${chalk.cyan.italic('npm install workflow')}\` to resolve this issue.`,
'',
`Caused by: ${chalk.red(String(err))}`,
].join('\n')
);
});
// Helper to create import statement from file path
// For workspace/node_modules packages, uses the package name so esbuild
// will resolve through package.json exports with the appropriate conditions
const createImport = (file: string) => {
const { importPath, isPackage } = getImportPath(
file,
this.config.workingDir
);
if (isPackage) {
// Use package name - esbuild will resolve via package.json exports
return `import '${importPath}';`;
}
// Local app file - use relative path
// Normalize both paths to forward slashes before calling relative()
// This is critical on Windows where relative() can produce unexpected results with mixed path formats
const normalizedWorkingDir = this.config.workingDir.replace(/\\/g, '/');
const normalizedFile = file.replace(/\\/g, '/');
// Calculate relative path from working directory to the file
let relativePath = relative(normalizedWorkingDir, normalizedFile).replace(
/\\/g,
'/'
);
// Ensure relative paths start with ./ so esbuild resolves them correctly.
// Paths like ".output/..." are not valid relative specifiers and must
// become "./.output/...".
if (!relativePath.startsWith('./') && !relativePath.startsWith('../')) {
relativePath = `./${relativePath}`;
}
return `import '${relativePath}';`;
};
// Create a virtual entry that imports all files. All step definitions
// will get registered thanks to the swc transform.
const stepImports = stepFiles.map(createImport).join('\n');
// Include serde-only files for class registration side effects
const serdeImports = serdeOnlyFiles.map(createImport).join('\n');
const entryContent = `
// Built in steps
import '${builtInSteps}';
// User steps
${stepImports}
// Serde files for cross-context class registration
${serdeImports}
// API entrypoint
export { stepEntrypoint as POST } from 'workflow/runtime';`;
// Bundle with esbuild and our custom SWC plugin
const entriesToBundle = externalizeNonSteps
? [
...stepFiles,
...serdeFiles,
...(resolvedBuiltInSteps ? [resolvedBuiltInSteps] : []),
]
: undefined;
const normalizedEntriesToBundle = entriesToBundle
? await withRealpaths(entriesToBundle)
: undefined;
const normalizedSideEffectEntries = await withRealpaths([
...stepFiles,
...serdeOnlyFiles,
...(resolvedBuiltInSteps ? [resolvedBuiltInSteps] : []),
]);
const esbuildTsconfigOptions =
await getEsbuildTsconfigOptions(tsconfigPath);
const { banner: importMetaBanner, define: importMetaDefine } =
this.getCjsImportMetaPolyfill(format);
const esmRequireBanner = this.getEsmRequireBanner(format);
const esbuildCtx = await esbuild.context({
banner: {
js: `// biome-ignore-all lint: generated file\n/* eslint-disable */\n${importMetaBanner}${esmRequireBanner}`,
},
stdin: {
contents: entryContent,
resolveDir: this.config.workingDir,
sourcefile: 'virtual-entry.js',
loader: 'js',
},
outfile,
absWorkingDir: this.config.workingDir,
bundle: true,
format,
platform: 'node',
conditions: ['node'],
target: 'es2022',
write: true,
treeShaking: true,
keepNames: true,
minify: false,
jsx: 'preserve',
logLevel: 'error',
// Use tsconfig for path alias resolution.
// For symlinked configs this uses tsconfigRaw to preserve cwd-relative aliases.
...esbuildTsconfigOptions,
define: importMetaDefine,
resolveExtensions: [
'.ts',
'.tsx',
'.mts',
'.cts',
'.js',
'.jsx',
'.mjs',
'.cjs',
],
// Inline source maps for better stack traces in step execution.
// Steps execute in Node.js context and inline sourcemaps ensure we get
// meaningful stack traces with proper file names and line numbers when errors
// occur in deeply nested function calls across multiple files.
sourcemap: 'inline',
plugins: [
// Handle pseudo-packages like 'server-only' and 'client-only' by providing
// empty modules. Must run first to intercept these before other resolution.
createPseudoPackagePlugin(),
createSwcPlugin({
mode: 'step',
entriesToBundle: normalizedEntriesToBundle,
outdir: outfile ? dirname(outfile) : undefined,
projectRoot: this.transformProjectRoot,
workflowManifest,
rewriteTsExtensions,
sideEffectEntries: normalizedSideEffectEntries,
}),
],
// Plugin should catch most things, but this lets users hard override
// if the plugin misses anything that should be externalized
external: ['bun', 'bun:*', ...(this.config.externalPackages || [])],
});
const stepsResult = await esbuildCtx.rebuild();
this.logEsbuildMessages(stepsResult, 'steps bundle creation');
this.logBaseBuilderInfo(
'Created steps bundle',
`${Date.now() - stepsBundleStart}ms`
);
// Handle workflow-only files that may have been tree-shaken from the bundle.
// These files have no steps, so esbuild removes them, but we still need their
// workflow metadata for the manifest. Transform them separately.
const workflowOnlyFiles = workflowFiles.filter(
(f) => !stepFiles.includes(f)
);
await Promise.all(
workflowOnlyFiles.map(async (workflowFile) => {
try {
const source = await readFile(workflowFile, 'utf8');
const relativeFilepath = this.getRelativeFilepath(workflowFile);
const { workflowManifest: fileManifest } = await applySwcTransform(
relativeFilepath,
source,
'workflow',
workflowFile,
this.transformProjectRoot
);
if (fileManifest.workflows) {
workflowManifest.workflows = Object.assign(
workflowManifest.workflows || {},
fileManifest.workflows
);
}
if (fileManifest.classes) {
workflowManifest.classes = Object.assign(
workflowManifest.classes || {},
fileManifest.classes
);
}
} catch (error) {
// Log warning but continue - don't fail build for workflow-only file issues
console.warn(
`Warning: Failed to extract workflow metadata from ${workflowFile}:`,
error instanceof Error ? error.message : String(error)
);
}
})
);
// Create .gitignore in .swc directory
await this.createSwcGitignore();
if (this.config.watch) {
return { context: esbuildCtx, manifest: workflowManifest };
}
await esbuildCtx.dispose();
return { context: undefined, manifest: workflowManifest };
}
/**
* Creates a bundle for workflow orchestration functions.
* Workflows run in a sandboxed VM and coordinate step execution.
*
* @param bundleFinalOutput - If false, skips the final bundling step (used by Next.js)
*/
protected async createWorkflowsBundle({
inputFiles,
format = 'esm',
outfile,
bundleFinalOutput = true,
keepInterimBundleContext = this.config.watch,
tsconfigPath,
discoveredEntries,
}: {
tsconfigPath?: string;
inputFiles: string[];
outfile: string;
format?: 'cjs' | 'esm';
bundleFinalOutput?: boolean;
keepInterimBundleContext?: boolean;
discoveredEntries?: DiscoveredEntries;
}): Promise<{
manifest: WorkflowManifest;
interimBundleCtx?: esbuild.BuildContext;
bundleFinal?: (interimBundleResult: string) => Promise<void>;
}> {
const discovered =
discoveredEntries ??
(await this.discoverEntries(inputFiles, dirname(outfile), tsconfigPath));
const workflowFiles = [...discovered.discoveredWorkflows].sort();
const serdeFiles = [...discovered.discoveredSerdeFiles].sort();
// Include serde files that aren't already workflow files for cross-context class registration.
// Classes need to be registered in the workflow bundle so they can be deserialized
// when receiving data from steps or when serializing data to send to steps.
const workflowFilesSet = new Set(workflowFiles);
const serdeOnlyFiles = serdeFiles.filter((f) => !workflowFilesSet.has(f));
// log the workflow files for debugging
await this.writeDebugFile(outfile, { workflowFiles, serdeOnlyFiles });
// Helper to create import statement from file path
// For packages, uses the package name so esbuild will resolve through
// package.json exports with conditions: ['workflow']
const createImport = (file: string) => {
const { importPath, isPackage } = getImportPath(
file,
this.config.workingDir
);
if (isPackage) {
// Use package name - esbuild will resolve via package.json exports
// and apply the 'workflow' condition
return `import '${importPath}';`;
}
// Local app file - use relative path
// Normalize both paths to forward slashes before calling relative()
// This is critical on Windows where relative() can produce unexpected results with mixed path formats
const normalizedWorkingDir = this.config.workingDir.replace(/\\/g, '/');
const normalizedFile = file.replace(/\\/g, '/');
// Calculate relative path from working directory to the file
let relativePath = relative(normalizedWorkingDir, normalizedFile).replace(
/\\/g,
'/'
);
// Ensure relative paths start with ./ so esbuild resolves them correctly.
// Paths like ".output/..." are not valid relative specifiers and must
// become "./.output/...".
if (!relativePath.startsWith('./') && !relativePath.startsWith('../')) {
relativePath = `./${relativePath}`;
}
return `import '${relativePath}';`;
};
// Create a virtual entry that imports all workflow files
// The SWC plugin in workflow mode emits `globalThis.__private_workflows.set(workflowId, fn)`
// calls directly, so we just need to import the files (Map is initialized via banner)
const workflowImports = workflowFiles.map(createImport).join('\n');
// Include serde-only files for class registration side effects
const serdeImports = serdeOnlyFiles.map(createImport).join('\n');
const imports = serdeImports
? `${workflowImports}\n// Serde files for cross-context class registration\n${serdeImports}`
: workflowImports;
const bundleStartTime = Date.now();
const workflowManifest: WorkflowManifest = {};
const esbuildTsconfigOptions =
await getEsbuildTsconfigOptions(tsconfigPath);
const normalizedWorkflowSideEffectEntries = await withRealpaths([
...workflowFiles,
...serdeOnlyFiles,
]);
// Bundle with esbuild and our custom SWC plugin in workflow mode.
// this bundle will be run inside a vm isolate
const interimBundleCtx = await esbuild.context({
stdin: {
contents: imports,
resolveDir: this.config.workingDir,
sourcefile: 'virtual-entry.js',
loader: 'js',
},
bundle: true,
absWorkingDir: this.config.workingDir,
format: 'cjs', // Runs inside the VM which expects cjs
platform: 'neutral', // The platform is neither node nor browser
mainFields: ['module', 'main'], // To support npm style imports
conditions: ['workflow'], // Allow packages to export 'workflow' compliant versions
target: 'es2022',
write: false,
treeShaking: true,
keepNames: true,
minify: false,
// Initialize the workflow registry at the very top of the bundle
// This must be in banner (not the virtual entry) because esbuild's bundling
// can reorder code, and the .set() calls need the Map to exist first
banner: {
js: 'globalThis.__private_workflows = new Map();',
},
// Inline source maps for better stack traces in workflow VM execution.
// This intermediate bundle is executed via runInContext() in a VM, so we need
// inline source maps to get meaningful stack traces instead of "evalmachine.<anonymous>".
sourcemap: 'inline',
// Use tsconfig for path alias resolution.
// For symlinked configs this uses tsconfigRaw to preserve cwd-relative aliases.
...esbuildTsconfigOptions,
resolveExtensions: [
'.ts',
'.tsx',
'.mts',
'.cts',
'.js',
'.jsx',
'.mjs',
'.cjs',
],
plugins: [
// Handle pseudo-packages like 'server-only' and 'client-only' by providing
// empty modules. Must run first to intercept these before other resolution.
createPseudoPackagePlugin(),
createSwcPlugin({
mode: 'workflow',
projectRoot: this.transformProjectRoot,
workflowManifest,
sideEffectEntries: normalizedWorkflowSideEffectEntries,
}),
// This plugin must run after the swc plugin to ensure dead code elimination
// happens first, preventing false positives on Node.js imports in unused code paths
createNodeModuleErrorPlugin(),
],
// NOTE: We intentionally do NOT use the external option here for workflow bundles.
// When packages are marked external with format: 'cjs', esbuild generates require() calls.
// However, the workflow VM (vm.runInContext) does not have require() defined - it only
// provides module.exports and exports. External packages would fail at runtime with:
// ReferenceError: require is not defined
// Instead, we bundle everything and rely on:
// - createPseudoPackagePlugin() to handle server-only/client-only with empty modules
// - createNodeModuleErrorPlugin() to catch Node.js builtin imports at build time
});
let shouldDisposeInterimBundleCtx = !keepInterimBundleContext;
try {
const interimBundle = await interimBundleCtx.rebuild();
this.logEsbuildMessages(
interimBundle,
'intermediate workflow bundle',
true,
{
suppressWarnings: this.config.suppressCreateWorkflowsBundleWarnings,
}
);
this.logCreateWorkflowsBundleInfo(
'Created intermediate workflow bundle',
`${Date.now() - bundleStartTime}ms`
);
if (this.config.workflowManifestPath) {
const resolvedPath = resolve(
process.cwd(),
this.config.workflowManifestPath
);
let prefix = '';
if (resolvedPath.endsWith('.cjs')) {
prefix = 'module.exports = ';
} else if (
resolvedPath.endsWith('.js') ||
resolvedPath.endsWith('.mjs')
) {
prefix = 'export default ';
}
await mkdir(dirname(resolvedPath), { recursive: true });
await writeFile(
resolvedPath,
prefix + JSON.stringify(workflowManifest, null, 2)
);
}
// Create .gitignore in .swc directory
await this.createSwcGitignore();
if (
!interimBundle.outputFiles ||
interimBundle.outputFiles.length === 0
) {
throw new Error('No output files generated from esbuild');
}
// Serde compliance warnings: check if workflow bundle has Node.js imports
// alongside serde-registered classes (these will fail at runtime in the sandbox)
if (
workflowManifest.classes &&
Object.keys(workflowManifest.classes).length > 0
) {
const { analyzeSerdeCompliance } = await import('./serde-checker.js');
const bundleText = interimBundle.outputFiles[0].text;
const serdeResult = analyzeSerdeCompliance({
sourceCode: '',
workflowCode: bundleText,
manifest: workflowManifest,
});
// De-dupe warnings: group identical issues across classes
const issuesToClasses = new Map<string, Set<string>>();
for (const cls of serdeResult.classes) {
if (!cls.compliant) {
for (const issue of cls.issues) {
let affectedClasses = issuesToClasses.get(issue);
if (!affectedClasses) {
affectedClasses = new Set<string>();
issuesToClasses.set(issue, affectedClasses);
}
affectedClasses.add(cls.className);
}
}
}
for (const [issue, affectedClasses] of issuesToClasses) {
const classNames = [...affectedClasses];
const classLabel =
classNames.length === 1
? `class "${classNames[0]}"`
: `classes ${classNames.map((name) => `"${name}"`).join(', ')}`;
console.warn(
chalk.yellow(`⚠ Serde warning for ${classLabel}: `) + issue
);
}
}
const bundleFinal = async (interimBundle: string) => {
const workflowBundleCode = interimBundle;
const workflowFunctionCode = `// biome-ignore-all lint: generated file
/* eslint-disable */
import { workflowEntrypoint } from 'workflow/runtime';
const workflowCode = \`${workflowBundleCode.replace(/[\\`$]/g, '\\$&')}\`;
export const POST = workflowEntrypoint(workflowCode);`;
// we skip the final bundling step for Next.js so it can bundle itself
if (!bundleFinalOutput) {
if (!outfile) {
throw new Error(`Invariant: missing outfile for workflow bundle`);
}
// Ensure the output directory exists
const outputDir = dirname(outfile);
await mkdir(outputDir, { recursive: true });
// Atomic write: write to temp file then rename to prevent
// file watchers from reading partial file during write
const tempPath = `${outfile}.${randomUUID()}.tmp`;
await writeFile(tempPath, workflowFunctionCode);
await rename(tempPath, outfile);
return;
}
const bundleStartTime = Date.now();
// Now bundle this so we can resolve the @workflow/core dependency
// we could remove this if we do nft tracing or similar instead
const finalEsmRequireBanner = this.getEsmRequireBanner(format);
const finalWorkflowResult = await esbuild.build({
banner: {
js: `// biome-ignore-all lint: generated file\n/* eslint-disable */\n${finalEsmRequireBanner}`,
},
stdin: {
contents: workflowFunctionCode,
resolveDir: this.config.workingDir,
sourcefile: 'virtual-entry.js',
loader: 'js',
},
outfile,
// Source maps for the final workflow bundle wrapper (not important since this code
// doesn't run in the VM - only the intermediate bundle sourcemap is relevant)
sourcemap: EMIT_SOURCEMAPS_FOR_DEBUGGING,
absWorkingDir: this.config.workingDir,
bundle: true,
format,
platform: 'node',
target: 'es2022',
write: true,
keepNames: true,
minify: false,
external: ['@aws-sdk/credential-provider-web-identity'],
});
this.logEsbuildMessages(
finalWorkflowResult,
'final workflow bundle',
true,
{
suppressWarnings: this.config.suppressCreateWorkflowsBundleWarnings,
}
);
this.logCreateWorkflowsBundleInfo(
'Created final workflow bundle',
`${Date.now() - bundleStartTime}ms`
);
};
await bundleFinal(interimBundle.outputFiles[0].text);
if (keepInterimBundleContext) {
shouldDisposeInterimBundleCtx = false;
return {
manifest: workflowManifest,
interimBundleCtx,
bundleFinal,
};
}
return { manifest: workflowManifest };
} catch (error) {
shouldDisposeInterimBundleCtx = true;
throw error;
} finally {
if (shouldDisposeInterimBundleCtx) {
try {
await interimBundleCtx.dispose();
} catch (disposeError) {
console.warn(
'Warning: Failed to dispose workflow bundle context',
disposeError
);
}
}
}
}
/**
* Creates a client library bundle for workflow execution.
* The client library allows importing and calling workflows from application code.
* Only generated if clientBundlePath is specified in config.
*/
protected async createClientLibrary(): Promise<void> {
if (!this.config.clientBundlePath) {
// Silently exit since no client bundle was requested
return;
}
this.logBaseBuilderInfo(
'Generating a client library at',
this.config.clientBundlePath
);
this.logBaseBuilderInfo(
'NOTE: The recommended way to use workflow with a framework like NextJS is using the loader/plugin with webpack/turbobpack/rollup'
);
// Ensure we have the directory for the client bundle