@workflow/next 5.0.0-beta.4 → 5.0.0-beta.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.
@@ -8,6 +8,7 @@ const node_fs_1 = require("node:fs");
8
8
  const promises_1 = require("node:fs/promises");
9
9
  const node_path_1 = require("node:path");
10
10
  const watchpack_1 = __importDefault(require("watchpack"));
11
+ const socket_server_js_1 = require("./socket-server.js");
11
12
  let CachedNextBuilderEager;
12
13
  // Create the eager Next builder dynamically by extending the ESM BaseBuilder.
13
14
  // Exported as getNextBuilderEager() to allow CommonJS modules to import from
@@ -16,16 +17,19 @@ async function getNextBuilderEager() {
16
17
  if (CachedNextBuilderEager) {
17
18
  return CachedNextBuilderEager;
18
19
  }
19
- const { BaseBuilder: BaseBuilderClass, STEP_QUEUE_TRIGGER, WORKFLOW_QUEUE_TRIGGER,
20
+ const { BaseBuilder: BaseBuilderClass, WORKFLOW_QUEUE_TRIGGER,
20
21
  // biome-ignore lint/security/noGlobalEval: Need to use eval here to avoid TypeScript from transpiling the import statement into `require()`
21
22
  } = (await eval('import("@workflow/builders")'));
22
23
  class NextBuilder extends BaseBuilderClass {
23
24
  async build() {
25
+ // Eager mode never starts a discovery socket server, so any leftover
26
+ // workflow-socket.json is from a previous deferred-mode build and
27
+ // would make the webpack loader connect to a dead port.
28
+ await (0, socket_server_js_1.cleanupStaleSocketInfoFiles)((0, node_path_1.join)(this.config.workingDir, this.config.distDir || '.next'));
24
29
  const outputDir = await this.findAppDirectory();
25
30
  const workflowGeneratedDir = (0, node_path_1.join)(outputDir, '.well-known/workflow/v1');
26
31
  // Ensure output directories exist
27
32
  await (0, promises_1.mkdir)(workflowGeneratedDir, { recursive: true });
28
- // ignore the generated assets
29
33
  await (0, promises_1.writeFile)((0, node_path_1.join)(workflowGeneratedDir, '.gitignore'), '*');
30
34
  const inputFiles = await this.getInputFiles();
31
35
  const tsconfigPath = await this.findTsConfigPath();
@@ -34,49 +38,42 @@ async function getNextBuilderEager() {
34
38
  workflowGeneratedDir,
35
39
  tsconfigPath,
36
40
  };
37
- const { manifest: stepsManifest, context: stepsBuildContext } = await this.buildStepsFunction(options);
38
- const workflowsBundle = await this.buildWorkflowsFunction(options);
41
+ // V2: Build combined route (replaces separate step + flow routes)
42
+ const combinedResult = await this.buildCombinedFunction(options);
39
43
  await this.buildWebhookRoute({ workflowGeneratedDir });
40
- // Merge manifests from both bundles
41
- const manifest = {
42
- steps: { ...stepsManifest.steps, ...workflowsBundle?.manifest?.steps },
43
- workflows: {
44
- ...stepsManifest.workflows,
45
- ...workflowsBundle?.manifest?.workflows,
46
- },
47
- classes: {
48
- ...stepsManifest.classes,
49
- ...workflowsBundle?.manifest?.classes,
50
- },
44
+ const writeManifest = async (sourceManifest) => {
45
+ const manifest = {
46
+ steps: { ...sourceManifest?.steps },
47
+ workflows: { ...sourceManifest?.workflows },
48
+ classes: { ...sourceManifest?.classes },
49
+ };
50
+ // Write manifest
51
+ const workflowBundlePath = (0, node_path_1.join)(workflowGeneratedDir, 'flow/route.js');
52
+ const manifestJson = await this.createManifest({
53
+ workflowBundlePath,
54
+ manifestDir: workflowGeneratedDir,
55
+ manifest,
56
+ });
57
+ // Expose manifest as a static file when WORKFLOW_PUBLIC_MANIFEST=1.
58
+ if (this.shouldExposePublicManifest && manifestJson) {
59
+ const publicManifestDir = (0, node_path_1.join)(this.config.workingDir, 'public/.well-known/workflow/v1');
60
+ await (0, promises_1.mkdir)(publicManifestDir, { recursive: true });
61
+ await (0, promises_1.copyFile)((0, node_path_1.join)(workflowGeneratedDir, 'manifest.json'), (0, node_path_1.join)(publicManifestDir, 'manifest.json'));
62
+ }
51
63
  };
52
- // Write unified manifest to workflow generated directory
53
- const workflowBundlePath = (0, node_path_1.join)(workflowGeneratedDir, 'flow/route.js');
54
- const manifestJson = await this.createManifest({
55
- workflowBundlePath,
56
- manifestDir: workflowGeneratedDir,
57
- manifest,
58
- });
59
- // Expose manifest as a static file when WORKFLOW_PUBLIC_MANIFEST=1.
60
- // Next.js serves files from public/ at the root URL.
61
- if (this.shouldExposePublicManifest && manifestJson) {
62
- const publicManifestDir = (0, node_path_1.join)(this.config.workingDir, 'public/.well-known/workflow/v1');
63
- await (0, promises_1.mkdir)(publicManifestDir, { recursive: true });
64
- await (0, promises_1.copyFile)((0, node_path_1.join)(workflowGeneratedDir, 'manifest.json'), (0, node_path_1.join)(publicManifestDir, 'manifest.json'));
65
- }
64
+ await writeManifest(combinedResult?.manifest);
66
65
  await this.writeFunctionsConfig(outputDir);
67
66
  if (this.config.watch) {
68
- if (!stepsBuildContext) {
67
+ // TODO: implement watch mode for combined bundle
68
+ // For now, fall back to full rebuild on file changes
69
+ let stepsCtx = combinedResult?.stepsContext;
70
+ if (!stepsCtx) {
69
71
  throw new Error('Invariant: expected steps build context in watch mode');
70
72
  }
71
- if (!workflowsBundle?.interimBundleCtx ||
72
- !workflowsBundle?.bundleFinal) {
73
- throw new Error('Invariant: expected workflows bundle in watch mode');
74
- }
75
- let stepsCtx = stepsBuildContext;
76
- // These are safe to assert as non-null because we checked above
73
+ // Use stepsCtx for the watch rebuild (workflow interim ctx from combined)
77
74
  let workflowsCtx = {
78
- interimBundleCtx: workflowsBundle.interimBundleCtx,
79
- bundleFinal: workflowsBundle.bundleFinal,
75
+ interimBundleCtx: combinedResult?.interimBundleCtx,
76
+ bundleFinal: combinedResult?.bundleFinal,
80
77
  };
81
78
  const normalizePath = (pathname) => pathname.replace(/\\/g, '/');
82
79
  const knownFiles = new Set();
@@ -152,21 +149,20 @@ async function getNextBuilderEager() {
152
149
  const newInputFiles = await this.getInputFiles();
153
150
  options.inputFiles = newInputFiles;
154
151
  await stepsCtx.dispose();
155
- const { context: newStepsCtx } = await this.buildStepsFunction(options);
156
- if (!newStepsCtx) {
152
+ await workflowsCtx.interimBundleCtx.dispose();
153
+ const newCombined = await this.buildCombinedFunction(options);
154
+ if (!newCombined?.stepsContext) {
157
155
  throw new Error('Invariant: expected steps build context after rebuild');
158
156
  }
159
- stepsCtx = newStepsCtx;
160
- await workflowsCtx.interimBundleCtx.dispose();
161
- const newWorkflowsCtx = await this.buildWorkflowsFunction(options);
162
- if (!newWorkflowsCtx?.interimBundleCtx ||
163
- !newWorkflowsCtx?.bundleFinal) {
157
+ stepsCtx = newCombined.stepsContext;
158
+ if (!newCombined?.interimBundleCtx || !newCombined?.bundleFinal) {
164
159
  throw new Error('Invariant: expected workflows bundle context after rebuild');
165
160
  }
166
161
  workflowsCtx = {
167
- interimBundleCtx: newWorkflowsCtx.interimBundleCtx,
168
- bundleFinal: newWorkflowsCtx.bundleFinal,
162
+ interimBundleCtx: newCombined.interimBundleCtx,
163
+ bundleFinal: newCombined.bundleFinal,
169
164
  };
165
+ await writeManifest(newCombined.manifest);
170
166
  };
171
167
  const logBuildMessages = (result, label) => {
172
168
  const logByType = (messages, method) => {
@@ -292,46 +288,31 @@ async function getNextBuilderEager() {
292
288
  if (process.env.NODE_ENV === 'development') {
293
289
  return;
294
290
  }
291
+ // V2 combined config: single trigger handles both workflow and step execution.
292
+ // The step route no longer needs its own trigger since steps are executed
293
+ // inline by the combined handler or queued back to __wkf_workflow_* with stepId.
295
294
  const generatedConfig = {
296
295
  version: '0',
297
- steps: {
298
- maxDuration: 'max',
299
- experimentalTriggers: [STEP_QUEUE_TRIGGER],
300
- },
301
296
  workflows: {
302
297
  maxDuration: 'max',
303
298
  experimentalTriggers: [WORKFLOW_QUEUE_TRIGGER],
304
299
  },
305
300
  };
306
- // We write this file to the generated directory for
307
- // the Next.js builder to consume
308
301
  await (0, promises_1.writeFile)((0, node_path_1.join)(outputDir, '.well-known/workflow/v1/config.json'), JSON.stringify(generatedConfig, null, 2));
309
302
  }
310
- async buildStepsFunction({ inputFiles, workflowGeneratedDir, tsconfigPath, }) {
311
- // Create steps bundle
312
- const stepsRouteDir = (0, node_path_1.join)(workflowGeneratedDir, 'step');
313
- await (0, promises_1.mkdir)(stepsRouteDir, { recursive: true });
314
- return await this.createStepsBundle({
315
- // If any dynamic requires are used when bundling with ESM
316
- // esbuild will create a too dynamic wrapper around require
317
- // which turbopack/webpack fail to analyze. If we externalize
318
- // correctly this shouldn't be an issue although we might want
319
- // to use cjs as alternative to avoid
303
+ /**
304
+ * V2: Build combined route that handles both workflow and step execution.
305
+ */
306
+ async buildCombinedFunction({ inputFiles, workflowGeneratedDir, tsconfigPath, }) {
307
+ const flowRouteDir = (0, node_path_1.join)(workflowGeneratedDir, 'flow');
308
+ await (0, promises_1.mkdir)(flowRouteDir, { recursive: true });
309
+ return await this.createCombinedBundle({
320
310
  format: 'esm',
321
311
  inputFiles,
322
- outfile: (0, node_path_1.join)(stepsRouteDir, 'route.js'),
323
- externalizeNonSteps: true,
324
- tsconfigPath,
325
- });
326
- }
327
- async buildWorkflowsFunction({ inputFiles, workflowGeneratedDir, tsconfigPath, }) {
328
- const workflowsRouteDir = (0, node_path_1.join)(workflowGeneratedDir, 'flow');
329
- await (0, promises_1.mkdir)(workflowsRouteDir, { recursive: true });
330
- return await this.createWorkflowsBundle({
331
- format: 'esm',
332
- outfile: (0, node_path_1.join)(workflowsRouteDir, 'route.js'),
312
+ stepsOutfile: (0, node_path_1.join)(flowRouteDir, '__step_registrations.js'),
313
+ flowOutfile: (0, node_path_1.join)(flowRouteDir, 'route.js'),
333
314
  bundleFinalOutput: false,
334
- inputFiles,
315
+ externalizeNonSteps: true,
335
316
  tsconfigPath,
336
317
  });
337
318
  }
@@ -1 +1 @@
1
- {"version":3,"file":"builder-eager.js","sourceRoot":"","sources":["../src/builder-eager.ts"],"names":[],"mappings":";;;;;AAUA,kDA4hBC;AAtiBD,qCAAoC;AACpC,+CAA4E;AAC5E,yCAAmD;AACnD,0DAAkC;AAElC,IAAI,sBAA2B,CAAC;AAEhC,8EAA8E;AAC9E,6EAA6E;AAC7E,oEAAoE;AAC7D,KAAK,UAAU,mBAAmB;IACvC,IAAI,sBAAsB,EAAE,CAAC;QAC3B,OAAO,sBAAsB,CAAC;IAChC,CAAC;IAED,M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,CAAC;oBACD,OAAO,KAAK,CAAC;gBACf,CAAC;YACH,CAAC,CAAC;YAEF,gCAAgC;YAChC,IAAI,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC9B,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,oCAAoC;YACpC,IAAI,MAAM,WAAW,CAAC,SAAS,CAAC,EAAE,CAAC;gBACjC,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,kFAAkF;YAClF,IAAI,MAAM,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAChC,+CAA+C;gBAC/C,MAAM,IAAA,gBAAK,EAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;gBACzC,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,IAAI,MAAM,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC;gBACnC,uDAAuD;gBACvD,MAAM,IAAA,gBAAK,EAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC5C,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,MAAM,IAAI,KAAK,CACb,qHAAqH,CACtH,CAAC;QACJ,CAAC;KACF;IAED,sBAAsB,GAAG,WAAW,CAAC;IACrC,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { constants } from 'node:fs';\nimport { access, copyFile, mkdir, stat, writeFile } from 'node:fs/promises';\nimport { extname, join, resolve } from 'node:path';\nimport Watchpack from 'watchpack';\n\nlet CachedNextBuilderEager: any;\n\n// Create the eager Next builder dynamically by extending the ESM BaseBuilder.\n// Exported as getNextBuilderEager() to allow CommonJS modules to import from\n// the ESM @workflow/builders package via dynamic import at runtime.\nexport async function getNextBuilderEager() {\n if (CachedNextBuilderEager) {\n return CachedNextBuilderEager;\n }\n\n const {\n BaseBuilder: BaseBuilderClass,\n STEP_QUEUE_TRIGGER,\n WORKFLOW_QUEUE_TRIGGER,\n // biome-ignore lint/security/noGlobalEval: Need to use eval here to avoid TypeScript from transpiling the import statement into `require()`\n } = (await eval(\n 'import(\"@workflow/builders\")'\n )) as typeof import('@workflow/builders');\n\n class NextBuilder extends BaseBuilderClass {\n async build() {\n const outputDir = await this.findAppDirectory();\n const workflowGeneratedDir = join(outputDir, '.well-known/workflow/v1');\n\n // Ensure output directories exist\n await mkdir(workflowGeneratedDir, { recursive: true });\n // ignore the generated assets\n\n await writeFile(join(workflowGeneratedDir, '.gitignore'), '*');\n\n const inputFiles = await this.getInputFiles();\n const tsconfigPath = await this.findTsConfigPath();\n\n const options = {\n inputFiles,\n workflowGeneratedDir,\n tsconfigPath,\n };\n\n const { manifest: stepsManifest, context: stepsBuildContext } =\n await this.buildStepsFunction(options);\n const workflowsBundle = await this.buildWorkflowsFunction(options);\n await this.buildWebhookRoute({ workflowGeneratedDir });\n\n // Merge manifests from both bundles\n const manifest = {\n steps: { ...stepsManifest.steps, ...workflowsBundle?.manifest?.steps },\n workflows: {\n ...stepsManifest.workflows,\n ...workflowsBundle?.manifest?.workflows,\n },\n classes: {\n ...stepsManifest.classes,\n ...workflowsBundle?.manifest?.classes,\n },\n };\n\n // Write unified manifest to workflow generated directory\n const workflowBundlePath = join(workflowGeneratedDir, 'flow/route.js');\n const manifestJson = await this.createManifest({\n workflowBundlePath,\n manifestDir: workflowGeneratedDir,\n manifest,\n });\n\n // Expose manifest as a static file when WORKFLOW_PUBLIC_MANIFEST=1.\n // Next.js serves files from public/ at the root URL.\n if (this.shouldExposePublicManifest && manifestJson) {\n const publicManifestDir = join(\n this.config.workingDir,\n 'public/.well-known/workflow/v1'\n );\n await mkdir(publicManifestDir, { recursive: true });\n await copyFile(\n join(workflowGeneratedDir, 'manifest.json'),\n join(publicManifestDir, 'manifest.json')\n );\n }\n\n await this.writeFunctionsConfig(outputDir);\n\n if (this.config.watch) {\n if (!stepsBuildContext) {\n throw new Error(\n 'Invariant: expected steps build context in watch mode'\n );\n }\n if (\n !workflowsBundle?.interimBundleCtx ||\n !workflowsBundle?.bundleFinal\n ) {\n throw new Error('Invariant: expected workflows bundle in watch mode');\n }\n\n let stepsCtx = stepsBuildContext;\n // These are safe to assert as non-null because we checked above\n let workflowsCtx = {\n interimBundleCtx: workflowsBundle.interimBundleCtx!,\n bundleFinal: workflowsBundle.bundleFinal!,\n };\n\n const normalizePath = (pathname: string) =>\n pathname.replace(/\\\\/g, '/');\n const knownFiles = new Set<string>();\n type WatchpackTimeInfoEntry = {\n safeTime: number;\n timestamp?: number;\n };\n let previousTimeInfo = new Map<string, WatchpackTimeInfoEntry>();\n\n const watchableExtensions = new Set([\n '.js',\n '.jsx',\n '.ts',\n '.tsx',\n '.mts',\n '.cts',\n '.cjs',\n '.mjs',\n ]);\n const ignoredPathFragments = [\n '/.git/',\n '/node_modules/',\n '/.next/',\n '/.turbo/',\n '/.vercel/',\n '/dist/',\n '/build/',\n '/out/',\n '/.cache/',\n '/.yarn/',\n '/.pnpm-store/',\n '/.parcel-cache/',\n '/.well-known/workflow/',\n ];\n const normalizedGeneratedDir = workflowGeneratedDir.replace(/\\\\/g, '/');\n ignoredPathFragments.push(normalizedGeneratedDir);\n\n // There is a node.js bug on MacOS which causes closing file watchers to be really slow.\n // This limits the number of watchers to mitigate the issue.\n // https://github.com/nodejs/node/issues/29949\n process.env.WATCHPACK_WATCHER_LIMIT =\n process.platform === 'darwin' ? '20' : undefined;\n\n const watcher = new Watchpack({\n // Watchpack default is 200ms which adds 200ms of dead time on bootup.\n aggregateTimeout: 5,\n ignored: (pathname: string) => {\n const normalizedPath = pathname.replace(/\\\\/g, '/');\n const extension = extname(normalizedPath);\n if (extension && !watchableExtensions.has(extension)) {\n return true;\n }\n if (normalizedPath.startsWith(normalizedGeneratedDir)) {\n return true;\n }\n for (const fragment of ignoredPathFragments) {\n if (normalizedPath.includes(fragment)) {\n return true;\n }\n }\n return false;\n },\n });\n\n const readTimeInfoEntries = () => {\n const rawEntries = watcher.getTimeInfoEntries() as Map<\n string,\n WatchpackTimeInfoEntry\n >;\n const normalizedEntries = new Map<string, WatchpackTimeInfoEntry>();\n for (const [path, info] of rawEntries) {\n normalizedEntries.set(normalizePath(path), info);\n }\n return normalizedEntries;\n };\n\n let rebuildQueue = Promise.resolve();\n\n const enqueue = (task: () => Promise<void>) => {\n rebuildQueue = rebuildQueue.then(task).catch((error) => {\n console.error('Failed to process file change', error);\n });\n return rebuildQueue;\n };\n\n const fullRebuild = async () => {\n const newInputFiles = await this.getInputFiles();\n options.inputFiles = newInputFiles;\n\n await stepsCtx.dispose();\n const { context: newStepsCtx } =\n await this.buildStepsFunction(options);\n if (!newStepsCtx) {\n throw new Error(\n 'Invariant: expected steps build context after rebuild'\n );\n }\n stepsCtx = newStepsCtx;\n\n await workflowsCtx.interimBundleCtx.dispose();\n const newWorkflowsCtx = await this.buildWorkflowsFunction(options);\n if (\n !newWorkflowsCtx?.interimBundleCtx ||\n !newWorkflowsCtx?.bundleFinal\n ) {\n throw new Error(\n 'Invariant: expected workflows bundle context after rebuild'\n );\n }\n workflowsCtx = {\n interimBundleCtx: newWorkflowsCtx.interimBundleCtx,\n bundleFinal: newWorkflowsCtx.bundleFinal,\n };\n };\n\n const logBuildMessages = (\n result: {\n errors?: import('esbuild').Message[];\n warnings?: import('esbuild').Message[];\n },\n label: string\n ) => {\n const logByType = (\n messages: import('esbuild').Message[] | undefined,\n method: 'error' | 'warn'\n ) => {\n if (!messages || messages.length === 0) {\n return;\n }\n const descriptor = method === 'error' ? 'errors' : 'warnings';\n console[method](`${descriptor} while rebuilding ${label}`);\n for (const message of messages) {\n console[method](message);\n }\n };\n\n logByType(result.errors, 'error');\n logByType(result.warnings, 'warn');\n };\n\n const rebuildExistingFiles = async () => {\n const rebuiltStepStart = Date.now();\n const stepsResult = await stepsCtx.rebuild();\n logBuildMessages(stepsResult, 'steps bundle');\n console.log(\n 'Rebuilt steps bundle',\n `${Date.now() - rebuiltStepStart}ms`\n );\n\n const rebuiltWorkflowStart = Date.now();\n const workflowResult = await workflowsCtx.interimBundleCtx.rebuild();\n logBuildMessages(workflowResult, 'workflows bundle');\n\n if (\n !workflowResult.outputFiles ||\n workflowResult.outputFiles.length === 0\n ) {\n console.error(\n 'No output generated while rebuilding workflows bundle'\n );\n return;\n }\n await workflowsCtx.bundleFinal(workflowResult.outputFiles[0].text);\n console.log(\n 'Rebuilt workflow bundle',\n `${Date.now() - rebuiltWorkflowStart}ms`\n );\n };\n\n const isWatchableFile = (path: string) =>\n watchableExtensions.has(extname(path));\n\n const getComparableTimestamp = (entry: WatchpackTimeInfoEntry) =>\n entry.timestamp ?? entry.safeTime;\n\n const findRemovedFiles = (\n currentEntries: Map<string, WatchpackTimeInfoEntry>,\n previousEntries: Map<string, WatchpackTimeInfoEntry>\n ) => {\n const removed: string[] = [];\n for (const path of previousEntries.keys()) {\n if (!currentEntries.has(path) && isWatchableFile(path)) {\n removed.push(path);\n }\n }\n return removed;\n };\n\n const findAddedAndModifiedFiles = (\n currentEntries: Map<string, WatchpackTimeInfoEntry>,\n previousEntries: Map<string, WatchpackTimeInfoEntry>\n ) => {\n const added: string[] = [];\n const modified: string[] = [];\n\n for (const [path, info] of currentEntries) {\n if (!isWatchableFile(path)) {\n continue;\n }\n\n const previous = previousEntries.get(path);\n if (!previous) {\n added.push(path);\n continue;\n }\n\n if (\n getComparableTimestamp(info) !== getComparableTimestamp(previous)\n ) {\n modified.push(path);\n }\n }\n\n return { added, modified };\n };\n\n const determineFileChanges = (\n currentEntries: Map<string, WatchpackTimeInfoEntry>,\n previousEntries: Map<string, WatchpackTimeInfoEntry>\n ) => {\n const removedFiles = findRemovedFiles(\n currentEntries,\n previousEntries\n );\n const { added, modified } = findAddedAndModifiedFiles(\n currentEntries,\n previousEntries\n );\n\n return {\n addedFiles: added,\n modifiedFiles: modified,\n removedFiles,\n };\n };\n\n let isInitial = true;\n\n watcher.on('aggregated', () => {\n const currentEntries = readTimeInfoEntries();\n const { addedFiles, modifiedFiles, removedFiles } =\n determineFileChanges(currentEntries, previousTimeInfo);\n\n previousTimeInfo = currentEntries;\n\n if (isInitial) {\n isInitial = false;\n return;\n }\n\n if (\n addedFiles.length === 0 &&\n modifiedFiles.length === 0 &&\n removedFiles.length === 0\n ) {\n return;\n }\n\n for (const removal of removedFiles) {\n knownFiles.delete(removal);\n }\n for (const added of addedFiles) {\n knownFiles.add(added);\n }\n\n enqueue(async () => {\n if (addedFiles.length > 0 || removedFiles.length > 0) {\n await fullRebuild();\n return;\n }\n\n if (modifiedFiles.length > 0) {\n await rebuildExistingFiles();\n }\n });\n });\n\n watcher.watch({\n directories: [this.config.workingDir],\n startTime: 0,\n });\n }\n }\n\n protected async getInputFiles(): Promise<string[]> {\n const inputFiles = await super.getInputFiles();\n return inputFiles.filter((item) => {\n // Match App Router entrypoints: route.ts, page.ts, layout.ts in app/ or src/app/ directories\n // Matches: /app/page.ts, /app/dashboard/page.ts, /src/app/route.ts, etc.\n if (\n item.match(\n /(^|.*[/\\\\])(app|src[/\\\\]app)([/\\\\](route|page|layout)\\.|[/\\\\].*[/\\\\](route|page|layout)\\.)/\n )\n ) {\n return true;\n }\n // Match Pages Router entrypoints: files in pages/ or src/pages/\n if (item.match(/[/\\\\](pages|src[/\\\\]pages)[/\\\\]/)) {\n return true;\n }\n return false;\n });\n }\n\n private async writeFunctionsConfig(outputDir: string) {\n // we don't run this in development mode as it's not needed\n if (process.env.NODE_ENV === 'development') {\n return;\n }\n const generatedConfig = {\n version: '0',\n steps: {\n maxDuration: 'max',\n experimentalTriggers: [STEP_QUEUE_TRIGGER],\n },\n workflows: {\n maxDuration: 'max',\n experimentalTriggers: [WORKFLOW_QUEUE_TRIGGER],\n },\n };\n\n // We write this file to the generated directory for\n // the Next.js builder to consume\n await writeFile(\n join(outputDir, '.well-known/workflow/v1/config.json'),\n JSON.stringify(generatedConfig, null, 2)\n );\n }\n\n private async buildStepsFunction({\n inputFiles,\n workflowGeneratedDir,\n tsconfigPath,\n }: {\n inputFiles: string[];\n workflowGeneratedDir: string;\n tsconfigPath?: string;\n }) {\n // Create steps bundle\n const stepsRouteDir = join(workflowGeneratedDir, 'step');\n await mkdir(stepsRouteDir, { recursive: true });\n return await this.createStepsBundle({\n // If any dynamic requires are used when bundling with ESM\n // esbuild will create a too dynamic wrapper around require\n // which turbopack/webpack fail to analyze. If we externalize\n // correctly this shouldn't be an issue although we might want\n // to use cjs as alternative to avoid\n format: 'esm',\n inputFiles,\n outfile: join(stepsRouteDir, 'route.js'),\n externalizeNonSteps: true,\n tsconfigPath,\n });\n }\n\n private async buildWorkflowsFunction({\n inputFiles,\n workflowGeneratedDir,\n tsconfigPath,\n }: {\n inputFiles: string[];\n workflowGeneratedDir: string;\n tsconfigPath?: string;\n }) {\n const workflowsRouteDir = join(workflowGeneratedDir, 'flow');\n await mkdir(workflowsRouteDir, { recursive: true });\n return await this.createWorkflowsBundle({\n format: 'esm',\n outfile: join(workflowsRouteDir, 'route.js'),\n bundleFinalOutput: false,\n inputFiles,\n tsconfigPath,\n });\n }\n\n private async buildWebhookRoute({\n workflowGeneratedDir,\n }: {\n workflowGeneratedDir: string;\n }): Promise<void> {\n const webhookRouteFile = join(\n workflowGeneratedDir,\n 'webhook/[token]/route.js'\n );\n await this.createWebhookBundle({\n outfile: webhookRouteFile,\n bundle: false, // Next.js doesn't need bundling\n });\n }\n\n private async findAppDirectory(): Promise<string> {\n const appDir = resolve(this.config.workingDir, 'app');\n const srcAppDir = resolve(this.config.workingDir, 'src/app');\n const pagesDir = resolve(this.config.workingDir, 'pages');\n const srcPagesDir = resolve(this.config.workingDir, 'src/pages');\n\n // Helper to check if a path exists and is a directory\n const isDirectory = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n const stats = await stat(path);\n if (!stats.isDirectory()) {\n throw new Error(`Path exists but is not a directory: ${path}`);\n }\n return true;\n } catch (e) {\n if (e instanceof Error && e.message.includes('not a directory')) {\n throw e;\n }\n return false;\n }\n };\n\n // Check if app directory exists\n if (await isDirectory(appDir)) {\n return appDir;\n }\n\n // Check if src/app directory exists\n if (await isDirectory(srcAppDir)) {\n return srcAppDir;\n }\n\n // If no app directory exists, check for pages directory and create app next to it\n if (await isDirectory(pagesDir)) {\n // Create app directory next to pages directory\n await mkdir(appDir, { recursive: true });\n return appDir;\n }\n\n if (await isDirectory(srcPagesDir)) {\n // Create src/app directory next to src/pages directory\n await mkdir(srcAppDir, { recursive: true });\n return srcAppDir;\n }\n\n throw new Error(\n 'Could not find Next.js app or pages directory. Expected one of: \"app\", \"src/app\", \"pages\", or \"src/pages\" to exist.'\n );\n }\n }\n\n CachedNextBuilderEager = NextBuilder;\n return NextBuilder;\n}\n"]}
1
+ {"version":3,"file":"builder-eager.js","sourceRoot":"","sources":["../src/builder-eager.ts"],"names":[],"mappings":";;;;;AAYA,kDAogBC;AAhhBD,qCAAoC;AACpC,+CAA4E;AAC5E,yCAAmD;AAEnD,0DAAkC;AAClC,yDAAiE;AAEjE,IAAI,sBAA2B,CAAC;AAEhC,8EAA8E;AAC9E,6EAA6E;AAC7E,oEAAoE;AAC7D,KAAK,UAAU,mBAAmB;IACvC,IAAI,sBAAsB,EAAE,CAAC;QAC3B,OAAO,sBAAsB,CAAC;IAChC,CAAC;IAED,MAAM,EACJ,WAAW,EAAE,gBAAgB,EAC7B,sBAAsB;IACtB,4IAA4I;MAC7I,GAAG,CAAC,MAAM,IAAI,CACb,8BAA8B,CAC/B,CAAwC,CAAC;IAE1C,MAAM,WAAY,SAAQ,gBAAgB;QACxC,KAAK,CAAC,KAAK;YACT,qEAAqE;YACrE,kEAAkE;YAClE,wDAAwD;YACxD,MAAM,IAAA,8CAA2B,EAC/B,IAAA,gBAAI,EACF,IAAI,CAAC,MAAM,CAAC,UAAU,EACrB,IAAI,CAAC,MAA+B,CAAC,OAAO,IAAI,OAAO,CACzD,CACF,CAAC;YAEF,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAChD,MAAM,oBAAoB,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,yBAAyB,CAAC,CAAC;YA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,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC;wBAChE,MAAM,CAAC,CAAC;oBACV,CAAC;oBACD,OAAO,KAAK,CAAC;gBACf,CAAC;YACH,CAAC,CAAC;YAEF,gCAAgC;YAChC,IAAI,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC9B,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,oCAAoC;YACpC,IAAI,MAAM,WAAW,CAAC,SAAS,CAAC,EAAE,CAAC;gBACjC,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,kFAAkF;YAClF,IAAI,MAAM,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAChC,+CAA+C;gBAC/C,MAAM,IAAA,gBAAK,EAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;gBACzC,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,IAAI,MAAM,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC;gBACnC,uDAAuD;gBACvD,MAAM,IAAA,gBAAK,EAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC5C,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,MAAM,IAAI,KAAK,CACb,qHAAqH,CACtH,CAAC;QACJ,CAAC;KACF;IAED,sBAAsB,GAAG,WAAW,CAAC;IACrC,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { constants } from 'node:fs';\nimport { access, copyFile, mkdir, stat, writeFile } from 'node:fs/promises';\nimport { extname, join, resolve } from 'node:path';\nimport type { WorkflowManifest } from '@workflow/builders';\nimport Watchpack from 'watchpack';\nimport { cleanupStaleSocketInfoFiles } from './socket-server.js';\n\nlet CachedNextBuilderEager: any;\n\n// Create the eager Next builder dynamically by extending the ESM BaseBuilder.\n// Exported as getNextBuilderEager() to allow CommonJS modules to import from\n// the ESM @workflow/builders package via dynamic import at runtime.\nexport async function getNextBuilderEager() {\n if (CachedNextBuilderEager) {\n return CachedNextBuilderEager;\n }\n\n const {\n BaseBuilder: BaseBuilderClass,\n WORKFLOW_QUEUE_TRIGGER,\n // biome-ignore lint/security/noGlobalEval: Need to use eval here to avoid TypeScript from transpiling the import statement into `require()`\n } = (await eval(\n 'import(\"@workflow/builders\")'\n )) as typeof import('@workflow/builders');\n\n class NextBuilder extends BaseBuilderClass {\n async build() {\n // Eager mode never starts a discovery socket server, so any leftover\n // workflow-socket.json is from a previous deferred-mode build and\n // would make the webpack loader connect to a dead port.\n await cleanupStaleSocketInfoFiles(\n join(\n this.config.workingDir,\n (this.config as { distDir?: string }).distDir || '.next'\n )\n );\n\n const outputDir = await this.findAppDirectory();\n const workflowGeneratedDir = join(outputDir, '.well-known/workflow/v1');\n\n // Ensure output directories exist\n await mkdir(workflowGeneratedDir, { recursive: true });\n await writeFile(join(workflowGeneratedDir, '.gitignore'), '*');\n\n const inputFiles = await this.getInputFiles();\n const tsconfigPath = await this.findTsConfigPath();\n\n const options = {\n inputFiles,\n workflowGeneratedDir,\n tsconfigPath,\n };\n\n // V2: Build combined route (replaces separate step + flow routes)\n const combinedResult = await this.buildCombinedFunction(options);\n await this.buildWebhookRoute({ workflowGeneratedDir });\n\n const writeManifest = async (\n sourceManifest: WorkflowManifest | undefined\n ) => {\n const manifest = {\n steps: { ...sourceManifest?.steps },\n workflows: { ...sourceManifest?.workflows },\n classes: { ...sourceManifest?.classes },\n };\n\n // Write manifest\n const workflowBundlePath = join(workflowGeneratedDir, 'flow/route.js');\n const manifestJson = await this.createManifest({\n workflowBundlePath,\n manifestDir: workflowGeneratedDir,\n manifest,\n });\n\n // Expose manifest as a static file when WORKFLOW_PUBLIC_MANIFEST=1.\n if (this.shouldExposePublicManifest && manifestJson) {\n const publicManifestDir = join(\n this.config.workingDir,\n 'public/.well-known/workflow/v1'\n );\n await mkdir(publicManifestDir, { recursive: true });\n await copyFile(\n join(workflowGeneratedDir, 'manifest.json'),\n join(publicManifestDir, 'manifest.json')\n );\n }\n };\n\n await writeManifest(combinedResult?.manifest);\n\n await this.writeFunctionsConfig(outputDir);\n\n if (this.config.watch) {\n // TODO: implement watch mode for combined bundle\n // For now, fall back to full rebuild on file changes\n let stepsCtx = combinedResult?.stepsContext;\n if (!stepsCtx) {\n throw new Error(\n 'Invariant: expected steps build context in watch mode'\n );\n }\n\n // Use stepsCtx for the watch rebuild (workflow interim ctx from combined)\n let workflowsCtx = {\n interimBundleCtx: combinedResult?.interimBundleCtx!,\n bundleFinal: combinedResult?.bundleFinal!,\n };\n\n const normalizePath = (pathname: string) =>\n pathname.replace(/\\\\/g, '/');\n const knownFiles = new Set<string>();\n type WatchpackTimeInfoEntry = {\n safeTime: number;\n timestamp?: number;\n };\n let previousTimeInfo = new Map<string, WatchpackTimeInfoEntry>();\n\n const watchableExtensions = new Set([\n '.js',\n '.jsx',\n '.ts',\n '.tsx',\n '.mts',\n '.cts',\n '.cjs',\n '.mjs',\n ]);\n const ignoredPathFragments = [\n '/.git/',\n '/node_modules/',\n '/.next/',\n '/.turbo/',\n '/.vercel/',\n '/dist/',\n '/build/',\n '/out/',\n '/.cache/',\n '/.yarn/',\n '/.pnpm-store/',\n '/.parcel-cache/',\n '/.well-known/workflow/',\n ];\n const normalizedGeneratedDir = workflowGeneratedDir.replace(/\\\\/g, '/');\n ignoredPathFragments.push(normalizedGeneratedDir);\n\n // There is a node.js bug on MacOS which causes closing file watchers to be really slow.\n // This limits the number of watchers to mitigate the issue.\n // https://github.com/nodejs/node/issues/29949\n process.env.WATCHPACK_WATCHER_LIMIT =\n process.platform === 'darwin' ? '20' : undefined;\n\n const watcher = new Watchpack({\n // Watchpack default is 200ms which adds 200ms of dead time on bootup.\n aggregateTimeout: 5,\n ignored: (pathname: string) => {\n const normalizedPath = pathname.replace(/\\\\/g, '/');\n const extension = extname(normalizedPath);\n if (extension && !watchableExtensions.has(extension)) {\n return true;\n }\n if (normalizedPath.startsWith(normalizedGeneratedDir)) {\n return true;\n }\n for (const fragment of ignoredPathFragments) {\n if (normalizedPath.includes(fragment)) {\n return true;\n }\n }\n return false;\n },\n });\n\n const readTimeInfoEntries = () => {\n const rawEntries = watcher.getTimeInfoEntries() as Map<\n string,\n WatchpackTimeInfoEntry\n >;\n const normalizedEntries = new Map<string, WatchpackTimeInfoEntry>();\n for (const [path, info] of rawEntries) {\n normalizedEntries.set(normalizePath(path), info);\n }\n return normalizedEntries;\n };\n\n let rebuildQueue = Promise.resolve();\n\n const enqueue = (task: () => Promise<void>) => {\n rebuildQueue = rebuildQueue.then(task).catch((error) => {\n console.error('Failed to process file change', error);\n });\n return rebuildQueue;\n };\n\n const fullRebuild = async () => {\n const newInputFiles = await this.getInputFiles();\n options.inputFiles = newInputFiles;\n\n await stepsCtx!.dispose();\n await workflowsCtx.interimBundleCtx.dispose();\n\n const newCombined = await this.buildCombinedFunction(options);\n if (!newCombined?.stepsContext) {\n throw new Error(\n 'Invariant: expected steps build context after rebuild'\n );\n }\n stepsCtx = newCombined.stepsContext;\n\n if (!newCombined?.interimBundleCtx || !newCombined?.bundleFinal) {\n throw new Error(\n 'Invariant: expected workflows bundle context after rebuild'\n );\n }\n workflowsCtx = {\n interimBundleCtx: newCombined.interimBundleCtx,\n bundleFinal: newCombined.bundleFinal,\n };\n\n await writeManifest(newCombined.manifest);\n };\n\n const logBuildMessages = (\n result: {\n errors?: import('esbuild').Message[];\n warnings?: import('esbuild').Message[];\n },\n label: string\n ) => {\n const logByType = (\n messages: import('esbuild').Message[] | undefined,\n method: 'error' | 'warn'\n ) => {\n if (!messages || messages.length === 0) {\n return;\n }\n const descriptor = method === 'error' ? 'errors' : 'warnings';\n console[method](`${descriptor} while rebuilding ${label}`);\n for (const message of messages) {\n console[method](message);\n }\n };\n\n logByType(result.errors, 'error');\n logByType(result.warnings, 'warn');\n };\n\n const rebuildExistingFiles = async () => {\n const rebuiltStepStart = Date.now();\n const stepsResult = await stepsCtx!.rebuild();\n logBuildMessages(stepsResult, 'steps bundle');\n console.log(\n 'Rebuilt steps bundle',\n `${Date.now() - rebuiltStepStart}ms`\n );\n\n const rebuiltWorkflowStart = Date.now();\n const workflowResult = await workflowsCtx.interimBundleCtx.rebuild();\n logBuildMessages(workflowResult, 'workflows bundle');\n\n if (\n !workflowResult.outputFiles ||\n workflowResult.outputFiles.length === 0\n ) {\n console.error(\n 'No output generated while rebuilding workflows bundle'\n );\n return;\n }\n await workflowsCtx.bundleFinal(workflowResult.outputFiles[0].text);\n console.log(\n 'Rebuilt workflow bundle',\n `${Date.now() - rebuiltWorkflowStart}ms`\n );\n };\n\n const isWatchableFile = (path: string) =>\n watchableExtensions.has(extname(path));\n\n const getComparableTimestamp = (entry: WatchpackTimeInfoEntry) =>\n entry.timestamp ?? entry.safeTime;\n\n const findRemovedFiles = (\n currentEntries: Map<string, WatchpackTimeInfoEntry>,\n previousEntries: Map<string, WatchpackTimeInfoEntry>\n ) => {\n const removed: string[] = [];\n for (const path of previousEntries.keys()) {\n if (!currentEntries.has(path) && isWatchableFile(path)) {\n removed.push(path);\n }\n }\n return removed;\n };\n\n const findAddedAndModifiedFiles = (\n currentEntries: Map<string, WatchpackTimeInfoEntry>,\n previousEntries: Map<string, WatchpackTimeInfoEntry>\n ) => {\n const added: string[] = [];\n const modified: string[] = [];\n\n for (const [path, info] of currentEntries) {\n if (!isWatchableFile(path)) {\n continue;\n }\n\n const previous = previousEntries.get(path);\n if (!previous) {\n added.push(path);\n continue;\n }\n\n if (\n getComparableTimestamp(info) !== getComparableTimestamp(previous)\n ) {\n modified.push(path);\n }\n }\n\n return { added, modified };\n };\n\n const determineFileChanges = (\n currentEntries: Map<string, WatchpackTimeInfoEntry>,\n previousEntries: Map<string, WatchpackTimeInfoEntry>\n ) => {\n const removedFiles = findRemovedFiles(\n currentEntries,\n previousEntries\n );\n const { added, modified } = findAddedAndModifiedFiles(\n currentEntries,\n previousEntries\n );\n\n return {\n addedFiles: added,\n modifiedFiles: modified,\n removedFiles,\n };\n };\n\n let isInitial = true;\n\n watcher.on('aggregated', () => {\n const currentEntries = readTimeInfoEntries();\n const { addedFiles, modifiedFiles, removedFiles } =\n determineFileChanges(currentEntries, previousTimeInfo);\n\n previousTimeInfo = currentEntries;\n\n if (isInitial) {\n isInitial = false;\n return;\n }\n\n if (\n addedFiles.length === 0 &&\n modifiedFiles.length === 0 &&\n removedFiles.length === 0\n ) {\n return;\n }\n\n for (const removal of removedFiles) {\n knownFiles.delete(removal);\n }\n for (const added of addedFiles) {\n knownFiles.add(added);\n }\n\n enqueue(async () => {\n if (addedFiles.length > 0 || removedFiles.length > 0) {\n await fullRebuild();\n return;\n }\n\n if (modifiedFiles.length > 0) {\n await rebuildExistingFiles();\n }\n });\n });\n\n watcher.watch({\n directories: [this.config.workingDir],\n startTime: 0,\n });\n }\n }\n\n protected async getInputFiles(): Promise<string[]> {\n const inputFiles = await super.getInputFiles();\n return inputFiles.filter((item) => {\n // Match App Router entrypoints: route.ts, page.ts, layout.ts in app/ or src/app/ directories\n // Matches: /app/page.ts, /app/dashboard/page.ts, /src/app/route.ts, etc.\n if (\n item.match(\n /(^|.*[/\\\\])(app|src[/\\\\]app)([/\\\\](route|page|layout)\\.|[/\\\\].*[/\\\\](route|page|layout)\\.)/\n )\n ) {\n return true;\n }\n // Match Pages Router entrypoints: files in pages/ or src/pages/\n if (item.match(/[/\\\\](pages|src[/\\\\]pages)[/\\\\]/)) {\n return true;\n }\n return false;\n });\n }\n\n private async writeFunctionsConfig(outputDir: string) {\n // we don't run this in development mode as it's not needed\n if (process.env.NODE_ENV === 'development') {\n return;\n }\n\n // V2 combined config: single trigger handles both workflow and step execution.\n // The step route no longer needs its own trigger since steps are executed\n // inline by the combined handler or queued back to __wkf_workflow_* with stepId.\n const generatedConfig = {\n version: '0',\n workflows: {\n maxDuration: 'max',\n experimentalTriggers: [WORKFLOW_QUEUE_TRIGGER],\n },\n };\n\n await writeFile(\n join(outputDir, '.well-known/workflow/v1/config.json'),\n JSON.stringify(generatedConfig, null, 2)\n );\n }\n\n /**\n * V2: Build combined route that handles both workflow and step execution.\n */\n private async buildCombinedFunction({\n inputFiles,\n workflowGeneratedDir,\n tsconfigPath,\n }: {\n inputFiles: string[];\n workflowGeneratedDir: string;\n tsconfigPath?: string;\n }) {\n const flowRouteDir = join(workflowGeneratedDir, 'flow');\n await mkdir(flowRouteDir, { recursive: true });\n\n return await this.createCombinedBundle({\n format: 'esm',\n inputFiles,\n stepsOutfile: join(flowRouteDir, '__step_registrations.js'),\n flowOutfile: join(flowRouteDir, 'route.js'),\n bundleFinalOutput: false,\n externalizeNonSteps: true,\n tsconfigPath,\n });\n }\n\n private async buildWebhookRoute({\n workflowGeneratedDir,\n }: {\n workflowGeneratedDir: string;\n }): Promise<void> {\n const webhookRouteFile = join(\n workflowGeneratedDir,\n 'webhook/[token]/route.js'\n );\n await this.createWebhookBundle({\n outfile: webhookRouteFile,\n bundle: false, // Next.js doesn't need bundling\n });\n }\n\n private async findAppDirectory(): Promise<string> {\n const appDir = resolve(this.config.workingDir, 'app');\n const srcAppDir = resolve(this.config.workingDir, 'src/app');\n const pagesDir = resolve(this.config.workingDir, 'pages');\n const srcPagesDir = resolve(this.config.workingDir, 'src/pages');\n\n // Helper to check if a path exists and is a directory\n const isDirectory = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n const stats = await stat(path);\n if (!stats.isDirectory()) {\n throw new Error(`Path exists but is not a directory: ${path}`);\n }\n return true;\n } catch (e) {\n if (e instanceof Error && e.message.includes('not a directory')) {\n throw e;\n }\n return false;\n }\n };\n\n // Check if app directory exists\n if (await isDirectory(appDir)) {\n return appDir;\n }\n\n // Check if src/app directory exists\n if (await isDirectory(srcAppDir)) {\n return srcAppDir;\n }\n\n // If no app directory exists, check for pages directory and create app next to it\n if (await isDirectory(pagesDir)) {\n // Create app directory next to pages directory\n await mkdir(appDir, { recursive: true });\n return appDir;\n }\n\n if (await isDirectory(srcPagesDir)) {\n // Create src/app directory next to src/pages directory\n await mkdir(srcAppDir, { recursive: true });\n return srcAppDir;\n }\n\n throw new Error(\n 'Could not find Next.js app or pages directory. Expected one of: \"app\", \"src/app\", \"pages\", or \"src/pages\" to exist.'\n );\n }\n }\n\n CachedNextBuilderEager = NextBuilder;\n return NextBuilder;\n}\n"]}
package/dist/builder.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export declare const DEFERRED_BUILDER_MIN_VERSION = "16.2.0-canary.48";
2
- export declare const WORKFLOW_DEFERRED_ENTRIES: readonly ["/.well-known/workflow/v1/flow", "/.well-known/workflow/v1/step", "/.well-known/workflow/v1/webhook/[token]"];
2
+ export declare const WORKFLOW_DEFERRED_ENTRIES: readonly ["/.well-known/workflow/v1/flow", "/.well-known/workflow/v1/webhook/[token]"];
3
3
  export declare function shouldUseDeferredBuilder(nextVersion: string): boolean;
4
4
  export declare function getNextBuilder(nextVersion: string): Promise<any>;
5
5
  //# sourceMappingURL=builder.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../src/builder.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,4BAA4B,qBAAqB,CAAC;AAE/D,eAAO,MAAM,yBAAyB,yHAI5B,CAAC;AAIX,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAerE;AAED,wBAAsB,cAAc,CAAC,WAAW,EAAE,MAAM,gBAMvD"}
1
+ {"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../src/builder.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,4BAA4B,qBAAqB,CAAC;AAE/D,eAAO,MAAM,yBAAyB,wFAG5B,CAAC;AAIX,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAgBrE;AAED,wBAAsB,cAAc,CAAC,WAAW,EAAE,MAAM,gBAMvD"}
package/dist/builder.js CHANGED
@@ -9,15 +9,15 @@ exports.getNextBuilder = getNextBuilder;
9
9
  const semver_1 = __importDefault(require("semver"));
10
10
  const builder_deferred_js_1 = require("./builder-deferred.js");
11
11
  const builder_eager_js_1 = require("./builder-eager.js");
12
+ const environment_flag_js_1 = require("./environment-flag.js");
12
13
  exports.DEFERRED_BUILDER_MIN_VERSION = '16.2.0-canary.48';
13
14
  exports.WORKFLOW_DEFERRED_ENTRIES = [
14
15
  '/.well-known/workflow/v1/flow',
15
- '/.well-known/workflow/v1/step',
16
16
  '/.well-known/workflow/v1/webhook/[token]',
17
17
  ];
18
18
  let warnedAboutFlagAndVersion = false;
19
19
  function shouldUseDeferredBuilder(nextVersion) {
20
- const flagEnabled = Boolean(process.env.WORKFLOW_NEXT_LAZY_DISCOVERY);
20
+ const flagEnabled = (0, environment_flag_js_1.parseEnvironmentFlag)(process.env.WORKFLOW_NEXT_LAZY_DISCOVERY) ?? false;
21
21
  const versionCompatible = semver_1.default.gte(nextVersion, exports.DEFERRED_BUILDER_MIN_VERSION);
22
22
  if (flagEnabled && !versionCompatible && !warnedAboutFlagAndVersion) {
23
23
  warnedAboutFlagAndVersion = true;
@@ -1 +1 @@
1
- {"version":3,"file":"builder.js","sourceRoot":"","sources":["../src/builder.ts"],"names":[],"mappings":";;;;;;AAcA,4DAeC;AAED,wCAMC;AArCD,oDAA4B;AAC5B,+DAA+D;AAC/D,yDAAyD;AAE5C,QAAA,4BAA4B,GAAG,kBAAkB,CAAC;AAElD,QAAA,yBAAyB,GAAG;IACvC,+BAA+B;IAC/B,+BAA+B;IAC/B,0CAA0C;CAClC,CAAC;AAEX,IAAI,yBAAyB,GAAG,KAAK,CAAC;AAEtC,SAAgB,wBAAwB,CAAC,WAAmB;IAC1D,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IACtE,MAAM,iBAAiB,GAAG,gBAAM,CAAC,GAAG,CAClC,WAAW,EACX,oCAA4B,CAC7B,CAAC;IAEF,IAAI,WAAW,IAAI,CAAC,iBAAiB,IAAI,CAAC,yBAAyB,EAAE,CAAC;QACpE,yBAAyB,GAAG,IAAI,CAAC;QACjC,OAAO,CAAC,IAAI,CACV,sEAAsE,oCAA4B,SAAS,WAAW,EAAE,CACzH,CAAC;IACJ,CAAC;IAED,OAAO,WAAW,IAAI,iBAAiB,CAAC;AAC1C,CAAC;AAEM,KAAK,UAAU,cAAc,CAAC,WAAmB;IACtD,IAAI,wBAAwB,CAAC,WAAW,CAAC,EAAE,CAAC;QAC1C,OAAO,IAAA,4CAAsB,GAAE,CAAC;IAClC,CAAC;IAED,OAAO,IAAA,sCAAmB,GAAE,CAAC;AAC/B,CAAC","sourcesContent":["import semver from 'semver';\nimport { getNextBuilderDeferred } from './builder-deferred.js';\nimport { getNextBuilderEager } from './builder-eager.js';\n\nexport const DEFERRED_BUILDER_MIN_VERSION = '16.2.0-canary.48';\n\nexport const WORKFLOW_DEFERRED_ENTRIES = [\n '/.well-known/workflow/v1/flow',\n '/.well-known/workflow/v1/step',\n '/.well-known/workflow/v1/webhook/[token]',\n] as const;\n\nlet warnedAboutFlagAndVersion = false;\n\nexport function shouldUseDeferredBuilder(nextVersion: string): boolean {\n const flagEnabled = Boolean(process.env.WORKFLOW_NEXT_LAZY_DISCOVERY);\n const versionCompatible = semver.gte(\n nextVersion,\n DEFERRED_BUILDER_MIN_VERSION\n );\n\n if (flagEnabled && !versionCompatible && !warnedAboutFlagAndVersion) {\n warnedAboutFlagAndVersion = true;\n console.warn(\n `Enabled lazyDiscovery but Next.js version is not compatible, needs ${DEFERRED_BUILDER_MIN_VERSION} have ${nextVersion}`\n );\n }\n\n return flagEnabled && versionCompatible;\n}\n\nexport async function getNextBuilder(nextVersion: string) {\n if (shouldUseDeferredBuilder(nextVersion)) {\n return getNextBuilderDeferred();\n }\n\n return getNextBuilderEager();\n}\n"]}
1
+ {"version":3,"file":"builder.js","sourceRoot":"","sources":["../src/builder.ts"],"names":[],"mappings":";;;;;;AAcA,4DAgBC;AAED,wCAMC;AAtCD,oDAA4B;AAC5B,+DAA+D;AAC/D,yDAAyD;AACzD,+DAA6D;AAEhD,QAAA,4BAA4B,GAAG,kBAAkB,CAAC;AAElD,QAAA,yBAAyB,GAAG;IACvC,+BAA+B;IAC/B,0CAA0C;CAClC,CAAC;AAEX,IAAI,yBAAyB,GAAG,KAAK,CAAC;AAEtC,SAAgB,wBAAwB,CAAC,WAAmB;IAC1D,MAAM,WAAW,GACf,IAAA,0CAAoB,EAAC,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,IAAI,KAAK,CAAC;IAC1E,MAAM,iBAAiB,GAAG,gBAAM,CAAC,GAAG,CAClC,WAAW,EACX,oCAA4B,CAC7B,CAAC;IAEF,IAAI,WAAW,IAAI,CAAC,iBAAiB,IAAI,CAAC,yBAAyB,EAAE,CAAC;QACpE,yBAAyB,GAAG,IAAI,CAAC;QACjC,OAAO,CAAC,IAAI,CACV,sEAAsE,oCAA4B,SAAS,WAAW,EAAE,CACzH,CAAC;IACJ,CAAC;IAED,OAAO,WAAW,IAAI,iBAAiB,CAAC;AAC1C,CAAC;AAEM,KAAK,UAAU,cAAc,CAAC,WAAmB;IACtD,IAAI,wBAAwB,CAAC,WAAW,CAAC,EAAE,CAAC;QAC1C,OAAO,IAAA,4CAAsB,GAAE,CAAC;IAClC,CAAC;IAED,OAAO,IAAA,sCAAmB,GAAE,CAAC;AAC/B,CAAC","sourcesContent":["import semver from 'semver';\nimport { getNextBuilderDeferred } from './builder-deferred.js';\nimport { getNextBuilderEager } from './builder-eager.js';\nimport { parseEnvironmentFlag } from './environment-flag.js';\n\nexport const DEFERRED_BUILDER_MIN_VERSION = '16.2.0-canary.48';\n\nexport const WORKFLOW_DEFERRED_ENTRIES = [\n '/.well-known/workflow/v1/flow',\n '/.well-known/workflow/v1/webhook/[token]',\n] as const;\n\nlet warnedAboutFlagAndVersion = false;\n\nexport function shouldUseDeferredBuilder(nextVersion: string): boolean {\n const flagEnabled =\n parseEnvironmentFlag(process.env.WORKFLOW_NEXT_LAZY_DISCOVERY) ?? false;\n const versionCompatible = semver.gte(\n nextVersion,\n DEFERRED_BUILDER_MIN_VERSION\n );\n\n if (flagEnabled && !versionCompatible && !warnedAboutFlagAndVersion) {\n warnedAboutFlagAndVersion = true;\n console.warn(\n `Enabled lazyDiscovery but Next.js version is not compatible, needs ${DEFERRED_BUILDER_MIN_VERSION} have ${nextVersion}`\n );\n }\n\n return flagEnabled && versionCompatible;\n}\n\nexport async function getNextBuilder(nextVersion: string) {\n if (shouldUseDeferredBuilder(nextVersion)) {\n return getNextBuilderDeferred();\n }\n\n return getNextBuilderEager();\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function parseEnvironmentFlag(rawValue: string | undefined): boolean | undefined;
2
+ //# sourceMappingURL=environment-flag.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environment-flag.d.ts","sourceRoot":"","sources":["../src/environment-flag.ts"],"names":[],"mappings":"AAEA,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,OAAO,GAAG,SAAS,CAWrB"}
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseEnvironmentFlag = parseEnvironmentFlag;
4
+ const FALSE_ENV_VALUES = new Set(['0', 'false', 'no', 'off']);
5
+ function parseEnvironmentFlag(rawValue) {
6
+ const normalizedValue = rawValue?.trim().toLowerCase();
7
+ if (!normalizedValue) {
8
+ return undefined;
9
+ }
10
+ if (FALSE_ENV_VALUES.has(normalizedValue)) {
11
+ return false;
12
+ }
13
+ return true;
14
+ }
15
+ //# sourceMappingURL=environment-flag.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environment-flag.js","sourceRoot":"","sources":["../src/environment-flag.ts"],"names":[],"mappings":";;AAEA,oDAaC;AAfD,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;AAE9D,SAAgB,oBAAoB,CAClC,QAA4B;IAE5B,MAAM,eAAe,GAAG,QAAQ,EAAE,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACvD,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,gBAAgB,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;QAC1C,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["const FALSE_ENV_VALUES = new Set(['0', 'false', 'no', 'off']);\n\nexport function parseEnvironmentFlag(\n rawValue: string | undefined\n): boolean | undefined {\n const normalizedValue = rawValue?.trim().toLowerCase();\n if (!normalizedValue) {\n return undefined;\n }\n\n if (FALSE_ENV_VALUES.has(normalizedValue)) {\n return false;\n }\n\n return true;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -7,6 +7,14 @@ export declare function withWorkflow(nextConfigOrFn: NextConfig | ((phase: strin
7
7
  local?: {
8
8
  port?: number;
9
9
  };
10
+ /**
11
+ * Controls how source maps are emitted for workflow bundles. Accepts
12
+ * the same values as esbuild's `sourcemap` option: `true`/`'inline'`
13
+ * (default), `'linked'`, `'external'`, `'both'`, or `false` to omit
14
+ * source maps. Can also be set via the `WORKFLOW_SOURCEMAP`
15
+ * environment variable.
16
+ */
17
+ sourcemap?: boolean | 'inline' | 'linked' | 'external' | 'both';
10
18
  };
11
19
  }): (phase: string, ctx: {
12
20
  defaultConfig: NextConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AA6CvC,wBAAgB,YAAY,CAC1B,cAAc,EACV,UAAU,GACV,CAAC,CACC,KAAK,EAAE,MAAM,EACb,GAAG,EAAE;IAAE,aAAa,EAAE,UAAU,CAAA;CAAE,KAC/B,OAAO,CAAC,UAAU,CAAC,CAAC,EAC7B,EACE,SAAS,GACV,GAAE;IACD,SAAS,CAAC,EAAE;QACV,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB,KAAK,CAAC,EAAE;YACN,IAAI,CAAC,EAAE,MAAM,CAAC;SACf,CAAC;KACH,CAAC;CACE,IAsBJ,OAAO,MAAM,EACb,KAAK;IAAE,aAAa,EAAE,UAAU,CAAA;CAAE,yBAwLrC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AA0TvC,wBAAgB,YAAY,CAC1B,cAAc,EACV,UAAU,GACV,CAAC,CACC,KAAK,EAAE,MAAM,EACb,GAAG,EAAE;IAAE,aAAa,EAAE,UAAU,CAAA;CAAE,KAC/B,OAAO,CAAC,UAAU,CAAC,CAAC,EAC7B,EACE,SAAS,GACV,GAAE;IACD,SAAS,CAAC,EAAE;QACV,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB,KAAK,CAAC,EAAE;YACN,IAAI,CAAC,EAAE,MAAM,CAAC;SACf,CAAC;QACF;;;;;;WAMG;QACH,SAAS,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,MAAM,CAAC;KACjE,CAAC;CACE,IA+BJ,OAAO,MAAM,EACb,KAAK;IAAE,aAAa,EAAE,UAAU,CAAA;CAAE,yBA8PrC"}