Skip to content

Commit

Permalink
feat(dev-server): support cf property in Cloudflare adapter (#161)
Browse files Browse the repository at this point in the history
* feat(dev-server): support `cf` property in Cloudflare adapter

* add changeset
  • Loading branch information
yusukebe authored Aug 12, 2024
1 parent 5bd2120 commit 6cb1002
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/thin-spies-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/vite-dev-server': minor
---

feat: support `cf` property in Cloudflare adapter
6 changes: 6 additions & 0 deletions packages/dev-server/e2e/e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
})
7 changes: 7 additions & 0 deletions packages/dev-server/e2e/mock/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 9 additions & 0 deletions packages/dev-server/src/adapter/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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,
Expand Down

0 comments on commit 6cb1002

Please sign in to comment.