@opennextjs/cloudflare 0.0.0-fd3c2b9 → 0.0.3

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.
@@ -17,7 +17,7 @@ function existsSync(path: string) {
17
17
  return FILES.has(path);
18
18
  }
19
19
 
20
- async function readFile(path: string, options: unknown): Promise<any> {
20
+ async function readFile(path: string, options: unknown): Promise<unknown> {
21
21
  console.log(
22
22
  "readFile",
23
23
  { path, options }
@@ -0,0 +1,156 @@
1
+ import type { ExportedHandler, Fetcher } from "@cloudflare/workers-types";
2
+ import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import type { CloudflareContext } from "../../api";
5
+ import type { IncomingMessage } from "node:http";
6
+ import { MockedResponse } from "next/dist/server/lib/mock-request";
7
+ import type { NextConfig } from "next";
8
+ import type { NodeRequestHandler } from "next/dist/server/next-server";
9
+ import Stream from "node:stream";
10
+
11
+ const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);
12
+
13
+ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
14
+
15
+ // Note: this symbol needs to be kept in sync with the one defined in `src/api/get-cloudflare-context.ts`
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ (globalThis as any)[Symbol.for("__cloudflare-context__")] = new Proxy(
18
+ {},
19
+ {
20
+ ownKeys: () => Reflect.ownKeys(cloudflareContextALS.getStore()!),
21
+ getOwnPropertyDescriptor: (_, ...args) =>
22
+ Reflect.getOwnPropertyDescriptor(cloudflareContextALS.getStore()!, ...args),
23
+ get: (_, property) => Reflect.get(cloudflareContextALS.getStore()!, property),
24
+ set: (_, property, value) => Reflect.set(cloudflareContextALS.getStore()!, property, value),
25
+ }
26
+ );
27
+
28
+ // Injected at build time
29
+ const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
30
+
31
+ let requestHandler: NodeRequestHandler | null = null;
32
+
33
+ export default {
34
+ async fetch(request, env, ctx) {
35
+ return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
36
+ if (requestHandler == null) {
37
+ globalThis.process.env = { ...globalThis.process.env, ...env };
38
+ // Note: "next/dist/server/next-server" is a cjs module so we have to `require` it not to confuse esbuild
39
+ // (since esbuild can run in projects with different module resolutions)
40
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
41
+ const NextNodeServer = require("next/dist/server/next-server")
42
+ .default as typeof import("next/dist/server/next-server").default;
43
+
44
+ requestHandler = new NextNodeServer({
45
+ conf: nextConfig,
46
+ customServer: false,
47
+ dev: false,
48
+ dir: "",
49
+ minimalMode: false,
50
+ }).getRequestHandler();
51
+ }
52
+
53
+ const url = new URL(request.url);
54
+
55
+ if (url.pathname === "/_next/image") {
56
+ const imageUrl =
57
+ url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
58
+ if (imageUrl.startsWith("/")) {
59
+ return env.ASSETS.fetch(new URL(imageUrl, request.url));
60
+ }
61
+ return fetch(imageUrl, { cf: { cacheEverything: true } });
62
+ }
63
+
64
+ const { req, res, webResponse } = getWrappedStreams(request, ctx);
65
+
66
+ ctx.waitUntil(Promise.resolve(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res))));
67
+
68
+ return await webResponse();
69
+ });
70
+ },
71
+ } as ExportedHandler<{ ASSETS: Fetcher }>;
72
+
73
+ function getWrappedStreams(request: Request, ctx: ExecutionContext) {
74
+ const url = new URL(request.url);
75
+
76
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
+ const reqBody = request.body && Stream.Readable.fromWeb(request.body as any);
78
+ const req = (reqBody ?? Stream.Readable.from([])) as IncomingMessage;
79
+ req.httpVersion = "1.0";
80
+ req.httpVersionMajor = 1;
81
+ req.httpVersionMinor = 0;
82
+ req.url = url.href.slice(url.origin.length);
83
+ req.headers = Object.fromEntries([...request.headers]);
84
+ req.method = request.method;
85
+ Object.defineProperty(req, "__node_stream__", {
86
+ value: true,
87
+ writable: false,
88
+ });
89
+ Object.defineProperty(req, "headersDistinct", {
90
+ get() {
91
+ const headers: Record<string, string[]> = {};
92
+ for (const [key, value] of Object.entries(req.headers)) {
93
+ if (!value) continue;
94
+ headers[key] = Array.isArray(value) ? value : [value];
95
+ }
96
+ return headers;
97
+ },
98
+ });
99
+
100
+ const { readable, writable } = new IdentityTransformStream();
101
+ const resBodyWriter = writable.getWriter();
102
+
103
+ const res = new MockedResponse({
104
+ resWriter: (chunk) => {
105
+ resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err) => {
106
+ if (
107
+ err.message.includes("WritableStream has been closed") ||
108
+ err.message.includes("Network connection lost")
109
+ ) {
110
+ // safe to ignore
111
+ return;
112
+ }
113
+ console.error("Error in resBodyWriter.write");
114
+ console.error(err);
115
+ });
116
+ return true;
117
+ },
118
+ });
119
+
120
+ // It's implemented as a no-op, but really it should mark the headers as done
121
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
122
+ res.flushHeaders = () => (res as any).headPromiseResolve();
123
+
124
+ // Only allow statusCode to be modified if not sent
125
+ let { statusCode } = res;
126
+ Object.defineProperty(res, "statusCode", {
127
+ get: function () {
128
+ return statusCode;
129
+ },
130
+ set: function (val) {
131
+ if (this.finished || this.headersSent) {
132
+ return;
133
+ }
134
+ statusCode = val;
135
+ },
136
+ });
137
+
138
+ // Make sure the writer is eventually closed
139
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
+ ctx.waitUntil((res as any).hasStreamed.finally(() => resBodyWriter.close().catch(() => {})));
141
+
142
+ return {
143
+ res,
144
+ req,
145
+ webResponse: async () => {
146
+ await res.headPromise;
147
+ // TODO: remove this once streaming with compression is working nicely
148
+ res.setHeader("content-encoding", "identity");
149
+ return new Response(NON_BODY_RESPONSES.has(res.statusCode) ? null : readable, {
150
+ status: res.statusCode,
151
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
+ headers: (res as any).headers,
153
+ });
154
+ },
155
+ };
156
+ }
package/package.json CHANGED
@@ -1,16 +1,24 @@
1
1
  {
2
2
  "name": "@opennextjs/cloudflare",
3
3
  "description": "Cloudflare builder for next apps",
4
- "version": "0.0.0-fd3c2b9",
5
- "bin": "dist/index.mjs",
4
+ "version": "0.0.3",
5
+ "bin": "dist/cli/index.mjs",
6
+ "main": "./dist/api/index.mjs",
7
+ "types": "./dist/api/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/api/index.mjs",
11
+ "types": "./dist/api/index.d.mts"
12
+ }
13
+ },
6
14
  "files": [
7
15
  "README.md",
8
16
  "dist"
9
17
  ],
10
18
  "repository": {
11
19
  "type": "git",
12
- "url": "https://github.com/flarelabs-net/poc-next.git",
13
- "directory": "builder"
20
+ "url": "https://github.com/opennextjs/opennextjs-cloudflare.git",
21
+ "directory": "packages/cloudflare"
14
22
  },
15
23
  "keywords": [
16
24
  "cloudflare",
@@ -19,23 +27,38 @@
19
27
  ],
20
28
  "license": "MIT",
21
29
  "bugs": {
22
- "url": "https://github.com/flarelabs-net/poc-next/issues"
30
+ "url": "https://github.com/opennextjs/opennextjs-cloudflare/issues"
23
31
  },
24
- "homepage": "https://github.com/flarelabs-net/poc-next",
32
+ "homepage": "https://github.com/opennextjs/opennextjs-cloudflare",
25
33
  "devDependencies": {
34
+ "@cloudflare/workers-types": "^4.20240925.0",
35
+ "@eslint/js": "^9.11.1",
36
+ "@tsconfig/strictest": "^2.0.5",
26
37
  "@types/node": "^22.2.0",
27
38
  "esbuild": "^0.23.0",
39
+ "eslint": "^9.11.1",
40
+ "eslint-plugin-unicorn": "^55.0.0",
28
41
  "glob": "^11.0.0",
42
+ "globals": "^15.9.0",
43
+ "next": "14.2.11",
44
+ "package-manager-detector": "^0.2.0",
29
45
  "tsup": "^8.2.4",
30
46
  "typescript": "^5.5.4",
47
+ "typescript-eslint": "^8.7.0",
31
48
  "vitest": "^2.1.1"
32
49
  },
33
50
  "dependencies": {
34
51
  "ts-morph": "^23.0.0"
35
52
  },
53
+ "peerDependencies": {
54
+ "wrangler": "^3.78.10"
55
+ },
36
56
  "scripts": {
37
57
  "build": "tsup",
38
58
  "build:watch": "tsup --watch src",
59
+ "lint:check": "eslint",
60
+ "lint:fix": "eslint --fix",
61
+ "ts:check": "tsc --noEmit",
39
62
  "test": "vitest --run",
40
63
  "test:watch": "vitest"
41
64
  }
@@ -1,128 +0,0 @@
1
- import Stream from "node:stream";
2
- import type { NextConfig } from "next";
3
- import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
4
- import { MockedResponse } from "next/dist/server/lib/mock-request";
5
- import NextNodeServer, { NodeRequestHandler } from "next/dist/server/next-server";
6
- import type { IncomingMessage } from "node:http";
7
-
8
- const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);
9
-
10
- // Injected at build time
11
- const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
12
-
13
- let requestHandler: NodeRequestHandler | null = null;
14
-
15
- export default {
16
- async fetch(request: Request, env: any, ctx: any) {
17
- if (requestHandler == null) {
18
- globalThis.process.env = { ...globalThis.process.env, ...env };
19
- requestHandler = new NextNodeServer({
20
- conf: { ...nextConfig, env },
21
- customServer: false,
22
- dev: false,
23
- dir: "",
24
- minimalMode: false,
25
- }).getRequestHandler();
26
- }
27
-
28
- const url = new URL(request.url);
29
-
30
- if (url.pathname === "/_next/image") {
31
- let imageUrl =
32
- url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
33
- if (imageUrl.startsWith("/")) {
34
- return env.ASSETS.fetch(new URL(imageUrl, request.url));
35
- }
36
- return fetch(imageUrl, { cf: { cacheEverything: true } } as any);
37
- }
38
-
39
- const { req, res, webResponse } = getWrappedStreams(request, ctx);
40
-
41
- ctx.waitUntil(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res)));
42
-
43
- return await webResponse();
44
- },
45
- };
46
-
47
- function getWrappedStreams(request: Request, ctx: any) {
48
- const url = new URL(request.url);
49
-
50
- const req = (
51
- request.body ? Stream.Readable.fromWeb(request.body as any) : Stream.Readable.from([])
52
- ) as IncomingMessage;
53
- req.httpVersion = "1.0";
54
- req.httpVersionMajor = 1;
55
- req.httpVersionMinor = 0;
56
- req.url = url.href.slice(url.origin.length);
57
- req.headers = Object.fromEntries([...request.headers]);
58
- req.method = request.method;
59
- Object.defineProperty(req, "__node_stream__", {
60
- value: true,
61
- writable: false,
62
- });
63
- Object.defineProperty(req, "headersDistinct", {
64
- get() {
65
- const headers: Record<string, string[]> = {};
66
- for (const [key, value] of Object.entries(req.headers)) {
67
- if (!value) continue;
68
- headers[key] = Array.isArray(value) ? value : [value];
69
- }
70
- return headers;
71
- },
72
- });
73
-
74
- const { readable, writable } = new IdentityTransformStream();
75
- const resBodyWriter = writable.getWriter();
76
-
77
- const res = new MockedResponse({
78
- resWriter: (chunk) => {
79
- resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err: any) => {
80
- if (
81
- err.message.includes("WritableStream has been closed") ||
82
- err.message.includes("Network connection lost")
83
- ) {
84
- // safe to ignore
85
- return;
86
- }
87
- console.error("Error in resBodyWriter.write");
88
- console.error(err);
89
- });
90
- return true;
91
- },
92
- });
93
-
94
- // It's implemented as a no-op, but really it should mark the headers as done
95
- res.flushHeaders = () => (res as any).headPromiseResolve();
96
-
97
- // Only allow statusCode to be modified if not sent
98
- let { statusCode } = res;
99
- Object.defineProperty(res, "statusCode", {
100
- get: function () {
101
- return statusCode;
102
- },
103
- set: function (val) {
104
- if (this.finished || this.headersSent) {
105
- console.error("headers already sent");
106
- return;
107
- }
108
- statusCode = val;
109
- },
110
- });
111
-
112
- // Make sure the writer is eventually closed
113
- ctx.waitUntil((res as any).hasStreamed.finally(() => resBodyWriter.close().catch(() => {})));
114
-
115
- return {
116
- res,
117
- req,
118
- webResponse: async () => {
119
- await res.headPromise;
120
- // TODO: remove this once streaming with compression is working nicely
121
- res.setHeader("content-encoding", "identity");
122
- return new Response(NON_BODY_RESPONSES.has(res.statusCode) ? null : readable, {
123
- status: res.statusCode,
124
- headers: (res as any).headers,
125
- });
126
- },
127
- };
128
- }
File without changes