eve 0.81.0 → 0.82.0
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 +37 -0
- package/dist/src/channel/channel-address.d.ts +21 -2
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/channel-operations.d.ts +32 -1
- package/dist/src/channel/channel-operations.js +1 -1
- package/dist/src/channel/delivery-idempotency.d.ts +4 -0
- package/dist/src/channel/delivery-idempotency.js +1 -0
- package/dist/src/channel/routes.d.ts +6 -0
- package/dist/src/channel/session.d.ts +5 -0
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +14 -11
- package/dist/src/chunks/{use-eve-agent-Bp6nbhfV.js → use-eve-agent-DTu78IAF.js} +36 -0
- package/dist/src/chunks/{use-eve-agent-DLkjJIm3.js → use-eve-agent-DlznYwQk.js} +36 -0
- package/dist/src/cli/dev/command-options.d.ts +1 -0
- package/dist/src/cli/dev/diagnostic-dump.js +1 -1
- package/dist/src/cli/run.d.ts +1 -0
- package/dist/src/cli/run.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/message-reducer-types.d.ts +7 -3
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/transcript-reducer.d.ts +6 -3
- package/dist/src/client/transcript-reducer.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -2
- package/dist/src/compiled/@eve/catalog/index.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +19 -18
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/load-binding-namespace.d.ts +2 -0
- package/dist/src/compiler/load-binding-namespace.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/module-lifecycle.d.ts +1 -1
- package/dist/src/compiler/module-lifecycle.js +1 -1
- package/dist/src/compiler/module-map.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/project-sources.d.ts +6 -0
- package/dist/src/compiler/project-sources.js +1 -1
- package/dist/src/context/keys.d.ts +2 -0
- package/dist/src/context/keys.js +1 -1
- package/dist/src/evals/cli/eval-state-directory.d.ts +7 -0
- package/dist/src/evals/cli/eval-state-directory.js +1 -0
- package/dist/src/evals/cli/eval.js +2 -2
- package/dist/src/eve-channel/create-request.d.ts +2 -1
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/request.d.ts +2 -1
- package/dist/src/eve-channel/request.js +1 -2
- package/dist/src/eve-channel/support.d.ts +11 -1
- package/dist/src/eve-channel/support.js +2 -1
- package/dist/src/eve-channel/types.d.ts +25 -0
- package/dist/src/execution/agent-sessions/context.d.ts +2 -13
- package/dist/src/execution/agent-sessions/context.js +1 -1
- package/dist/src/execution/agent-sessions/runtime-overrides.d.ts +5 -0
- package/dist/src/execution/agent-sessions/runtime-overrides.js +1 -0
- package/dist/src/execution/agent-sessions/session.d.ts +2 -2
- package/dist/src/execution/agent-sessions/session.js +1 -1
- package/dist/src/execution/agent-sessions/steps.d.ts +2 -0
- package/dist/src/execution/agent-sessions/steps.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.d.ts +5 -5
- package/dist/src/execution/coordination-dispatch-step.d.ts +17 -2
- package/dist/src/execution/coordination-dispatch-step.js +1 -1
- package/dist/src/execution/create-session-step.d.ts +5 -2
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/deliver-payloads.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +0 -1
- package/dist/src/execution/dynamic-connection-recovery.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/effective-agent-config.d.ts +8 -2
- package/dist/src/execution/effective-agent-config.js +1 -1
- package/dist/src/execution/hook-ownership.d.ts +8 -0
- package/dist/src/execution/hook-ownership.js +1 -1
- package/dist/src/execution/install-workflow-deployment-id.d.ts +3 -0
- package/dist/src/execution/install-workflow-deployment-id.js +1 -0
- package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
- package/dist/src/execution/node-step.d.ts +1 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/runtime-context.d.ts +2 -0
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/admission.js +1 -1
- package/dist/src/execution/session/checkpoint-migrations.js +1 -1
- package/dist/src/execution/session/entry-input.d.ts +20 -8
- package/dist/src/execution/session/entry-input.js +1 -1
- package/dist/src/execution/session/entry.js +1 -1
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff-steps.d.ts +75 -13
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +73 -34
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +5 -1
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/pending-history.d.ts +5 -0
- package/dist/src/execution/session/pending-history.js +1 -0
- package/dist/src/execution/session/pending-turn-state.js +1 -1
- package/dist/src/execution/session/program.d.ts +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/run-watch.d.ts +22 -0
- package/dist/src/execution/session/run-watch.js +1 -0
- package/dist/src/execution/session/timeout-control.d.ts +18 -4
- package/dist/src/execution/session/timeout-control.js +1 -1
- package/dist/src/execution/session/timeout.d.ts +1 -2
- package/dist/src/execution/session/timeout.js +1 -1
- package/dist/src/execution/session/turn-event-handler.js +1 -1
- package/dist/src/execution/session/turn-step-result.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn-waiting-step.js +1 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/session-inbox/address.d.ts +4 -1
- package/dist/src/execution/session-inbox/end-stranded-session.js +1 -1
- package/dist/src/execution/session-inbox/hook-release.d.ts +9 -2
- package/dist/src/execution/session-inbox/hook-release.js +1 -1
- package/dist/src/execution/session-inbox/inbox.d.ts +66 -6
- package/dist/src/execution/session-inbox/inbox.js +1 -1
- package/dist/src/execution/session-inbox/protocol.js +1 -1
- package/dist/src/execution/session-inbox/resume.d.ts +4 -3
- package/dist/src/execution/session.d.ts +0 -12
- package/dist/src/execution/session.js +2 -2
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/model-step.js +1 -1
- package/dist/src/execution/tasks/start.d.ts +4 -4
- package/dist/src/execution/tasks/start.js +1 -1
- package/dist/src/execution/tasks/steps.js +1 -1
- package/dist/src/execution/terminate-child-sessions-step.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/workflow/body.d.ts +2 -2
- package/dist/src/execution/workflow-runtime.d.ts +11 -12
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/hitl/approvals.js +1 -1
- package/dist/src/harness/hitl/budget-request.d.ts +12 -6
- package/dist/src/harness/hitl/budget-request.js +1 -1
- package/dist/src/harness/hitl/budget.d.ts +7 -1
- package/dist/src/harness/hitl/budget.js +1 -1
- package/dist/src/harness/hitl/coordinator.js +1 -1
- package/dist/src/harness/hitl/delivery.d.ts +1 -1
- package/dist/src/harness/hitl/delivery.js +1 -1
- package/dist/src/harness/hitl/index.js +1 -1
- package/dist/src/harness/hitl/intake.d.ts +2 -2
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/messages.d.ts +5 -0
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/model-call/call.d.ts +2 -2
- package/dist/src/harness/model-call/call.js +1 -1
- package/dist/src/harness/model-call/request.d.ts +2 -2
- package/dist/src/harness/session-machine/transitions.d.ts +3 -1
- package/dist/src/harness/session-machine/transitions.js +1 -1
- package/dist/src/harness/step/context.d.ts +3 -0
- package/dist/src/harness/step/context.js +1 -1
- package/dist/src/harness/step/intake.d.ts +5 -2
- package/dist/src/harness/step/intake.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/turn-tag-state.d.ts +7 -26
- package/dist/src/harness/turn-tag-state.js +1 -1
- package/dist/src/harness/types.d.ts +10 -25
- package/dist/src/instrumentation/content.d.ts +1 -1
- package/dist/src/instrumentation/content.js +1 -1
- package/dist/src/instrumentation/lifecycle.d.ts +4 -2
- package/dist/src/internal/application/build-profile.d.ts +3 -0
- package/dist/src/internal/application/build-profile.js +1 -1
- package/dist/src/internal/application/compiled-artifacts.js +2 -2
- package/dist/src/internal/application/dev-environment.d.ts +13 -0
- package/dist/src/internal/application/dev-environment.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/authored-module-build-options.d.ts +7 -0
- package/dist/src/internal/authored-module-build-options.js +1 -0
- package/dist/src/internal/authored-module-graph.d.ts +13 -0
- package/dist/src/internal/authored-module-graph.js +1 -0
- package/dist/src/internal/authored-module-loader.d.ts +22 -1
- package/dist/src/internal/authored-module-loader.js +1 -3
- package/dist/src/internal/authored-module.d.ts +7 -0
- package/dist/src/internal/authored-module.js +1 -1
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/bundler/nitro-rolldown.d.ts +5 -1
- package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
- package/dist/src/internal/development-programmatic-source-loader.d.ts +1 -0
- package/dist/src/internal/development-programmatic-source-loader.js +1 -1
- package/dist/src/internal/mcp/skills.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-generation-metadata.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/build-deployment-id.d.ts +8 -0
- package/dist/src/internal/nitro/host/build-deployment-id.js +1 -0
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-server-state.js +1 -1
- package/dist/src/internal/nitro/host/skill-server-assets.js +1 -1
- package/dist/src/internal/nitro/host/stage-build-deployment-id.d.ts +2 -0
- package/dist/src/internal/nitro/host/stage-build-deployment-id.js +1 -0
- package/dist/src/internal/nitro/host/start-production-server.d.ts +1 -0
- package/dist/src/internal/nitro/host/start-production-server.js +3 -3
- package/dist/src/internal/nitro/routes/schedule-task.d.ts +3 -0
- package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
- package/dist/src/internal/programmatic-source-loader.d.ts +1 -0
- package/dist/src/internal/programmatic-source-loader.js +1 -1
- package/dist/src/internal/schedules/disabled.d.ts +2 -0
- package/dist/src/internal/schedules/disabled.js +1 -0
- package/dist/src/internal/workflow/development-world-client.js +1 -1
- package/dist/src/internal/workflow/development-world-server.js +1 -1
- package/dist/src/internal/workflow/local-world-data-directory.d.ts +2 -1
- package/dist/src/internal/workflow/local-world-data-directory.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +1 -1
- package/dist/src/protocol/message.d.ts +27 -1
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +13 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
- package/dist/src/public/channels/chat-sdk/fetch-message.d.ts +10 -0
- package/dist/src/public/channels/chat-sdk/fetch-message.js +1 -0
- package/dist/src/public/channels/chat-sdk/index.d.ts +1 -1
- package/dist/src/public/channels/chat-sdk/messageToUserContent.d.ts +2 -1
- package/dist/src/public/channels/chat-sdk/messageToUserContent.js +1 -1
- package/dist/src/public/channels/chat-sdk/reply-context.d.ts +15 -0
- package/dist/src/public/channels/chat-sdk/reply-context.js +2 -0
- package/dist/src/public/channels/discord/discordChannel.d.ts +3 -0
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +3 -0
- package/dist/src/public/channels/imessage-tapbacks.d.ts +74 -0
- package/dist/src/public/channels/imessage-tapbacks.js +1 -0
- package/dist/src/public/channels/index.d.ts +2 -1
- package/dist/src/public/channels/index.js +1 -1
- package/dist/src/public/channels/linear/linearChannel.d.ts +3 -0
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/linq/inboundContent.d.ts +7 -0
- package/dist/src/public/channels/linq/inboundContent.js +1 -1
- package/dist/src/public/channels/linq/index.d.ts +1 -0
- package/dist/src/public/channels/linq/index.js +1 -1
- package/dist/src/public/channels/linq/linqChannel.d.ts +17 -1
- package/dist/src/public/channels/linq/linqChannel.js +1 -1
- package/dist/src/public/channels/photon/attachments.d.ts +5 -2
- package/dist/src/public/channels/photon/attachments.js +1 -1
- package/dist/src/public/channels/photon/inboundContent.d.ts +7 -0
- package/dist/src/public/channels/photon/inboundContent.js +2 -1
- package/dist/src/public/channels/photon/index.d.ts +1 -0
- package/dist/src/public/channels/photon/index.js +1 -1
- package/dist/src/public/channels/photon/photonIMessageChannel.d.ts +17 -1
- package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -1
- package/dist/src/public/channels/slack/api.d.ts +14 -1
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/slack/model-context.d.ts +7 -0
- package/dist/src/public/channels/slack/model-context.js +1 -1
- package/dist/src/public/channels/slack/reply-delivery.d.ts +5 -0
- package/dist/src/public/channels/slack/reply-delivery.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +17 -3
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +3 -0
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +3 -0
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/definitions/agent.d.ts +1 -1
- package/dist/src/public/definitions/channel.d.ts +2 -2
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +1 -0
- package/dist/src/public/index.d.ts +1 -1
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/runtime/agent/resolve-model.d.ts +4 -0
- package/dist/src/runtime/agent/resolve-model.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
- package/dist/src/runtime/subagents/dynamic-agent-config.d.ts +2 -1
- package/dist/src/runtime/subagents/dynamic-agent-config.js +1 -1
- package/dist/src/runtime/types.d.ts +3 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +31 -42
- package/dist/src/shared/gateway-routing.d.ts +20 -0
- package/dist/src/shared/gateway-routing.js +1 -0
- package/dist/src/shared/session-history.d.ts +22 -0
- package/dist/src/shared/session-history.js +1 -0
- package/dist/src/shared/skill-package.js +1 -1
- package/dist/src/subagents/tool.d.ts +1 -3
- package/dist/src/subagents/tool.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tools/workflow-definition.d.ts +14 -1
- package/dist/src/tracing/eve/agent-otel-provider.js +1 -1
- package/dist/src/tracing/eve/conversation-context.d.ts +4 -1
- package/dist/src/tracing/eve/conversation-context.js +1 -1
- package/dist/src/tracing/eve/gateway.d.ts +5 -0
- package/dist/src/tracing/eve/gateway.js +1 -1
- package/dist/src/tracing/eve/invoke-tool-span.js +1 -1
- package/dist/src/tracing/eve/operation-input.d.ts +0 -12
- package/dist/src/tracing/eve/operation-input.js +1 -1
- package/dist/src/tracing/eve/otel-registration.js +1 -1
- package/dist/src/tracing/eve/policy.d.ts +1 -1
- package/dist/src/tracing/eve/policy.js +1 -1
- package/dist/src/tracing/eve/session.d.ts +5 -2
- package/dist/src/tracing/eve/session.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/README.md +1 -0
- package/docs/agent-config.md +108 -65
- package/docs/channels/chat-sdk.mdx +10 -3
- package/docs/channels/custom.mdx +38 -6
- package/docs/channels/eve.mdx +73 -0
- package/docs/channels/linq.mdx +51 -0
- package/docs/channels/photon.mdx +68 -2
- package/docs/channels/slack.mdx +6 -2
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/execution-model-and-durability.mdx +27 -11
- package/docs/concepts/sessions-runs-and-streaming.md +9 -8
- package/docs/connections/overview.mdx +1 -1
- package/docs/experimental/dynamic-schedules.mdx +186 -0
- package/docs/experimental/meta.json +4 -0
- package/docs/guides/client/streaming.mdx +1 -0
- package/docs/guides/deployment/self-hosting.md +3 -0
- package/docs/guides/hooks.md +21 -1
- package/docs/guides/instrumentation/otel.mdx +20 -0
- package/docs/memory/overview.mdx +2 -1
- package/docs/patterns/dynamic-scheduling.md +3 -1
- package/docs/patterns/meta.json +1 -0
- package/docs/patterns/voice-notes.md +67 -0
- package/docs/reference/cli.md +14 -7
- package/docs/sandbox/index.mdx +2 -0
- package/docs/schedules.mdx +2 -0
- package/docs/subagents/index.mdx +2 -0
- package/docs/tools/overview.mdx +2 -1
- package/docs/tools/tasks-upgrade.md +12 -7
- package/docs/tools/tasks.md +10 -6
- package/docs/tools/workflows.mdx +36 -5
- package/docs/tutorial/connect-a-warehouse.mdx +1 -1
- package/docs/tutorial/run-analysis.mdx +1 -1
- package/package.json +1 -1
- package/dist/src/execution/run-session-limits.d.ts +0 -12
- package/dist/src/execution/run-session-limits.js +0 -1
- package/dist/src/harness/session-usage-limits.d.ts +0 -49
- package/dist/src/harness/session-usage-limits.js +0 -1
- package/dist/src/subagents/token-budget.d.ts +0 -15
- package/dist/src/subagents/token-budget.js +0 -1
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,realpathSync,writeFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{EXTENSION_CHUNK_DIRECTORY,createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{authoredModuleConditions}from"#internal/authored-module-conditions.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createExtensionScopePlugin,createFixedMountScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.js";import{applyWorkflowTransform,isAuthoredApplicationModule}from"#internal/workflow-bundle/workflow-builders.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),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,t){let n=AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,t):await import(createFileImportSpecifier(e));return expectObjectRecord(n,`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 bundleAuthoredModuleCode(e,t={}){let n=resolveAuthoredPackageRoot(e),r=t.extension?.entry,i=t.extension?.mountId,a=r===void 0?[]:[...t.extension?.ancestors??[],{...r,mountId:i}];return await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:n,extensionSpecifiers:new Set(a.map(e=>e.specifier))}),plugins:[...r===void 0?[]:[{name:`eve-compile-mount-entry`,resolveId(e){return e===`\0eve-compile-mount-entry`?e:void 0},load(t){if(t!==`\0eve-compile-mount-entry`)return;let n=a.map(e=>`import ${JSON.stringify(`${e.mountSourcePath}?eve-mount=${encodeURIComponent(e.mountId)}`)};`),r=`${e}?eve-mount=${encodeURIComponent(i)}`;return`${n.join(` `)} export * from ${JSON.stringify(r)}; import entry from ${JSON.stringify(r)}; export default entry;`}}],createAuthoredWorkflowDirectivePlugin({appRoot:t.appRoot??n}),...r===void 0?[]:[createExtensionMountPlugin(a)]],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return removeRolldownModuleRegionComments(await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1}))}async function bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`${EXTENSION_CHUNK_DIRECTORY}/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map,i=new Set;for(let e of n.output)if(e.type===`chunk`){r.set(e.fileName,removeRolldownModuleRegionComments(e.code));for(let t of[...e.imports,...e.dynamicImports])i.add(t)}return{files:r,imports:[...i]}}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(usesDevelopmentExtensionModules(e.manifest)?`src/internal/development-programmatic-source-loader.ts`:`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),a=[e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),o=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({mountId:e.mountId,sourceRoot:e.sourceRoot})))),s=new AuthoredWorkflowSourceRecorder(e.appRoot),c=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:i}),createExternalRuntimeImportPlugin(n),createAuthoredWorkflowDirectivePlugin({appRoot:e.appRoot,recorder:s}),createDynamicCapabilityTransformPlugin({workflowFunctions:e=>s.workflowFunctions(e)}),s.graphPlugin(),createExtensionMountPlugin(a,extensionOverridePaths(e.manifest)),o,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:t}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:r,packageRoot:t,extensionSpecifiers:new Set(a.map(e=>e.specifier)),resolveExternalPaths:e.resolveExternalPaths})].filter(e=>e!==null);try{let n=await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:c,resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}});return{authoredWorkflowModules:s.modules(),code:removeRolldownModuleRegionComments(n.code),sourceModules:s.sourceModules().filter(t=>t!==e.moduleMapPath),workflowSourceFingerprint:s.fingerprint()}}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function usesDevelopmentExtensionModules(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>Object.values(e.bindings).some(e=>e.backing.kind===`programmatic`&&e.backing.registryId.startsWith(`eve:development-extension:`)))}function createExternalRuntimeImportPlugin(e){let t=normalizeEsmImportSpecifier(e);return{name:`eve-external-runtime-import`,resolveId(e){return e===t?{external:!0,id:t}:void 0}}}var AuthoredWorkflowSourceRecorder=class{#e;#t=new Set;#n=new Map;#r=new Map;#i=new Map;constructor(e){this.#e=e}record(e,t,n){this.#r.set(e,t),(n.steps!==void 0||n.workflows!==void 0)&&this.#t.add(e);let r=Object.values(n.workflows??{})[0];r!==void 0&&this.#i.set(e,new Set(Object.keys(r)))}workflowFunctions(e){return this.#i.get(e)}sourceModules(){return[...this.#r.keys()].sort()}graphPlugin(){let e=this.#n;return{name:`eve-authored-module-graph`,buildEnd(){for(let t of this.getModuleIds()){let n=this.getModuleInfo(t);n!==null&&e.set(t,[...n.importedIds,...n.dynamicallyImportedIds])}}}}modules(){return{directiveModules:[...this.#t].sort(),workflowModules:[...this.#i.keys()].sort()}}fingerprint(){if(this.#t.size===0)return;let e=new Set,t=[...this.#t];for(let n=t.shift();n!==void 0;n=t.shift())!e.has(n)&&this.#r.has(n)&&(e.add(n),t.push(...this.#n.get(n)??[]));let n=createHash(`sha256`);for(let t of[...e].sort())n.update(relative(this.#e,t).split(sep).join(`/`)).update(`\0`).update(this.#r.get(t)??``).update(`\0`);return n.digest(`hex`)}};function createVirtualGenerationModuleMapPlugin(e){return{name:`eve-generation-module-map`,resolveId(t){return t===e.id?t:void 0},load(t){return t===e.id?{code:e.source,moduleType:`js`}:void 0}}}async function buildAuthoredModuleBundle(e,t,n){let r=resolveAuthoredPackageRoot(e),i=resolveAuthoredTsConfigPath(r),a=[...n.plugins,t.extension===void 0?null:createFixedMountScopePlugin(t.extension.mountId),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:r}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:r,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),n.packageBoundaryPlugin].filter(e=>e!==null);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{cwd:r,input:t.extension?.entry===void 0?e:`\0eve-compile-mount-entry`,platform:`node`,plugins:a,resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:i,output:{comments:!1,format:`esm`,sourcemap:n.sourcemap}})).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t))return;let{hasDirectives:n}=await prepareAuthoredWorkflowDirectives({filePath:t,source:e});if(n)throw Error(`Module "${t}" uses Workflow directives ("use step" or "use workflow"). Workflow directives are supported in application modules only, not in extensions or instrumentation.`)}}}function createAuthoredWorkflowDirectivePlugin(e){return{name:`eve-authored-workflow-directives`,async transform(t,n){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(n)||isNodeModulesPath(n)||!isAuthoredApplicationModule(n,e.appRoot))return;let r=await applyWorkflowTransform(n,t,`client`,n,e.appRoot);return e.recorder?.record(n,t,r.workflowManifest),r.code===t?void 0:{code:r.code,map:null}}}}function removeRolldownModuleRegionComments(e){return e.split(`
|
|
2
|
-
`).filter(e=>!e.startsWith(`//#region `)&&e!==`//#endregion`).join(`
|
|
3
|
-
`)}async function loadBundledAuthoredModule(e,t){let n=await bundleAuthoredModuleCode(e,t),r=normalizeExternalDependencies(t.externalDependencies),i=createHash(`sha1`).update(e).update(`\0`).update(r.join(`\0`)).update(`\0`).update(t.extension?.mountId??``).update(`\0`).update(n).digest(`hex`),a=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),o=join(a,`${i}.mjs`);existsSync(o)||(mkdirSync(a,{recursive:!0}),writeFileSync(o,n));try{let e=t.extension?.evaluationId??``;return await import(`${createFileImportSpecifier(o)}?v=${i}&instance=${encodeURIComponent(e)}`)}catch(t){throw createAuthoredModuleEvaluationError(e,t)}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extension?.mountId??``}\0${t.extension?.evaluationId??``}\0${t.appRoot??``}`}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);if(existsSync(n))return n}return!1}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return realpathSync(t);let n=dirname(t);if(n===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=n}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,bundleExtensionDistributionGraph,loadAuthoredModuleNamespace,resolveAuthoredPackageRoot,resolveAuthoredTsConfigPath};
|
|
1
|
+
import{createHash}from"node:crypto";import{expectObjectRecord,interopAuthoredModuleNamespace}from"#internal/authored-module.js";import{existsSync,mkdirSync,realpathSync,writeFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{authoredModuleConditions}from"#internal/authored-module-conditions.js";import{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredModuleBuildOptions,resolveAuthoredTsConfigPath}from"#internal/authored-module-build-options.js";import{EXTENSION_CHUNK_DIRECTORY,createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createExtensionScopePlugin,createFixedMountScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.js";import{applyWorkflowTransform,isAuthoredApplicationModule}from"#internal/workflow-bundle/workflow-builders.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),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,t){let n=AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,t):await import(createFileImportSpecifier(e));return expectObjectRecord(interopAuthoredModuleNamespace(n),`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 bundleAuthoredModuleCode(e,t={}){let n=resolveAuthoredPackageRoot(e),r=t.extension?.entry,i=t.extension?.mountId,a=r===void 0?[]:[...t.extension?.ancestors??[],{...r,mountId:i}];return await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:n,extensionSpecifiers:new Set(a.map(e=>e.specifier))}),plugins:[...r===void 0?[]:[{name:`eve-compile-mount-entry`,resolveId(e){return e===`\0eve-compile-mount-entry`?e:void 0},load(t){if(t!==`\0eve-compile-mount-entry`)return;let n=a.map(e=>`import ${JSON.stringify(`${e.mountSourcePath}?eve-mount=${encodeURIComponent(e.mountId)}`)};`),r=`${e}?eve-mount=${encodeURIComponent(i)}`;return`${n.join(` `)} export * from ${JSON.stringify(r)}; import entry from ${JSON.stringify(r)}; export default entry;`}}],createAuthoredWorkflowDirectivePlugin({appRoot:t.appRoot??n}),...r===void 0?[]:[createExtensionMountPlugin(a)]],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1})}async function bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`${EXTENSION_CHUNK_DIRECTORY}/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map,i=new Set;for(let e of n.output)if(e.type===`chunk`){r.set(e.fileName,e.code);for(let t of[...e.imports,...e.dynamicImports])i.add(t)}return{files:r,imports:[...i]}}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(usesDevelopmentExtensionModules(e.manifest)?`src/internal/development-programmatic-source-loader.ts`:`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),a=[e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),o=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({mountId:e.mountId,sourceRoot:e.sourceRoot})))),s=new AuthoredWorkflowSourceRecorder(e.appRoot),c=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:i}),createExternalRuntimeImportPlugin(n),createAuthoredWorkflowDirectivePlugin({appRoot:e.appRoot,recorder:s}),createDynamicCapabilityTransformPlugin({workflowFunctions:e=>s.workflowFunctions(e)}),s.graphPlugin(),createExtensionMountPlugin(a,extensionOverridePaths(e.manifest)),o,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:t}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:r,packageRoot:t,extensionSpecifiers:new Set(a.map(e=>e.specifier)),resolveExternalPaths:e.resolveExternalPaths})].filter(e=>e!==null);try{let n=await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:c,resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}});return{authoredWorkflowModules:s.modules(),code:n.code,sourceModules:s.sourceModules().filter(t=>t!==e.moduleMapPath),workflowSourceFingerprint:s.fingerprint()}}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function usesDevelopmentExtensionModules(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>Object.values(e.bindings).some(e=>e.backing.kind===`programmatic`&&e.backing.registryId.startsWith(`eve:development-extension:`)))}function createExternalRuntimeImportPlugin(e){let t=normalizeEsmImportSpecifier(e);return{name:`eve-external-runtime-import`,resolveId(e){return e===t?{external:!0,id:t}:void 0}}}var AuthoredWorkflowSourceRecorder=class{#e;#t=new Set;#n=new Map;#r=new Map;#i=new Map;constructor(e){this.#e=e}record(e,t,n){this.#r.set(e,t),(n.steps!==void 0||n.workflows!==void 0)&&this.#t.add(e);let r=Object.values(n.workflows??{})[0];r!==void 0&&this.#i.set(e,new Set(Object.keys(r)))}workflowFunctions(e){return this.#i.get(e)}sourceModules(){return[...this.#r.keys()].sort()}graphPlugin(){let e=this.#n;return{name:`eve-authored-module-graph`,buildEnd(){for(let t of this.getModuleIds()){let n=this.getModuleInfo(t);n!==null&&e.set(t,[...n.importedIds,...n.dynamicallyImportedIds])}}}}modules(){return{directiveModules:[...this.#t].sort(),workflowModules:[...this.#i.keys()].sort()}}fingerprint(){if(this.#t.size===0)return;let e=new Set,t=[...this.#t];for(let n=t.shift();n!==void 0;n=t.shift())!e.has(n)&&this.#r.has(n)&&(e.add(n),t.push(...this.#n.get(n)??[]));let n=createHash(`sha256`);for(let t of[...e].sort())n.update(relative(this.#e,t).split(sep).join(`/`)).update(`\0`).update(this.#r.get(t)??``).update(`\0`);return n.digest(`hex`)}};function createVirtualGenerationModuleMapPlugin(e){return{name:`eve-generation-module-map`,resolveId(t){return t===e.id?t:void 0},load(t){return t===e.id?{code:e.source,moduleType:`js`}:void 0}}}async function buildAuthoredModuleBundle(e,t,n){let r=resolveAuthoredPackageRoot(e);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{...createAuthoredModuleBuildOptions({packageBoundaryPlugin:n.packageBoundaryPlugin,packageRoot:r,plugins:[...n.plugins,t.extension===void 0?null:createFixedMountScopePlugin(t.extension.mountId)]}),input:t.extension?.entry===void 0?e:`\0eve-compile-mount-entry`,output:{comments:!1,format:`esm`,sourcemap:n.sourcemap}})).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t))return;let{hasDirectives:n}=await prepareAuthoredWorkflowDirectives({filePath:t,source:e});if(n)throw Error(`Module "${t}" uses Workflow directives ("use step" or "use workflow"). Workflow directives are supported in application modules only, not in extensions or instrumentation.`)}}}function createAuthoredWorkflowDirectivePlugin(e){return{name:`eve-authored-workflow-directives`,async transform(t,n){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(n)||isNodeModulesPath(n)||!isAuthoredApplicationModule(n,e.appRoot))return;let r=await applyWorkflowTransform(n,t,`client`,n,e.appRoot);return e.recorder?.record(n,t,r.workflowManifest),r.code===t?void 0:{code:r.code,map:null}}}}async function loadBundledAuthoredModule(e,t){let n=t.extension===void 0?await t.graph?.entryPath(e,t.externalDependencies??[]):void 0,r=n===void 0?await writeAuthoredModuleBundle(e,t):createFileImportSpecifier(n);try{return await import(r)}catch(t){throw createAuthoredModuleEvaluationError(e,t)}}async function writeAuthoredModuleBundle(e,t){let n=await bundleAuthoredModuleCode(e,t),r=normalizeExternalDependencies(t.externalDependencies),i=createHash(`sha1`).update(e).update(`\0`).update(r.join(`\0`)).update(`\0`).update(t.extension?.mountId??``).update(`\0`).update(n).digest(`hex`),a=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),o=join(a,`${i}.mjs`);existsSync(o)||(mkdirSync(a,{recursive:!0}),writeFileSync(o,n));let s=t.extension?.evaluationId??``;return`${createFileImportSpecifier(o)}?v=${i}&instance=${encodeURIComponent(s)}`}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extension?.mountId??``}\0${t.extension?.evaluationId??``}\0${t.appRoot??``}`}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return realpathSync(t);let n=dirname(t);if(n===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=n}}export{AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,bundleExtensionDistributionGraph,createAuthoredWorkflowDirectivePlugin,loadAuthoredModuleNamespace,resolveAuthoredPackageRoot};
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import type { ModuleDefinitionExport } from "#public/definitions/source.js";
|
|
2
2
|
import type { ModuleSourceRef } from "#shared/source-ref.js";
|
|
3
3
|
import type { AgentModelOptionsDefinition, AgentToolExposure } from "#shared/agent-definition.js";
|
|
4
|
+
/**
|
|
5
|
+
* Returns the exports of transpiled CommonJS as its module namespace. Bundlers
|
|
6
|
+
* expose a CommonJS module's whole `exports` object as the ESM default, so a
|
|
7
|
+
* module marked `__esModule` would otherwise read its namespace as
|
|
8
|
+
* `{ default: { default, ...named } }`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function interopAuthoredModuleNamespace(namespace: unknown): unknown;
|
|
4
11
|
/**
|
|
5
12
|
* Returns the selected authored module export from one namespace.
|
|
6
13
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function getAuthoredModuleExport(e,t){return e[t.exportName??`default`]}async function materializeAuthoredModuleExport(e){return typeof e==`function`?await e():e}function expectObjectRecord(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function expectString(e,t){if(typeof e!=`string`)throw Error(t);return e}function expectBoolean(e,t){if(typeof e!=`boolean`)throw Error(t);return e}function expectAgentToolExposure(e,t){return e===`deferred`?e:expectBoolean(e,`${t} Expected "tool" to be true, false, or "deferred".`)}function expectPositiveInteger(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function expectFunction(e,t){if(typeof e!=`function`)throw Error(t);return e}function expectProviderOptions(e,t){let n=expectObjectRecord(e,t),r={};for(let[e,i]of Object.entries(n))r[e]=expectObjectRecord(i,t);return r}function expectOnlyKnownKeys(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw Error(`${n} Unknown key "${t}".`)}function getOptionalStringRecordProperty(e,t,n){let r=e[t];if(r===void 0)return;let i=expectObjectRecord(r,n),a={};for(let[e,t]of Object.entries(i))a[e]=expectString(t,n);return a}export{expectAgentToolExposure,expectBoolean,expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectPositiveInteger,expectProviderOptions,expectString,getAuthoredModuleExport,getOptionalStringRecordProperty,materializeAuthoredModuleExport};
|
|
1
|
+
function interopAuthoredModuleNamespace(e){if(typeof e!=`object`||!e)return e;let t=Reflect.get(e,`default`);return typeof t==`object`&&t&&Reflect.get(t,`__esModule`)===!0?t:e}function getAuthoredModuleExport(e,t){return e[t.exportName??`default`]}async function materializeAuthoredModuleExport(e){return typeof e==`function`?await e():e}function expectObjectRecord(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function expectString(e,t){if(typeof e!=`string`)throw Error(t);return e}function expectBoolean(e,t){if(typeof e!=`boolean`)throw Error(t);return e}function expectAgentToolExposure(e,t){return e===`deferred`?e:expectBoolean(e,`${t} Expected "tool" to be true, false, or "deferred".`)}function expectPositiveInteger(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function expectFunction(e,t){if(typeof e!=`function`)throw Error(t);return e}function expectProviderOptions(e,t){let n=expectObjectRecord(e,t),r={};for(let[e,i]of Object.entries(n))r[e]=expectObjectRecord(i,t);return r}function expectOnlyKnownKeys(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw Error(`${n} Unknown key "${t}".`)}function getOptionalStringRecordProperty(e,t,n){let r=e[t];if(r===void 0)return;let i=expectObjectRecord(r,n),a={};for(let[e,t]of Object.entries(i))a[e]=expectString(t,n);return a}export{expectAgentToolExposure,expectBoolean,expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectPositiveInteger,expectProviderOptions,expectString,getAuthoredModuleExport,getOptionalStringRecordProperty,interopAuthoredModuleNamespace,materializeAuthoredModuleExport};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire,isBuiltin}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{dirname,join,resolve,sep}from"node:path";import{resolvePackageDependencyPath,resolvePackageRoot,resolveWorkflowModulePath}from"#internal/application/package.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(!isPackageImport(t)||e.extensionSpecifiers?.has(t))return;if(isFrameworkRuntimeImport(t,n))return e.extensionSpecifiers?.has(t)?void 0:{external:!0,id:resolveFrameworkRuntimeImport(t)};if(t.startsWith(`#`)){let r=resolvePackageImport(t,n,e.packageRoot);if(r!==void 0)return{id:r}}let i=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t});if(i!==void 0)return{external:!0,id:e.resolveExternalPaths?normalizeEsmImportSpecifier(i.resolvedId):t}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n)||e.extensionSpecifiers?.has(n)===!0)return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:resolveRuntimeLoaderFrameworkImport(n)};if(n.startsWith(`#`)){let t=resolvePackageImport(n,r,e.packageRoot);if(t!==void 0)return isFrameworkPackagePath(t)?{external:!0,id:normalizeEsmImportSpecifier(t)}:{id:t}}let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:normalizeEsmImportSpecifier(e)}}let o=r===void 0||r.startsWith(`\0`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". 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:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=nearestPackageRoot(e);if(t!==void 0)try{let e=JSON.parse(readFileSync(join(t,`package.json`),`utf8`));return typeof e.name==`string`&&e.name.length>0?e.name:void 0}catch{return}}function nearestPackageRoot(e){let t=dirname(toCanonicalPath(e));for(;;){if(existsSync(join(t,`package.json`)))return t;let e=dirname(t);if(e===t)return;t=e}}function resolvePackageImport(e,t,n){let r=t===void 0||t.startsWith(`\0`)?n:nearestPackageRoot(t)??n;try{let t=createRequire(join(r,`package.json`)).resolve(e);return isPathInsideOrEqual(toCanonicalPath(t),toCanonicalPath(r))?t:void 0}catch{return}}let canonicalFrameworkPackageRoot;function isFrameworkPackagePath(e){return canonicalFrameworkPackageRoot??=toCanonicalPath(resolvePackageRoot()),nearestPackageRoot(e)===canonicalFrameworkPackageRoot}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)?!1:!e.startsWith(`@/`)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}const SELF_MODIFICATION_MOUNT_SPECIFIERS=new Set([`eve/self-modification`,`eve/self-modification/local`,`eve/self-modification/remote`]);function isFrameworkRuntimeImport(e,t){return SELF_MODIFICATION_MOUNT_SPECIFIERS.has(e)?!1:e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function resolveRuntimeLoaderFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)?normalizeEsmImportSpecifier(resolvePackageDependencyPath(e)):resolveFrameworkRuntimeImport(e)}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}`)}export{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies,packageImportName,resolveConfiguredExternalDependency};
|
|
1
|
+
import{createRequire,isBuiltin}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{dirname,join,resolve,sep}from"node:path";import{resolvePackageDependencyPath,resolvePackageRoot,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(!isPackageImport(t)||e.extensionSpecifiers?.has(t))return;if(isFrameworkRuntimeImport(t,n))return e.extensionSpecifiers?.has(t)?void 0:{external:!0,id:toExternalModuleId(resolveFrameworkRuntimeImport(t),r.kind)};if(t.startsWith(`#`)){let r=resolvePackageImport(t,n,e.packageRoot);if(r!==void 0)return{id:r}}let i=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t});if(i!==void 0)return{external:!0,id:e.resolveExternalPaths?toExternalModuleId(normalizeEsmImportSpecifier(i.resolvedId),r.kind):t}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n)||e.extensionSpecifiers?.has(n)===!0)return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:toExternalModuleId(resolveRuntimeLoaderFrameworkImport(n),i.kind)};if(n.startsWith(`#`)){let t=resolvePackageImport(n,r,e.packageRoot);if(t!==void 0)return isFrameworkPackagePath(t)?{external:!0,id:toExternalModuleId(normalizeEsmImportSpecifier(t),i.kind)}:{id:t}}let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:toExternalModuleId(normalizeEsmImportSpecifier(e),i.kind)}}let o=r===void 0||r.startsWith(`\0`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". 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:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=nearestPackageRoot(e);if(t!==void 0)try{let e=JSON.parse(readFileSync(join(t,`package.json`),`utf8`));return typeof e.name==`string`&&e.name.length>0?e.name:void 0}catch{return}}function nearestPackageRoot(e){let t=dirname(toCanonicalPath(e));for(;;){if(existsSync(join(t,`package.json`)))return t;let e=dirname(t);if(e===t)return;t=e}}function resolvePackageImport(e,t,n){let r=t===void 0||t.startsWith(`\0`)?n:nearestPackageRoot(t)??n;try{let t=createRequire(join(r,`package.json`)).resolve(e);return isPathInsideOrEqual(toCanonicalPath(t),toCanonicalPath(r))?t:void 0}catch{return}}let canonicalFrameworkPackageRoot;function isFrameworkPackagePath(e){return canonicalFrameworkPackageRoot??=toCanonicalPath(resolvePackageRoot()),nearestPackageRoot(e)===canonicalFrameworkPackageRoot}function toExternalModuleId(e,t){return t===`require-call`&&e.startsWith(`file:`)?fileURLToPath(e):e}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)?!1:!e.startsWith(`@/`)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}const SELF_MODIFICATION_MOUNT_SPECIFIERS=new Set([`eve/self-modification`,`eve/self-modification/local`,`eve/self-modification/remote`]);function isFrameworkRuntimeImport(e,t){return SELF_MODIFICATION_MOUNT_SPECIFIERS.has(e)?!1:e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function resolveRuntimeLoaderFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)?normalizeEsmImportSpecifier(resolvePackageDependencyPath(e)):resolveFrameworkRuntimeImport(e)}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}`)}export{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies,packageImportName,resolveConfiguredExternalDependency};
|
|
@@ -4,6 +4,8 @@ export type RolldownOutputChunk = {
|
|
|
4
4
|
readonly fileName: string;
|
|
5
5
|
readonly imports: readonly string[];
|
|
6
6
|
readonly dynamicImports: readonly string[];
|
|
7
|
+
readonly isEntry: boolean;
|
|
8
|
+
readonly name: string;
|
|
7
9
|
};
|
|
8
10
|
export type RolldownOutputAsset = {
|
|
9
11
|
readonly type: "asset";
|
|
@@ -21,7 +23,9 @@ export declare function parseWithNitroRolldownAst(filename: string, sourceText:
|
|
|
21
23
|
* code are dropped unless the caller supplies its own `onLog`, except
|
|
22
24
|
* unresolved imports.
|
|
23
25
|
*/
|
|
24
|
-
export declare function buildWithNitroRolldown(options: Record<string, unknown>
|
|
26
|
+
export declare function buildWithNitroRolldown(options: Record<string, unknown> & {
|
|
27
|
+
readonly experimental?: Record<string, unknown>;
|
|
28
|
+
}): Promise<RolldownOutput>;
|
|
25
29
|
export declare const ROLLDOWN_STANDARD_CONDITION_NAMES: ReadonlySet<string>;
|
|
26
30
|
/**
|
|
27
31
|
* Runs a Rolldown build whose contract is exactly one in-memory chunk:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{pathToFileURL}from"node:url";import{onVendoredDependencyLog}from"#internal/bundler/vendored-dependency-log.js";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>{let e=createRequire(import.meta.url),t=createRequire(e.resolve(`nitro/package.json`)).resolve(`rolldown`);return await import(pathToFileURL(t).href)})(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>{let e=createRequire(import.meta.url),t=createRequire(e.resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`);return await import(pathToFileURL(t).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){assertCustomRolldownConditionNames(e);let{build:t}=await loadNitroRolldown();return await t({onLog:onRolldownBuildLog,...e})}function onRolldownBuildLog(e,t,n){if(e===`warn`&&t?.code===`UNRESOLVED_IMPORT`){n(e,t);return}onVendoredDependencyLog(e,t,n)}const ROLLDOWN_STANDARD_CONDITION_NAMES=new Set([`browser`,`default`,`import`,`node`,`require`]);function assertCustomRolldownConditionNames(e){let t=e.resolve;if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`conditionNames`);if(Array.isArray(n)){for(let e of n)if(typeof e==`string`&&ROLLDOWN_STANDARD_CONDITION_NAMES.has(e))throw Error(`Rolldown resolves the standard condition ${JSON.stringify(e)} per import edge; conditionNames may contain only eve-specific additions.`)}}async function buildSingleRolldownChunk(e,t){return getSingleRolldownChunk(await buildWithNitroRolldown({...t,write:!1,output:{...t.output,codeSplitting:!1}}),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{ROLLDOWN_STANDARD_CONDITION_NAMES,buildSingleRolldownChunk,buildWithNitroRolldown,parseWithNitroRolldownAst};
|
|
1
|
+
import{createRequire}from"node:module";import{pathToFileURL}from"node:url";import{onVendoredDependencyLog}from"#internal/bundler/vendored-dependency-log.js";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>{let e=createRequire(import.meta.url),t=createRequire(e.resolve(`nitro/package.json`)).resolve(`rolldown`);return await import(pathToFileURL(t).href)})(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>{let e=createRequire(import.meta.url),t=createRequire(e.resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`);return await import(pathToFileURL(t).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){assertCustomRolldownConditionNames(e);let{build:t}=await loadNitroRolldown();return await t({onLog:onRolldownBuildLog,...e,experimental:{...e.experimental,attachDebugInfo:`none`}})}function onRolldownBuildLog(e,t,n){if(e===`warn`&&t?.code===`UNRESOLVED_IMPORT`){n(e,t);return}onVendoredDependencyLog(e,t,n)}const ROLLDOWN_STANDARD_CONDITION_NAMES=new Set([`browser`,`default`,`import`,`node`,`require`]);function assertCustomRolldownConditionNames(e){let t=e.resolve;if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`conditionNames`);if(Array.isArray(n)){for(let e of n)if(typeof e==`string`&&ROLLDOWN_STANDARD_CONDITION_NAMES.has(e))throw Error(`Rolldown resolves the standard condition ${JSON.stringify(e)} per import edge; conditionNames may contain only eve-specific additions.`)}}async function buildSingleRolldownChunk(e,t){return getSingleRolldownChunk(await buildWithNitroRolldown({...t,write:!1,output:{...t.output,codeSplitting:!1}}),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{ROLLDOWN_STANDARD_CONDITION_NAMES,buildSingleRolldownChunk,buildWithNitroRolldown,parseWithNitroRolldownAst};
|
|
@@ -4,3 +4,4 @@ export declare function loadFrameworkProgrammaticModule(backing: Extract<AgentMo
|
|
|
4
4
|
readonly kind: "programmatic";
|
|
5
5
|
}>, dependencyNamespaces?: Readonly<Record<string, ProgrammaticModuleNamespace>>): Promise<ProgrammaticModuleNamespace>;
|
|
6
6
|
export { memoizeModuleNamespaceFactories } from "#compiler/source-graph.js";
|
|
7
|
+
export { interopAuthoredModuleNamespace } from "#internal/authored-module.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getDevelopmentExtensionSourceRegistry}from"#compiler/development-extensions.js";import{loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories,memoizeModuleNamespaceFactories as memoizeModuleNamespaceFactories$1}from"#compiler/source-graph.js";import{frameworkAgentSourceRegistry}from"#framework/sources/registry.js";async function loadFrameworkProgrammaticModule(e,t){return memoizeModuleNamespaceFactories$1(await loadProgrammaticModuleNamespace({backing:e,dependencyNamespaces:t,registries:[frameworkAgentSourceRegistry,getDevelopmentExtensionSourceRegistry()]}))}export{loadFrameworkProgrammaticModule,memoizeModuleNamespaceFactories};
|
|
1
|
+
import{interopAuthoredModuleNamespace}from"#internal/authored-module.js";import{getDevelopmentExtensionSourceRegistry}from"#compiler/development-extensions.js";import{loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories,memoizeModuleNamespaceFactories as memoizeModuleNamespaceFactories$1}from"#compiler/source-graph.js";import{frameworkAgentSourceRegistry}from"#framework/sources/registry.js";async function loadFrameworkProgrammaticModule(e,t){return memoizeModuleNamespaceFactories$1(await loadProgrammaticModuleNamespace({backing:e,dependencyNamespaces:t,registries:[frameworkAgentSourceRegistry,getDevelopmentExtensionSourceRegistry()]}))}export{interopAuthoredModuleNamespace,loadFrameworkProgrammaticModule,memoizeModuleNamespaceFactories};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{createLogger}from"#internal/logging.js";import{MAX_SKILL_FILE_BYTES,SKILL_ENTRY_FILE_NAME,SkillReadError,comparePaths,isSkillEntryFileName}from"#channel/skill-files.js";import{z}from"#compiled/zod/index.js";import{parseFrontmatter}from"#internal/helpers/frontmatter.js";import{ProtocolError,ProtocolErrorCode,ResourceNotFoundError}from"#compiled/@modelcontextprotocol/server/index.js";import{MCP_LIST_CACHE_HINT}from"#internal/mcp/streamable-http-server.js";import{Buffer}from"node:buffer";
|
|
1
|
+
import{createHash}from"node:crypto";import{createLogger}from"#internal/logging.js";import{MAX_SKILL_FILE_BYTES,SKILL_ENTRY_FILE_NAME,SkillReadError,comparePaths,isSkillEntryFileName}from"#channel/skill-files.js";import{z}from"#compiled/zod/index.js";import{parseFrontmatter}from"#internal/helpers/frontmatter.js";import{mapWithConcurrency}from"#shared/map-with-concurrency.js";import{ProtocolError,ProtocolErrorCode,ResourceNotFoundError}from"#compiled/@modelcontextprotocol/server/index.js";import{MCP_LIST_CACHE_HINT}from"#internal/mcp/streamable-http-server.js";import{Buffer}from"node:buffer";const MCP_SKILLS_EXTENSION=`io.modelcontextprotocol/skills`,MCP_SKILL_MAX_RESOURCES=512,MCP_SKILL_MAX_TOTAL_BYTES=16777216,SKILL_URI_PREFIX=`skill://`,log=createLogger(`mcp.skills`),warned=new Set;function warnOnce(e){warned.has(e)||(warned.add(e),log.warn(e))}function createMcpSkillsFeature(e){return{capabilities:{resources:{listChanged:!1},extensions:{[MCP_SKILLS_EXTENSION]:{directoryRead:!0}}},register(t){registerSkillHandlers(t,e.files,createSkillCatalog(e))}}}const snapshotCache=new WeakMap;function createSkillCatalog({files:e,skills:t}){let n=snapshotCache.get(t)??new Map;snapshotCache.set(t,n);let snapshot=async r=>{let i=t.find(e=>e.name===r);if(i===void 0)return;let a=n.get(r);return a===void 0&&(a=snapshotSkill(e,i),n.set(r,a),a.catch(()=>n.delete(r))),await a};return{async served(){let e=t.map(e=>e.name).sort(comparePaths),n=[];for(let t of e){let e=await snapshot(t);e!==void 0&&n.push(e)}return n},skill:snapshot}}function registerSkillHandlers(e,t,n){let r=e.server;r.setRequestHandler(`skills/list`,{params:z.looseObject({cursor:z.string().optional()})},async e=>(rejectCursor(e.cursor),{skills:(await n.served()).map(e=>e.entry),...MCP_LIST_CACHE_HINT})),r.setRequestHandler(`skills/get`,{params:z.looseObject({uri:z.string()})},async e=>{let t=parseSkillUri(e.uri),r=t?.path===SKILL_ENTRY_FILE_NAME?await n.skill(t.skill):void 0;if(r===void 0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Unknown skill: ${e.uri}`,{uri:e.uri});return{skill:r.entry,...MCP_LIST_CACHE_HINT}}),r.setRequestHandler(`resources/directory/read`,{params:z.looseObject({uri:z.string(),cursor:z.string().optional()})},async e=>{rejectCursor(e.cursor);let t=parseSkillUri(e.uri),r=t===void 0?void 0:await n.skill(t.skill),i=r===void 0?void 0:listDirectory(r,t?.path);if(i===void 0)throw new ResourceNotFoundError(e.uri);return{resources:i,...MCP_LIST_CACHE_HINT}}),r.setRequestHandler(`resources/list`,async e=>(rejectCursor(e.params?.cursor),{resources:(await n.served()).map(e=>({uri:e.entry.uri,name:e.name,description:e.description,mimeType:mimeTypeFor(SKILL_ENTRY_FILE_NAME),size:e.document.bytes.byteLength}))})),r.setRequestHandler(`resources/templates/list`,async e=>(rejectCursor(e.params?.cursor),{resourceTemplates:[]})),r.setRequestHandler(`resources/read`,async e=>{let r=e.params?.uri;if(typeof r!=`string`)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`params.uri must be a string.`);let i=parseSkillUri(r),a=i?.path===void 0?void 0:await n.skill(i.skill),o=i?.path===void 0?void 0:a?.files.get(i.path);if(a===void 0||i?.path===void 0||o===void 0)throw new ResourceNotFoundError(r);let s=i.path===SKILL_ENTRY_FILE_NAME?a.document:toServedFile(await readListedFile(t,a.name,i.path,r));return{contents:[s.text===void 0?{uri:r,mimeType:o.mimeType,blob:Buffer.from(s.bytes).toString(`base64`)}:{uri:r,mimeType:o.mimeType,text:s.text}]}})}async function readListedFile(e,t,n,r){try{return await e.readFile(t,n)}catch(e){throw e instanceof SkillReadError&&e.code===`unknown-file`?new ResourceNotFoundError(r):e}}function toServedFile(e){let t=decodeText(e);return t===void 0?{bytes:e}:{bytes:e,text:t}}function decodeText(e){if(!e.includes(0))try{return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}catch{return}}function servedPaths(e,t,n){if(!isSafeSegment(e))return`its name is not a valid skill:// segment`;let r=n.find(e=>!e.split(`/`).every(isSafeSegment));if(r!==void 0)return`its directory "${r}" is not a valid skill:// path`;if(t.length>512)return`it has more than 512 files`;let i=new Map,a=0;for(let{path:e,size:n}of t){if(!e.split(`/`).every(isSafeSegment))return`its file "${e}" is not a valid skill:// path`;if(n>MAX_SKILL_FILE_BYTES)return`its file "${e}" is over ${MAX_SKILL_FILE_BYTES} bytes`;a+=n;let t=!e.includes(`/`)&&isSkillEntryFileName(e)?SKILL_ENTRY_FILE_NAME:e;if(i.has(t))return`it has more than one ${SKILL_ENTRY_FILE_NAME}`;i.set(t,e)}return i.has(SKILL_ENTRY_FILE_NAME)?a>16777216?`its files total more than ${MCP_SKILL_MAX_TOTAL_BYTES} bytes`:i:`it has no ${SKILL_ENTRY_FILE_NAME}`}async function snapshotSkill(e,t){let unserved=e=>{warnOnce(`mcpChannel does not serve the skill "${t.name}": ${e}.`)},[n,r]=await Promise.all([e.listFiles(t.name),e.listDirectories(t.name)]),i=servedPaths(t.name,n,r);if(typeof i==`string`)return unserved(i);let a=[...i.entries()].sort(([e],[t])=>comparePaths(e,t)),o=await mapWithConcurrency(a,8,async([,n])=>{try{return toServedFile(await e.readFile(t.name,n))}catch(e){if(e instanceof SkillReadError)return e.message;throw e}}),s=o.find(e=>typeof e==`string`);if(s!==void 0)return unserved(`a file did not read (${s})`);let c=o,l=a.findIndex(([e])=>e===SKILL_ENTRY_FILE_NAME),u=entryDocument(t,c[l]);if(u===void 0)return unserved(`its ${SKILL_ENTRY_FILE_NAME} is not UTF-8 text with frontmatter that meets the Agent Skills format`);if(c[l]=u,c.reduce((e,t)=>e+t.bytes.byteLength,0)>16777216||c.some(e=>e.bytes.byteLength>MAX_SKILL_FILE_BYTES))return unserved(`its files as read are over the size limits`);let d=new Map,f=[];for(let[e,[n]]of a.entries()){let r=c[e];d.set(n,{mimeType:servedMimeType(n,r),size:r.bytes.byteLength}),f.push({uri:skillFileUri(t.name,n),digest:`sha256:${createHash(`sha256`).update(r.bytes).digest(`hex`)}`,size:r.bytes.byteLength})}return{name:t.name,description:u.description,document:u,entry:{uri:skillFileUri(t.name,SKILL_ENTRY_FILE_NAME),frontmatter:u.frontmatter,resources:f},files:d,directories:new Set(r)}}function entryDocument(e,t){if(t.text===void 0)return;let n=parseFrontmatterJson(t.text);if(n===void 0)return;if(n.present&&n.data.name===e.name&&typeof n.data.description==`string`)return conforming({bytes:t.bytes,description:n.data.description,frontmatter:n.data,text:t.text});let r=typeof n.data.description==`string`?n.data.description:e.description,{name:i,description:a,...o}=n.data,s=`---\n${renderFrontmatter({name:e.name,description:r,...o})}---\n${n.content}`,c=parseFrontmatterJson(s);if(c!==void 0&&c.data.name===e.name)return conforming({bytes:new TextEncoder().encode(s),description:r,frontmatter:c.data,text:s})}const SKILL_NAME_PATTERN=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function conforming(e){let{name:t,description:n}=e.frontmatter;if(typeof t==`string`&&typeof n==`string`&&!(Array.from(t).length>64||!SKILL_NAME_PATTERN.test(t))&&!(n.trim().length===0||Array.from(n).length>1024))return e}function renderFrontmatter(e){return Object.entries(e).map(([e,t])=>`${/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(e)?e:JSON.stringify(e)}: ${JSON.stringify(t)}\n`).join(``)}function parseFrontmatterJson(e){let t,n;try{n=parseFrontmatter(e),t=JSON.parse(JSON.stringify(n?.data??{}))}catch{return}if(typeof t==`object`&&t&&!Array.isArray(t))return{content:n?.content??e,data:t,present:n!==void 0}}function listDirectory(e,t){if(t!==void 0&&!e.directories.has(t))return;let n=t===void 0?``:`${t}/`,r=[],add=(t,i)=>{let a=t.slice(n.length);t.startsWith(n)&&!a.includes(`/`)&&r.push({uri:skillFileUri(e.name,t),name:a,mimeType:i})};for(let[t,n]of e.files)add(t,n.mimeType);for(let t of e.directories)add(t,`inode/directory`);return r.sort((e,t)=>comparePaths(e.name,t.name))}function parseSkillUri(e){if(!e.startsWith(SKILL_URI_PREFIX))return;let t=e.slice(8);if(/[?#\\\s]/u.test(t))return;let n=[];for(let e of t.split(`/`)){let t;try{t=decodeURIComponent(e)}catch{return}if(!isSafeSegment(t))return;n.push(t)}let[r,...i]=n;if(r!==void 0)return i.length===0?{skill:r}:{skill:r,path:i.join(`/`)}}function isSafeSegment(e){return e.length>0&&e!==`.`&&e!==`..`&&!e.includes(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)}function skillFileUri(e,t){let n=t.split(`/`).map(encodeURIComponent).join(`/`);return`${SKILL_URI_PREFIX}${encodeURIComponent(e)}/${n}`}function rejectCursor(e){if(e!==void 0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Unknown cursor.`)}const MIME_TYPES=new Map([[`css`,`text/css`],[`csv`,`text/csv`],[`gif`,`image/gif`],[`htm`,`text/html`],[`html`,`text/html`],[`jpeg`,`image/jpeg`],[`jpg`,`image/jpeg`],[`js`,`text/javascript`],[`json`,`application/json`],[`md`,`text/markdown`],[`mjs`,`text/javascript`],[`pdf`,`application/pdf`],[`png`,`image/png`],[`py`,`text/x-python`],[`sh`,`text/x-shellscript`],[`svg`,`image/svg+xml`],[`ts`,`text/typescript`],[`txt`,`text/plain`],[`webp`,`image/webp`],[`xml`,`application/xml`],[`yaml`,`application/yaml`],[`yml`,`application/yaml`]]);function servedMimeType(e,t){let n=e.slice(e.lastIndexOf(`/`)+1),r=n.lastIndexOf(`.`);return(r<=0?void 0:MIME_TYPES.get(n.slice(r+1).toLowerCase()))??(t.text===void 0?`application/octet-stream`:`text/plain`)}function mimeTypeFor(e){return servedMimeType(e,{bytes:new Uint8Array})}export{MCP_SKILLS_EXTENSION,MCP_SKILL_MAX_RESOURCES,MCP_SKILL_MAX_TOTAL_BYTES,createMcpSkillsFeature,parseSkillUri};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{cp,mkdir,readFile,rm,symlink,writeFile}from"node:fs/promises";import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageRoot}from"#internal/application/package.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createDevelopmentSourceSnapshotPlan,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts-retention.js";import{resolveDevelopmentRuntimeArtifactsSnapshotsDirectory}from"#internal/nitro/dev-runtime-generation-metadata.js";function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(e,`.eve`,`dev-runtime`,`current.json`)}function isDevelopmentRuntimeArtifactsSnapshotRoot(e,t){return dirname(resolve(t))===resolve(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e))}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,authoredSourceRoots:collectExtensionMountSourceRoots(e.manifest),snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await mountFrameworkPackage(n.runtimeAppRoot),await mountExtensionExternalDependencies({manifest:e.manifest,runtimeAppRoot:n.runtimeAppRoot}),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,extensionPackageRoots:(e.manifest?.subagents??[]).flatMap(e=>e.owner.kind===`extension`?[{sourceRoot:e.agent.appRoot,packageName:e.owner.packageName}]:[]),manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),snapshotSourceRoot:n.snapshotSourceRoot}),await writeFile(join(t,`generation.json`),`${JSON.stringify({runtimeAppRoot:n.runtimeAppRoot})}\n`)}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{sourceWatchPaths:n.watchPaths,runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function mountFrameworkPackage(e){let t=join(e,`node_modules`,`eve`);await mkdir(dirname(t),{recursive:!0}),await rm(t,{force:!0,recursive:!0}),await symlink(resolvePackageRoot(),t,`junction`)}async function mountExtensionExternalDependencies(e){if(e.manifest===void 0)return;let t=[e.manifest,...(e.manifest.subagents??[]).map(e=>e.agent)].flatMap(e=>e.extensionMounts??[]).filter(e=>(e.externalDependencies??[]).length>0);for(let[n,r]of Object.entries(resolveExtensionExternalDependencyPaths(t))){let t=findPackageRoot(r,n),i=join(e.runtimeAppRoot,`node_modules`,...n.split(`/`));await mkdir(dirname(i),{recursive:!0}),await rm(i,{force:!0,recursive:!0}),await symlink(t,i,`junction`)}}function findPackageRoot(e,t){let n=dirname(e);for(;;){let e=join(n,`package.json`);if(existsSync(e))try{if(JSON.parse(readFileSync(e,`utf8`)).name===t)return n}catch{}let r=dirname(n);if(r===n)throw Error(`Cannot locate package root for extension external dependency "${t}".`);n=r}}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=await readMaterializedAuthoredModuleIndex(e.snapshot.runtimeAppRoot);if(t===void 0||!existsSync(join(e.snapshot.runtimeAppRoot,`.eve`,`compile`,t.moduleMap)))throw Error(`Cannot activate development runtime generation "${e.snapshot.snapshotRoot}" before its authored modules are materialized.`);let n=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),r=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(r),a=await readOptionalFile(r);try{await writeFile(n,``),await writeDevelopmentRuntimeArtifactsPointer(e),i?.version===2&&i.snapshotRoot!==e.snapshot.snapshotRoot&&isDevelopmentRuntimeArtifactsSnapshotRoot(e.appRoot,i.snapshotRoot)&&await recordRetiredDevelopmentRuntimeArtifactsSnapshot(i.snapshotRoot).catch(e=>{console.warn(`[eve:dev] failed to record retired runtime generation "${i.snapshotRoot}": ${String(e)}`)})}catch(e){throw await rollbackFailedActivation({cause:e,markerPath:n,pointerPath:r,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:n,pointerPath:r,previousPointerSource:a});if(e!==void 0)throw e}}}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readActiveDevelopmentRuntimeArtifactsSnapshot(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e));if(t!==void 0&&t.version!==1)return{runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot}}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot));return await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({activeSnapshotRoot:t?.version===2?t.snapshotRoot:void 0,gracePeriodMs:e.gracePeriodMs,now:e.now,protectAll:t?.version===1,retainCount:e.retainCount,snapshotsDirectory:resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot)})}function collectExtensionMountSourceRoots(e){return e===void 0?[]:[e,...(e.subagents??[]).map(e=>e.agent)].flatMap(e=>(e.extensionMounts??[]).map(e=>e.sourceRoot))}function readDevelopmentRuntimeArtifactsPointer(e){if(e!==void 0&&existsSync(e))try{let t=JSON.parse(readFileSync(e,`utf8`));return t.kind!==`eve-dev-runtime-artifacts-pointer`||typeof t.version!=`number`?void 0:t.version===1&&typeof t.appRoot==`string`&&t.appRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:t.version===2&&typeof t.appRoot==`string`&&typeof t.runtimeAppRoot==`string`&&t.runtimeAppRoot.length>0&&typeof t.snapshotRoot==`string`&&t.snapshotRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot,version:2}:void 0}catch{return}}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,extensionPackageRoots:e.extensionPackageRoots,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,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]=isPathInsideOrEqual(r,e.appRoot)||e.extensionPackageRoots.some(e=>isPathInsideOrEqual(r,e.sourceRoot))?rewritePathWithinAppRoot({appRoot:e.appRoot,extensionPackageRoots:e.extensionPackageRoots,path:r,runtimeAppRoot:e.runtimeAppRoot}):rewritePathWithinSourceRoot({path:r,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot});continue}if(typeof r==`string`&&n===`sourceRoot`){t[n]=rewritePathWithinSourceRoot({path:r,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,extensionPackageRoots:e.extensionPackageRoots,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:r})}return t}function rewritePathWithinSourceRoot(e){return isPathInsideOrEqual(e.path,e.sourceRoot)?toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:e.path,sourceRoot:e.sourceRoot}):e.path}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot)){let t=e.extensionPackageRoots.find(t=>isPathInsideOrEqual(e.path,t.sourceRoot));return t===void 0?e.path:join(e.runtimeAppRoot,`node_modules`,t.packageName,relative(t.sourceRoot,e.path))}let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),n={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await writeDevelopmentRuntimeArtifactsPointerSource(t,`${JSON.stringify(n,null,2)}\n`)}async function writeDevelopmentRuntimeArtifactsPointerSource(e,t){let n=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(n,t);try{await renameWithTransientBusyRetry(n,e)}catch(e){throw await rm(n,{force:!0}).catch(()=>{}),e}}async function readOptionalFile(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function rollbackFailedActivation(e){let t=await restoreDevelopmentRuntimeArtifactsActivation(e);return t===void 0?e.cause:AggregateError([e.cause,t],`Development runtime activation and rollback failed.`,{cause:e.cause})}async function restoreDevelopmentRuntimeArtifactsActivation(e){let t=(await Promise.allSettled([e.previousPointerSource===void 0?rm(e.pointerPath,{force:!0}):writeDevelopmentRuntimeArtifactsPointerSource(e.pointerPath,e.previousPointerSource),rm(e.markerPath,{force:!0})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length!==0)return AggregateError(t,`Failed to restore development runtime activation.`)}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.snapshotSourceRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime snapshot source root "${e.snapshotSourceRoot}".`)}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{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,readActiveDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
|
|
1
|
+
import{randomUUID}from"node:crypto";import{cp,mkdir,readFile,rm,symlink,writeFile}from"node:fs/promises";import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageRoot}from"#internal/application/package.js";import{resolveDevelopmentStateDirectory}from"#internal/application/dev-environment.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createDevelopmentSourceSnapshotPlan,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts-retention.js";import{resolveDevelopmentRuntimeArtifactsSnapshotsDirectory}from"#internal/nitro/dev-runtime-generation-metadata.js";function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(resolveDevelopmentStateDirectory(e),`dev-runtime`,`current.json`)}function isDevelopmentRuntimeArtifactsSnapshotRoot(e,t){return dirname(resolve(t))===resolve(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e))}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,authoredSourceRoots:collectExtensionMountSourceRoots(e.manifest),snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await mountFrameworkPackage(n.runtimeAppRoot),await mountExtensionExternalDependencies({manifest:e.manifest,runtimeAppRoot:n.runtimeAppRoot}),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,extensionPackageRoots:(e.manifest?.subagents??[]).flatMap(e=>e.owner.kind===`extension`?[{sourceRoot:e.agent.appRoot,packageName:e.owner.packageName}]:[]),manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),snapshotSourceRoot:n.snapshotSourceRoot}),await writeFile(join(t,`generation.json`),`${JSON.stringify({runtimeAppRoot:n.runtimeAppRoot})}\n`)}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{sourceWatchPaths:n.watchPaths,runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function mountFrameworkPackage(e){let t=join(e,`node_modules`,`eve`);await mkdir(dirname(t),{recursive:!0}),await rm(t,{force:!0,recursive:!0}),await symlink(resolvePackageRoot(),t,`junction`)}async function mountExtensionExternalDependencies(e){if(e.manifest===void 0)return;let t=[e.manifest,...(e.manifest.subagents??[]).map(e=>e.agent)].flatMap(e=>e.extensionMounts??[]).filter(e=>(e.externalDependencies??[]).length>0);for(let[n,r]of Object.entries(resolveExtensionExternalDependencyPaths(t))){let t=findPackageRoot(r,n),i=join(e.runtimeAppRoot,`node_modules`,...n.split(`/`));await mkdir(dirname(i),{recursive:!0}),await rm(i,{force:!0,recursive:!0}),await symlink(t,i,`junction`)}}function findPackageRoot(e,t){let n=dirname(e);for(;;){let e=join(n,`package.json`);if(existsSync(e))try{if(JSON.parse(readFileSync(e,`utf8`)).name===t)return n}catch{}let r=dirname(n);if(r===n)throw Error(`Cannot locate package root for extension external dependency "${t}".`);n=r}}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=await readMaterializedAuthoredModuleIndex(e.snapshot.runtimeAppRoot);if(t===void 0||!existsSync(join(e.snapshot.runtimeAppRoot,`.eve`,`compile`,t.moduleMap)))throw Error(`Cannot activate development runtime generation "${e.snapshot.snapshotRoot}" before its authored modules are materialized.`);let n=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),r=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(r),a=await readOptionalFile(r);try{await writeFile(n,``),await writeDevelopmentRuntimeArtifactsPointer(e),i?.version===2&&i.snapshotRoot!==e.snapshot.snapshotRoot&&isDevelopmentRuntimeArtifactsSnapshotRoot(e.appRoot,i.snapshotRoot)&&await recordRetiredDevelopmentRuntimeArtifactsSnapshot(i.snapshotRoot).catch(e=>{console.warn(`[eve:dev] failed to record retired runtime generation "${i.snapshotRoot}": ${String(e)}`)})}catch(e){throw await rollbackFailedActivation({cause:e,markerPath:n,pointerPath:r,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:n,pointerPath:r,previousPointerSource:a});if(e!==void 0)throw e}}}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readActiveDevelopmentRuntimeArtifactsSnapshot(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e));if(t!==void 0&&t.version!==1)return{runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot}}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot));return await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({activeSnapshotRoot:t?.version===2?t.snapshotRoot:void 0,gracePeriodMs:e.gracePeriodMs,now:e.now,protectAll:t?.version===1,retainCount:e.retainCount,snapshotsDirectory:resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot)})}function collectExtensionMountSourceRoots(e){return e===void 0?[]:[e,...(e.subagents??[]).map(e=>e.agent)].flatMap(e=>(e.extensionMounts??[]).map(e=>e.sourceRoot))}function readDevelopmentRuntimeArtifactsPointer(e){if(e!==void 0&&existsSync(e))try{let t=JSON.parse(readFileSync(e,`utf8`));return t.kind!==`eve-dev-runtime-artifacts-pointer`||typeof t.version!=`number`?void 0:t.version===1&&typeof t.appRoot==`string`&&t.appRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:t.version===2&&typeof t.appRoot==`string`&&typeof t.runtimeAppRoot==`string`&&t.runtimeAppRoot.length>0&&typeof t.snapshotRoot==`string`&&t.snapshotRoot.length>0?{appRoot:t.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot,version:2}:void 0}catch{return}}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,extensionPackageRoots:e.extensionPackageRoots,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,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]=isPathInsideOrEqual(r,e.appRoot)||e.extensionPackageRoots.some(e=>isPathInsideOrEqual(r,e.sourceRoot))?rewritePathWithinAppRoot({appRoot:e.appRoot,extensionPackageRoots:e.extensionPackageRoots,path:r,runtimeAppRoot:e.runtimeAppRoot}):rewritePathWithinSourceRoot({path:r,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot});continue}if(typeof r==`string`&&n===`sourceRoot`){t[n]=rewritePathWithinSourceRoot({path:r,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,extensionPackageRoots:e.extensionPackageRoots,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:r})}return t}function rewritePathWithinSourceRoot(e){return isPathInsideOrEqual(e.path,e.sourceRoot)?toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:e.path,sourceRoot:e.sourceRoot}):e.path}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot)){let t=e.extensionPackageRoots.find(t=>isPathInsideOrEqual(e.path,t.sourceRoot));return t===void 0?e.path:join(e.runtimeAppRoot,`node_modules`,t.packageName,relative(t.sourceRoot,e.path))}let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),n={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await writeDevelopmentRuntimeArtifactsPointerSource(t,`${JSON.stringify(n,null,2)}\n`)}async function writeDevelopmentRuntimeArtifactsPointerSource(e,t){let n=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(n,t);try{await renameWithTransientBusyRetry(n,e)}catch(e){throw await rm(n,{force:!0}).catch(()=>{}),e}}async function readOptionalFile(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function rollbackFailedActivation(e){let t=await restoreDevelopmentRuntimeArtifactsActivation(e);return t===void 0?e.cause:AggregateError([e.cause,t],`Development runtime activation and rollback failed.`,{cause:e.cause})}async function restoreDevelopmentRuntimeArtifactsActivation(e){let t=(await Promise.allSettled([e.previousPointerSource===void 0?rm(e.pointerPath,{force:!0}):writeDevelopmentRuntimeArtifactsPointerSource(e.pointerPath,e.previousPointerSource),rm(e.markerPath,{force:!0})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length!==0)return AggregateError(t,`Failed to restore development runtime activation.`)}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.snapshotSourceRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime snapshot source root "${e.snapshotSourceRoot}".`)}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{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,readActiveDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,readdir}from"node:fs/promises";import{basename,join}from"node:path";function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(e
|
|
1
|
+
import{readFile,readdir}from"node:fs/promises";import{basename,join}from"node:path";import{resolveDevelopmentStateDirectory}from"#internal/application/dev-environment.js";function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(resolveDevelopmentStateDirectory(e),`dev-runtime`,`snapshots`)}async function listDevelopmentGenerationIds(e){try{return(await readdir(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e),{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return[];throw e}}async function readDevelopmentGenerationMetadata(e,t){if(!t||t===`.`||t===`..`||basename(t)!==t)throw Error(`Workflow run references an invalid development generation.`);let n;try{n=await readFile(join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e),t,`generation.json`),`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{kind:`missing`};throw e}let r;try{r=JSON.parse(n)}catch{return{kind:`invalid`}}return typeof r!=`object`||!r||Array.isArray(r)||!(`runtimeAppRoot`in r)||typeof r.runtimeAppRoot!=`string`||r.runtimeAppRoot.length===0?{kind:`invalid`}:{kind:`ready`,metadata:{runtimeAppRoot:r.runtimeAppRoot}}}export{listDevelopmentGenerationIds,readDevelopmentGenerationMetadata,resolveDevelopmentRuntimeArtifactsSnapshotsDirectory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{isObject}from"#shared/guards.js";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{resolveDiscoveryProject}from"#discover/project.js";import{resolveInstalledPackageInfo,resolvePackageSourceFilePath}from"#internal/application/package.js";import{normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{toErrorMessage}from"#shared/errors.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile}from"#internal/application/build-profile.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{materializeVercelWorkflowFunctionOutput,normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{emitConnectManifest}from"#internal/external-resources.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{normalizeVercelServiceCrons}from"#internal/nitro/host/normalize-vercel-service-crons.js";import{prepareProductionApplicationHost,refreshProductionCompiledArtifacts}from"#internal/nitro/host/prepare-application-host.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{prewarmAppSandboxes}from"#execution/sandbox/prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";import{resolveEveServicePrefixByRoot}from"#internal/vercel/vercel-service-config-operations.js";import{parseVercelServicesConfig}from"#internal/vercel/vercel-services-config.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}async function measureBuildPhase(e,t,n){return e===void 0?n():e.measure(t,n)}function isPathInside(e,t){let n=relative(e,t);return n.length===0||!n.startsWith(`..${sep}`)&&n!==`..`&&!isAbsolute(n)}function assertProfileOutputOutsideBuildOutput(e,t){if(e!==void 0&&isPathInside(t,e))throw Error(`Build profile path ${e} must be outside the published output directory ${t}.`)}async function writeOptionalApplicationBuildProfile(e){try{assertProfileOutputOutsideBuildOutput(e.profileOutputPath,e.outputDirectory);let t=e.profiler.finish(),n=await measureApplicationBuildOutput(e.outputDirectory);await writeApplicationBuildProfile(e.profileOutputPath,createApplicationBuildProfile({output:n,target:process.env.VERCEL?`vercel`:`local`,timing:t}))}catch(t){console.warn(`eve: failed to write optional build profile to ${e.profileOutputPath}; continuing with the published build output: ${toErrorMessage(t)}`)}}async function resolveEveServicePrefixForVercelFunctionOutput(e,t){let n=Array.from(new Set([resolve(e),resolve(t)])),r=await findClosestVercelOutputDirectory(e);if(r!==void 0)try{let e=join(r,`config.json`),t=parseVercelServicesConfig(JSON.parse(await readFile(e,`utf8`)),e),i=resolveEveServicePrefixByRoot({appRoots:n,configRoot:await resolveVercelOutputConfigRoot(r),config:t});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let i=e;for(;;){for(let e of[join(i,`vercel.json`),join(i,`.vercel`,`output`,`config.json`)])try{let t=parseVercelServicesConfig(JSON.parse(await readFile(e,`utf8`)),e),r=e.endsWith(`vercel.json`)?i:await resolveVercelOutputConfigRoot(dirname(e)),a=resolveEveServicePrefixByRoot({appRoots:n,configRoot:r,config:t});if(a!==void 0)return a}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(i);if(e===i)return;i=e}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isObject(e)&&isObject(e.settings)){let n=e.settings.rootDirectory;if(typeof n==`string`&&n.trim().length>0)return resolve(t,n)}}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function buildNitroOutput(e,t,n){let r=trimTrailingSlash(e.options.output.dir);return await measureBuildPhase(t,`${n}.cache.prepare`,()=>prepareEveVersionedCacheDirectory(r)),await measureBuildPhase(t,`${n}.prepare`,()=>prepare(e)),await measureBuildPhase(t,`${n}.public-assets`,()=>copyPublicAssets(e)),await measureBuildPhase(t,`${n}.prerender`,()=>prerender(e)),await measureBuildPhase(t,`${n}.bundle`,()=>build(e)),await measureBuildPhase(t,`${n}.cache.write`,()=>writeEveVersionedCacheMetadata(r)),r}async function buildApplication(e,t){let n=t.profileOutputPath===void 0?void 0:resolve(t.profileOutputPath),r=n===void 0?void 0:new ApplicationBuildProfiler,i=await measureBuildPhase(r,`extension.check`,()=>tryReadExtensionBuildConfig(e));if(i!==null)throw Error(`Package "${i.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let a=await measureBuildPhase(r,`project.resolve`,()=>resolveDiscoveryProject(e)),o=await measureBuildPhase(r,`workspace.create`,()=>createApplicationBuildWorkspace(a.appRoot,t.vercelServiceOutput?.serviceOutputDirectory)),s=!1,c;try{c=await buildApplicationInWorkspace(o,t,r)}catch(e){throw s=e instanceof RecoverablePublicationError,e}finally{s||await measureBuildPhase(r,`workspace.remove`,()=>removeApplicationBuildWorkspace(o))}return r!==void 0&&n!==void 0&&await writeOptionalApplicationBuildProfile({outputDirectory:c,profileOutputPath:n,profiler:r}),c}async function buildApplicationInWorkspace(e,t,n){let r=await measureBuildPhase(n,`host.prepare`,()=>prepareProductionApplicationHost(e)),i=!!process.env.VERCEL,a=i?await measureBuildPhase(n,`vercel.service-prefix.resolve`,()=>resolveEveServicePrefixForVercelFunctionOutput(r.appRoot,r.compileResult.project.agentRoot)):void 0,o=normalizePublicRoutePrefix(a),s=o===EVE_ROUTE_PREFIX?void 0:o;if(t.publicRoutePrefix!==void 0&&s!==void 0&&t.publicRoutePrefix!==s)throw Error(`EVE_PUBLIC_ROUTE_PREFIX ${JSON.stringify(t.publicRoutePrefix)} conflicts with the configured Vercel service prefix ${JSON.stringify(a)}.`);let c=t.publicRoutePrefix??s,l=createProductionNitroArtifactsConfig(e.appRoot).sandboxScope,u=await measureBuildPhase(n,`nitro.create`,()=>createProductionApplicationNitro(r,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,publicRoutePrefix:c,workspaceMember:t.workspaceMember}));try{if(!t.skipSandboxPrewarm){let t={appRoot:r.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:r.appRoot,sandboxScope:l}),log(e){console.log(e)}};await measureBuildPhase(n,`sandbox.prewarm`,async()=>{i?await runVercelBuildPrewarm(t):await prewarmAppSandboxes(t)}),await refreshProductionCompiledArtifacts(r,e.host.artifactsDir)}await buildNitroOutput(u,n,`nitro`),i&&await measureBuildPhase(n,`vercel.workflow-function.materialize`,()=>materializeVercelWorkflowFunctionOutput(e.publication.output.stagedDir)),a!==void 0&&await measureBuildPhase(n,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:a}));let o=t.vercelServiceOutput;o!==void 0&&(await measureBuildPhase(n,`vercel.service-crons.normalize`,()=>normalizeVercelServiceCrons({publicRoutePrefix:c,serviceOutputDirectory:e.publication.output.stagedDir})),await measureBuildPhase(n,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:o.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir}))),await measureBuildPhase(n,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:r.compileResult.manifest,outputPath:e.publication.summary.stagedPath})),await measureBuildPhase(n,`connect-manifest.emit`,()=>emitConnectManifest({appRoot:r.appRoot,generatorVersion:resolveInstalledPackageInfo().version,manifest:r.compileResult.manifest,outputDirectory:e.publication.output.stagedDir,publicRoutePrefix:c})),i||await measureBuildPhase(n,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir}))}finally{await measureBuildPhase(n,`nitro.close`,()=>u.close())}return await measureBuildPhase(n,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
|
|
1
|
+
import{readFile}from"node:fs/promises";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{isObject}from"#shared/guards.js";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{resolveDiscoveryProject}from"#discover/project.js";import{resolveInstalledPackageInfo,resolvePackageSourceFilePath}from"#internal/application/package.js";import{normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{toErrorMessage}from"#shared/errors.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile}from"#internal/application/build-profile.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{stageBuildDeploymentId}from"#internal/nitro/host/stage-build-deployment-id.js";import{materializeVercelWorkflowFunctionOutput,normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{emitConnectManifest}from"#internal/external-resources.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{normalizeVercelServiceCrons}from"#internal/nitro/host/normalize-vercel-service-crons.js";import{prepareProductionApplicationHost,refreshProductionCompiledArtifacts}from"#internal/nitro/host/prepare-application-host.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{prewarmAppSandboxes}from"#execution/sandbox/prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";import{resolveEveServicePrefixByRoot}from"#internal/vercel/vercel-service-config-operations.js";import{parseVercelServicesConfig}from"#internal/vercel/vercel-services-config.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}async function measureBuildPhase(e,t,n){return e===void 0?n():e.measure(t,n)}function isPathInside(e,t){let n=relative(e,t);return n.length===0||!n.startsWith(`..${sep}`)&&n!==`..`&&!isAbsolute(n)}function assertProfileOutputOutsideBuildOutput(e,t){if(e!==void 0&&isPathInside(t,e))throw Error(`Build profile path ${e} must be outside the published output directory ${t}.`)}async function writeOptionalApplicationBuildProfile(e){try{assertProfileOutputOutsideBuildOutput(e.profileOutputPath,e.outputDirectory);let t=e.profiler.finish(),n=await measureApplicationBuildOutput(e.outputDirectory);await writeApplicationBuildProfile(e.profileOutputPath,createApplicationBuildProfile({deploymentId:e.deploymentId,output:n,target:process.env.VERCEL?`vercel`:`local`,timing:t}))}catch(t){console.warn(`eve: failed to write optional build profile to ${e.profileOutputPath}; continuing with the published build output: ${toErrorMessage(t)}`)}}async function resolveEveServicePrefixForVercelFunctionOutput(e,t){let n=Array.from(new Set([resolve(e),resolve(t)])),r=await findClosestVercelOutputDirectory(e);if(r!==void 0)try{let e=join(r,`config.json`),t=parseVercelServicesConfig(JSON.parse(await readFile(e,`utf8`)),e),i=resolveEveServicePrefixByRoot({appRoots:n,configRoot:await resolveVercelOutputConfigRoot(r),config:t});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let i=e;for(;;){for(let e of[join(i,`vercel.json`),join(i,`.vercel`,`output`,`config.json`)])try{let t=parseVercelServicesConfig(JSON.parse(await readFile(e,`utf8`)),e),r=e.endsWith(`vercel.json`)?i:await resolveVercelOutputConfigRoot(dirname(e)),a=resolveEveServicePrefixByRoot({appRoots:n,configRoot:r,config:t});if(a!==void 0)return a}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(i);if(e===i)return;i=e}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isObject(e)&&isObject(e.settings)){let n=e.settings.rootDirectory;if(typeof n==`string`&&n.trim().length>0)return resolve(t,n)}}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function buildNitroOutput(e,t,n){let r=trimTrailingSlash(e.options.output.dir);return await measureBuildPhase(t,`${n}.cache.prepare`,()=>prepareEveVersionedCacheDirectory(r)),await measureBuildPhase(t,`${n}.prepare`,()=>prepare(e)),await measureBuildPhase(t,`${n}.public-assets`,()=>copyPublicAssets(e)),await measureBuildPhase(t,`${n}.prerender`,()=>prerender(e)),await measureBuildPhase(t,`${n}.bundle`,()=>build(e)),await measureBuildPhase(t,`${n}.cache.write`,()=>writeEveVersionedCacheMetadata(r)),r}async function buildApplication(e,t){let n=t.profileOutputPath===void 0?void 0:resolve(t.profileOutputPath),r=n===void 0?void 0:new ApplicationBuildProfiler,i=await measureBuildPhase(r,`extension.check`,()=>tryReadExtensionBuildConfig(e));if(i!==null)throw Error(`Package "${i.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let a=await measureBuildPhase(r,`project.resolve`,()=>resolveDiscoveryProject(e)),o=await measureBuildPhase(r,`workspace.create`,()=>createApplicationBuildWorkspace(a.appRoot,t.vercelServiceOutput?.serviceOutputDirectory)),s=!1,c;try{c=await buildApplicationInWorkspace(o,t,r)}catch(e){throw s=e instanceof RecoverablePublicationError,e}finally{s||await measureBuildPhase(r,`workspace.remove`,()=>removeApplicationBuildWorkspace(o))}return r!==void 0&&n!==void 0&&await writeOptionalApplicationBuildProfile({deploymentId:c.deploymentId,outputDirectory:c.outputDirectory,profileOutputPath:n,profiler:r}),c.outputDirectory}async function buildApplicationInWorkspace(e,t,n){let r=await measureBuildPhase(n,`host.prepare`,()=>prepareProductionApplicationHost(e)),i=!!process.env.VERCEL,a=i?await measureBuildPhase(n,`vercel.service-prefix.resolve`,()=>resolveEveServicePrefixForVercelFunctionOutput(r.appRoot,r.compileResult.project.agentRoot)):void 0,o=normalizePublicRoutePrefix(a),s=o===EVE_ROUTE_PREFIX?void 0:o;if(t.publicRoutePrefix!==void 0&&s!==void 0&&t.publicRoutePrefix!==s)throw Error(`EVE_PUBLIC_ROUTE_PREFIX ${JSON.stringify(t.publicRoutePrefix)} conflicts with the configured Vercel service prefix ${JSON.stringify(a)}.`);let c=t.publicRoutePrefix??s,l=createProductionNitroArtifactsConfig(e.appRoot).sandboxScope,u=await measureBuildPhase(n,`nitro.create`,()=>createProductionApplicationNitro(r,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,publicRoutePrefix:c,workspaceMember:t.workspaceMember}));try{if(!t.skipSandboxPrewarm){let t={appRoot:r.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:r.appRoot,sandboxScope:l}),log(e){console.log(e)}};await measureBuildPhase(n,`sandbox.prewarm`,async()=>{i?await runVercelBuildPrewarm(t):await prewarmAppSandboxes(t)}),await refreshProductionCompiledArtifacts(r,e.host.artifactsDir)}await buildNitroOutput(u,n,`nitro`),i&&await measureBuildPhase(n,`vercel.workflow-function.materialize`,()=>materializeVercelWorkflowFunctionOutput(e.publication.output.stagedDir)),a!==void 0&&await measureBuildPhase(n,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:a}));let o=t.vercelServiceOutput;o!==void 0&&(await measureBuildPhase(n,`vercel.service-crons.normalize`,()=>normalizeVercelServiceCrons({publicRoutePrefix:c,serviceOutputDirectory:e.publication.output.stagedDir})),await measureBuildPhase(n,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:o.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir}))),await measureBuildPhase(n,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:r.compileResult.manifest,outputPath:e.publication.summary.stagedPath})),await measureBuildPhase(n,`connect-manifest.emit`,()=>emitConnectManifest({appRoot:r.appRoot,generatorVersion:resolveInstalledPackageInfo().version,manifest:r.compileResult.manifest,outputDirectory:e.publication.output.stagedDir,publicRoutePrefix:c})),i||await measureBuildPhase(n,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir}))}finally{await measureBuildPhase(n,`nitro.close`,()=>u.close())}let d=u.options.preset===`node-server`?await measureBuildPhase(n,`id.compute`,()=>stageBuildDeploymentId(e.publication.output.stagedDir)):void 0;return await measureBuildPhase(n,`output.publish`,()=>publishCompletedApplicationBuild(e)),{deploymentId:d,outputDirectory:e.publication.output.finalDir}}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const BUILD_DEPLOYMENT_ID_PLACEHOLDER = "eve_BUILD_DEPLOYMENT_ID_PLACEHOLDER_";
|
|
2
|
+
export interface BuildDeploymentFile {
|
|
3
|
+
readonly relativePath: string;
|
|
4
|
+
readonly bytes: Uint8Array;
|
|
5
|
+
}
|
|
6
|
+
/** Hashes files in path order while holding at most `READ_AHEAD` files in memory. */
|
|
7
|
+
export declare function computeBuildDeploymentId(relativePaths: readonly string[], readBytes: (relativePath: string) => Promise<Uint8Array>, extraInputs?: readonly string[]): Promise<string>;
|
|
8
|
+
export declare function replaceBuildDeploymentId(files: readonly BuildDeploymentFile[], deploymentId: string): BuildDeploymentFile;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash}from"node:crypto";import{BUILD_DEPLOYMENT_ID_PATTERN}from"#execution/install-workflow-deployment-id.js";const BUILD_DEPLOYMENT_ID_PLACEHOLDER=`eve_BUILD_DEPLOYMENT_ID_PLACEHOLDER_`;async function computeBuildDeploymentId(e,t,n=[]){let r=createHash(`sha256`),append=e=>{r.update(`${e.byteLength}:`),r.update(e)};r.update(`eve-build-v1\0`);let i=e.filter(e=>e!==`nitro.json`).sort((e,t)=>e<t?-1:+(e>t)),a=[],startRead=e=>{if(e>=i.length)return;let n=t(i[e]);n.catch(()=>void 0),a[e]=n};for(let e=0;e<16;e++)startRead(e);for(let e=0;e<i.length;e++){let t=await a[e];delete a[e],startRead(e+16),r.update(`file\0`),append(Buffer.from(i[e])),append(t)}for(let e of[...n].sort())r.update(`input\0`),append(Buffer.from(e));return`eve_${r.digest(`hex`).slice(0,32)}`}function replaceBuildDeploymentId(e,t){let n=Buffer.from(BUILD_DEPLOYMENT_ID_PLACEHOLDER),r=Buffer.from(t);if(!BUILD_DEPLOYMENT_ID_PATTERN.test(t)||r.length!==n.length)throw Error(`Invalid build deployment id: expected eve_ followed by 32 lowercase hex characters.`);let i,a=0;for(let t of e){let e=Buffer.from(t.bytes);for(let r=e.indexOf(n);r!==-1;r=e.indexOf(n,r+n.length))a++,i={file:t,offset:r}}if(a!==1||i===void 0)throw Error(`Cannot install build deployment id: expected exactly one workflow-world placeholder in server/**/*.mjs outside node_modules, found ${a}. This is an eve bug; please report it.`);let o=Buffer.from(i.file.bytes);return r.copy(o,i.offset),{relativePath:i.file.relativePath,bytes:o}}export{BUILD_DEPLOYMENT_ID_PLACEHOLDER,computeBuildDeploymentId,replaceBuildDeploymentId};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-loader.js";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{hasVercelScheduleCollections,usesLocalVercelSchedules}from"#internal/schedules/consumer-route.js";import{configureInstrumentationEntry}from"#internal/nitro/host/instrumentation-entry.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{createDevelopmentRuntimePrunePlugin}from"#internal/nitro/host/development-runtime-prune-plugin.js";import{prepareSkillServerAssets}from"#internal/nitro/host/skill-server-assets.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createExternalDependencyOutputCheckPlugin}from"#internal/nitro/host/external-dependency-output-check-plugin.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),EVE_NITRO_BUILDER=`rolldown`,LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=collectConfiguredExternalDependencies(e.compileResult.manifest);return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectConfiguredExternalDependencies(e){return[...e.config.build?.externalDependencies??[],...e.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let{preset:n}=t,r=collectConfiguredSandboxProviderNames(e.compileResult.manifest),i=shouldPruneLocalSandboxProviders({configuredBackendNames:r,preset:n})?createCompiledSandboxProviderPrunePlugin():null,a=[],o=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(r.has(e)?a:o).push(t);let s=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,mountId:e.mountId})))),c=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),l=[t.development?null:createDevelopmentRuntimePrunePlugin(),i,createOptionalEngineDependencyPlugin(o),createExtensionExternalDependencyPlugin(c),t.development?null:createExternalDependencyOutputCheckPlugin({appRoot:e.appRoot,externalDependencies:collectConfiguredExternalDependencies(e.compileResult.manifest)}),createExtensionMountPlugin(c,extensionOverridePaths(e.compileResult.manifest)),s].filter(e=>e!==null);return{nitroRolldownConfig:{output:{sourcemapIgnoreList:/node_modules/},tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(l),tracedAppDependencies:collectHostedTraceDependencies(e,a),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(c)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){t.compiledArtifacts.instrumentationPluginPath!==void 0&&configureInstrumentationEntry(e,t.compiledArtifacts.instrumentationPluginPath),addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,{development:!0,preset:void 0}),r=createApplicationNitroPlugins(e);usesLocalVercelSchedules(e.compileResult.manifest)&&r.push(resolvePackageSourceFilePath(`src/internal/nitro/host/local-schedules-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},builder:EVE_NITRO_BUILDER,buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,{development:!1,preset:n}),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let{manifest:a,paths:o}=e.compileResult,s=await prepareSkillServerAssets({stagingDirectory:join(t.buildDir,`eve-skill-assets`),skills:a.skills.map(e=>e.name),skillsRoot:join(o.compileDirectoryPath,a.workspaceResourceRoot.logicalPath,`skills`)}),c=await createNitro({_cli:{command:`build`},builder:EVE_NITRO_BUILDER,buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},logging:{compressedSizes:!1},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverAssets:s,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,hasVercelScheduleCollections:hasVercelScheduleCollections(e.compileResult.manifest),publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),c.options.serverAssets=c.options.serverAssets.filter(e=>e.baseName!==`server`),configureSharedApplicationNitro(c,e),configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(c);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(c,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(c,e),await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
|
|
1
|
+
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-build-options.js";import{createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{hasVercelScheduleCollections,usesLocalVercelSchedules}from"#internal/schedules/consumer-route.js";import{configureInstrumentationEntry}from"#internal/nitro/host/instrumentation-entry.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{createDevelopmentRuntimePrunePlugin}from"#internal/nitro/host/development-runtime-prune-plugin.js";import{prepareSkillServerAssets}from"#internal/nitro/host/skill-server-assets.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createExternalDependencyOutputCheckPlugin}from"#internal/nitro/host/external-dependency-output-check-plugin.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),EVE_NITRO_BUILDER=`rolldown`,LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=collectConfiguredExternalDependencies(e.compileResult.manifest);return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectConfiguredExternalDependencies(e){return[...e.config.build?.externalDependencies??[],...e.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let{preset:n}=t,r=collectConfiguredSandboxProviderNames(e.compileResult.manifest),i=shouldPruneLocalSandboxProviders({configuredBackendNames:r,preset:n})?createCompiledSandboxProviderPrunePlugin():null,a=[],o=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(r.has(e)?a:o).push(t);let s=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,mountId:e.mountId})))),c=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),l=[t.development?null:createDevelopmentRuntimePrunePlugin(),i,createOptionalEngineDependencyPlugin(o),createExtensionExternalDependencyPlugin(c),t.development?null:createExternalDependencyOutputCheckPlugin({appRoot:e.appRoot,externalDependencies:collectConfiguredExternalDependencies(e.compileResult.manifest)}),createExtensionMountPlugin(c,extensionOverridePaths(e.compileResult.manifest)),s].filter(e=>e!==null);return{nitroRolldownConfig:{output:{sourcemapIgnoreList:/node_modules/},tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(l),tracedAppDependencies:collectHostedTraceDependencies(e,a),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(c)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){t.compiledArtifacts.instrumentationPluginPath!==void 0&&configureInstrumentationEntry(e,t.compiledArtifacts.instrumentationPluginPath),addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,{development:!0,preset:void 0}),r=createApplicationNitroPlugins(e);usesLocalVercelSchedules(e.compileResult.manifest)&&r.push(resolvePackageSourceFilePath(`src/internal/nitro/host/local-schedules-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},builder:EVE_NITRO_BUILDER,buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,{development:!1,preset:n}),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let{manifest:a,paths:o}=e.compileResult,s=await prepareSkillServerAssets({stagingDirectory:join(t.buildDir,`eve-skill-assets`),skills:a.skills.map(e=>e.name),skillsRoot:join(o.compileDirectoryPath,a.workspaceResourceRoot.logicalPath,`skills`)}),c=await createNitro({_cli:{command:`build`},builder:EVE_NITRO_BUILDER,buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},logging:{compressedSizes:!1},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:{...r.nitroRolldownConfig,experimental:{attachDebugInfo:`none`}},rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverAssets:s,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,hasVercelScheduleCollections:hasVercelScheduleCollections(e.compileResult.manifest),publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),c.options.serverAssets=c.options.serverAssets.filter(e=>e.baseName!==`server`),configureSharedApplicationNitro(c,e),configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(c);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(c,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(c,e),await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir,readFile,rm,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{httpServerUrlSchema}from"#shared/network-address.js";import{join}from"node:path";const developmentServerStateSchema=z.object({url:httpServerUrlSchema}).strict();var DevelopmentServerState=class{appRoot;#e;#t;constructor(e){this.appRoot=e.appRoot,this.#e=
|
|
1
|
+
import{mkdir,readFile,rm,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{httpServerUrlSchema}from"#shared/network-address.js";import{join}from"node:path";import{resolveDevelopmentStateDirectory}from"#internal/application/dev-environment.js";const developmentServerStateSchema=z.object({url:httpServerUrlSchema}).strict();var DevelopmentServerState=class{appRoot;#e;#t;constructor(e){this.appRoot=e.appRoot,this.#e=resolveDevelopmentStateDirectory(this.appRoot),this.#t=join(this.#e,`dev-server-state.v1.json`)}async read(){let e;try{e=await readFile(this.#t,`utf8`)}catch(e){if(isErrnoException(e,`ENOENT`))return;throw e}try{let t=developmentServerStateSchema.safeParse(JSON.parse(e));return t.success?t.data.url:void 0}catch{return}}async write(e){let t=developmentServerStateSchema.parse({url:e});await mkdir(this.#e,{recursive:!0}),await writeFile(this.#t,`${JSON.stringify(t)}\n`,`utf8`)}async remove(){await rm(this.#t,{force:!0})}};function isErrnoException(e,t){return e instanceof Error&&`code`in e&&e.code===t}export{DevelopmentServerState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{mkdir,rm,writeFile}from"node:fs/promises";import{MAX_SKILL_FILE_BYTES,SKILL_FILES_INDEX_KEY,SKILL_FILES_INDEX_SERVER_ASSET_BASE,SKILL_FILES_SERVER_ASSET_BASE,comparePaths,createDiskSkillFileSource,skillFileStorageKey}from"#channel/skill-files.js";import{join,resolve}from"node:path";async function prepareSkillServerAssets(e){let t=createDiskSkillFileSource(resolve(e.skillsRoot)),n=join(e.stagingDirectory,`files`),r=join(e.stagingDirectory,`index`);await rm(e.stagingDirectory,{force:!0,recursive:!0}),await mkdir(n,{recursive:!0}),await mkdir(r,{recursive:!0});let i=[];for(let r of[...new Set(e.skills)].sort(comparePaths)){let e=[];for(let{path:i,size:a}of await t.listFiles(r)){if(a>MAX_SKILL_FILE_BYTES){e.push([i,a,null]);continue}let o=await t.readFile(r,i),s=createHash(`sha256`).update(o).digest(`hex`)
|
|
1
|
+
import{createHash}from"node:crypto";import{mkdir,rm,utimes,writeFile}from"node:fs/promises";import{MAX_SKILL_FILE_BYTES,SKILL_FILES_INDEX_KEY,SKILL_FILES_INDEX_SERVER_ASSET_BASE,SKILL_FILES_SERVER_ASSET_BASE,comparePaths,createDiskSkillFileSource,skillFileStorageKey}from"#channel/skill-files.js";import{join,resolve}from"node:path";async function prepareSkillServerAssets(e){let t=createDiskSkillFileSource(resolve(e.skillsRoot)),n=join(e.stagingDirectory,`files`),r=join(e.stagingDirectory,`index`);await rm(e.stagingDirectory,{force:!0,recursive:!0}),await mkdir(n,{recursive:!0}),await mkdir(r,{recursive:!0});let i=[];for(let r of[...new Set(e.skills)].sort(comparePaths)){let e=[];for(let{path:i,size:a}of await t.listFiles(r)){if(a>MAX_SKILL_FILE_BYTES){e.push([i,a,null]);continue}let o=await t.readFile(r,i),s=createHash(`sha256`).update(o).digest(`hex`),c=join(n,skillFileStorageKey(s));await writeFile(c,o),await utimes(c,0,0),e.push([i,o.byteLength,s])}i.push([r,e,await t.listDirectories(r)])}let a={version:1,skills:i},o=join(r,SKILL_FILES_INDEX_KEY);return await writeFile(o,JSON.stringify(a)),await utimes(o,0,0),[{baseName:SKILL_FILES_INDEX_SERVER_ASSET_BASE,dir:r},{baseName:SKILL_FILES_SERVER_ASSET_BASE,dir:n}]}export{prepareSkillServerAssets};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire}from"node:module";import{readFile,readdir,realpath,stat,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{BUILD_DEPLOYMENT_ID_PLACEHOLDER,computeBuildDeploymentId,replaceBuildDeploymentId}from"#internal/nitro/host/build-deployment-id.js";async function optionalPeerIdentity(e){let t=createRequire(join(e,`server`,`index.mjs`)),n;try{n=t.resolve(`@opentelemetry/api`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`MODULE_NOT_FOUND`)return`@opentelemetry/api@absent`;throw e}for(let e=dirname(n);;e=dirname(e)){try{let t=JSON.parse(await readFile(join(e,`package.json`),`utf8`));if(typeof t==`object`&&t&&`name`in t&&t.name===`@opentelemetry/api`&&`version`in t&&typeof t.version==`string`)return`@opentelemetry/api@${t.version}`}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}if(dirname(e)===e)throw Error(`Cannot compute build deployment id: @opentelemetry/api has no package version.`)}}function mayContainPlaceholder(e){return e.startsWith(`server/`)&&e.endsWith(`.mjs`)&&!e.split(`/`).includes(`node_modules`)}async function stageBuildDeploymentId(e){let t=[];async function walk(n,r){let i=join(e,n),a=await realpath(i);if(r.has(a))throw Error(`Cannot hash build output: cyclic directory link at ${n}.`);let o=new Set([...r,a]);for(let r of await readdir(i,{withFileTypes:!0})){let i=n?`${n}/${r.name}`:r.name,a=r.isSymbolicLink()?await stat(join(e,i)):r;if(a.isDirectory())await walk(i,o);else if(a.isFile())t.push(i);else throw Error(`Cannot hash build output: unsupported file type at ${i}.`)}}await walk(``,new Set);let n=Buffer.from(BUILD_DEPLOYMENT_ID_PLACEHOLDER),r=[],i=await computeBuildDeploymentId(t,async t=>{let i=await readFile(join(e,t));return mayContainPlaceholder(t)&&i.includes(n)&&r.push({relativePath:t,bytes:i}),i},[`eve@${resolveInstalledPackageInfo().version}`,`node@${process.version}`,await optionalPeerIdentity(e)]),a=replaceBuildDeploymentId(r,i);return await writeFile(join(e,a.relativePath),a.bytes),i}export{stageBuildDeploymentId};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createConnection,createServer}from"node:net";import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{spawn}from"node:child_process";import{setTimeout}from"node:timers/promises";const HEALTH_TIMEOUT_MS=6e4,LOCAL_SERVER_URL_PATTERN=/https?:\/\/(?:\[[^\]\s]+\]|[^\s/:[\]]+)(?::\d+)?/,WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`,`0.0.0.0`]);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 isListening(e){let t=new URL(e),n=Number(t.port||(t.protocol===`https:`?443:80));return await new Promise(e=>{let r=createConnection({host:t.hostname,port:n}),finish=t=>{r.destroy(),e(t)};r.setTimeout(2e3,()=>finish(!1)),r.once(`connect`,()=>finish(!0)),r.once(`error`,()=>finish(!1))})}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()),r=n??e.knownUrl;if(r!==void 0&&(n!==void 0||await isListening(r)))return new URL(r).toString();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(2e4).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,t={}){let n=resolve(e),r=resolveOutputServerEntry(n);if(!existsSync(r))throw Error(`Missing eve build output at ${r}. Run "eve build" before "eve start".`);await loadDevelopmentEnvironmentFiles(n);let i=t.host??`0.0.0.0`,a=await resolveListenPort({host:i,port:t.port??readEnvironmentPort()??3e3}),o=createKnownPortUrl({host:i,port:a}),s=``,c=!1,l=!1,u,d=
|
|
3
|
-
`)))})});
|
|
1
|
+
import{createConnection,createServer}from"node:net";import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{spawn}from"node:child_process";import{EVE_SCHEDULES_DISABLED_ENV}from"#internal/schedules/disabled.js";import{setTimeout}from"node:timers/promises";const HEALTH_TIMEOUT_MS=6e4,LOCAL_SERVER_URL_PATTERN=/https?:\/\/(?:\[[^\]\s]+\]|[^\s/:[\]]+)(?::\d+)?/,WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`,`0.0.0.0`]);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 isListening(e){let t=new URL(e),n=Number(t.port||(t.protocol===`https:`?443:80));return await new Promise(e=>{let r=createConnection({host:t.hostname,port:n}),finish=t=>{r.destroy(),e(t)};r.setTimeout(2e3,()=>finish(!1)),r.once(`connect`,()=>finish(!0)),r.once(`error`,()=>finish(!1))})}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()),r=n??e.knownUrl;if(r!==void 0&&(n!==void 0||await isListening(r)))return new URL(r).toString();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(2e4).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,t={}){let n=resolve(e),r=resolveOutputServerEntry(n);if(!existsSync(r))throw Error(`Missing eve build output at ${r}. Run "eve build" before "eve start".`);await loadDevelopmentEnvironmentFiles(n);let i=t.host??`0.0.0.0`,a=await resolveListenPort({host:i,port:t.port??readEnvironmentPort()??3e3}),o=createKnownPortUrl({host:i,port:a}),s=``,c=!1,l=!1,u,d={...process.env,HOST:i,NITRO_HOST:i,NITRO_PORT:String(a),PORT:String(a)};t.schedules===!1&&(d[EVE_SCHEDULES_DISABLED_ENV]=`1`);let f=spawn(process.execPath,[r],{cwd:n,env:d,stdio:[`ignore`,`pipe`,`pipe`]});f.stdout?.on(`data`,e=>{c||(s+=e.toString(`utf8`)),process.stdout.write(e)}),f.stderr?.on(`data`,e=>{c||(s+=e.toString(`utf8`)),process.stderr.write(e)});let p=new Promise((e,t)=>{f.once(`error`,e=>{u=e,t(e)}),f.once(`exit`,(n,r)=>{if(l||n===0){e();return}t(Error([`Built server process exited unexpectedly (code=${String(n)}, signal=${String(r)}).`,s].join(`
|
|
3
|
+
`)))})});p.catch(()=>void 0);try{let e=await waitForReady({child:f,getStartError:()=>u,getOutput:()=>s,knownUrl:o});return c=!0,s=``,{async close(){l=!0,await terminate(f)},url:e,async wait(){await p}}}catch(e){throw l=!0,await terminate(f),e instanceof Error&&e.name===`AbortError`?Error(`Timed out waiting for built eve server to respond.`,{cause:e}):e}}export{startProductionServer};
|
|
@@ -10,6 +10,9 @@ import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts
|
|
|
10
10
|
export declare function dispatchScheduleTask(taskName: string, config: NitroArtifactsConfig): Promise<{
|
|
11
11
|
scheduleId: string;
|
|
12
12
|
sessionIds: readonly string[];
|
|
13
|
+
} | {
|
|
14
|
+
skipped: "schedules-disabled";
|
|
15
|
+
taskName: string;
|
|
13
16
|
}>;
|
|
14
17
|
/**
|
|
15
18
|
* Variant of {@link dispatchScheduleTask} for callers that already resolved
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{loadResolvedCompiledScheduleByTaskName}from"#runtime/schedules/resolve-schedule.js";import{ScheduleDispatcher,expectScheduleRun}from"#channel/schedule.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";async function dispatchScheduleTask(e,t){return await dispatchScheduleTaskFromArtifacts(e,resolveNitroCompiledArtifactsSource(t))}async function dispatchScheduleTaskFromArtifacts(e,t){let n=await loadResolvedCompiledScheduleByTaskName(e,{compiledArtifactsSource:t}),r=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:t}),i=createWorkflowRuntime({compiledArtifactsSource:t}),a=new ScheduleDispatcher({runtime:i,channels:r.graph.root.channels}),o={scheduleId:n.name};n.hasRun&&(o.run=await loadScheduleRun(n,r.moduleMap)),n.markdown!==void 0&&(o.markdown=n.markdown);let s=await a.trigger(o);return s.waitUntilTasks.length>0&&await Promise.allSettled(s.waitUntilTasks),{scheduleId:n.name,sessionIds:s.sessions.map(e=>e.id)}}async function loadScheduleRun(e,t){if(e.sourceKind!==`module`)throw Error(`Schedule "${e.name}" claims hasRun but is not a module-backed schedule.`);let n=e,r=await loadResolvedModuleExport({definition:{exportName:n.exportName,logicalPath:n.logicalPath,sourceId:n.sourceId},kindLabel:`schedule`,moduleMap:t,nodeId:void 0});return expectScheduleRun(r,n.logicalPath,n.exportName)}export{dispatchScheduleTask,dispatchScheduleTaskFromArtifacts};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{EVE_SCHEDULES_DISABLED_ENV,areSchedulesDisabled}from"#internal/schedules/disabled.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{loadResolvedCompiledScheduleByTaskName}from"#runtime/schedules/resolve-schedule.js";import{ScheduleDispatcher,expectScheduleRun}from"#channel/schedule.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";const log=createLogger(`schedule.dispatch`);let loggedSchedulesDisabled=!1;async function dispatchScheduleTask(e,t){return areSchedulesDisabled()?(loggedSchedulesDisabled||(loggedSchedulesDisabled=!0,log.info(`Schedules are disabled in this process (${EVE_SCHEDULES_DISABLED_ENV}); skipping "${e}"`)),{skipped:`schedules-disabled`,taskName:e}):await dispatchScheduleTaskFromArtifacts(e,resolveNitroCompiledArtifactsSource(t))}async function dispatchScheduleTaskFromArtifacts(e,t){let n=await loadResolvedCompiledScheduleByTaskName(e,{compiledArtifactsSource:t}),r=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:t}),i=createWorkflowRuntime({compiledArtifactsSource:t}),a=new ScheduleDispatcher({runtime:i,channels:r.graph.root.channels}),o={scheduleId:n.name};n.hasRun&&(o.run=await loadScheduleRun(n,r.moduleMap)),n.markdown!==void 0&&(o.markdown=n.markdown);let s=await a.trigger(o);return s.waitUntilTasks.length>0&&await Promise.allSettled(s.waitUntilTasks),{scheduleId:n.name,sessionIds:s.sessions.map(e=>e.id)}}async function loadScheduleRun(e,t){if(e.sourceKind!==`module`)throw Error(`Schedule "${e.name}" claims hasRun but is not a module-backed schedule.`);let n=e,r=await loadResolvedModuleExport({definition:{exportName:n.exportName,logicalPath:n.logicalPath,sourceId:n.sourceId},kindLabel:`schedule`,moduleMap:t,nodeId:void 0});return expectScheduleRun(r,n.logicalPath,n.exportName)}export{dispatchScheduleTask,dispatchScheduleTaskFromArtifacts};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{memoizeModuleNamespaceFactories}from"#compiler/source-graph.js";import{loadFrameworkProgrammaticModule}from"#framework/sources/registry.js";export{loadFrameworkProgrammaticModule,memoizeModuleNamespaceFactories};
|
|
1
|
+
import{interopAuthoredModuleNamespace}from"#internal/authored-module.js";import{memoizeModuleNamespaceFactories}from"#compiler/source-graph.js";import{loadFrameworkProgrammaticModule}from"#framework/sources/registry.js";export{interopAuthoredModuleNamespace,loadFrameworkProgrammaticModule,memoizeModuleNamespaceFactories};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const EVE_SCHEDULES_DISABLED_ENV=`EVE_SCHEDULES_DISABLED`;function areSchedulesDisabled(e=process.env){let t=e[EVE_SCHEDULES_DISABLED_ENV]?.toLowerCase();return t===`1`||t===`true`}export{EVE_SCHEDULES_DISABLED_ENV,areSchedulesDisabled};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_SECRET_ENV,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldJson,decodeDevelopmentWorldValue,deserializeDevelopmentWorldError,encodeDevelopmentWorldValue}from"#internal/workflow/development-world-codec.js";import{getDevelopmentWorkflowGeneration,withDevelopmentWorkflowGeneration}from"#internal/workflow/development-generation-context.js";import{cancelExpiredDevelopmentRun}from"#internal/workflow/cancel-expired-development-run.js";var MissingDevelopmentGenerationError=class extends Error{constructor(e,t){super(`Workflow run references missing development generation "${e}". Start a new local session.`,t===void 0?void 0:{cause:t}),this.name=`MissingDevelopmentGenerationError`}};async function call(e,t=[]){let n=await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE,{body:encodeDevelopmentWorldValue({arguments:t,operation:e}),method:`POST`});return decodeDevelopmentWorldValue(await n.text())}async function getGenerationAvailability(e){let t=await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE,{body:encodeDevelopmentWorldValue({operation:`eve.getGenerationAvailability`,generationId:e}),method:`POST`});return decodeDevelopmentWorldValue(await t.text())}function createDevelopmentWorkflowWorld(){let e=buildForwardedOperations();return{specVersion:8,async getDeploymentId(){return getDevelopmentWorkflowGeneration()?.generationId??await call(`getDeploymentId`)},resolveLatestDeploymentId:e.topLevel.resolveLatestDeploymentId,queue:e.topLevel.queue,createQueueHandler,runs:e.groups.runs,steps:e.groups.steps,events:e.groups.events,hooks:e.groups.hooks,streams:{...e.groups.streams,get:async(e,t,n)=>{let r=new URL(resolveDevelopmentWorldBaseUrl());r.pathname=DEVELOPMENT_WORKFLOW_STREAM_ROUTE,r.searchParams.set(`runId`,e),r.searchParams.set(`name`,t),n!==void 0&&r.searchParams.set(`startIndex`,String(n));let i=await fetchDevelopmentWorld(r,{method:`GET`});if(i.body===null)throw Error(`Development Workflow stream response had no body.`);return i.body}},async start(){},async close(){}}}function buildForwardedOperations(){let e={},t={};for(let n of DEVELOPMENT_WORLD_OPERATIONS){let forward=async(...e)=>await call(n,e),r=n.indexOf(`.`);r===-1?t[n]=forward:(e[n.slice(0,r)]??={})[n.slice(r+1)]=forward}return{groups:e,topLevel:t}}function createQueueHandler(e,t){return async n=>{let r=readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV),i=n.headers.get(DEVELOPMENT_WORKFLOW_DELIVERY_HEADER);if(i===null||!timingSafeEqualStrings(i,r))return Response.json({error:`Workflow delivery is not trusted.`},{status:401});let a=n.headers.get(`x-vqs-queue-name`),o=n.headers.get(`x-vqs-message-id`),s=Number(n.headers.get(`x-vqs-message-attempt`));if(a===null||!a.startsWith(e)||o===null||!Number.isInteger(s)||s<1||n.body===null)return Response.json({error:`Workflow delivery is malformed.`},{status:400});let c=decodeDevelopmentWorldJson(await n.text());try{let e=readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV),n=await resolveDeliveryGenerationId(c);if(n===void 0)return Response.json({ok:!0});let r=await getGenerationAvailability(n);if(r.kind===`missing`)throw new MissingDevelopmentGenerationError(n);if(r.kind===`ineligible`||r.kind===`dormant`)return Response.json({ok:!0});let i=r.runtimeAppRoot,l=await withDevelopmentWorkflowGeneration({generationId:n,source:createDiskRuntimeCompiledArtifactsSource(i,{durableReference:`development-generation`,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:e})},async()=>await t(c,{attempt:s,messageId:o,queueName:a}));return Response.json(l===void 0?{ok:!0}:{timeoutSeconds:l.timeoutSeconds})}catch(e){if(e instanceof MissingDevelopmentGenerationError){let e=resolveDeliveryRunId(c);if(e!==void 0)try{await cancelExpiredDevelopmentRun(createDevelopmentWorkflowWorld(),e)}catch(e){return Response.json(String(e),{status:500})}return Response.json({ok:!0})}return Response.json(String(e),{status:500})}}}async function resolveDeliveryGenerationId(e){if(!isRecord(e)||e.__healthCheck===!0)return await call(`resolveLatestDeploymentId`);let t=isRecord(e.runInput)?e.runInput:void 0;if(t!==void 0)return typeof t.deploymentId==`string`?t.deploymentId:await call(`resolveLatestDeploymentId`);let n=resolveDeliveryRunId(e);if(n===void 0)return await call(`resolveLatestDeploymentId`);try{return(await call(`runs.get`,[n,{resolveData:`none`}])).deploymentId}catch(e){if(!isMissingWorkflowRunError(e))throw e;return}}function resolveDeliveryRunId(e){if(isRecord(e)&&e.__healthCheck!==!0)return typeof e.runId==`string`?e.runId:typeof e.workflowRunId==`string`?e.workflowRunId:void 0}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function fetchDevelopmentWorld(e,t){let n=e instanceof URL?e:new URL(e,resolveDevelopmentWorldBaseUrl()),r=new Headers(t.headers);r.set(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV));let i=await fetch(n,{...t,headers:r});if(!i.ok){let e=await i.text(),t=readDevelopmentWorldError(e);throw t===void 0?Error(`Development Workflow World request failed (${String(i.status)}): ${e}`):t}return i}function readDevelopmentWorldError(e){try{return deserializeDevelopmentWorldError(decodeDevelopmentWorldValue(e))}catch{return}}function resolveDevelopmentWorldBaseUrl(){return readRequiredEnvironment(`WORKFLOW_LOCAL_BASE_URL`)}function readRequiredEnvironment(e){let t=process.env[e];if(t===void 0||t.length===0)throw Error(`Development Workflow transport is missing ${e}.`);return t}export{MissingDevelopmentGenerationError,createDevelopmentWorkflowWorld};
|
|
1
|
+
import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_SECRET_ENV,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldJson,decodeDevelopmentWorldValue,deserializeDevelopmentWorldError,encodeDevelopmentWorldValue}from"#internal/workflow/development-world-codec.js";import{getDevelopmentWorkflowGeneration,withDevelopmentWorkflowGeneration}from"#internal/workflow/development-generation-context.js";import{cancelExpiredDevelopmentRun}from"#internal/workflow/cancel-expired-development-run.js";var MissingDevelopmentGenerationError=class extends Error{constructor(e,t){super(`Workflow run references missing development generation "${e}". Start a new local session.`,t===void 0?void 0:{cause:t}),this.name=`MissingDevelopmentGenerationError`}};async function call(e,t=[]){let n=await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE,{body:encodeDevelopmentWorldValue({arguments:t,operation:e}),method:`POST`});return decodeDevelopmentWorldValue(await n.text())}async function getGenerationAvailability(e){let t=await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE,{body:encodeDevelopmentWorldValue({operation:`eve.getGenerationAvailability`,generationId:e}),method:`POST`});return decodeDevelopmentWorldValue(await t.text())}function createDevelopmentWorkflowWorld(){let e=buildForwardedOperations();return{specVersion:8,capabilities:{hookForceClaim:!0,hookRetention:{active:!0}},async getDeploymentId(){return getDevelopmentWorkflowGeneration()?.generationId??await call(`getDeploymentId`)},resolveLatestDeploymentId:e.topLevel.resolveLatestDeploymentId,queue:e.topLevel.queue,createQueueHandler,runs:e.groups.runs,steps:e.groups.steps,events:e.groups.events,hooks:e.groups.hooks,streams:{...e.groups.streams,get:async(e,t,n)=>{let r=new URL(resolveDevelopmentWorldBaseUrl());r.pathname=DEVELOPMENT_WORKFLOW_STREAM_ROUTE,r.searchParams.set(`runId`,e),r.searchParams.set(`name`,t),n!==void 0&&r.searchParams.set(`startIndex`,String(n));let i=await fetchDevelopmentWorld(r,{method:`GET`});if(i.body===null)throw Error(`Development Workflow stream response had no body.`);return i.body}},async start(){},async close(){}}}function buildForwardedOperations(){let e={},t={};for(let n of DEVELOPMENT_WORLD_OPERATIONS){let forward=async(...e)=>await call(n,e),r=n.indexOf(`.`);r===-1?t[n]=forward:(e[n.slice(0,r)]??={})[n.slice(r+1)]=forward}return{groups:e,topLevel:t}}function createQueueHandler(e,t){return async n=>{let r=readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV),i=n.headers.get(DEVELOPMENT_WORKFLOW_DELIVERY_HEADER);if(i===null||!timingSafeEqualStrings(i,r))return Response.json({error:`Workflow delivery is not trusted.`},{status:401});let a=n.headers.get(`x-vqs-queue-name`),o=n.headers.get(`x-vqs-message-id`),s=Number(n.headers.get(`x-vqs-message-attempt`));if(a===null||!a.startsWith(e)||o===null||!Number.isInteger(s)||s<1||n.body===null)return Response.json({error:`Workflow delivery is malformed.`},{status:400});let c=decodeDevelopmentWorldJson(await n.text());try{let e=readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV),n=await resolveDeliveryGenerationId(c);if(n===void 0)return Response.json({ok:!0});let r=await getGenerationAvailability(n);if(r.kind===`missing`)throw new MissingDevelopmentGenerationError(n);if(r.kind===`ineligible`||r.kind===`dormant`)return Response.json({ok:!0});let i=r.runtimeAppRoot,l=await withDevelopmentWorkflowGeneration({generationId:n,source:createDiskRuntimeCompiledArtifactsSource(i,{durableReference:`development-generation`,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:e})},async()=>await t(c,{attempt:s,messageId:o,queueName:a}));return Response.json(l===void 0?{ok:!0}:{timeoutSeconds:l.timeoutSeconds})}catch(e){if(e instanceof MissingDevelopmentGenerationError){let e=resolveDeliveryRunId(c);if(e!==void 0)try{await cancelExpiredDevelopmentRun(createDevelopmentWorkflowWorld(),e)}catch(e){return Response.json(String(e),{status:500})}return Response.json({ok:!0})}return Response.json(String(e),{status:500})}}}async function resolveDeliveryGenerationId(e){if(!isRecord(e)||e.__healthCheck===!0)return await call(`resolveLatestDeploymentId`);let t=isRecord(e.runInput)?e.runInput:void 0;if(t!==void 0)return typeof t.deploymentId==`string`?t.deploymentId:await call(`resolveLatestDeploymentId`);let n=resolveDeliveryRunId(e);if(n===void 0)return await call(`resolveLatestDeploymentId`);try{return(await call(`runs.get`,[n,{resolveData:`none`}])).deploymentId}catch(e){if(!isMissingWorkflowRunError(e))throw e;return}}function resolveDeliveryRunId(e){if(isRecord(e)&&e.__healthCheck!==!0)return typeof e.runId==`string`?e.runId:typeof e.workflowRunId==`string`?e.workflowRunId:void 0}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function fetchDevelopmentWorld(e,t){let n=e instanceof URL?e:new URL(e,resolveDevelopmentWorldBaseUrl()),r=new Headers(t.headers);r.set(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV));let i=await fetch(n,{...t,headers:r});if(!i.ok){let e=await i.text(),t=readDevelopmentWorldError(e);throw t===void 0?Error(`Development Workflow World request failed (${String(i.status)}): ${e}`):t}return i}function readDevelopmentWorldError(e){try{return deserializeDevelopmentWorldError(decodeDevelopmentWorldValue(e))}catch{return}}function resolveDevelopmentWorldBaseUrl(){return readRequiredEnvironment(`WORKFLOW_LOCAL_BASE_URL`)}function readRequiredEnvironment(e){let t=process.env[e];if(t===void 0||t.length===0)throw Error(`Development Workflow transport is missing ${e}.`);return t}export{MissingDevelopmentGenerationError,createDevelopmentWorkflowWorld};
|