eve 0.9.0 → 0.9.2
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.
- package/CHANGELOG.md +24 -0
- package/bin/eve.d.ts +5 -0
- package/bin/eve.js +16 -13
- package/dist/src/cli/agent-detection.d.ts +8 -0
- package/dist/src/cli/agent-detection.js +1 -0
- package/dist/src/cli/commands/agent-instructions.d.ts +7 -0
- package/dist/src/cli/commands/agent-instructions.js +1 -0
- package/dist/src/cli/commands/init-agent-handoff.md +12 -0
- package/dist/src/cli/commands/init-agent-instructions.md +16 -0
- package/dist/src/cli/commands/init-git.js +1 -1
- package/dist/src/cli/commands/init.d.ts +8 -1
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/environment.js +1 -1
- package/dist/src/cli/dev/tui/blocks.d.ts +8 -0
- package/dist/src/cli/dev/tui/blocks.js +2 -2
- package/dist/src/cli/dev/tui/command-typeahead.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +10 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +4 -0
- package/dist/src/cli/dev/tui/setup-commands.js +2 -2
- package/dist/src/cli/dev/tui/setup-issues.d.ts +15 -0
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +8 -2
- package/dist/src/cli/dev/tui/terminal-renderer.js +9 -6
- package/dist/src/cli/run.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +3 -1
- package/dist/src/compiled/@vercel/detect-agent/LICENSE +202 -0
- package/dist/src/compiled/@vercel/detect-agent/index.d.ts +20 -0
- package/dist/src/compiled/@vercel/detect-agent/index.js +1 -0
- package/dist/src/compiled/semver/LICENSE +15 -0
- package/dist/src/compiled/semver/index.d.ts +23 -0
- package/dist/src/compiled/semver/index.js +1 -0
- package/dist/src/execution/sandbox/bindings/docker-templates.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-templates.js +1 -1
- package/dist/src/execution/sandbox/logging-session.js +2 -1
- package/dist/src/internal/application/compiled-artifacts.js +1 -1
- package/dist/src/internal/application/optional-package-install.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/application/paths.js +1 -1
- package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
- package/dist/src/internal/authored-module-loader.js +2 -2
- package/dist/src/internal/bundler/nitro-rolldown.d.ts +3 -0
- package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/dev-watcher-log.d.ts +3 -0
- package/dist/src/internal/nitro/host/dev-watcher-log.js +1 -1
- package/dist/src/internal/nitro/host/start-development-server.d.ts +1 -2
- package/dist/src/internal/nitro/host/start-development-server.js +2 -1
- package/dist/src/internal/nitro/host/start-production-server.js +2 -2
- package/dist/src/internal/process/pnpm.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.js +2 -2
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +3 -3
- package/dist/src/public/next/server.js +1 -1
- package/dist/src/setup/boxes/add-channels.d.ts +4 -6
- package/dist/src/setup/boxes/add-channels.js +1 -1
- package/dist/src/setup/boxes/apply-ai-gateway-credential.js +1 -1
- package/dist/src/setup/boxes/link-project.js +1 -1
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/boxes/scaffold.d.ts +2 -2
- package/dist/src/setup/boxes/scaffold.js +1 -1
- package/dist/src/setup/flows/channels.d.ts +2 -0
- package/dist/src/setup/flows/channels.js +1 -1
- package/dist/src/setup/flows/deploy.js +1 -1
- package/dist/src/setup/flows/install-vercel-cli.d.ts +42 -0
- package/dist/src/setup/flows/install-vercel-cli.js +1 -0
- package/dist/src/setup/flows/link.js +1 -1
- package/dist/src/setup/flows/login.d.ts +49 -0
- package/dist/src/setup/flows/login.js +1 -0
- package/dist/src/setup/flows/model.js +1 -1
- package/dist/src/setup/flows/vercel.d.ts +2 -0
- package/dist/src/setup/flows/vercel.js +1 -1
- package/dist/src/setup/node-engine.d.ts +31 -0
- package/dist/src/setup/node-engine.js +1 -0
- package/dist/src/setup/onboarding.d.ts +3 -2
- package/dist/src/setup/onboarding.js +1 -1
- package/dist/src/setup/primitives/coding-agent-env.d.ts +17 -0
- package/dist/src/setup/primitives/coding-agent-env.js +1 -0
- package/dist/src/setup/primitives/pm/pnpm.js +2 -2
- package/dist/src/setup/primitives/pm/run.d.ts +6 -0
- package/dist/src/setup/primitives/pm/run.js +1 -1
- package/dist/src/setup/primitives/run-vercel.d.ts +1 -1
- package/dist/src/setup/primitives/run-vercel.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.d.ts +10 -5
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.d.ts +17 -4
- package/dist/src/setup/scaffold/create/project.js +9 -5
- package/dist/src/setup/scaffold/index.d.ts +1 -1
- package/dist/src/setup/scaffold/update/channels.d.ts +4 -2
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/package-json.d.ts +12 -1
- package/dist/src/setup/scaffold/update/package-json.js +1 -1
- package/dist/src/setup/scaffold/version-tokens.js +1 -1
- package/dist/src/setup/slack-connect-create.d.ts +41 -0
- package/dist/src/setup/slack-connect-create.js +1 -0
- package/dist/src/setup/slack-connect-lifecycle.d.ts +40 -11
- package/dist/src/setup/slack-connect-lifecycle.js +1 -1
- package/dist/src/setup/slack-connect.d.ts +25 -14
- package/dist/src/setup/slack-connect.js +1 -1
- package/dist/src/setup/slackbot.d.ts +12 -16
- package/dist/src/setup/slackbot.js +1 -1
- package/dist/src/setup/vercel-project.d.ts +25 -0
- package/dist/src/setup/vercel-project.js +1 -1
- package/dist/src/source-change/apply-model-name.d.ts +2 -2
- package/dist/src/source-change/apply-model-name.js +1 -1
- package/dist/src/source-change/static-source-change.js +1 -1
- package/docs/getting-started.mdx +7 -7
- package/docs/guides/dev-tui.md +3 -1
- package/docs/reference/cli.md +2 -0
- package/package.json +9 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,join}from"node:path";import
|
|
1
|
+
import"node:fs";import{dirname,join}from"node:path";import{mkdir,readdir,rename,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{randomUUID}from"node:crypto";import{copyDirectoryAtomically,createFileBackedInternalSandboxSession,pathExists,resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory,touchDirectory,writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,selectStaleTemplateEntries}from"#execution/sandbox/bindings/local-template-prune.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{createBashSandbox,createJustBashHandle,justBashSetNetworkPolicyUnsupported}from"#execution/sandbox/bindings/just-bash-runtime.js";const JUST_BASH_CACHE_DIRECTORY_NAME=`just-bash`,JUST_BASH_BACKEND_NAME=`just-bash`;function createJustBashSandboxBackend(t={}){let r=t.createOptions?.autoInstall??!0;return{name:JUST_BASH_BACKEND_NAME,async prewarm(t){let a=resolveTemplateRootPath(resolveSandboxCacheDirectory(t.runtimeContext.appRoot),t.templateKey);if(await pathExists(a))return await touchDirectory(a),{reused:!0};let s=`${a}.${randomUUID()}.tmp`,u=!1,d=await createBashSandbox({appRoot:t.runtimeContext.appRoot,autoInstall:r,rootPath:s,sessionKey:t.templateKey}),f=buildSandboxSession(createFileBackedInternalSandboxSession({id:d.sessionKey,sandbox:d}),justBashSetNetworkPolicyUnsupported);try{if(t.bootstrap!==void 0&&(t.log?.(`running sandbox bootstrap`),await t.bootstrap({use:async()=>createLoggingSandboxSession({log:t.log,session:f})})),await writeSandboxSeedFiles(f,t.seedFiles),await d.captureState()===null)throw Error(`Failed to capture local sandbox template state for "${t.templateKey}".`);await mkdir(dirname(a),{recursive:!0});try{await rename(s,a),u=!0}catch(e){if(await pathExists(a))return{reused:!0};throw e}}finally{await d.dispose(),u||await rm(s,{force:!0,recursive:!0}).catch(()=>{})}return{reused:!1}},async create(e){let t=resolveSandboxCacheDirectory(e.runtimeContext.appRoot),i=getLocalRootPath(e.existingMetadata)??resolveSessionRootPath(t,e.sessionKey);if(!await pathExists(i))if(e.templateKey===null)await mkdir(i,{recursive:!0});else{let n=resolveTemplateRootPath(t,e.templateKey);if(!await pathExists(n))throw new SandboxTemplateNotProvisionedError({backendName:JUST_BASH_BACKEND_NAME,templateKey:e.templateKey});await copyDirectoryAtomically(n,i)}return createJustBashHandle(await createBashSandbox({appRoot:e.runtimeContext.appRoot,autoInstall:r,rootPath:i,sessionKey:e.sessionKey}),JUST_BASH_BACKEND_NAME)}}}async function pruneJustBashSandboxTemplates(e){let n=resolveLocalBackendTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot),JUST_BASH_CACHE_DIRECTORY_NAME),i=e.now??Date.now(),o=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,s=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,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 r=join(n,e.name);return{isTemporary:e.name.endsWith(`.tmp`),mtimeMs:(await stat(r)).mtimeMs,path:r}})),u=selectStaleTemplateEntries(l.filter(e=>!e.isTemporary),{now:i,recentWindowMs:o,retainCount:s}),d=selectStaleTemplateEntries(l.filter(e=>e.isTemporary),{now:i,recentWindowMs:o,retainCount:0});await Promise.all([...u,...d].map(async e=>await rm(e.path,{force:!0,recursive:!0})))}function resolveTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function resolveSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function getLocalRootPath(e){let t=e?.rootPath;return typeof t==`string`?t:void 0}export{JUST_BASH_BACKEND_NAME,createJustBashSandboxBackend,pruneJustBashSandboxTemplates};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import"node:fs";import{join}from"node:path";import{readdir,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT}from"#execution/sandbox/bindings/local-template-prune.js";import{readTemplateMetadata,resolveMicrosandboxMetadataPath}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{loadMicrosandboxWithoutInstall,removeSnapshotIfExists}from"#execution/sandbox/bindings/microsandbox-runtime.js";const MICROSANDBOX_CACHE_DIRECTORY_NAME=`microsandbox`;async function pruneMicrosandboxTemplates(e){let t=resolveMicrosandboxTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot)),n=e.now??Date.now(),r=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,a=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,o=await readMicrosandboxTemplateDirectories(t),s=o.filter(e=>!e.isTemporary);await Promise.all([...s.map(async(e,t)=>{t<a||n-e.mtimeMs<=r||await removeTemplateDirectory(e.path,e.metadata)}),...o.filter(e=>e.isTemporary).map(async e=>{n-e.mtimeMs<=r||await removeTemplateDirectory(e.path,e.metadata)})])}function resolveMicrosandboxTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}function resolveMicrosandboxTemplatesDirectory(e){return resolveLocalBackendTemplatesDirectory(e,MICROSANDBOX_CACHE_DIRECTORY_NAME)}function resolveMicrosandboxSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}async function readMicrosandboxTemplateDirectories(n){let i;try{i=await readdir(n,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return[];throw e}return(await Promise.all(i.filter(e=>e.isDirectory()).map(async t=>{let i=join(n,t.name);return{isTemporary:t.name.endsWith(`.tmp`),metadata:await readTemplateMetadata(resolveMicrosandboxMetadataPath(i)),mtimeMs:(await stat(i)).mtimeMs,path:i}}))).sort((e,t)=>t.mtimeMs-e.mtimeMs)}async function removeTemplateDirectory(e,t){if(await rm(e,{force:!0,recursive:!0}),t===null)return;let r=await loadMicrosandboxWithoutInstall();r!==null&&await removeSnapshotIfExists(r,t.snapshotName)}export{pruneMicrosandboxTemplates,resolveMicrosandboxSessionRootPath,resolveMicrosandboxTemplateRootPath,resolveMicrosandboxTemplatesDirectory};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
function createLoggingSandboxSession(e){let{log:t,session:n}=e;return
|
|
1
|
+
function createLoggingSandboxSession(e){let{log:t,session:n}=e;return{...n,async run(e){t?.(`bootstrap run: ${formatCommand(e.command)}`);let r=await n.run(e);if(r.exitCode===1)throw Error(formatBootstrapRunFailure(e.command,r));return r},async spawn(e){return t?.(`bootstrap spawn: ${formatCommand(e.command)}`),await n.spawn(e)},async setNetworkPolicy(e){return t?.(`bootstrap set network policy: ${formatNetworkPolicy(e)}`),await n.setNetworkPolicy(e)},async writeFile(e){return t?.(`bootstrap write file: ${e.path}`),await n.writeFile(e)},async writeBinaryFile(e){return t?.(`bootstrap write binary file: ${e.path} (${e.content.byteLength} bytes)`),await n.writeBinaryFile(e)},async writeTextFile(e){return t?.(`bootstrap write text file: ${e.path} (${e.content.length} chars)`),await n.writeTextFile(e)},async removePath(e){return t?.(`bootstrap remove path: ${e.path}`),await n.removePath(e)}}}function formatBootstrapRunFailure(e,t){return[`Sandbox bootstrap failed because sandbox.run command exited with code 1:`,e,``,`stdout:`,t.stdout,``,`stderr:`,t.stderr].join(`
|
|
2
|
+
`)}function formatCommand(e){return truncateOneLine(e)}function formatNetworkPolicy(e){return truncateOneLine(typeof e==`string`?e:JSON.stringify(e))}function truncateOneLine(e){let t=e.replaceAll(/\s+/g,` `).trim();return t.length<=240?t:`${t.slice(0,239)}…`}export{createLoggingSandboxSession};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{
|
|
1
|
+
import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{join}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";async function writeCompiledArtifactsFiles(t){let i=join(t.outDir,`compiled-artifacts-bootstrap.mjs`),a=join(t.outDir,`compiled-artifacts-instrumentation.mjs`),o=resolveInstrumentationModule(t.compileResult.manifest.agentRoot);await mkdir(t.outDir,{recursive:!0}),await writeFile(i,await createCompiledArtifactsBootstrapSource({compileResult:t.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:i,metadata:t.compileResult.metadata})),o!==void 0&&await writeFile(a,createInstrumentationPluginSource({agentName:t.compileResult.manifest.config.name,instrumentationPath:o,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)}));let s={bootstrapPath:i};return o!==void 0&&(s.instrumentationPluginPath=a,s.instrumentationSourcePath=o),s}const INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];function resolveInstrumentationModule(e){for(let n of INSTRUMENTATION_EXTENSIONS){let r=join(e,`instrumentation${n}`);if(existsSync(r))return r}}function stripCompiledModuleMapExports(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
|
|
2
2
|
`)}async function createCompiledArtifactsBootstrapSource(e){let t=stripCompiledModuleMapExports(createCompiledModuleMapSource({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by Eve. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(e.installModulePath)};`,``,t,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``,`export async function __eveInstallCompiledArtifactsStep() {`,` "use step";`,` return null;`,`}`,``].join(`
|
|
3
3
|
`)}function createInstrumentationPluginSource(e){return[`// Generated by Eve. Do not edit by hand.`,`import * as instrumentationModule from ${stringifyEsmImportSpecifier(e.instrumentationPath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(e.registerConfigPath)};`,``,`if (instrumentationModule.default != null) {`,` registerInstrumentationConfig(instrumentationModule.default, { agentName: ${JSON.stringify(e.agentName)} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
|
|
4
4
|
`)}export{writeCompiledArtifactsFiles};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync}from"node:fs";import{dirname,join}from"node:path";import{spawn}from"node:child_process";const EVE_DEV_ENV_FLAG=`EVE_DEV`;function isEveDevEnvironment(){return process.env[EVE_DEV_ENV_FLAG]===`1`}function detectProjectPackageManager(r){let i=r;for(;;){if(existsSync(join(i,`pnpm-lock.yaml`))||existsSync(join(i,`pnpm-workspace.yaml`)))return`pnpm`;if(existsSync(join(i,`yarn.lock`)))return`yarn`;if(existsSync(join(i,`bun.lock`))||existsSync(join(i,`bun.lockb`)))return`bun`;if(existsSync(join(i,`package-lock.json`)))return`npm`;let r=dirname(i);if(r===i)return`npm`;i=r}}const INSTALL_ARGUMENTS={bun:[`add`,`--dev`],npm:[`install`,`--save-dev`],pnpm:[`add`,`-D`],yarn:[`add`,`-D`]};async function installPackageIntoProject(e){let t=detectProjectPackageManager(e.appRoot),n=[...INSTALL_ARGUMENTS[t],e.packageName];console.info(`[eve:dev] installing optional dependency "${e.packageName}" via \`${t} ${n.join(` `)}\`...`);let i=spawn(t,n,{cwd:e.appRoot,shell:shouldSpawnPackageManagerWithShell(),stdio:[`ignore`,`pipe`,`pipe`]}),a=[];i.stdout?.on(`data`,e=>a.push(e)),i.stderr?.on(`data`,e=>a.push(e));let o=await new Promise((e,t)=>{i.on(`error`,t),i.on(`close`,t=>e(t??1))});if(o!==0){let n=Buffer.concat(a).toString(`utf8`).trim();throw Error(`Failed to install "${e.packageName}" with ${t} (exit ${o}).`+(n.length>0?`\n${n.slice(-2e3)}`:``))}console.info(`[eve:dev] installed "${e.packageName}".`)}async function loadOptionalEnginePackage(e){try{return await e.importModule()}catch(t){if(!e.autoInstall||!isEveDevEnvironment())throw Error(e.missingMessage,{cause:t});try{await installPackageIntoProject({appRoot:e.appRoot,packageName:e.packageName})}catch(t){throw Error(`${e.missingMessage} Automatic installation failed: ${toMessage(t)}`,{cause:t})}return await e.importModule()}}function shouldSpawnPackageManagerWithShell(e=process.platform){return e===`win32`}function toMessage(e){return e instanceof Error?e.message:String(e)}export{EVE_DEV_ENV_FLAG,detectProjectPackageManager,installPackageIntoProject,isEveDevEnvironment,loadOptionalEnginePackage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.9.2`,WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveInstalledPackageInfo,resolvePackageRoot,resolvePackageSourceDirectoryPath}from"#internal/application/package.js";import{
|
|
1
|
+
import{resolveInstalledPackageInfo,resolvePackageRoot,resolvePackageSourceDirectoryPath}from"#internal/application/package.js";import{existsSync,readFileSync,readdirSync,rmSync}from"node:fs";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{workflowEntryReference}from"#execution/workflow-runtime.js";function resolveApplicationRoot(e=process.cwd()){return resolve(e)}function getWorkflowBuildCacheKey(e){return createHash(`sha256`).update(e).digest(`hex`).slice(0,12)}function isVercelBuildEnvironment(){return!!process.env.VERCEL}function resolveNitroBuildDirectory(e,t=`all`){let n=join(e,`.eve`,`nitro`);return t===`all`?n:join(n,t)}function resolveNitroSurfaceOutputDirectory(e,t){return join(e,`.eve`,`nitro-output`,t)}function resolveWorkflowBuildDirectory(e){let n=join(resolvePackageRoot(),`.eve`,`workflow-cache`);return pruneStaleWorkflowCacheSiblings(n),join(n,getWorkflowBuildCacheKey(e))}function pruneStaleWorkflowCacheSiblings(t){if(!existsSync(t))return;let n=resolveInstalledPackageInfo().version,i;try{i=readdirSync(t)}catch{return}for(let e of i){let r=join(t,e),i=join(r,`eve-cache.json`);if(existsSync(i))try{let e=JSON.parse(readFileSync(i,`utf8`));typeof e.eveVersion==`string`&&e.eveVersion!==n&&rmSync(r,{force:!0,recursive:!0})}catch{}}}function resolveSandboxCacheDirectory(e){return join(e,`.eve`,`sandbox-cache`)}function resolveOutputDirectory(e){return isVercelBuildEnvironment()?join(e,`.vercel`,`output`):join(e,`.output`)}function getApplicationInfo(e){return{appRoot:e,outputDir:resolveOutputDirectory(e),workflowId:workflowEntryReference.workflowId,workflowBuildDir:resolveWorkflowBuildDirectory(e),workflowSourceDir:resolvePackageSourceDirectoryPath(`src/execution`)}}export{getApplicationInfo,resolveApplicationRoot,resolveNitroBuildDirectory,resolveNitroSurfaceOutputDirectory,resolveOutputDirectory,resolveSandboxCacheDirectory,resolveWorkflowBuildDirectory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import{readFile,readdir}from"node:fs/promises";import{parse}from"#compiled/jsonc-parser/index.js";async function resolveTsConfigDependencyPaths(e){let t=await resolveRootTsConfigPaths(e),n=new Set,r=new Set;for(let e of t)await collectTsConfigDependencyPaths({configPath:e,resolvedConfigPaths:n,visitingConfigPaths:r});return[...n].sort((e,t)=>e.localeCompare(t))}async function resolveRootTsConfigPaths(e){let t=new Set([join(e,`tsconfig.json`),join(e,`jsconfig.json`)]);try{let n=await readdir(e,{withFileTypes:!0});for(let r of n)r.isFile()&&/^tsconfig\..+\.json$/i.test(r.name)&&t.add(join(e,r.name))}catch{}return[...t]}async function collectTsConfigDependencyPaths(e){let t=resolve(e.configPath);if(e.resolvedConfigPaths.has(t)||e.visitingConfigPaths.has(t))return;let n=await readTextFileIfExists(t);if(n!==void 0){e.resolvedConfigPaths.add(t),e.visitingConfigPaths.add(t);try{let r=extractTsConfigExtendsSpecifiers(n);for(let n of r)for(let r of resolveTsConfigExtendsTargetPaths({configPath:t,extendsSpecifier:n}))await collectTsConfigDependencyPaths({configPath:r,resolvedConfigPaths:e.resolvedConfigPaths,visitingConfigPaths:e.visitingConfigPaths})}finally{e.visitingConfigPaths.delete(t)}}}async function readTextFileIfExists(e){try{return await readFile(e,`utf8`)}catch{return}}function parseTsConfigObject(e){let t=[],n=parse(e,t,{allowTrailingComma:!0});if(!(t.length>0||typeof n!=`object`||!n||Array.isArray(n)))return n}function extractTsConfigExtendsSpecifiers(e){let t=parseTsConfigObject(e);if(t===void 0)return[];let n=t.extends;return typeof n==`string`?n.length>0?[n]:[]:Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.length>0):[]}function resolveTsConfigExtendsTargetPaths(e){let t=new Set;if(isTsConfigFilePath(e.extendsSpecifier))for(let n of resolveFileExtendsCandidates({configPath:e.configPath,extendsSpecifier:e.extendsSpecifier}))t.add(n);else for(let n of resolvePackageExtendsCandidates({configPath:e.configPath,extendsSpecifier:e.extendsSpecifier}))t.add(n);return[...t]}function resolveFirstExistingTsConfigExtendsTarget(e){for(let n of resolveTsConfigExtendsTargetPaths(e))if(existsSync(n))return n}function resolveFileExtendsCandidates(e){let t=resolve(dirname(e.configPath),e.extendsSpecifier),r=new Set;return r.add(t),t.endsWith(`.json`)||(r.add(`${t}.json`),r.add(join(t,`tsconfig.json`))),[...r]}function resolvePackageExtendsCandidates(t){let n=new Set([t.extendsSpecifier]);t.extendsSpecifier.endsWith(`.json`)||(n.add(`${t.extendsSpecifier}.json`),n.add(`${t.extendsSpecifier}/tsconfig.json`));let r=new Set,i=createRequire(t.configPath);for(let e of n)try{r.add(i.resolve(e))}catch{}return[...r]}function isTsConfigFilePath(e){return e.startsWith(`.`)||isAbsolute(e)?!0:/^[A-Za-z]:[\\/]/.test(e)}export{collectTsConfigDependencyPaths,extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveRootTsConfigPaths,resolveTsConfigDependencyPaths,resolveTsConfigExtendsTargetPaths};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{expectObjectRecord}from"#internal/authored-module.js";import{
|
|
2
|
-
`),moduleType:`js`}}}:null,d=[createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:
|
|
1
|
+
import{createRequire}from"node:module";import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,realpathSync,writeFileSync}from"node:fs";import{dirname,join,resolve,sep}from"node:path";import{createHash}from"node:crypto";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`],CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`,CACHED_CHANNEL_PREFIX=`eve-cached-channel:`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(e,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,n):await import(createFileImportSpecifier(e)),`Expected "${e}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function loadBundledAuthoredModule(e,t){let i=getChannelModuleCache(),o=resolveAuthoredPackageRoot(e),c=resolveAuthoredTsConfigPath(o),l=normalizeExternalDependencies(t.externalDependencies),u=i&&i.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let r=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(r===null||typeof r.id!=`string`)return;let a=resolve(r.id);if(i.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(19);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
|
|
2
|
+
`),moduleType:`js`}}}:null,d=[createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:o,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createPackageBoundaryPlugin(o,l),u].filter(e=>e!==null),f;try{f=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:o,input:e,platform:`node`,plugins:d,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:c,write:!1,output:{comments:!1,format:`esm`,sourcemap:`inline`}}),`authored module for "${e}"`)}catch(t){throw createAuthoredModuleBundleError(e,t)}let p=createHash(`sha1`).update(e).update(`\0`).update(l.join(`\0`)).update(`\0`).update(f.code).digest(`hex`),m=join(o,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),h=join(m,`${p}.mjs`);return existsSync(h)||(mkdirSync(m,{recursive:!0}),writeFileSync(h,f.code)),await import(`${createFileImportSpecifier(h)}?v=${p}`)}function createPackageBoundaryPlugin(e,t){let n=toCanonicalPath(e);return{name:`eve-package-boundary`,async resolveId(r,i,a){if(!isPackageImport(r))return;if(isEveFrameworkImport(r))return{external:!0,id:r};let o=resolveConfiguredExternalDependency(r,t);if(o!==void 0){if(r!==o){let t=await this.resolve(r,i,{kind:a.kind,skipSelf:!0});if(t!==null&&typeof t.id==`string`)return{external:!0,id:resolveExternalFilePath({importer:i,packageRoot:e,resolvedId:t.id,source:r})};let n=resolveExternalFilePath({importer:i,packageRoot:e,source:r});if(n!==void 0)return{external:!0,id:n}}return{external:!0,id:r}}let s=i===void 0||i.startsWith(`\0`)||i.startsWith(CACHED_CHANNEL_PREFIX)?void 0:resolve(i);if(s!==void 0&&isPathInsideOrEqual(toCanonicalPath(s),n)){let e=await this.resolve(r,i,{kind:a.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${r}" imported from "${s}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:r}}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}`}function normalizeExternalDependencies(e=[]){return[...new Set([...SERVER_EXTERNAL_PACKAGES,...e])].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function resolveExternalFilePath(t){if(t.resolvedId!==void 0){let e=resolveExistingExternalFilePath(t.resolvedId);if(e!==void 0)return e}let n=normalizeImporterPath(t.importer);if(n!==void 0)try{return createRequire(n).resolve(t.source)}catch{}try{return createRequire(join(t.packageRoot,`package.json`)).resolve(t.source)}catch{return t.resolvedId}}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let r=`${e}${t}`;if(existsSync(r))return r}}function normalizeImporterPath(e){if(!(e===void 0||e.startsWith(`\0`)||e.startsWith(CACHED_CHANNEL_PREFIX)))return resolve(e)}function isPackageImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)||/^(?:node|data|file):/.test(e)||e.startsWith(`@/`)?!1:!e.startsWith(CACHED_CHANNEL_PREFIX)}function isEveFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,t);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return t;let r=dirname(t);if(r===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=r}}export{loadAuthoredModuleNamespace};
|
|
@@ -13,6 +13,7 @@ type RolldownOutput = {
|
|
|
13
13
|
};
|
|
14
14
|
export type RolldownBuild = (options: Record<string, unknown>) => Promise<RolldownOutput>;
|
|
15
15
|
type RolldownParseAst = (sourceText: string, options?: Record<string, unknown> | null, filename?: string) => unknown;
|
|
16
|
+
export type RolldownParserLanguage = "js" | "jsx" | "ts" | "tsx";
|
|
16
17
|
type RolldownParseAstModule = {
|
|
17
18
|
readonly parseAst: RolldownParseAst;
|
|
18
19
|
};
|
|
@@ -21,6 +22,8 @@ type RolldownParseAstModule = {
|
|
|
21
22
|
* transforms can use the same bundler dependency without exposing it publicly.
|
|
22
23
|
*/
|
|
23
24
|
export declare function loadNitroRolldownParseAst(): Promise<RolldownParseAstModule>;
|
|
25
|
+
export declare function inferRolldownParserLanguage(filename: string): RolldownParserLanguage;
|
|
26
|
+
export declare function parseWithNitroRolldownAst(filename: string, sourceText: string): Promise<unknown>;
|
|
24
27
|
export declare function buildWithNitroRolldown(options: Record<string, unknown>): Promise<RolldownOutput>;
|
|
25
28
|
export declare function getSingleRolldownChunk(output: RolldownOutput, description: string): RolldownOutputChunk;
|
|
26
29
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{pathToFileURL}from"node:url";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown`)).href))(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`)).href))(),rolldownParseAstPromise}async function buildWithNitroRolldown(e){let{build:t}=await loadNitroRolldown();return await t(e)}function getSingleRolldownChunk(e,t){let n=e.output.filter(e=>e.type===`chunk`),r=n[0];if(r===void 0||n.length!==1)throw Error(`Expected one bundled ${t}.`);return r}export{buildWithNitroRolldown,getSingleRolldownChunk,loadNitroRolldownParseAst};
|
|
1
|
+
import{createRequire}from"node:module";import{pathToFileURL}from"node:url";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown`)).href))(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`)).href))(),rolldownParseAstPromise}function inferRolldownParserLanguage(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:/\.[cm]?ts$/.test(e)?`ts`:`js`}async function parseWithNitroRolldownAst(e,t){let{parseAst:n}=await loadNitroRolldownParseAst();return n(t,{astType:`ts`,lang:inferRolldownParserLanguage(e),range:!0,sourceType:`module`},e)}async function buildWithNitroRolldown(e){let{build:t}=await loadNitroRolldown();return await t(e)}function getSingleRolldownChunk(e,t){let n=e.output.filter(e=>e.type===`chunk`),r=n[0];if(r===void 0||n.length!==1)throw Error(`Expected one bundled ${t}.`);return r}export{buildWithNitroRolldown,getSingleRolldownChunk,inferRolldownParserLanguage,loadNitroRolldownParseAst,parseWithNitroRolldownAst};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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`;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 publishDevelopmentRuntimeArtifactsSnapshot(e){let t=await stageDevelopmentRuntimeArtifactsSnapshot(e);return await activateDevelopmentRuntimeArtifactsSnapshot({appRoot:e.project.appRoot,snapshot:t}),t}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}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){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}}function pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(e){pruneDevelopmentRuntimeArtifactsSnapshots({appRoot:e}).catch(e=>{console.warn(`[eve:dev] failed to prune stale runtime snapshots: ${formatErrorMessage(e)}`)})}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot),n=collectProtectedSnapshotPaths(readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot))),i=e.now??Date.now(),a=e.recentWindowMs??9e5,o=e.retainCount??5,s;try{s=await readdir(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let c=(await Promise.all(s.filter(e=>e.isDirectory()).map(async e=>{let n=join(t,e.name);return{path:n,mtimeMs:(await stat(n)).mtimeMs}}))).sort((e,t)=>t.mtimeMs-e.mtimeMs);await Promise.all(c.map(async(e,t)=>{t<o||i-e.mtimeMs<=a||n.some(t=>pathsOverlap(e.path,t))||await rm(e.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]}function pathsOverlap(e,t){return isPathInsideOrEqual(e,t)||isPathInsideOrEqual(t,e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(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,pruneDevelopmentRuntimeArtifactsSnapshotsInBackground,publishDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,join,relative,resolve,sep}from"node:path";import{
|
|
1
|
+
import{existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.eve`,`.git`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`node_modules`]);async function copyDevelopmentSourceSnapshot(t){await mkdir(t.snapshotSourceRoot,{recursive:!0});for(let e of t.copyRoots)await copySnapshotPath({plan:t,sourcePath:e,targetPath:toSnapshotPathForPlan(t,e)});for(let n of t.copyFiles)existsSync(n)&&await copySnapshotPath({plan:t,sourcePath:n,targetPath:toSnapshotPathForPlan(t,n)});await rewriteSnapshotTsConfigAbsoluteExtends(t),await createSnapshotSymlinks(t),await validateDevelopmentSourceSnapshot(t)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let r=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan.sourceRoot,r)||await cp(r,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan.sourceRoot,t),recursive:!0})}}function shouldSkipSnapshotSource(e,t){let n=relative(e,t);return n.length===0?!1:n.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e))}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let n of e.symlinks){let i=toSnapshotPathForPlan(e,n.linkPath),a=n.targetKind===`local`?toSnapshotPathForPlan(e,n.targetPath):n.targetPath,o=n.targetKind===`local`?relative(dirname(i),a)||`.`:a;await mkdir(dirname(i),{recursive:!0}),await symlink(o,i,`junction`)}}async function validateDevelopmentSourceSnapshot(t){let r=join(t.runtimeAppRoot,`package.json`);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${r}".`);for(let n of t.tsconfigPaths){let r=toSnapshotPathForPlan(t,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(t){let n=extractTsConfigExtendsSpecifiers(await readFile(t,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:t,extendsSpecifier:r}).some(t=>existsSync(t))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${t}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,join,relative,resolve,sep}from"node:path";import{
|
|
1
|
+
import{existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{lstat,readlink,realpath}from"node:fs/promises";import{parseTsConfigObject,readTextFileIfExists,resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";const DEV_RUNTIME_SOURCE_DIRECTORY=`source`,SOURCE_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WORKSPACE_METADATA_FILE_NAMES=[`package.json`,`pnpm-workspace.yaml`,`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`,`.npmrc`],PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`];var DevelopmentRuntimeSourceSnapshotError=class extends Error{constructor(e){super(e),this.name=`DevelopmentRuntimeSourceSnapshotError`}};async function createDevelopmentSourceSnapshotPlan(e){let t=resolve(e.appRoot),r=resolve(e.snapshotRoot),a=resolveDevelopmentSourceRoot(t),o=join(r,DEV_RUNTIME_SOURCE_DIRECTORY),s={appRoot:t,copyFiles:new Set,copyRoots:new Set,localRootsToProcess:[t],processedLocalRoots:new Set,snapshotRoot:r,snapshotSourceRoot:o,sourceRoot:a,symlinksByLinkPath:new Map,tsconfigPaths:new Set};for(addWorkspaceMetadataFiles(s);s.localRootsToProcess.length>0;){let e=s.localRootsToProcess.shift();if(e===void 0)continue;let t=resolve(e);s.processedLocalRoots.has(t)||!isAuthoredSourcePath(t,a)||(s.processedLocalRoots.add(t),s.copyRoots.add(t),await addTsConfigDependenciesForRoot(s,t),await addDependencySymlinksForRoot(s,t))}let c=normalizeCopyRoots([...s.copyRoots]),l=[...s.copyFiles].filter(e=>isPathInsideOrEqual(e,a)).sort((e,t)=>e.localeCompare(t)),u=[...s.tsconfigPaths].filter(e=>isPathInsideOrEqual(e,a)).sort((e,t)=>e.localeCompare(t)),d=[...s.symlinksByLinkPath.values()].sort((e,t)=>e.linkPath.localeCompare(t.linkPath)),f=createWatchPaths({appRoot:t,copyFiles:l,copyRoots:c,sourceRoot:a,symlinks:d,tsconfigPaths:u});return{appRoot:t,copyFiles:l,copyRoots:c,runtimeAppRoot:toSnapshotPath({sourcePath:t,sourceRoot:a,snapshotSourceRoot:o}),snapshotRoot:r,snapshotSourceRoot:o,sourceRoot:a,symlinks:d,tsconfigPaths:u,watchPaths:f}}async function resolveDevelopmentSourceSnapshotWatchPaths(e){return[...(await createDevelopmentSourceSnapshotPlan({appRoot:e,snapshotRoot:join(resolve(e),`.eve`,`dev-runtime`,`__watch-plan__`)})).watchPaths]}function toDevelopmentSourceSnapshotPath(e){return toSnapshotPath(e)}function resolveDevelopmentSourceRoot(r){let a=resolve(r);for(;;){if(SOURCE_ROOT_MARKER_NAMES.some(t=>existsSync(join(a,t))))return a;let o=dirname(a);if(o===a)return resolve(r);a=o}}function addWorkspaceMetadataFiles(t){for(let r of WORKSPACE_METADATA_FILE_NAMES){let i=join(t.sourceRoot,r);existsSync(i)&&t.copyFiles.add(i)}}async function addTsConfigDependenciesForRoot(e,t){let n=await resolveTsConfigDependencyPaths(t);for(let t of n)if(isPathInsideOrEqual(t,e.sourceRoot)){e.tsconfigPaths.add(t),e.copyFiles.add(t);for(let n of await resolveLocalTsConfigPathTargetRoots({configPath:t,sourceRoot:e.sourceRoot}))enqueueLocalRoot(e,n)}}async function addDependencySymlinksForRoot(e,t){let n=await readPackageDependencyNames(t);for(let r of n)for(let n of[t,e.sourceRoot])await addDependencySymlink(e,joinNodeModulesPackagePath(n,r))}async function addDependencySymlink(t,n){let r;try{r=await lstat(n)}catch{return}if(!r.isSymbolicLink())return;let a=await resolveSymlinkTargetPathCandidates(n),s=a.find(e=>isAuthoredSourcePath(e,t.sourceRoot));if(s!==void 0){await addLocalDependencySymlink({linkPath:n,state:t,targetPath:s});return}let c=a.find(t=>existsSync(t));c!==void 0&&t.symlinksByLinkPath.set(resolve(n),{linkPath:resolve(n),targetKind:`external`,targetPath:c})}async function addLocalDependencySymlink(e){let t=await resolveNearestPackageRoot(e.targetPath,e.state.sourceRoot);if(t===void 0||!isAuthoredSourcePath(t,e.state.sourceRoot))return;let{state:n}=e;enqueueLocalRoot(n,t),n.symlinksByLinkPath.set(resolve(e.linkPath),{linkPath:resolve(e.linkPath),targetKind:`local`,targetPath:t})}async function resolveSymlinkTargetPathCandidates(e){let n=new Set;try{let r=await readlink(e);n.add(resolve(dirname(e),r))}catch{}try{n.add(await realpath(e))}catch{}return[...n]}function enqueueLocalRoot(e,t){let n=resolve(t);e.processedLocalRoots.has(n)||e.localRootsToProcess.includes(n)||!isAuthoredSourcePath(n,e.sourceRoot)||e.localRootsToProcess.push(n)}async function readPackageDependencyNames(e){let t=await readTextFileIfExists(join(e,`package.json`));if(t===void 0)return[];let r;try{r=JSON.parse(t)}catch{return[]}if(!isObjectRecord(r))return[];let i=new Set;for(let e of PACKAGE_DEPENDENCY_FIELDS){let t=r[e];if(isObjectRecord(t))for(let e of Object.keys(t))i.add(e)}return[...i].sort((e,t)=>e.localeCompare(t))}async function resolveLocalTsConfigPathTargetRoots(e){let n=await readTextFileIfExists(e.configPath);if(n===void 0)return[];let r=parseTsConfigObject(n),a=isObjectRecord(r?.compilerOptions)?r.compilerOptions:void 0,o=isObjectRecord(a?.paths)?a.paths:void 0;if(a===void 0||o===void 0)return[];let s=typeof a.baseUrl==`string`?resolve(dirname(e.configPath),a.baseUrl):dirname(e.configPath),c=new Set;for(let t of Object.values(o))if(Array.isArray(t))for(let n of t){if(typeof n!=`string`||n.length===0)continue;let t=await resolveLocalTsConfigPathTargetRoot({baseDirectory:s,sourceRoot:e.sourceRoot,target:n});t!==void 0&&c.add(t)}return[...c].sort((e,t)=>e.localeCompare(t))}async function resolveLocalTsConfigPathTargetRoot(e){let t=e.target.includes(`*`),n=t?e.target.slice(0,e.target.indexOf(`*`)):e.target;if(n.length===0||n===`.`||n===`./`)return;let r=resolve(e.baseDirectory,n);if(!isAuthoredSourcePath(r,e.sourceRoot))return;let a=await resolveExistingPathOrAncestor({path:r,stopDirectory:e.sourceRoot});if(a===void 0)return;let o=await resolveNearestPackageRoot(a,e.sourceRoot);if(o!==void 0&&o!==e.sourceRoot)return o;if(!t)return a===e.sourceRoot?void 0:a}async function resolveExistingPathOrAncestor(n){let r=resolve(n.path);for(;isAuthoredSourcePath(r,n.stopDirectory);){if(existsSync(r))return r;let n=dirname(r);if(n===r)return;r=n}}async function resolveNearestPackageRoot(r,a){let s=resolve(r);try{(await lstat(s)).isDirectory()||(s=dirname(s))}catch{s=dirname(s)}for(;isAuthoredSourcePath(s,a);){if(existsSync(join(s,`package.json`)))return s;let r=dirname(s);if(r===s)return;s=r}}function normalizeCopyRoots(e){let t=[...new Set(e.map(e=>resolve(e)))].sort((e,t)=>{let n=e.length-t.length;return n===0?e.localeCompare(t):n}),n=[];for(let e of t)n.some(t=>isPathInsideOrEqual(e,t))||n.push(e);return n.sort((e,t)=>e.localeCompare(t))}function createWatchPaths(t){let r=new Set([join(t.appRoot,`package.json`),...t.copyFiles,...t.tsconfigPaths]);for(let e of t.copyRoots)e!==t.appRoot&&r.add(e);for(let e of t.symlinks)e.targetKind===`local`&&e.targetPath!==t.appRoot&&r.add(e.targetPath);if(t.sourceRoot!==t.appRoot)for(let i of WORKSPACE_METADATA_FILE_NAMES){let a=join(t.sourceRoot,i);existsSync(a)&&r.add(a)}return[...r].sort((e,t)=>e.localeCompare(t))}function joinNodeModulesPackagePath(e,t){return join(e,`node_modules`,...t.split(`/`))}function toSnapshotPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.sourceRoot))throw new DevelopmentRuntimeSourceSnapshotError(`Cannot map source path "${e.sourcePath}" into a development runtime snapshot because it is outside source root "${e.sourceRoot}".`);return join(e.snapshotSourceRoot,relative(e.sourceRoot,e.sourcePath))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAuthoredSourcePath(e,t){return isPathInsideOrEqual(e,t)?!relative(t,e).split(/[\\/]/).includes(`node_modules`):!1}function isObjectRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{DEV_RUNTIME_SOURCE_DIRECTORY,DevelopmentRuntimeSourceSnapshotError,createDevelopmentSourceSnapshotPlan,resolveDevelopmentSourceSnapshotWatchPaths,toDevelopmentSourceSnapshotPath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.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{getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.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{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{computeChannelRouteRegistrations,syncChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";import{watch}from"#compiled/chokidar/index.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{registerDevelopmentRebuildHandle}from"#internal/nitro/host/dev-rebuild-registry.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,d=await resolveAuthoredWatchPaths(t),f=createWatchPathMap(d),p=watch(d,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),m=waitForWatcherReady(p),flush=async()=>{n||(i!==void 0&&(clearTimeout(i),i=void 0),r=r.then(async()=>{if(n)return;let r=[...s.values()];if(r.length===0)return;let i=[...c];s.clear(),c.clear();let o=t,l=hasSandboxRelatedChange(o.compileResult.project.agentRoot,i),u=hasDevelopmentEnvironmentFileChange(o.appRoot,i);console.log(formatChangeDetectedLogLine(o.appRoot,r));try{u&&loadDevelopmentEnvironmentFiles(o.appRoot);let n=await prepareApplicationHost(o.appRoot,{dev:e.nitro.options.dev===!0}),r=createNitroArtifactsConfig({appRoot:n.appRoot,dev:e.nitro.options.dev===!0});l&&startDevelopmentSandboxPrewarmInBackground({appRoot:n.appRoot,compiledArtifactsSource:resolveNitroCompiledArtifactsSource(r),log:e=>console.log(e)});let i=syncChannelVirtualHandlers(e.nitro,{artifactsConfig:r,next:computeChannelRouteRegistrations(n),previous:computeChannelRouteRegistrations(o)});clearCompiledRuntimeAgentBundleCache(),t=n,i||u?(console.log(STRUCTURAL_RELOAD_LOG_LINE),await e.nitro.hooks.callHook(`rollup:reload`)):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),f=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(n),previousWatchPathsByKey:f,watcher:p})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},h=registerDevelopmentRebuildHandle(t.appRoot,{flush});return p.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 m,o=!0,{async close(){n=!0,h(),i!==void 0&&(clearTimeout(i),i=void 0),await p.close(),await r},flush}}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 +1 @@
|
|
|
1
|
-
import{isAbsolute,relative,sep}from"node:path";const AUTHORED_ARTIFACTS_UPDATED_LOG_LINE=`[eve:dev] authored artifacts updated.`,STRUCTURAL_RELOAD_LOG_LINE=`[eve:dev] structural change detected, reloading Nitro worker...`;function formatChangeDetectedLogLine(e,t){return`[eve:dev] change detected (${formatChangeEventList(e,t)}), rebuilding authored artifacts...`}const CHANGE_DETECTED_PATTERN=/^\[eve:dev\] change detected \(\d+ events?: (.+)\), rebuilding authored artifacts\.\.\.$/u,MORE_EVENTS_PATTERN=/^\+(\d+) more$/u;function parseDevRebuildLogLine(e){if(e===`[eve:dev] authored artifacts updated.`)return{kind:`rebuilt`};if(e===`[eve:dev] structural change detected, reloading Nitro worker...`)return{kind:`reloading`};let t=
|
|
1
|
+
import{isAbsolute,relative,sep}from"node:path";const AUTHORED_ARTIFACTS_UPDATED_LOG_LINE=`[eve:dev] authored artifacts updated.`,STRUCTURAL_RELOAD_LOG_LINE=`[eve:dev] structural change detected, reloading Nitro worker...`;function formatChangeDetectedLogLine(e,t){return`[eve:dev] change detected (${formatChangeEventList(e,t)}), rebuilding authored artifacts...`}const CHANGE_DETECTED_PATTERN=/^\[eve:dev\] change detected \(\d+ events?: (.+)\), rebuilding authored artifacts\.\.\.$/u,MORE_EVENTS_PATTERN=/^\+(\d+) more$/u,REBUILD_FAILED_PATTERN=/^\[eve:dev\] rebuild (?:failed|queue error): (.+)$/u;function parseDevRebuildLogLine(e){if(e===`[eve:dev] authored artifacts updated.`)return{kind:`rebuilt`};if(e===`[eve:dev] structural change detected, reloading Nitro worker...`)return{kind:`reloading`};let t=REBUILD_FAILED_PATTERN.exec(e);if(t!==null)return{kind:`failed`,message:t[1]};let n=CHANGE_DETECTED_PATTERN.exec(e);if(n===null)return;let r=[],i=0;for(let e of n[1].split(`, `)){let t=MORE_EVENTS_PATTERN.exec(e);if(t!==null){i+=Number(t[1]);continue}let n=e.indexOf(` `);if(n===-1)return;r.push({event:e.slice(0,n),path:e.slice(n+1)})}if(r.length!==0)return{kind:`rebuilding`,events:r,more:i}}function formatChangeEventList(e,t){let n=`${t.length} event${t.length===1?``:`s`}`,r=t.slice(0,6).map(t=>`${t.event} ${formatChangeEventPath(e,t.path)}`),i=t.length-r.length;return i>0&&r.push(`+${i} more`),`${n}: ${r.join(`, `)}`}function formatChangeEventPath(r,i){let a=relative(r,i),o=a===`..`||a.startsWith(`..${sep}`)||isAbsolute(a);return(a.length>0&&!o?a:i).replaceAll(`\\`,`/`)}export{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine,parseDevRebuildLogLine};
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import type { DevelopmentServerHandle } from "#internal/nitro/host/types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Rewrites a server URL whose hostname is a wildcard listen address into a
|
|
4
|
-
* loopback URL
|
|
5
|
-
* Returns the input unchanged when the hostname is already routable.
|
|
4
|
+
* loopback URL on the same address family.
|
|
6
5
|
*/
|
|
7
6
|
export declare function normalizeDevelopmentServerClientUrl(serverUrl: string): string;
|
|
8
7
|
/**
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{pruneDevelopmentRuntimeArtifactsSnapshotsInBackground}from"#internal/nitro/dev-runtime-artifacts.js";import{build,createDevServer,prepare}from"nitro/builder";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`,
|
|
1
|
+
import{join}from"node:path";import{mkdir,readFile,rm,writeFile}from"node:fs/promises";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{pruneDevelopmentRuntimeArtifactsSnapshotsInBackground}from"#internal/nitro/dev-runtime-artifacts.js";import{build,createDevServer,prepare}from"nitro/builder";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`,DEFAULT_DEVELOPMENT_SERVER_HOST=`127.0.0.1`,IPV6_WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return IPV6_WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`[::1]`,t.toString()):t.hostname===`0.0.0.0`?(t.hostname=DEFAULT_DEVELOPMENT_SERVER_HOST,t.toString()):e}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function resolveDevelopmentProcessIdPath(t){return join(t,`.eve`,`dev-process.pid`)}function parseProcessId(e){let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:void 0}function isProcessRunning(e){try{return process.kill(e,0),!0}catch(e){return e instanceof Error&&`code`in e&&e.code===`EPERM`}}function formatKillCommand(e){return process.platform===`win32`?`taskkill /PID ${e}`:`kill ${e}`}async function readActiveDevelopmentProcessId(e){let t;try{t=parseProcessId(await readFile(resolveDevelopmentProcessIdPath(e),`utf8`))}catch{return}if(!(t===void 0||!isProcessRunning(t)))return t}async function writeDevelopmentProcessId(a){let o=resolveDevelopmentProcessIdPath(a),s=await readActiveDevelopmentProcessId(a);if(s!==void 0)throw Error([`A dev server is already running for this Eve agent (pid ${s}).`,`To stop it, run: ${formatKillCommand(s)}`].join(`
|
|
2
|
+
`));return await mkdir(join(a,`.eve`),{recursive:!0}),await writeFile(o,`${process.pid}\n`,`utf8`),async()=>{let e;try{e=parseProcessId(await readFile(o,`utf8`))}catch{return}e===process.pid&&await rm(o,{force:!0})}}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function installWorkflowLocalQueueEnvironment(e){let t=process.env[WORKFLOW_LOCAL_BASE_URL_ENV],n=process.env[PORT_ENV],r=new URL(normalizeDevelopmentServerClientUrl(e));return process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=r.origin,r.port&&(process.env[PORT_ENV]=r.port),()=>{t===void 0?delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV]:process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=t,n===void 0?delete process.env[PORT_ENV]:process.env[PORT_ENV]=n}}function attachTemporarySocketErrorHandler(e){let onSocketError=()=>{};return e.once(`error`,onSocketError),()=>{e.off(`error`,onSocketError)}}function shouldProxyDevelopmentServerWebSocketUpgrades(e){return e.options.features.websocket===!0||e.options.experimental.websocket===!0}function guardDevelopmentServerWebSocketUpgrades(e,t){let n=t.upgrade.bind(t),r=shouldProxyDevelopmentServerWebSocketUpgrades(e);t.upgrade=async(e,t,i)=>{if(!r){t.destroyed||t.destroy();return}let a=attachTemporarySocketErrorHandler(t);try{await n(e,t,i)}catch{t.destroyed||t.destroy()}finally{a()}}}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startDevelopmentServer(e,t={}){process.env[EVE_DEV_ENV_FLAG]??=`1`,loadDevelopmentEnvironmentFiles(e);let n=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],r=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=r;let i,u,d,f,p;try{let o=await prepareApplicationHost(e,{dev:!0});p=await writeDevelopmentProcessId(o.appRoot),pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(o.appRoot);let s=resolveNitroCompiledArtifactsSource(createNitroArtifactsConfig({appRoot:o.appRoot,dev:!0}));startDevelopmentSandboxPrewarmInBackground({appRoot:o.appRoot,compiledArtifactsSource:s}),pruneLocalSandboxTemplatesInBackground(o.appRoot),i=await createApplicationNitro(o,!0),u=createDevServer(i),guardDevelopmentServerWebSocketUpgrades(i,u);let c=t.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,l=t.port??readEnvironmentPort(),m=l??i.options.devServer.port,h=await listenForDevelopmentServer({devServer:u,host:c,port:m,retryOnAddressInUse:l===void 0});if(!h.url)throw Error(`Nitro dev server did not expose a URL.`);d=installWorkflowLocalQueueEnvironment(h.url),await prepare(i),await build(i);let{startAuthoredSourceWatcher:g}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);f=await g({nitro:i,preparedHost:o});let _=d;if(_===void 0)throw Error(`Workflow local queue environment was not initialized.`);let v=f,y=u,b=i;return{async close(){try{await v.close(),await y.close(),await b.close(),await stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(r),devRunId:r,log:e=>console.warn(`[eve:dev] ${e}`)})}finally{clearInitializedDevelopmentSandboxBackendNames(r),await p?.(),_(),restoreDevelopmentSandboxRunId(n)}},url:normalizeDevelopmentServerClientUrl(h.url)}}catch(e){throw await f?.close().catch(()=>{}),d?.(),await u?.close().catch(()=>{}),await i?.close().catch(()=>{}),await stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(r),devRunId:r,log:e=>console.warn(`[eve:dev] ${e}`)}).catch(()=>{}),clearInitializedDevelopmentSandboxBackendNames(r),await p?.().catch(()=>{}),restoreDevelopmentSandboxRunId(n),e}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{normalizeDevelopmentServerClientUrl,startDevelopmentServer};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";import{
|
|
2
|
-
`))}async function terminate(e){e.exitCode!==null||e.killed||(e.kill(`SIGTERM`),await Promise.race([once(e,`exit`),setTimeout(5e3).then(()=>`timeout`)])===`timeout`&&e.exitCode===null&&(e.kill(`SIGKILL`),await once(e,`exit`)),e.stdout?.destroy(),e.stderr?.destroy())}function once(e,t){return new Promise(n=>{e.once(t,()=>n())})}async function startProductionServer(e,
|
|
1
|
+
import{EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{spawn}from"node:child_process";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{setTimeout}from"node:timers/promises";import{prewarmBuiltAppSandboxes}from"#execution/sandbox/prewarm.js";import{createServer}from"node:net";const HEALTH_TIMEOUT_MS=6e4,LOCAL_SERVER_URL_PATTERN=/https?:\/\/(?:\[[^\]\s]+\]|[^\s/:[\]]+)(?::\d+)?/,WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`,`0.0.0.0`]);function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveOutputServerEntry(e){return join(resolve(e),`.output`,`server`,`index.mjs`)}function readEnvironmentPort(){let e=process.env.PORT;if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>65535)throw Error(`Invalid PORT environment variable "${e}". Expected an integer between 0 and 65535.`);return t}function normalizeServerClientUrl(e){let t=new URL(e);return WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)&&(t.hostname=`127.0.0.1`),t.toString()}function formatClientHost(e){return WILDCARD_LISTEN_HOSTNAMES.has(e)?`127.0.0.1`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function createKnownPortUrl(e){return`http://${formatClientHost(e.host)}:${String(e.port)}/`}async function resolveListenPort(e){if(e.port!==0)return e.port;let t=createServer();return await new Promise((n,r)=>{t.once(`error`,r),t.listen(0,e.host,()=>{let e=t.address();t.close(t=>{if(t){r(t);return}if(e===null||typeof e==`string`){r(Error(`Failed to resolve an available port for eve start.`));return}n(e.port)})})})}function parseServerUrlFromOutput(e){let t=LOCAL_SERVER_URL_PATTERN.exec(e);if(t!==null)return normalizeServerClientUrl(t[0])}async function waitForHealth(t){let{child:n,url:r}=t,i=new URL(EVE_HEALTH_ROUTE_PATH,r).toString(),a=Date.now()+HEALTH_TIMEOUT_MS;for(;Date.now()<a;){let e=t.getStartError();if(e!==void 0)throw e;if(n.exitCode!==null||n.signalCode!==null)throw Error(`Built server process exited (code=${String(n.exitCode)}, signal=${String(n.signalCode)}) before becoming healthy.`);try{if((await fetch(i,{signal:AbortSignal.timeout(2e3)})).ok)return new URL(r).toString()}catch(e){if(isAddressInUseError(e))throw e}await setTimeout(250)}throw Error(`Built server did not become healthy within ${HEALTH_TIMEOUT_MS/1e3}s at ${i}.`)}async function waitForReady(e){let t=Date.now()+HEALTH_TIMEOUT_MS;for(;Date.now()<t;){let t=e.getStartError();if(t!==void 0)throw t;let n=parseServerUrlFromOutput(e.getOutput())??e.knownUrl;if(n!==void 0)return await waitForHealth({child:e.child,getStartError:e.getStartError,url:n});if(e.child.exitCode!==null||e.child.signalCode!==null)throw Error(`Built server process exited (code=${String(e.child.exitCode)}, signal=${String(e.child.signalCode)}) before printing its URL.`);await setTimeout(250)}throw Error([`Built server did not become ready within ${HEALTH_TIMEOUT_MS/1e3}s.`,`Output:`,e.getOutput()].join(`
|
|
2
|
+
`))}async function terminate(e){e.exitCode!==null||e.killed||(e.kill(`SIGTERM`),await Promise.race([once(e,`exit`),setTimeout(5e3).then(()=>`timeout`)])===`timeout`&&e.exitCode===null&&(e.kill(`SIGKILL`),await once(e,`exit`)),e.stdout?.destroy(),e.stderr?.destroy())}function once(e,t){return new Promise(n=>{e.once(t,()=>n())})}async function startProductionServer(e,n={}){let o=resolve(e),s=resolveOutputServerEntry(o);if(!existsSync(s))throw Error(`Missing Eve build output at ${s}. Run "eve build" before "eve start".`);loadDevelopmentEnvironmentFiles(o),await prewarmBuiltAppSandboxes({appRoot:o,log:e=>console.log(e)});let c=n.host??`0.0.0.0`,l=await resolveListenPort({host:c,port:n.port??readEnvironmentPort()??3e3}),u=createKnownPortUrl({host:c,port:l}),d=``,f=!1,p,m=spawn(process.execPath,[s],{cwd:o,env:{...process.env,HOST:c,NITRO_HOST:c,NITRO_PORT:String(l),PORT:String(l)},stdio:[`ignore`,`pipe`,`pipe`]});m.stdout?.on(`data`,e=>{d+=e.toString(`utf8`),process.stdout.write(e)}),m.stderr?.on(`data`,e=>{d+=e.toString(`utf8`),process.stderr.write(e)});let h=new Promise((e,t)=>{m.once(`error`,e=>{p=e,t(e)}),m.once(`exit`,(n,r)=>{if(f||n===0){e();return}t(Error([`Built server process exited unexpectedly (code=${String(n)}, signal=${String(r)}).`,d].join(`
|
|
3
3
|
`)))})});h.catch(()=>void 0);try{return{async close(){f=!0,await terminate(m)},url:await waitForReady({child:m,getStartError:()=>p,getOutput:()=>d,knownUrl:u}),async wait(){await h}}}catch(e){throw f=!0,await terminate(m),isRecord(e)&&e.name===`AbortError`?Error(`Timed out waiting for built Eve server to respond.`,{cause:e}):e}}export{startProductionServer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync}from"node:fs";import{extname,join}from"node:path";function resolvePnpmInvocation(n){let r=process.env.PNPM_HOME;if(r!==void 0){let t=join(r,process.platform===`win32`?`pnpm.CMD`:`pnpm`);if(existsSync(t))return{args:n,command:t,shell:process.platform===`win32`}}let i=process.env.npm_execpath;if(i!==void 0&&i.toLowerCase().includes(`pnpm`)){let e=extname(i).toLowerCase();return e===`.cjs`||e===`.js`?{args:[i,...n],command:process.execPath}:{args:n,command:i,shell:process.platform===`win32`}}return{args:n,command:`pnpm`}}export{resolvePnpmInvocation};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{
|
|
1
|
+
import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,readdir,rename,writeFile}from"node:fs/promises";import{EVE_WORKFLOW_QUEUE_NAMESPACE}from"#internal/workflow/queue-namespace.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_INPUT_EXTENSIONS=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}if(!r.isFile())continue;let n=r.name.match(/\.[^.]+$/)?.[0];n!==void 0&&WORKFLOW_INPUT_EXTENSIONS.has(n)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(!(e!==`workflow`&&!e.startsWith(`workflow/`)))return resolveWorkflowModulePath(e)}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):resolveFirstExistingPath([join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]);let a=n.match(/^#(.+)\.js$/)?.[1];if(a!==void 0)return resolveFirstExistingPath([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[join(e,`src`,`${a}${t}`),join(e,`dist`,`src`,`${a}${t}`)]))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
|
|
2
2
|
`),o=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:isWorkflowStepExternalPackage,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(a),createWorkflowPseudoPackagePlugin(),createWorkflowRuntimeAliasPlugin(),createEvePackageImportsPlugin(e.workingDir),createWorkflowTransformPlugin({manifest:i,mode:`step`,projectRoot:e.projectRoot,sideEffectFiles:[...t,...r],workingDir:e.workingDir})],resolve:{conditionNames:[`eve-source`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:`inline`}}),`step registrations bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,o.code)}function isWorkflowStepExternalPackage(e){return WORKFLOW_STEP_EXTERNAL_PACKAGES.some(t=>e===t||e.startsWith(`${t}/`))}function createWorkflowNodeBuiltinGuardPlugin(){return{name:`eve-workflow-node-builtins`,resolveId(e,t){let n=e.startsWith(`node:`)?e.slice(5):e;if(!NODE_BUILTIN_MODULES.has(e)&&!NODE_BUILTIN_MODULES.has(n))return;let r=t?` (imported by "${t}")`:``;throw Error(`Workflow bundle cannot import Node.js builtin "${e}"${r}. Move Node.js APIs behind a "use step" function, or keep the importing module out of the workflow driver body (only reachable through a "use step").`)}}}async function bundleFinalWorkflowOutput(e){let t=`// biome-ignore-all lint: generated file
|
|
3
3
|
/* eslint-disable */
|
|
4
4
|
import { workflowEntrypoint } from 'workflow/runtime';
|
|
@@ -6,4 +6,4 @@ import { workflowEntrypoint } from 'workflow/runtime';
|
|
|
6
6
|
const workflowCode = \`${(e.code.endsWith(`
|
|
7
7
|
`)?e.code:`${e.code}\n`).replace(/[\\`$]/g,`\\$&`)}\`;
|
|
8
8
|
|
|
9
|
-
export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(EVE_WORKFLOW_QUEUE_NAMESPACE)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,t);return}let n=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(t)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,n.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0});let
|
|
9
|
+
export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(EVE_WORKFLOW_QUEUE_NAMESPACE)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,t);return}let n=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(t)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,n.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await writeFile(n,t),await rename(n,e)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=relative(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}async function atomicWriteFile(e,t){let n=`${e}.tmp-${process.pid}-${Date.now().toString(36)}`;await writeFile(n,t),await rename(n,e)}export{WORKFLOW_VIRTUAL_ENTRY_ID,atomicWriteFile,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";let transformCounter=0;async function transformDynamicToolExecute(e,t){if(!t.includes(`defineDynamic`)||!t.includes(`events`)||!t.includes(`execute`))return null;let n=findDynamicToolHandlers(t,await parseSource(e,t));return n.every(e=>e.executes.length===0)?null:applyTransform(t,n)}async function parseSource(t,n){return await parseWithNitroRolldownAst(t,n)}function findDynamicToolHandlers(e,t){let n=[];return walkNode(t,t=>{if(t.type===`CallExpression`&&t.callee?.type===`Identifier`&&t.callee.name===`defineDynamic`&&t.arguments?.length===1){let r=t.arguments[0];if(r.type===`ObjectExpression`){let t=findProperty(r,`events`);t?.value&&t.value.type===`ObjectExpression`&&collectHandlers(e,t.value,n)}return!1}return!0}),n}function collectHandlers(e,t,n){for(let r of t.properties??[]){if(r.type!==`Property`)continue;let t=r.value;if(!t||t.type!==`ArrowFunctionExpression`&&t.type!==`FunctionExpression`)continue;let i=t.body;if(!i)continue;let a=findBlockBodyStart(i);if(a===null)continue;let o=extractParamNames(t),s=collectScopeVarDeclarations(i),c=findExecuteFunctions(e,i);c.length>0&&n.push({handlerNode:t,bodyStart:a,scopeVars:s,paramNames:o,executes:c})}}function findBlockBodyStart(e){return e.type===`BlockStatement`&&e.start!==void 0?e.start:typeof e.body==`object`&&!Array.isArray(e.body)&&e.body?.type===`BlockStatement`&&e.body.start!==void 0?e.body.start:null}function extractParamNames(e){let t=[];for(let n of e.params??[])n.type===`Identifier`&&n.name&&t.push(n.name);return t}function collectScopeVarDeclarations(e){let t=[];return collectVarsRecursive(e,t),t}function collectVarsRecursive(e,t){if(!e||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`||e.type===`FunctionDeclaration`)return;if(e.type===`VariableDeclaration`)for(let n of e.declarations??[])collectDeclaredNames(n,t);e.type===`ForStatement`&&e.init&&collectVarsRecursive(e.init,t);let n=e;if((e.type===`ForInStatement`||e.type===`ForOfStatement`)&&e.left&&collectVarsRecursive(e.left,t),Array.isArray(e.body))for(let n of e.body)collectVarsRecursive(n,t);else e.body&&typeof e.body==`object`&&`type`in e.body&&collectVarsRecursive(e.body,t);if(e.declarations)for(let n of e.declarations)collectVarsRecursive(n,t);if(e.expression&&collectVarsRecursive(e.expression,t),Array.isArray(n.consequent))for(let e of n.consequent)collectVarsRecursive(e,t);else n.consequent&&collectVarsRecursive(n.consequent,t);if(n.alternate&&collectVarsRecursive(n.alternate,t),n.block&&collectVarsRecursive(n.block,t),n.handler&&collectVarsRecursive(n.handler,t),n.finalizer&&collectVarsRecursive(n.finalizer,t),n.cases&&Array.isArray(n.cases))for(let e of n.cases)collectVarsRecursive(e,t)}function collectDeclaredNames(e,t){e.type===`VariableDeclarator`&&collectPatternNames(e.id,t)}function collectPatternNames(e,t){if(e){if(e.type===`Identifier`&&e.name){t.push(e.name);return}if(e.type===`ObjectPattern`)for(let n of e.properties??[])n.type===`Property`?collectPatternNames(n.value,t):n.type===`RestElement`&&collectPatternNames(n.argument,t);if(e.type===`ArrayPattern`)for(let n of e.elements??[])n&&collectPatternNames(n,t)}}function findExecuteFunctions(e,t){let n=[];return walkForExecuteProps(e,t,n,[]),n}function walkForExecuteProps(e,n,r,i){if(!n)return;if(n.type===`FunctionExpression`||n.type===`ArrowFunctionExpression`||n.type===`FunctionDeclaration`){let t=extractParamNames(n),a=n.body;if(!a)return;let o=collectScopeVarDeclarations(a),s=[...i,{params:t,vars:o}];a.type,walkForExecuteProps(e,a,r,s);return}if(n.type===`CallExpression`&&n.callee?.type===`Identifier`&&n.callee.name===`defineTool`&&n.arguments?.length===1&&n.arguments[0].type===`ObjectExpression`){let a=n.arguments[0];for(let n of a.properties??[])if(n.type===`Property`&&!n.computed&&n.key?.type===`Identifier`&&n.key.name===`execute`&&n.start!==void 0&&n.end!==void 0){let a=n.value;if(!a||a.start===void 0||a.end===void 0)continue;let o=a.type===`FunctionExpression`||a.type===`ArrowFunctionExpression`,s=n.method===!0;if(o||s){let o=extractFnParams(e,a),s=extractFnBody(e,a),c=a.async===!0;r.push({propStart:n.start,propEnd:n.end,fnSource:e.slice(a.start,a.end),isAsync:c,params:o,body:s,hoistedName:`__eve_dynamic_exec_${transformCounter++}`,nestedScopes:i})}}return}let walk=t=>walkForExecuteProps(e,t,r,i);if(Array.isArray(n.body))for(let e of n.body)walk(e);else n.body&&typeof n.body==`object`&&`type`in n.body&&walk(n.body);if(n.properties)for(let e of n.properties)e.value&&typeof e.value==`object`&&`type`in e.value&&walk(e.value);if(n.callee&&walk(n.callee),n.arguments)for(let e of n.arguments)walk(e);if(n.expression&&walk(n.expression),n.argument&&walk(n.argument),n.init&&walk(n.init),n.left&&walk(n.left),n.right&&walk(n.right),n.declarations)for(let e of n.declarations)walk(e);let a=n;if(Array.isArray(a.consequent))for(let e of a.consequent)walk(e);else a.consequent&&walk(a.consequent);if(a.alternate&&walk(a.alternate),a.block&&walk(a.block),a.handler&&walk(a.handler),a.finalizer&&walk(a.finalizer),a.cases&&Array.isArray(a.cases))for(let e of a.cases)walk(e)}function extractFnParams(e,t){if(!t.params||t.params.length===0)return``;let n=t.params[0],r=t.params[t.params.length-1];return n.start===void 0||r.end===void 0?``:e.slice(n.start,r.end)}function extractFnBody(e,t){let n=t.body;if(!n||n.start===void 0||n.end===void 0)return`{}`;let r=e.slice(n.start,n.end);return t.type===`ArrowFunctionExpression`&&n.type!==`BlockStatement`?`{ return ${r}; }`:r}function applyTransform(e,t){let n=[],r=[],i=[],a=[];for(let e of t)for(let t of e.executes){let o=[...e.paramNames,...e.scopeVars,...t.nestedScopes.flatMap(e=>[...e.params,...e.vars])],s=new Set,c=[];for(let e=o.length-1;e>=0;e--)s.has(o[e])||(s.add(o[e]),c.unshift(o[e]));let l=t.body,u=extractExecuteParamNames(t.params),d=c.filter(e=>!u.has(e)&&RegExp(`\\b${escapeForRegex(e)}\\b`).test(l)),f=d.length>0?`{ ${d.join(`, `)} }`:`{}`,p=t.isAsync?`async `:``,m=d.length>0?`const ${f} = __vars;\n `:``,h=t.params,g=h?`__vars, ${h}`:`__vars`,_=t.body.slice(1,-1).trim(),v=`eve:dynamic-tool//${t.hoistedName}`;r.push(`${p}function ${t.hoistedName}(${g}) {\n ${m}${_}\n}`),i.push(`${t.hoistedName}.stepId = ${JSON.stringify(v)};`),i.push(`__eveStepRegistry.set(${JSON.stringify(v)}, ${t.hoistedName});`),a.push(t.hoistedName);let y=h||``,b=h?splitParamsTopLevel(h).map(e=>extractParamBindingName(e)).join(`, `):``,x=b?`${f}, ${b}`:f,S=t.isAsync?`async `:``,C=t.isAsync?`await `:``;n.push({start:t.propStart,end:t.propEnd,text:[`execute: ${S}(${y}) => ${C}${t.hoistedName}(${x})`,`__executeStepFn: ${t.hoistedName}`,`__closureVars: ${f}`].join(`,
|
|
2
2
|
`)})}let o=[...n].sort((e,t)=>t.start-e.start),s=e;for(let e of o)s=s.slice(0,e.start)+e.text+s.slice(e.end);s=`${[`var __eveStepRegistrySym = Symbol.for("@workflow/core//registeredSteps");`,`if (!globalThis[__eveStepRegistrySym]) globalThis[__eveStepRegistrySym] = new Map();`,`var __eveStepRegistry = globalThis[__eveStepRegistrySym];`].join(`
|
|
3
3
|
`)}\n${s}`;let c=[...r,...i];return c.length>0&&(s=`${s}\n\n${c.join(`
|
|
4
4
|
`)}\n`),{code:s}}function walkNode(e,t){if(t(e)){if(Array.isArray(e.body))for(let n of e.body)walkNode(n,t);else e.body&&typeof e.body==`object`&&`type`in e.body&&walkNode(e.body,t);if(e.declarations)for(let n of e.declarations)walkNode(n,t);if(e.init&&walkNode(e.init,t),e.expression&&walkNode(e.expression,t),e.declaration&&walkNode(e.declaration,t),e.argument&&walkNode(e.argument,t),e.arguments)for(let n of e.arguments)walkNode(n,t);if(e.properties)for(let n of e.properties)walkNode(n,t),n.value&&typeof n.value==`object`&&`type`in n.value&&walkNode(n.value,t);e.left&&walkNode(e.left,t),e.right&&walkNode(e.right,t)}}function findProperty(e,t){return e.properties?.find(e=>e.type===`Property`&&!e.computed&&e.key?.type===`Identifier`&&e.key.name===t)}function escapeForRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function splitParamsTopLevel(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let a=e[i];a===`<`||a===`(`||a===`[`||a===`{`?n++:a===`>`||a===`)`||a===`]`||a===`}`?n--:a===`,`&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function extractParamBindingName(e){let t=e.trim(),n=0;for(let e=0;e<t.length;e++){let r=t[e];if(r===`<`||r===`(`||r===`[`||r===`{`)n++;else if(r===`>`||r===`)`||r===`]`||r===`}`)n--;else if(n===0&&(r===`:`||r===`=`))return t.slice(0,e).trim()}return t}function extractExecuteParamNames(e){if(!e)return new Set;let t=new Set;for(let n of splitParamsTopLevel(e)){let e=extractParamBindingName(n);e&&t.add(e)}return t}export{transformDynamicToolExecute as transformDynamicToolAwait,transformDynamicToolExecute};
|