feat(mount): introduce Mount Middleware and deprecate `app.mount` (#5221)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(mount)!: introduce Mount Middleware and obsolete `app.mount` * mark `app.mount()` deprecated * format * refactored
authored by Yusuke Wada · committed by GitHub · parent f23b146 · Browse files · 5 files·+454 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+454 added−0 removed
- tests:+334 added−0 removed
- other:+120 added−0 removed
Provenance
- Commit
ae595de- Tree
517453f- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
f23b146
5 files changed+454 added−0 removed
added:src/middleware/mount/index.test.ts+334 added
1+import { mount } from '.'2+/* eslint-disable @typescript-eslint/ban-ts-comment */3+import type { ExecutionContext } from '../../context'4+import { Hono } from '../../hono'5+import { getPath } from '../../utils/url'6+7+describe('mount()', () => {8+ describe('Basic', () => {9+ const anotherApp = (req: Request, ...params: unknown[]) => {10+ const path = getPath(req)11+ if (path === '/') {12+ return new Response('AnotherApp')13+ }14+ if (path === '/hello') {15+ return new Response('Hello from AnotherApp')16+ }17+ if (path === '/header') {18+ const message = req.headers.get('x-message')19+ return new Response(message)20+ }21+ if (path === '/with-query') {22+ const queryStrings = new URL(req.url).searchParams.toString()23+ return new Response(queryStrings)24+ }25+ if (path == '/with-params') {26+ return new Response(27+ JSON.stringify({28+ params,29+ }),30+ {31+ headers: {32+ 'Content-Type': 'application.json',33+ },34+ }35+ )36+ }37+ if (path === '/undefined') {38+ return undefined as unknown as Response39+ }40+ return new Response('Not Found from AnotherApp', {41+ status: 404,42+ })43+ }44+45+ const app = new Hono()46+ app.use('*', async (c, next) => {47+ await next()48+ c.header('x-message', 'Foo')49+ })50+ app.get('/', (c) => c.text('Hono'))51+ app.notFound((c) => {52+ return c.text('Not Found from App', 404)53+ })54+55+ app.all(56+ '/another-app/*',57+ mount(anotherApp, () => {58+ return 'params'59+ })60+ )61+ app.all(62+ '/another-app-with-array-option/*',63+ mount(anotherApp, () => {64+ return ['param1', 'param2']65+ })66+ )67+ app.all('/another-app2/sub-slash/*', mount(anotherApp))68+69+ const api = new Hono().basePath('/api')70+ api.all('/another-app/*', mount(anotherApp))71+72+ it('Should return responses from Hono app', async () => {73+ const res = await app.request('/')74+ expect(res.status).toBe(200)75+ expect(res.headers.get('x-message')).toBe('Foo')76+ expect(await res.text()).toBe('Hono')77+ })78+79+ it('Should return responses from AnotherApp', async () => {80+ let res = await app.request('/another-app')81+ expect(res.status).toBe(200)82+ expect(res.headers.get('x-message')).toBe('Foo')83+ expect(await res.text()).toBe('AnotherApp')84+85+ res = await app.request('/another-app/hello')86+ expect(res.status).toBe(200)87+ expect(res.headers.get('x-message')).toBe('Foo')88+ expect(await res.text()).toBe('Hello from AnotherApp')89+90+ const req = new Request('http://localhost/another-app/header', {91+ headers: {92+ 'x-message': 'Message Foo!',93+ },94+ })95+ res = await app.request(req)96+ expect(res.status).toBe(200)97+ expect(res.headers.get('x-message')).toBe('Foo')98+ expect(await res.text()).toBe('Message Foo!')99+100+ res = await app.request('/another-app/not-found')101+ expect(res.status).toBe(404)102+ expect(res.headers.get('x-message')).toBe('Foo')103+ expect(await res.text()).toBe('Not Found from AnotherApp')104+105+ res = await app.request('/another-app/with-query?foo=bar&baz=qux')106+ expect(res.status).toBe(200)107+ expect(await res.text()).toBe('foo=bar&baz=qux')108+109+ res = await app.request('/another-app/with-params')110+ expect(res.status).toBe(200)111+ expect(await res.json()).toEqual({112+ params: ['params'],113+ })114+115+ res = await app.request('/another-app/undefined')116+ expect(res.status).toBe(404)117+ expect(await res.text()).toBe('Not Found from App')118+ })119+120+ it('Should return response from Another app with an array option', async () => {121+ const res = await app.request('/another-app-with-array-option/with-params')122+ expect(res.status).toBe(200)123+ expect(await res.json()).toEqual({124+ params: ['param1', 'param2'],125+ })126+ })127+128+ it('Should return responses from AnotherApp - sub + slash', async () => {129+ const res = await app.request('/another-app2/sub-slash')130+ expect(res.status).toBe(200)131+ expect(await res.text()).toBe('AnotherApp')132+ })133+134+ it('Should return responses from AnotherApp - with `basePath()`', async () => {135+ const res = await api.request('/api/another-app')136+ expect(res.status).toBe(200)137+ expect(await res.text()).toBe('AnotherApp')138+ })139+ })140+141+ describe('With encoded paths', () => {142+ const anotherApp = (req: Request) => new Response(getPath(req))143+144+ it('Should strip a decoded non-ASCII mount prefix', async () => {145+ const app = new Hono()146+ app.all('/api/é/*', mount(anotherApp))147+148+ const res = await app.request('/api/%C3%A9/hello')149+150+ expect(res.status).toBe(200)151+ expect(await res.text()).toBe('/hello')152+ })153+154+ it('Should preserve an encoded slash as a literal path segment after stripping the prefix', async () => {155+ const app = new Hono()156+ app.all('/api/v1/*', mount(anotherApp))157+158+ const res = await app.request('/api/v1/admin%2Fsecret')159+160+ expect(res.status).toBe(200)161+ expect(await res.text()).toBe('/admin%2Fsecret')162+ })163+164+ it('Should preserve encoded percent characters after stripping the prefix', async () => {165+ const app = new Hono()166+ app.all('/api/*', mount(anotherApp))167+168+ const res = await app.request('/api/foo%252Fbar')169+170+ expect(res.status).toBe(200)171+ expect(await res.text()).toBe('/foo%252Fbar')172+ })173+ })174+175+ describe('With fetch', () => {176+ const anotherApp = async (req: Request, env: {}, executionContext: ExecutionContext) => {177+ const path = getPath(req)178+ if (path === '/') {179+ return new Response(180+ JSON.stringify({181+ env,182+ executionContext,183+ }),184+ {185+ headers: {186+ 'Content-Type': 'application/json',187+ },188+ }189+ )190+ }191+ return new Response('Not Found from AnotherApp', {192+ status: 404,193+ })194+ }195+196+ const app = new Hono()197+ app.all('/another-app/*', mount(anotherApp))198+199+ it('Should handle Env and ExecuteContext', async () => {200+ const request = new Request('http://localhost/another-app')201+ const res = await app.fetch(202+ request,203+ {204+ TOKEN: 'foo',205+ },206+ {207+ // Force mocking!208+209+ // @ts-ignore210+ waitUntil: 'waitUntil',211+212+ // @ts-ignore213+ passThroughOnException: 'passThroughOnException',214+ }215+ )216+ expect(res.status).toBe(200)217+ expect(await res.json()).toEqual({218+ env: {219+ TOKEN: 'foo',220+ },221+ executionContext: {222+ waitUntil: 'waitUntil',223+ passThroughOnException: 'passThroughOnException',224+ },225+ })226+ })227+ })228+229+ describe('Mount on `/`', () => {230+ const anotherApp = (req: Request, _params: unknown) => {231+ const path = getPath(req)232+ if (path === '/') {233+ return new Response('AnotherApp')234+ }235+ if (path === '/hello') {236+ return new Response('Hello from AnotherApp')237+ }238+ if (path === '/good/night') {239+ return new Response('Good Night from AnotherApp')240+ }241+ return new Response('Not Found from AnotherApp', {242+ status: 404,243+ })244+ }245+246+ const app = new Hono()247+ app.all('/*', mount(anotherApp))248+249+ it('Should return responses from AnotherApp - mount on `/`', async () => {250+ let res = await app.request('/')251+ expect(res.status).toBe(200)252+ expect(await res.text()).toBe('AnotherApp')253+ res = await app.request('/hello')254+ expect(res.status).toBe(200)255+ expect(await res.text()).toBe('Hello from AnotherApp')256+ res = await app.request('/good/night')257+ expect(res.status).toBe(200)258+ expect(await res.text()).toBe('Good Night from AnotherApp')259+ res = await app.request('/not-found')260+ expect(res.status).toBe(404)261+ expect(await res.text()).toBe('Not Found from AnotherApp')262+ })263+ })264+265+ describe('With replaceRequest option', () => {266+ const anotherApp = (req: Request) => {267+ const path = getPath(req)268+ if (path === '/app') {269+ return new Response(getPath(req))270+ }271+ return new Response(null, { status: 404 })272+ }273+274+ const app = new Hono()275+ app.all(276+ '/app/*',277+ mount(anotherApp, {278+ replaceRequest: (req) => req,279+ })280+ )281+282+ it('Should return 200 response with the correct path', async () => {283+ const res = await app.request('/app')284+ expect(res.status).toBe(200)285+ expect(await res.text()).toBe('/app')286+ })287+ })288+289+ describe('With replaceRequest: false', () => {290+ const anotherApp = (req: Request) => {291+ const path = getPath(req)292+ if (path === '/app') {293+ return new Response(getPath(req))294+ }295+ return new Response(null, { status: 404 })296+ }297+298+ const app = new Hono()299+ app.all('/app/*', mount(anotherApp, { replaceRequest: false }))300+301+ it('Should return 200 response with the correct path', async () => {302+ const res = await app.request('/app')303+ expect(res.status).toBe(200)304+ expect(await res.text()).toBe('/app')305+ })306+ })307+308+ describe('Used as `app.use()` middleware', () => {309+ const anotherApp = (req: Request) => {310+ const path = getPath(req)311+ if (path === '/hello') {312+ return new Response('Hello from AnotherApp')313+ }314+ // Fall through to the Hono app315+ return undefined as unknown as Response316+ }317+318+ const app = new Hono()319+ app.use('/another-app/*', mount(anotherApp))320+ app.get('/another-app/fallback', (c) => c.text('Fallback from App'))321+322+ it('Should return responses from AnotherApp', async () => {323+ const res = await app.request('/another-app/hello')324+ expect(res.status).toBe(200)325+ expect(await res.text()).toBe('Hello from AnotherApp')326+ })327+328+ it('Should fall through to the Hono app if AnotherApp returns nothing', async () => {329+ const res = await app.request('/another-app/fallback')330+ expect(res.status).toBe(200)331+ expect(await res.text()).toBe('Fallback from App')332+ })333+ })334+})added:src/middleware/mount/index.ts+109 added
1+/**2+ * @module3+ * Mount Helper for Hono.4+ */5+6+import type { Context, ExecutionContext } from '../../context'7+import { routePath } from '../../helper/route'8+import type { MiddlewareHandler } from '../../types'9+10+// eslint-disable-next-line @typescript-eslint/no-explicit-any11+type ApplicationHandler = (request: Request, ...args: any) => Response | Promise<Response>12+type MountOptionHandler = (c: Context) => unknown13+type MountReplaceRequest = (originalRequest: Request) => Request14+type MountOptions =15+ | MountOptionHandler16+ | {17+ optionHandler?: MountOptionHandler18+ replaceRequest?: MountReplaceRequest | false19+ }20+21+const defaultReplaceRequest = (c: Context): Request => {22+ // e.g. `/another-app/*` (basePath is already merged) -> `/another-app`23+ const pathPrefix = routePath(c).replace(/\/\*$/, '')24+ const url = new URL(c.req.raw.url)25+ url.pathname = c.req.path.slice(pathPrefix.length) || '/'26+ return new Request(url, c.req.raw)27+}28+29+const defaultGetOptions = (c: Context): unknown[] => {30+ let executionContext: ExecutionContext | undefined = undefined31+ try {32+ executionContext = c.executionCtx33+ } catch {} // Do nothing34+ return [c.env, executionContext]35+}36+37+/**38+ * `mount()` allows you to mount applications built with other frameworks into your Hono application.39+ *40+ * @see {@link https://hono.dev/docs/api/hono#mount}41+ *42+ * @param {Function} applicationHandler - other Request Handler43+ * @param {MountOptions} [options] - options of `mount()`44+ * @returns {MiddlewareHandler} handler to register with `app.all()`45+ *46+ * @example47+ * ```ts48+ * import { Router as IttyRouter } from 'itty-router'49+ * import { Hono } from 'hono'50+ * import { mount } from 'hono/mount'51+ * // Create itty-router application52+ * const ittyRouter = IttyRouter()53+ * // GET /itty-router/hello54+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))55+ *56+ * const app = new Hono()57+ * app.all('/itty-router/*', mount(ittyRouter.handle))58+ * ```59+ *60+ * @example61+ * ```ts62+ * const app = new Hono()63+ * // Send the request to another application without modification.64+ * app.all('/app/*', mount(anotherApp, {65+ * replaceRequest: (req) => req,66+ * }))67+ * ```68+ */69+export const mount = (70+ applicationHandler: ApplicationHandler,71+ options?: MountOptions72+): MiddlewareHandler => {73+ // handle options74+ let replaceRequest: MountReplaceRequest | undefined75+ let optionHandler: MountOptionHandler | undefined76+ if (options) {77+ if (typeof options === 'function') {78+ optionHandler = options79+ } else {80+ optionHandler = options.optionHandler81+ if (options.replaceRequest === false) {82+ replaceRequest = (request) => request83+ } else {84+ replaceRequest = options.replaceRequest85+ }86+ }87+ }88+89+ // prepare handlers for request90+ const getOptions: (c: Context) => unknown[] = optionHandler91+ ? (c) => {92+ const options = optionHandler!(c)93+ return Array.isArray(options) ? options : [options]94+ }95+ : defaultGetOptions96+97+ return async (c, next) => {98+ const request = replaceRequest ? replaceRequest(c.req.raw) : defaultReplaceRequest(c)99+ const res = await applicationHandler(request, ...getOptions(c))100+101+ if (res) {102+ return res103+ }104+105+ await next()106+ }107+}108+109+export type { ApplicationHandler, MountOptionHandler, MountReplaceRequest, MountOptions }modified:src/hono-base.ts+2 added
297 unmodified lines298 299 /**300 * `.mount()` allows you to mount applications built with other frameworks into your Hono application.301 *302+ * @deprecated Use `mount()` from `hono/mount` instead. `.mount()` will be removed in v5.303+ *304 * @see {@link https://hono.dev/docs/api/hono#mount}305 *306 * @param {string} path - base Path307 * @param {Function} applicationHandler - other Request Handler242 unmodified linesmodified:jsr.json+1 added
17 unmodified lines18192021222324252687 unmodified lines17 unmodified lines "./body-limit": "./src/middleware/body-limit/index.ts", "./ip-restriction": "./src/middleware/ip-restriction/index.ts", "./cache": "./src/middleware/cache/index.ts", "./route": "./src/helper/route/index.ts", "./mount": "./src/middleware/mount/index.ts", "./cookie": "./src/helper/cookie/index.ts", "./accepts": "./src/helper/accepts/index.ts", "./compress": "./src/middleware/compress/index.ts", "./context-storage": "./src/middleware/context-storage/index.ts",87 unmodified linesmodified:package.json+8 added
101 unmodified lines102 "types": "./dist/types/helper/route/index.d.ts",103 "import": "./dist/helper/route/index.js",104 "require": "./dist/cjs/helper/route/index.js"105 },106+ "./mount": {107+ "types": "./dist/types/middleware/mount/index.d.ts",108+ "import": "./dist/middleware/mount/index.js",109+ "require": "./dist/cjs/middleware/mount/index.js"110+ },111 "./cookie": {112 "types": "./dist/types/helper/cookie/index.d.ts",113 "import": "./dist/helper/cookie/index.js",114 "require": "./dist/cjs/helper/cookie/index.js"346 unmodified lines461 ],462 "route": [463 "./dist/types/helper/route"464 ],465+ "mount": [466+ "./dist/types/middleware/mount"467+ ],468 "cookie": [469 "./dist/types/helper/cookie"470 ],471 "accepts": [243 unmodified lines