@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 171 lines 6.65 KB
Raw
1 import type { Input } from "alchemy/Input";
2 import * as Namespace from "alchemy/Namespace";
3 import * as Output from "alchemy/Output";
4 import type lambda from "aws-lambda";
5 import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import { type ApiGatewayResource, GatewayResource } from "../ApiGateway/GatewayResource.ts";
8 import { MethodResource } from "../ApiGateway/Method.ts";
9 import type { RestApi } from "../ApiGateway/RestApi.ts";
10 import {
11 RestApiEventSource as AGRestApiEventSource,
12 type RestApiEvent,
13 type RestApiEventSourceService,
14 type RestApiResult,
15 type RestApiRouteProps,
16 } from "../ApiGateway/RestApiEventSource.ts";
17 import * as Lambda from "./Function.ts";
18 import { Permission as LambdaPermission } from "./Permission.ts";
19
20 export const isRestApiEvent = (event: any): event is lambda.APIGatewayProxyEvent =>
21 typeof event?.httpMethod === "string" &&
22 typeof event?.resource === "string" &&
23 typeof event?.requestContext?.apiId === "string" &&
24 // WebSocket proxy events carry `messageDirection`; REST v1 events don't.
25 event?.requestContext?.messageDirection === undefined;
26
27 /** `/items/{proxy+}` → `itemsproxy` for stable, readable logical ids. */
28 const sanitizePathKey = (path: string, httpMethod: string) =>
29 `${path}-${httpMethod}`.replace(/[^A-Za-z0-9]+/g, "") || "root";
30
31 /**
32 * Connects a REST API (v1) route to the current Lambda function.
33 *
34 * At deploy time this layer materializes the path `Resource` chain, the
35 * `Method` with an `AWS_PROXY` integration, and the API Gateway invoke
36 * `Permission` for each registered route — and registers each child as a
37 * `RestApiBinding` on the API so any `Deployment` of the same API is
38 * ordered after them. At runtime it dispatches matching REST proxy events
39 * to the registered handler.
40 * ### Handling REST API routes
41 * **Example:** JSON endpoint
42 * ```typescript
43 * yield* AWS.ApiGateway.onRestApiRoute(
44 * api,
45 * { path: "/items", httpMethod: "GET" },
46 * () =>
47 * Effect.succeed({
48 * statusCode: 200,
49 * body: JSON.stringify({ items: [] }),
50 * }),
51 * );
52 * ```
53 *
54 * @binding
55 */
56 export const RestApiEventSource = Layer.effect(
57 AGRestApiEventSource,
58 Effect.gen(function* () {
59 // this layer can only be used in a Lambda Function
60 const host = yield* Lambda.eventSourceHost("AWS.Lambda.RestApiEventSource");
61 const Resource = yield* GatewayResource;
62 const Method = yield* MethodResource;
63 const Permission = yield* LambdaPermission;
64
65 return Effect.fn(function* <Req = never>(
66 api: RestApi,
67 props: RestApiRouteProps,
68 handler: (event: RestApiEvent) => Effect.Effect<RestApiResult, never, Req>,
69 ) {
70 const path = props.path ?? "/";
71 const httpMethod = (props.httpMethod ?? "ANY").toUpperCase();
72
73 // Deploy-time: materialize the path Resource chain + Method +
74 // invoke Permission for this route. Skipped once running inside
75 // the deployed Function (the global guard), where the only work is
76 // registering the runtime dispatcher below. Namespaced under the
77 // host for stable logical identity.
78 if (!globalThis.__ALCHEMY_RUNTIME__) {
79 yield* Namespace.push(
80 host.LogicalId,
81 Effect.gen(function* () {
82 const key = sanitizePathKey(path, httpMethod);
83
84 // Build the Resource chain for each path segment; methods on
85 // the root path attach directly to `api.rootResourceId`.
86 let parentId: Input<string> = api.rootResourceId;
87 let prefix = "";
88 for (const segment of path.split("/").filter(Boolean)) {
89 prefix += `/${segment}`;
90 const resourceKey = prefix.replace(/[^A-Za-z0-9]+/g, "") || "root";
91 // Explicit annotation: `resource` feeds `parentId` for the next
92 // loop iteration's `Resource(...)` call, which TS 7 otherwise
93 // flags as a self-referential inference cycle (TS7022).
94 const resource: ApiGatewayResource = yield* Resource(
95 `${api.LogicalId}-${resourceKey}-Resource`,
96 {
97 restApiId: api.restApiId,
98 parentId,
99 pathPart: segment,
100 },
101 );
102 yield* api.bind`${resource}`({
103 kind: "resource",
104 resourceId: resource.resourceId,
105 parentId: resource.parentId,
106 pathPart: resource.pathPart,
107 });
108 parentId = resource.resourceId;
109 }
110
111 const method = yield* Method(`${api.LogicalId}-${key}-Method`, {
112 restApiId: api.restApiId,
113 resourceId: parentId,
114 httpMethod,
115 authorizationType: "NONE",
116 integration: {
117 type: "AWS_PROXY",
118 integrationHttpMethod: "POST",
119 // AWS_PROXY integrations require the full Lambda invocation
120 // URI. Region is derived from the function ARN so the
121 // binding needs no ambient environment.
122 uri: Output.map(
123 Lambda.qualifiedArnOf(host),
124 (arn: string) =>
125 `arn:aws:apigateway:${arn.split(":")[3]}:lambda:path/2015-03-31/functions/${arn}/invocations`,
126 ),
127 },
128 });
129 yield* api.bind`${method}`({
130 kind: "method",
131 methodId: method.LogicalId,
132 restApiId: method.restApiId,
133 resourceId: method.resourceId,
134 httpMethod: method.httpMethod,
135 });
136
137 yield* Permission(`${api.LogicalId}-${key}-Permission`, {
138 action: "lambda:InvokeFunction",
139 functionName: Lambda.qualifiedNameOf(host),
140 principal: "apigateway.amazonaws.com",
141 sourceArn: Output.map(
142 Output.all(host.functionArn, api.restApiId),
143 ([fnArn, apiId]: [string, string]) => {
144 const [, , , region, accountId] = fnArn.split(":");
145 return `arn:aws:execute-api:${region}:${accountId}:${apiId}/*`;
146 },
147 ),
148 });
149 }),
150 );
151 }
152
153 yield* host.listen(
154 Effect.gen(function* () {
155 return (event: any) => {
156 if (
157 isRestApiEvent(event) &&
158 event.resource === path &&
159 (httpMethod === "ANY" || event.httpMethod === httpMethod)
160 ) {
161 return handler(event).pipe(
162 Effect.map((result) => result ?? { statusCode: 200, body: "" }),
163 Effect.orDie,
164 );
165 }
166 };
167 }),
168 );
169 }) as RestApiEventSourceService;
170 }),
171 );