From 3767f32ed548aa839a0adf3c9c5237409c654b19 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Mon, 12 Aug 2024 10:45:35 +0900 Subject: [PATCH 1/2] feat(dev-server): support `cf` property in Cloudflare adapter --- packages/dev-server/e2e/e2e.test.ts | 6 ++++++ packages/dev-server/e2e/mock/worker.ts | 7 +++++++ packages/dev-server/src/adapter/cloudflare.ts | 9 +++++++++ 3 files changed, 22 insertions(+) diff --git a/packages/dev-server/e2e/e2e.test.ts b/packages/dev-server/e2e/e2e.test.ts index cfe3659..59d36bd 100644 --- a/packages/dev-server/e2e/e2e.test.ts +++ b/packages/dev-server/e2e/e2e.test.ts @@ -95,3 +95,9 @@ test('Should not throw an error if accessing the `caches`', async ({ page }) => // It does **not** return cached content. expect(await resCached?.text()).not.toBe('cached') }) + +test('Should set `cf` properties', async ({ page }) => { + const res = await page.goto('/cf') + expect(res?.ok()).toBe(true) + expect(await res?.json()).toEqual({ cf: true }) +}) diff --git a/packages/dev-server/e2e/mock/worker.ts b/packages/dev-server/e2e/mock/worker.ts index 5158269..56044cc 100644 --- a/packages/dev-server/e2e/mock/worker.ts +++ b/packages/dev-server/e2e/mock/worker.ts @@ -92,4 +92,11 @@ app.get('/cache', async (c) => { return c.text('first') }) +app.get('/cf', (c) => { + return c.json({ + // @ts-expect-error `Request.cf` is not typed + cf: typeof c.req.raw.cf === 'object' ? true : false, + }) +}) + export default app diff --git a/packages/dev-server/src/adapter/cloudflare.ts b/packages/dev-server/src/adapter/cloudflare.ts index 6a4892f..0e5872f 100644 --- a/packages/dev-server/src/adapter/cloudflare.ts +++ b/packages/dev-server/src/adapter/cloudflare.ts @@ -16,6 +16,7 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise< proxy ??= await getPlatformProxy(options?.proxy) // Cache API provided by `getPlatformProxy` currently do nothing. Object.assign(globalThis, { caches: proxy.caches }) + if (typeof globalThis.navigator === 'undefined') { // @ts-expect-error not typed well globalThis.navigator = { @@ -28,6 +29,14 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise< }) } + Object.defineProperty(Request.prototype, 'cf', { + get: function () { + return proxy.cf + }, + configurable: true, + enumerable: true, + }) + return { env: proxy.env, executionContext: proxy.ctx, From 0433b438c119ed940483c73ad86d3fd69dff4092 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Mon, 12 Aug 2024 10:47:28 +0900 Subject: [PATCH 2/2] add changeset --- .changeset/thin-spies-watch.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/thin-spies-watch.md diff --git a/.changeset/thin-spies-watch.md b/.changeset/thin-spies-watch.md new file mode 100644 index 0000000..acfca0b --- /dev/null +++ b/.changeset/thin-spies-watch.md @@ -0,0 +1,5 @@ +--- +'@hono/vite-dev-server': minor +--- + +feat: support `cf` property in Cloudflare adapter