Skip to content

Commit

Permalink
feat: implement static middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
cyco130 committed Aug 14, 2023
1 parent c5171a3 commit 7ba45c1
Show file tree
Hide file tree
Showing 45 changed files with 1,116 additions and 211 deletions.
8 changes: 4 additions & 4 deletions packages/adapter/adapter-cloudflare-workers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,6 @@ export default function cloudflareWorkersAdapter(
const context: AdapterRequestContext<CloudflareWorkersPlatformInfo> = {
request,
ip: request.headers.get("CF-Connecting-IP") || "127.0.0.1", // wrangler no longer sets this header
env(variable) {
const value = (env as any)[variable];
return typeof value === "string" ? value : undefined;
},
waitUntil: ctx.waitUntil.bind(ctx),
passThrough() {
// Do nothing
Expand All @@ -65,6 +61,10 @@ export default function cloudflareWorkersAdapter(
env,
context: ctx,
},
env(variable) {
const value = (env as any)[variable];
return typeof value === "string" ? value : undefined;
},
};

return handler(context);
Expand Down
11 changes: 7 additions & 4 deletions packages/adapter/adapter-cloudflare-workers/src/no-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ export default function cloudflareWorkersAdapter(
return async function fetchHandler(request, env, ctx) {
const context: AdapterRequestContext<CloudflareWorkersPlatformInfo> = {
request,
ip: request.headers.get("CF-Connecting-IP") || "",
ip: request.headers.get("CF-Connecting-IP") || "127.0.0.1",
waitUntil: ctx.waitUntil.bind(ctx),
passThrough() {
// TODO: Investigate if there is a way to make CFW pass through the
// request to the origin server.
// Do nothing
},
platform: {
name: "cloudflare-workers",
env,
context: ctx,
},
platform: { name: "cloudflare-workers", env, context: ctx },
env(variable) {
const value = (env as any)[variable];
return typeof value === "string" ? value : undefined;
Expand Down
3 changes: 2 additions & 1 deletion packages/adapter/adapter-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
},
"dependencies": {
"@hattip/core": "workspace:*",
"@hattip/polyfills": "workspace:*"
"@hattip/polyfills": "workspace:*",
"@hattip/walk": "workspace:*"
}
}
102 changes: 58 additions & 44 deletions packages/adapter/adapter-node/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ export interface DecoratedRequest extends Omit<IncomingMessage, "socket"> {
export type NodeMiddleware = (
req: DecoratedRequest,
res: ServerResponse,
next?: () => void,
next?: (err?: unknown) => void,
) => void;

/** Adapter options */
export interface NodeAdapterOptions extends NodeRequestAdapterOptions {
/**
* Whether to call the next middleware in the chain even if the request
* was handled. @default true
* was handled.@default true
*/
alwaysCallNext?: boolean;
}
Expand All @@ -59,48 +59,62 @@ export function createMiddleware(
const requestAdapter = createRequestAdapter(requestOptions);

return async (req, res, next) => {
const [request, ip] = requestAdapter(req);

let passThroughCalled = false;

const context: AdapterRequestContext<NodePlatformInfo> = {
request,

ip,

env(variable) {
return process.env[variable];
},

waitUntil(promise) {
// Do nothing
void promise;
},

passThrough() {
passThroughCalled = true;
},

platform: {
name: "node",
request: req,
response: res,
},
};

const response = await handler(context);

if (passThroughCalled && next) {
next();
return;
}

await sendResponse(response, res).catch((error) => {
console.error(error);
});

if (next && alwaysCallNext) {
next();
try {
const [request, ip] = requestAdapter(req);

let passThroughCalled = false;

const context: AdapterRequestContext<NodePlatformInfo> = {
request,

ip,

env(variable) {
return process.env[variable];
},

waitUntil(promise) {
// Do nothing
void promise;
},

passThrough() {
passThroughCalled = true;
},

platform: {
name: "node",
request: req,
response: res,
},
};

const response = await handler(context);

if (passThroughCalled && next) {
next();
return;
}

await sendResponse(response, res);

if (next && alwaysCallNext) {
next();
}
} catch (error) {
if (next) {
next(error);
} else {
console.error(error);

if (!res.headersSent) {
res.statusCode = 500;
}

if (!res.writableEnded) {
res.end();
}
}
}
};
}
Expand Down
1 change: 1 addition & 0 deletions packages/adapter/adapter-node/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export function createRequestAdapter(
}

let headers = req.headers as any;
// Filter out pseudo-headers
if (headers[":method"]) {
headers = Object.fromEntries(
Object.entries(headers).filter(([key]) => !key.startsWith(":")),
Expand Down
12 changes: 7 additions & 5 deletions packages/adapter/adapter-node/src/response.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { ServerResponse } from "node:http";
import { Readable, pipeline as pipelineCb } from "node:stream";
import { promisify } from "node:util";

const pipeline = promisify(pipelineCb);
import { Readable } from "node:stream";

// @ts-ignore
const deno = typeof Deno !== "undefined";
Expand Down Expand Up @@ -74,7 +71,12 @@ export async function sendResponse(
}

if (body) {
await pipeline(body, nodeResponse);
body.pipe(nodeResponse);
await new Promise((resolve, reject) => {
body!.on("error", reject);
nodeResponse.on("finish", resolve);
nodeResponse.on("error", reject);
});
} else {
nodeResponse.setHeader("content-length", "0");
nodeResponse.end();
Expand Down
4 changes: 2 additions & 2 deletions packages/bundler/bundler-cloudflare-workers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ export default async function bundle(
platform: "browser",
target: "chrome96",
format: "esm",
mainFields: ["module", "main", "browser"],
conditions: ["worker", "import", "require"],
mainFields: ["module", "main"],
conditions: ["workerd", "worker", "import", "require"],
external: [...builtinModules, "__STATIC_CONTENT_MANIFEST"],
};

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
"bin": {
"hattip-walk": "cli.js"
},
"exports": "./dist/index.js",
"exports": {
".": "./dist/index.js"
},
"typesVersions": {
"*": {
"*": [
Expand All @@ -33,7 +35,8 @@
},
"dependencies": {
"cac": "^6.7.14",
"mime-types": "^2.1.35"
"mime-types": "^2.1.35",
"@hattip/headers": "workspace:*"
},
"devDependencies": {
"@cyco130/eslint-config": "^3.3.0",
Expand Down
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 7ba45c1

Please sign in to comment.