Skip to content

Commit 4eeac40

Browse files
authored
fix(devframe): let a devframe at base / fall through to the host app (#478)
1 parent 6aa3210 commit 4eeac40

5 files changed

Lines changed: 107 additions & 2 deletions

File tree

‎docs/content/1.guide/1.tutorial-server-data-inspector.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,12 +182,14 @@ export function App() {
182182
To try what we've built, let Vite serve the UI and hand RPC traffic to devframe:
183183

184184
```ts [app/vite.config.ts]
185+
import { fileURLToPath } from 'node:url'
185186
import { devframeViteBridge } from '@devframes/vite/single'
186187
import react from '@vitejs/plugin-react'
187188
import { defineConfig } from 'vite'
188189
import dataInspectorFrame from '../src/node/data-inspector.ts'
189190

190191
export default defineConfig({
192+
root: fileURLToPath(new URL('.', import.meta.url)), // serve app/, wherever you run vite from
191193
base: './', // relative asset URLs, so the built UI works under any mount path
192194
build: { outDir: '../dist/client', emptyOutDir: true },
193195
plugins: [

‎packages/devframe/src/adapters/__tests__/initiate.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,48 @@ describe('adapters/handler', () => {
236236
}
237237
})
238238

239+
it('nodeMiddleware at base `/` hands unmatched paths back to the host', async () => {
240+
const host = '127.0.0.1'
241+
const port = await getPort({ port: 18135, host })
242+
243+
let devtoolsRef!: ReturnType<typeof initDevframe>
244+
const server = createServer((req, res) => {
245+
devtoolsRef.nodeMiddleware(req, res, () => {
246+
res.statusCode = 200
247+
res.setHeader('content-type', 'text/html')
248+
res.end(`host app ${req.url}`)
249+
})
250+
})
251+
// No distDir: the host app owns the pages, the devframe only its routes.
252+
devtoolsRef = initDevframe(defineTestDef('handler-root'), { base: '/', auth: false, distDir: false, server })
253+
await new Promise<void>(resolve => server.listen(port, host, resolve))
254+
255+
try {
256+
await devtoolsRef.ready
257+
258+
// Every path sits inside base `/`, but the devframe has no route for
259+
// these, so next() ran and the host app answered.
260+
for (const path of ['/', '/main.tsx', '/nested/page?x=1']) {
261+
const res = await fetch(`http://${host}:${port}${path}`)
262+
expect(res.status).toBe(200)
263+
expect(await res.text()).toBe(`host app ${path}`)
264+
}
265+
266+
// The devframe's own routes still answer.
267+
const meta = await (await fetch(`http://${host}:${port}/__connection.json`)).json()
268+
expect(meta).toEqual({ backend: 'websocket', websocket: { path: '__ws' }, sse: { path: '__sse' } })
269+
270+
// Without a `next`, a miss is still the devframe's own 404.
271+
const bare = await devtoolsRef.handler(new Request(`http://${host}:${port}/main.tsx`))
272+
expect(bare.status).toBe(404)
273+
}
274+
finally {
275+
await devtoolsRef.close()
276+
server.close()
277+
server.closeAllConnections()
278+
}
279+
})
280+
239281
it('shared-server tier: a TLS host server advertises wss://', async () => {
240282
const host = '127.0.0.1'
241283
const server = createSecureServer({ allowHTTP1: true })

‎packages/devframe/src/adapters/initiate.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,9 @@ export interface DevframeInstance {
175175
* Connect/Express-style middleware over the same surface, for
176176
* `viteServer.middlewares.use(handler.nodeMiddleware)` or any other
177177
* node middleware stack. Mount it un-prefixed: paths outside the base
178-
* call `next()` so the rest of the stack keeps working.
178+
* call `next()` so the rest of the stack keeps working. At base `/`, a
179+
* path no devframe route answers calls `next()` too, so the host app
180+
* keeps its own pages.
179181
*/
180182
nodeMiddleware: (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void
181183
/**

‎packages/devframe/src/node/instance-shell.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import process from 'node:process'
1717
import { Server as TlsServer } from 'node:tls'
1818
import { validateOriginCandidate } from 'devframe/utils/origin'
1919
import { joinURL, withLeadingSlash, withoutLeadingSlash, withoutTrailingSlash } from 'devframe/utils/url'
20-
import { defineHandler, H3 as H3App, toNodeHandler } from 'h3'
20+
import { defineHandler, fromNodeHandler, H3 as H3App, toNodeHandler } from 'h3'
2121
import { DEVFRAME_SSE_ROUTE, DEVFRAME_WS_ROUTE } from '../constants'
2222
import { createInteractiveAuth } from '../recipes/interactive-auth'
2323
import { diagnostics } from './diagnostics'
@@ -663,6 +663,35 @@ export function createInstanceShell<TContext extends DevframeNodeContext>(
663663
maybeRegister()
664664
}
665665

666+
/**
667+
* The host stack's `next` for each in-flight `nodeMiddleware` request at
668+
* base `/`, read by the fall-through middleware mounted at the end of
669+
* `init()`.
670+
*/
671+
const hostFallthrough = new WeakMap<object, () => void>()
672+
673+
/**
674+
* A devframe at `/` shares the origin root with its host, so it can't claim
675+
* every path the way it owns a `/__<id>/` base. A `nodeMiddleware` request
676+
* that no route answers goes to the host's `next` instead of h3's 404, so
677+
* the host app (e.g. Vite with the bridge) keeps serving its own pages.
678+
*/
679+
function mountHostFallthrough(): void {
680+
if (base !== '/')
681+
return
682+
app.use((event, next) => {
683+
if (event.context.matchedRoute)
684+
return next()
685+
const nodeReq = event.runtime?.node?.req
686+
const hostNext = nodeReq && hostFallthrough.get(nodeReq)
687+
if (!hostNext)
688+
return next()
689+
hostFallthrough.delete(nodeReq)
690+
// Resolves once the host stack has sent its own response.
691+
return fromNodeHandler((_req, _res, _next) => hostNext())(event)
692+
})
693+
}
694+
666695
let started: StartedServer | undefined
667696
let transport: WsRpcTransport | undefined
668697
let dispose: (() => Promise<void>) | undefined
@@ -894,6 +923,9 @@ export function createInstanceShell<TContext extends DevframeNodeContext>(
894923

895924
await options.mount?.(ctx, meta, api)
896925

926+
// Last in the chain, after every route the instance mounts.
927+
mountHostFallthrough()
928+
897929
// A pinned origin means the registry record needn't wait for a first
898930
// request.
899931
maybeRegister()
@@ -970,6 +1002,8 @@ export function createInstanceShell<TContext extends DevframeNodeContext>(
9701002
const { toNodeHandler } = await import('h3/node')
9711003
nodeHandler = toNodeHandler(app)
9721004
}
1005+
if (next && base === '/')
1006+
hostFallthrough.set(req, () => next())
9731007
return nodeHandler(req, res)
9741008
})
9751009
.catch((err: unknown) => {

‎packages/vite/test/single.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,31 @@ describe('devframeViteBridge (bridge mode mcp)', () => {
198198
rpc.$close?.()
199199
}
200200
})
201+
202+
it('at base `/`, leaves the host app\'s own pages to Vite', async () => {
203+
const host = '127.0.0.1'
204+
const vitePort = await getPort({ port: 19717, host })
205+
bridge = devframeViteBridge(defineTestDef(), { host, base: '/', auth: false })
206+
207+
vite = fakeViteServer()
208+
await vite.listen(vitePort, host)
209+
await bridge.configureServer(vite)
210+
// Vite's own middlewares (transform, static, index.html) run after a
211+
// plugin's `configureServer` middlewares.
212+
vite.middlewares.use((req, res) => {
213+
res.setHeader('content-type', 'text/html')
214+
res.end(`vite ${req.url}`)
215+
})
216+
217+
for (const path of ['/', '/main.tsx']) {
218+
const res = await fetch(`http://${host}:${vitePort}${path}`)
219+
expect(res.status).toBe(200)
220+
expect(await res.text()).toBe(`vite ${path}`)
221+
}
222+
223+
const meta = await (await fetch(`http://${host}:${vitePort}/__connection.json`)).json()
224+
expect(meta.websocket).toEqual({ path: '__ws' })
225+
})
201226
})
202227

203228
describe('devframeViteBridge (auth default)', () => {

0 commit comments

Comments
 (0)