eve 0.47.3 → 0.47.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/NOTICE +72 -0
- package/bin/eve.js +4 -0
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
- package/dist/src/cli/dev/tui/vercel-trusted-sources.js +1 -1
- package/dist/src/cli/invoke/result.d.ts +1 -1
- package/dist/src/compiled/.vendor-stamp.json +5 -5
- package/dist/src/compiled/@agentclientprotocol/sdk/index.js +29 -43
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +4 -4
- package/dist/src/compiled/@ai-sdk/code-mode/LICENSE +13 -0
- package/dist/src/compiled/@ai-sdk/code-mode/_run.d.ts +1 -0
- package/dist/src/compiled/@ai-sdk/code-mode/index.d.ts +300 -0
- package/dist/src/compiled/@ai-sdk/code-mode/index.js +663 -0
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.js +8 -8
- package/dist/src/compiled/@ai-sdk/provider/index.d.ts +6 -0
- package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +50 -2
- package/dist/src/compiled/@modelcontextprotocol/server/index.js +36 -50
- package/dist/src/compiled/@opentelemetry/api/index.d.ts +37 -0
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.js +55 -55
- package/dist/src/compiled/@vercel/otel/index.d.ts +11 -0
- package/dist/src/compiled/@vercel/sandbox/index.js +3 -3
- package/dist/src/compiled/@vercel/sandbox-delete/index.js +3 -3
- package/dist/src/compiled/_chunks/client/errors-BLhNglBt.js +2 -0
- package/dist/src/compiled/_chunks/node/auth-BSKyPAEP.js +2 -0
- package/dist/src/compiled/_chunks/node/auth-YpKlwhP1.js +2 -0
- package/dist/src/compiled/_chunks/node/schemas-cFtr4EoN.js +50 -0
- package/dist/src/compiled/_chunks/node/xdg-app-paths-Buj3-Svl.js +1 -0
- package/dist/src/compiled/_chunks/workflow/dist-Cz-ffHKC.js +65 -0
- package/dist/src/compiled/zod/index.js +32 -45
- package/dist/src/compiled/zod-validation-error/index.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +7 -5
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +14 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-connection.d.ts +9 -2
- package/dist/src/compiler/normalize-connection.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/validate-artifact.js +1 -1
- package/dist/src/context/dynamic-connection-lifecycle.d.ts +9 -0
- package/dist/src/context/dynamic-connection-lifecycle.js +1 -0
- package/dist/src/context/keys.d.ts +3 -1
- package/dist/src/context/memory-tools.js +1 -1
- package/dist/src/context/providers/connection.js +1 -1
- package/dist/src/dynamic/definition.d.ts +6 -3
- package/dist/src/dynamic/definition.js +1 -1
- package/dist/src/execution/authorization-callback-match.js +1 -1
- package/dist/src/execution/cancelled-turn-message.d.ts +2 -0
- package/dist/src/execution/cancelled-turn-message.js +1 -0
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/dynamic-connections.d.ts +9 -0
- package/dist/src/execution/dynamic-connections.js +1 -0
- package/dist/src/execution/eve-workflow-attributes.js +1 -1
- package/dist/src/execution/node-step.d.ts +2 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tools/connection-search.js +2 -2
- package/dist/src/execution/tools/load-skill.js +1 -1
- package/dist/src/execution/tools/subagent/local.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/execution/workflow-trace-context.d.ts +3 -6
- package/dist/src/execution/workflow-trace-context.js +1 -1
- package/dist/src/harness/advertised-tools.d.ts +0 -5
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/authorization.d.ts +11 -4
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/inline-tool-authorization.d.ts +13 -1
- package/dist/src/harness/inline-tool-authorization.js +1 -1
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/model-call-error.js +1 -1
- package/dist/src/harness/semantic-errors/rule.d.ts +5 -2
- package/dist/src/harness/semantic-errors/rules/gateway.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-tag-state.d.ts +1 -1
- package/dist/src/harness/types.d.ts +2 -2
- package/dist/src/harness/workflow-interrupt-state.d.ts +6 -0
- package/dist/src/harness/workflow-interrupt-state.js +1 -1
- package/dist/src/harness/workflow-lifecycle.d.ts +15 -5
- package/dist/src/harness/workflow-lifecycle.js +1 -1
- package/dist/src/harness/workflow-runtime-action-state.d.ts +2 -2
- package/dist/src/harness/workflow-runtime-action-state.js +1 -1
- package/dist/src/harness/workflow-sandbox.d.ts +1 -2
- package/dist/src/harness/workflow-sandbox.js +1 -1
- package/dist/src/harness/workflow-subagent-limit.d.ts +3 -13
- package/dist/src/harness/workflow-subagent-limit.js +1 -1
- package/dist/src/{harness → instrumentation}/ai-sdk-hook-bridge.d.ts +1 -1
- package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -0
- package/dist/src/{harness/channel-delivery-instrumentation.d.ts → instrumentation/channel-delivery.d.ts} +5 -7
- package/dist/src/instrumentation/channel-delivery.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/config.d.ts +0 -10
- package/dist/src/instrumentation/config.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/content-policy.d.ts +1 -1
- package/dist/src/instrumentation/content-policy.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/content.d.ts +1 -1
- package/dist/src/{harness/instrumentation → instrumentation}/dispatch.d.ts +1 -1
- package/dist/src/instrumentation/dispatch.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/lifecycle.d.ts +26 -33
- package/dist/src/instrumentation/lifecycle.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/native-events.d.ts +1 -1
- package/dist/src/instrumentation/native-events.js +1 -0
- package/dist/src/{harness → instrumentation}/parent-lineage.d.ts +1 -1
- package/dist/src/{harness → instrumentation}/prepare-trace-context.d.ts +8 -5
- package/dist/src/instrumentation/prepare-trace-context.js +1 -0
- package/dist/src/instrumentation/provider.d.ts +13 -9
- package/dist/src/{harness/instrumentation → instrumentation}/providers.d.ts +1 -1
- package/dist/src/instrumentation/providers.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/runtime-context.d.ts +13 -2
- package/dist/src/instrumentation/runtime-context.js +1 -0
- package/dist/src/instrumentation/runtime.d.ts +100 -0
- package/dist/src/instrumentation/runtime.js +1 -0
- package/dist/src/{harness/instrumentation → instrumentation}/state.d.ts +2 -11
- package/dist/src/internal/application/compiled-artifacts.js +3 -3
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/instrumentation.d.ts +1 -1
- package/dist/src/internal/nitro/host/workflow-sandbox-runtime-plugin.js +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +4 -6
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/lib/schemas.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/aclaction.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/sdkvalidationerror.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/updateprojectblock.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/updateprojectprojectsbranchmatcher.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/types/primitives.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/types/smartUnion.js +1 -1
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/index.js +1 -0
- package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/ZodError.js +1 -1
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v3/types.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/checks.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/deep-partial.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/errors.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/external.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/from-json-schema.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/in-out.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/iso.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/parse.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/schemas.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/api.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/checks.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/compile.js +2 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/core.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/doc.js +3 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/errors.js +2 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/index.js +1 -0
- package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/core/json-schema-generator.js +1 -1
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/json-schema-processors.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/memoizer.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/parse.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/regexes.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/schemas.js +46 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/to-json-schema.js +3 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/util.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/versions.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/visit.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ar.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/az.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/be.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/bg.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/bn.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ca.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ckb.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/cs.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/da.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/de.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/el.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/en.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/eo.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/es.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/fa.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/fi.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/fr-CA.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/fr.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/gu.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/he.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/hi.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/hr.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/hu.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/hy.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/id.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/index.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/is.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/it.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ja.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ka.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/km.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/kn.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ko.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/lt.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/mk.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ms.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ne.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/nl.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/nn.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/no.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ota.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/pl.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ps.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/pt-BR.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/pt.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ro.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ru.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/sk.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/sl.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/sv.js +1 -0
- package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/locales/ta.js +1 -1
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/th.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/tk.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/tr.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/uk.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/ur.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/uz.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/vi.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/yo.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/zh-CN.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/zh-TW.js +1 -0
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/public/channels/slack/defaults.js +6 -3
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/interactions.d.ts +8 -5
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +66 -1
- package/dist/src/public/channels/slack/slash-command.d.ts +9 -0
- package/dist/src/public/channels/slack/slash-command.js +1 -0
- package/dist/src/public/connections/index.d.ts +2 -0
- package/dist/src/public/connections/index.js +1 -1
- package/dist/src/public/definitions/connections/dynamic.d.ts +23 -0
- package/dist/src/public/definitions/connections/dynamic.js +1 -0
- package/dist/src/public/definitions/connections/mcp.d.ts +8 -0
- package/dist/src/public/definitions/connections/openapi.d.ts +8 -0
- package/dist/src/public/definitions/connections/protocol.d.ts +6 -0
- package/dist/src/public/definitions/connections/protocol.js +1 -1
- package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
- package/dist/src/runtime/connections/authorization-tokens.d.ts +11 -10
- package/dist/src/runtime/connections/instance-identity.d.ts +12 -0
- package/dist/src/runtime/connections/instance-identity.js +1 -0
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/registry.d.ts +2 -0
- package/dist/src/runtime/connections/registry.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +10 -6
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/resolve-connection.d.ts +5 -0
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/resolve-dynamic-connection.d.ts +5 -0
- package/dist/src/runtime/resolve-dynamic-connection.js +1 -0
- package/dist/src/runtime/types.d.ts +11 -0
- package/dist/src/services/dev-client/request-headers.js +1 -1
- package/dist/src/setup/flows/registry.js +1 -1
- package/dist/src/setup/integrations/discord/api.js +1 -1
- package/dist/src/setup/integrations/discord/connect.js +1 -1
- package/dist/src/setup/integrations/github/connect.js +1 -1
- package/dist/src/setup/integrations/linear/connect.js +1 -1
- package/dist/src/setup/integrations/linq/connect.js +1 -1
- package/dist/src/setup/integrations/photon/connect.js +1 -1
- package/dist/src/setup/project-resolution.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/extension.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +1 -1
- package/dist/src/setup/scaffold/update/web-options.js +1 -1
- package/dist/src/setup/slack-connect.js +1 -1
- package/dist/src/setup/vercel-api-failure.js +1 -1
- package/dist/src/setup/vercel-deployment.js +1 -1
- package/dist/src/setup/vercel-project-api.js +1 -1
- package/dist/src/setup/vercel-project-framework.js +1 -1
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/shared/input.js +1 -1
- package/dist/src/shared/trace-policy.d.ts +20 -0
- package/dist/src/shared/trace-policy.js +1 -0
- package/dist/src/shared/workflow-sandbox.d.ts +10 -5
- package/dist/src/shared/workflow-sandbox.js +1 -1
- package/dist/src/tracing/agent-action-instrumentation.d.ts +1 -1
- package/dist/src/tracing/agent-action-instrumentation.js +1 -1
- package/dist/src/tracing/agent-approval-instrumentation.d.ts +1 -1
- package/dist/src/tracing/agent-channel-delivery-instrumentation.d.ts +1 -1
- package/dist/src/tracing/agent-channel-delivery-instrumentation.js +1 -1
- package/dist/src/tracing/agent-otel-provider.d.ts +2 -2
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-runtime-context.d.ts +5 -0
- package/dist/src/tracing/agent-otel-runtime-context.js +1 -0
- package/dist/src/tracing/agent-otel-session-context.d.ts +1 -1
- package/dist/src/tracing/agent-otel-session-context.js +1 -1
- package/dist/src/tracing/agent-otel-usage.d.ts +4 -2
- package/dist/src/tracing/agent-otel-usage.js +1 -1
- package/dist/src/tracing/agent-span-id-generator.d.ts +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.d.ts +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
- package/dist/src/tracing/agent-trace-context-store.d.ts +3 -0
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/agent-trace-context.d.ts +3 -0
- package/dist/src/tracing/agent-trace-context.js +1 -0
- package/dist/src/tracing/agent-trace-state.d.ts +8 -1
- package/dist/src/tracing/agent-trace-state.js +1 -1
- package/dist/src/tracing/install-instrumentation-runtime.d.ts +3 -2
- package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
- package/dist/src/tracing/local-instrumentation-runtime.d.ts +1 -1
- package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
- package/dist/src/tracing/local-trace-reader.d.ts +1 -0
- package/dist/src/tracing/local-trace-reader.js +1 -1
- package/dist/src/tracing/otel-declaration.d.ts +13 -16
- package/dist/src/tracing/otel-declaration.js +1 -1
- package/dist/src/tracing/otel-registration.js +1 -1
- package/dist/src/tracing/sampled-trace.d.ts +1 -14
- package/dist/src/tracing/sampled-trace.js +1 -1
- package/docs/channels/slack.mdx +25 -5
- package/docs/connections/overview.mdx +46 -2
- package/docs/extensions.md +2 -2
- package/docs/getting-started.mdx +1 -1
- package/docs/guides/dynamic-capabilities.md +91 -5
- package/docs/memory.md +7 -4
- package/docs/reference/cli.md +4 -4
- package/docs/reference/typescript-api.md +32 -23
- package/package.json +6 -5
- package/dist/src/compiled/_chunks/client/errors-C14fPFvs.js +0 -2
- package/dist/src/compiled/_chunks/node/auth-DpzFWvTn.js +0 -2
- package/dist/src/compiled/_chunks/node/auth-QgeX8nBM.js +0 -2
- package/dist/src/compiled/_chunks/node/compat-Dm2n85Mx.js +0 -1
- package/dist/src/compiled/_chunks/node/schemas-DtQwuPdM.js +0 -65
- package/dist/src/compiled/_chunks/node/xdg-app-paths-Bys8q02u.js +0 -1
- package/dist/src/compiled/_chunks/workflow/dist-eUxFublw.js +0 -77
- package/dist/src/compiled/experimental-ai-sdk-code-mode/LICENSE +0 -21
- package/dist/src/compiled/experimental-ai-sdk-code-mode/approval-continuation.d.ts +0 -71
- package/dist/src/compiled/experimental-ai-sdk-code-mode/approval.d.ts +0 -32
- package/dist/src/compiled/experimental-ai-sdk-code-mode/code-mode-tool.d.ts +0 -16
- package/dist/src/compiled/experimental-ai-sdk-code-mode/continuation-capability.d.ts +0 -44
- package/dist/src/compiled/experimental-ai-sdk-code-mode/errors.d.ts +0 -114
- package/dist/src/compiled/experimental-ai-sdk-code-mode/fetch-policy.d.ts +0 -21
- package/dist/src/compiled/experimental-ai-sdk-code-mode/host-interrupt.d.ts +0 -25
- package/dist/src/compiled/experimental-ai-sdk-code-mode/index.d.ts +0 -11
- package/dist/src/compiled/experimental-ai-sdk-code-mode/index.js +0 -419
- package/dist/src/compiled/experimental-ai-sdk-code-mode/interrupt-continuation.d.ts +0 -32
- package/dist/src/compiled/experimental-ai-sdk-code-mode/options.d.ts +0 -3
- package/dist/src/compiled/experimental-ai-sdk-code-mode/run-code-mode.d.ts +0 -12
- package/dist/src/compiled/experimental-ai-sdk-code-mode/runtime/guest-sources.d.ts +0 -3
- package/dist/src/compiled/experimental-ai-sdk-code-mode/runtime/manager.d.ts +0 -22
- package/dist/src/compiled/experimental-ai-sdk-code-mode/runtime/max-workers.d.ts +0 -20
- package/dist/src/compiled/experimental-ai-sdk-code-mode/runtime/protocol.d.ts +0 -60
- package/dist/src/compiled/experimental-ai-sdk-code-mode/runtime/worker-source.d.ts +0 -11
- package/dist/src/compiled/experimental-ai-sdk-code-mode/serialization.d.ts +0 -5
- package/dist/src/compiled/experimental-ai-sdk-code-mode/source-cache.d.ts +0 -11
- package/dist/src/compiled/experimental-ai-sdk-code-mode/telemetry.d.ts +0 -20
- package/dist/src/compiled/experimental-ai-sdk-code-mode/tool-invocation.d.ts +0 -24
- package/dist/src/compiled/experimental-ai-sdk-code-mode/tool-prompt.d.ts +0 -3
- package/dist/src/compiled/experimental-ai-sdk-code-mode/types.d.ts +0 -828
- package/dist/src/execution/subagent-usage-span.d.ts +0 -9
- package/dist/src/execution/subagent-usage-span.js +0 -1
- package/dist/src/harness/ai-sdk-hook-bridge.js +0 -1
- package/dist/src/harness/channel-delivery-instrumentation.js +0 -1
- package/dist/src/harness/instrumentation/config.js +0 -1
- package/dist/src/harness/instrumentation/content-policy.js +0 -1
- package/dist/src/harness/instrumentation/dispatch.js +0 -1
- package/dist/src/harness/instrumentation/lifecycle.js +0 -1
- package/dist/src/harness/instrumentation/native-events.js +0 -1
- package/dist/src/harness/instrumentation/providers.js +0 -1
- package/dist/src/harness/instrumentation/runtime-context.js +0 -1
- package/dist/src/harness/instrumentation/runtime.d.ts +0 -21
- package/dist/src/harness/instrumentation/runtime.js +0 -1
- package/dist/src/harness/prepare-trace-context.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/index.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/types.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +0 -3
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js +0 -2
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +0 -60
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +0 -3
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js +0 -1
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js +0 -1
- /package/dist/src/{harness → instrumentation}/ai-sdk-telemetry.d.ts +0 -0
- /package/dist/src/{harness → instrumentation}/ai-sdk-telemetry.js +0 -0
- /package/dist/src/{harness/instrumentation → instrumentation}/content.js +0 -0
- /package/dist/src/{harness → instrumentation}/parent-lineage.js +0 -0
- /package/dist/src/{harness/instrumentation → instrumentation}/setup-context.d.ts +0 -0
- /package/dist/src/{harness/instrumentation → instrumentation}/setup-context.js +0 -0
- /package/dist/src/{harness/instrumentation → instrumentation}/state.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/errors.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/external.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/helpers/errorUtil.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/helpers/parseUtil.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/helpers/typeAliases.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/helpers/util.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/index.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v3/locales/en.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/classic/coerce.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/classic/compat.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/core/json-schema.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/core/registries.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/locales/kh.js +0 -0
- /package/dist/src/node_modules/.pnpm/{zod@4.4.3 → zod@4.5.4}/node_modules/zod/v4/locales/ua.js +0 -0
|
@@ -51,11 +51,22 @@ export type SamplerOrName =
|
|
|
51
51
|
| "parentbased_traceidratio"
|
|
52
52
|
| "traceidratio";
|
|
53
53
|
|
|
54
|
+
/**
|
|
55
|
+
* A `MetricReader`. Structural for the same reason the exporter is: the
|
|
56
|
+
* instance comes from whichever `@opentelemetry/sdk-metrics` build the app
|
|
57
|
+
* installed, and eve only ever hands it to `registerOTel`.
|
|
58
|
+
*/
|
|
59
|
+
export interface MetricReader {
|
|
60
|
+
forceFlush(): Promise<void>;
|
|
61
|
+
shutdown(): Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
|
|
54
64
|
export interface Configuration {
|
|
55
65
|
readonly attributes?: Readonly<Record<string, unknown>>;
|
|
56
66
|
readonly autoDetectResources?: boolean;
|
|
57
67
|
readonly idGenerator?: IdGenerator;
|
|
58
68
|
readonly instrumentations?: readonly unknown[];
|
|
69
|
+
readonly metricReaders?: readonly MetricReader[];
|
|
59
70
|
readonly propagators?: readonly PropagatorOrName[];
|
|
60
71
|
readonly serviceName?: string;
|
|
61
72
|
readonly spanProcessors?: readonly SpanProcessorOrName[];
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{o as e}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as r}from"../../_chunks/node/retry-qwFNGj4P.js";import{At as i,Bt as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,dn as f,wn as p,yt as m}from"../../_chunks/node/schemas-DtQwuPdM.js";import{t as ee}from"../../_chunks/node/undici-CUIybhQ2.js";import{a as te,c as ne,i as re,n as ie,o as ae,r as oe,s as se,t as ce}from"../../_chunks/node/decode_jwt-Col8JOnf.js";import{t as le}from"../../_chunks/node/version-BYHw-SDY.js";import{Readable as h}from"stream";import g,{dirname as ue,resolve as de}from"path";import{createWriteStream as fe}from"fs";import pe from"zlib";import me from"os";import{pipeline as he}from"stream/promises";import{mkdir as ge}from"fs/promises";import*as _e from"node:constants";import{setTimeout as ve}from"node:timers/promises";var _=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},v=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function ye(e){return e==null?[]:Array.isArray(e)?e:[e]}var be=e(ne(),1);function xe(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,be.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new _(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await Se(e*1e3,n.signal),new _(o)}if(o.status>=500&&o.status<600)throw new _(o);return o}catch(e){if(Ce(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof _)return e.response;throw e}}}async function Se(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function Ce(e){return e!=null&&e.name===`AbortError`}const we=new(ee()).Agent({bodyTimeout:0});var Te=class{constructor(e){this.fetch=xe(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=we}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))ye(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function Ee(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function De(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}async function Oe(e,t){let n=Ee(t.url),r;n||(r=De(t.url));let i=await t.text().catch(e=>new _(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new _(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok)return new _(t,{message:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r});let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new _(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function y(e,t){let n=await Oe(e,t);if(n instanceof _)throw n;return n}const b=l({exact:c().optional(),startsWith:c().optional(),regex:c().optional()}),ke=l({key:b.optional(),value:b.optional()}),x=l({path:b.optional(),method:o(c()).optional(),queryString:o(ke).optional(),headers:o(ke).optional()}),Ae=l({domain:c(),headers:s(c(),c()).optional(),headerNames:o(c()).optional(),match:x.optional()}),je=l({domain:c(),forwardURL:c(),match:x.optional()}),Me=l({headers:s(c(),c()).optional()}),Ne=l({match:x.optional(),transform:o(Me).optional(),forwardURL:c().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),Pe=l({allow:d([o(c()),s(c(),o(Ne))]).optional(),subnets:l({allow:o(c()).optional(),deny:o(c()).optional()}).optional()}),S=d([l({mode:f(`allow-all`)}).passthrough(),l({mode:f(`deny-all`)}).passthrough()]),Fe=l({mode:f(`custom`),allowedDomains:o(c()).optional(),allowedCIDRs:o(c()).optional(),deniedCIDRs:o(c()).optional(),injectionRules:o(Ae).optional(),forwardRules:o(je).optional()}).passthrough(),Ie=d([S,Pe.passthrough()]),C=d([S,Fe]),w=l({id:c(),memory:p(),vcpus:p(),region:c(),runtime:c(),timeout:p(),status:m([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:p(),startedAt:p().optional(),requestedStopAt:p().optional(),stoppedAt:p().optional(),abortedAt:p().optional(),duration:p().optional(),sourceSnapshotId:c().optional(),snapshottedAt:p().optional(),createdAt:p(),cwd:c(),updatedAt:p(),interactivePort:p().optional(),networkPolicy:C.optional(),activeCpuDurationMs:p().optional(),networkTransfer:l({ingress:p(),egress:p()}).optional()}),T=l({url:c(),subdomain:c(),port:p()}),E=l({id:c(),sourceSessionId:c(),region:c(),status:m([`created`,`deleted`,`failed`]),sizeBytes:p(),expiresAt:p().optional(),createdAt:p(),updatedAt:p(),lastUsedAt:p().optional(),creationMethod:c().optional(),parentId:c().optional()}),D=l({count:p(),next:c().nullable()}),O=l({id:c(),name:c(),args:o(c()),cwd:c(),sessionId:c(),exitCode:p().nullable(),durationMs:p().optional(),startedAt:p()}),Le=O.extend({exitCode:p()}),k=l({session:w.passthrough()}),Re=k.extend({routes:o(T)}),ze=l({url:c(),token:c()}),Be=l({sessions:o(w.passthrough()),pagination:D}),A=l({command:O}),Ve=l({command:Le}),He=l({}),Ue=l({data:c()}),We=a(`stream`,[Ue.extend({stream:f(`stdout`)}),Ue.extend({stream:f(`stderr`)}),l({stream:f(`error`),data:l({code:c(),message:c()})})]),Ge=l({snapshots:o(E),pagination:D}),Ke=l({snapshot:E,siblings:o(E),count:c()}),qe=l({snapshots:o(Ke),anchor:Ke.optional(),pagination:D}),Je=l({snapshot:E,session:w.passthrough()}),Ye=l({snapshot:E}),Xe=l({name:c(),projectId:c(),maxSizeBytes:p(),currentSessionId:c().optional(),currentSandboxName:c().optional(),createdAt:p(),updatedAt:p()}),Ze=l({drives:o(Xe),pagination:D}),Qe=l({drive:Xe}),j=l({name:c(),persistent:i(),region:c().optional(),vcpus:p().optional(),memory:p().optional(),runtime:c().optional(),image:c().optional(),timeout:p().optional(),networkPolicy:C.optional(),totalEgressBytes:p().optional(),totalIngressBytes:p().optional(),totalActiveCpuDurationMs:p().optional(),totalDurationMs:p().optional(),createdAt:p(),updatedAt:p(),expiresAt:p().optional(),currentSessionId:c(),currentSnapshotId:c().optional(),status:w.shape.status,statusUpdatedAt:p().optional(),cwd:c().optional(),tags:s(c(),c()).optional(),mounts:s(c(),l({drive:c(),mode:m([`read-only`,`read-write`]).optional()})).optional(),snapshotExpiration:p().optional(),keepLastSnapshots:l({count:p(),expiration:p().optional(),deleteEvicted:i().optional()}).optional()}),$e=l({session:w.passthrough(),sandbox:j.optional(),snapshot:E.optional()}),M=l({sandbox:j,session:w.passthrough(),routes:o(T),resumed:i().optional()}),et=l({sandboxes:o(j),pagination:D}),N=l({sandbox:j,routes:o(T).optional()});var tt=e(se(),1),nt=class{constructor(){let e=pe.createGzip();this.pack=tt.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof h?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function rt(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function it(e){if(!g.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!g.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=g.posix.isAbsolute(e.filePath)?g.posix.normalize(e.filePath):g.posix.join(e.cwd,e.filePath);return g.posix.relative(e.extractDir,t)}function P(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ie.parse(t),t}function at(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const F=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var ot=e(ae(),1),st=te();function ct(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var I=class extends Te{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=ct(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,st.getVercelOidcToken)({expirationBufferMs:300*1e3,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=ct(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${le} (Node.js/${process.version}; ${me.platform()}/${me.arch()})`,...t?.headers}})}async getSession(e){let t=F(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,y(Re,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=F(e);return y(M,await this.request(`/v2/sandboxes`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,mounts:e.mounts,...t}),signal:e.signal}))}async forkSandbox(e){let t=F(e);return y(M,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await y(u(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new _(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new _(t,{message:`No response body`,sessionId:e.sessionId});let n=ot.parse();lt(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new v(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:a}=A.parse(i.value);return{command:a,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new v(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=Ve.parse(t.value);return e}let n=We.parse(t.value);if(n.stream===`error`)throw new v(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?y(Ve,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return y(ze,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return y(He,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new nt;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await rt(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return y(Be,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return y(Ge,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return y(qe,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listDrives(e){return y(Ze,await this.request(`/v2/sandboxes/drives`,{query:{projectId:e.projectId,limit:e.limit,cursor:e.cursor??e.until,since:e.since,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix},method:`GET`,signal:e.signal}))}async getOrCreateDrive(e){return y(Qe,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,maxSizeBytes:e.maxSizeBytes}),signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:it({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await y(He,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new _(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:h.fromWeb(t.body)}async killCommand(e){return y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?ut(e.signal,n.signal):n.signal,i=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,i=await t.request(n,{method:`GET`,signal:r});if(i.ok||await y(u(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new _(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new _(i,{message:`No response body`,sessionId:e.sessionId});let a=ot.parse();lt(i.body,a,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of a){let n=We.parse(t);if(n.stream===`error`)throw new v(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(i,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return y($e,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return y(k,await this.request(t,{method:`POST`,body:JSON.stringify(P(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return y(k,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return y(Je,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return y(Ye,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return y(Ye,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=F(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),y(M,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return y(et,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:dt(e.tags)},method:`GET`,signal:e.signal}))}async deleteDrive(e){let t=`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`;return y(Qe,await this.request(t,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}async updateSandbox(e){return y(N,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,runtime:e.runtime,timeout:e.timeout,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId}),signal:e.signal}))}async deleteSandbox(e){return y(N,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}};async function lt(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function ut(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function dt(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>`${e}:${t}`)}function ft(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var L=e(re(),1);const pt={warn:L.default.yellow,error:L.default.red,success:L.default.green,info:L.default.blue},mt=L.default.dim(`[vercel/sandbox]`);function R(e,t){t=Array.isArray(t)?t.join(`
|
|
2
|
-
`):t;let n=t.replace(/^/gm,`${mt} `);console.error(pt[e](n))}function ht(e){return L.default.italic(L.default.dim("`")+e+L.default.dim("`"))}var gt=e(r(),1);async function _t(){return await import(`../../_chunks/node/auth-
|
|
1
|
+
import{o as e}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as r}from"../../_chunks/node/retry-qwFNGj4P.js";import{a as i,f as a,g as o,l as s,o as c,p as l,s as u,t as d,u as f,v as p,y as m}from"../../_chunks/node/schemas-cFtr4EoN.js";import{t as ee}from"../../_chunks/node/undici-CUIybhQ2.js";import{a as te,c as ne,i as re,n as ie,o as ae,r as oe,s as se,t as ce}from"../../_chunks/node/decode_jwt-Col8JOnf.js";import{t as le}from"../../_chunks/node/version-BYHw-SDY.js";import{Readable as h}from"stream";import g,{dirname as ue,resolve as de}from"path";import{createWriteStream as fe}from"fs";import pe from"zlib";import me from"os";import{pipeline as he}from"stream/promises";import{mkdir as ge}from"fs/promises";import*as _e from"node:constants";import{setTimeout as ve}from"node:timers/promises";var _=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},v=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function ye(e){return e==null?[]:Array.isArray(e)?e:[e]}var be=e(ne(),1);function xe(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,be.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new _(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await Se(e*1e3,n.signal),new _(o)}if(o.status>=500&&o.status<600)throw new _(o);return o}catch(e){if(Ce(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof _)return e.response;throw e}}}async function Se(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function Ce(e){return e!=null&&e.name===`AbortError`}const we=new(ee()).Agent({bodyTimeout:0});var Te=class{constructor(e){this.fetch=xe(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=we}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))ye(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function Ee(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function De(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}async function Oe(e,t){let n=Ee(t.url),r;n||(r=De(t.url));let i=await t.text().catch(e=>new _(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new _(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok)return new _(t,{message:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r});let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new _(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function y(e,t){let n=await Oe(e,t);if(n instanceof _)throw n;return n}const b=l({exact:p().optional(),startsWith:p().optional(),regex:p().optional()}),ke=l({key:b.optional(),value:b.optional()}),x=l({path:b.optional(),method:c(p()).optional(),queryString:c(ke).optional(),headers:c(ke).optional()}),Ae=l({domain:p(),headers:o(p(),p()).optional(),headerNames:c(p()).optional(),match:x.optional()}),je=l({domain:p(),forwardURL:p(),match:x.optional()}),Me=l({headers:o(p(),p()).optional()}),Ne=l({match:x.optional(),transform:c(Me).optional(),forwardURL:p().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),Pe=l({allow:m([c(p()),o(p(),c(Ne))]).optional(),subnets:l({allow:c(p()).optional(),deny:c(p()).optional()}).optional()}),S=m([l({mode:f(`allow-all`)}).passthrough(),l({mode:f(`deny-all`)}).passthrough()]),Fe=l({mode:f(`custom`),allowedDomains:c(p()).optional(),allowedCIDRs:c(p()).optional(),deniedCIDRs:c(p()).optional(),injectionRules:c(Ae).optional(),forwardRules:c(je).optional()}).passthrough(),Ie=m([S,Pe.passthrough()]),C=m([S,Fe]),w=l({id:p(),memory:a(),vcpus:a(),region:p(),runtime:p(),timeout:a(),status:d([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:a(),startedAt:a().optional(),requestedStopAt:a().optional(),stoppedAt:a().optional(),abortedAt:a().optional(),duration:a().optional(),sourceSnapshotId:p().optional(),snapshottedAt:a().optional(),createdAt:a(),cwd:p(),updatedAt:a(),interactivePort:a().optional(),networkPolicy:C.optional(),activeCpuDurationMs:a().optional(),networkTransfer:l({ingress:a(),egress:a()}).optional()}),T=l({url:p(),subdomain:p(),port:a()}),E=l({id:p(),sourceSessionId:p(),region:p(),status:d([`created`,`deleted`,`failed`]),sizeBytes:a(),expiresAt:a().optional(),createdAt:a(),updatedAt:a(),lastUsedAt:a().optional(),creationMethod:p().optional(),parentId:p().optional()}),D=l({count:a(),next:p().nullable()}),O=l({id:p(),name:p(),args:c(p()),cwd:p(),sessionId:p(),exitCode:a().nullable(),durationMs:a().optional(),startedAt:a()}),Le=O.extend({exitCode:a()}),k=l({session:w.passthrough()}),Re=k.extend({routes:c(T)}),ze=l({url:p(),token:p()}),Be=l({sessions:c(w.passthrough()),pagination:D}),A=l({command:O}),Ve=l({command:Le}),He=l({}),Ue=l({data:p()}),We=s(`stream`,[Ue.extend({stream:f(`stdout`)}),Ue.extend({stream:f(`stderr`)}),l({stream:f(`error`),data:l({code:p(),message:p()})})]),Ge=l({snapshots:c(E),pagination:D}),Ke=l({snapshot:E,siblings:c(E),count:p()}),qe=l({snapshots:c(Ke),anchor:Ke.optional(),pagination:D}),Je=l({snapshot:E,session:w.passthrough()}),Ye=l({snapshot:E}),Xe=l({name:p(),projectId:p(),maxSizeBytes:a(),currentSessionId:p().optional(),currentSandboxName:p().optional(),createdAt:a(),updatedAt:a()}),Ze=l({drives:c(Xe),pagination:D}),Qe=l({drive:Xe}),j=l({name:p(),persistent:u(),region:p().optional(),vcpus:a().optional(),memory:a().optional(),runtime:p().optional(),image:p().optional(),timeout:a().optional(),networkPolicy:C.optional(),totalEgressBytes:a().optional(),totalIngressBytes:a().optional(),totalActiveCpuDurationMs:a().optional(),totalDurationMs:a().optional(),createdAt:a(),updatedAt:a(),expiresAt:a().optional(),currentSessionId:p(),currentSnapshotId:p().optional(),status:w.shape.status,statusUpdatedAt:a().optional(),cwd:p().optional(),tags:o(p(),p()).optional(),mounts:o(p(),l({drive:p(),mode:d([`read-only`,`read-write`]).optional()})).optional(),snapshotExpiration:a().optional(),keepLastSnapshots:l({count:a(),expiration:a().optional(),deleteEvicted:u().optional()}).optional()}),$e=l({session:w.passthrough(),sandbox:j.optional(),snapshot:E.optional()}),M=l({sandbox:j,session:w.passthrough(),routes:c(T),resumed:u().optional()}),et=l({sandboxes:c(j),pagination:D}),N=l({sandbox:j,routes:c(T).optional()});var tt=e(se(),1),nt=class{constructor(){let e=pe.createGzip();this.pack=tt.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof h?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function rt(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function it(e){if(!g.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!g.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=g.posix.isAbsolute(e.filePath)?g.posix.normalize(e.filePath):g.posix.join(e.cwd,e.filePath);return g.posix.relative(e.extractDir,t)}function P(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ie.parse(t),t}function at(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const F=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var ot=e(ae(),1),st=te();function ct(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var I=class extends Te{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=ct(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,st.getVercelOidcToken)({expirationBufferMs:300*1e3,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=ct(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${le} (Node.js/${process.version}; ${me.platform()}/${me.arch()})`,...t?.headers}})}async getSession(e){let t=F(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,y(Re,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=F(e);return y(M,await this.request(`/v2/sandboxes`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,mounts:e.mounts,...t}),signal:e.signal}))}async forkSandbox(e){let t=F(e);return y(M,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await y(i(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new _(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new _(t,{message:`No response body`,sessionId:e.sessionId});let n=ot.parse();lt(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),a=await r.next();if(a.done)throw new v(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:o}=A.parse(a.value);return{command:o,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new v(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=Ve.parse(t.value);return e}let n=We.parse(t.value);if(n.stream===`error`)throw new v(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?y(Ve,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return y(ze,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return y(He,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new nt;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await rt(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return y(Be,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return y(Ge,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return y(qe,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listDrives(e){return y(Ze,await this.request(`/v2/sandboxes/drives`,{query:{projectId:e.projectId,limit:e.limit,cursor:e.cursor??e.until,since:e.since,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix},method:`GET`,signal:e.signal}))}async getOrCreateDrive(e){return y(Qe,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,maxSizeBytes:e.maxSizeBytes}),signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:it({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await y(He,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new _(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:h.fromWeb(t.body)}async killCommand(e){return y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?ut(e.signal,n.signal):n.signal,a=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,a=await t.request(n,{method:`GET`,signal:r});if(a.ok||await y(i(),a),a.headers.get(`content-type`)!==`application/x-ndjson`)throw new _(a,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(a.body===null)throw new _(a,{message:`No response body`,sessionId:e.sessionId});let o=ot.parse();lt(a.body,o,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of o){let n=We.parse(t);if(n.stream===`error`)throw new v(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(a,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return y($e,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return y(k,await this.request(t,{method:`POST`,body:JSON.stringify(P(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return y(k,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return y(Je,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return y(Ye,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return y(Ye,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=F(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),y(M,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return y(et,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:dt(e.tags)},method:`GET`,signal:e.signal}))}async deleteDrive(e){let t=`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`;return y(Qe,await this.request(t,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}async updateSandbox(e){return y(N,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,runtime:e.runtime,timeout:e.timeout,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId}),signal:e.signal}))}async deleteSandbox(e){return y(N,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}};async function lt(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function ut(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function dt(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>`${e}:${t}`)}function ft(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var L=e(re(),1);const pt={warn:L.default.yellow,error:L.default.red,success:L.default.green,info:L.default.blue},mt=L.default.dim(`[vercel/sandbox]`);function R(e,t){t=Array.isArray(t)?t.join(`
|
|
2
|
+
`):t;let n=t.replace(/^/gm,`${mt} `);console.error(pt[e](n))}function ht(e){return L.default.italic(L.default.dim("`")+e+L.default.dim("`"))}var gt=e(r(),1);async function _t(){return await import(`../../_chunks/node/auth-YpKlwhP1.js`)}function vt(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const yt=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,bt(t).catch(t=>{throw e=null,t})]);let n=await e[1];return R(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function bt(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await _t(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await xt({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${L.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
|
|
3
3
|
`));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&R(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function xt(e,t){R(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${L.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();R(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${L.default.italic(r.verification_uri)} and type ${L.default.bold(r.user_code)}`,` Press ${L.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${L.default.bold(`help:`)} Link your project with ${ht(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
|
|
4
4
|
`);i=Error(e),a.return()},(0,gt.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw R(`error`,`${L.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return R(`success`,`${L.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var St=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
|
|
5
5
|
`);super(t,{cause:e}),this.name=`LocalOidcContextError`}},Ct=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
|
|
6
|
-
`);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function wt(e){try{return Dt(await(0,st.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!vt())throw process.env.VERCEL_URL?new Ct(t):new St(t);return await yt(e)}}async function z(e){return Tt(e??{})||await wt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Tt(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Et=l({exp:p().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:p().optional().describe(`Issued at timestamp`),owner_id:c(),project_id:c()});function Dt(e){try{let t=Et.parse(ft(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const Ot={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function kt(e){if(typeof e==`number`)return e;if(e in Ot)return Ot[e];throw Error(`Unknown signal name: ${String(e)}`)}var B=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[t](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new V({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:kt(e??`SIGTERM`),abortSignal:t?.abortSignal})}},V=class e extends B{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[t](e){return{...B[t](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function H(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){U(i);let t=e;for(yield t;t.pagination.next!==null;)U(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)U(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function U(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var At=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[t](e){return{snapshot:e.snapshot}}static[n](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return H(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return H(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function W(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?at(t):void 0}}var G=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[t](e){return{session:e.session,routes:e.routes}}static[n](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=W(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new B({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new V({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new B({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:rt(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=de(t.cwd??``,t.path);return n?.mkdirRecursive&&await ge(ue(e),{recursive:!0}),await he(i,fe(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=W(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=W((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=W((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=W(n.json.session),new At({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:K,S_IFREG:jt,S_IFDIR:Mt,S_IFLNK:Nt,S_IFBLK:Pt,S_IFCHR:Ft,S_IFIFO:It,S_IFSOCK:Lt}=_e;function q(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function Rt(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var zt=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&K)===jt}isDirectory(){return(this.mode&K)===Mt}isBlockDevice(){return(this.mode&K)===Pt}isCharacterDevice(){return(this.mode&K)===Ft}isSymbolicLink(){return(this.mode&K)===Nt}isFIFO(){return(this.mode&K)===It}isSocket(){return(this.mode&K)===Lt}},Bt=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function Vt(e){let t=e.trim().split(`|`);return new zt(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function Ht(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw q(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new Bt(r,Wt[i]??1,t)}const Ut=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,Wt={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var Gt=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=Rt(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw q(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw q(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`scandir`,e):q(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
|
|
6
|
+
`);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function wt(e){try{return Dt(await(0,st.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!vt())throw process.env.VERCEL_URL?new Ct(t):new St(t);return await yt(e)}}async function z(e){return Tt(e??{})||await wt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Tt(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Et=l({exp:a().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:a().optional().describe(`Issued at timestamp`),owner_id:p(),project_id:p()});function Dt(e){try{let t=Et.parse(ft(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const Ot={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function kt(e){if(typeof e==`number`)return e;if(e in Ot)return Ot[e];throw Error(`Unknown signal name: ${String(e)}`)}var B=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[t](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new V({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:kt(e??`SIGTERM`),abortSignal:t?.abortSignal})}},V=class e extends B{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[t](e){return{...B[t](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function H(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){U(i);let t=e;for(yield t;t.pagination.next!==null;)U(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)U(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function U(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var At=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[t](e){return{snapshot:e.snapshot}}static[n](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return H(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return H(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function W(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?at(t):void 0}}var G=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[t](e){return{session:e.session,routes:e.routes}}static[n](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=W(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new B({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new V({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new B({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:rt(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=de(t.cwd??``,t.path);return n?.mkdirRecursive&&await ge(ue(e),{recursive:!0}),await he(i,fe(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=W(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=W((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=W((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=W(n.json.session),new At({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:K,S_IFREG:jt,S_IFDIR:Mt,S_IFLNK:Nt,S_IFBLK:Pt,S_IFCHR:Ft,S_IFIFO:It,S_IFSOCK:Lt}=_e;function q(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function Rt(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var zt=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&K)===jt}isDirectory(){return(this.mode&K)===Mt}isBlockDevice(){return(this.mode&K)===Pt}isCharacterDevice(){return(this.mode&K)===Ft}isSymbolicLink(){return(this.mode&K)===Nt}isFIFO(){return(this.mode&K)===It}isSocket(){return(this.mode&K)===Lt}},Bt=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function Vt(e){let t=e.trim().split(`|`);return new zt(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function Ht(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw q(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new Bt(r,Wt[i]??1,t)}const Ut=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,Wt={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var Gt=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=Rt(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw q(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw q(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`scandir`,e):q(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
|
|
7
7
|
`).filter(Boolean).map(t=>Ht(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`scandir`,e):q(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
|
|
8
8
|
`).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,Ut,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`stat`,e):q(`EACCES`,t.trim(),`stat`,e)}return Vt(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,Ut,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`lstat`,e):q(`EACCES`,t.trim(),`lstat`,e)}return Vt(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`unlink`,e):q(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`rm`,e):q(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?q(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):q(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`rename`,e):q(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`copyfile`,e):q(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw q(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`chmod`,e):q(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`chown`,e):q(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?q(`EEXIST`,`file already exists`,`symlink`,t):q(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`readlink`,e):q(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`realpath`,e):q(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`truncate`,e):q(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw q(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const Kt=/^[a-z_][a-z0-9_-]*$/;function J(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!Kt.test(e))throw Error(`Invalid ${t} "${e}": must match ${Kt} (lowercase letters, digits, hyphens, underscores)`)}var qt=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},Y=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:h.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=de(t.cwd??``,t.path);return n?.mkdirRecursive&&await ge(ue(i),{recursive:!0}),await he(r,fe(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){J(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){J(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function X(e){return e instanceof _&&e.response.status===410}function Jt(e){return e instanceof _&&e.response.status===404}function Yt(e){return e instanceof _&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function Z(e){return e instanceof _&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function Xt(e){return e instanceof _&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var Zt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get mounts(){return this.sandbox.mounts}get networkPolicy(){return this.sandbox.networkPolicy?at(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return H(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[t](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[n](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new G({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=F(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,mounts:e?.mounts,snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new Qt({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=F(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,persistent:e.persistent,signal:e.signal,...r});return new Qt({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=F(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(Jt(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(Yt(n)){let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=F(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!Jt(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new G({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new Gt(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new G({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await ve(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new G({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(X(n))return await this.resume(t),e();if(Z(n)||Xt(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
|
|
9
9
|
`);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){J(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new qt(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new Y({sandbox:this,username:e})}asUser(e){return J(e,`username`),new Y({sandbox:this,username:e})}async createGroup(e,t){J(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){J(e,`username`),J(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){J(e,`username`),J(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!X(e)&&!Z(e))throw e}}if(e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(X(e)||Z(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return H(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return H(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},Qt=class extends Zt{async[Symbol.asyncDispose](){await this.stop()}},$t=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get name(){return this.drive.name}get projectId(){return this._projectId}get maxSize(){return this.drive.maxSizeBytes}get currentSessionId(){return this.drive.currentSessionId}get currentSandboxName(){return this.drive.currentSandboxName}get createdAt(){return new Date(this.drive.createdAt)}get updatedAt(){return new Date(this.drive.updatedAt)}static[t](e){return{drive:e.drive,projectId:e._projectId}}static[n](t){return new e({drive:t.drive,projectId:t.projectId})}constructor({client:e,drive:t,projectId:n}){this._client=null,this._client=e??null,this.drive=t,this._projectId=n??t.projectId}static async list(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t?.fetch}),i=async i=>{let a=await r.listDrives({...n,...t,...i!==void 0&&{cursor:i}});return{...a.json,drives:a.json.drives.map(t=>new e({client:r,drive:t,projectId:n.projectId}))}};return H(await i(t?.cursor??t?.until),{itemsKey:`drives`,fetchNext:i,signal:t?.signal})}static async getOrCreate(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,drive:(await r.getOrCreateDrive({projectId:n.projectId,name:t.name,maxSizeBytes:t.maxSize,signal:t.signal})).json.drive,projectId:n.projectId})}async delete(e){"use step";this.drive=(await(await this.ensureClient()).deleteDrive({projectId:this._projectId,name:this.drive.name,signal:e?.signal})).json.drive}};const en=`vercel-forwarded-host`,tn=`vercel-forwarded-scheme`,nn=`vercel-forwarded-port`,rn=`vercel-forwarded-path`,an=`vercel-sandbox-oidc-token`,on=new Map;function sn(e,t=cn){return async function(n){let r=new Headers(n.headers),i=r.get(en),a=r.get(tn),o=r.get(nn),s=r.get(rn),c=r.get(an);if(r.delete(en),r.delete(tn),r.delete(nn),r.delete(rn),r.delete(an),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(ln(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=un(new URL(n.url),s),r=await fn(c,t),i=dn(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function cn(){return new Response(`Forbidden`,{status:403})}function ln(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function un(e,t){let n=Q(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=Q(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=Q(r.pathname.slice(0,-n.length))),r}function Q(e){return e.replace(/\/+$/,``)||`/`}function dn(e,t){let n=$(t,`team_id`),r=$(t,`project_id`),i=$(t,`sandbox_id`),a=$(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function fn(e,t){let n=$(ce(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await oe(e,mn(n),{audience:pn(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function pn(e){let t=Q(e.pathname);return t===`/`?e.origin:e.origin+t}function mn(e){let t=on.get(e);if(t)return t;let n=ie(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return on.set(e,n),n}function $(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{_ as APIError,B as Command,V as CommandFinished,$t as Drive,Gt as FileSystem,Zt as Sandbox,Y as SandboxUser,qt as SandboxUserAlreadyExistsError,G as Session,At as Snapshot,v as StreamError,sn as defineSandboxProxy};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{o as e}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as r}from"../../_chunks/node/retry-qwFNGj4P.js";import{At as i,Bt as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,dn as f,wn as p,yt as m}from"../../_chunks/node/schemas-DtQwuPdM.js";import{t as h}from"../../_chunks/node/undici-CUIybhQ2.js";import{a as g,c as _,i as v,n as y,o as ee,r as te,s as ne,t as b}from"../../_chunks/node/decode_jwt-Col8JOnf.js";import{t as re}from"../../_chunks/node/version-DH6yRy-M.js";import{Readable as x}from"stream";import S,{dirname as ie,resolve as ae}from"path";import{createWriteStream as oe}from"fs";import se from"zlib";import ce from"os";import{pipeline as le}from"stream/promises";import{mkdir as ue}from"fs/promises";import*as de from"node:constants";import{setTimeout as fe}from"node:timers/promises";var C=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},w=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};const pe=`iad1`;function me(e){return e==null?[]:Array.isArray(e)?e:[e]}var he=e(_(),1);function ge(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,he.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new C(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await _e(e*1e3,n.signal),new C(o)}if(o.status>=500&&o.status<600)throw new C(o);return o}catch(e){if(ve(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof C)return e.response;throw e}}}async function _e(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function ve(e){return e!=null&&e.name===`AbortError`}const ye=new(h()).Agent({bodyTimeout:0});var be=class{constructor(e){this.fetch=ge(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=ye}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))me(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function xe(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function Se(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}const Ce=l({error:l({message:c()})});function we(e){let t=Ce.safeParse(e);return t.success?t.data.error.message:void 0}async function Te(e,t){let n=xe(t.url),r;n||(r=Se(t.url));let i=await t.text().catch(e=>new C(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new C(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok){let e=we(a);return new C(t,{message:e?`Status code ${t.status} is not ok: ${e}`:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r})}let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new C(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function T(e,t){let n=await Te(e,t);if(n instanceof C)throw n;return n}const Ee=l({exact:c().optional(),startsWith:c().optional(),regex:c().optional()}),De=l({key:Ee.optional(),value:Ee.optional()}),Oe=l({path:Ee.optional(),method:o(c()).optional(),queryString:o(De).optional(),headers:o(De).optional()}),ke=l({domain:c(),headers:s(c(),c()).optional(),headerNames:o(c()).optional(),match:Oe.optional()}),Ae=l({domain:c(),forwardURL:c(),match:Oe.optional()}),je=l({headers:s(c(),c()).optional()}),Me=l({match:Oe.optional(),transform:o(je).optional(),forwardURL:c().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),Ne=l({allow:d([o(c()),s(c(),o(Me))]).optional(),subnets:l({allow:o(c()).optional(),deny:o(c()).optional()}).optional()}),Pe=d([l({mode:f(`allow-all`)}).passthrough(),l({mode:f(`deny-all`)}).passthrough()]),Fe=l({mode:f(`custom`),allowedDomains:o(c()).optional(),allowedCIDRs:o(c()).optional(),deniedCIDRs:o(c()).optional(),injectionRules:o(ke).optional(),forwardRules:o(Ae).optional()}).passthrough(),Ie=d([Pe,Ne.passthrough()]),Le=d([Pe,Fe]),E=l({id:c(),memory:p(),vcpus:p(),region:c(),runtime:c().optional(),timeout:p(),status:m([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:p(),startedAt:p().optional(),requestedStopAt:p().optional(),stoppedAt:p().optional(),abortedAt:p().optional(),duration:p().optional(),sourceSnapshotId:c().optional(),snapshottedAt:p().optional(),createdAt:p(),cwd:c(),updatedAt:p(),interactivePort:p().optional(),networkPolicy:Le.optional(),activeCpuDurationMs:p().optional(),networkTransfer:l({ingress:p(),egress:p()}).optional()}),Re=l({url:c(),subdomain:c(),port:p()}),D=l({id:c(),sourceSessionId:c(),region:c(),regions:o(c()).optional(),status:m([`created`,`deleted`,`failed`]),sizeBytes:p(),expiresAt:p().optional(),createdAt:p(),updatedAt:p(),lastUsedAt:p().optional(),creationMethod:c().optional(),parentId:c().optional()}),O=l({count:p(),next:c().nullable()}),ze=l({id:c(),name:c(),args:o(c()),cwd:c(),sessionId:c(),exitCode:p().nullable(),durationMs:p().optional(),startedAt:p()}),Be=ze.extend({exitCode:p()}),Ve=l({session:E.passthrough()}),He=Ve.extend({routes:o(Re)}),Ue=l({url:c(),token:c()}),We=l({sessions:o(E.passthrough()),pagination:O}),k=l({command:ze}),Ge=l({command:Be}),Ke=l({}),qe=l({data:c()}),Je=a(`stream`,[qe.extend({stream:f(`stdout`)}),qe.extend({stream:f(`stderr`)}),l({stream:f(`error`),data:l({code:c(),message:c()})})]),Ye=l({snapshots:o(D),pagination:O}),Xe=l({snapshot:D,siblings:o(D),count:c()}),Ze=l({snapshots:o(Xe),anchor:Xe.optional(),pagination:O}),Qe=l({snapshot:D,session:E.passthrough()}),$e=l({snapshot:D}),A=l({name:c(),persistent:i(),region:c().optional(),failoverRegions:o(c()).optional(),vcpus:p().optional(),memory:p().optional(),runtime:c().optional(),image:c().optional(),timeout:p().optional(),networkPolicy:Le.optional(),totalEgressBytes:p().optional(),totalIngressBytes:p().optional(),totalActiveCpuDurationMs:p().optional(),totalDurationMs:p().optional(),createdAt:p(),updatedAt:p(),expiresAt:p().optional(),currentSessionId:c(),currentSnapshotId:c().optional(),status:E.shape.status,statusUpdatedAt:p().optional(),cwd:c().optional(),tags:s(c(),c()).optional(),snapshotExpiration:p().optional(),keepLastSnapshots:l({count:p(),expiration:p().optional(),deleteEvicted:i().optional()}).optional()}),et=l({session:E.passthrough(),sandbox:A.optional(),snapshot:D.optional()}),tt=l({sandbox:A,session:E.passthrough(),routes:o(Re),resumed:i().optional()}),nt=l({sandboxes:o(A),pagination:O}),rt=l({sandbox:A,routes:o(Re).optional()});var it=e(ne(),1),at=class{constructor(){let e=se.createGzip();this.pack=it.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof x?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function ot(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function st(e){if(!S.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!S.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=S.posix.isAbsolute(e.filePath)?S.posix.normalize(e.filePath):S.posix.join(e.cwd,e.filePath);return S.posix.relative(e.extractDir,t)}function j(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ie.parse(t),t}function ct(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const M=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var lt=e(ee(),1),ut=g();function dt(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var N=class extends be{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=dt(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,ut.getVercelOidcToken)({expirationBufferMs:300*1e3,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=dt(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${re} (Node.js/${process.version}; ${ce.platform()}/${ce.arch()})`,...t?.headers}})}async getSession(e){let t=M(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,T(He,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=M(e),n=e.runtime===void 0?`/v3/sandboxes`:`/v2/sandboxes`;return T(tt,await this.request(n,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async forkSandbox(e){let t=M(e);return T(tt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await T(u(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new C(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new C(t,{message:`No response body`,sessionId:e.sessionId});let n=lt.parse();ft(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new w(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:a}=k.parse(i.value);return{command:a,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new w(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=Ge.parse(t.value);return e}let n=Je.parse(t.value);if(n.stream===`error`)throw new w(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?T(Ge,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return T(Ue,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return T(Ke,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new at;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await ot(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return T(We,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return T(Ye,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return T(Ze,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:st({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await T(Ke,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new C(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:x.fromWeb(t.body)}async killCommand(e){return T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?pt(e.signal,n.signal):n.signal,i=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,i=await t.request(n,{method:`GET`,signal:r});if(i.ok||await T(u(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new C(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new C(i,{message:`No response body`,sessionId:e.sessionId});let a=lt.parse();ft(i.body,a,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of a){let n=Je.parse(t);if(n.stream===`error`)throw new w(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(i,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return T(et,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return T(Ve,await this.request(t,{method:`POST`,body:JSON.stringify(j(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return T(Ve,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return T(Qe,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return T($e,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return T($e,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=M(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),T(tt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return T(nt,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:mt(e.tags)},method:`GET`,signal:e.signal}))}async updateSandbox(e){return T(rt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,timeout:e.timeout,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions}),signal:e.signal}))}async deleteSandbox(e){return T(rt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId,deleteOrphanSnapshots:e.deleteOrphanSnapshots?`true`:void 0},signal:e.signal}))}};async function ft(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function pt(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function mt(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>`${e}:${t}`)}function ht(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var P=e(v(),1);const gt={warn:P.default.yellow,error:P.default.red,success:P.default.green,info:P.default.blue},_t=P.default.dim(`[vercel/sandbox]`);function F(e,t){t=Array.isArray(t)?t.join(`
|
|
2
|
-
`):t;let n=t.replace(/^/gm,`${_t} `);console.error(gt[e](n))}function vt(e){return P.default.italic(P.default.dim("`")+e+P.default.dim("`"))}var yt=e(r(),1);async function bt(){return await import(`../../_chunks/node/auth-
|
|
1
|
+
import{o as e}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as r}from"../../_chunks/node/retry-qwFNGj4P.js";import{a as i,f as a,g as o,l as s,o as c,p as l,s as u,t as d,u as f,v as p,y as m}from"../../_chunks/node/schemas-cFtr4EoN.js";import{t as h}from"../../_chunks/node/undici-CUIybhQ2.js";import{a as g,c as _,i as v,n as y,o as ee,r as te,s as ne,t as b}from"../../_chunks/node/decode_jwt-Col8JOnf.js";import{t as re}from"../../_chunks/node/version-DH6yRy-M.js";import{Readable as x}from"stream";import S,{dirname as ie,resolve as ae}from"path";import{createWriteStream as oe}from"fs";import se from"zlib";import ce from"os";import{pipeline as le}from"stream/promises";import{mkdir as ue}from"fs/promises";import*as de from"node:constants";import{setTimeout as fe}from"node:timers/promises";var C=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},w=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};const pe=`iad1`;function me(e){return e==null?[]:Array.isArray(e)?e:[e]}var he=e(_(),1);function ge(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,he.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new C(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await _e(e*1e3,n.signal),new C(o)}if(o.status>=500&&o.status<600)throw new C(o);return o}catch(e){if(ve(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof C)return e.response;throw e}}}async function _e(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function ve(e){return e!=null&&e.name===`AbortError`}const ye=new(h()).Agent({bodyTimeout:0});var be=class{constructor(e){this.fetch=ge(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=ye}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))me(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function xe(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function Se(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}const Ce=l({error:l({message:p()})});function we(e){let t=Ce.safeParse(e);return t.success?t.data.error.message:void 0}async function Te(e,t){let n=xe(t.url),r;n||(r=Se(t.url));let i=await t.text().catch(e=>new C(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new C(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok){let e=we(a);return new C(t,{message:e?`Status code ${t.status} is not ok: ${e}`:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r})}let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new C(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function T(e,t){let n=await Te(e,t);if(n instanceof C)throw n;return n}const Ee=l({exact:p().optional(),startsWith:p().optional(),regex:p().optional()}),De=l({key:Ee.optional(),value:Ee.optional()}),Oe=l({path:Ee.optional(),method:c(p()).optional(),queryString:c(De).optional(),headers:c(De).optional()}),ke=l({domain:p(),headers:o(p(),p()).optional(),headerNames:c(p()).optional(),match:Oe.optional()}),Ae=l({domain:p(),forwardURL:p(),match:Oe.optional()}),je=l({headers:o(p(),p()).optional()}),Me=l({match:Oe.optional(),transform:c(je).optional(),forwardURL:p().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),Ne=l({allow:m([c(p()),o(p(),c(Me))]).optional(),subnets:l({allow:c(p()).optional(),deny:c(p()).optional()}).optional()}),Pe=m([l({mode:f(`allow-all`)}).passthrough(),l({mode:f(`deny-all`)}).passthrough()]),Fe=l({mode:f(`custom`),allowedDomains:c(p()).optional(),allowedCIDRs:c(p()).optional(),deniedCIDRs:c(p()).optional(),injectionRules:c(ke).optional(),forwardRules:c(Ae).optional()}).passthrough(),Ie=m([Pe,Ne.passthrough()]),Le=m([Pe,Fe]),E=l({id:p(),memory:a(),vcpus:a(),region:p(),runtime:p().optional(),timeout:a(),status:d([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:a(),startedAt:a().optional(),requestedStopAt:a().optional(),stoppedAt:a().optional(),abortedAt:a().optional(),duration:a().optional(),sourceSnapshotId:p().optional(),snapshottedAt:a().optional(),createdAt:a(),cwd:p(),updatedAt:a(),interactivePort:a().optional(),networkPolicy:Le.optional(),activeCpuDurationMs:a().optional(),networkTransfer:l({ingress:a(),egress:a()}).optional()}),Re=l({url:p(),subdomain:p(),port:a()}),D=l({id:p(),sourceSessionId:p(),region:p(),regions:c(p()).optional(),status:d([`created`,`deleted`,`failed`]),sizeBytes:a(),expiresAt:a().optional(),createdAt:a(),updatedAt:a(),lastUsedAt:a().optional(),creationMethod:p().optional(),parentId:p().optional()}),O=l({count:a(),next:p().nullable()}),ze=l({id:p(),name:p(),args:c(p()),cwd:p(),sessionId:p(),exitCode:a().nullable(),durationMs:a().optional(),startedAt:a()}),Be=ze.extend({exitCode:a()}),Ve=l({session:E.passthrough()}),He=Ve.extend({routes:c(Re)}),Ue=l({url:p(),token:p()}),We=l({sessions:c(E.passthrough()),pagination:O}),k=l({command:ze}),Ge=l({command:Be}),Ke=l({}),qe=l({data:p()}),Je=s(`stream`,[qe.extend({stream:f(`stdout`)}),qe.extend({stream:f(`stderr`)}),l({stream:f(`error`),data:l({code:p(),message:p()})})]),Ye=l({snapshots:c(D),pagination:O}),Xe=l({snapshot:D,siblings:c(D),count:p()}),Ze=l({snapshots:c(Xe),anchor:Xe.optional(),pagination:O}),Qe=l({snapshot:D,session:E.passthrough()}),$e=l({snapshot:D}),A=l({name:p(),persistent:u(),region:p().optional(),failoverRegions:c(p()).optional(),vcpus:a().optional(),memory:a().optional(),runtime:p().optional(),image:p().optional(),timeout:a().optional(),networkPolicy:Le.optional(),totalEgressBytes:a().optional(),totalIngressBytes:a().optional(),totalActiveCpuDurationMs:a().optional(),totalDurationMs:a().optional(),createdAt:a(),updatedAt:a(),expiresAt:a().optional(),currentSessionId:p(),currentSnapshotId:p().optional(),status:E.shape.status,statusUpdatedAt:a().optional(),cwd:p().optional(),tags:o(p(),p()).optional(),snapshotExpiration:a().optional(),keepLastSnapshots:l({count:a(),expiration:a().optional(),deleteEvicted:u().optional()}).optional()}),et=l({session:E.passthrough(),sandbox:A.optional(),snapshot:D.optional()}),tt=l({sandbox:A,session:E.passthrough(),routes:c(Re),resumed:u().optional()}),nt=l({sandboxes:c(A),pagination:O}),rt=l({sandbox:A,routes:c(Re).optional()});var it=e(ne(),1),at=class{constructor(){let e=se.createGzip();this.pack=it.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof x?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function ot(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function st(e){if(!S.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!S.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=S.posix.isAbsolute(e.filePath)?S.posix.normalize(e.filePath):S.posix.join(e.cwd,e.filePath);return S.posix.relative(e.extractDir,t)}function j(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ie.parse(t),t}function ct(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const M=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var lt=e(ee(),1),ut=g();function dt(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var N=class extends be{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=dt(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,ut.getVercelOidcToken)({expirationBufferMs:300*1e3,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=dt(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${re} (Node.js/${process.version}; ${ce.platform()}/${ce.arch()})`,...t?.headers}})}async getSession(e){let t=M(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,T(He,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=M(e),n=e.runtime===void 0?`/v3/sandboxes`:`/v2/sandboxes`;return T(tt,await this.request(n,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async forkSandbox(e){let t=M(e);return T(tt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await T(i(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new C(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new C(t,{message:`No response body`,sessionId:e.sessionId});let n=lt.parse();ft(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),a=await r.next();if(a.done)throw new w(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:o}=k.parse(a.value);return{command:o,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new w(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=Ge.parse(t.value);return e}let n=Je.parse(t.value);if(n.stream===`error`)throw new w(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?T(Ge,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return T(Ue,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return T(Ke,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new at;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await ot(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return T(We,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return T(Ye,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return T(Ze,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:st({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await T(Ke,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new C(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:x.fromWeb(t.body)}async killCommand(e){return T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?pt(e.signal,n.signal):n.signal,a=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,a=await t.request(n,{method:`GET`,signal:r});if(a.ok||await T(i(),a),a.headers.get(`content-type`)!==`application/x-ndjson`)throw new C(a,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(a.body===null)throw new C(a,{message:`No response body`,sessionId:e.sessionId});let o=lt.parse();ft(a.body,o,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of o){let n=Je.parse(t);if(n.stream===`error`)throw new w(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(a,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return T(et,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return T(Ve,await this.request(t,{method:`POST`,body:JSON.stringify(j(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return T(Ve,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return T(Qe,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return T($e,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return T($e,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=M(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),T(tt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return T(nt,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:mt(e.tags)},method:`GET`,signal:e.signal}))}async updateSandbox(e){return T(rt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,timeout:e.timeout,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions}),signal:e.signal}))}async deleteSandbox(e){return T(rt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId,deleteOrphanSnapshots:e.deleteOrphanSnapshots?`true`:void 0},signal:e.signal}))}};async function ft(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function pt(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function mt(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>`${e}:${t}`)}function ht(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var P=e(v(),1);const gt={warn:P.default.yellow,error:P.default.red,success:P.default.green,info:P.default.blue},_t=P.default.dim(`[vercel/sandbox]`);function F(e,t){t=Array.isArray(t)?t.join(`
|
|
2
|
+
`):t;let n=t.replace(/^/gm,`${_t} `);console.error(gt[e](n))}function vt(e){return P.default.italic(P.default.dim("`")+e+P.default.dim("`"))}var yt=e(r(),1);async function bt(){return await import(`../../_chunks/node/auth-BSKyPAEP.js`)}function xt(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const St=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,Ct(t).catch(t=>{throw e=null,t})]);let n=await e[1];return F(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function Ct(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await bt(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await wt({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${P.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
|
|
3
3
|
`));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&F(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function wt(e,t){F(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${P.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();F(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${P.default.italic(r.verification_uri)} and type ${P.default.bold(r.user_code)}`,` Press ${P.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${P.default.bold(`help:`)} Link your project with ${vt(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
|
|
4
4
|
`);i=Error(e),a.return()},(0,yt.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw F(`error`,`${P.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return F(`success`,`${P.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var Tt=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
|
|
5
5
|
`);super(t,{cause:e}),this.name=`LocalOidcContextError`}},Et=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
|
|
6
|
-
`);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function Dt(e){try{return At(await(0,ut.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!xt())throw process.env.VERCEL_URL?new Et(t):new Tt(t);return await St(e)}}async function I(e){return Ot(e??{})||await Dt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Ot(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const kt=l({exp:p().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:p().optional().describe(`Issued at timestamp`),owner_id:c(),project_id:c()});function At(e){try{let t=kt.parse(ht(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const jt={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function Mt(e){if(typeof e==`number`)return e;if(e in jt)return jt[e];throw Error(`Unknown signal name: ${String(e)}`)}var L=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[t](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new R({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:Mt(e??`SIGTERM`),abortSignal:t?.abortSignal})}},R=class e extends L{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[t](e){return{...L[t](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function z(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){Nt(i);let t=e;for(yield t;t.pagination.next!==null;)Nt(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)Nt(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function Nt(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var Pt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get regions(){return this.snapshot.regions??[this.snapshot.region]}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[t](e){return{snapshot:e.snapshot}}static[n](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return z(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await I(t),r=new N({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function B(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?ct(t):void 0}}var V=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[t](e){return{session:e.session,routes:e.routes}}static[n](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=B(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new L({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new R({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new L({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:ot(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=ae(t.cwd??``,t.path);return n?.mkdirRecursive&&await ue(ie(e),{recursive:!0}),await le(i,oe(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=B(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=B((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=B((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=B(n.json.session),new Pt({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:H,S_IFREG:Ft,S_IFDIR:It,S_IFLNK:Lt,S_IFBLK:Rt,S_IFCHR:zt,S_IFIFO:Bt,S_IFSOCK:Vt}=de;function U(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function Ht(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var Ut=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&H)===Ft}isDirectory(){return(this.mode&H)===It}isBlockDevice(){return(this.mode&H)===Rt}isCharacterDevice(){return(this.mode&H)===zt}isSymbolicLink(){return(this.mode&H)===Lt}isFIFO(){return(this.mode&H)===Bt}isSocket(){return(this.mode&H)===Vt}},Wt=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function Gt(e){let t=e.trim().split(`|`);return new Ut(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function Kt(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw U(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new Wt(r,Jt[i]??1,t)}const qt=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,Jt={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var Yt=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=Ht(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw U(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw U(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`scandir`,e):U(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
|
|
6
|
+
`);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function Dt(e){try{return At(await(0,ut.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!xt())throw process.env.VERCEL_URL?new Et(t):new Tt(t);return await St(e)}}async function I(e){return Ot(e??{})||await Dt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Ot(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const kt=l({exp:a().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:a().optional().describe(`Issued at timestamp`),owner_id:p(),project_id:p()});function At(e){try{let t=kt.parse(ht(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const jt={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function Mt(e){if(typeof e==`number`)return e;if(e in jt)return jt[e];throw Error(`Unknown signal name: ${String(e)}`)}var L=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[t](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new R({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:Mt(e??`SIGTERM`),abortSignal:t?.abortSignal})}},R=class e extends L{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[t](e){return{...L[t](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function z(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){Nt(i);let t=e;for(yield t;t.pagination.next!==null;)Nt(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)Nt(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function Nt(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var Pt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get regions(){return this.snapshot.regions??[this.snapshot.region]}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[t](e){return{snapshot:e.snapshot}}static[n](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return z(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await I(t),r=new N({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function B(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?ct(t):void 0}}var V=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[t](e){return{session:e.session,routes:e.routes}}static[n](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=B(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new L({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new R({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new L({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:ot(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=ae(t.cwd??``,t.path);return n?.mkdirRecursive&&await ue(ie(e),{recursive:!0}),await le(i,oe(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=B(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=B((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=B((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=B(n.json.session),new Pt({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:H,S_IFREG:Ft,S_IFDIR:It,S_IFLNK:Lt,S_IFBLK:Rt,S_IFCHR:zt,S_IFIFO:Bt,S_IFSOCK:Vt}=de;function U(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function Ht(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var Ut=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&H)===Ft}isDirectory(){return(this.mode&H)===It}isBlockDevice(){return(this.mode&H)===Rt}isCharacterDevice(){return(this.mode&H)===zt}isSymbolicLink(){return(this.mode&H)===Lt}isFIFO(){return(this.mode&H)===Bt}isSocket(){return(this.mode&H)===Vt}},Wt=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function Gt(e){let t=e.trim().split(`|`);return new Ut(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function Kt(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw U(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new Wt(r,Jt[i]??1,t)}const qt=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,Jt={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var Yt=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=Ht(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw U(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw U(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`scandir`,e):U(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
|
|
7
7
|
`).filter(Boolean).map(t=>Kt(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`scandir`,e):U(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
|
|
8
8
|
`).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,qt,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`stat`,e):U(`EACCES`,t.trim(),`stat`,e)}return Gt(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,qt,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`lstat`,e):U(`EACCES`,t.trim(),`lstat`,e)}return Gt(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`unlink`,e):U(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`rm`,e):U(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?U(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):U(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`rename`,e):U(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`copyfile`,e):U(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw U(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`chmod`,e):U(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`chown`,e):U(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?U(`EEXIST`,`file already exists`,`symlink`,t):U(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`readlink`,e):U(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`realpath`,e):U(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`truncate`,e):U(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw U(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const Xt=/^[a-z_][a-z0-9_-]*$/;function W(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!Xt.test(e))throw Error(`Invalid ${t} "${e}": must match ${Xt} (lowercase letters, digits, hyphens, underscores)`)}var Zt=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},G=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:x.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=ae(t.cwd??``,t.path);return n?.mkdirRecursive&&await ue(ie(i),{recursive:!0}),await le(r,oe(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){W(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){W(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function K(e){return e instanceof C&&e.response.status===410}function Qt(e){return e instanceof C&&e.response.status===404}function $t(e){return e instanceof C&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function q(e){return e instanceof C&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function en(e){return e instanceof C&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var tn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region??`iad1`}get failoverRegions(){return this.sandbox.failoverRegions??[]}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get networkPolicy(){return this.sandbox.networkPolicy?ct(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[t](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[n](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new V({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";if(e?.runtime!==void 0&&e.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=M(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,region:e?.region,failoverRegions:e?.failoverRegions,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new nn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=M(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,persistent:e.persistent,signal:e.signal,...r});return new nn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await I(t),r=new N({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=M(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(t?.runtime!==void 0&&t.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(Qt(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if($t(n)){let n=await I(t),r=new N({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=M(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!Qt(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new V({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new Yt(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new V({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await fe(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new V({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(K(n))return await this.resume(t),e();if(q(n)||en(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
|
|
9
9
|
`);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){W(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new Zt(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new G({sandbox:this,username:e})}asUser(e){return W(e,`username`),new G({sandbox:this,username:e})}async createGroup(e,t){W(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){W(e,`username`),W(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){W(e,`username`),W(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!K(e)&&!q(e))throw e}}if(e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(K(e)||q(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,deleteOrphanSnapshots:e?.deleteOrphanSnapshots,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},nn=class extends tn{async[Symbol.asyncDispose](){await this.stop()}};const J=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,rn=new Set,an=typeof process==`object`&&process?process:{},on=(e,t,n,r)=>{typeof an.emitWarning==`function`?an.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let Y=globalThis.AbortController,sn=globalThis.AbortSignal;if(Y===void 0){sn=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},Y=class{constructor(){t()}signal=new sn;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=an.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,on("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}const cn=e=>!rn.has(e),X=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),ln=e=>X(e)?e<=2**8?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?Z:null:null;var Z=class extends Array{constructor(e){super(e),this.fill(0)}},un=class e{heap;length;static#e=!1;static create(t){let n=ln(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},dn=class e{#e;#t;#n;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#y,sizes:e.#_,keyMap:e.#c,keyList:e.#l,valList:e.#u,next:e.#d,prev:e.#f,get head(){return e.#p},get tail(){return e.#m},free:e.#h,isBackgroundFetch:t=>e.#L(t),backgroundFetch:(t,n,r,i)=>e.#I(t,n,r,i),moveToTail:t=>e.#z(t),indexes:t=>e.#M(t),rindexes:t=>e.#N(t),isStale:t=>e.#D(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#s}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:_,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:ee,allowStaleOnFetchAbort:te,ignoreFetchAbort:ne}=t;if(n!==0&&!X(n))throw TypeError(`max option must be a nonnegative integer`);let b=n?ln(n):Array;if(!b)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=p,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(_!==void 0&&typeof _!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#a=_,g!==void 0&&typeof g!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#i=g,this.#x=!!g,this.#c=new Map,this.#l=Array(n).fill(void 0),this.#u=Array(n).fill(void 0),this.#d=new b(n),this.#f=new b(n),this.#p=0,this.#m=0,this.#h=un.create(n),this.#o=0,this.#s=0,typeof l==`function`&&(this.#n=l),typeof u==`function`?(this.#r=u,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#b=!!this.#n,this.#S=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!ee,this.allowStaleOnFetchAbort=!!te,this.ignoreFetchAbort=!!ne,this.maxEntrySize!==0){if(this.#t!==0&&!X(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!X(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#O()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=X(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!X(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#C()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;cn(t)&&(rn.add(t),on(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#C(){let e=new Z(this.#e),t=new Z(this.#e);this.#y=e,this.#v=t,this.#E=(n,r,i=J.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#D(n)&&this.#B(this.#l[n],`expire`)},r+1);e.unref&&e.unref()}},this.#w=n=>{t[n]=e[n]===0?0:J.now()},this.#T=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r(),i.remainingTTL=o-(i.now-s)}};let n=0,r=()=>{let e=J.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#c.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((n||r())-s)},this.#D=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#w=()=>{};#T=()=>{};#E=()=>{};#D=()=>!1;#O(){let e=new Z(this.#e);this.#s=0,this.#_=e,this.#k=t=>{this.#s-=e[t],e[t]=0},this.#j=(e,t,n,r)=>{if(this.#L(t))return 0;if(!X(n))if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!X(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`);return n},this.#A=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#s>n;)this.#F(!0)}this.#s+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#s)}}#k=e=>{};#A=(e,t,n)=>{};#j=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#m;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#p));)t=this.#f[t]}*#N({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#p;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#m));)t=this.#d[t]}#P(e){return e!==void 0&&this.#c.get(this.#l[e])===e}*entries(){for(let e of this.#M())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*rentries(){for(let e of this.#N())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*keys(){for(let e of this.#M()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*rkeys(){for(let e of this.#N()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*values(){for(let e of this.#M())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}*rvalues(){for(let e of this.#N())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#N()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#N({allowStale:!0}))this.#D(t)&&(this.#B(this.#l[t],`expire`),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#u[t],r=this.#L(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#y&&this.#v){let e=this.#y[t],n=this.#v[t];e&&n&&(i.ttl=e-(J.now()-n),i.start=Date.now())}return this.#_&&(i.size=this.#_[t]),i}dump(){let e=[];for(let t of this.#M({allowStale:!0})){let n=this.#l[t],r=this.#u[t],i=this.#L(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#y&&this.#v){a.ttl=this.#y[t];let e=J.now()-this.#v[t];a.start=Math.floor(Date.now()-e)}this.#_&&(a.size=this.#_[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=J.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#j(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#B(e,`set`),this;let u=this.#o===0?void 0:this.#c.get(e);if(u===void 0)u=this.#o===0?this.#m:this.#h.length===0?this.#o===this.#e?this.#F(!1):this.#o:this.#h.pop(),this.#l[u]=e,this.#u[u]=t,this.#c.set(e,u),this.#d[this.#m]=u,this.#f[u]=this.#m,this.#m=u,this.#o++,this.#A(u,l,s),s&&(s.set=`add`),c=!1;else{this.#z(u);let n=this.#u[u];if(t!==n){if(this.#x&&this.#L(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#b&&this.#n?.(t,e,`set`),this.#S&&this.#g?.push([t,e,`set`]))}else a||(this.#b&&this.#n?.(n,e,`set`),this.#S&&this.#g?.push([n,e,`set`]));if(this.#k(u),this.#A(u,l,s),this.#u[u]=t,s){s.set=`replace`;let e=n&&this.#L(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`)}if(r!==0&&!this.#y&&this.#C(),this.#y&&(c||this.#E(u,r,i),s&&this.#T(s,u)),!a&&this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return this}pop(){try{for(;this.#o;){let e=this.#u[this.#p];if(this.#F(!0),this.#L(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],r=this.#u[t];return this.#x&&this.#L(r)?r.__abortController.abort(Error(`evicted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(r,n,`evict`),this.#S&&this.#g?.push([r,n,`evict`])),this.#k(t),e&&(this.#l[t]=void 0,this.#u[t]=void 0,this.#h.push(t)),this.#o===1?(this.#p=this.#m=0,this.#h.length=0):this.#p=this.#d[t],this.#c.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#c.get(e);if(i!==void 0){let e=this.#u[i];if(this.#L(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#D(i))r&&(r.has=`stale`,this.#T(r,i));else return n&&this.#w(i),r&&(r.has=`hit`,this.#T(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#c.get(e);if(r===void 0||!n&&this.#D(r))return;let i=this.#u[r];return this.#L(i)?i.__staleWhileFetching:i}#I(e,t,n,r){let i=t===void 0?void 0:this.#u[t];if(this.#L(i))return i;let a=new Y,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#u[t]===f&&(r===void 0?l.__staleWhileFetching?this.#u[t]=l.__staleWhileFetching:this.#B(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#u[t]===f&&(!c||l.__staleWhileFetching===void 0?this.#B(e,`fetch`):o||(this.#u[t]=l.__staleWhileFetching)),s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#i?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#c.get(e)):this.#u[t]=p,p}#L(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof Y}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#x)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#c.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#I(e,y,v,m);return t.__returned=t}else{let t=this.#u[y];if(this.#L(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#D(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#z(y),r&&this.#w(y),g&&this.#T(g,y),t;let a=this.#I(e,y,v,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#a;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#c.get(e);if(o!==void 0){let t=this.#u[o],s=this.#L(t);return a&&this.#T(a,o),this.#D(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#B(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#z(o),r&&this.#w(o),t))}else a&&(a.get=`miss`)}#R(e,t){this.#f[t]=e,this.#d[e]=t}#z(e){e!==this.#m&&(e===this.#p?this.#p=this.#d[e]:this.#R(this.#f[e],this.#d[e]),this.#R(this.#m,e),this.#m=e)}delete(e){return this.#B(e,`delete`)}#B(e,t){let n=!1;if(this.#o!==0){let r=this.#c.get(e);if(r!==void 0)if(n=!0,this.#o===1)this.#V(t);else{this.#k(r);let n=this.#u[r];if(this.#L(n)?n.__abortController.abort(Error(`deleted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(n,e,t),this.#S&&this.#g?.push([n,e,t])),this.#c.delete(e),this.#l[r]=void 0,this.#u[r]=void 0,r===this.#m)this.#m=this.#f[r];else if(r===this.#p)this.#p=this.#d[r];else{let e=this.#f[r];this.#d[e]=this.#d[r];let t=this.#d[r];this.#f[t]=this.#f[r]}this.#o--,this.#h.push(r)}}if(this.#S&&this.#g?.length){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return n}clear(){return this.#V(`delete`)}#V(e){for(let t of this.#N({allowStale:!0})){let n=this.#u[t];if(this.#L(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#l[t];this.#b&&this.#n?.(n,r,e),this.#S&&this.#g?.push([n,r,e])}}if(this.#c.clear(),this.#u.fill(void 0),this.#l.fill(void 0),this.#y&&this.#v&&(this.#y.fill(0),this.#v.fill(0)),this.#_&&this.#_.fill(0),this.#p=0,this.#m=0,this.#h.length=0,this.#s=0,this.#o=0,this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}};const fn=`vercel-forwarded-host`,pn=`vercel-forwarded-scheme`,mn=`vercel-forwarded-port`,hn=`vercel-forwarded-path`,gn=`vercel-sandbox-oidc-token`,_n=new dn({max:100});function vn(e,t=yn){return async function(n){let r=new Headers(n.headers),i=r.get(fn),a=r.get(pn),o=r.get(mn),s=r.get(hn),c=r.get(gn);if(r.delete(fn),r.delete(pn),r.delete(mn),r.delete(hn),r.delete(gn),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(bn(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=xn(new URL(n.url),s),r=await Cn(c,t),i=Sn(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function yn(){return new Response(`Forbidden`,{status:403})}function bn(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function xn(e,t){let n=Q(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=Q(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=Q(r.pathname.slice(0,-n.length))),r}function Q(e){return e.replace(/\/+$/,``)||`/`}function Sn(e,t){let n=$(t,`team_id`),r=$(t,`project_id`),i=$(t,`sandbox_id`),a=$(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function Cn(e,t){let n=$(b(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await te(e,Tn(n),{audience:wn(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function wn(e){let t=Q(e.pathname);return t===`/`?e.origin:e.origin+t}function Tn(e){let t=_n.get(e);if(t)return t;let n=y(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return _n.set(e,n),n}function $(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{C as APIError,L as Command,R as CommandFinished,pe as DEFAULT_SANDBOX_REGION,Yt as FileSystem,tn as Sandbox,G as SandboxUser,Zt as SandboxUserAlreadyExistsError,V as Session,Pt as Snapshot,w as StreamError,vn as defineSandboxProxy};
|