-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathcloudflare-streaming.ts
72 lines (59 loc) · 2.27 KB
/
cloudflare-streaming.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { InternalEvent, InternalResult } from "types/open-next";
import type { Wrapper, WrapperHandler } from "types/overrides";
import { Writable } from "node:stream";
import type { StreamCreator } from "http/index";
const handler: WrapperHandler<InternalEvent, InternalResult> =
async (handler, converter) =>
async (
request: Request,
env: Record<string, string>,
ctx: any,
): Promise<Response> => {
globalThis.process = process;
globalThis.openNextWaitUntil = ctx.waitUntil.bind(ctx);
// Set the environment variables
// Cloudflare suggests to not override the process.env object but instead apply the values to it
for (const [key, value] of Object.entries(env)) {
if (typeof value === "string") {
process.env[key] = value;
}
}
const internalEvent = await converter.convertFrom(request);
// TODO:
// The edge converter populate event.url with the url including the origin.
// This is required for middleware to keep track of the protocol (i.e. http with wrangler dev).
// However the server expects that the origin is not included.
const url = new URL(internalEvent.url);
(internalEvent.url as string) = url.href.slice(url.origin.length);
const { promise: promiseResponse, resolve: resolveResponse } =
Promise.withResolvers<Response>();
const streamCreator: StreamCreator = {
writeHeaders(prelude: {
statusCode: number;
cookies: string[];
headers: Record<string, string>;
}): Writable {
const { statusCode, cookies, headers } = prelude;
const responseHeaders = new Headers(headers);
for (const cookie of cookies) {
responseHeaders.append("Set-Cookie", cookie);
}
const { readable, writable } = new TransformStream();
const response = new Response(readable, {
status: statusCode,
headers: responseHeaders,
});
resolveResponse(response);
return Writable.fromWeb(writable);
},
onWrite: () => {},
onFinish: (_length: number) => {},
};
ctx.waitUntil(handler(internalEvent, streamCreator));
return promiseResponse;
};
export default {
wrapper: handler,
name: "cloudflare-streaming",
supportStreaming: true,
} satisfies Wrapper;