eve 0.24.1 → 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 (147) hide show
  1. package/CHANGELOG.md +19 -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/cli/run.js +2 -2
  5. package/dist/src/cli/vercel-service-output.d.ts +4 -0
  6. package/dist/src/cli/vercel-service-output.js +1 -0
  7. package/dist/src/compiled/.vendor-stamp.json +2 -1
  8. package/dist/src/compiled/@chat-adapter/slack/index.js +12 -12
  9. package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -1
  10. package/dist/src/compiled/@vercel/sandbox/index.js +19 -19
  11. package/dist/src/compiled/@workflow/world-local/index.d.ts +14 -0
  12. package/dist/src/compiled/_chunks/node/{auth-CWHn3Yve.js → auth-BuQkq4Gr.js} +2 -2
  13. package/dist/src/compiled/_chunks/node/{dist-BdTs18CF.js → chunk-BTyA9uPd.js} +1 -1
  14. package/dist/src/compiled/_chunks/node/{dist-W8yle6rh.js → dist-CdH_Yoxt.js} +5 -5
  15. package/dist/src/compiled/_chunks/node/{dist-RHRJZ03Q.js → dist-Drt-_JVK.js} +1 -1
  16. package/dist/src/compiled/_chunks/node/dist-DsNhwdzf.js +1 -0
  17. package/dist/src/compiled/_chunks/node/retry-DngYleaI.js +1 -0
  18. package/dist/src/compiled/_chunks/node/token-DabMnh8F.js +1 -0
  19. package/dist/src/compiled/_chunks/node/token-util-BoSJPKrG.js +1 -0
  20. package/dist/src/compiled/_chunks/node/token-util-DVigMYWS.js +1 -0
  21. package/dist/src/compiled/_chunks/node/virtual-loader-B8K8w9cr.js +1 -0
  22. package/dist/src/compiled/chat/index.js +1 -1
  23. package/dist/src/compiled/env-runner/LICENSE +21 -0
  24. package/dist/src/compiled/env-runner/index.d.ts +38 -0
  25. package/dist/src/compiled/env-runner/index.js +1 -0
  26. package/dist/src/compiled/env-runner/node-worker.d.ts +1 -0
  27. package/dist/src/compiled/env-runner/node-worker.js +12 -0
  28. package/dist/src/compiler/compile-agent.d.ts +4 -6
  29. package/dist/src/compiler/compile-agent.js +1 -1
  30. package/dist/src/execution/create-session-step.d.ts +2 -2
  31. package/dist/src/execution/create-session-step.js +1 -1
  32. package/dist/src/execution/workflow-runtime.js +1 -1
  33. package/dist/src/harness/compaction-prompt.d.ts +16 -0
  34. package/dist/src/harness/compaction-prompt.js +24 -0
  35. package/dist/src/harness/compaction.d.ts +2 -1
  36. package/dist/src/harness/compaction.js +1 -4
  37. package/dist/src/harness/input-requests.d.ts +1 -0
  38. package/dist/src/harness/input-requests.js +1 -1
  39. package/dist/src/harness/tool-loop.js +1 -1
  40. package/dist/src/internal/application/build-workspace.d.ts +1 -1
  41. package/dist/src/internal/application/build-workspace.js +1 -1
  42. package/dist/src/internal/application/compiled-artifacts.d.ts +13 -0
  43. package/dist/src/internal/application/compiled-artifacts.js +3 -2
  44. package/dist/src/internal/application/dev-environment.d.ts +4 -0
  45. package/dist/src/internal/application/dev-environment.js +1 -0
  46. package/dist/src/internal/application/optional-package-install.d.ts +2 -10
  47. package/dist/src/internal/application/optional-package-install.js +1 -1
  48. package/dist/src/internal/application/output-publication-lock.js +1 -1
  49. package/dist/src/internal/application/package.js +1 -1
  50. package/dist/src/internal/application/paths.d.ts +2 -0
  51. package/dist/src/internal/application/paths.js +1 -1
  52. package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
  53. package/dist/src/internal/authored-module-loader.d.ts +3 -9
  54. package/dist/src/internal/authored-module-loader.js +2 -2
  55. package/dist/src/internal/authored-package-boundary.d.ts +0 -2
  56. package/dist/src/internal/authored-package-boundary.js +1 -1
  57. package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
  58. package/dist/src/internal/compiled-manifest-fingerprint.d.ts +5 -0
  59. package/dist/src/internal/compiled-manifest-fingerprint.js +1 -0
  60. package/dist/src/internal/materialized-authored-modules.d.ts +0 -3
  61. package/dist/src/internal/materialized-authored-modules.js +1 -1
  62. package/dist/src/internal/nitro/dev-client-address.d.ts +22 -0
  63. package/dist/src/internal/nitro/dev-client-address.js +1 -0
  64. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.d.ts +12 -0
  65. package/dist/src/internal/nitro/dev-runtime-artifacts-retention.js +1 -0
  66. package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +19 -1
  67. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  68. package/dist/src/internal/nitro/development-generation.d.ts +5 -1
  69. package/dist/src/internal/nitro/development-generation.js +1 -1
  70. package/dist/src/internal/nitro/host/artifacts-config.d.ts +2 -0
  71. package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
  72. package/dist/src/internal/nitro/host/build-application.js +1 -1
  73. package/dist/src/internal/nitro/host/channel-routes.d.ts +1 -13
  74. package/dist/src/internal/nitro/host/channel-routes.js +3 -3
  75. package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +1 -2
  76. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  77. package/dist/src/internal/nitro/host/copy-host-middleware.d.ts +12 -0
  78. package/dist/src/internal/nitro/host/copy-host-middleware.js +1 -0
  79. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +3 -5
  80. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  81. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.d.ts +32 -0
  82. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -0
  83. package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +4 -15
  84. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  85. package/dist/src/internal/nitro/host/dev-host-candidate.d.ts +16 -0
  86. package/dist/src/internal/nitro/host/dev-host-candidate.js +1 -0
  87. package/dist/src/internal/nitro/host/dev-host-fingerprint.d.ts +2 -0
  88. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -0
  89. package/dist/src/internal/nitro/host/dev-host-workspace.d.ts +10 -0
  90. package/dist/src/internal/nitro/host/dev-host-workspace.js +1 -0
  91. package/dist/src/internal/nitro/host/dev-runner.d.ts +21 -0
  92. package/dist/src/internal/nitro/host/dev-runner.js +1 -0
  93. package/dist/src/internal/nitro/host/dev-server-http.d.ts +5 -0
  94. package/dist/src/internal/nitro/host/dev-server-http.js +1 -0
  95. package/dist/src/internal/nitro/host/dev-server-url.d.ts +6 -0
  96. package/dist/src/internal/nitro/host/dev-server-url.js +1 -0
  97. package/dist/src/internal/nitro/host/dev-workflow-world-setup.d.ts +9 -0
  98. package/dist/src/internal/nitro/host/dev-workflow-world-setup.js +1 -0
  99. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -1
  100. package/dist/src/internal/nitro/host/drained-nitro-dev-server.d.ts +53 -0
  101. package/dist/src/internal/nitro/host/drained-nitro-dev-server.js +1 -0
  102. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +4 -5
  103. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  104. package/dist/src/internal/nitro/host/start-development-server.d.ts +2 -5
  105. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  106. package/dist/src/internal/nitro/host/types.d.ts +10 -0
  107. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  108. package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +7 -0
  109. package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
  110. package/dist/src/internal/nitro/routes/schedule-task.d.ts +9 -0
  111. package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
  112. package/dist/src/internal/workflow/development-generation-context.d.ts +8 -0
  113. package/dist/src/internal/workflow/development-generation-context.js +1 -0
  114. package/dist/src/internal/workflow/development-world-client.d.ts +29 -0
  115. package/dist/src/internal/workflow/development-world-client.js +1 -0
  116. package/dist/src/internal/workflow/development-world-codec.d.ts +11 -0
  117. package/dist/src/internal/workflow/development-world-codec.js +1 -0
  118. package/dist/src/internal/workflow/development-world-protocol.d.ts +31 -0
  119. package/dist/src/internal/workflow/development-world-protocol.js +1 -0
  120. package/dist/src/internal/workflow/development-world-server.d.ts +27 -0
  121. package/dist/src/internal/workflow/development-world-server.js +1 -0
  122. package/dist/src/public/next/vercel-output-config.js +1 -1
  123. package/dist/src/runtime/compiled-artifacts-source.d.ts +9 -0
  124. package/dist/src/runtime/compiled-artifacts-source.js +1 -1
  125. package/dist/src/runtime/durable-compiled-artifacts-source.d.ts +8 -0
  126. package/dist/src/runtime/durable-compiled-artifacts-source.js +1 -0
  127. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  128. package/dist/src/setup/scaffold/create/project.js +1 -1
  129. package/dist/src/shared/atomic-write-file.d.ts +1 -1
  130. package/dist/src/shared/atomic-write-file.js +1 -1
  131. package/dist/src/shared/rename-with-retry.d.ts +5 -0
  132. package/dist/src/shared/rename-with-retry.js +1 -0
  133. package/docs/agent-config.md +3 -1
  134. package/docs/concepts/default-harness.md +1 -1
  135. package/docs/concepts/execution-model-and-durability.md +1 -1
  136. package/docs/reference/cli.md +1 -1
  137. package/package.json +2 -1
  138. package/dist/src/compiled/_chunks/node/retry-DkR2H1Y0.js +0 -1
  139. package/dist/src/compiled/_chunks/node/token-ORseRyWn.js +0 -1
  140. package/dist/src/internal/bundler/nitro-node-file-trace.d.ts +0 -10
  141. package/dist/src/internal/bundler/nitro-node-file-trace.js +0 -1
  142. package/dist/src/internal/materialize-authored-external-dependencies.d.ts +0 -10
  143. package/dist/src/internal/materialize-authored-external-dependencies.js +0 -2
  144. package/dist/src/internal/nitro/host/dev-live-virtual-modules.d.ts +0 -15
  145. package/dist/src/internal/nitro/host/dev-live-virtual-modules.js +0 -1
  146. package/dist/src/internal/nitro/host/server-external-packages.d.ts +0 -5
  147. package/dist/src/internal/nitro/host/server-external-packages.js +0 -1
@@ -0,0 +1 @@
1
+ import{createHash,createHmac,timingSafeEqual}from"node:crypto";const DEVELOPMENT_CLIENT_ADDRESS_HEADER=`x-eve-dev-client-address`,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER=`x-eve-dev-client-address-signature`;function stampDevelopmentClientAddress(e,t,n){deleteHeader(e,DEVELOPMENT_CLIENT_ADDRESS_HEADER),deleteHeader(e,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER),!(t===void 0||t.length===0||n===void 0||n.length===0)&&(setHeader(e,DEVELOPMENT_CLIENT_ADDRESS_HEADER,t),setHeader(e,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,signClientAddress(t,n)))}function readTrustedDevelopmentClientAddress(e,t){let n=e.get(DEVELOPMENT_CLIENT_ADDRESS_HEADER),i=e.get(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER);if(!(n===null||i===null||t===void 0||t.length===0||!timingSafeEqualStrings(i,signClientAddress(n,t))))return n}function timingSafeEqualStrings(t,r){return timingSafeEqual(createHash(`sha256`).update(t).digest(),createHash(`sha256`).update(r).digest())}function signClientAddress(e,n){return createHmac(`sha256`,n).update(e).digest(`base64url`)}function deleteHeader(e,t){if(e instanceof Headers){e.delete(t);return}delete e[t]}function setHeader(e,t,n){if(e instanceof Headers){e.set(t,n);return}e[t]=n}export{DEVELOPMENT_CLIENT_ADDRESS_HEADER,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,readTrustedDevelopmentClientAddress,stampDevelopmentClientAddress,timingSafeEqualStrings};
@@ -0,0 +1,12 @@
1
+ export declare const DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER = "activated";
2
+ /** Records the instant at which an activated generation stopped being current. */
3
+ export declare function recordRetiredDevelopmentRuntimeArtifactsSnapshot(snapshotRoot: string, retiredAt?: number): Promise<void>;
4
+ /** Applies the bounded retention policy within one dev snapshot directory. */
5
+ export declare function pruneDevelopmentRuntimeArtifactsSnapshotDirectory(input: {
6
+ readonly activeSnapshotRoot: string | undefined;
7
+ readonly gracePeriodMs?: number;
8
+ readonly now?: number;
9
+ readonly protectAll: boolean;
10
+ readonly retainCount?: number;
11
+ readonly snapshotsDirectory: string;
12
+ }): Promise<void>;
@@ -0,0 +1 @@
1
+ import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{readFile,readdir,rm,stat,writeFile}from"node:fs/promises";const DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER=`activated`,DEVELOPMENT_RUNTIME_ARTIFACTS_RETIRED_METADATA=`retired.json`;async function recordRetiredDevelopmentRuntimeArtifactsSnapshot(e,n=Date.now()){await writeFile(join(e,DEVELOPMENT_RUNTIME_ARTIFACTS_RETIRED_METADATA),`${JSON.stringify({retiredAt:n})}\n`)}async function pruneDevelopmentRuntimeArtifactsSnapshotDirectory(r){if(r.protectAll)return;let o=r.now??Date.now(),s=Math.max(0,r.gracePeriodMs??18e5),c=Math.max(0,Math.trunc(r.retainCount??5)),l;try{l=await readdir(r.snapshotsDirectory,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let u=r.activeSnapshotRoot===void 0?void 0:resolve(r.activeSnapshotRoot),d=await Promise.all(l.filter(e=>e.isDirectory()).map(async i=>{let a=join(r.snapshotsDirectory,i.name),s=u===resolve(a),c=existsSync(join(a,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER)),l;if(c&&!s)try{l=await readRetiredAt(a),l===void 0&&(await recordRetiredDevelopmentRuntimeArtifactsSnapshot(a,o),l=o)}catch(e){console.warn(`[eve:dev] failed to read or initialize runtime generation retirement metadata for "${a}": ${String(e)}`)}return{activated:c,active:s,path:a,retiredAt:l,mtimeMs:(await stat(a)).mtimeMs}})),f=new Set(d.flatMap(e=>e.retiredAt===void 0?[]:[{path:e.path,retiredAt:e.retiredAt}]).sort((e,t)=>t.retiredAt-e.retiredAt).slice(0,c).map(e=>e.path)),p=new Set(d.filter(e=>!e.activated).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(0,c).map(e=>e.path));await Promise.all(d.map(async e=>{e.active||e.activated&&e.retiredAt===void 0||f.has(e.path)||p.has(e.path)||e.retiredAt!==void 0&&o-e.retiredAt<=s||!e.activated&&o-e.mtimeMs<=s||await rm(e.path,{force:!0,recursive:!0})}))}async function readRetiredAt(e){let n;try{n=await readFile(join(e,DEVELOPMENT_RUNTIME_ARTIFACTS_RETIRED_METADATA),`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let i;try{i=JSON.parse(n)}catch{return}if(typeof i==`object`&&i&&!Array.isArray(i)&&`retiredAt`in i&&typeof i.retiredAt==`number`&&Number.isFinite(i.retiredAt)&&i.retiredAt>=0)return i.retiredAt}export{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot};
@@ -8,6 +8,14 @@ export interface DevelopmentRuntimeArtifactsSnapshot {
8
8
  readonly snapshotSourceRoot: string;
9
9
  readonly sourceRoot: string;
10
10
  }
11
+ export interface ActiveDevelopmentRuntimeArtifactsSnapshot {
12
+ readonly runtimeAppRoot: string;
13
+ readonly snapshotRoot: string;
14
+ }
15
+ export interface DevelopmentRuntimeArtifactsActivation {
16
+ commit(): void;
17
+ rollback(): Promise<void>;
18
+ }
11
19
  /**
12
20
  * Resolves the dev-server pointer that records the latest runtime artifact
13
21
  * snapshot for new sessions.
@@ -24,17 +32,27 @@ export declare function activateDevelopmentRuntimeArtifactsSnapshot(input: {
24
32
  readonly appRoot: string;
25
33
  readonly snapshot: DevelopmentRuntimeArtifactsSnapshot;
26
34
  }): Promise<void>;
35
+ export declare function activateDevelopmentRuntimeArtifactsSnapshotTransaction(input: {
36
+ readonly appRoot: string;
37
+ readonly snapshot: DevelopmentRuntimeArtifactsSnapshot;
38
+ }): Promise<DevelopmentRuntimeArtifactsActivation>;
27
39
  /**
28
40
  * Reads the latest dev runtime snapshot root when the dev server has one.
29
41
  */
30
42
  export declare function readDevelopmentRuntimeArtifactsSnapshotRoot(pointerPath: string | undefined): string | undefined;
43
+ export declare function readActiveDevelopmentRuntimeArtifactsSnapshot(appRoot: string): ActiveDevelopmentRuntimeArtifactsSnapshot | undefined;
31
44
  /**
32
45
  * Reads a revision token for the latest dev runtime artifact snapshot.
33
46
  */
34
47
  export declare function readDevelopmentRuntimeArtifactsRevision(appRoot: string): DevelopmentRuntimeArtifactsRevision;
48
+ /**
49
+ * Bounds dev snapshot storage without consulting a Workflow World. The active
50
+ * generation is always retained; retired generations receive a grace period,
51
+ * and the newest retired generations remain as a rebuild-rate safety net.
52
+ */
35
53
  export declare function pruneDevelopmentRuntimeArtifactsSnapshots(input: {
36
54
  readonly appRoot: string;
55
+ readonly gracePeriodMs?: number;
37
56
  readonly now?: number;
38
- readonly recentWindowMs?: number;
39
57
  readonly retainCount?: number;
40
58
  }): Promise<void>;
@@ -1 +1 @@
1
- import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,mkdir,readFile,readdir,rename,rm,stat,writeFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{createDevelopmentSourceSnapshotPlan}from"#internal/nitro/dev-runtime-source-snapshot.js";const DEV_RUNTIME_ARTIFACTS_DIRECTORY=`dev-runtime`,DEV_RUNTIME_ARTIFACTS_ACTIVATED_MARKER=`activated`,TERMINAL_WORKFLOW_RUN_STATUSES=new Set([`completed`,`failed`,`cancelled`,`canceled`]);function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`current.json`)}function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`snapshots`)}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot})}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){await writeFile(join(e.snapshot.snapshotRoot,DEV_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),``),await writeDevelopmentRuntimeArtifactsPointer(e)}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(t){let n=resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(t.appRoot),i=[...collectProtectedSnapshotPaths(readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(t.appRoot))),...await collectWorkflowDataSnapshotPaths({appRoot:t.appRoot,snapshotsDirectory:n})],a=t.now??Date.now(),o=t.recentWindowMs??9e5,s=t.retainCount??5,c;try{c=await readdir(n,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let l=(await Promise.all(c.filter(e=>e.isDirectory()).map(async e=>{let t=join(n,e.name);return{path:t,mtimeMs:(await stat(t)).mtimeMs}}))).sort((e,t)=>t.mtimeMs-e.mtimeMs);await Promise.all(l.map(async(t,n)=>{existsSync(join(t.path,DEV_RUNTIME_ARTIFACTS_ACTIVATED_MARKER))||n<s||a-t.mtimeMs<=o||i.some(e=>pathsOverlap(t.path,e))||await rm(t.path,{force:!0,recursive:!0})}))}function readDevelopmentRuntimeArtifactsPointer(n){if(!(n===void 0||!existsSync(n)))try{let e=JSON.parse(readFileSync(n,`utf8`));return e.kind!==`eve-dev-runtime-artifacts-pointer`||typeof e.version!=`number`?void 0:e.version===1&&typeof e.appRoot==`string`&&e.appRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:e.version===2&&typeof e.appRoot==`string`&&typeof e.runtimeAppRoot==`string`&&e.runtimeAppRoot.length>0&&typeof e.snapshotRoot==`string`&&e.snapshotRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.runtimeAppRoot,snapshotRoot:e.snapshotRoot,version:2}:void 0}catch{return}}function collectProtectedSnapshotPaths(e){return e===void 0?[]:e.version===1?[e.appRoot]:[e.runtimeAppRoot,e.snapshotRoot]}async function collectWorkflowDataSnapshotPaths(e){let t=join(e.appRoot,`.workflow-data`),n=new Set;return await collectSnapshotPathsFromDirectory({directory:t,snapshotPaths:n,snapshotsDirectory:e.snapshotsDirectory}),[...n]}async function collectSnapshotPathsFromDirectory(e){let t;try{t=await readdir(e.directory,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(t.map(async t=>{let n=join(e.directory,t.name);if(t.isDirectory()){await collectSnapshotPathsFromDirectory({directory:n,snapshotPaths:e.snapshotPaths,snapshotsDirectory:e.snapshotsDirectory});return}if(!t.isFile()||(await stat(n)).size>1048576)return;let i=await readFile(n,`utf8`);if(shouldScanWorkflowDataSource(i))for(let t of collectSnapshotPathsFromText(i,e.snapshotsDirectory))e.snapshotPaths.add(t)}))}function collectSnapshotPathsFromText(e,t){let n=new Set,i=t.replaceAll(`\\`,`/`),a=RegExp(`${escapeRegExp(i)}/([^/"'\\s]+)`,`gu`),o=e.replaceAll(`\\\\`,`/`).replaceAll(`\\`,`/`);for(let e of o.matchAll(a)){let i=e[1];i!==void 0&&i.length>0&&n.add(join(t,i))}return[...n]}function shouldScanWorkflowDataSource(e){let t=parseJsonObject(e);if(t===void 0)return!0;let n=t.status;return typeof n!=`string`||!TERMINAL_WORKFLOW_RUN_STATUSES.has(n)}function parseJsonObject(e){try{let t=JSON.parse(e);return isObjectRecord(t)?t:void 0}catch{return}}function isObjectRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}function pathsOverlap(e,t){return isPathInsideOrEqual(e,t)||isPathInsideOrEqual(t,e)}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:t});await writeFile(e.manifestPath,`${JSON.stringify(n,null,2)}\n`)}function rewriteManifestRoots(e){if(Array.isArray(e.value))return e.value.map(t=>rewriteManifestRoots({...e,value:t}));if(e.value===null||typeof e.value!=`object`)return e.value;let t={};for(let[n,r]of Object.entries(e.value)){if(typeof r==`string`&&(n===`appRoot`||n===`agentRoot`)){t[n]=rewritePathWithinAppRoot({appRoot:e.appRoot,path:r,runtimeAppRoot:e.runtimeAppRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:r})}return t}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot))return e.path;let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),r=`${t}.${randomUUID()}.tmp`,i={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await mkdir(dirname(t),{recursive:!0}),await writeFile(r,`${JSON.stringify(i,null,2)}\n`);try{await rename(r,t)}catch(e){throw await rm(r,{force:!0}).catch(()=>{}),e}}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.runtimeAppRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime app root "${e.runtimeAppRoot}".`)}function collectManifestRootPaths(e){if(Array.isArray(e))return e.flatMap(e=>collectManifestRootPaths(e));if(typeof e!=`object`||!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if((n===`appRoot`||n===`agentRoot`)&&typeof r==`string`){t.push(r);continue}t.push(...collectManifestRootPaths(r))}return t}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{activateDevelopmentRuntimeArtifactsSnapshot,pruneDevelopmentRuntimeArtifactsSnapshots,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
1
+ import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{createDevelopmentSourceSnapshotPlan}from"#internal/nitro/dev-runtime-source-snapshot.js";import{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts-retention.js";const DEV_RUNTIME_ARTIFACTS_DIRECTORY=`dev-runtime`;function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`current.json`)}function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`snapshots`)}function isDevelopmentRuntimeArtifactsSnapshotRoot(e,t){return dirname(resolve(t))===resolve(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e))}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await writeFile(join(t,`generation.json`),`${JSON.stringify({runtimeAppRoot:n.runtimeAppRoot})}\n`)}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){(await activateDevelopmentRuntimeArtifactsSnapshotTransaction(e)).commit()}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),n=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(n),a=await readOptionalFile(n);try{await writeFile(t,``),await writeDevelopmentRuntimeArtifactsPointer(e),i?.version===2&&i.snapshotRoot!==e.snapshot.snapshotRoot&&isDevelopmentRuntimeArtifactsSnapshotRoot(e.appRoot,i.snapshotRoot)&&await recordRetiredDevelopmentRuntimeArtifactsSnapshot(i.snapshotRoot).catch(e=>{console.warn(`[eve:dev] failed to record retired runtime generation "${i.snapshotRoot}": ${String(e)}`)})}catch(e){throw await rollbackFailedActivation({cause:e,markerPath:t,pointerPath:n,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:t,pointerPath:n,previousPointerSource:a});if(e!==void 0)throw e}}}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readActiveDevelopmentRuntimeArtifactsSnapshot(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e));if(!(t===void 0||t.version===1))return{runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot}}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot));await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({activeSnapshotRoot:t?.version===2?t.snapshotRoot:void 0,gracePeriodMs:e.gracePeriodMs,now:e.now,protectAll:t?.version===1,retainCount:e.retainCount,snapshotsDirectory:resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot)})}function readDevelopmentRuntimeArtifactsPointer(n){if(!(n===void 0||!existsSync(n)))try{let e=JSON.parse(readFileSync(n,`utf8`));return e.kind!==`eve-dev-runtime-artifacts-pointer`||typeof e.version!=`number`?void 0:e.version===1&&typeof e.appRoot==`string`&&e.appRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:e.version===2&&typeof e.appRoot==`string`&&typeof e.runtimeAppRoot==`string`&&e.runtimeAppRoot.length>0&&typeof e.snapshotRoot==`string`&&e.snapshotRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.runtimeAppRoot,snapshotRoot:e.snapshotRoot,version:2}:void 0}catch{return}}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:t});await writeFile(e.manifestPath,`${JSON.stringify(n,null,2)}\n`)}function rewriteManifestRoots(e){if(Array.isArray(e.value))return e.value.map(t=>rewriteManifestRoots({...e,value:t}));if(e.value===null||typeof e.value!=`object`)return e.value;let t={};for(let[n,r]of Object.entries(e.value)){if(typeof r==`string`&&(n===`appRoot`||n===`agentRoot`)){t[n]=rewritePathWithinAppRoot({appRoot:e.appRoot,path:r,runtimeAppRoot:e.runtimeAppRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:r})}return t}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot))return e.path;let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),n={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await writeDevelopmentRuntimeArtifactsPointerSource(t,`${JSON.stringify(n,null,2)}\n`)}async function writeDevelopmentRuntimeArtifactsPointerSource(e,t){let r=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(r,t);try{await renameWithTransientBusyRetry(r,e)}catch(e){throw await rm(r,{force:!0}).catch(()=>{}),e}}async function readOptionalFile(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function rollbackFailedActivation(e){let t=await restoreDevelopmentRuntimeArtifactsActivation(e);return t===void 0?e.cause:AggregateError([e.cause,t],`Development runtime activation and rollback failed.`,{cause:e.cause})}async function restoreDevelopmentRuntimeArtifactsActivation(e){let t=(await Promise.allSettled([e.previousPointerSource===void 0?rm(e.pointerPath,{force:!0}):writeDevelopmentRuntimeArtifactsPointerSource(e.pointerPath,e.previousPointerSource),rm(e.markerPath,{force:!0})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length!==0)return AggregateError(t,`Failed to restore development runtime activation.`)}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.runtimeAppRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime app root "${e.runtimeAppRoot}".`)}function collectManifestRootPaths(e){if(Array.isArray(e))return e.flatMap(e=>collectManifestRootPaths(e));if(typeof e!=`object`||!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if((n===`appRoot`||n===`agentRoot`)&&typeof r==`string`){t.push(r);continue}t.push(...collectManifestRootPaths(r))}return t}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{activateDevelopmentRuntimeArtifactsSnapshot,activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,readActiveDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
@@ -1,5 +1,5 @@
1
1
  import type { CompileAgentResult } from "#compiler/compile-agent.js";
2
- import { type DevelopmentRuntimeArtifactsSnapshot } from "#internal/nitro/dev-runtime-artifacts.js";
2
+ import { type DevelopmentRuntimeArtifactsActivation, type DevelopmentRuntimeArtifactsSnapshot } from "#internal/nitro/dev-runtime-artifacts.js";
3
3
  export interface DevelopmentGeneration extends DevelopmentRuntimeArtifactsSnapshot {
4
4
  readonly fingerprint: string;
5
5
  }
@@ -9,4 +9,8 @@ export declare function activateDevelopmentGeneration(input: {
9
9
  readonly appRoot: string;
10
10
  readonly generation: DevelopmentGeneration;
11
11
  }): Promise<void>;
12
+ export declare function activateDevelopmentGenerationTransaction(input: {
13
+ readonly appRoot: string;
14
+ readonly generation: DevelopmentGeneration;
15
+ }): Promise<DevelopmentRuntimeArtifactsActivation>;
12
16
  export declare function discardDevelopmentGeneration(generation: DevelopmentGeneration): Promise<void>;
@@ -1 +1 @@
1
- import{rm}from"node:fs/promises";import{materializeAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshot,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";async function stageDevelopmentGeneration(n){let r=await stageDevelopmentRuntimeArtifactsSnapshot(n);try{let e=await materializeAuthoredModules({appRoot:n.project.appRoot,runtimeAppRoot:r.runtimeAppRoot,snapshotSourceRoot:r.snapshotSourceRoot,sourceRoot:r.sourceRoot});return{...r,fingerprint:e.fingerprint}}catch(t){try{await rm(r.snapshotRoot,{force:!0,recursive:!0})}catch(e){throw AggregateError([t,e],`Failed to materialize and discard development generation "${r.snapshotRoot}".`)}throw t}}async function publishDevelopmentGeneration(e){let t=await stageDevelopmentGeneration(e);return await activateDevelopmentGeneration({appRoot:e.project.appRoot,generation:t}),t}async function activateDevelopmentGeneration(e){await activateDevelopmentRuntimeArtifactsSnapshot({appRoot:e.appRoot,snapshot:e.generation})}async function discardDevelopmentGeneration(t){await rm(t.snapshotRoot,{force:!0,recursive:!0})}export{activateDevelopmentGeneration,discardDevelopmentGeneration,publishDevelopmentGeneration,stageDevelopmentGeneration};
1
+ import{rm}from"node:fs/promises";import{materializeAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";const developmentGenerationPruneStates=new Map;async function stageDevelopmentGeneration(n){let r=await stageDevelopmentRuntimeArtifactsSnapshot(n);try{let e=await materializeAuthoredModules({runtimeAppRoot:r.runtimeAppRoot});return{...r,fingerprint:e.fingerprint}}catch(t){try{await rm(r.snapshotRoot,{force:!0,recursive:!0})}catch(e){throw AggregateError([t,e],`Failed to materialize and discard development generation "${r.snapshotRoot}".`)}throw t}}async function publishDevelopmentGeneration(e){let t=await stageDevelopmentGeneration(e);return await activateDevelopmentGeneration({appRoot:e.project.appRoot,generation:t}),t}async function activateDevelopmentGeneration(e){(await activateDevelopmentGenerationTransaction(e)).commit()}async function activateDevelopmentGenerationTransaction(e){let t=await activateDevelopmentRuntimeArtifactsSnapshotTransaction({appRoot:e.appRoot,snapshot:e.generation}),r=!1;return{commit(){r||(r=!0,t.commit(),requestDevelopmentGenerationPrune(e.appRoot))},async rollback(){r||(r=!0,await t.rollback())}}}async function discardDevelopmentGeneration(t){await rm(t.snapshotRoot,{force:!0,recursive:!0})}function requestDevelopmentGenerationPrune(e){let t=developmentGenerationPruneStates.get(e)??{requested:!1,running:void 0};developmentGenerationPruneStates.set(e,t),t.requested=!0,t.running===void 0&&startDevelopmentGenerationPruning(e,t)}function startDevelopmentGenerationPruning(e,t){t.running=(async()=>{for(;t.requested;)t.requested=!1,await pruneDevelopmentRuntimeArtifactsSnapshots({appRoot:e})})().catch(e=>{console.warn(`[eve:dev] failed to prune runtime generations: ${String(e)}`)}).finally(()=>{t.running=void 0,t.requested?startDevelopmentGenerationPruning(e,t):developmentGenerationPruneStates.delete(e)})}export{activateDevelopmentGeneration,activateDevelopmentGenerationTransaction,discardDevelopmentGeneration,publishDevelopmentGeneration,stageDevelopmentGeneration};
@@ -1,4 +1,5 @@
1
1
  import type { DevelopmentNitroArtifactsConfig, ProductionNitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
2
+ import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";
2
3
  /**
3
4
  * Runtime-artifacts wiring for the dev server: routes read compiled
4
5
  * artifacts from the authored app root via the snapshot pointer so hot
@@ -6,6 +7,7 @@ import type { DevelopmentNitroArtifactsConfig, ProductionNitroArtifactsConfig }
6
7
  */
7
8
  export declare function createDevelopmentNitroArtifactsConfig(input: {
8
9
  readonly appRoot: string;
10
+ readonly configuredWorld?: AgentWorkflowWorldDefinition;
9
11
  }): DevelopmentNitroArtifactsConfig;
10
12
  /**
11
13
  * Runtime-artifacts wiring for built output: routes require the artifacts
@@ -1 +1 @@
1
- import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{resolveDevelopmentRuntimeArtifactsPointerPath}from"#internal/nitro/dev-runtime-artifacts.js";function createDevelopmentNitroArtifactsConfig(e){return{appRoot:e.appRoot,devRuntimeArtifactsPointerPath:resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),kind:`development`,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`)}}function createProductionNitroArtifactsConfig(){return{kind:`production`}}export{createDevelopmentNitroArtifactsConfig,createProductionNitroArtifactsConfig};
1
+ import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{resolveDevelopmentRuntimeArtifactsPointerPath}from"#internal/nitro/dev-runtime-artifacts.js";function createDevelopmentNitroArtifactsConfig(e){return{appRoot:e.appRoot,devRuntimeArtifactsPointerPath:resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),durableArtifactsReference:usesParentDevelopmentWorkflowWorld(e.configuredWorld)?`development-generation`:void 0,kind:`development`,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`)}}function createProductionNitroArtifactsConfig(){return{kind:`production`}}export{createDevelopmentNitroArtifactsConfig,createProductionNitroArtifactsConfig};
@@ -1 +1 @@
1
- import{resolvePackageRoot,resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,join,resolve}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{resolveDiscoveryProject}from"#discover/project.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,t){let a=Array.from(new Set([resolve(e),resolve(t)])),s=await findClosestVercelOutputDirectory(e);if(s!==void 0)try{let e=JSON.parse(await readFile(join(s,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:await resolveVercelOutputConfigRoot(s),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let c=e;for(;;){for(let e of[join(c,`vercel.json`),join(c,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),r=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:e.endsWith(`vercel.json`)?c:await resolveVercelOutputConfigRoot(dirname(e)),config:t});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(c);if(e===c)return;c=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(t,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e){let t=trimTrailingSlash(e.options.output.dir);return await prepareEveVersionedCacheDirectory(t),await prepare(e),await copyPublicAssets(e),await prerender(e),await build(e),await writeEveVersionedCacheMetadata(t),t}async function buildVercelNitroSurface(e,t,n){let i=await createProductionApplicationNitro(e,{buildDir:join(t.nitro.buildDir,n),outputDir:join(t.nitro.surfaceOutputDir,n),surface:n});try{return await buildNitroOutput(i)}finally{await i.close()}}async function buildApplication(e,t){let n=await tryReadExtensionBuildConfig(e);if(n!==null)throw Error(`Package "${n.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let r=await createApplicationBuildWorkspace((await resolveDiscoveryProject(e)).appRoot),i=!1;try{return await buildApplicationInWorkspace(r,t)}catch(e){throw i=e instanceof RecoverablePublicationError,e}finally{i||await removeApplicationBuildWorkspace(r)}}async function buildApplicationInWorkspace(e,n){let i=await prepareProductionApplicationHost(e);if(!process.env.VERCEL){let t=await createProductionApplicationNitro(i,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,surface:`all`});try{await buildNitroOutput(t),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath}),await stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir})}finally{await t.close()}return await publishCompletedApplicationBuild(e),e.publication.output.finalDir}let a=await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(i.appRoot,i.compileResult.project.agentRoot),o=await createProductionApplicationNitro(i,{buildDir:join(e.nitro.buildDir,`app`),outputDir:e.publication.output.stagedDir,surface:`app`});try{await buildNitroOutput(o),n.skipVercelSandboxPrewarm||await runVercelBuildPrewarm({appRoot:i.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:i.appRoot}),log(e){console.log(e)}});let r=await buildVercelNitroSurface(i,e,`flow`);await emitVercelWorkflowFunctions({agentName:i.compileResult.manifest.config.name,appRoot:i.appRoot,compiledArtifactsBootstrapPath:i.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e.publication.output.stagedDir,workflowBuildDir:e.workflow.buildDir}),a!==void 0&&await normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:a}),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath})}finally{await o.close()}return await publishCompletedApplicationBuild(e),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
1
+ import{resolvePackageRoot,resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,join,resolve}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{resolveDiscoveryProject}from"#discover/project.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,t){let a=Array.from(new Set([resolve(e),resolve(t)])),s=await findClosestVercelOutputDirectory(e);if(s!==void 0)try{let e=JSON.parse(await readFile(join(s,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:await resolveVercelOutputConfigRoot(s),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let c=e;for(;;){for(let e of[join(c,`vercel.json`),join(c,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),r=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:e.endsWith(`vercel.json`)?c:await resolveVercelOutputConfigRoot(dirname(e)),config:t});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(c);if(e===c)return;c=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(t,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e){let t=trimTrailingSlash(e.options.output.dir);return await prepareEveVersionedCacheDirectory(t),await prepare(e),await copyPublicAssets(e),await prerender(e),await build(e),await writeEveVersionedCacheMetadata(t),t}async function buildVercelNitroSurface(e,t,n){let i=await createProductionApplicationNitro(e,{buildDir:join(t.nitro.buildDir,n),outputDir:join(t.nitro.surfaceOutputDir,n),surface:n});try{return await buildNitroOutput(i)}finally{await i.close()}}async function buildApplication(e,t){let n=await tryReadExtensionBuildConfig(e);if(n!==null)throw Error(`Package "${n.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let r=await createApplicationBuildWorkspace((await resolveDiscoveryProject(e)).appRoot,t.vercelServiceOutput?.serviceOutputDirectory),i=!1;try{return await buildApplicationInWorkspace(r,t)}catch(e){throw i=e instanceof RecoverablePublicationError,e}finally{i||await removeApplicationBuildWorkspace(r)}}async function buildApplicationInWorkspace(e,n){let i=await prepareProductionApplicationHost(e);if(!process.env.VERCEL){let t=await createProductionApplicationNitro(i,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,surface:`all`});try{await buildNitroOutput(t),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath}),await stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir})}finally{await t.close()}return await publishCompletedApplicationBuild(e),e.publication.output.finalDir}let a=await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(i.appRoot,i.compileResult.project.agentRoot),o=await createProductionApplicationNitro(i,{buildDir:join(e.nitro.buildDir,`app`),outputDir:e.publication.output.stagedDir,surface:`app`});try{await buildNitroOutput(o),n.skipVercelSandboxPrewarm||await runVercelBuildPrewarm({appRoot:i.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:i.appRoot}),log(e){console.log(e)}});let r=await buildVercelNitroSurface(i,e,`flow`);await emitVercelWorkflowFunctions({agentName:i.compileResult.manifest.config.name,appRoot:i.appRoot,compiledArtifactsBootstrapPath:i.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e.publication.output.stagedDir,workflowBuildDir:e.workflow.buildDir}),a!==void 0&&await normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:a}),n.vercelServiceOutput!==void 0&&await copyHostMiddlewareFunctions({hostOutputDirectory:n.vercelServiceOutput.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir}),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath})}finally{await o.close()}return await publishCompletedApplicationBuild(e),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
@@ -4,10 +4,7 @@ import type { ChannelRouteMethod } from "#public/definitions/channel.js";
4
4
  import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
5
5
  import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
6
6
  interface ChannelRouteNitro {
7
- options: Pick<Nitro["options"], "handlers" | "virtual">;
8
- routing: {
9
- sync(): void;
10
- };
7
+ readonly options: Pick<Nitro["options"], "handlers" | "virtual">;
11
8
  }
12
9
  /**
13
10
  * One Nitro route registration for an eve channel.
@@ -28,13 +25,4 @@ export declare function registerChannelVirtualHandlers(nitro: Pick<ChannelRouteN
28
25
  readonly artifactsConfig: NitroArtifactsConfig;
29
26
  readonly registrations: readonly NitroChannelRouteRegistration[];
30
27
  }): void;
31
- /**
32
- * Replaces the currently-mounted eve channel virtual handlers when the route
33
- * set changes.
34
- */
35
- export declare function syncChannelVirtualHandlers(nitro: ChannelRouteNitro, input: {
36
- readonly artifactsConfig: NitroArtifactsConfig;
37
- readonly next: readonly NitroChannelRouteRegistration[];
38
- readonly previous: readonly NitroChannelRouteRegistration[];
39
- }): boolean;
40
28
  export {};
@@ -1,5 +1,5 @@
1
- import{resolvePackageDependencyPath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{replaceDevLiveVirtualModules}from"#internal/nitro/host/dev-live-virtual-modules.js";const EVE_CHANNEL_VIRTUAL_ID_PREFIX=`#nitro/virtual/eve-channel/`;function computeChannelRouteRegistrations(e){let t=e.compileResult.manifest.channels,n=new Set,a=[],o=new Set,s=getAllFrameworkChannelNames();for(let e of t){if(e.kind===`disabled`){if(!s.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...s].sort().join(`, `)}.`);o.add(e.name);continue}n.add(e.name),a.push({method:e.method,route:e.urlPath,cors:e.cors})}let c=getFrameworkChannelDefinitions().filter(e=>!n.has(e.name)&&!o.has(e.name)).map(e=>({method:e.method,route:e.urlPath,cors:e.cors})),l=new Set,u=[];for(let e of[...c,...a]){let t=createChannelRouteKey(e);l.has(t)||(l.add(t),u.push(e))}return u}function registerChannelVirtualHandlers(e,t){let n=new Set;for(let r of t.registrations)addChannelVirtualHandler(e,{artifactsConfig:t.artifactsConfig,cors:r.cors,method:r.method,preflightRoutes:n,route:r.route})}function syncChannelVirtualHandlers(e,t){if(areChannelRouteRegistrationsEqual(t.previous,t.next))return!1;removeChannelVirtualHandlers(e),registerChannelVirtualHandlers(e,{artifactsConfig:t.artifactsConfig,registrations:t.next});let n={};for(let[t,r]of Object.entries(e.options.virtual))t.startsWith(EVE_CHANNEL_VIRTUAL_ID_PREFIX)&&typeof r==`string`&&(n[t]=r);return replaceDevLiveVirtualModules(e,{entries:n,prefix:EVE_CHANNEL_VIRTUAL_ID_PREFIX})||console.warn("[eve:dev] channel routes changed but the dev bundler's virtual-module map was not captured; restart `eve dev` to mount the new routes."),e.routing.sync(),!0}function createChannelRouteKey(e){return`${e.method.toUpperCase()} ${e.route}`}function addChannelVirtualHandler(r,i){let a=createChannelRouteKey(i),s=`${EVE_CHANNEL_VIRTUAL_ID_PREFIX}${a}`,c=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/nitro/routes/channel-dispatch.ts`)),l=stringifyEsmImportSpecifier(resolvePackageDependencyPath(`nitro`)),u=stringifyEsmImportSpecifier(resolvePackageDependencyPath(`nitro/h3`));if(i.method===`WEBSOCKET`){r.options.handlers.push({handler:s,route:i.route}),r.options.virtual[s]=[`import { defineWebSocketHandler } from ${l};`,`import { dispatchChannelWebSocketRequest } from ${c};`,`const config = ${JSON.stringify(i.artifactsConfig)};`,`export default defineWebSocketHandler((event) => dispatchChannelWebSocketRequest(event, ${JSON.stringify(a)}, config));`].join(`
2
- `);return}r.options.handlers.push({handler:s,method:i.method,route:i.route}),i.cors!==void 0&&addChannelCorsPreflightHandler(r,{cors:i.cors,nitroH3ModulePath:u,preflightRoutes:i.preflightRoutes,route:i.route}),r.options.virtual[s]=[...i.cors===void 0?[]:[`import { handleCors } from ${u};`,`const cors = ${JSON.stringify(i.cors)};`],`import { dispatchChannelRequest } from ${c};`,`const config = ${JSON.stringify(i.artifactsConfig)};`,i.cors===void 0?`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(a)}, config);`:[`export default (event) => {`,` const corsResponse = handleCors(event, cors);`,` if (corsResponse !== false) return corsResponse;`,` return dispatchChannelRequest(event, ${JSON.stringify(a)}, config);`,`};`].join(`
1
+ import{resolvePackageDependencyPath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";const EVE_CHANNEL_VIRTUAL_ID_PREFIX=`#nitro/virtual/eve-channel/`;function computeChannelRouteRegistrations(e){let t=e.compileResult.manifest.channels,n=new Set,a=[],o=new Set,s=getAllFrameworkChannelNames();for(let e of t){if(e.kind===`disabled`){if(!s.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...s].sort().join(`, `)}.`);o.add(e.name);continue}n.add(e.name),a.push({method:e.method,route:e.urlPath,cors:e.cors})}let c=getFrameworkChannelDefinitions().filter(e=>!n.has(e.name)&&!o.has(e.name)).map(e=>({method:e.method,route:e.urlPath,cors:e.cors})),l=new Set,u=[];for(let e of[...c,...a]){let t=createChannelRouteKey(e);l.has(t)||(l.add(t),u.push(e))}return u}function registerChannelVirtualHandlers(e,t){let n=new Set;for(let r of t.registrations)addChannelVirtualHandler(e,{artifactsConfig:t.artifactsConfig,cors:r.cors,method:r.method,preflightRoutes:n,route:r.route})}function createChannelRouteKey(e){return`${e.method.toUpperCase()} ${e.route}`}function addChannelVirtualHandler(r,i){let o=createChannelRouteKey(i),s=`${EVE_CHANNEL_VIRTUAL_ID_PREFIX}${o}`,c=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/nitro/routes/channel-dispatch.ts`)),l=stringifyEsmImportSpecifier(resolvePackageDependencyPath(`nitro`)),u=stringifyEsmImportSpecifier(resolvePackageDependencyPath(`nitro/h3`));if(i.method===`WEBSOCKET`){r.options.handlers.push({handler:s,route:i.route}),r.options.virtual[s]=[`import { defineWebSocketHandler } from ${l};`,`import { dispatchChannelWebSocketRequest } from ${c};`,`const config = ${JSON.stringify(i.artifactsConfig)};`,`export default defineWebSocketHandler((event) => dispatchChannelWebSocketRequest(event, ${JSON.stringify(o)}, config));`].join(`
2
+ `);return}r.options.handlers.push({handler:s,method:i.method,route:i.route}),i.cors!==void 0&&addChannelCorsPreflightHandler(r,{cors:i.cors,nitroH3ModulePath:u,preflightRoutes:i.preflightRoutes,route:i.route}),r.options.virtual[s]=[...i.cors===void 0?[]:[`import { handleCors } from ${u};`,`const cors = ${JSON.stringify(i.cors)};`],`import { dispatchChannelRequest } from ${c};`,`const config = ${JSON.stringify(i.artifactsConfig)};`,i.cors===void 0?`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(o)}, config);`:[`export default (event) => {`,` const corsResponse = handleCors(event, cors);`,` if (corsResponse !== false) return corsResponse;`,` return dispatchChannelRequest(event, ${JSON.stringify(o)}, config);`,`};`].join(`
3
3
  `)].join(`
4
4
  `)}function addChannelCorsPreflightHandler(e,t){if(t.preflightRoutes.has(t.route))return;t.preflightRoutes.add(t.route);let n=`${EVE_CHANNEL_VIRTUAL_ID_PREFIX}${`OPTIONS ${t.route}`}`;e.options.handlers.push({handler:n,method:`OPTIONS`,route:t.route}),e.options.virtual[n]=[`import { handleCors } from ${t.nitroH3ModulePath};`,`const cors = ${JSON.stringify(t.cors)};`,`export default (event) => {`,` const corsResponse = handleCors(event, cors);`,` if (corsResponse !== false) return corsResponse;`,` return new Response(null, { status: 204 });`,`};`].join(`
5
- `)}function removeChannelVirtualHandlers(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&isChannelVirtualHandler(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(EVE_CHANNEL_VIRTUAL_ID_PREFIX)&&delete e.options.virtual[t]}function isChannelVirtualHandler(e){return e.handler.startsWith(EVE_CHANNEL_VIRTUAL_ID_PREFIX)}function areChannelRouteRegistrationsEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.method!==i.method||r.route!==i.route||!areChannelCorsOptionsEqual(r.cors,i.cors))return!1}return!0}function areChannelCorsOptionsEqual(e,t){return JSON.stringify(e)===JSON.stringify(t)}export{computeChannelRouteRegistrations,registerChannelVirtualHandlers,syncChannelVirtualHandlers};
5
+ `)}export{computeChannelRouteRegistrations,registerChannelVirtualHandlers};
@@ -2,8 +2,7 @@ import type { Nitro } from "nitro/types";
2
2
  import type { NitroBuildSurface, PreparedApplicationHost } from "#internal/nitro/host/types.js";
3
3
  /**
4
4
  * Wires eve's package-owned app, channel, workflow inspection, dev-control,
5
- * and Workflow SDK endpoints into the watch-mode Nitro host, rebuilding
6
- * workflow bundles on reload.
5
+ * and Workflow SDK endpoints into one development Nitro candidate.
7
6
  */
8
7
  export declare function configureDevelopmentNitroRoutes(nitro: Nitro, preparedHost: PreparedApplicationHost): Promise<void>;
9
8
  /**
@@ -1,4 +1,4 @@
1
- import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";import{resolvePackageRoot,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{isVercelBuildEnvironment}from"#internal/application/paths.js";import{normalizeEsmImportSpecifier,stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{createDevelopmentNitroArtifactsConfig,createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{computeChannelRouteRegistrations,registerChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";function includesApplicationRoutes(e){return e===`all`||e===`app`}function includesWorkflowBundles(e){return includesWorkflowRoute(e)}function includesWorkflowRoute(e){return e===`all`||e===`flow`}function registerHandler(e,t){let n=`#eve-route-handler/${t.method??`ALL`} ${t.route}`,r=stringifyEsmImportSpecifier(t.handlerPath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import handler from ${r};`,`export default handler;`].join(`
1
+ import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";import{resolvePackageRoot,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{isVercelBuildEnvironment}from"#internal/application/paths.js";import{normalizeEsmImportSpecifier,stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{createDevelopmentNitroArtifactsConfig,createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{computeChannelRouteRegistrations,registerChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";function includesApplicationRoutes(e){return e===`all`||e===`app`}function includesWorkflowBundles(e){return includesWorkflowRoute(e)}function includesWorkflowRoute(e){return e===`all`||e===`flow`}function registerHandler(e,t){let n=`#eve-route-handler/${t.method??`ALL`} ${t.route}`,r=stringifyEsmImportSpecifier(t.handlerPath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import handler from ${r};`,`export default handler;`].join(`
2
2
  `)}function resolveNitroWorkflowBuildDirectory(e){return join(e.options.buildDir,`workflow`)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function addWorkflowFileHandler(e,t){let n=join(resolveNitroWorkflowBuildDirectory(e),`${t.bundleName}-handler.mjs`),r=dirname(n),i=createRelativeImportSpecifier(r,t.bundlePath),a=t.directHandlers??[],s=a.length>0&&t.workflowWorldPluginPath!==void 0?createRelativeImportSpecifier(r,t.workflowWorldPluginPath):void 0,c=a.map(e=>{let t=createRelativeImportSpecifier(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await mkdir(r,{recursive:!0}),await writeFile(n,buildWorkflowFileHandlerSource({bundlePath:i,directHandlers:c,runtimeImportSpecifier:t.runtimeImportSpecifier,workflowWorldPluginImportSpecifier:s})),e.options.handlers.push({handler:n,route:t.route})}function buildWorkflowFileHandlerSource(e){let t=[`// Generated by eve. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__eveWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);e.workflowWorldPluginImportSpecifier!==void 0&&t.push(`import ${JSON.stringify(e.workflowWorldPluginImportSpecifier)};`),t.push(`import { getWorld as __eveGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __eveWorkflowWorld = await __eveGetWorkflowWorld();`,` if (typeof __eveWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __eveWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[eve] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
3
3
  `)}function addFrameworkVirtualHandler(e,t){let n=`#eve-route${t.route}`,r=stringifyEsmImportSpecifier(t.modulePath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import { ${t.handlerExport} } from ${r};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
4
- `)}async function registerWorkflowArtifactBuildHook(e,t){let n=!0;await t(),e.hooks.hook(`build:before`,async()=>{if(n){n=!1;return}await t()})}function registerApplicationRoutes(e,t,r){addFrameworkVirtualHandler(e,{args:JSON.stringify({agentName:t.compileResult.manifest.config.name}),handlerExport:`handleHomePageRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/index.ts`),route:`/`});for(let t of[`GET`,`HEAD`])registerHandler(e,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/health.ts`),method:t,route:EVE_HEALTH_ROUTE_PATH});registerChannelVirtualHandlers(e,{artifactsConfig:r,registrations:computeChannelRouteRegistrations(t)})}function registerDevelopmentControlRoutes(n,r){addFrameworkVirtualHandler(n,{args:JSON.stringify({appRoot:r.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}),addFrameworkVirtualHandler(n,{args:JSON.stringify(r),handlerExport:`handleDevScheduleDispatchRequest`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN})}function createWorkflowDirectHandlerEntry(e,t){return{bundlePath:t,queuePrefix:deriveEveWorkflowQueuePrefix(e.compileResult.manifest.config.name)}}async function registerWorkflowRoute(e,t,n,r){await addWorkflowFileHandler(e,{bundleName:`workflows`,bundlePath:n,directHandlers:r,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:r.length===0?void 0:normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)),workflowWorldPluginPath:t.compiledArtifacts.workflowWorldPluginPath})}async function configureDevelopmentNitroRoutes(e,t){let n=resolveNitroWorkflowBuildDirectory(e),i=new WorkflowBundleBuilder({agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!0}),syncWorkflowArtifacts=async()=>{await i.build({nitroStepOutfile:join(n,`steps.mjs`),nitroWorkflowOutfile:join(n,`workflows.mjs`)})};await registerWorkflowArtifactBuildHook(e,syncWorkflowArtifacts),e.hooks.hook(`dev:reload`,syncWorkflowArtifacts);let a=createDevelopmentNitroArtifactsConfig({appRoot:t.appRoot});registerApplicationRoutes(e,t,a),registerDevelopmentControlRoutes(e,a);let o=join(n,`workflows.mjs`);await registerWorkflowRoute(e,t,o,[createWorkflowDirectHandlerEntry(t,o)]),e.routing.sync()}async function configureProductionNitroRoutes(e,t,n){if(includesWorkflowBundles(n)){let n=new WorkflowBundleBuilder({agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1});await registerWorkflowArtifactBuildHook(e,async()=>{await n.build({nitroStepOutfile:join(resolveNitroWorkflowBuildDirectory(e),`steps.mjs`)})})}if(includesApplicationRoutes(n)&&registerApplicationRoutes(e,t,createProductionNitroArtifactsConfig()),includesWorkflowRoute(n)){let n=join(t.workflowBuildDir,`workflows.mjs`),r=t.compileResult.manifest.config.experimental?.workflow?.world!==void 0;await registerWorkflowRoute(e,t,n,!isVercelBuildEnvironment()&&r?[createWorkflowDirectHandlerEntry(t,n)]:[])}e.routing.sync()}export{configureDevelopmentNitroRoutes,configureProductionNitroRoutes};
4
+ `)}async function registerWorkflowArtifactBuildHook(e,t){let n=!0;await t(),e.hooks.hook(`build:before`,async()=>{if(n){n=!1;return}await t()})}function registerApplicationRoutes(e,t,r){addFrameworkVirtualHandler(e,{args:JSON.stringify({agentName:t.compileResult.manifest.config.name}),handlerExport:`handleHomePageRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/index.ts`),route:`/`});for(let t of[`GET`,`HEAD`])registerHandler(e,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/health.ts`),method:t,route:EVE_HEALTH_ROUTE_PATH});registerChannelVirtualHandlers(e,{artifactsConfig:r,registrations:computeChannelRouteRegistrations(t)})}function registerDevelopmentControlRoutes(n,r){addFrameworkVirtualHandler(n,{args:JSON.stringify({appRoot:r.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}),addFrameworkVirtualHandler(n,{args:JSON.stringify(r),handlerExport:`handleDevScheduleDispatchRequest`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN})}function createWorkflowDirectHandlerEntry(e,t){return{bundlePath:t,queuePrefix:deriveEveWorkflowQueuePrefix(e.compileResult.manifest.config.name)}}async function registerWorkflowRoute(e,t,n,r){await addWorkflowFileHandler(e,{bundleName:`workflows`,bundlePath:n,directHandlers:r,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:r.length===0?void 0:normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)),workflowWorldPluginPath:t.compiledArtifacts.workflowWorldPluginPath})}async function configureDevelopmentNitroRoutes(e,t){let n=resolveNitroWorkflowBuildDirectory(e),i=new WorkflowBundleBuilder({agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!0});await registerWorkflowArtifactBuildHook(e,async()=>{await i.build({nitroStepOutfile:join(n,`steps.mjs`),nitroWorkflowOutfile:join(n,`workflows.mjs`)})});let a=createDevelopmentNitroArtifactsConfig({appRoot:t.appRoot,configuredWorld:t.compileResult.manifest.config.experimental?.workflow?.world});registerApplicationRoutes(e,t,a),registerDevelopmentControlRoutes(e,a);let o=join(n,`workflows.mjs`),s=[];usesParentDevelopmentWorkflowWorld(t.compileResult.manifest.config.experimental?.workflow?.world)||s.push(createWorkflowDirectHandlerEntry(t,o)),await registerWorkflowRoute(e,t,o,s),e.routing.sync()}async function configureProductionNitroRoutes(e,t,n){if(includesWorkflowBundles(n)){let n=new WorkflowBundleBuilder({agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1});await registerWorkflowArtifactBuildHook(e,async()=>{await n.build({nitroStepOutfile:join(resolveNitroWorkflowBuildDirectory(e),`steps.mjs`)})})}if(includesApplicationRoutes(n)&&registerApplicationRoutes(e,t,createProductionNitroArtifactsConfig()),includesWorkflowRoute(n)){let n=join(t.workflowBuildDir,`workflows.mjs`),r=t.compileResult.manifest.config.experimental?.workflow?.world!==void 0;await registerWorkflowRoute(e,t,n,!isVercelBuildEnvironment()&&r?[createWorkflowDirectHandlerEntry(t,n)]:[])}e.routing.sync()}export{configureDevelopmentNitroRoutes,configureProductionNitroRoutes};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Copies host middleware functions into a generated service Build Output.
3
+ *
4
+ * Vercel validates generated-service routes against each service builder's
5
+ * function map. The host remains the runtime owner of these functions; this
6
+ * copy makes that same opaque Build Output function available while Vercel
7
+ * collects the generated service.
8
+ */
9
+ export declare function copyHostMiddlewareFunctions(input: {
10
+ readonly hostOutputDirectory: string;
11
+ readonly serviceOutputDirectory: string;
12
+ }): Promise<void>;
@@ -0,0 +1 @@
1
+ import{dirname,join,posix,resolve,sep}from"node:path";import{access,cp,mkdir,readFile}from"node:fs/promises";function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const NEXT_MIDDLEWARE_PATH=`/_middleware`;function resolveMiddlewareFunctionDirectory(e,t){let a=posix.normalize(t.replace(/^\/+/,``));if(a.length===0||a===`.`||a===`..`||a.startsWith(`../`)||a.includes(`\\`)||a.includes(`\0`))throw Error(`Invalid Vercel middlewarePath: ${JSON.stringify(t)}.`);let o=resolve(e,`functions`),s=resolve(o,`${a}.func`);if(!s.startsWith(`${o}${sep}`))throw Error(`Vercel middlewarePath escapes the functions directory: ${t}.`);return s}async function copyHostMiddlewareFunctions(n){let r=JSON.parse(await readFile(join(n.hostOutputDirectory,`config.json`),`utf8`));if(!isRecord(r))return;let i=new Set;if(Array.isArray(r.routes))for(let e of r.routes)isRecord(e)&&typeof e.middlewarePath==`string`&&i.add(e.middlewarePath);let c=resolveMiddlewareFunctionDirectory(n.hostOutputDirectory,NEXT_MIDDLEWARE_PATH);try{await access(c),i.add(NEXT_MIDDLEWARE_PATH)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}for(let t of i){let r=resolveMiddlewareFunctionDirectory(n.hostOutputDirectory,t),i=resolveMiddlewareFunctionDirectory(n.serviceOutputDirectory,t);await mkdir(dirname(i),{recursive:!0}),await cp(r,i,{force:!0,recursive:!0})}}export{copyHostMiddlewareFunctions};
@@ -1,5 +1,5 @@
1
1
  import type { Nitro } from "nitro/types";
2
- import type { NitroBuildSurface, PreparedApplicationHost } from "#internal/nitro/host/types.js";
2
+ import type { NitroBuildSurface, PreparedApplicationHost, PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
3
3
  /**
4
4
  * Hosted Vercel builds can prune local sandbox backends only when the
5
5
  * app did not explicitly configure one. Omitted backends resolve through
@@ -11,11 +11,9 @@ export declare function shouldPruneLocalSandboxBackends(input: {
11
11
  readonly preset: "vercel" | undefined;
12
12
  }): boolean;
13
13
  /**
14
- * Creates the watch-mode Nitro host for `eve dev`: all route surfaces on one
15
- * instance, live virtual modules, and hot-reload hooks wired to the authored
16
- * source.
14
+ * Creates one isolated Nitro host candidate for `eve dev`.
17
15
  */
18
- export declare function createDevelopmentApplicationNitro(preparedHost: PreparedApplicationHost): Promise<Nitro>;
16
+ export declare function createDevelopmentApplicationNitro(preparedHost: PreparedDevelopmentApplicationHost): Promise<Nitro>;
19
17
  interface ProductionApplicationNitroOptions {
20
18
  readonly buildDir: string;
21
19
  readonly outputDir: string;
@@ -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};