The best way to control Claude Code, Codex and more from any computer or phone

main
ts 254 lines 9.18 KB
Raw
1 import { makeFunctionHttpHandler } from "@alchemy.run/aws/Lambda/HttpServer";
2 import { describe, expect, it } from "@alchemy.run/test";
3 import type { LambdaFunctionURLEvent, LambdaFunctionURLResult } from "aws-lambda";
4 import * as Effect from "effect/Effect";
5 import * as HttpServerRequest from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import type { Scope } from "effect/Scope";
8 import { TestHttpEffect } from "./HttpServer.fixture";
9
10 describe(
11 "AWS.Lambda.HttpServer",
12 { tags: ["unit", "provider:aws", "provider:aws:lambda", "local"] },
13 () => {
14 it("maps a Function URL event into HttpServerRequest", async () => {
15 const result = asStructuredResult(
16 await invoke(
17 makeEvent({
18 rawPath: "/inspect",
19 rawQueryString: "jobId=job-123&trace=1",
20 headers: { "x-forwarded-proto": "https", "x-request-id": "req-123" },
21 cookies: ["session=abc", "theme=dark"],
22 requestContext: {
23 http: { method: "GET", path: "/inspect", sourceIp: "203.0.113.42" },
24 } as LambdaFunctionURLEvent["requestContext"],
25 }),
26 ),
27 );
28
29 expect(result.statusCode).toBe(200);
30 expect(result.headers?.["content-type"]).toContain("application/json");
31 expect(JSON.parse(result.body ?? "")).toEqual({
32 method: "GET",
33 url: "https://example.lambda-url.us-east-1.on.aws/inspect?jobId=job-123&trace=1",
34 originalUrl: "https://example.lambda-url.us-east-1.on.aws/inspect?jobId=job-123&trace=1",
35 host: "example.lambda-url.us-east-1.on.aws",
36 protocol: "https",
37 requestId: "req-123",
38 remoteAddress: "203.0.113.42",
39 query: { jobId: "job-123", trace: "1" },
40 cookies: { session: "abc", theme: "dark" },
41 });
42 });
43
44 it("maps HttpServerResponse into a Function URL result", async () => {
45 const result = asStructuredResult(
46 await invoke(
47 makeEvent({
48 rawPath: "/jobs",
49 headers: { "content-type": "application/json" },
50 body: JSON.stringify({ content: "ship it" }),
51 requestContext: {
52 http: { method: "POST", path: "/jobs" },
53 } as LambdaFunctionURLEvent["requestContext"],
54 }),
55 ),
56 );
57
58 expect(result.statusCode).toBe(201);
59 expect(result.headers).toMatchObject({
60 "content-type": "application/json",
61 "x-handler": "lambda-http",
62 });
63 expect(result.cookies).toHaveLength(1);
64 expect(result.cookies?.[0]).toContain("job-session=created");
65 expect(JSON.parse(result.body ?? "")).toEqual({
66 method: "POST",
67 url: "https://example.lambda-url.us-east-1.on.aws/jobs",
68 payload: { content: "ship it" },
69 });
70 expect(result.body).not.toContain("HttpServerResponse");
71 });
72
73 it("base64 encodes binary responses", async () => {
74 const result = asStructuredResult(
75 await invoke(
76 makeEvent({
77 rawPath: "/binary",
78 requestContext: {
79 http: { method: "GET", path: "/binary" },
80 } as LambdaFunctionURLEvent["requestContext"],
81 }),
82 ),
83 );
84
85 expect(result.statusCode).toBe(200);
86 expect(result.headers?.["content-type"]).toBe("application/octet-stream");
87 expect(result.isBase64Encoded).toBe(true);
88 expect(Buffer.from(result.body ?? "", "base64").toString("utf8")).toBe("alchemy");
89 });
90
91 it("detects an API Gateway v2 HTTP API (payload 2.0) event and maps it like a Function URL event", async () => {
92 // Same wire shape as a Function URL event (APIGatewayProxyEventV2), but
93 // with an execute-api domain, a real routeKey, and a named apiId.
94 const result = asStructuredResult(
95 await invoke(
96 makeEvent({
97 version: "2.0",
98 routeKey: "GET /inspect",
99 rawPath: "/inspect",
100 rawQueryString: "jobId=job-123&trace=1",
101 headers: {
102 host: "abc123.execute-api.us-west-2.amazonaws.com",
103 "x-forwarded-proto": "https",
104 "x-request-id": "req-apigw-v2",
105 },
106 cookies: ["session=abc"],
107 requestContext: {
108 apiId: "abc123",
109 domainName: "abc123.execute-api.us-west-2.amazonaws.com",
110 domainPrefix: "abc123",
111 routeKey: "GET /inspect",
112 stage: "$default",
113 http: { method: "GET", path: "/inspect", sourceIp: "203.0.113.99" },
114 } as LambdaFunctionURLEvent["requestContext"],
115 }),
116 ),
117 );
118
119 expect(result.statusCode).toBe(200);
120 expect(JSON.parse(result.body ?? "")).toEqual({
121 method: "GET",
122 url: "https://abc123.execute-api.us-west-2.amazonaws.com/inspect?jobId=job-123&trace=1",
123 originalUrl:
124 "https://abc123.execute-api.us-west-2.amazonaws.com/inspect?jobId=job-123&trace=1",
125 host: "abc123.execute-api.us-west-2.amazonaws.com",
126 protocol: "https",
127 requestId: "req-apigw-v2",
128 remoteAddress: "203.0.113.99",
129 query: { jobId: "job-123", trace: "1" },
130 cookies: { session: "abc" },
131 });
132 });
133
134 it("keeps the stage prefix in rawPath for named-stage API Gateway v2 events", async () => {
135 // On the default execute-api endpoint with a named (non-$default) stage,
136 // API Gateway includes the stage in rawPath (e.g. /prod/inspect). We use
137 // rawPath as-is — consistent with the v1 branch using event.path as-is —
138 // so handlers see the stage-prefixed path.
139 const result = asStructuredResult(
140 await invoke(
141 makeEvent({
142 version: "2.0",
143 routeKey: "GET /inspect",
144 rawPath: "/prod/inspect",
145 headers: { host: "abc123.execute-api.us-west-2.amazonaws.com" },
146 requestContext: {
147 routeKey: "GET /inspect",
148 stage: "prod",
149 http: { method: "GET", path: "/prod/inspect" },
150 } as LambdaFunctionURLEvent["requestContext"],
151 }),
152 ),
153 );
154
155 // Fixture only serves /inspect; the stage-prefixed path 404s, proving the
156 // prefix is preserved rather than stripped.
157 expect(result.statusCode).toBe(404);
158 });
159
160 it("uses shared Http error handling for defects", async () => {
161 const result = asStructuredResult(
162 await invoke(
163 makeEvent({
164 rawPath: "/boom",
165 requestContext: {
166 http: { method: "GET", path: "/boom" },
167 } as LambdaFunctionURLEvent["requestContext"],
168 }),
169 Effect.fail({ message: "Boom" } as any).pipe(Effect.orDie),
170 ),
171 );
172
173 // Defects render effect's native `causeResponse` fallback — an empty
174 // `500` with no body or content-type (the same wire shape effect's own
175 // servers produce) — instead of alchemy's former hand-rolled
176 // "Internal Server Error" text response. The cause is reported/logged
177 // server-side, never echoed to the client.
178 expect(result.statusCode).toBe(500);
179 expect(result.headers?.["content-type"]).toBeUndefined();
180 expect(result.body).toBeUndefined();
181 });
182 },
183 );
184
185 const invoke = async (
186 event: LambdaFunctionURLEvent,
187 handler: Effect.Effect<
188 HttpServerResponse.HttpServerResponse,
189 any,
190 HttpServerRequest.HttpServerRequest | Scope
191 > = TestHttpEffect,
192 ): Promise<LambdaFunctionURLResult> => {
193 const out = makeFunctionHttpHandler(handler)(event);
194 if (!Effect.isEffect(out)) {
195 throw new Error("Expected Effect from Function URL handler");
196 }
197 // Buffered mode (no `responseStream`) always yields a Function URL result.
198 return Effect.runPromise(out) as Promise<LambdaFunctionURLResult>;
199 };
200
201 const makeEvent = (overrides: Partial<LambdaFunctionURLEvent> = {}): LambdaFunctionURLEvent => {
202 const event: LambdaFunctionURLEvent = {
203 version: "2.0",
204 routeKey: "$default",
205 rawPath: "/",
206 rawQueryString: "",
207 cookies: undefined,
208 headers: { host: "example.lambda-url.us-east-1.on.aws", "x-forwarded-proto": "https" },
209 queryStringParameters: undefined,
210 requestContext: {
211 accountId: "123456789012",
212 apiId: "api-id",
213 domainName: "example.lambda-url.us-east-1.on.aws",
214 domainPrefix: "example",
215 http: {
216 method: "GET",
217 path: "/",
218 protocol: "HTTP/1.1",
219 sourceIp: "203.0.113.10",
220 userAgent: "vitest",
221 },
222 requestId: "request-id",
223 routeKey: "$default",
224 stage: "$default",
225 time: "09/Mar/2026:00:00:00 +0000",
226 timeEpoch: 1741478400000,
227 },
228 body: undefined,
229 pathParameters: undefined,
230 isBase64Encoded: false,
231 stageVariables: undefined,
232 };
233
234 return {
235 ...event,
236 ...overrides,
237 headers: { ...event.headers, ...overrides.headers },
238 requestContext: {
239 ...event.requestContext,
240 ...overrides.requestContext,
241 http: { ...event.requestContext.http, ...overrides.requestContext?.http },
242 },
243 };
244 };
245
246 const asStructuredResult = (
247 result: LambdaFunctionURLResult,
248 ): Exclude<LambdaFunctionURLResult, string> => {
249 if (typeof result === "string") {
250 throw new Error(`Expected a structured Lambda response, got: ${result}`);
251 }
252
253 return result;
254 };