eve 0.24.2 → 0.24.3

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 (128) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/src/cli/dev/environment.d.ts +6 -0
  3. package/dist/src/cli/dev/environment.js +1 -1
  4. package/dist/src/compiled/.vendor-stamp.json +2 -1
  5. package/dist/src/compiled/@chat-adapter/slack/index.js +12 -12
  6. package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -1
  7. package/dist/src/compiled/@vercel/sandbox/index.js +19 -19
  8. package/dist/src/compiled/@workflow/world-local/index.d.ts +14 -0
  9. package/dist/src/compiled/_chunks/node/{auth-CWHn3Yve.js → auth-BuQkq4Gr.js} +2 -2
  10. package/dist/src/compiled/_chunks/node/{dist-BdTs18CF.js → chunk-BTyA9uPd.js} +1 -1
  11. package/dist/src/compiled/_chunks/node/{dist-W8yle6rh.js → dist-CdH_Yoxt.js} +5 -5
  12. package/dist/src/compiled/_chunks/node/{dist-RHRJZ03Q.js → dist-Drt-_JVK.js} +1 -1
  13. package/dist/src/compiled/_chunks/node/dist-DsNhwdzf.js +1 -0
  14. package/dist/src/compiled/_chunks/node/retry-DngYleaI.js +1 -0
  15. package/dist/src/compiled/_chunks/node/token-DabMnh8F.js +1 -0
  16. package/dist/src/compiled/_chunks/node/token-util-BoSJPKrG.js +1 -0
  17. package/dist/src/compiled/_chunks/node/token-util-DVigMYWS.js +1 -0
  18. package/dist/src/compiled/_chunks/node/virtual-loader-B8K8w9cr.js +1 -0
  19. package/dist/src/compiled/chat/index.js +1 -1
  20. package/dist/src/compiled/env-runner/LICENSE +21 -0
  21. package/dist/src/compiled/env-runner/index.d.ts +38 -0
  22. package/dist/src/compiled/env-runner/index.js +1 -0
  23. package/dist/src/compiled/env-runner/node-worker.d.ts +1 -0
  24. package/dist/src/compiled/env-runner/node-worker.js +12 -0
  25. package/dist/src/compiler/compile-agent.d.ts +4 -6
  26. package/dist/src/compiler/compile-agent.js +1 -1
  27. package/dist/src/execution/create-session-step.d.ts +2 -2
  28. package/dist/src/execution/create-session-step.js +1 -1
  29. package/dist/src/execution/workflow-runtime.js +1 -1
  30. package/dist/src/internal/application/compiled-artifacts.d.ts +13 -0
  31. package/dist/src/internal/application/compiled-artifacts.js +3 -2
  32. package/dist/src/internal/application/dev-environment.d.ts +4 -0
  33. package/dist/src/internal/application/dev-environment.js +1 -0
  34. package/dist/src/internal/application/optional-package-install.d.ts +2 -10
  35. package/dist/src/internal/application/optional-package-install.js +1 -1
  36. package/dist/src/internal/application/output-publication-lock.js +1 -1
  37. package/dist/src/internal/application/package.js +1 -1
  38. package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
  39. package/dist/src/internal/authored-module-loader.d.ts +3 -9
  40. package/dist/src/internal/authored-module-loader.js +2 -2
  41. package/dist/src/internal/authored-package-boundary.d.ts +0 -2
  42. package/dist/src/internal/authored-package-boundary.js +1 -1
  43. package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
  44. package/dist/src/internal/compiled-manifest-fingerprint.d.ts +5 -0
  45. package/dist/src/internal/compiled-manifest-fingerprint.js +1 -0
  46. package/dist/src/internal/materialized-authored-modules.d.ts +0 -3
  47. package/dist/src/internal/materialized-authored-modules.js +1 -1
  48. package/dist/src/internal/nitro/dev-client-address.d.ts +22 -0
  49. package/dist/src/internal/nitro/dev-client-address.js +1 -0
  50. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.d.ts +12 -0
  51. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.js +1 -0
  52. package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +19 -1
  53. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  54. package/dist/src/internal/nitro/development-generation.d.ts +5 -1
  55. package/dist/src/internal/nitro/development-generation.js +1 -1
  56. package/dist/src/internal/nitro/host/artifacts-config.d.ts +2 -0
  57. package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
  58. package/dist/src/internal/nitro/host/channel-routes.d.ts +1 -13
  59. package/dist/src/internal/nitro/host/channel-routes.js +3 -3
  60. package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +1 -2
  61. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  62. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +3 -5
  63. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  64. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.d.ts +32 -0
  65. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -0
  66. package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +4 -15
  67. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  68. package/dist/src/internal/nitro/host/dev-host-candidate.d.ts +16 -0
  69. package/dist/src/internal/nitro/host/dev-host-candidate.js +1 -0
  70. package/dist/src/internal/nitro/host/dev-host-fingerprint.d.ts +2 -0
  71. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -0
  72. package/dist/src/internal/nitro/host/dev-host-workspace.d.ts +10 -0
  73. package/dist/src/internal/nitro/host/dev-host-workspace.js +1 -0
  74. package/dist/src/internal/nitro/host/dev-runner.d.ts +21 -0
  75. package/dist/src/internal/nitro/host/dev-runner.js +1 -0
  76. package/dist/src/internal/nitro/host/dev-server-http.d.ts +5 -0
  77. package/dist/src/internal/nitro/host/dev-server-http.js +1 -0
  78. package/dist/src/internal/nitro/host/dev-server-url.d.ts +6 -0
  79. package/dist/src/internal/nitro/host/dev-server-url.js +1 -0
  80. package/dist/src/internal/nitro/host/dev-workflow-world-setup.d.ts +9 -0
  81. package/dist/src/internal/nitro/host/dev-workflow-world-setup.js +1 -0
  82. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -1
  83. package/dist/src/internal/nitro/host/drained-nitro-dev-server.d.ts +53 -0
  84. package/dist/src/internal/nitro/host/drained-nitro-dev-server.js +1 -0
  85. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +4 -5
  86. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  87. package/dist/src/internal/nitro/host/start-development-server.d.ts +2 -5
  88. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  89. package/dist/src/internal/nitro/host/types.d.ts +6 -0
  90. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  91. package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +7 -0
  92. package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
  93. package/dist/src/internal/nitro/routes/schedule-task.d.ts +9 -0
  94. package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
  95. package/dist/src/internal/workflow/development-generation-context.d.ts +8 -0
  96. package/dist/src/internal/workflow/development-generation-context.js +1 -0
  97. package/dist/src/internal/workflow/development-world-client.d.ts +29 -0
  98. package/dist/src/internal/workflow/development-world-client.js +1 -0
  99. package/dist/src/internal/workflow/development-world-codec.d.ts +11 -0
  100. package/dist/src/internal/workflow/development-world-codec.js +1 -0
  101. package/dist/src/internal/workflow/development-world-protocol.d.ts +31 -0
  102. package/dist/src/internal/workflow/development-world-protocol.js +1 -0
  103. package/dist/src/internal/workflow/development-world-server.d.ts +27 -0
  104. package/dist/src/internal/workflow/development-world-server.js +1 -0
  105. package/dist/src/runtime/compiled-artifacts-source.d.ts +9 -0
  106. package/dist/src/runtime/compiled-artifacts-source.js +1 -1
  107. package/dist/src/runtime/durable-compiled-artifacts-source.d.ts +8 -0
  108. package/dist/src/runtime/durable-compiled-artifacts-source.js +1 -0
  109. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  110. package/dist/src/setup/scaffold/create/project.js +1 -1
  111. package/dist/src/shared/atomic-write-file.d.ts +1 -1
  112. package/dist/src/shared/atomic-write-file.js +1 -1
  113. package/dist/src/shared/rename-with-retry.d.ts +5 -0
  114. package/dist/src/shared/rename-with-retry.js +1 -0
  115. package/docs/agent-config.md +2 -0
  116. package/docs/concepts/execution-model-and-durability.md +1 -1
  117. package/docs/reference/cli.md +1 -1
  118. package/package.json +2 -1
  119. package/dist/src/compiled/_chunks/node/retry-DkR2H1Y0.js +0 -1
  120. package/dist/src/compiled/_chunks/node/token-ORseRyWn.js +0 -1
  121. package/dist/src/internal/bundler/nitro-node-file-trace.d.ts +0 -10
  122. package/dist/src/internal/bundler/nitro-node-file-trace.js +0 -1
  123. package/dist/src/internal/materialize-authored-external-dependencies.d.ts +0 -10
  124. package/dist/src/internal/materialize-authored-external-dependencies.js +0 -2
  125. package/dist/src/internal/nitro/host/dev-live-virtual-modules.d.ts +0 -15
  126. package/dist/src/internal/nitro/host/dev-live-virtual-modules.js +0 -1
  127. package/dist/src/internal/nitro/host/server-external-packages.d.ts +0 -5
  128. package/dist/src/internal/nitro/host/server-external-packages.js +0 -1
@@ -1 +1 @@
1
- import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroBuildDirectory}from"#internal/application/paths.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{captureDevLiveVirtualModules}from"#internal/nitro/host/dev-live-virtual-modules.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{transformDynamicToolExecute}from"#internal/workflow-bundle/dynamic-tool-transform.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`],LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function includesApplicationSurface(e){return e===`all`||e===`app`}function includesWorkflowSurface(e){return e===`all`||e===`flow`}function includesWorkflowStepRegistrations(e){return includesWorkflowSurface(e)}function manifestEnablesWorkflow(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.workflowTool!==void 0)}function manifestHasWebSocketChannel(e){return e.channels.some(e=>e.kind===`channel`&&e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.config.build?.externalDependencies??[]);return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...t,...SERVER_EXTERNAL_PACKAGES,...n])].filter(e=>e!==EVE_PACKAGE_NAME)}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let c=relative(r,i).replaceAll(`\\`,`/`);if(c.startsWith(`../`)&&(c=c.split(`/`).filter(e=>e!==`..`).join(`/`)),c.includes(`:`)||c.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return c}function createPackageRelativeTransformFilename(t){let n=normalizePath(resolvePackageRoot()).replace(/\/$/,``),r=normalizePath(t),i=n.toLowerCase(),a=r.toLowerCase(),o=`${n}/src/`,s=`${i}/src/`,c=`${n}/dist/src/`,l=`${i}/dist/src/`;if(a.startsWith(s))return`src/${r.slice(o.length)}`;if(a.startsWith(l))return`src/${r.slice(c.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})}),clearCachedStepTransformTargets}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})}),clearCachedStepTransformTargets}function addDynamicToolTransformPlugin(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({async transform(e,t){if(!t.includes(`/tools/`))return null;let n=await transformDynamicToolExecute(t,e);return n===null?null:{code:n.code,map:null}},name:`eve:dynamic-tool-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return normalizePath(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxBackendNames(e.compileResult.manifest),r=shouldPruneLocalSandboxBackends({configuredBackendNames:n,preset:t})?createCompiledSandboxBackendPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin((e.compileResult.manifest.extensionMounts??[]).map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace}))),s=[r,createOptionalEngineDependencyPlugin(a),o].filter(e=>e!==null);return{nitroRolldownConfig:createNitroBundlerConfig(s),nitroRollupConfig:createNitroBundlerConfig(s),tracedAppDependencies:collectHostedTraceDependencies(e,i)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestEnablesWorkflow(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t,n){if(addNitroRoutingImportSpecifierPlugin(e),includesWorkflowSurface(n)){let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir)}addDynamicToolTransformPlugin(e),t.compiledArtifacts.instrumentationSourcePath!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePath)}function configureNitroStepPlugins(e,t){return[addNitroStepModuleSideEffectsPlugin(e,{stepEntrypointPath:t}),addNitroStepTransformPlugin(e,{stepEntrypointPath:t})]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let n=resolveNitroBuildDirectory(e.appRoot),r=createApplicationNitroBundlerConfiguration(e,void 0);await prepareEveVersionedCacheDirectory(n);let i=await createNitro({_cli:{command:`dev`},buildDir:n,dev:!0,features:{websocket:!0},logLevel:1,plugins:createApplicationNitroPlugins(e),publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,vercel:createEveVercelOptions(!1),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(n),captureDevLiveVirtualModules(i);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e,`all`);let s=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of s)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,r){let i=resolveProductionNitroPreset(),a=createApplicationNitroBundlerConfiguration(e,i),s=createApplicationNitroPlugins(e);s.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(r.buildDir);let c=await createNitro({_cli:{command:`build`},buildDir:r.buildDir,dev:!1,features:{websocket:includesApplicationSurface(r.surface)&&manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:r.outputDir},preset:i,plugins:s,publicAssets:[],scanDirs:includesWorkflowStepRegistrations(r.surface)?[resolvePackageSourceDirectoryPath(`src/execution`)]:void 0,rolldownConfig:a.nitroRolldownConfig,rollupConfig:a.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:a.tracedAppDependencies,vercel:createEveVercelOptions(i===`vercel`&&includesApplicationSurface(r.surface))});return await writeEveVersionedCacheMetadata(r.buildDir),configureSharedApplicationNitro(c,e,r.surface),includesWorkflowStepRegistrations(r.surface)&&configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),includesApplicationSurface(r.surface)&&e.scheduleRegistrations.length>0&&(applyEveCronHandlerRoute(c),registerScheduleTaskHandlers(c,{artifactsConfig:createProductionNitroArtifactsConfig(),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureProductionNitroRoutes(c,e,r.surface),includesWorkflowStepRegistrations(r.surface)&&await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
1
+ import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{readFile}from"node:fs/promises";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{transformDynamicToolExecute}from"#internal/workflow-bundle/dynamic-tool-transform.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`],LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function includesApplicationSurface(e){return e===`all`||e===`app`}function includesWorkflowSurface(e){return e===`all`||e===`flow`}function includesWorkflowStepRegistrations(e){return includesWorkflowSurface(e)}function manifestEnablesWorkflow(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.workflowTool!==void 0)}function manifestHasWebSocketChannel(e){return e.channels.some(e=>e.kind===`channel`&&e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.config.build?.externalDependencies??[]);return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...t,...n])].filter(e=>e!==EVE_PACKAGE_NAME)}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let c=relative(r,i).replaceAll(`\\`,`/`);if(c.startsWith(`../`)&&(c=c.split(`/`).filter(e=>e!==`..`).join(`/`)),c.includes(`:`)||c.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return c}function createPackageRelativeTransformFilename(t){let n=normalizePath(resolvePackageRoot()).replace(/\/$/,``),r=normalizePath(t),i=n.toLowerCase(),a=r.toLowerCase(),o=`${n}/src/`,s=`${i}/src/`,c=`${n}/dist/src/`,l=`${i}/dist/src/`;if(a.startsWith(s))return`src/${r.slice(o.length)}`;if(a.startsWith(l))return`src/${r.slice(c.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})}),clearCachedStepTransformTargets}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})}),clearCachedStepTransformTargets}function addDynamicToolTransformPlugin(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({async transform(e,t){if(!t.includes(`/tools/`))return null;let n=await transformDynamicToolExecute(t,e);return n===null?null:{code:n.code,map:null}},name:`eve:dynamic-tool-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return normalizePath(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxBackendNames(e.compileResult.manifest),r=shouldPruneLocalSandboxBackends({configuredBackendNames:n,preset:t})?createCompiledSandboxBackendPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin((e.compileResult.manifest.extensionMounts??[]).map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace}))),s=[r,createOptionalEngineDependencyPlugin(a),o].filter(e=>e!==null);return{nitroRolldownConfig:createNitroBundlerConfig(s),nitroRollupConfig:createNitroBundlerConfig(s),tracedAppDependencies:collectHostedTraceDependencies(e,i)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestEnablesWorkflow(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t,n){if(addNitroRoutingImportSpecifierPlugin(e),includesWorkflowSurface(n)){let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir)}addDynamicToolTransformPlugin(e),t.compiledArtifacts.instrumentationSourcePath!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePath)}function configureNitroStepPlugins(e,t){return[addNitroStepModuleSideEffectsPlugin(e,{stepEntrypointPath:t}),addNitroStepTransformPlugin(e,{stepEntrypointPath:t})]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let n=e.workspace.nitroBuildDir,r=createApplicationNitroBundlerConfiguration(e,void 0),i=createApplicationNitroPlugins(e);await prepareEveVersionedCacheDirectory(n);let a=await createNitro({_cli:{command:`dev`},buildDir:n,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,vercel:createEveVercelOptions(!1),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(n);let s=join(a.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(a,e,`all`);let c=configureNitroStepPlugins(a,s);return a.hooks.hook(`dev:reload`,()=>{for(let e of c)e()}),externalizeDevelopmentWorkflowBundle(a,e),await configureDevelopmentNitroRoutes(a,e),await addNitroStepNoExternals(a,s),a}async function createProductionApplicationNitro(e,r){let i=resolveProductionNitroPreset(),a=createApplicationNitroBundlerConfiguration(e,i),s=createApplicationNitroPlugins(e);s.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(r.buildDir);let c=await createNitro({_cli:{command:`build`},buildDir:r.buildDir,dev:!1,features:{websocket:includesApplicationSurface(r.surface)&&manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:r.outputDir},preset:i,plugins:s,publicAssets:[],scanDirs:includesWorkflowStepRegistrations(r.surface)?[resolvePackageSourceDirectoryPath(`src/execution`)]:void 0,rolldownConfig:a.nitroRolldownConfig,rollupConfig:a.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:a.tracedAppDependencies,vercel:createEveVercelOptions(i===`vercel`&&includesApplicationSurface(r.surface))});return await writeEveVersionedCacheMetadata(r.buildDir),configureSharedApplicationNitro(c,e,r.surface),includesWorkflowStepRegistrations(r.surface)&&configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),includesApplicationSurface(r.surface)&&e.scheduleRegistrations.length>0&&(applyEveCronHandlerRoute(c),registerScheduleTaskHandlers(c,{artifactsConfig:createProductionNitroArtifactsConfig(),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureProductionNitroRoutes(c,e,r.surface),includesWorkflowStepRegistrations(r.surface)&&await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
@@ -0,0 +1,32 @@
1
+ import { DrainedNitroDevServer } from "#internal/nitro/host/drained-nitro-dev-server.js";
2
+ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
3
+ export type DevelopmentRebuildKind = "structural" | "unchanged" | "runtime";
4
+ /**
5
+ * Raised when generation activation fails after the replacement worker has
6
+ * already been swapped in. The server keeps serving on the new worker with
7
+ * the previous generation; the next rebuild retries activation.
8
+ */
9
+ export declare class PostCommitDevelopmentRebuildError extends Error {
10
+ constructor(cause: unknown);
11
+ }
12
+ /**
13
+ * Raised when an authored reload changes which process owns the Workflow
14
+ * World. That ownership is fixed when the development server starts, so the
15
+ * existing server must keep serving until the user restarts it.
16
+ */
17
+ export declare class DevelopmentWorkflowWorldChangeRequiresRestartError extends Error {
18
+ constructor();
19
+ }
20
+ export interface DevelopmentRebuildResult {
21
+ readonly host: PreparedDevelopmentApplicationHost;
22
+ readonly kind: DevelopmentRebuildKind;
23
+ }
24
+ export interface DevelopmentAuthoredRebuildCoordinator {
25
+ rebuild(input: {
26
+ readonly changedPaths: readonly string[];
27
+ }): Promise<DevelopmentRebuildResult>;
28
+ }
29
+ export declare function createDevelopmentAuthoredRebuildCoordinator(input: {
30
+ readonly devServer: DrainedNitroDevServer;
31
+ readonly initialHost: PreparedDevelopmentApplicationHost;
32
+ }): Promise<DevelopmentAuthoredRebuildCoordinator>;
@@ -0,0 +1 @@
1
+ import{relative,resolve}from"node:path";import{stageDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{buildDevelopmentHostCandidate}from"#internal/nitro/host/dev-host-candidate.js";import{computeDevelopmentHostFingerprint}from"#internal/nitro/host/dev-host-fingerprint.js";import{removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import"#internal/nitro/host/drained-nitro-dev-server.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";var PostCommitDevelopmentRebuildError=class extends Error{constructor(e){super(`The development worker was replaced but its generation failed to activate. The server keeps serving the previous generation; the next rebuild retries activation.`,{cause:e}),this.name=`PostCommitDevelopmentRebuildError`}},DevelopmentWorkflowWorldChangeRequiresRestartError=class extends Error{constructor(){super(`Changing experimental.workflow.world between the parent-owned local World and a custom World requires restarting eve dev.`),this.name=`DevelopmentWorkflowWorldChangeRequiresRestartError`}};async function createDevelopmentAuthoredRebuildCoordinator(e){return new TransactionalDevelopmentAuthoredRebuildCoordinator({currentHostFingerprint:await computeDevelopmentHostFingerprint(e.initialHost),currentRuntimeFingerprint:e.initialHost.generation.fingerprint,devServer:e.devServer,initialHost:e.initialHost})}var TransactionalDevelopmentAuthoredRebuildCoordinator=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.initialHost,this.#t=e.currentHostFingerprint,this.#n=e.currentRuntimeFingerprint,this.#r=e.devServer,this.#i=usesParentDevelopmentWorkflowWorld(e.initialHost.compileResult.manifest.config.experimental?.workflow?.world)}async rebuild(e){let t=this.#e,r=stageDevelopmentEnvironmentFiles(t.appRoot),a;try{if(a=await prepareDevelopmentApplicationHost(t.appRoot),usesParentDevelopmentWorkflowWorld(a.compileResult.manifest.config.experimental?.workflow?.world)!==this.#i)throw new DevelopmentWorkflowWorldChangeRequiresRestartError;let n=await computeDevelopmentHostFingerprint(a),o=a.generation.fingerprint,s=n!==this.#t,c=o!==this.#n;if(!s&&!c)return await discardPreparedHost(a),a=void 0,r.commit(),{host:t,kind:`unchanged`};if(!s){await removeDevelopmentHostWorkspace(a.workspace);let i=retainActiveHostWorkspace(t,a);return await activateDevelopmentGeneration({appRoot:i.appRoot,generation:i.generation}),this.#o(i,n,o),a=void 0,r.commit(),startSandboxPrewarmAfterCommit(i,e.changedPaths),{host:i,kind:`runtime`}}let l=await this.#a({hasRuntimeChange:c,nextHost:a,nextHostFingerprint:n,nextRuntimeFingerprint:o});return a=void 0,r.commit(),startSandboxPrewarmAfterCommit(l.host,e.changedPaths),l}catch(e){throw e instanceof PostCommitDevelopmentRebuildError?(r.commit(),e):(r.rollback(),a===void 0?e:await discardFailedHost(e,a))}}async#a(e){let t=e.nextHost;e.hasRuntimeChange||(await discardDevelopmentGeneration(e.nextHost.generation),t={...e.nextHost,generation:this.#e.generation});let n=await createDevelopmentApplicationNitro(t),r=await buildDevelopmentHostCandidate({host:t,nitro:n}),i=t.workspace;if(await this.#r.replaceWorker({dispose:async()=>await removeDevelopmentHostWorkspace(i),entry:r.entry,workerData:r.workerData}),e.hasRuntimeChange)try{await activateDevelopmentGeneration({appRoot:t.appRoot,generation:t.generation})}catch(n){throw await discardDevelopmentGeneration(t.generation).catch(()=>void 0),this.#o({...t,generation:this.#e.generation},e.nextHostFingerprint,this.#n),new PostCommitDevelopmentRebuildError(n)}return this.#o(t,e.nextHostFingerprint,e.hasRuntimeChange?e.nextRuntimeFingerprint:this.#n),{host:t,kind:`structural`}}#o(e,t,n){this.#e=e,this.#t=t,this.#n=n}};function retainActiveHostWorkspace(e,t){return{...t,compiledArtifacts:e.compiledArtifacts,workflowBuildDir:e.workflowBuildDir,workspace:e.workspace}}function startSandboxPrewarmAfterCommit(e,t){if(!hasSandboxRelatedChange(e.compileResult.project.agentRoot,t))return;let n=createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world});startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:resolveNitroCompiledArtifactsSource(n),log:e=>console.log(e)})}function hasSandboxRelatedChange(n,r){return r.some(r=>{let i=relative(resolve(n),resolve(r)),a=i.split(/[\\/]/u);return a[0]===`..`||i===``?!1:a[0]===`sandbox.ts`||a[0]===`sandbox`||a[0]===`workspace`||a[0]===`skills`})}async function discardPreparedHost(e){let t=(await Promise.allSettled([discardDevelopmentGeneration(e.generation),removeDevelopmentHostWorkspace(e.workspace)])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length>0)throw AggregateError(t,`Failed to discard development host "${e.workspace.rootDir}".`)}async function discardFailedHost(e,t){try{return await discardPreparedHost(t),e}catch(t){return AggregateError([e,t],`Development rebuild rollback failed.`,{cause:e})}}export{DevelopmentWorkflowWorldChangeRequiresRestartError,PostCommitDevelopmentRebuildError,createDevelopmentAuthoredRebuildCoordinator};
@@ -1,15 +1,5 @@
1
- import type { Nitro } from "nitro/types";
2
- import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
3
- type DevelopmentWatcherNitroOptions = Pick<Nitro["options"], "experimental" | "handlers" | "scheduledTasks" | "tasks" | "virtual"> & Partial<Pick<Nitro["options"], "dev" | "preset">>;
4
- interface DevelopmentWatcherNitro {
5
- hooks: {
6
- callHook: Nitro["hooks"]["callHook"];
7
- };
8
- options: DevelopmentWatcherNitroOptions;
9
- routing: {
10
- sync(): void;
11
- };
12
- }
1
+ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
2
+ import type { DevelopmentAuthoredRebuildCoordinator } from "#internal/nitro/host/dev-authored-rebuild-coordinator.js";
13
3
  /**
14
4
  * Handle for the authored-source development watcher.
15
5
  */
@@ -25,7 +15,6 @@ export interface AuthoredSourceWatcherHandle {
25
15
  * triggers Nitro rebuild reloads only when structural runtime wiring changes.
26
16
  */
27
17
  export declare function startAuthoredSourceWatcher(input: {
28
- nitro: DevelopmentWatcherNitro;
29
- preparedHost: PreparedApplicationHost;
18
+ coordinator: DevelopmentAuthoredRebuildCoordinator;
19
+ preparedHost: PreparedDevelopmentApplicationHost;
30
20
  }): Promise<AuthoredSourceWatcherHandle>;
31
- export {};
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{clearCompiledRuntimeAgentBundleCache}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{computeChannelRouteRegistrations,syncChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";import{watch as watch$1}from"#compiled/chokidar/index.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,o=!1,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch$1(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),p=waitForWatcherReady(f),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t,u=hasSandboxRelatedChange(l.compileResult.project.agentRoot,o),p=hasDevelopmentEnvironmentFileChange(l.appRoot,o);r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{p&&loadDevelopmentEnvironmentFiles(l.appRoot);let n=await prepareDevelopmentApplicationHost(l.appRoot),r=createDevelopmentNitroArtifactsConfig({appRoot:n.appRoot});u&&startDevelopmentSandboxPrewarmInBackground({appRoot:n.appRoot,compiledArtifactsSource:resolveNitroCompiledArtifactsSource(r),log:e=>console.log(e)});let i=syncChannelVirtualHandlers(e.nitro,{artifactsConfig:r,next:computeChannelRouteRegistrations(n),previous:computeChannelRouteRegistrations(l)});clearCompiledRuntimeAgentBundleCache(),t=n,i||p?(console.log(STRUCTURAL_RELOAD_LOG_LINE),await e.nitro.hooks.callHook(`rollup:reload`)):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(n),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)};return f.on(`all`,(e,t)=>{n||!o||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,o=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),r=await resolveTsConfigWatchPaths(e.appRoot),i=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of i)t.add(e);for(let e of r)t.add(e);for(let r of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(r,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return e.replaceAll(`\\`,`/`)}function hasDevelopmentEnvironmentFileChange(e,t){let n=new Set(getDevelopmentEnvironmentFilePaths(e).map(e=>toWatchPathKey(resolve(e))));return t.some(e=>n.has(toWatchPathKey(resolve(e))))}function hasSandboxRelatedChange(e,t){return t.some(t=>{let n=toAgentRelativePath(e,t);return n===`sandbox.ts`||n.startsWith(`sandbox/`)||n===`workspace`||n.startsWith(`workspace/`)||n===`skills`||n.startsWith(`skills/`)})}function toAgentRelativePath(e,t){let n=toWatchPathKey(relative(resolve(e),resolve(t)));return n===`..`||n.startsWith(`../`)||n===``?``:n}function resolveLockfileSearchDirectories(e){let n=resolve(e),r=[n],a=n;for(;;){if(hasWatchRootMarker(a))return r;let e=dirname(a);if(e===a)return[n];a=e,r.push(a)}}function hasWatchRootMarker(t){return WATCH_ROOT_MARKER_NAMES.some(r=>existsSync(join(t,r)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e){return e.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))}export{startAuthoredSourceWatcher};
1
+ import{existsSync}from"node:fs";import{dirname,join,normalize,resolve,sep}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=new Map,s=new Set,c=await resolveAuthoredWatchPaths(t),l=createWatchPathMap(c),u=watch$1(c,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),d=waitForWatcherReady(u),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...o.values()];if(!i&&r.length===0)return;let a=[...s];o.clear(),s.clear();let c=t;r.length>0&&console.log(formatChangeDetectedLogLine(c.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:a});t=n.host,n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),l=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:l,watcher:u})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)};return u.on(`all`,(e,t)=>{n||!a||e===`addDir`||e===`unlinkDir`||(o.set(`${e}:${t}`,{event:e,path:t}),s.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await d,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await u.close(),await r},flush,rebuild:async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),r=await resolveTsConfigWatchPaths(e.appRoot),i=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of i)t.add(e);for(let e of r)t.add(e);for(let r of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(r,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let n=resolve(e),r=[n],a=n;for(;;){if(hasWatchRootMarker(a))return r;let e=dirname(a);if(e===a)return[n];a=e,r.push(a)}}function hasWatchRootMarker(t){return WATCH_ROOT_MARKER_NAMES.some(r=>existsSync(join(t,r)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))}export{startAuthoredSourceWatcher};
@@ -0,0 +1,16 @@
1
+ import type { Nitro } from "nitro/types";
2
+ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
3
+ export interface DevelopmentWorkerPayload {
4
+ readonly entry: string;
5
+ readonly workerData: Readonly<Record<string, unknown>>;
6
+ }
7
+ /**
8
+ * Builds one host candidate in its invocation-owned workspace and returns the
9
+ * worker payload Nitro emitted for it. The Nitro instance is closed before
10
+ * returning: the payload's entry lives on disk in the workspace, so nothing
11
+ * retains the builder.
12
+ */
13
+ export declare function buildDevelopmentHostCandidate(input: {
14
+ readonly host: PreparedDevelopmentApplicationHost;
15
+ readonly nitro: Nitro;
16
+ }): Promise<DevelopmentWorkerPayload>;
@@ -0,0 +1 @@
1
+ import{resolve}from"node:path";import{build,prepare}from"nitro/builder";async function buildDevelopmentHostCandidate(r){let i=r.nitro,a=!1,o,s,c,l=new Promise(e=>{c=e}),u=i.hooks.hook(`dev:reload`,t=>{a||(a=!0,o={entry:t?.entry??resolve(i.options.output.dir,i.options.output.serverDir,`index.mjs`),workerData:t?.workerData??{}},c?.())}),d=i.hooks.hook(`dev:error`,e=>{a||(a=!0,s=e,c?.())});try{if(await prepare(i),await build(i),await waitForSignal(l),s!==void 0)throw s instanceof Error?s:Error(String(s));if(o===void 0||o.entry.length===0)throw Error(`Nitro did not emit a development worker entry.`);return o}finally{u(),d(),await i.close().catch(()=>void 0)}}async function waitForSignal(e){let t;try{await Promise.race([e,new Promise((e,n)=>{t=setTimeout(()=>n(Error(`Timed out waiting for the Nitro dev build to emit a worker.`)),12e4)})])}finally{clearTimeout(t)}}export{buildDevelopmentHostCandidate};
@@ -0,0 +1,2 @@
1
+ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
2
+ export declare function computeDevelopmentHostFingerprint(host: PreparedDevelopmentApplicationHost): Promise<string>;
@@ -0,0 +1 @@
1
+ import{readFile}from"node:fs/promises";import{readDevelopmentEnvironmentHostValues}from"#cli/dev/environment.js";import{createHash}from"node:crypto";import{computeChannelRouteRegistrations}from"#internal/nitro/host/channel-routes.js";async function computeDevelopmentHostFingerprint(e){let r=e.compileResult.manifest,i=[r,...r.subagents.map(e=>e.agent)],a={agentName:r.config.name,bundler:{externalDependencies:[...new Set(i.flatMap(e=>e.config.build?.externalDependencies??[]))].sort((e,t)=>e.localeCompare(t)),extensionScopes:(r.extensionMounts??[]).map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot})).sort((e,t)=>e.sourceRoot.localeCompare(t.sourceRoot)),sandboxBackends:[...new Set(i.map(e=>e.sandbox?.backendName).filter(e=>e!==void 0))].sort((e,t)=>e.localeCompare(t))},channels:computeChannelRouteRegistrations(e),environment:readDevelopmentEnvironmentHostValues(e.appRoot),instrumentation:await readInstrumentationSource(e),workflow:{enabled:i.some(e=>e.workflowTool!==void 0),world:r.config.experimental?.workflow?.world??`local`}};return createHash(`sha256`).update(JSON.stringify(a)).digest(`hex`)}async function readInstrumentationSource(t){let n=t.compiledArtifacts.instrumentationSourcePath;return n===void 0?null:await readFile(n,`utf8`)}export{computeDevelopmentHostFingerprint};
@@ -0,0 +1,10 @@
1
+ export interface DevelopmentHostWorkspace {
2
+ readonly artifactsDir: string;
3
+ readonly compilerArtifactsDir: string;
4
+ readonly nitroBuildDir: string;
5
+ readonly nitroOutputDir: string;
6
+ readonly rootDir: string;
7
+ readonly workflowBuildDir: string;
8
+ }
9
+ export declare function createDevelopmentHostWorkspace(appRoot: string): Promise<DevelopmentHostWorkspace>;
10
+ export declare function removeDevelopmentHostWorkspace(workspace: DevelopmentHostWorkspace): Promise<void>;
@@ -0,0 +1 @@
1
+ import{join}from"node:path";import{mkdir,rm}from"node:fs/promises";import{randomUUID}from"node:crypto";async function createDevelopmentHostWorkspace(t){let n=join(t,`.eve`,`dev-hosts`,randomUUID()),r={artifactsDir:join(n,`artifacts`),compilerArtifactsDir:join(n,`compiler`),nitroBuildDir:join(n,`nitro`),nitroOutputDir:join(n,`output`),rootDir:n,workflowBuildDir:join(n,`workflow`)};return await mkdir(n,{recursive:!0}),r}async function removeDevelopmentHostWorkspace(e){await rm(e.rootDir,{force:!0,recursive:!0})}export{createDevelopmentHostWorkspace,removeDevelopmentHostWorkspace};
@@ -0,0 +1,21 @@
1
+ export interface DevelopmentRunner {
2
+ readonly closed: boolean;
3
+ close(cause?: unknown): Promise<void>;
4
+ fetch(request: Request, init?: RequestInit): Promise<Response>;
5
+ onceClosed(listener: (cause?: unknown) => void): void;
6
+ upgrade(input: {
7
+ readonly node: {
8
+ readonly head: Buffer;
9
+ readonly req: import("node:http").IncomingMessage;
10
+ readonly socket: import("node:net").Socket;
11
+ };
12
+ }): Promise<void>;
13
+ waitForReady(timeout: number): Promise<void>;
14
+ }
15
+ export interface DevelopmentRunnerInput {
16
+ readonly entry: string;
17
+ readonly name: string;
18
+ readonly workerData: Readonly<Record<string, unknown>>;
19
+ }
20
+ export type DevelopmentRunnerFactory = (input: DevelopmentRunnerInput) => DevelopmentRunner;
21
+ export declare const createNodeDevelopmentRunner: DevelopmentRunnerFactory;
@@ -0,0 +1 @@
1
+ import{resolvePackageCompiledFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{Worker}from"node:worker_threads";import{BaseEnvRunner}from"#compiled/env-runner/index.js";var NodeDevelopmentRunner=class extends BaseEnvRunner{#e;#t=new Set;#n;constructor(t){let n=resolvePackageCompiledFilePath(`src/compiled/env-runner/node-worker.js`);super({data:{entry:t.entry,...t.workerData},hooks:{onClose:(e,t)=>{let n=[...this.#t];this.#t.clear();for(let e of n)e(t)}},name:t.name,workerEntry:n}),this._initWithVirtualData(()=>this.#r())}onceClosed(e){if(this.closed){e(this.#e);return}this.#t.add(e)}sendMessage(e){if(this.#n===void 0)throw Error(`Development worker is not initialized.`);this.#n.postMessage(e)}async waitForReady(e){try{await super.waitForReady(e)}catch(e){throw this.#e===void 0?e:Error(`Development worker failed before readiness: ${this.#e instanceof Error?this.#e.message:String(this.#e)}`,{cause:this.#e})}}_hasRuntime(){return this.#n!==void 0}_runtimeType(){return`worker`}async _closeRuntime(){let e=this.#n;e!==void 0&&(this.#n=void 0,e.removeAllListeners(),await e.terminate())}_handleMessage(e){isWorkerInitializationError(e)&&(this.#e=Error(e.error)),super._handleMessage(e)}#r(){if(!existsSync(this._workerEntry)){this.close(`Development worker entry not found at "${this._workerEntry}".`);return}let e=new Worker(this._workerEntry,{env:process.env,workerData:{name:this._name,...this._data}});this.#n=e,e.once(`error`,e=>{this.#e=e,this.close(e)}),e.once(`exit`,e=>{let t=Error(`Development worker exited with code ${String(e)}.`);this.#e??=t,this.close(t)}),e.on(`message`,e=>this._handleMessage(e))}};const createNodeDevelopmentRunner=e=>new NodeDevelopmentRunner(e);function isWorkerInitializationError(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.event===`init-error`&&typeof t.error==`string`}export{createNodeDevelopmentRunner};
@@ -0,0 +1,5 @@
1
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
2
+ export declare function createPublicRequest(request: IncomingMessage, signal: AbortSignal): Request;
3
+ export declare function writeResponse(response: ServerResponse, webResponse: Response, signal: AbortSignal): Promise<void>;
4
+ export declare function writeRequestError(response: ServerResponse, error: unknown): void;
5
+ export declare function closeServer(server: Server): Promise<void>;
@@ -0,0 +1 @@
1
+ import{toErrorMessage}from"#shared/errors.js";import{Readable}from"node:stream";function createPublicRequest(e,n){let r=e.headers.host??`localhost`,i=new URL(e.url??`/`,`http://${r}`),a=new Headers;for(let[t,n]of Object.entries(e.headers))if(Array.isArray(n))for(let e of n)a.append(t,e);else n!==void 0&&a.set(t,n);let o=e.method!==`GET`&&e.method!==`HEAD`;return new Request(i,{body:o?Readable.toWeb(e):void 0,duplex:o?`half`:void 0,headers:a,method:e.method,signal:n})}async function writeResponse(e,n,r){if(e.destroyed){await n.body?.cancel();return}e.statusCode=n.status,e.statusMessage=n.statusText;let i=n.headers.getSetCookie?.call(n.headers)??[];if(n.headers.forEach((t,n)=>{n.toLowerCase()!==`set-cookie`&&e.setHeader(n,t)}),i.length>0&&e.setHeader(`set-cookie`,[...i]),n.body===null){await endResponse(e);return}let a=Readable.fromWeb(n.body),cancelBody=()=>a.destroy(r.reason);r.addEventListener(`abort`,cancelBody,{once:!0});try{await new Promise((t,n)=>{a.once(`error`,n),e.once(`error`,n),e.once(`close`,()=>{e.writableEnded||n(Error(`Development client disconnected.`))}),e.once(`finish`,t),a.pipe(e)})}finally{r.removeEventListener(`abort`,cancelBody),!a.destroyed&&(r.aborted||e.destroyed)&&a.destroy()}}function writeRequestError(t,n){if(t.headersSent){t.destroy();return}t.statusCode=503,t.setHeader(`content-type`,`application/json; charset=utf-8`),!t.writableEnded&&!t.destroyed&&t.end(JSON.stringify({error:toErrorMessage(n)}))}function closeServer(e){if(!e.listening)return Promise.resolve();let t=new Promise((t,n)=>{e.close(e=>{e===void 0?t():n(e)})});return e.closeIdleConnections?.(),t}async function endResponse(e){await new Promise((t,n)=>{e.once(`error`,n),e.end(t)})}export{closeServer,createPublicRequest,writeRequestError,writeResponse};
@@ -0,0 +1,6 @@
1
+ export declare const DEFAULT_DEVELOPMENT_SERVER_HOST = "127.0.0.1";
2
+ /**
3
+ * Rewrites a server URL whose hostname is a wildcard listen address into a
4
+ * loopback URL on the same address family.
5
+ */
6
+ export declare function normalizeDevelopmentServerClientUrl(serverUrl: string): string;
@@ -0,0 +1 @@
1
+ const DEFAULT_DEVELOPMENT_SERVER_HOST=`127.0.0.1`,IPV6_WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return IPV6_WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`[::1]`,t.toString()):t.hostname===`0.0.0.0`?(t.hostname=DEFAULT_DEVELOPMENT_SERVER_HOST,t.toString()):e}export{DEFAULT_DEVELOPMENT_SERVER_HOST,normalizeDevelopmentServerClientUrl};
@@ -0,0 +1,9 @@
1
+ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
2
+ import { type ParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-server.js";
3
+ export declare function createDevelopmentWorkflowWorld(input: {
4
+ readonly appRoot: string;
5
+ readonly preparedHost: PreparedDevelopmentApplicationHost;
6
+ readonly transportSecret: string;
7
+ }): ParentDevelopmentWorkflowWorld | undefined;
8
+ export declare function installWorkflowTransportEnvironment(appRoot: string, secret: string): () => void;
9
+ export declare function installWorkflowLocalQueueEnvironment(serverUrl: string): () => void;
@@ -0,0 +1 @@
1
+ import{basename}from"node:path";import{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_SECRET_ENV,usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{readActiveDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";import{normalizeDevelopmentServerClientUrl}from"#internal/nitro/host/dev-server-url.js";import{createParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-server.js";const WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`;function createDevelopmentWorkflowWorld(t){if(usesParentDevelopmentWorkflowWorld(t.preparedHost.compileResult.manifest.config.experimental?.workflow?.world))return createParentDevelopmentWorkflowWorld({agentName:t.preparedHost.compileResult.manifest.config.name,appRoot:t.appRoot,resolveActiveGenerationId:()=>{let n=readActiveDevelopmentRuntimeArtifactsSnapshot(t.appRoot);if(n===void 0)throw Error(`Development runtime generation is unavailable.`);return basename(n.snapshotRoot)},transportSecret:t.transportSecret})}function installWorkflowTransportEnvironment(e,r){let i=process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV],a=process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV];return process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]=r,process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV]=e,()=>{i===void 0?delete process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]:process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]=i,a===void 0?delete process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV]:process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV]=a}}function installWorkflowLocalQueueEnvironment(e){let t=process.env[WORKFLOW_LOCAL_BASE_URL_ENV],n=process.env[PORT_ENV],r=new URL(normalizeDevelopmentServerClientUrl(e));return process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=r.origin,r.port&&(process.env[PORT_ENV]=r.port),()=>{t===void 0?delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV]:process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=t,n===void 0?delete process.env[PORT_ENV]:process.env[PORT_ENV]=n}}export{createDevelopmentWorkflowWorld,installWorkflowLocalQueueEnvironment,installWorkflowTransportEnvironment};
@@ -1 +1 @@
1
- import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules}from"#runtime/schedules/resolve-schedule.js";var UnknownDevScheduleError=class extends Error{availableScheduleIds;scheduleId;constructor(e,t){let n=t.length===0?`No schedules are defined in this app.`:`Available schedules: ${t.map(e=>`"${e}"`).join(`, `)}.`;super(`Unknown schedule "${e}". ${n}`),this.name=`UnknownDevScheduleError`,this.scheduleId=e,this.availableScheduleIds=t}};async function dispatchScheduleInDev(r){let{appRoot:i,moduleMapLoaderPath:a}=r.artifactsConfig;if(!i||!a)throw Error(`Dev schedule dispatch requires "appRoot" and "moduleMapLoaderPath" in the artifacts config.`);let o=createScheduleRegistrations(await loadResolvedCompiledSchedules({compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(i,{moduleMapLoaderPath:a})})),s=o.find(e=>e.scheduleId===r.scheduleId);if(s===void 0)throw new UnknownDevScheduleError(r.scheduleId,o.map(e=>e.scheduleId));let{dispatchScheduleTask:c}=await import(`#internal/nitro/routes/schedule-task.js`),l=await c(s.taskName,r.artifactsConfig);return{scheduleId:l.scheduleId,sessionIds:[...l.sessionIds]}}export{UnknownDevScheduleError,dispatchScheduleInDev};
1
+ import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules}from"#runtime/schedules/resolve-schedule.js";var UnknownDevScheduleError=class extends Error{availableScheduleIds;scheduleId;constructor(e,t){let n=t.length===0?`No schedules are defined in this app.`:`Available schedules: ${t.map(e=>`"${e}"`).join(`, `)}.`;super(`Unknown schedule "${e}". ${n}`),this.name=`UnknownDevScheduleError`,this.scheduleId=e,this.availableScheduleIds=t}};async function dispatchScheduleInDev(r){let{appRoot:i,moduleMapLoaderPath:a}=r.artifactsConfig;if(!i||!a)throw Error(`Dev schedule dispatch requires "appRoot" and "moduleMapLoaderPath" in the artifacts config.`);let o=resolveNitroCompiledArtifactsSource(r.artifactsConfig),s=createScheduleRegistrations(await loadResolvedCompiledSchedules({compiledArtifactsSource:o})),c=s.find(e=>e.scheduleId===r.scheduleId);if(c===void 0)throw new UnknownDevScheduleError(r.scheduleId,s.map(e=>e.scheduleId));let{dispatchScheduleTaskFromArtifacts:l}=await import(`#internal/nitro/routes/schedule-task.js`),u=await l(c.taskName,o);return{scheduleId:u.scheduleId,sessionIds:[...u.sessionIds]}}export{UnknownDevScheduleError,dispatchScheduleInDev};
@@ -0,0 +1,53 @@
1
+ import { type Server } from "node:http";
2
+ import { type DevelopmentRunnerFactory } from "#internal/nitro/host/dev-runner.js";
3
+ export interface DrainedDevServerListener {
4
+ close(): Promise<void>;
5
+ readonly node: {
6
+ readonly server: Server;
7
+ };
8
+ ready(): Promise<void>;
9
+ readonly url: string | undefined;
10
+ }
11
+ export interface DevelopmentWorkerReplacement {
12
+ readonly dispose?: () => Promise<void>;
13
+ readonly entry: string;
14
+ readonly workerData: Readonly<Record<string, unknown>>;
15
+ }
16
+ interface DevServerLogger {
17
+ error(message: unknown, ...details: unknown[]): unknown;
18
+ }
19
+ /**
20
+ * Development server with drained worker replacement: `replaceWorker` swaps
21
+ * to a ready candidate while the retired worker keeps serving the responses
22
+ * and sockets it already admitted — without bound, a streaming turn can hold
23
+ * one for minutes — and is terminated once its last exchange settles. Stock
24
+ * Nitro's dev server terminates the previous worker as soon as the next one
25
+ * attaches, which resets admitted work; this class exists solely to close
26
+ * that gap and is intended to be deleted in favor of `createDevServer` once
27
+ * equivalent drain semantics are available upstream.
28
+ */
29
+ export declare class DrainedNitroDevServer {
30
+ #private;
31
+ constructor(logger?: DevServerLogger, createRunner?: DevelopmentRunnerFactory);
32
+ setControlHandler(handler: (request: Request) => Promise<Response | undefined>): void;
33
+ /**
34
+ * Enables signed client-address metadata on requests forwarded to
35
+ * workers. Without it the worker only ever observes the parent's loopback
36
+ * hop as the request's peer address.
37
+ */
38
+ setClientAddressSecret(secret: string): void;
39
+ /**
40
+ * Swaps to a ready worker built from `entry`. Throws without touching the
41
+ * active worker when the candidate fails readiness. `dispose` is invoked
42
+ * once the worker created here has fully retired (drained, crashed, or
43
+ * closed at shutdown), so a caller can tie workspace cleanup to it.
44
+ */
45
+ replaceWorker(replacement: DevelopmentWorkerReplacement): Promise<void>;
46
+ listen(input: {
47
+ readonly hostname: string;
48
+ readonly port: number;
49
+ }): DrainedDevServerListener;
50
+ waitForActiveRunner(timeoutMs?: number): Promise<void>;
51
+ close(): Promise<void>;
52
+ }
53
+ export {};
@@ -0,0 +1 @@
1
+ import{createServer}from"node:http";import{toErrorMessage}from"#shared/errors.js";import{closeServer,createPublicRequest,writeRequestError,writeResponse}from"#internal/nitro/host/dev-server-http.js";import{createNodeDevelopmentRunner}from"#internal/nitro/host/dev-runner.js";import{stampDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";const RUNNER_READY_TIMEOUT_MS=6e4;var DrainedNitroDevServer=class{#e;#t=new Set;#n=new Set;#r;#i;#a=[];#o;#s=!1;#c;#l;#u;#d=Promise.resolve();#f=0;constructor(e=console,t=createNodeDevelopmentRunner){this.#e=t,this.#r=e}setControlHandler(e){this.#l=e}setClientAddressSecret(e){this.#c=e}replaceWorker(e){let t=this.#d.catch(()=>void 0).then(async()=>await this.#p(e));return this.#d=t.catch(()=>void 0),t}async#p(e){if(this.#s)throw Error(`Development server is closed.`);let t={activeExchanges:0,dispose:e.dispose,disposed:!1,entry:e.entry,quietListeners:[],releasePromise:void 0,runner:this.#e({entry:e.entry,name:`eve-dev-${String(this.#f++)}`,workerData:e.workerData}),workerData:e.workerData};this.#u=t;try{await t.runner.waitForReady(RUNNER_READY_TIMEOUT_MS)}catch(e){throw await t.runner.close(e).catch(()=>void 0),await this.#_(t),e}finally{this.#u=void 0}if(this.#s)throw await this.#h(t),Error(`Development server closed before the worker was ready.`);let n=this.#i;this.#i=t,t.runner.onceClosed(()=>{this.#v(t)}),this.#C(),n!==void 0&&this.#y(n)}listen(t){if(this.#s)throw Error(`Development server is closed.`);let r=new Set,i=createServer((e,t)=>{this.#x(e,t)});i.on(`connection`,e=>{r.add(e),e.once(`close`,()=>r.delete(e))}),i.on(`upgrade`,(e,t,n)=>{this.#S(e,t,n)});let a,o=new Promise((e,n)=>{let onError=e=>{i.off(`listening`,onListening),n(e)},onListening=()=>{i.off(`error`,onError);let r=i.address();if(r===null||typeof r==`string`){n(Error(`Development server did not expose a TCP address.`));return}a=`http://${t.hostname.includes(`:`)?`[${t.hostname}]`:t.hostname}:${String(r.port)}/`,e()};i.once(`error`,onError),i.once(`listening`,onListening),i.listen({host:t.hostname,port:t.port})}),s,c={beginClose:()=>(s??=closeServer(i).finally(()=>{this.#n.delete(c)}),s),destroySockets:()=>{for(let e of r)e.destroy()}};return this.#n.add(c),{async close(){let e=c.beginClose();c.destroySockets(),await e},node:{server:i},ready:async()=>await o,get url(){return a}}}async waitForActiveRunner(e=RUNNER_READY_TIMEOUT_MS){let t=Date.now()+e;for(;this.#i===void 0&&!this.#s;){if(Date.now()>=t)throw Error(`Timed out waiting for the development worker to become ready.`);await new Promise(e=>{this.#a.push(e),setTimeout(e,100)})}if(this.#s)throw Error(`Development server is closed.`)}close(){return this.#o??=this.#m(),this.#o}async#m(){this.#s=!0,this.#C(),await this.#u?.runner.close(Error(`Development server is closing.`)).catch(()=>void 0),await this.#d.catch(()=>void 0);let e=[...this.#n],t=e.map(e=>e.beginClose()),n=[this.#i,...this.#t].filter(e=>e!==void 0);this.#i=void 0,this.#t.clear(),await Promise.all(n.map(async e=>await this.#h(e)));for(let t of e)t.destroySockets();await Promise.all(t)}#h(e){return e.releasePromise??=this.#g(e),e.releasePromise}async#g(e){await e.runner.close().catch(()=>void 0),await this.#_(e)}async#_(e){e.dispose===void 0||e.disposed||(e.disposed=!0,await e.dispose().catch(e=>{this.#r.error(`[eve:dev] failed to dispose a retired dev host: ${toErrorMessage(e)}`)}))}async#v(e){if(this.#s||this.#i!==e)return;this.#i=void 0,this.#r.error(`[eve:dev] dev worker exited; restarting.`);let n=this.#d.catch(()=>void 0).then(async()=>{if(this.#s||this.#i!==void 0){await this.#h(e);return}e.disposed=!0,e.releasePromise=Promise.resolve(),await this.#p({dispose:e.dispose,entry:e.entry,workerData:e.workerData})});this.#d=n.catch(()=>void 0);try{await n}catch(e){this.#r.error(`[eve:dev] dev worker restart failed: ${toErrorMessage(e)}`)}}#y(e){this.#t.add(e);let finishDrain=()=>{this.#h(e).finally(()=>this.#t.delete(e))};if(e.activeExchanges===0){finishDrain();return}e.quietListeners.push(finishDrain)}#b(e){e.activeExchanges+=1;let t=!1;return()=>{if(!t&&(t=!0,--e.activeExchanges,e.activeExchanges===0))for(let t of e.quietListeners.splice(0))t()}}async#x(e,t){let n=new AbortController,abortRequest=e=>{n.signal.aborted||n.abort(e)};e.once(`error`,abortRequest),t.once(`close`,()=>{t.writableEnded||abortRequest()});let o;try{let i=createPublicRequest(e,n.signal);stampDevelopmentClientAddress(i.headers,e.socket.remoteAddress??void 0,this.#c);let c=await this.#l?.(i);if(c!==void 0){await writeResponse(t,c,n.signal);return}await this.waitForActiveRunner();let l=this.#i;if(l===void 0)throw Error(`Development worker is unavailable.`);o=this.#b(l),await writeResponse(t,await l.runner.fetch(i,{signal:n.signal}),n.signal)}catch(e){n.signal.aborted||writeRequestError(t,e)}finally{o?.(),e.off(`error`,abortRequest)}}async#S(e,t,n){let r;try{stampDevelopmentClientAddress(e.headers,e.socket.remoteAddress??void 0,this.#c),await this.waitForActiveRunner();let i=this.#i;if(i===void 0)throw Error(`Development worker is unavailable.`);r=this.#b(i),t.once(`close`,r),t.once(`error`,r),await i.runner.upgrade({node:{head:n,req:e,socket:t}})}catch{r?.(),t.destroyed||t.destroy()}}#C(){for(let e of this.#a.splice(0))e()}};export{DrainedNitroDevServer};
@@ -1,11 +1,10 @@
1
1
  import type { ApplicationBuildWorkspace } from "#internal/application/build-workspace.js";
2
- import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
2
+ import type { PreparedApplicationHost, PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
3
3
  /**
4
- * Compiles one authored app in place and stages the package-owned artifacts
5
- * the dev-server Nitro host needs, activating a fresh runtime-artifacts
6
- * snapshot for hot reload.
4
+ * Compiles one authored app and stages an isolated runtime generation and host
5
+ * candidate without changing the active development server.
7
6
  */
8
- export declare function prepareDevelopmentApplicationHost(startPath: string): Promise<PreparedApplicationHost>;
7
+ export declare function prepareDevelopmentApplicationHost(appRoot: string): Promise<PreparedDevelopmentApplicationHost>;
9
8
  /**
10
9
  * Compiles one authored app into an invocation-owned build workspace and
11
10
  * stages the package-owned artifacts the production Nitro build needs.
@@ -1 +1 @@
1
- import{join}from"node:path";import{resolveApplicationHostArtifactsDirectory,resolveWorkflowBuildDirectory}from"#internal/application/paths.js";import{createAuthoredSourceRuntimeCompiledArtifactsSource}from"#internal/application/runtime-compiled-artifacts-source.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules,resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgent,compileAgentInBuildWorkspace}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration,stageDevelopmentGeneration}from"#internal/nitro/development-generation.js";async function prepareDevelopmentApplicationHost(e){let i=await compileAgent({startPath:e}),a=await loadResolvedCompiledSchedules({compiledArtifactsSource:createAuthoredSourceRuntimeCompiledArtifactsSource(i.project.appRoot)}),o=await stageDevelopmentGeneration(i);try{let e=await writeDevelopmentCompiledArtifactsFiles({compileResult:i,outDir:resolveApplicationHostArtifactsDirectory(i.project.appRoot),runtimeAppRoot:o.runtimeAppRoot});return await activateDevelopmentGeneration({appRoot:i.project.appRoot,generation:o}),createPreparedApplicationHost({compileResult:i,compiledArtifacts:e,schedules:a,workflowBuildDir:resolveWorkflowBuildDirectory(i.project.appRoot)})}catch(e){throw await discardDevelopmentGeneration(o),e}}async function prepareProductionApplicationHost(t){let n=await compileAgentInBuildWorkspace({artifactLocations:{publishedRoot:join(t.publication.output.finalDir,`.eve`),writeRoot:t.compiler.artifactsDir},startPath:t.appRoot}),r=await resolveSchedules({manifest:n.manifest});return createPreparedApplicationHost({compileResult:n,compiledArtifacts:await writeCompiledArtifactsFiles({compileResult:n,defaultWorkflowWorld:resolveProductionWorkflowWorldTarget(),outDir:t.host.artifactsDir}),schedules:r,workflowBuildDir:t.workflow.buildDir})}function createPreparedApplicationHost(e){return{appRoot:e.compileResult.project.appRoot,compileResult:e.compileResult,compiledArtifacts:e.compiledArtifacts,scheduleRegistrations:createScheduleRegistrations(e.schedules),schedules:e.schedules,workflowBuildDir:e.workflowBuildDir}}function resolveProductionWorkflowWorldTarget(){return process.env.VERCEL?`vercel`:`local`}export{prepareDevelopmentApplicationHost,prepareProductionApplicationHost};
1
+ import{join}from"node:path";import{createDevelopmentHostWorkspace,removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{discardDevelopmentGeneration,stageDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgentInWorkspace}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";async function prepareDevelopmentApplicationHost(a){let o=await createDevelopmentHostWorkspace(a),s;try{let t=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(a,`.eve`),writeRoot:o.compilerArtifactsDir},startPath:a}),n=await resolveSchedules({manifest:t.manifest});return s=await stageDevelopmentGeneration(t),{...createPreparedApplicationHost({compileResult:t,compiledArtifacts:await writeDevelopmentCompiledArtifactsFiles({compileResult:t,outDir:o.artifactsDir,runtimeAppRoot:s.runtimeAppRoot}),schedules:n,workflowBuildDir:o.workflowBuildDir}),generation:s,workspace:o}}catch(e){let t=[removeDevelopmentHostWorkspace(o)];s!==void 0&&t.push(discardDevelopmentGeneration(s));let i=(await Promise.allSettled(t)).flatMap(e=>e.status===`rejected`?[e.reason]:[]);throw i.length>0?AggregateError([e,...i],`Failed to prepare and discard a development host candidate.`,{cause:e}):e}}async function prepareProductionApplicationHost(t){let n=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(t.publication.output.finalDir,`.eve`),writeRoot:t.compiler.artifactsDir},startPath:t.appRoot}),r=await resolveSchedules({manifest:n.manifest});return createPreparedApplicationHost({compileResult:n,compiledArtifacts:await writeCompiledArtifactsFiles({compileResult:n,defaultWorkflowWorld:resolveProductionWorkflowWorldTarget(),outDir:t.host.artifactsDir}),schedules:r,workflowBuildDir:t.workflow.buildDir})}function createPreparedApplicationHost(e){return{appRoot:e.compileResult.project.appRoot,compileResult:e.compileResult,compiledArtifacts:e.compiledArtifacts,scheduleRegistrations:createScheduleRegistrations(e.schedules),schedules:e.schedules,workflowBuildDir:e.workflowBuildDir}}function resolveProductionWorkflowWorldTarget(){return process.env.VERCEL?`vercel`:`local`}export{prepareDevelopmentApplicationHost,prepareProductionApplicationHost};
@@ -1,9 +1,6 @@
1
1
  import type { DevelopmentServer, DevelopmentServerOptions, StartedDevelopmentServer } from "#internal/nitro/host/types.js";
2
- /**
3
- * Rewrites a server URL whose hostname is a wildcard listen address into a
4
- * loopback URL on the same address family.
5
- */
6
- export declare function normalizeDevelopmentServerClientUrl(serverUrl: string): string;
2
+ import { normalizeDevelopmentServerClientUrl } from "#internal/nitro/host/dev-server-url.js";
3
+ export { normalizeDevelopmentServerClientUrl };
7
4
  /**
8
5
  * Returns whether a supplied URL identifies this app's healthy local development
9
6
  * server. Only that server receives the local TUI credential path.
@@ -1,2 +1,2 @@
1
- import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{build,createDevServer,prepare}from"nitro/builder";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`,DEFAULT_DEVELOPMENT_SERVER_HOST=`127.0.0.1`,IPV6_WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return IPV6_WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`[::1]`,t.toString()):t.hostname===`0.0.0.0`?(t.hostname=DEFAULT_DEVELOPMENT_SERVER_HOST,t.toString()):e}async function isActiveDevelopmentServerForApp(e){try{let n=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return n===void 0||!isLoopbackServerUrl(n)||!await isEveServerHealthy(n)?!1:new URL(n).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
- `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function installWorkflowLocalQueueEnvironment(e){let t=process.env[WORKFLOW_LOCAL_BASE_URL_ENV],n=process.env[PORT_ENV],r=new URL(normalizeDevelopmentServerClientUrl(e));return process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=r.origin,r.port&&(process.env[PORT_ENV]=r.port),()=>{t===void 0?delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV]:process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=t,n===void 0?delete process.env[PORT_ENV]:process.env[PORT_ENV]=n}}function attachTemporarySocketErrorHandler(e){let onSocketError=()=>{};return e.once(`error`,onSocketError),()=>{e.off(`error`,onSocketError)}}function shouldProxyDevelopmentServerWebSocketUpgrades(e){return e.options.features.websocket===!0||e.options.experimental.websocket===!0}function guardDevelopmentServerWebSocketUpgrades(e,t){let n=t.upgrade.bind(t),r=shouldProxyDevelopmentServerWebSocketUpgrades(e);t.upgrade=async(e,t,i)=>{if(!r){t.destroyed||t.destroy();return}let a=attachTemporarySocketErrorHandler(t);try{await n(e,t,i)}catch{t.destroyed||t.destroy()}finally{a()}}}function addDevelopmentRuntimeArtifactsRebuildHandler(t){t.nitro.options.devHandlers.push({route:EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,handler:async e=>{let n=e.node?.req.url??``;return new URL(n,`http://localhost`).searchParams.get(`force`)===`1`?await t.watcher.rebuild():await t.watcher.flush(),handleDevRuntimeArtifactsRequest({appRoot:t.appRoot})}})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.nitro;return a!==void 0&&await attempt(()=>a.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,n){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),u=n.port??i,p=n.host!==void 0||n.port!==void 0||i!==void 0,m=new DevelopmentServerState(r),h=await m.read();if(h!==void 0&&isLoopbackServerUrl(h)&&await isEveServerHealthy(h)){if(n.existing===`attach-if-unconfigured`&&!p)return{handle:{kind:`existing`,appRoot:r.appRoot,url:h},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,h)}let g=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],_=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=_;let v,y,b,x;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(r.appRoot),n.onBootProgress),t=resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot}));startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:t}),pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),n.onBootProgress);v=i,y=createDevServer(i);let a=y;guardDevelopmentServerWebSocketUpgrades(i,y);let o=n.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,s=u===void 0,c=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:a,host:o,port:u,retryOnAddressInUse:s}),n.onBootProgress);if(!c.url)throw Error(`Nitro dev server did not expose a URL.`);let l=normalizeDevelopmentServerClientUrl(c.url);b=installWorkflowLocalQueueEnvironment(l),await devBootPhase(`building dev bundle`,async()=>{await prepare(i),await build(i)},n.onBootProgress),x=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({nitro:i,preparedHost:e})},n.onBootProgress),addDevelopmentRuntimeArtifactsRebuildHandler({appRoot:r.appRoot,nitro:i,watcher:x}),await m.write(l);let d=b;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);let f=x,p=y,h=i,S;return{handle:{kind:`started`,appRoot:r.appRoot,url:l},close:()=>(S??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:f,devServer:p,developmentSandboxRunId:_,nitro:h});e.listenerClosed&&await m.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(_),d(),restoreDevelopmentSandboxRunId(g)}})(),S)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:x,devServer:y,developmentSandboxRunId:_,nitro:v}),n=[...t.errors];throw b?.(),clearInitializedDevelopmentSandboxBackendNames(_),t.listenerClosed&&await m.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(g),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
1
+ import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{randomBytes}from"node:crypto";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{buildDevelopmentHostCandidate}from"#internal/nitro/host/dev-host-candidate.js";import{removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{DrainedNitroDevServer}from"#internal/nitro/host/drained-nitro-dev-server.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DEFAULT_DEVELOPMENT_SERVER_HOST,normalizeDevelopmentServerClientUrl}from"#internal/nitro/host/dev-server-url.js";import{createDevelopmentAuthoredRebuildCoordinator}from"#internal/nitro/host/dev-authored-rebuild-coordinator.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";import{createDevelopmentWorkflowWorld,installWorkflowLocalQueueEnvironment,installWorkflowTransportEnvironment}from"#internal/nitro/host/dev-workflow-world-setup.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,PORT_ENV=`PORT`;async function isActiveDevelopmentServerForApp(e){try{let t=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return t===void 0||!isLoopbackServerUrl(t)||!await isEveServerHealthy(t)?!1:new URL(t).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
+ `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function addDevelopmentControlHandler(n){n.devServer.setControlHandler(async r=>{let i=await n.workflowWorld?.handleRequest(r);if(i!==void 0)return i;let a=new URL(r.url);if(a.pathname===EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH&&r.method===`GET`)return handleDevRuntimeArtifactsRequest({appRoot:n.appRoot});if(a.pathname!==EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH||r.method!==`GET`)return;let o=n.getWatcher();return o===void 0?Response.json({error:`The development server is still starting.`},{status:503}):(a.searchParams.get(`force`)===`1`?await o.rebuild():await o.flush(),handleDevRuntimeArtifactsRequest({appRoot:n.appRoot}))})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.workflowWorld;a!==void 0&&await attempt(()=>a.close());let o=e.nitro;return o!==void 0&&await attempt(()=>o.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,t){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),a=t.port??i,d=t.host!==void 0||t.port!==void 0||i!==void 0,h=new DevelopmentServerState(r),g=await h.read();if(g!==void 0&&isLoopbackServerUrl(g)&&await isEveServerHealthy(g)){if(t.existing===`attach-if-unconfigured`&&!d)return{handle:{kind:`existing`,appRoot:r.appRoot,url:g},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,g)}let _=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],v=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=v;let y,b,x,S,C,w,T,E=!1,D=!1;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(r.appRoot),t.onBootProgress);T=e;let n=resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),t.onBootProgress);y=i,b=new DrainedNitroDevServer(i.logger);let o=b,s=randomBytes(32).toString(`base64url`);o.setClientAddressSecret(s),S=installWorkflowTransportEnvironment(r.appRoot,s),C=createDevelopmentWorkflowWorld({appRoot:r.appRoot,preparedHost:e,transportSecret:s}),addDevelopmentControlHandler({appRoot:r.appRoot,devServer:o,getWatcher:()=>w,workflowWorld:C});let c=t.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,l=a===void 0,u=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:o,host:c,port:a,retryOnAddressInUse:l}),t.onBootProgress);if(!u.url)throw Error(`Nitro dev server did not expose a URL.`);let d=normalizeDevelopmentServerClientUrl(u.url);x=installWorkflowLocalQueueEnvironment(d),await devBootPhase(`building dev bundle`,async()=>{let t=await buildDevelopmentHostCandidate({host:e,nitro:i});y=void 0;let n=e.workspace;D=!0,await o.replaceWorker({dispose:async()=>await removeDevelopmentHostWorkspace(n),entry:t.entry,workerData:t.workerData}),await activateDevelopmentGeneration({appRoot:e.appRoot,generation:e.generation}),E=!0},t.onBootProgress),await C?.start(),startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:n});let f=await createDevelopmentAuthoredRebuildCoordinator({devServer:o,initialHost:e});w=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({coordinator:f,preparedHost:e})},t.onBootProgress),await h.write(d);let p=x;if(p===void 0)throw Error(`Workflow local queue environment was not initialized.`);let m=w,g=b,O=C,k=S,A;return{handle:{kind:`started`,appRoot:r.appRoot,url:d},close:()=>(A??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:m,devServer:g,developmentSandboxRunId:v,nitro:void 0,workflowWorld:O});e.listenerClosed&&await h.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(v),p(),k?.(),restoreDevelopmentSandboxRunId(_)}})(),A)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:w,devServer:b,developmentSandboxRunId:v,nitro:y,workflowWorld:C}),n=[...t.errors];throw T!==void 0&&!E&&await discardDevelopmentGeneration(T.generation).catch(e=>{n.push(e)}),T!==void 0&&!D&&await removeDevelopmentHostWorkspace(T.workspace).catch(e=>{n.push(e)}),x?.(),S?.(),clearInitializedDevelopmentSandboxBackendNames(v),t.listenerClosed&&await h.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(_),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
@@ -3,6 +3,8 @@ import type { ScheduleRegistration } from "#runtime/schedules/register.js";
3
3
  import type { ResolvedScheduleDefinition } from "#runtime/types.js";
4
4
  import type { GeneratedCompiledArtifactsFiles } from "#internal/application/compiled-artifacts.js";
5
5
  import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
6
+ import type { DevelopmentGeneration } from "#internal/nitro/development-generation.js";
7
+ import type { DevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-workspace.js";
6
8
  /**
7
9
  * Route surface included in one programmatic Nitro host build.
8
10
  */
@@ -65,3 +67,7 @@ export interface PreparedApplicationHost {
65
67
  schedules: readonly ResolvedScheduleDefinition[];
66
68
  workflowBuildDir: string;
67
69
  }
70
+ export interface PreparedDevelopmentApplicationHost extends PreparedApplicationHost {
71
+ generation: DevelopmentGeneration;
72
+ workspace: DevelopmentHostWorkspace;
73
+ }
@@ -1 +1 @@
1
- import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),c;try{c=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),c}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,c=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,c.args));return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,s,c){let l=readVercelRequestId(t.req.headers),u=extractSocketIp(t),d=[],f=t.context.params??{},p={};for(let[e,t]of Object.entries(f))p[e]=decodeURIComponent(t);let waitUntil=e=>{d.push(e)},m=n.channels.find(e=>e.name===s)?.adapter??{kind:`channel`};return{agent:createRouteAgent(n.runtime,l),args:attachAgentInfoRouteResponse({send:createSendFn(n.runtime,m,s,{requestId:l}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:p,waitUntil,requestIp:u},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(c)}),backgroundTasks:d}}function createRouteAgent(e,t){return{async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
1
+ import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{attachAgentInfoRouteResponse}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`};return{agent:createRouteAgent(n.runtime,c),args:attachAgentInfoRouteResponse({send:createSendFn(n.runtime,p,o,{requestId:c}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:f,waitUntil,requestIp:l},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(s)}),backgroundTasks:u}}function createRouteAgent(e,t){return{async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
@@ -7,6 +7,13 @@ import { type RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts
7
7
  export interface DevelopmentNitroArtifactsConfig {
8
8
  readonly appRoot: string;
9
9
  readonly devRuntimeArtifactsPointerPath: string;
10
+ /**
11
+ * Set when durable Workflow payloads may store a logical generation
12
+ * selector instead of this source's exact snapshot path. Only true when
13
+ * the parent-owned dev World delivers the queue, because only those
14
+ * deliveries install the context that resolves the selector.
15
+ */
16
+ readonly durableArtifactsReference?: "development-generation";
10
17
  readonly kind: "development";
11
18
  readonly moduleMapLoaderPath: string;
12
19
  }
@@ -1 +1 @@
1
- import{createBundledRuntimeCompiledArtifactsSource,createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{readDevelopmentRuntimeArtifactsSnapshotRoot}from"#internal/nitro/dev-runtime-artifacts.js";function resolveNitroCompiledArtifactsSource(e){if(e.kind===`development`)return createDiskRuntimeCompiledArtifactsSource(readDevelopmentRuntimeArtifactsSnapshotRoot(e.devRuntimeArtifactsPointerPath)??e.appRoot,{moduleMapLoaderPath:e.moduleMapLoaderPath,sandboxAppRoot:e.appRoot});if(readBundledCompiledArtifacts()!==null)return createBundledRuntimeCompiledArtifactsSource();throw Error(`eve Nitro production requires bundled artifacts.`)}export{resolveNitroCompiledArtifactsSource};
1
+ import{createBundledRuntimeCompiledArtifactsSource,createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{readDevelopmentRuntimeArtifactsSnapshotRoot}from"#internal/nitro/dev-runtime-artifacts.js";function resolveNitroCompiledArtifactsSource(e){if(e.kind===`development`)return createDiskRuntimeCompiledArtifactsSource(readDevelopmentRuntimeArtifactsSnapshotRoot(e.devRuntimeArtifactsPointerPath)??e.appRoot,{durableReference:e.durableArtifactsReference,moduleMapLoaderPath:e.moduleMapLoaderPath,sandboxAppRoot:e.appRoot});if(readBundledCompiledArtifacts()!==null)return createBundledRuntimeCompiledArtifactsSource();throw Error(`eve Nitro production requires bundled artifacts.`)}export{resolveNitroCompiledArtifactsSource};
@@ -1,4 +1,5 @@
1
1
  import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
2
+ import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
2
3
  /**
3
4
  * Dispatches one eve authored schedule via the execution engine.
4
5
  *
@@ -10,3 +11,11 @@ export declare function dispatchScheduleTask(taskName: string, config: NitroArti
10
11
  scheduleId: string;
11
12
  sessionIds: readonly string[];
12
13
  }>;
14
+ /**
15
+ * Variant of {@link dispatchScheduleTask} for callers that already resolved
16
+ * an artifact source and need the dispatch to stay on that generation.
17
+ */
18
+ export declare function dispatchScheduleTaskFromArtifacts(taskName: string, compiledArtifactsSource: RuntimeCompiledArtifactsSource): Promise<{
19
+ scheduleId: string;
20
+ sessionIds: readonly string[];
21
+ }>;
@@ -1 +1 @@
1
- import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{loadResolvedCompiledScheduleByTaskName}from"#runtime/schedules/resolve-schedule.js";import{ScheduleDispatcher,expectScheduleRun}from"#channel/schedule.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";async function dispatchScheduleTask(r,i){let a=resolveNitroCompiledArtifactsSource(i),o=await loadResolvedCompiledScheduleByTaskName(r,{compiledArtifactsSource:a}),s=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:a}),c=new ScheduleDispatcher({runtime:createWorkflowRuntime({compiledArtifactsSource:a}),channels:s.graph.root.channels}),l={scheduleId:o.name};o.hasRun&&(l.run=await loadScheduleRun(o,s.moduleMap)),o.markdown!==void 0&&(l.markdown=o.markdown);let u=await c.trigger(l);return u.waitUntilTasks.length>0&&await Promise.allSettled(u.waitUntilTasks),{scheduleId:o.name,sessionIds:u.sessions.map(e=>e.id)}}async function loadScheduleRun(e,t){if(e.sourceKind!==`module`)throw Error(`Schedule "${e.name}" claims hasRun but is not a module-backed schedule.`);let n=e;return expectScheduleRun(await loadResolvedModuleExport({definition:{exportName:n.exportName,logicalPath:n.logicalPath,sourceId:n.sourceId},kindLabel:`schedule`,moduleMap:t,nodeId:void 0}),n.logicalPath,n.exportName)}export{dispatchScheduleTask};
1
+ import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{loadResolvedCompiledScheduleByTaskName}from"#runtime/schedules/resolve-schedule.js";import{ScheduleDispatcher,expectScheduleRun}from"#channel/schedule.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";async function dispatchScheduleTask(e,t){return await dispatchScheduleTaskFromArtifacts(e,resolveNitroCompiledArtifactsSource(t))}async function dispatchScheduleTaskFromArtifacts(n,r){let i=await loadResolvedCompiledScheduleByTaskName(n,{compiledArtifactsSource:r}),a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:r}),o=new ScheduleDispatcher({runtime:createWorkflowRuntime({compiledArtifactsSource:r}),channels:a.graph.root.channels}),s={scheduleId:i.name};i.hasRun&&(s.run=await loadScheduleRun(i,a.moduleMap)),i.markdown!==void 0&&(s.markdown=i.markdown);let c=await o.trigger(s);return c.waitUntilTasks.length>0&&await Promise.allSettled(c.waitUntilTasks),{scheduleId:i.name,sessionIds:c.sessions.map(e=>e.id)}}async function loadScheduleRun(e,t){if(e.sourceKind!==`module`)throw Error(`Schedule "${e.name}" claims hasRun but is not a module-backed schedule.`);let n=e;return expectScheduleRun(await loadResolvedModuleExport({definition:{exportName:n.exportName,logicalPath:n.logicalPath,sourceId:n.sourceId},kindLabel:`schedule`,moduleMap:t,nodeId:void 0}),n.logicalPath,n.exportName)}export{dispatchScheduleTask,dispatchScheduleTaskFromArtifacts};