@geostrategists/react-router-aws 2.2.1 → 2.3.0-rc.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.
@@ -1,107 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { htmlResponse, invokeHandlerWithRRMock, redirectResponse } from "./utils";
3
- import type { LambdaFunctionURLEvent } from "aws-lambda";
4
-
5
- function lambdaFunctionUrlEvent(
6
- path: string,
7
- method = "GET",
8
- headers: Record<string, string> = {},
9
- cookies?: string[],
10
- ): LambdaFunctionURLEvent {
11
- return {
12
- requestContext: { http: { method } } as LambdaFunctionURLEvent["requestContext"],
13
- rawPath: path,
14
- rawQueryString: "",
15
- headers: {
16
- host: "example.com",
17
- "x-forwarded-proto": "https",
18
- ...headers,
19
- },
20
- cookies,
21
- body: undefined,
22
- isBase64Encoded: false,
23
- } as Partial<LambdaFunctionURLEvent> as LambdaFunctionURLEvent;
24
- }
25
-
26
- describe("Function URL streaming request handling", () => {
27
- it("parses Function URL event", async () => {
28
- await invokeHandlerWithRRMock(
29
- "createFunctionURLStreamingRequestHandler",
30
- (request) => {
31
- expect(request.url).toBe("https://example.com/test");
32
- expect(request.method).toBe("POST");
33
- expect(request.headers.get("x-custom-header")).toBe("a");
34
- return new Response("ok");
35
- },
36
- lambdaFunctionUrlEvent("/test", "POST", { "x-custom-header": "a" }),
37
- );
38
- });
39
- });
40
-
41
- describe("Function URL streaming response handling", () => {
42
- it("html without cookie", async () => {
43
- const res = await invokeHandlerWithRRMock(
44
- "createFunctionURLStreamingRequestHandler",
45
- () => htmlResponse(),
46
- lambdaFunctionUrlEvent("/html"),
47
- );
48
- expect(res).toStrictEqual({
49
- statusCode: 200,
50
- headers: {
51
- "content-type": "text/html",
52
- },
53
- body: "<html>ok</html>",
54
- cookies: [],
55
- });
56
- });
57
-
58
- it("html with cookie", async () => {
59
- const res = await invokeHandlerWithRRMock(
60
- "createFunctionURLStreamingRequestHandler",
61
- () => htmlResponse("a=1; Path=/"),
62
- lambdaFunctionUrlEvent("/html"),
63
- );
64
- expect(res).toStrictEqual({
65
- statusCode: 200,
66
- headers: {
67
- "content-type": "text/html",
68
- },
69
- body: "<html>ok</html>",
70
- cookies: ["a=1; Path=/"],
71
- });
72
- });
73
-
74
- it("redirect without cookie", async () => {
75
- const res = await invokeHandlerWithRRMock(
76
- "createFunctionURLStreamingRequestHandler",
77
- () => redirectResponse(),
78
- lambdaFunctionUrlEvent("/redir"),
79
- );
80
- expect(res).toStrictEqual({
81
- statusCode: 302,
82
- headers: {
83
- location: "https://example.com/next",
84
- },
85
- cookies: [],
86
- // empty body gets added to provoke a write on the stream
87
- body: "",
88
- });
89
- });
90
-
91
- it("redirect with cookie", async () => {
92
- const res = await invokeHandlerWithRRMock(
93
- "createFunctionURLStreamingRequestHandler",
94
- () => redirectResponse("b=2; Path=/"),
95
- lambdaFunctionUrlEvent("/redir"),
96
- );
97
- expect(res).toStrictEqual({
98
- statusCode: 302,
99
- headers: {
100
- location: "https://example.com/next",
101
- },
102
- cookies: ["b=2; Path=/"],
103
- // empty body gets added to provoke a write on the stream
104
- body: "",
105
- });
106
- });
107
- });
@@ -1,107 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { htmlResponse, invokeHandlerWithRRMock, redirectResponse } from "./utils";
3
- import type { LambdaFunctionURLEvent } from "aws-lambda";
4
-
5
- function lambdaFunctionUrlEvent(
6
- path: string,
7
- method = "GET",
8
- headers: Record<string, string> = {},
9
- cookies?: string[],
10
- ): LambdaFunctionURLEvent {
11
- return {
12
- requestContext: { http: { method } } as LambdaFunctionURLEvent["requestContext"],
13
- rawPath: path,
14
- rawQueryString: "",
15
- headers: {
16
- host: "example.com",
17
- "x-forwarded-proto": "https",
18
- ...headers,
19
- },
20
- cookies,
21
- body: undefined,
22
- isBase64Encoded: false,
23
- } as Partial<LambdaFunctionURLEvent> as LambdaFunctionURLEvent;
24
- }
25
-
26
- describe("Function URL request handling", () => {
27
- it("parses Function URL event", async () => {
28
- await invokeHandlerWithRRMock(
29
- "createFunctionURLRequestHandler",
30
- (request) => {
31
- expect(request.url).toBe("https://example.com/test");
32
- expect(request.method).toBe("POST");
33
- expect(request.headers.get("x-custom-header")).toBe("a");
34
- return new Response("ok");
35
- },
36
- lambdaFunctionUrlEvent("/test", "POST", { "x-custom-header": "a" }),
37
- );
38
- });
39
- });
40
-
41
- describe("Function URL buffered response handling", () => {
42
- it("html without cookie", async () => {
43
- const res = await invokeHandlerWithRRMock(
44
- "createFunctionURLRequestHandler",
45
- () => htmlResponse(),
46
- lambdaFunctionUrlEvent("/html"),
47
- );
48
- expect(res).toStrictEqual({
49
- statusCode: 200,
50
- headers: {
51
- "content-type": "text/html",
52
- },
53
- body: "<html>ok</html>",
54
- isBase64Encoded: false,
55
- cookies: [],
56
- });
57
- });
58
-
59
- it("html with cookie", async () => {
60
- const res = await invokeHandlerWithRRMock(
61
- "createFunctionURLRequestHandler",
62
- () => htmlResponse("a=1; Path=/"),
63
- lambdaFunctionUrlEvent("/html"),
64
- );
65
- expect(res).toStrictEqual({
66
- statusCode: 200,
67
- headers: {
68
- "content-type": "text/html",
69
- },
70
- body: "<html>ok</html>",
71
- isBase64Encoded: false,
72
- cookies: ["a=1; Path=/"],
73
- });
74
- });
75
-
76
- it("redirect without cookie", async () => {
77
- const res = await invokeHandlerWithRRMock(
78
- "createFunctionURLRequestHandler",
79
- () => redirectResponse(),
80
- lambdaFunctionUrlEvent("/redir"),
81
- );
82
- expect(res).toStrictEqual({
83
- statusCode: 302,
84
- headers: {
85
- location: "https://example.com/next",
86
- },
87
- isBase64Encoded: false,
88
- cookies: [],
89
- });
90
- });
91
-
92
- it("redirect with cookie", async () => {
93
- const res = await invokeHandlerWithRRMock(
94
- "createFunctionURLRequestHandler",
95
- () => redirectResponse("b=2; Path=/"),
96
- lambdaFunctionUrlEvent("/redir"),
97
- );
98
- expect(res).toStrictEqual({
99
- statusCode: 302,
100
- headers: {
101
- location: "https://example.com/next",
102
- },
103
- isBase64Encoded: false,
104
- cookies: ["b=2; Path=/"],
105
- });
106
- });
107
- });
@@ -1,34 +0,0 @@
1
- // biome-ignore-all lint: keep close to upstream
2
- /**
3
- * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4
- *
5
- * HttpResponseStream is NOT used by the runtime.
6
- * It is only exposed in the `awslambda` variable for customers to use.
7
- */
8
-
9
- // based on https://github.com/aws/aws-lambda-nodejs-runtime-interface-client/blob/main/src/HttpResponseStream.js
10
- // which is licensed under Apache License 2.0
11
-
12
- import type { ResponseStream } from "./ResponseStream";
13
-
14
- const METADATA_PRELUDE_CONTENT_TYPE = "application/vnd.awslambda.http-integration-response";
15
- const DELIMITER_LEN = 8;
16
-
17
- // Implements the application/vnd.awslambda.http-integration-response content type.
18
- export class HttpResponseStream {
19
- static from(underlyingStream: ResponseStream, prelude: unknown) {
20
- underlyingStream.setContentType(METADATA_PRELUDE_CONTENT_TYPE);
21
-
22
- // JSON.stringify is required. NULL byte is not allowed in metadataPrelude.
23
- const metadataPrelude = JSON.stringify(prelude);
24
-
25
- underlyingStream._onBeforeFirstWrite = (write) => {
26
- write(metadataPrelude);
27
-
28
- // Write 8 null bytes after the JSON prelude.
29
- write(new Uint8Array(DELIMITER_LEN));
30
- };
31
-
32
- return underlyingStream;
33
- }
34
- }
@@ -1,44 +0,0 @@
1
- import { Stream } from "node:stream";
2
-
3
- // based on https://github.com/astuyve/lambda-stream/blob/main/src/ResponseStream.ts
4
- // which is MIT licensed according to https://www.npmjs.com/package/lambda-stream
5
-
6
- export class ResponseStream extends Stream.Writable {
7
- private response: Buffer[];
8
- _contentType?: string;
9
- _isBase64Encoded?: boolean;
10
- _onBeforeFirstWrite?: (write: (chunk: string | Uint8Array) => void) => void;
11
- _firstWriteHappened?: boolean = false;
12
-
13
- constructor() {
14
- super();
15
- this.response = [];
16
- }
17
-
18
- write(chunk: any, encoding: any, callback?: any): boolean {
19
- if (!this._firstWriteHappened) {
20
- this._firstWriteHappened = true;
21
- this._onBeforeFirstWrite?.(super.write.bind(this));
22
- }
23
- return super.write(chunk, encoding, callback);
24
- }
25
-
26
- // @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode
27
- // streams, `chunk` may be any JavaScript value.
28
- _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
29
- this.response.push(Buffer.from(chunk, encoding));
30
- callback();
31
- }
32
-
33
- getBufferedData(): Buffer {
34
- return Buffer.concat(this.response);
35
- }
36
-
37
- setContentType(contentType: string) {
38
- this._contentType = contentType;
39
- }
40
-
41
- setIsBase64Encoded(isBase64Encoded: boolean) {
42
- this._isBase64Encoded = isBase64Encoded;
43
- }
44
- }
@@ -1,56 +0,0 @@
1
- // based on https://github.com/astuyve/lambda-stream/blob/main/src/index.ts
2
- // which is MIT licensed according to https://www.npmjs.com/package/lambda-stream
3
-
4
- import type { StreamifyHandler } from "aws-lambda";
5
- import { ResponseStream } from "./ResponseStream";
6
- import { HttpResponseStream } from "./HttpResponseStream";
7
-
8
- export function streamifyResponse<TEvent = any, TResult = void>(
9
- handler: StreamifyHandler<TEvent, TResult>,
10
- ): StreamifyHandler<TEvent, TResult> {
11
- // Check for global awslambda
12
- return new Proxy(handler, {
13
- apply: async (target, _, argList: Parameters<StreamifyHandler<TEvent, TResult>>) => {
14
- const responseStream: ResponseStream = patchArgs(argList);
15
- await target(...argList);
16
-
17
- const bodyAndPrelude = responseStream._isBase64Encoded
18
- ? responseStream.getBufferedData().toString("base64")
19
- : responseStream.getBufferedData().toString();
20
-
21
- const delim = "\0".repeat(8);
22
- const delimPos = bodyAndPrelude.indexOf(delim);
23
- if (delimPos === -1) {
24
- return {
25
- statusCode: 200,
26
- headers: {
27
- "content-type": responseStream._contentType ?? "application/json",
28
- },
29
- cookies: [],
30
- body: bodyAndPrelude,
31
- };
32
- } else {
33
- const prelude = bodyAndPrelude.slice(0, delimPos);
34
- const body = bodyAndPrelude.slice(delimPos + delim.length);
35
- const parsedPrelude = JSON.parse(prelude);
36
- return {
37
- ...parsedPrelude,
38
- body,
39
- };
40
- }
41
- },
42
- });
43
- }
44
-
45
- function patchArgs(argList: any[]): ResponseStream {
46
- if (!(argList[1] instanceof ResponseStream)) {
47
- const responseStream = new ResponseStream();
48
- argList.splice(1, 0, responseStream);
49
- }
50
- return argList[1];
51
- }
52
-
53
- export const awslambda = {
54
- HttpResponseStream: HttpResponseStream,
55
- streamifyResponse: streamifyResponse,
56
- };
package/test/setup.ts DELETED
@@ -1,7 +0,0 @@
1
- import { vi } from "vitest";
2
- import { awslambda } from "./lambda-stream";
3
-
4
- vi.mock("react", () => ({}));
5
- vi.mock("react/jsx-runtime", () => ({}));
6
-
7
- vi.stubGlobal("awslambda", awslambda);
package/test/utils.ts DELETED
@@ -1,69 +0,0 @@
1
- import { vi } from "vitest";
2
- import type { Context, Handler } from "aws-lambda";
3
-
4
- import type { ServerBuild } from "react-router";
5
-
6
- let currentRRHandler: RRHandler | null = null;
7
- export function setReactRouterHandler(fn: RRHandler) {
8
- currentRRHandler = fn;
9
- }
10
- vi.mock("react-router", () => {
11
- return {
12
- createRequestHandler: () => {
13
- if (!currentRRHandler) throw new Error("React Router handler not set");
14
- return currentRRHandler;
15
- },
16
- };
17
- });
18
-
19
- type ReactRouterAws = typeof import("../src");
20
- type GatewayHandlers = Pick<
21
- ReactRouterAws,
22
- | "createALBRequestHandler"
23
- | "createAPIGatewayV1RequestHandler"
24
- | "createAPIGatewayV2RequestHandler"
25
- | "createFunctionURLRequestHandler"
26
- | "createFunctionURLStreamingRequestHandler"
27
- >;
28
-
29
- type RRHandler = (request: Request) => Response | Promise<Response>;
30
-
31
- export async function createHandlerWithRRMock<T extends keyof GatewayHandlers>(
32
- gatewayHandler: T,
33
- handler: RRHandler,
34
- ): Promise<GatewayHandlers[T]> {
35
- setReactRouterHandler(handler);
36
- const handlerFactory = (await import("../src"))[gatewayHandler] as any;
37
- return handlerFactory({ build: {} as unknown as ServerBuild });
38
- }
39
-
40
- export async function invokeHandlerWithRRMock<T extends keyof GatewayHandlers>(
41
- gatewayHandler: T,
42
- rrHandler: RRHandler,
43
- event: Parameters<ReturnType<GatewayHandlers[T]>>[0],
44
- ) {
45
- const handler = await createHandlerWithRRMock(gatewayHandler, rrHandler);
46
- return invokeHandler(handler as any, event);
47
- }
48
-
49
- export async function invokeHandler<E, R>(handler: Handler<E, R>, event: E): Promise<R> {
50
- return (await handler(event, {} as unknown as Context, () => {
51
- throw new Error("Callback not supported");
52
- })) as R;
53
- }
54
-
55
- export function htmlResponse(setCookie?: string) {
56
- const headers = new Headers({ "Content-Type": "text/html" });
57
- if (setCookie) {
58
- headers.append("Set-Cookie", setCookie);
59
- }
60
- return new Response("<html>ok</html>", { status: 200, headers });
61
- }
62
-
63
- export function redirectResponse(setCookie?: string) {
64
- const headers = new Headers({ Location: "https://example.com/next" });
65
- if (setCookie) {
66
- headers.append("Set-Cookie", setCookie);
67
- }
68
- return new Response(null, { status: 302, headers });
69
- }
package/vitest.config.ts DELETED
@@ -1,12 +0,0 @@
1
- import { defineConfig } from "vitest/config";
2
-
3
- export default defineConfig({
4
- test: {
5
- environment: "node",
6
- include: ["test/**/*.test.ts"],
7
- setupFiles: ["./test/setup.ts"],
8
- coverage: {
9
- reporter: ["text", "lcov"],
10
- },
11
- },
12
- });