@mastra/deployer-sandbox 0.0.0 → 0.1.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +30 -0
- package/dist/alias.d.ts +10 -0
- package/dist/alias.d.ts.map +1 -0
- package/dist/chunk-CSXC6CZL.cjs +115 -0
- package/dist/chunk-CSXC6CZL.cjs.map +1 -0
- package/dist/chunk-Z636GNUQ.js +101 -0
- package/dist/chunk-Z636GNUQ.js.map +1 -0
- package/dist/client/index.cjs +159 -0
- package/dist/client/index.cjs.map +1 -0
- package/dist/client/index.d.ts +98 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +155 -0
- package/dist/client/index.js.map +1 -0
- package/dist/deployer.d.ts +57 -0
- package/dist/deployer.d.ts.map +1 -0
- package/dist/engine.d.ts +19 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/index.cjs +381 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +372 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest.d.ts +7 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/shared.d.ts +63 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/studio/assets/CommitMono-400-Regular-DzkyLZ26.woff2 +0 -0
- package/dist/studio/assets/CommitMono-700-Regular-DmOSN4kd.woff2 +0 -0
- package/dist/studio/assets/MonaSans-VariableFont_wdth-wght-CX-7s9jm.ttf +0 -0
- package/dist/studio/assets/babel-lWBcy2sH.js +16 -0
- package/dist/studio/assets/bash-atvbtKCR.js +1 -0
- package/dist/studio/assets/core-kRNZLmmj.js +12 -0
- package/dist/studio/assets/engine-compile-BkERmzkH.js +137 -0
- package/dist/studio/assets/engine-javascript-CSIo_1eZ.js +1 -0
- package/dist/studio/assets/estree-Dd9JfUIE.js +44 -0
- package/dist/studio/assets/github-dark-DHJKELXO.js +1 -0
- package/dist/studio/assets/github-light-DAi9KRSo.js +1 -0
- package/dist/studio/assets/index-LFLxh8sD.js +2 -0
- package/dist/studio/assets/index-yUiD89B4.js +1 -0
- package/dist/studio/assets/javascript-ySlJ1b_l.js +1 -0
- package/dist/studio/assets/json-BQoSv7ci.js +1 -0
- package/dist/studio/assets/jsx-BAng5TT0.js +1 -0
- package/dist/studio/assets/livekit-client.esm-CKIgC2IJ.js +39 -0
- package/dist/studio/assets/main-DLJrsCT1.js +780 -0
- package/dist/studio/assets/markdown-UIAJJxZW.js +1 -0
- package/dist/studio/assets/preload-helper-PPVm8Dsz.js +1 -0
- package/dist/studio/assets/python-DhUJRlN_.js +1 -0
- package/dist/studio/assets/shell-CjFT_Tl9.js +1 -0
- package/dist/studio/assets/standalone-Dfz2oS5J.js +29 -0
- package/dist/studio/assets/style-C3ow9ANP.css +1 -0
- package/dist/studio/assets/tsx-B6W0miNI.js +1 -0
- package/dist/studio/assets/typescript-Dj6nwHGl.js +1 -0
- package/dist/studio/index.html +100 -0
- package/dist/studio/mastra.svg +17 -0
- package/dist/studio/routes-manifest.json +27 -0
- package/dist/types.d.ts +90 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +18 -18
package/LICENSE.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Portions of this software are licensed as follows:
|
|
2
|
+
|
|
3
|
+
- All content that resides under any directory named "ee/" within this
|
|
4
|
+
repository, including but not limited to:
|
|
5
|
+
- `packages/core/src/auth/ee/`
|
|
6
|
+
- `packages/server/src/server/auth/ee/`
|
|
7
|
+
is licensed under the license defined in `ee/LICENSE`.
|
|
8
|
+
|
|
9
|
+
- All third-party components incorporated into the Mastra Software are
|
|
10
|
+
licensed under the original license provided by the owner of the
|
|
11
|
+
applicable component.
|
|
12
|
+
|
|
13
|
+
- Content outside of the above-mentioned directories or restrictions is
|
|
14
|
+
available under the "Apache License 2.0" as defined below.
|
|
15
|
+
|
|
16
|
+
# Apache License 2.0
|
|
17
|
+
|
|
18
|
+
Copyright (c) 2025 Kepler Software, Inc.
|
|
19
|
+
|
|
20
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
21
|
+
you may not use this file except in compliance with the License.
|
|
22
|
+
You may obtain a copy of the License at
|
|
23
|
+
|
|
24
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
25
|
+
|
|
26
|
+
Unless required by applicable law or agreed to in writing, software
|
|
27
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
28
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
29
|
+
See the License for the specific language governing permissions and
|
|
30
|
+
limitations under the License.
|
package/dist/alias.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SandboxAliasOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Upsert a Vercel Edge Config item so a stable key always points at the
|
|
4
|
+
* current sandbox URL. Used for Tier 3 routing: apps read the key from Edge
|
|
5
|
+
* Config (e.g. in middleware) instead of hardcoding the rotating sandbox URL.
|
|
6
|
+
*/
|
|
7
|
+
export declare function updateEdgeConfigAlias(options: SandboxAliasOptions & {
|
|
8
|
+
url: string;
|
|
9
|
+
}): Promise<void>;
|
|
10
|
+
//# sourceMappingURL=alias.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"alias.d.ts","sourceRoot":"","sources":["../src/alias.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAEnD;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,mBAAmB,GAAG;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA6BzG"}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/shared.ts
|
|
4
|
+
var REMOTE_DIR_NAME = "mastra-app";
|
|
5
|
+
var DEFAULT_PORT = 4111;
|
|
6
|
+
var SERVER_SCRIPT = ".mastra-server.sh";
|
|
7
|
+
var SERVER_PIDFILE = ".mastra-server.pid";
|
|
8
|
+
var SERVER_LOGFILE = ".mastra-server.log";
|
|
9
|
+
var INSTALL_MARKER = ".mastra-install-hash";
|
|
10
|
+
async function getInfoSafe(sandbox) {
|
|
11
|
+
try {
|
|
12
|
+
return await sandbox.getInfo?.();
|
|
13
|
+
} catch {
|
|
14
|
+
return void 0;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function resolveRemoteDir(sandbox, remoteDir) {
|
|
18
|
+
if (remoteDir) return remoteDir;
|
|
19
|
+
const result = await runInSandbox(sandbox, `printf %s "\${HOME:-$(pwd)}"`, { allowFailure: true });
|
|
20
|
+
const base = result.stdout.trim();
|
|
21
|
+
if (!base) {
|
|
22
|
+
throw new Error("Could not resolve the sandbox home directory. Pass `remoteDir` explicitly.");
|
|
23
|
+
}
|
|
24
|
+
return `${base}/${REMOTE_DIR_NAME}`;
|
|
25
|
+
}
|
|
26
|
+
function shellQuote(value) {
|
|
27
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
28
|
+
}
|
|
29
|
+
async function runInSandbox(sandbox, script, opts) {
|
|
30
|
+
if (!sandbox.executeCommand) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
`Sandbox provider "${sandbox.provider}" does not support executeCommand, which is required for sandbox deploys.`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
const result = await sandbox.executeCommand(
|
|
36
|
+
"sh",
|
|
37
|
+
["-c", script],
|
|
38
|
+
opts?.timeout ? { timeout: opts.timeout } : void 0
|
|
39
|
+
);
|
|
40
|
+
if (!result.success && !opts?.allowFailure) {
|
|
41
|
+
const what = opts?.label ?? truncate(script, 120);
|
|
42
|
+
throw new Error(
|
|
43
|
+
`Command failed inside sandbox (exit ${result.exitCode}): ${what}
|
|
44
|
+
${truncate(result.stderr || result.stdout, 4e3)}`
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
|
|
48
|
+
}
|
|
49
|
+
function truncate(value, max) {
|
|
50
|
+
return value.length > max ? `${value.slice(0, max)}\u2026 (truncated)` : value;
|
|
51
|
+
}
|
|
52
|
+
async function killPreviousServer(sandbox, remoteDir) {
|
|
53
|
+
const pidfile = shellQuote(`${remoteDir}/${SERVER_PIDFILE}`);
|
|
54
|
+
const script = [
|
|
55
|
+
`if [ -f ${pidfile} ]; then`,
|
|
56
|
+
` pid="$(cat ${pidfile})"`,
|
|
57
|
+
` kill "$pid" 2>/dev/null || true`,
|
|
58
|
+
// Wait up to ~5s for the old server to release the port, then force-kill.
|
|
59
|
+
` i=0`,
|
|
60
|
+
` while kill -0 "$pid" 2>/dev/null && [ "$i" -lt 50 ]; do sleep 0.1; i=$((i + 1)); done`,
|
|
61
|
+
` kill -9 "$pid" 2>/dev/null || true`,
|
|
62
|
+
` rm -f ${pidfile}`,
|
|
63
|
+
`fi`
|
|
64
|
+
].join("\n");
|
|
65
|
+
await runInSandbox(sandbox, script, { allowFailure: true, timeout: 15e3 });
|
|
66
|
+
}
|
|
67
|
+
async function launchServer(sandbox, remoteDir) {
|
|
68
|
+
const script = `${remoteDir}/${SERVER_SCRIPT}`;
|
|
69
|
+
await runInSandbox(sandbox, `nohup sh ${shellQuote(script)} >/dev/null 2>&1 & echo launched`);
|
|
70
|
+
}
|
|
71
|
+
async function tailServerLog(sandbox, remoteDir, lines = 50) {
|
|
72
|
+
const logfile = `${remoteDir}/${SERVER_LOGFILE}`;
|
|
73
|
+
const result = await runInSandbox(
|
|
74
|
+
sandbox,
|
|
75
|
+
`tail -n ${Math.floor(lines)} ${shellQuote(logfile)} 2>/dev/null || true`,
|
|
76
|
+
{
|
|
77
|
+
allowFailure: true
|
|
78
|
+
}
|
|
79
|
+
);
|
|
80
|
+
return result.stdout;
|
|
81
|
+
}
|
|
82
|
+
async function waitForHealthy(url, opts = {}) {
|
|
83
|
+
const path = opts.path ?? "/api";
|
|
84
|
+
const timeoutMs = opts.timeoutMs ?? 6e4;
|
|
85
|
+
const intervalMs = opts.intervalMs ?? 1e3;
|
|
86
|
+
const deadline = Date.now() + timeoutMs;
|
|
87
|
+
while (Date.now() < deadline) {
|
|
88
|
+
try {
|
|
89
|
+
const res = await fetch(new URL(path, url), { signal: AbortSignal.timeout(intervalMs * 5) });
|
|
90
|
+
const providerError = res.status === 410 || res.headers.has("x-vercel-error");
|
|
91
|
+
if (res.status < 500 && !providerError) {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
} catch {
|
|
95
|
+
}
|
|
96
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
97
|
+
}
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
exports.DEFAULT_PORT = DEFAULT_PORT;
|
|
102
|
+
exports.INSTALL_MARKER = INSTALL_MARKER;
|
|
103
|
+
exports.SERVER_LOGFILE = SERVER_LOGFILE;
|
|
104
|
+
exports.SERVER_PIDFILE = SERVER_PIDFILE;
|
|
105
|
+
exports.SERVER_SCRIPT = SERVER_SCRIPT;
|
|
106
|
+
exports.getInfoSafe = getInfoSafe;
|
|
107
|
+
exports.killPreviousServer = killPreviousServer;
|
|
108
|
+
exports.launchServer = launchServer;
|
|
109
|
+
exports.resolveRemoteDir = resolveRemoteDir;
|
|
110
|
+
exports.runInSandbox = runInSandbox;
|
|
111
|
+
exports.shellQuote = shellQuote;
|
|
112
|
+
exports.tailServerLog = tailServerLog;
|
|
113
|
+
exports.waitForHealthy = waitForHealthy;
|
|
114
|
+
//# sourceMappingURL=chunk-CSXC6CZL.cjs.map
|
|
115
|
+
//# sourceMappingURL=chunk-CSXC6CZL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/shared.ts"],"names":[],"mappings":";;;AAGO,IAAM,eAAA,GAAkB,YAAA;AAExB,IAAM,YAAA,GAAe;AAErB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,CAAC,GAAG,CAAA;AAG3F,MAAA,MAAM,gBAAgB,GAAA,CAAI,MAAA,KAAW,OAAO,GAAA,CAAI,OAAA,CAAQ,IAAI,gBAAgB,CAAA;AAC5E,MAAA,IAAI,GAAA,CAAI,MAAA,GAAS,GAAA,IAAO,CAAC,aAAA,EAAe;AACtC,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,IAAI,OAAA,CAAQ,CAAA,OAAA,KAAW,UAAA,CAAW,OAAA,EAAS,UAAU,CAAC,CAAA;AAAA,EAC9D;AACA,EAAA,OAAO,KAAA;AACT","file":"chunk-CSXC6CZL.cjs","sourcesContent":["import type { SandboxInfo, WorkspaceSandbox } from '@mastra/core/workspace';\n\n/** Directory name (under the sandbox user's home) that the app is deployed into by default. */\nexport const REMOTE_DIR_NAME = 'mastra-app';\n/** Default port the Mastra server listens on. */\nexport const DEFAULT_PORT = 4111;\n/** Launch script written into the remote dir. Re-running it restarts the server (e.g. after a wake). */\nexport const SERVER_SCRIPT = '.mastra-server.sh';\n/** Pidfile written by the launch script. */\nexport const SERVER_PIDFILE = '.mastra-server.pid';\n/** Server log file inside the remote dir. */\nexport const SERVER_LOGFILE = '.mastra-server.log';\n/** Marker recording the package.json hash of the last completed dependency install. */\nexport const INSTALL_MARKER = '.mastra-install-hash';\n\n/** getInfo may be sync or async, and may throw — normalize to `undefined` on failure. */\nexport async function getInfoSafe(sandbox: WorkspaceSandbox): Promise<SandboxInfo | undefined> {\n try {\n return await sandbox.getInfo?.();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve the directory the app is (or will be) deployed into. Defaults to\n * `$HOME/mastra-app` resolved inside the sandbox — home directories persist\n * across snapshot stop/resume on providers that support it, unlike `/tmp`.\n * The sandbox must be running.\n */\nexport async function resolveRemoteDir(sandbox: WorkspaceSandbox, remoteDir?: string): Promise<string> {\n if (remoteDir) return remoteDir;\n const result = await runInSandbox(sandbox, `printf %s \"\\${HOME:-$(pwd)}\"`, { allowFailure: true });\n const base = result.stdout.trim();\n if (!base) {\n throw new Error('Could not resolve the sandbox home directory. Pass `remoteDir` explicitly.');\n }\n return `${base}/${REMOTE_DIR_NAME}`;\n}\n\n/** Single-quote a value for POSIX shells. */\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Run a shell script string inside the sandbox and throw on failure. */\nexport async function runInSandbox(\n sandbox: WorkspaceSandbox,\n script: string,\n opts?: {\n allowFailure?: boolean;\n timeout?: number;\n /** Safe description used in error messages instead of the script itself. */\n label?: string;\n },\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n if (!sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support executeCommand, which is required for sandbox deploys.`,\n );\n }\n // Run via `sh -c` (argv style): providers pass `command` straight to their\n // exec API as an executable, so a raw script string with spaces would fail.\n const result = await sandbox.executeCommand(\n 'sh',\n ['-c', script],\n opts?.timeout ? { timeout: opts.timeout } : undefined,\n );\n if (!result.success && !opts?.allowFailure) {\n // Never echo the full script back: it can contain secrets (env values)\n // or entire base64 upload chunks. Use the label or a bounded excerpt.\n const what = opts?.label ?? truncate(script, 120);\n throw new Error(\n `Command failed inside sandbox (exit ${result.exitCode}): ${what}\\n${truncate(result.stderr || result.stdout, 4_000)}`,\n );\n }\n return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };\n}\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? `${value.slice(0, max)}… (truncated)` : value;\n}\n\n/**\n * Kill the previously launched server (if any) using its pidfile, waiting for\n * the process to exit (bounded, then SIGKILL) so the replacement never races\n * the old server for the port. Safe when nothing is running.\n */\nexport async function killPreviousServer(sandbox: WorkspaceSandbox, remoteDir: string): Promise<void> {\n const pidfile = shellQuote(`${remoteDir}/${SERVER_PIDFILE}`);\n const script = [\n `if [ -f ${pidfile} ]; then`,\n ` pid=\"$(cat ${pidfile})\"`,\n ` kill \"$pid\" 2>/dev/null || true`,\n // Wait up to ~5s for the old server to release the port, then force-kill.\n ` i=0`,\n ` while kill -0 \"$pid\" 2>/dev/null && [ \"$i\" -lt 50 ]; do sleep 0.1; i=$((i + 1)); done`,\n ` kill -9 \"$pid\" 2>/dev/null || true`,\n ` rm -f ${pidfile}`,\n `fi`,\n ].join('\\n');\n await runInSandbox(sandbox, script, { allowFailure: true, timeout: 15_000 });\n}\n\n/**\n * Launch (or relaunch) the server by running the recorded launch script,\n * detached via nohup. Deliberately NOT `processes.spawn()`: provider process\n * handles follow the command's log stream, which would keep the calling\n * process's event loop alive for as long as the server runs. The server's\n * lifecycle is managed through its pidfile instead.\n */\nexport async function launchServer(sandbox: WorkspaceSandbox, remoteDir: string): Promise<void> {\n const script = `${remoteDir}/${SERVER_SCRIPT}`;\n await runInSandbox(sandbox, `nohup sh ${shellQuote(script)} >/dev/null 2>&1 & echo launched`);\n}\n\n/** Tail the server log from inside the sandbox. */\nexport async function tailServerLog(sandbox: WorkspaceSandbox, remoteDir: string, lines = 50): Promise<string> {\n const logfile = `${remoteDir}/${SERVER_LOGFILE}`;\n const result = await runInSandbox(\n sandbox,\n `tail -n ${Math.floor(lines)} ${shellQuote(logfile)} 2>/dev/null || true`,\n {\n allowFailure: true,\n },\n );\n return result.stdout;\n}\n\n/**\n * Poll `${url}${path}` until the server responds. Any HTTP status below 500\n * counts as \"the server is up\" — gateway errors (502/503) mean nothing is\n * listening on the port, and 410 is what some providers (e.g. Vercel) return\n * from their edge when the sandbox itself is stopped.\n */\nexport async function waitForHealthy(\n url: string,\n opts: { path?: string; timeoutMs?: number; intervalMs?: number } = {},\n): Promise<boolean> {\n const path = opts.path ?? '/api';\n const timeoutMs = opts.timeoutMs ?? 60_000;\n const intervalMs = opts.intervalMs ?? 1_000;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n try {\n const res = await fetch(new URL(path, url), { signal: AbortSignal.timeout(intervalMs * 5) });\n // A provider-edge error header means the response came from the sandbox\n // infrastructure (stopped/unreachable VM), not from the Mastra server.\n const providerError = res.status === 410 || res.headers.has('x-vercel-error');\n if (res.status < 500 && !providerError) {\n return true;\n }\n } catch {\n // Not reachable yet.\n }\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n }\n return false;\n}\n"]}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// src/shared.ts
|
|
2
|
+
var REMOTE_DIR_NAME = "mastra-app";
|
|
3
|
+
var DEFAULT_PORT = 4111;
|
|
4
|
+
var SERVER_SCRIPT = ".mastra-server.sh";
|
|
5
|
+
var SERVER_PIDFILE = ".mastra-server.pid";
|
|
6
|
+
var SERVER_LOGFILE = ".mastra-server.log";
|
|
7
|
+
var INSTALL_MARKER = ".mastra-install-hash";
|
|
8
|
+
async function getInfoSafe(sandbox) {
|
|
9
|
+
try {
|
|
10
|
+
return await sandbox.getInfo?.();
|
|
11
|
+
} catch {
|
|
12
|
+
return void 0;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
async function resolveRemoteDir(sandbox, remoteDir) {
|
|
16
|
+
if (remoteDir) return remoteDir;
|
|
17
|
+
const result = await runInSandbox(sandbox, `printf %s "\${HOME:-$(pwd)}"`, { allowFailure: true });
|
|
18
|
+
const base = result.stdout.trim();
|
|
19
|
+
if (!base) {
|
|
20
|
+
throw new Error("Could not resolve the sandbox home directory. Pass `remoteDir` explicitly.");
|
|
21
|
+
}
|
|
22
|
+
return `${base}/${REMOTE_DIR_NAME}`;
|
|
23
|
+
}
|
|
24
|
+
function shellQuote(value) {
|
|
25
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
26
|
+
}
|
|
27
|
+
async function runInSandbox(sandbox, script, opts) {
|
|
28
|
+
if (!sandbox.executeCommand) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
`Sandbox provider "${sandbox.provider}" does not support executeCommand, which is required for sandbox deploys.`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const result = await sandbox.executeCommand(
|
|
34
|
+
"sh",
|
|
35
|
+
["-c", script],
|
|
36
|
+
opts?.timeout ? { timeout: opts.timeout } : void 0
|
|
37
|
+
);
|
|
38
|
+
if (!result.success && !opts?.allowFailure) {
|
|
39
|
+
const what = opts?.label ?? truncate(script, 120);
|
|
40
|
+
throw new Error(
|
|
41
|
+
`Command failed inside sandbox (exit ${result.exitCode}): ${what}
|
|
42
|
+
${truncate(result.stderr || result.stdout, 4e3)}`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
|
|
46
|
+
}
|
|
47
|
+
function truncate(value, max) {
|
|
48
|
+
return value.length > max ? `${value.slice(0, max)}\u2026 (truncated)` : value;
|
|
49
|
+
}
|
|
50
|
+
async function killPreviousServer(sandbox, remoteDir) {
|
|
51
|
+
const pidfile = shellQuote(`${remoteDir}/${SERVER_PIDFILE}`);
|
|
52
|
+
const script = [
|
|
53
|
+
`if [ -f ${pidfile} ]; then`,
|
|
54
|
+
` pid="$(cat ${pidfile})"`,
|
|
55
|
+
` kill "$pid" 2>/dev/null || true`,
|
|
56
|
+
// Wait up to ~5s for the old server to release the port, then force-kill.
|
|
57
|
+
` i=0`,
|
|
58
|
+
` while kill -0 "$pid" 2>/dev/null && [ "$i" -lt 50 ]; do sleep 0.1; i=$((i + 1)); done`,
|
|
59
|
+
` kill -9 "$pid" 2>/dev/null || true`,
|
|
60
|
+
` rm -f ${pidfile}`,
|
|
61
|
+
`fi`
|
|
62
|
+
].join("\n");
|
|
63
|
+
await runInSandbox(sandbox, script, { allowFailure: true, timeout: 15e3 });
|
|
64
|
+
}
|
|
65
|
+
async function launchServer(sandbox, remoteDir) {
|
|
66
|
+
const script = `${remoteDir}/${SERVER_SCRIPT}`;
|
|
67
|
+
await runInSandbox(sandbox, `nohup sh ${shellQuote(script)} >/dev/null 2>&1 & echo launched`);
|
|
68
|
+
}
|
|
69
|
+
async function tailServerLog(sandbox, remoteDir, lines = 50) {
|
|
70
|
+
const logfile = `${remoteDir}/${SERVER_LOGFILE}`;
|
|
71
|
+
const result = await runInSandbox(
|
|
72
|
+
sandbox,
|
|
73
|
+
`tail -n ${Math.floor(lines)} ${shellQuote(logfile)} 2>/dev/null || true`,
|
|
74
|
+
{
|
|
75
|
+
allowFailure: true
|
|
76
|
+
}
|
|
77
|
+
);
|
|
78
|
+
return result.stdout;
|
|
79
|
+
}
|
|
80
|
+
async function waitForHealthy(url, opts = {}) {
|
|
81
|
+
const path = opts.path ?? "/api";
|
|
82
|
+
const timeoutMs = opts.timeoutMs ?? 6e4;
|
|
83
|
+
const intervalMs = opts.intervalMs ?? 1e3;
|
|
84
|
+
const deadline = Date.now() + timeoutMs;
|
|
85
|
+
while (Date.now() < deadline) {
|
|
86
|
+
try {
|
|
87
|
+
const res = await fetch(new URL(path, url), { signal: AbortSignal.timeout(intervalMs * 5) });
|
|
88
|
+
const providerError = res.status === 410 || res.headers.has("x-vercel-error");
|
|
89
|
+
if (res.status < 500 && !providerError) {
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
}
|
|
94
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export { DEFAULT_PORT, INSTALL_MARKER, SERVER_LOGFILE, SERVER_PIDFILE, SERVER_SCRIPT, getInfoSafe, killPreviousServer, launchServer, resolveRemoteDir, runInSandbox, shellQuote, tailServerLog, waitForHealthy };
|
|
100
|
+
//# sourceMappingURL=chunk-Z636GNUQ.js.map
|
|
101
|
+
//# sourceMappingURL=chunk-Z636GNUQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/shared.ts"],"names":[],"mappings":";AAGO,IAAM,eAAA,GAAkB,YAAA;AAExB,IAAM,YAAA,GAAe;AAErB,IAAM,aAAA,GAAgB;AAEtB,IAAM,cAAA,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BAAgB,GAAA,CAAI,MAAA,KAAW,OAAO,GAAA,CAAI,OAAA,CAAQ,IAAI,gBAAgB,CAAA;AAC5E,MAAA,IAAI,GAAA,CAAI,MAAA,GAAS,GAAA,IAAO,CAAC,aAAA,EAAe;AACtC,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,IAAI,OAAA,CAAQ,CAAA,OAAA,KAAW,UAAA,CAAW,OAAA,EAAS,UAAU,CAAC,CAAA;AAAA,EAC9D;AACA,EAAA,OAAO,KAAA;AACT","file":"chunk-Z636GNUQ.js","sourcesContent":["import type { SandboxInfo, WorkspaceSandbox } from '@mastra/core/workspace';\n\n/** Directory name (under the sandbox user's home) that the app is deployed into by default. */\nexport const REMOTE_DIR_NAME = 'mastra-app';\n/** Default port the Mastra server listens on. */\nexport const DEFAULT_PORT = 4111;\n/** Launch script written into the remote dir. Re-running it restarts the server (e.g. after a wake). */\nexport const SERVER_SCRIPT = '.mastra-server.sh';\n/** Pidfile written by the launch script. */\nexport const SERVER_PIDFILE = '.mastra-server.pid';\n/** Server log file inside the remote dir. */\nexport const SERVER_LOGFILE = '.mastra-server.log';\n/** Marker recording the package.json hash of the last completed dependency install. */\nexport const INSTALL_MARKER = '.mastra-install-hash';\n\n/** getInfo may be sync or async, and may throw — normalize to `undefined` on failure. */\nexport async function getInfoSafe(sandbox: WorkspaceSandbox): Promise<SandboxInfo | undefined> {\n try {\n return await sandbox.getInfo?.();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve the directory the app is (or will be) deployed into. Defaults to\n * `$HOME/mastra-app` resolved inside the sandbox — home directories persist\n * across snapshot stop/resume on providers that support it, unlike `/tmp`.\n * The sandbox must be running.\n */\nexport async function resolveRemoteDir(sandbox: WorkspaceSandbox, remoteDir?: string): Promise<string> {\n if (remoteDir) return remoteDir;\n const result = await runInSandbox(sandbox, `printf %s \"\\${HOME:-$(pwd)}\"`, { allowFailure: true });\n const base = result.stdout.trim();\n if (!base) {\n throw new Error('Could not resolve the sandbox home directory. Pass `remoteDir` explicitly.');\n }\n return `${base}/${REMOTE_DIR_NAME}`;\n}\n\n/** Single-quote a value for POSIX shells. */\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Run a shell script string inside the sandbox and throw on failure. */\nexport async function runInSandbox(\n sandbox: WorkspaceSandbox,\n script: string,\n opts?: {\n allowFailure?: boolean;\n timeout?: number;\n /** Safe description used in error messages instead of the script itself. */\n label?: string;\n },\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n if (!sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support executeCommand, which is required for sandbox deploys.`,\n );\n }\n // Run via `sh -c` (argv style): providers pass `command` straight to their\n // exec API as an executable, so a raw script string with spaces would fail.\n const result = await sandbox.executeCommand(\n 'sh',\n ['-c', script],\n opts?.timeout ? { timeout: opts.timeout } : undefined,\n );\n if (!result.success && !opts?.allowFailure) {\n // Never echo the full script back: it can contain secrets (env values)\n // or entire base64 upload chunks. Use the label or a bounded excerpt.\n const what = opts?.label ?? truncate(script, 120);\n throw new Error(\n `Command failed inside sandbox (exit ${result.exitCode}): ${what}\\n${truncate(result.stderr || result.stdout, 4_000)}`,\n );\n }\n return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };\n}\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? `${value.slice(0, max)}… (truncated)` : value;\n}\n\n/**\n * Kill the previously launched server (if any) using its pidfile, waiting for\n * the process to exit (bounded, then SIGKILL) so the replacement never races\n * the old server for the port. Safe when nothing is running.\n */\nexport async function killPreviousServer(sandbox: WorkspaceSandbox, remoteDir: string): Promise<void> {\n const pidfile = shellQuote(`${remoteDir}/${SERVER_PIDFILE}`);\n const script = [\n `if [ -f ${pidfile} ]; then`,\n ` pid=\"$(cat ${pidfile})\"`,\n ` kill \"$pid\" 2>/dev/null || true`,\n // Wait up to ~5s for the old server to release the port, then force-kill.\n ` i=0`,\n ` while kill -0 \"$pid\" 2>/dev/null && [ \"$i\" -lt 50 ]; do sleep 0.1; i=$((i + 1)); done`,\n ` kill -9 \"$pid\" 2>/dev/null || true`,\n ` rm -f ${pidfile}`,\n `fi`,\n ].join('\\n');\n await runInSandbox(sandbox, script, { allowFailure: true, timeout: 15_000 });\n}\n\n/**\n * Launch (or relaunch) the server by running the recorded launch script,\n * detached via nohup. Deliberately NOT `processes.spawn()`: provider process\n * handles follow the command's log stream, which would keep the calling\n * process's event loop alive for as long as the server runs. The server's\n * lifecycle is managed through its pidfile instead.\n */\nexport async function launchServer(sandbox: WorkspaceSandbox, remoteDir: string): Promise<void> {\n const script = `${remoteDir}/${SERVER_SCRIPT}`;\n await runInSandbox(sandbox, `nohup sh ${shellQuote(script)} >/dev/null 2>&1 & echo launched`);\n}\n\n/** Tail the server log from inside the sandbox. */\nexport async function tailServerLog(sandbox: WorkspaceSandbox, remoteDir: string, lines = 50): Promise<string> {\n const logfile = `${remoteDir}/${SERVER_LOGFILE}`;\n const result = await runInSandbox(\n sandbox,\n `tail -n ${Math.floor(lines)} ${shellQuote(logfile)} 2>/dev/null || true`,\n {\n allowFailure: true,\n },\n );\n return result.stdout;\n}\n\n/**\n * Poll `${url}${path}` until the server responds. Any HTTP status below 500\n * counts as \"the server is up\" — gateway errors (502/503) mean nothing is\n * listening on the port, and 410 is what some providers (e.g. Vercel) return\n * from their edge when the sandbox itself is stopped.\n */\nexport async function waitForHealthy(\n url: string,\n opts: { path?: string; timeoutMs?: number; intervalMs?: number } = {},\n): Promise<boolean> {\n const path = opts.path ?? '/api';\n const timeoutMs = opts.timeoutMs ?? 60_000;\n const intervalMs = opts.intervalMs ?? 1_000;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n try {\n const res = await fetch(new URL(path, url), { signal: AbortSignal.timeout(intervalMs * 5) });\n // A provider-edge error header means the response came from the sandbox\n // infrastructure (stopped/unreachable VM), not from the Mastra server.\n const providerError = res.status === 410 || res.headers.has('x-vercel-error');\n if (res.status < 500 && !providerError) {\n return true;\n }\n } catch {\n // Not reachable yet.\n }\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n }\n return false;\n}\n"]}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkCSXC6CZL_cjs = require('../chunk-CSXC6CZL.cjs');
|
|
4
|
+
var workspace = require('@mastra/core/workspace');
|
|
5
|
+
|
|
6
|
+
function assertServerOnly() {
|
|
7
|
+
if (typeof globalThis.window !== "undefined") {
|
|
8
|
+
throw new Error(
|
|
9
|
+
"@mastra/deployer-sandbox/client is server-only: resolving a sandbox requires provider credentials that must never reach the browser. Proxy requests through your own backend instead (see createSandboxHandler / createSandboxProxy)."
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
async function getDeployment(options) {
|
|
14
|
+
assertServerOnly();
|
|
15
|
+
const {
|
|
16
|
+
sandbox,
|
|
17
|
+
port = chunkCSXC6CZL_cjs.DEFAULT_PORT,
|
|
18
|
+
wake = false,
|
|
19
|
+
healthCheckPath = "/api",
|
|
20
|
+
healthCheckTimeoutMs = 6e4
|
|
21
|
+
} = options;
|
|
22
|
+
const handle = (url2, status, expiresAt) => ({
|
|
23
|
+
url: url2,
|
|
24
|
+
status,
|
|
25
|
+
expiresAt,
|
|
26
|
+
stop: async () => {
|
|
27
|
+
await sandbox.stop?.();
|
|
28
|
+
},
|
|
29
|
+
destroy: async () => {
|
|
30
|
+
await sandbox.destroy?.();
|
|
31
|
+
},
|
|
32
|
+
// Resolved lazily — reading logs requires a running sandbox anyway.
|
|
33
|
+
logs: async (lines) => chunkCSXC6CZL_cjs.tailServerLog(sandbox, await chunkCSXC6CZL_cjs.resolveRemoteDir(sandbox, options.remoteDir), lines)
|
|
34
|
+
});
|
|
35
|
+
if (!wake) {
|
|
36
|
+
const url2 = workspace.supportsNetworking(sandbox) ? await sandbox.networking.getPortUrl(port) : null;
|
|
37
|
+
if (!url2) {
|
|
38
|
+
return handle(null, "stopped");
|
|
39
|
+
}
|
|
40
|
+
const healthy2 = await chunkCSXC6CZL_cjs.waitForHealthy(url2, { path: healthCheckPath, timeoutMs: 3e3, intervalMs: 1e3 });
|
|
41
|
+
return handle(url2, healthy2 ? "running" : "stopped");
|
|
42
|
+
}
|
|
43
|
+
await sandbox.start?.();
|
|
44
|
+
if (!workspace.supportsNetworking(sandbox)) {
|
|
45
|
+
throw new Error(`Sandbox provider "${sandbox.provider}" does not support networking (public port URLs).`);
|
|
46
|
+
}
|
|
47
|
+
const url = await sandbox.networking.getPortUrl(port);
|
|
48
|
+
if (!url) {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`Sandbox provider "${sandbox.provider}" did not expose a public URL for port ${port}. Make sure the port is declared when constructing the sandbox (e.g. \`ports: [${port}]\`).`
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
let healthy = await chunkCSXC6CZL_cjs.waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3e3, intervalMs: 1e3 });
|
|
54
|
+
if (!healthy) {
|
|
55
|
+
const remoteDir = await chunkCSXC6CZL_cjs.resolveRemoteDir(sandbox, options.remoteDir);
|
|
56
|
+
await chunkCSXC6CZL_cjs.killPreviousServer(sandbox, remoteDir);
|
|
57
|
+
await chunkCSXC6CZL_cjs.launchServer(sandbox, remoteDir);
|
|
58
|
+
healthy = await chunkCSXC6CZL_cjs.waitForHealthy(url, { path: healthCheckPath, timeoutMs: healthCheckTimeoutMs, intervalMs: 1e3 });
|
|
59
|
+
}
|
|
60
|
+
if (!healthy) {
|
|
61
|
+
const log = await chunkCSXC6CZL_cjs.resolveRemoteDir(sandbox, options.remoteDir).then((dir) => chunkCSXC6CZL_cjs.tailServerLog(sandbox, dir)).catch(() => "");
|
|
62
|
+
throw new Error(
|
|
63
|
+
`Woke sandbox but the Mastra server did not become healthy at ${url}${healthCheckPath}.` + (log ? `
|
|
64
|
+
|
|
65
|
+
Server log:
|
|
66
|
+
${log}` : "")
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const info = await chunkCSXC6CZL_cjs.getInfoSafe(sandbox);
|
|
70
|
+
return handle(url, "running", info?.timeoutAt);
|
|
71
|
+
}
|
|
72
|
+
function createSandboxHandler(options) {
|
|
73
|
+
assertServerOnly();
|
|
74
|
+
let cachedUrl = null;
|
|
75
|
+
const forward = async (request, baseUrl) => {
|
|
76
|
+
const incoming = new URL(request.url);
|
|
77
|
+
const target = new URL(incoming.pathname + incoming.search, baseUrl);
|
|
78
|
+
const headers = new Headers(request.headers);
|
|
79
|
+
headers.delete("host");
|
|
80
|
+
if (options.secret) {
|
|
81
|
+
headers.set("x-mastra-sandbox-secret", options.secret);
|
|
82
|
+
}
|
|
83
|
+
const response = await fetch(target, {
|
|
84
|
+
method: request.method,
|
|
85
|
+
headers,
|
|
86
|
+
body: request.body,
|
|
87
|
+
// duplex is required by Node's fetch for streamed request bodies
|
|
88
|
+
duplex: "half",
|
|
89
|
+
redirect: "manual"
|
|
90
|
+
});
|
|
91
|
+
const location = response.headers.get("location");
|
|
92
|
+
if (location) {
|
|
93
|
+
const resolved = new URL(location, target);
|
|
94
|
+
if (resolved.origin === new URL(baseUrl).origin) {
|
|
95
|
+
const rewritten = new URL(resolved.pathname + resolved.search + resolved.hash, incoming.origin);
|
|
96
|
+
const responseHeaders = new Headers(response.headers);
|
|
97
|
+
responseHeaders.set("location", rewritten.toString());
|
|
98
|
+
return new Response(response.body, {
|
|
99
|
+
status: response.status,
|
|
100
|
+
statusText: response.statusText,
|
|
101
|
+
headers: responseHeaders
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return response;
|
|
106
|
+
};
|
|
107
|
+
return async (request) => {
|
|
108
|
+
cachedUrl ??= options.resolve();
|
|
109
|
+
try {
|
|
110
|
+
return await forward(request, await cachedUrl);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
cachedUrl = null;
|
|
113
|
+
if (!["GET", "HEAD", "OPTIONS"].includes(request.method)) {
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
cachedUrl = options.resolve();
|
|
117
|
+
try {
|
|
118
|
+
return await forward(request, await cachedUrl);
|
|
119
|
+
} catch (retryError) {
|
|
120
|
+
cachedUrl = null;
|
|
121
|
+
throw retryError;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function createSandboxProxy(options) {
|
|
127
|
+
assertServerOnly();
|
|
128
|
+
return async (request) => {
|
|
129
|
+
const connection = options.edgeConfig ?? process.env.EDGE_CONFIG;
|
|
130
|
+
if (!connection) {
|
|
131
|
+
throw new Error("createSandboxProxy requires an Edge Config connection string (EDGE_CONFIG).");
|
|
132
|
+
}
|
|
133
|
+
const conn = new URL(connection);
|
|
134
|
+
const token = conn.searchParams.get("token");
|
|
135
|
+
const itemUrl = new URL(`${conn.origin}${conn.pathname}/item/${encodeURIComponent(options.key)}`);
|
|
136
|
+
const res = await fetch(itemUrl, { headers: { Authorization: `Bearer ${token}` } });
|
|
137
|
+
if (!res.ok) {
|
|
138
|
+
return void 0;
|
|
139
|
+
}
|
|
140
|
+
const sandboxUrl = await res.json();
|
|
141
|
+
if (typeof sandboxUrl !== "string" || !sandboxUrl) {
|
|
142
|
+
return void 0;
|
|
143
|
+
}
|
|
144
|
+
const incoming = new URL(request.url);
|
|
145
|
+
const target = new URL(incoming.pathname + incoming.search, sandboxUrl);
|
|
146
|
+
const headers = new Headers({ "x-middleware-rewrite": target.toString() });
|
|
147
|
+
if (options.secret) {
|
|
148
|
+
headers.set("x-middleware-request-x-mastra-sandbox-secret", options.secret);
|
|
149
|
+
headers.set("x-middleware-override-headers", "x-mastra-sandbox-secret");
|
|
150
|
+
}
|
|
151
|
+
return new Response(null, { headers });
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
exports.createSandboxHandler = createSandboxHandler;
|
|
156
|
+
exports.createSandboxProxy = createSandboxProxy;
|
|
157
|
+
exports.getDeployment = getDeployment;
|
|
158
|
+
//# sourceMappingURL=index.cjs.map
|
|
159
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/client/index.ts"],"names":["DEFAULT_PORT","url","tailServerLog","resolveRemoteDir","supportsNetworking","healthy","waitForHealthy","killPreviousServer","launchServer","getInfoSafe"],"mappings":";;;;;AAoBA,SAAS,gBAAA,GAAyB;AAChC,EAAA,IAAI,OAAQ,UAAA,CAAoC,MAAA,KAAW,WAAA,EAAa;AACtE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACF;AAmDA,eAAsB,cAAc,OAAA,EAA4D;AAC9F,EAAA,gBAAA,EAAiB;AAEjB,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,IAAA,GAAOA,8BAAA;AAAA,IACP,IAAA,GAAO,KAAA;AAAA,IACP,eAAA,GAAkB,MAAA;AAAA,IAClB,oBAAA,GAAuB;AAAA,GACzB,GAAI,OAAA;AAEJ,EAAA,MAAM,MAAA,GAAS,CAACC,IAAAA,EAAoB,MAAA,EAA0B,SAAA,MAA0C;AAAA,IACtG,GAAA,EAAAA,IAAAA;AAAA,IACA,MAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAM,YAAY;AAChB,MAAA,MAAM,QAAQ,IAAA,IAAO;AAAA,IACvB,CAAA;AAAA,IACA,SAAS,YAAY;AACnB,MAAA,MAAM,QAAQ,OAAA,IAAU;AAAA,IAC1B,CAAA;AAAA;AAAA,IAEA,IAAA,EAAM,OAAO,KAAA,KAAmBC,+BAAA,CAAc,OAAA,EAAS,MAAMC,kCAAA,CAAiB,OAAA,EAAS,OAAA,CAAQ,SAAS,CAAA,EAAG,KAAK;AAAA,GAClH,CAAA;AAEA,EAAA,IAAI,CAAC,IAAA,EAAM;AAET,IAAA,MAAMF,IAAAA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AA,OAAA,EAAU,KAAK,CAAA,CAAA,EAAG,EAAG,CAAA;AAClF,IAAA,IAAI,CAAC,IAAI,EAAA,EAAI;AACX,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,MAAM,UAAA,GAAsB,MAAM,GAAA,CAAI,IAAA,EAAK;AAC3C,IAAA,IAAI,OAAO,UAAA,KAAe,QAAA,IAAY,CAAC,UAAA,EAAY;AACjD,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,MAAM,QAAA,GAAW,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA;AACpC,IAAA,MAAM,SAAS,IAAI,GAAA,CAAI,SAAS,QAAA,GAAW,QAAA,CAAS,QAAQ,UAAU,CAAA;AAKtE,IAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAQ,EAAE,wBAAwB,MAAA,CAAO,QAAA,IAAY,CAAA;AACzE,IAAA,IAAI,QAAQ,MAAA,EAAQ;AAClB,MAAA,OAAA,CAAQ,GAAA,CAAI,8CAAA,EAAgD,OAAA,CAAQ,MAAM,CAAA;AAC1E,MAAA,OAAA,CAAQ,GAAA,CAAI,iCAAiC,yBAAyB,CAAA;AAAA,IACxE;AACA,IAAA,OAAO,IAAI,QAAA,CAAS,IAAA,EAAM,EAAE,SAAS,CAAA;AAAA,EACvC,CAAA;AACF","file":"index.cjs","sourcesContent":["/**\n * Runtime resolver + routing helpers for sandbox deployments.\n *\n * SERVER-ONLY. This module resolves sandbox URLs using provider credentials\n * (e.g. VERCEL_TOKEN) — importing it in the browser would ship those\n * credentials to the client. Use the proxy/handler patterns instead so the\n * browser only ever talks to your own domain.\n */\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n tailServerLog,\n waitForHealthy,\n} from '../shared';\n\nfunction assertServerOnly(): void {\n if (typeof (globalThis as { window?: unknown }).window !== 'undefined') {\n throw new Error(\n '@mastra/deployer-sandbox/client is server-only: resolving a sandbox requires provider credentials ' +\n 'that must never reach the browser. Proxy requests through your own backend instead ' +\n '(see createSandboxHandler / createSandboxProxy).',\n );\n }\n}\n\nexport type DeploymentStatus = 'running' | 'stopped' | 'unknown';\n\nexport interface GetDeploymentOptions {\n /**\n * The sandbox to resolve. Provider construction is identity — e.g.\n * `new VercelSandbox({ sandboxName: 'my-preview', ports: [4111] })` resolves\n * the same sandbox from any process.\n */\n sandbox: WorkspaceSandbox;\n /** Port the Mastra server listens on. Defaults to 4111. */\n port?: number;\n /**\n * Wake the sandbox when it is not running. Waking starts (resumes) the\n * sandbox and, only if the server is not answering, relaunches it from the\n * recorded launch script — some providers (e.g. E2B) resume processes on\n * wake, others (e.g. Vercel) restore just the filesystem. Defaults to false.\n */\n wake?: boolean;\n /** Directory the app was deployed into. Defaults to `$HOME/mastra-app` resolved inside the sandbox. */\n remoteDir?: string;\n /** Path polled for health. Defaults to `/api`. */\n healthCheckPath?: string;\n /** Max time to wait for health after a wake, in ms. Defaults to 60000. */\n healthCheckTimeoutMs?: number;\n}\n\nexport interface ResolvedDeployment {\n /** Public URL of the Mastra server, or null when it could not be resolved without waking. */\n url: string | null;\n status: DeploymentStatus;\n /** When the sandbox will auto-shutdown (when known). */\n expiresAt?: Date;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n logs(lines?: number): Promise<string>;\n}\n\n/**\n * Resolve (and optionally wake) a sandbox deployment.\n *\n * With `wake: false` (default) the sandbox is not started: the URL is resolved\n * only if the sandbox is already running in this process, otherwise\n * `{ url: null, status: 'stopped' | 'unknown' }` is returned and the caller\n * decides whether to wake.\n *\n * With `wake: true` the sandbox is started (providers resume by identity,\n * e.g. name), the server is relaunched if it is not answering, and the\n * deployment is returned once healthy.\n */\nexport async function getDeployment(options: GetDeploymentOptions): Promise<ResolvedDeployment> {\n assertServerOnly();\n\n const {\n sandbox,\n port = DEFAULT_PORT,\n wake = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n } = options;\n\n const handle = (url: string | null, status: DeploymentStatus, expiresAt?: Date): ResolvedDeployment => ({\n url,\n status,\n expiresAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n // Resolved lazily — reading logs requires a running sandbox anyway.\n logs: async (lines?: number) => tailServerLog(sandbox, await resolveRemoteDir(sandbox, options.remoteDir), lines),\n });\n\n if (!wake) {\n // Resolve without starting the sandbox (starting can resume billing).\n const url = supportsNetworking(sandbox) ? await sandbox.networking.getPortUrl(port) : null;\n if (!url) {\n return handle(null, 'stopped');\n }\n const healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3_000, intervalMs: 1_000 });\n return handle(url, healthy ? 'running' : 'stopped');\n }\n\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(`Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs).`);\n }\n const url = await sandbox.networking.getPortUrl(port);\n if (!url) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" did not expose a public URL for port ${port}. ` +\n `Make sure the port is declared when constructing the sandbox (e.g. \\`ports: [${port}]\\`).`,\n );\n }\n\n // Some providers (e.g. Vercel) restore the filesystem but not processes on\n // resume, while others (e.g. E2B) resume processes too — relaunch the server\n // from the recorded launch script only when it is not answering.\n let healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3_000, intervalMs: 1_000 });\n if (!healthy) {\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n await killPreviousServer(sandbox, remoteDir);\n await launchServer(sandbox, remoteDir);\n healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: healthCheckTimeoutMs, intervalMs: 1_000 });\n }\n if (!healthy) {\n const log = await resolveRemoteDir(sandbox, options.remoteDir)\n .then(dir => tailServerLog(sandbox, dir))\n .catch(() => '');\n throw new Error(\n `Woke sandbox but the Mastra server did not become healthy at ${url}${healthCheckPath}.` +\n (log ? `\\n\\nServer log:\\n${log}` : ''),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n return handle(url, 'running', info?.timeoutAt);\n}\n\n// =============================================================================\n// Tier 3 helpers\n// =============================================================================\n\nexport interface CreateSandboxHandlerOptions {\n /**\n * Resolve the current sandbox URL. Called once, cached, and re-invoked when\n * a forwarded request fails at the network level (e.g. the sandbox rotated\n * its URL or went to sleep). Typically wraps `getDeployment`:\n *\n * ```typescript\n * createSandboxHandler({\n * resolve: async () => {\n * const dep = await getDeployment({ sandbox, wake: true });\n * return dep.url!;\n * },\n * });\n * ```\n */\n resolve: () => Promise<string>;\n /** Shared secret attached as the `x-mastra-sandbox-secret` header on forwarded requests. */\n secret?: string;\n}\n\n/**\n * Framework-free route-handler proxy (fetch `Request` → `Response`). Mount it\n * as a catch-all API route; the browser only ever sees your own domain, and\n * the sandbox URL (which rotates across resumes) stays server-side.\n */\nexport function createSandboxHandler(options: CreateSandboxHandlerOptions): (request: Request) => Promise<Response> {\n assertServerOnly();\n\n let cachedUrl: Promise<string> | null = null;\n\n const forward = async (request: Request, baseUrl: string): Promise<Response> => {\n const incoming = new URL(request.url);\n const target = new URL(incoming.pathname + incoming.search, baseUrl);\n\n const headers = new Headers(request.headers);\n headers.delete('host');\n if (options.secret) {\n headers.set('x-mastra-sandbox-secret', options.secret);\n }\n\n const response = await fetch(target, {\n method: request.method,\n headers,\n body: request.body,\n // duplex is required by Node's fetch for streamed request bodies\n duplex: 'half',\n redirect: 'manual',\n } as RequestInit);\n\n // Redirects are passed through manually — rewrite sandbox-host Locations\n // onto the incoming origin so the rotating sandbox URL never reaches the\n // browser (and subsequent requests keep flowing through this handler).\n const location = response.headers.get('location');\n if (location) {\n const resolved = new URL(location, target);\n if (resolved.origin === new URL(baseUrl).origin) {\n const rewritten = new URL(resolved.pathname + resolved.search + resolved.hash, incoming.origin);\n const responseHeaders = new Headers(response.headers);\n responseHeaders.set('location', rewritten.toString());\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n }\n }\n\n return response;\n };\n\n return async (request: Request): Promise<Response> => {\n cachedUrl ??= options.resolve();\n\n try {\n return await forward(request, await cachedUrl);\n } catch (error) {\n // Connection-level failure: the sandbox may have rotated its URL or gone\n // to sleep. Drop the cached URL so the next request re-resolves, and\n // retry once — but only for idempotent, bodyless methods. A failed\n // connection doesn't prove a write never landed, and a streamed body is\n // already consumed.\n cachedUrl = null;\n if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {\n throw error;\n }\n cachedUrl = options.resolve();\n try {\n return await forward(request, await cachedUrl);\n } catch (retryError) {\n cachedUrl = null;\n throw retryError;\n }\n }\n };\n}\n\nexport interface CreateSandboxProxyOptions {\n /** Edge Config item key that holds the current sandbox URL. */\n key: string;\n /**\n * Edge Config connection string (`https://edge-config.vercel.com/ecfg_...?token=...`).\n * Defaults to `process.env.EDGE_CONFIG`.\n */\n edgeConfig?: string;\n /** Shared secret attached as the `x-mastra-sandbox-secret` header on the rewrite. */\n secret?: string;\n}\n\n/**\n * Next.js middleware helper for Tier 3 routing: reads the current sandbox URL\n * from Edge Config (kept fresh by the deployer's `alias` option) and rewrites\n * the request to it. Returns `undefined` when no URL is configured so the\n * request falls through.\n *\n * ```typescript\n * // middleware.ts\n * export const middleware = createSandboxProxy({ key: 'my-preview' });\n * export const config = { matcher: '/api/:path*' };\n * ```\n */\nexport function createSandboxProxy(\n options: CreateSandboxProxyOptions,\n): (request: Request) => Promise<Response | undefined> {\n // Reads (and would transmit) the Edge Config bearer token — same\n // server-only contract as the rest of this module.\n assertServerOnly();\n\n return async (request: Request): Promise<Response | undefined> => {\n const connection = options.edgeConfig ?? process.env.EDGE_CONFIG;\n if (!connection) {\n throw new Error('createSandboxProxy requires an Edge Config connection string (EDGE_CONFIG).');\n }\n\n const conn = new URL(connection);\n const token = conn.searchParams.get('token');\n const itemUrl = new URL(`${conn.origin}${conn.pathname}/item/${encodeURIComponent(options.key)}`);\n\n const res = await fetch(itemUrl, { headers: { Authorization: `Bearer ${token}` } });\n if (!res.ok) {\n return undefined;\n }\n const sandboxUrl: unknown = await res.json();\n if (typeof sandboxUrl !== 'string' || !sandboxUrl) {\n return undefined;\n }\n\n const incoming = new URL(request.url);\n const target = new URL(incoming.pathname + incoming.search, sandboxUrl);\n\n // A Response with the x-middleware-rewrite header is how Next.js\n // middleware expresses a rewrite (NextResponse.rewrite does the same) —\n // this keeps the helper free of a next dependency.\n const headers = new Headers({ 'x-middleware-rewrite': target.toString() });\n if (options.secret) {\n headers.set('x-middleware-request-x-mastra-sandbox-secret', options.secret);\n headers.set('x-middleware-override-headers', 'x-mastra-sandbox-secret');\n }\n return new Response(null, { headers });\n };\n}\n"]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { WorkspaceSandbox } from '@mastra/core/workspace';
|
|
2
|
+
export type DeploymentStatus = 'running' | 'stopped' | 'unknown';
|
|
3
|
+
export interface GetDeploymentOptions {
|
|
4
|
+
/**
|
|
5
|
+
* The sandbox to resolve. Provider construction is identity — e.g.
|
|
6
|
+
* `new VercelSandbox({ sandboxName: 'my-preview', ports: [4111] })` resolves
|
|
7
|
+
* the same sandbox from any process.
|
|
8
|
+
*/
|
|
9
|
+
sandbox: WorkspaceSandbox;
|
|
10
|
+
/** Port the Mastra server listens on. Defaults to 4111. */
|
|
11
|
+
port?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Wake the sandbox when it is not running. Waking starts (resumes) the
|
|
14
|
+
* sandbox and, only if the server is not answering, relaunches it from the
|
|
15
|
+
* recorded launch script — some providers (e.g. E2B) resume processes on
|
|
16
|
+
* wake, others (e.g. Vercel) restore just the filesystem. Defaults to false.
|
|
17
|
+
*/
|
|
18
|
+
wake?: boolean;
|
|
19
|
+
/** Directory the app was deployed into. Defaults to `$HOME/mastra-app` resolved inside the sandbox. */
|
|
20
|
+
remoteDir?: string;
|
|
21
|
+
/** Path polled for health. Defaults to `/api`. */
|
|
22
|
+
healthCheckPath?: string;
|
|
23
|
+
/** Max time to wait for health after a wake, in ms. Defaults to 60000. */
|
|
24
|
+
healthCheckTimeoutMs?: number;
|
|
25
|
+
}
|
|
26
|
+
export interface ResolvedDeployment {
|
|
27
|
+
/** Public URL of the Mastra server, or null when it could not be resolved without waking. */
|
|
28
|
+
url: string | null;
|
|
29
|
+
status: DeploymentStatus;
|
|
30
|
+
/** When the sandbox will auto-shutdown (when known). */
|
|
31
|
+
expiresAt?: Date;
|
|
32
|
+
stop(): Promise<void>;
|
|
33
|
+
destroy(): Promise<void>;
|
|
34
|
+
logs(lines?: number): Promise<string>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Resolve (and optionally wake) a sandbox deployment.
|
|
38
|
+
*
|
|
39
|
+
* With `wake: false` (default) the sandbox is not started: the URL is resolved
|
|
40
|
+
* only if the sandbox is already running in this process, otherwise
|
|
41
|
+
* `{ url: null, status: 'stopped' | 'unknown' }` is returned and the caller
|
|
42
|
+
* decides whether to wake.
|
|
43
|
+
*
|
|
44
|
+
* With `wake: true` the sandbox is started (providers resume by identity,
|
|
45
|
+
* e.g. name), the server is relaunched if it is not answering, and the
|
|
46
|
+
* deployment is returned once healthy.
|
|
47
|
+
*/
|
|
48
|
+
export declare function getDeployment(options: GetDeploymentOptions): Promise<ResolvedDeployment>;
|
|
49
|
+
export interface CreateSandboxHandlerOptions {
|
|
50
|
+
/**
|
|
51
|
+
* Resolve the current sandbox URL. Called once, cached, and re-invoked when
|
|
52
|
+
* a forwarded request fails at the network level (e.g. the sandbox rotated
|
|
53
|
+
* its URL or went to sleep). Typically wraps `getDeployment`:
|
|
54
|
+
*
|
|
55
|
+
* ```typescript
|
|
56
|
+
* createSandboxHandler({
|
|
57
|
+
* resolve: async () => {
|
|
58
|
+
* const dep = await getDeployment({ sandbox, wake: true });
|
|
59
|
+
* return dep.url!;
|
|
60
|
+
* },
|
|
61
|
+
* });
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
resolve: () => Promise<string>;
|
|
65
|
+
/** Shared secret attached as the `x-mastra-sandbox-secret` header on forwarded requests. */
|
|
66
|
+
secret?: string;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Framework-free route-handler proxy (fetch `Request` → `Response`). Mount it
|
|
70
|
+
* as a catch-all API route; the browser only ever sees your own domain, and
|
|
71
|
+
* the sandbox URL (which rotates across resumes) stays server-side.
|
|
72
|
+
*/
|
|
73
|
+
export declare function createSandboxHandler(options: CreateSandboxHandlerOptions): (request: Request) => Promise<Response>;
|
|
74
|
+
export interface CreateSandboxProxyOptions {
|
|
75
|
+
/** Edge Config item key that holds the current sandbox URL. */
|
|
76
|
+
key: string;
|
|
77
|
+
/**
|
|
78
|
+
* Edge Config connection string (`https://edge-config.vercel.com/ecfg_...?token=...`).
|
|
79
|
+
* Defaults to `process.env.EDGE_CONFIG`.
|
|
80
|
+
*/
|
|
81
|
+
edgeConfig?: string;
|
|
82
|
+
/** Shared secret attached as the `x-mastra-sandbox-secret` header on the rewrite. */
|
|
83
|
+
secret?: string;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Next.js middleware helper for Tier 3 routing: reads the current sandbox URL
|
|
87
|
+
* from Edge Config (kept fresh by the deployer's `alias` option) and rewrites
|
|
88
|
+
* the request to it. Returns `undefined` when no URL is configured so the
|
|
89
|
+
* request falls through.
|
|
90
|
+
*
|
|
91
|
+
* ```typescript
|
|
92
|
+
* // middleware.ts
|
|
93
|
+
* export const middleware = createSandboxProxy({ key: 'my-preview' });
|
|
94
|
+
* export const config = { matcher: '/api/:path*' };
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export declare function createSandboxProxy(options: CreateSandboxProxyOptions): (request: Request) => Promise<Response | undefined>;
|
|
98
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AASA,OAAO,K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