|
| 1 | +/** |
| 2 | + * Initialization for the workerd runtime. |
| 3 | + * |
| 4 | + * The file must be imported at the top level the worker. |
| 5 | + */ |
| 6 | + |
| 7 | +import { AsyncLocalStorage } from "node:async_hooks"; |
| 8 | +import process from "node:process"; |
| 9 | +import stream from "node:stream"; |
| 10 | + |
| 11 | +// @ts-expect-error: resolved by wrangler build |
| 12 | +import * as nextEnvVars from "./next-env.mjs"; |
| 13 | + |
| 14 | +const cloudflareContextALS = new AsyncLocalStorage(); |
| 15 | + |
| 16 | +// Note: this symbol needs to be kept in sync with `src/api/get-cloudflare-context.ts` |
| 17 | +Object.defineProperty(globalThis, Symbol.for("__cloudflare-context__"), { |
| 18 | + get() { |
| 19 | + return cloudflareContextALS.getStore(); |
| 20 | + }, |
| 21 | +}); |
| 22 | + |
| 23 | +/** |
| 24 | + * Executes the handler with the Cloudflare context. |
| 25 | + */ |
| 26 | +export async function runWithCloudflareRequestContext( |
| 27 | + request: Request, |
| 28 | + env: CloudflareEnv, |
| 29 | + ctx: ExecutionContext, |
| 30 | + handler: () => Promise<Response> |
| 31 | +): Promise<Response> { |
| 32 | + init(request, env); |
| 33 | + |
| 34 | + return cloudflareContextALS.run({ env, ctx, cf: request.cf }, handler); |
| 35 | +} |
| 36 | + |
| 37 | +let initialized = false; |
| 38 | + |
| 39 | +/** |
| 40 | + * Initializes the runtime on the first call, |
| 41 | + * no-op on subsequent invocations. |
| 42 | + */ |
| 43 | +function init(request: Request, env: CloudflareEnv) { |
| 44 | + if (initialized) { |
| 45 | + return; |
| 46 | + } |
| 47 | + initialized = true; |
| 48 | + |
| 49 | + const url = new URL(request.url); |
| 50 | + |
| 51 | + initRuntime(); |
| 52 | + populateProcessEnv(url, env); |
| 53 | +} |
| 54 | + |
| 55 | +function initRuntime() { |
| 56 | + // Some packages rely on `process.version` and `process.versions.node` (i.e. Jose@4) |
| 57 | + // TODO: Remove when https://github.com/unjs/unenv/pull/493 is merged |
| 58 | + Object.assign(process, { version: process.version || "v22.14.0" }); |
| 59 | + // @ts-expect-error Node type does not match workerd |
| 60 | + Object.assign(process.versions, { node: "22.14.0", ...process.versions }); |
| 61 | + |
| 62 | + globalThis.__dirname ??= ""; |
| 63 | + globalThis.__filename ??= ""; |
| 64 | + |
| 65 | + // Do not crash on cache not supported |
| 66 | + // https://github.com/cloudflare/workerd/pull/2434 |
| 67 | + // compatibility flag "cache_option_enabled" -> does not support "force-cache" |
| 68 | + const __original_fetch = globalThis.fetch; |
| 69 | + |
| 70 | + globalThis.fetch = (input, init) => { |
| 71 | + if (init) { |
| 72 | + delete (init as { cache: unknown }).cache; |
| 73 | + } |
| 74 | + return __original_fetch(input, init); |
| 75 | + }; |
| 76 | + |
| 77 | + const CustomRequest = class extends globalThis.Request { |
| 78 | + constructor(input: RequestInfo | URL, init?: RequestInit) { |
| 79 | + if (init) { |
| 80 | + delete (init as { cache: unknown }).cache; |
| 81 | + // https://github.com/cloudflare/workerd/issues/2746 |
| 82 | + // https://github.com/cloudflare/workerd/issues/3245 |
| 83 | + Object.defineProperty(init, "body", { |
| 84 | + // @ts-ignore |
| 85 | + value: init.body instanceof stream.Readable ? ReadableStream.from(init.body) : init.body, |
| 86 | + }); |
| 87 | + } |
| 88 | + super(input, init); |
| 89 | + } |
| 90 | + }; |
| 91 | + |
| 92 | + Object.assign(globalThis, { |
| 93 | + Request: CustomRequest, |
| 94 | + //@ts-expect-error Inline at build time by ESBuild |
| 95 | + __BUILD_TIMESTAMP_MS__: __BUILD_TIMESTAMP_MS__, |
| 96 | + }); |
| 97 | +} |
| 98 | + |
| 99 | +/** |
| 100 | + * Populate process.env with: |
| 101 | + * - the environment variables and secrets from the cloudflare platform |
| 102 | + * - the variables from Next .env* files |
| 103 | + * - the origin resolver information |
| 104 | + */ |
| 105 | +function populateProcessEnv(url: URL, env: CloudflareEnv) { |
| 106 | + for (const [key, value] of Object.entries(env)) { |
| 107 | + if (typeof value === "string") { |
| 108 | + process.env[key] = value; |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + const mode = env.NEXTJS_ENV ?? "production"; |
| 113 | + if (nextEnvVars[mode]) { |
| 114 | + for (const key in nextEnvVars[mode]) { |
| 115 | + process.env[key] ??= nextEnvVars[mode][key]; |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + // Set the default Origin for the origin resolver. |
| 120 | + // This is only needed for an external middleware bundle |
| 121 | + process.env.OPEN_NEXT_ORIGIN = JSON.stringify({ |
| 122 | + default: { |
| 123 | + host: url.hostname, |
| 124 | + protocol: url.protocol.slice(0, -1), |
| 125 | + port: url.port, |
| 126 | + }, |
| 127 | + }); |
| 128 | +} |
0 commit comments