| 111 | } |
| 112 | |
| 113 | async function handleExec(request: Request, env: Env, name: string): Promise<Response> { |
| 114 | if (request.method !== "POST") { |
| 115 | return new Response("method not allowed", { status: 405, headers: { allow: "POST" } }); |
| 116 | } |
| 117 | let body: ExecRequest; |
| 118 | try { |
| 119 | body = (await request.json()) as ExecRequest; |
| 120 | } catch { |
| 121 | return errorJSON(new Error("invalid JSON body"), 400); |
| 122 | } |
| 123 | |
| 124 | if (typeof body.source !== "string" || body.source.length === 0) { |
| 125 | return errorJSON(new Error("must provide source"), 400); |
| 126 | } |
| 127 | |
| 128 | const stub = env.ContainerExample.get(env.ContainerExample.idFromName(name)); |
| 129 | const ws = await getWorkspace(stub as unknown as Parameters<typeof getWorkspace>[0]); |
| 130 | try { |
| 131 | const handle = await ws.runtime.exec(body.source, { |
| 132 | backend: "worker-javascript", |
| 133 | cwd: body.cwd, |
| 134 | input: body.input, |
| 135 | env: body.env, |
| 136 | stdin: body.stdin, |
| 137 | encoding: "utf8", |
| 138 | }); |
| 139 | const result = await handle.result(); |
| 140 | return new Response(JSON.stringify(result), { |
| 141 | status: 200, |
| 142 | headers: { "content-type": "application/json" }, |
| 143 | }); |
| 144 | } catch (error) { |
| 145 | return errorJSON(error, 500); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | function errorJSON(error: unknown, status: number): Response { |
| 150 | const message = error instanceof Error ? error.message : String(error); |