lambda-reactor 1.0.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.
@@ -0,0 +1,7 @@
1
+ import {createHandler} from "#src/handler"
2
+ import {method} from "#src/method"
3
+ import {Response} from "#src/response"
4
+
5
+ export const handler = createHandler({
6
+ GET: method().handle(() => Response.text(200, "OK")),
7
+ })
@@ -0,0 +1,25 @@
1
+ import {createHandler} from "#src/handler"
2
+ import {method} from "#src/method"
3
+ import {Response} from "#src/response"
4
+ import {z} from "zod"
5
+
6
+ const ItemSchema = z.object({id: z.string(), label: z.string(), qty: z.number().int()})
7
+ const CreateItemSchema = ItemSchema.omit({id: true})
8
+ const ListSchema = z.array(ItemSchema)
9
+
10
+ const store: z.infer<typeof ItemSchema>[] = []
11
+
12
+ export const handler = createHandler({
13
+ GET: method()
14
+ .output(ListSchema)
15
+ .handle(() => store),
16
+
17
+ POST: method()
18
+ .input(CreateItemSchema)
19
+ .output(ItemSchema)
20
+ .handle(({body}) => {
21
+ const item = {id: crypto.randomUUID(), ...body}
22
+ store.push(item)
23
+ return Response.json(201, item)
24
+ }),
25
+ })
@@ -0,0 +1,20 @@
1
+ import {createHandler} from "#src/handler"
2
+ import {method} from "#src/method"
3
+ import {Response} from "#src/response"
4
+ import {z} from "zod"
5
+
6
+ const UserSchema = z.object({
7
+ id: z.string(),
8
+ name: z.string(),
9
+ email: z.email(),
10
+ })
11
+
12
+ export const handler = createHandler({
13
+ GET: method()
14
+ .output(UserSchema)
15
+ .handle(({event}) => {
16
+ const id = event.pathParameters?.["id"]
17
+ if (!id) return Response.text(400, "Missing id")
18
+ return {id, name: "Alice", email: "alice@example.com"}
19
+ }),
20
+ })
@@ -0,0 +1,26 @@
1
+ import {createHandler} from "#src/handler"
2
+ import {method} from "#src/method"
3
+ import {cors} from "#src/middleware"
4
+ import {Response} from "#src/response"
5
+ import {z} from "zod"
6
+
7
+ const CreateUserSchema = z.object({
8
+ name: z.string().min(1),
9
+ email: z.email(),
10
+ })
11
+
12
+ const CreatedUserSchema = z.object({
13
+ id: z.string(),
14
+ name: z.string(),
15
+ email: z.email(),
16
+ })
17
+
18
+ export const handler = createHandler({
19
+ POST: method()
20
+ .use(cors())
21
+ .input(CreateUserSchema)
22
+ .output(CreatedUserSchema)
23
+ .handle(({body}) => {
24
+ return Response.json(201, {id: crypto.randomUUID(), ...body})
25
+ }),
26
+ })
package/lefthook.yml ADDED
@@ -0,0 +1,16 @@
1
+ pre-commit:
2
+ parallel: true
3
+ jobs:
4
+ - name: format
5
+ glob: "*.{ts,tsx,js,json,yml,yaml,md}"
6
+ run: bunx prettier -w {staged_files} && git add {staged_files}
7
+ - name: lint
8
+ glob: "*.{ts,tsx}"
9
+ run: bunx eslint --fix {staged_files} && git add {staged_files}
10
+
11
+ pre-push:
12
+ jobs:
13
+ - name: check
14
+ run: bun run check
15
+ - name: test
16
+ run: bun test
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "lambda-reactor",
3
+ "version": "1.0.0",
4
+ "scripts": {
5
+ "prepare": "lefthook install",
6
+ "check": "tsgo",
7
+ "lint": "eslint --fix",
8
+ "format": "prettier -uwu .",
9
+ "test": "vitest",
10
+ "build": "rm -rf dist && tsgo -p tsconfig.build.json && bun build --target=node --external='*' --splitting --sourcemap=external --keep-names --root=src --outdir=dist src/*.ts"
11
+ },
12
+ "type": "module",
13
+ "imports": {
14
+ "#src/*": "./src/*.ts"
15
+ },
16
+ "devDependencies": {
17
+ "@eslint/js": "^10.0.1",
18
+ "@types/aws-lambda": "^8.10.161",
19
+ "@types/node": "^25.6.0",
20
+ "@types/source-map-support": "^0.5.10",
21
+ "@typescript/native-preview": "^7.0.0-dev.20260410.1",
22
+ "eslint": "^10.2.0",
23
+ "eslint-plugin-perfectionist": "^5.8.0",
24
+ "jiti": "^2.6.1",
25
+ "lefthook": "^2.1.5",
26
+ "prettier": "^3.8.2",
27
+ "typescript-eslint": "^8.46.1",
28
+ "vitest": "^4.1.4"
29
+ },
30
+ "dependencies": {
31
+ "aws-cdk-lib": "^2.248.0",
32
+ "source-map-support": "^0.5.21",
33
+ "zod": "^4.3.6"
34
+ }
35
+ }
@@ -0,0 +1,30 @@
1
+ import {join} from "path"
2
+
3
+ import type {IFunction} from "aws-cdk-lib/aws-lambda"
4
+ /**
5
+ * A factory function that constructs an AWS Lambda {@link IFunction} from a
6
+ * source-file entry path and a logical identifier string.
7
+ */
8
+ export type FunctionFactory = (entry: string, id: string) => IFunction
9
+
10
+ /**
11
+ * Builds a map of route paths to Lambda functions by invoking `factory` for
12
+ * each path.
13
+ *
14
+ * The `entry` passed to `factory` is the absolute path
15
+ * `<cwd>/src/<path>.ts`, and the `id` is the route path string itself.
16
+ *
17
+ * @param paths - Array of route path strings (e.g. `["/users", "/items"]`).
18
+ * @param factory - {@link FunctionFactory} used to construct each Lambda function.
19
+ */
20
+ export function buildHandlers<TPaths extends string>(
21
+ paths: TPaths[],
22
+ factory: FunctionFactory,
23
+ ): Record<TPaths, IFunction> {
24
+ return Object.fromEntries(
25
+ paths.map((path) => [
26
+ path,
27
+ factory(join(process.cwd(), "src", `${path}.ts`), path),
28
+ ]),
29
+ ) as Record<TPaths, IFunction>
30
+ }
@@ -0,0 +1,91 @@
1
+ import {logError} from "#src/logger"
2
+ import {RouteHandler} from "#src/method"
3
+ import {Response} from "#src/response"
4
+ import type {APIGatewayProxyEvent, Context} from "aws-lambda"
5
+ import {z} from "zod"
6
+
7
+ import {applyMiddlewares} from "./middleware"
8
+
9
+ /**
10
+ * Executes a single {@link RouteHandler} for an incoming Lambda proxy event.
11
+ *
12
+ * Processing order:
13
+ * 1. Parse `event.body` as JSON when possible.
14
+ * 2. Validate the body against `route.bodySchema` (Zod); return `400` on
15
+ * failure.
16
+ * 3. Invoke `route.callback` with the validated body, event, and context.
17
+ * 4. If the callback returns a {@link Response}, optionally validate its body
18
+ * against `route.outputSchema`; return `500` on failure.
19
+ * 5. If the callback returns a plain value, wrap it in a `200 JSON` response,
20
+ * optionally validating against `route.outputSchema`.
21
+ * 6. Apply all middlewares left-to-right before returning.
22
+ *
23
+ * @param route - The route handler to execute.
24
+ * @param event - Raw API Gateway proxy event.
25
+ * @param context - Lambda execution context.
26
+ */
27
+ export async function dispatch(
28
+ route: RouteHandler,
29
+ event: APIGatewayProxyEvent,
30
+ context: Context,
31
+ ) {
32
+ let body
33
+ try {
34
+ body = event.body ? JSON.parse(event.body) : undefined
35
+ } catch (error) {
36
+ if (error instanceof Error) {
37
+ return Response.text(400, error.message).toAPIGatewayProxyResult()
38
+ }
39
+ throw error
40
+ }
41
+ if (route.bodySchema) {
42
+ const parsed = route.bodySchema.safeParse(body)
43
+ if (!parsed.success) {
44
+ return Response.text(
45
+ 400,
46
+ z.treeifyError(parsed.error).errors.join("\n"),
47
+ ).toAPIGatewayProxyResult()
48
+ }
49
+ body = parsed.data
50
+ }
51
+ if (!route.callback) {
52
+ const err = new Error("Route has no handler defined")
53
+ logError(err)
54
+ return Response.text(500, err.message).toAPIGatewayProxyResult()
55
+ }
56
+ const cb = route.callback as (props: {
57
+ body: unknown
58
+ event: APIGatewayProxyEvent
59
+ context: Context
60
+ }) => Promise<unknown>
61
+ const result = await cb({body, event, context})
62
+ if (result instanceof Response) {
63
+ if (route.outputSchema) {
64
+ const parsed = route.outputSchema.safeParse(result.body)
65
+ if (!parsed.success) {
66
+ logError(parsed.error)
67
+ return Response.text(
68
+ 500,
69
+ z.treeifyError(parsed.error).errors.join("\n"),
70
+ ).toAPIGatewayProxyResult()
71
+ }
72
+ result.body = parsed.data
73
+ }
74
+ return applyMiddlewares(result.toAPIGatewayProxyResult(), route)
75
+ }
76
+ if (route.outputSchema) {
77
+ const parsed = route.outputSchema.safeParse(result)
78
+ if (!parsed.success) {
79
+ logError(parsed.error)
80
+ return Response.text(
81
+ 500,
82
+ z.treeifyError(parsed.error).errors.join("\n"),
83
+ ).toAPIGatewayProxyResult()
84
+ }
85
+ return applyMiddlewares(
86
+ Response.json(200, parsed.data).toAPIGatewayProxyResult(),
87
+ route,
88
+ )
89
+ }
90
+ return applyMiddlewares(Response.json(200, result).toAPIGatewayProxyResult(), route)
91
+ }
package/src/env.ts ADDED
@@ -0,0 +1,23 @@
1
+ const PROD_VALUES = new Set(["production", "prod"])
2
+
3
+ /**
4
+ * Returns `true` if the given environment variable value represents a
5
+ * production environment (`"production"` or `"prod"`, case-insensitive).
6
+ */
7
+ function isProductionValue(value: string | undefined): boolean {
8
+ return value !== undefined && PROD_VALUES.has(value.toLowerCase())
9
+ }
10
+
11
+ /**
12
+ * Returns `true` when any of the conventional environment variables
13
+ * (`NODE_ENV`, `STAGE`, `ENV`, `ENVIRONMENT`) indicate a production
14
+ * deployment.
15
+ */
16
+ export function isProduction(): boolean {
17
+ return (
18
+ isProductionValue(process.env["NODE_ENV"]) ||
19
+ isProductionValue(process.env["STAGE"]) ||
20
+ isProductionValue(process.env["ENV"]) ||
21
+ isProductionValue(process.env["ENVIRONMENT"])
22
+ )
23
+ }
package/src/handler.ts ADDED
@@ -0,0 +1,58 @@
1
+ import {dispatch} from "#src/dispatch"
2
+ import {isProduction} from "#src/env"
3
+ import {formatError, logError} from "#src/logger"
4
+ import {RouteHandler} from "#src/method"
5
+ import {Response} from "#src/response"
6
+ import type {APIGatewayProxyEvent, APIGatewayProxyResult, Context} from "aws-lambda"
7
+ import {install} from "source-map-support"
8
+
9
+ install()
10
+
11
+ /**
12
+ * Creates an AWS Lambda handler function from a map of HTTP-method names to
13
+ * {@link RouteHandler} instances.
14
+ *
15
+ * The returned handler:
16
+ * - Returns `405 Method Not Allowed` (with an `Allow` header) for any HTTP
17
+ * method not present in `routes`.
18
+ * - Delegates matching requests to {@link dispatch}.
19
+ * - Catches any `Error` thrown by `dispatch`, logs it, and returns
20
+ * `500 Internal Server Error`. In non-production environments the error
21
+ * message and stack trace are included in the response body.
22
+ * - Re-throws non-`Error` throwables so they propagate to the Lambda runtime.
23
+ *
24
+ * @param routes - Map of upper-case HTTP method names (e.g. `"GET"`, `"POST"`)
25
+ * to their corresponding {@link RouteHandler}.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * export const handler = createHandler({
30
+ * GET: method().handle(async () => Response.json(200, {ok: true})),
31
+ * })
32
+ * ```
33
+ */
34
+ export function createHandler<T extends Record<string, RouteHandler>>(routes: T) {
35
+ return async (
36
+ event: APIGatewayProxyEvent,
37
+ context: Context,
38
+ ): Promise<APIGatewayProxyResult> => {
39
+ const route = routes[event.httpMethod as keyof T]
40
+ if (!route) {
41
+ return Response.text(405, "Method Not Allowed")
42
+ .header("Allow", Object.keys(routes).join(", "))
43
+ .toAPIGatewayProxyResult()
44
+ }
45
+ try {
46
+ return await dispatch(route, event, context)
47
+ } catch (error) {
48
+ if (error instanceof Error) {
49
+ logError(error)
50
+ return Response.text(
51
+ 500,
52
+ isProduction() ? "Internal Server Error" : formatError(error),
53
+ ).toAPIGatewayProxyResult()
54
+ }
55
+ throw error
56
+ }
57
+ }
58
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,19 @@
1
+ import * as z from "zod"
2
+
3
+ /**
4
+ * Formats an `Error` into a human-readable string that includes the error
5
+ * name, message, an optional Zod validation detail block, and the stack
6
+ * trace when available.
7
+ */
8
+ export function formatError(error: Error): string {
9
+ let detail
10
+ if (error instanceof z.ZodError) {
11
+ detail = z.treeifyError(error).errors.join("\n")
12
+ }
13
+ return `${error.name}: ${error.message}${detail ? `\n${detail}` : ""}${error.stack ? `\n${error.stack}` : ""}`
14
+ }
15
+
16
+ /** Writes a formatted error to `stderr` via `console.error`. */
17
+ export function logError(error: Error): void {
18
+ console.error(formatError(error))
19
+ }
package/src/method.ts ADDED
@@ -0,0 +1,92 @@
1
+ import {type Middleware} from "#src/middleware"
2
+ import {EndpointCallback, RouteHandler} from "#src/route-handler"
3
+ import type {ZodType} from "zod"
4
+
5
+ export type {EndpointCallback, RouteHandler}
6
+
7
+ /**
8
+ * Fluent, immutable builder for a single HTTP-method handler.
9
+ *
10
+ * Every method returns a new `Method` instance, leaving the original
11
+ * unchanged. Build a method with the following chain:
12
+ *
13
+ * ```ts
14
+ * method().use(cors()).input(schema).output(schema).handle(async ({body}) => …)
15
+ * ```
16
+ *
17
+ * @typeParam TInput - Shape of the validated request body.
18
+ * @typeParam TOutput - Return type of the handler callback.
19
+ */
20
+ export class Method<TInput = unknown, TOutput = unknown> {
21
+ middlewares: Middleware[] = []
22
+ bodySchema?: ZodType<TInput>
23
+ outputSchema?: ZodType<TOutput>
24
+ callback?: EndpointCallback<TInput, TOutput>
25
+
26
+ /**
27
+ * Appends a middleware to the chain. Middlewares are applied
28
+ * left-to-right after the callback resolves.
29
+ *
30
+ * @param middleware - The {@link Middleware} to append.
31
+ */
32
+ use(middleware: Middleware): Method<TInput, TOutput> {
33
+ const r = new Method<TInput, TOutput>()
34
+ r.middlewares = [...this.middlewares, middleware]
35
+ if (this.bodySchema) r.bodySchema = this.bodySchema
36
+ if (this.outputSchema) r.outputSchema = this.outputSchema
37
+ if (this.callback) r.callback = this.callback
38
+ return r
39
+ }
40
+
41
+ /**
42
+ * Attaches a Zod schema used to validate (and narrow) the request body.
43
+ * When validation fails, `dispatch` returns a `400` response automatically.
44
+ *
45
+ * @param bodySchema - Zod schema for the request body.
46
+ */
47
+ input<U>(bodySchema: ZodType<U>): Method<U, TOutput> {
48
+ const r = new Method<U, TOutput>()
49
+ r.middlewares = this.middlewares
50
+ r.bodySchema = bodySchema
51
+ if (this.outputSchema) r.outputSchema = this.outputSchema as ZodType<TOutput>
52
+ if (this.callback)
53
+ r.callback = this.callback as unknown as EndpointCallback<U, TOutput>
54
+ return r
55
+ }
56
+
57
+ /**
58
+ * Attaches a Zod schema that describes the expected response shape.
59
+ * Currently stored for documentation / code-generation purposes.
60
+ *
61
+ * @param schema - Zod schema for the response body.
62
+ */
63
+ output<U>(schema: ZodType<U>): Method<TInput, U> {
64
+ const r = new Method<TInput, U>()
65
+ r.middlewares = this.middlewares
66
+ if (this.bodySchema) r.bodySchema = this.bodySchema
67
+ r.outputSchema = schema
68
+ if (this.callback)
69
+ r.callback = this.callback as unknown as EndpointCallback<TInput, U>
70
+ return r
71
+ }
72
+
73
+ /**
74
+ * Registers the async handler callback for this method.
75
+ *
76
+ * @param callback - Function that receives the validated body, the raw
77
+ * Lambda event, and the Lambda context, and returns the response.
78
+ */
79
+ handle(callback: EndpointCallback<TInput, TOutput>): Method<TInput, TOutput> {
80
+ const r = new Method<TInput, TOutput>()
81
+ r.middlewares = this.middlewares
82
+ if (this.bodySchema) r.bodySchema = this.bodySchema
83
+ if (this.outputSchema) r.outputSchema = this.outputSchema
84
+ r.callback = callback
85
+ return r
86
+ }
87
+ }
88
+
89
+ /** Creates a new, empty {@link Method} builder. */
90
+ export function method(): Method {
91
+ return new Method()
92
+ }
@@ -0,0 +1,41 @@
1
+ import type {APIGatewayProxyResult} from "aws-lambda"
2
+
3
+ import {RouteHandler} from "./route-handler"
4
+
5
+ /**
6
+ * A pure function that receives an {@link APIGatewayProxyResult} and returns
7
+ * a (possibly modified) copy of it. Middlewares are composed left-to-right
8
+ * by {@link dispatch}.
9
+ */
10
+ export type Middleware = (result: APIGatewayProxyResult) => APIGatewayProxyResult
11
+
12
+ /**
13
+ * Creates a middleware that injects CORS response headers.
14
+ *
15
+ * Each key in `headers` is prefixed with `"Access-Control-"` before being
16
+ * merged into the response, so passing `{"Allow-Origin": "*"}` produces the
17
+ * `Access-Control-Allow-Origin: *` header.
18
+ *
19
+ * @param headers - Map of unprefixed CORS header names to their values.
20
+ * Defaults to an empty object (no CORS headers added).
21
+ */
22
+ export function cors(headers: Record<string, string> = {}): Middleware {
23
+ return (result) => {
24
+ const corsHeaders: Record<string, string> = {}
25
+ for (const [key, value] of Object.entries(headers)) {
26
+ corsHeaders[`Access-Control-${key}`] = value
27
+ }
28
+ return {...result, headers: {...result.headers, ...corsHeaders}}
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Folds all middlewares registered on `route` over `result`, applying them
34
+ * left-to-right, and returns the final {@link APIGatewayProxyResult}.
35
+ */
36
+ export function applyMiddlewares(
37
+ result: APIGatewayProxyResult,
38
+ route: RouteHandler,
39
+ ): APIGatewayProxyResult {
40
+ return route.middlewares.reduce((r, middleware) => middleware(r), result)
41
+ }
@@ -0,0 +1,86 @@
1
+ import type {APIGatewayProxyResult} from "aws-lambda"
2
+
3
+ /**
4
+ * Immutable builder for AWS Lambda proxy responses.
5
+ *
6
+ * All mutation methods return a new `Response` instance so that existing
7
+ * instances are never modified. Construct instances through the static
8
+ * factory methods {@link Response.text} and {@link Response.json}.
9
+ */
10
+ export class Response {
11
+ status?: number
12
+ body?: unknown
13
+ text?: string
14
+ headers?: Record<string, string>
15
+
16
+ private constructor() {}
17
+
18
+ /**
19
+ * Creates a plain-text response.
20
+ *
21
+ * @param status - HTTP status code.
22
+ * @param text - Response body as a plain string.
23
+ */
24
+ static text(status: number, text: string) {
25
+ const r = new Response()
26
+ r.status = status
27
+ r.text = text
28
+ return r
29
+ }
30
+
31
+ /**
32
+ * Creates a JSON response.
33
+ *
34
+ * @param status - HTTP status code.
35
+ * @param body - Value to be serialised with `JSON.stringify`.
36
+ */
37
+ static json(status: number, body: unknown) {
38
+ const r = new Response()
39
+ r.status = status
40
+ r.body = body
41
+ return r
42
+ }
43
+
44
+ /**
45
+ * Returns a new `Response` with an additional HTTP response header.
46
+ *
47
+ * @param name - Header name (e.g. `"Allow"`).
48
+ * @param value - Header value.
49
+ */
50
+ header(name: string, value: string): Response {
51
+ const r = new Response()
52
+ if (this.status !== undefined) r.status = this.status
53
+ if (this.body !== undefined) r.body = this.body
54
+ if (this.text !== undefined) r.text = this.text
55
+ r.headers = {...this.headers, [name]: value}
56
+ return r
57
+ }
58
+
59
+ /**
60
+ * Serialises this `Response` into the shape expected by the AWS Lambda
61
+ * proxy integration.
62
+ *
63
+ * - When constructed via {@link Response.json} the body is JSON-encoded
64
+ * and `Content-Type` is set to `application/json; charset=utf-8`.
65
+ * - When constructed via {@link Response.text} the body is returned as-is
66
+ * and `Content-Type` is set to `text/plain; charset=utf-8`.
67
+ * - Additional headers set via {@link Response.header} are merged last and
68
+ * therefore take precedence over the defaults above.
69
+ */
70
+ toAPIGatewayProxyResult(): APIGatewayProxyResult {
71
+ return {
72
+ statusCode: this.status ?? 200,
73
+ body:
74
+ this.text === undefined ?
75
+ (JSON.stringify(this.body) ?? "null")
76
+ : this.text,
77
+ headers: {
78
+ "Content-Type":
79
+ this.text === undefined ?
80
+ "application/json; charset=utf-8"
81
+ : "text/plain; charset=utf-8",
82
+ ...this.headers,
83
+ },
84
+ }
85
+ }
86
+ }
@@ -0,0 +1,28 @@
1
+ import {type Middleware} from "#src/middleware"
2
+ import {Response} from "#src/response"
3
+ import type {APIGatewayProxyEvent, Context} from "aws-lambda"
4
+ import type {ZodType} from "zod"
5
+
6
+ /**
7
+ * The user-supplied handler function for a single HTTP method on a route.
8
+ *
9
+ * @typeParam TInput - Shape of the validated request body (after Zod parsing).
10
+ * @typeParam TOutput - Shape of the value returned by the callback.
11
+ */
12
+ export type EndpointCallback<TInput, TOutput> = (props: {
13
+ body: TInput
14
+ event: APIGatewayProxyEvent
15
+ context: Context
16
+ }) => Promise<TOutput | Response> | TOutput | Response
17
+
18
+ /**
19
+ * Internal read-only view of a {@link Method} used by {@link dispatch} and
20
+ * {@link createHandler}. The type parameters are erased so that handlers for
21
+ * different routes can be stored in the same map.
22
+ */
23
+ export interface RouteHandler {
24
+ readonly middlewares: Middleware[]
25
+ readonly bodySchema?: ZodType<unknown>
26
+ readonly outputSchema?: ZodType<unknown>
27
+ readonly callback?: (props: never) => unknown
28
+ }