Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/devframe/src/node/hub-internals/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,23 @@ export interface DevframeInternalContext {
/** Full `ws://` or `wss://` URL with host and port. */
url: string
}

/**
* Set {@link DevframeInternalContext.wsEndpoint} and notify subscribers —
* the WS-binding tiers (side-car, shared-server, and the `unbound` tier's
* `attach()`) call this once the socket is bound (or `undefined` once torn
* down) instead of assigning the field directly, so anything that already
* projected the endpoint (a hub's remote-dock URLs, registered before an
* async bind resolves) gets a chance to re-project it.
*/
setWsEndpoint: (endpoint: { url: string } | undefined) => void
/**
* Subscribe to every {@link DevframeInternalContext.setWsEndpoint} call.
* Returns an unsubscribe function. The hub context uses this to refresh
* the `devframe:docks` shared state so a remote dock registered before the
* WS port resolves still ends up with a live connection URL.
*/
onWsEndpointChange: (cb: () => void) => () => void
}

export const internalContextMap = new WeakMap<DevframeNodeContext, DevframeInternalContext>()
Expand All @@ -66,6 +83,7 @@ export function getInternalContext(context: DevframeNodeContext): DevframeIntern
},
})
const remoteTokens = new Map<string, RemoteTokenRecord>()
const wsEndpointListeners = new Set<() => void>()

function revokeRemoteToken(token: string): void {
if (!remoteTokens.delete(token))
Expand All @@ -78,6 +96,14 @@ export function getInternalContext(context: DevframeNodeContext): DevframeIntern
auth: storage,
},
revokeAuthToken: (token: string) => revokeAuthToken(context, storage, token),
setWsEndpoint(endpoint) {
internalContext.wsEndpoint = endpoint
for (const listener of wsEndpointListeners) listener()
},
onWsEndpointChange(cb) {
wsEndpointListeners.add(cb)
return () => wsEndpointListeners.delete(cb)
},
remoteTokens,
allocateRemoteToken(dockId, origin, originLock) {
const token = randomToken()
Expand Down
8 changes: 4 additions & 4 deletions packages/devframe/src/node/instance-shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ async function bindHttpAndWs(options: BindHttpAndWsOptions): Promise<StartedServ
const internal = getInternalContext(context)
const wsUrl = `ws://${formatHostForUrl(bindHost)}:${resolvedPort}${options.path ?? ''}`
if (websocket)
internal.wsEndpoint = { url: wsUrl }
internal.setWsEndpoint({ url: wsUrl })

function connectionMeta(): ConnectionMeta {
const jsonSerializableMethods: string[] = []
Expand All @@ -154,7 +154,7 @@ async function bindHttpAndWs(options: BindHttpAndWsOptions): Promise<StartedServ
if (ownsHttpServer)
await new Promise<void>(r => httpServer.close(() => r()))
if (websocket && getInternalContext(context).wsEndpoint?.url === wsUrl)
getInternalContext(context).wsEndpoint = undefined
getInternalContext(context).setWsEndpoint(undefined)
},
}
}
Expand Down Expand Up @@ -701,9 +701,9 @@ export function createInstanceShell<TContext extends DevframeNodeContext>(
if (typeof address !== 'object' || !address)
return
const host = options.host ?? (address.address === '::' || address.address === '0.0.0.0' ? 'localhost' : address.address)
getInternalContext(ctx).wsEndpoint = {
getInternalContext(ctx).setWsEndpoint({
url: `ws://${formatHostForUrl(host)}:${address.port}${routePath}`,
}
})
}
if (server.listening)
record()
Expand Down
43 changes: 43 additions & 0 deletions packages/hub/src/node/__tests__/context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,49 @@ describe('createHubContext dock activation', () => {
})
})

describe('createHubContext remote dock republishing', () => {
it('re-projects a remote dock once the WS endpoint resolves after registration', async () => {
// Mirrors vitejs/devtools#517/#520: a remote iframe dock can register
// before an async WS bind (side-car port probing, an `unbound` tier
// waiting on the host's own `attach()`) resolves `wsEndpoint`. Nothing
// else re-registers that dock once the port is known, so the fix has to
// re-project every dock when the endpoint changes.
const context = await createHubContext({
cwd: process.cwd(),
mode: 'build',
host: createHost(),
})

context.docks.register({
type: 'iframe',
id: 'remote',
title: 'Remote',
icon: 'ph:cube-duotone',
url: 'https://remote.test/app',
remote: true,
})

// The registration's own refresh is debounced too — let it settle before
// asserting the pre-bind projection.
await new Promise(resolve => setTimeout(resolve, 20))

const docksState = await context.rpc.sharedState.get<DevframeDockEntry[]>('devframe:docks')
const beforeBind = docksState.value()[0]
expect(beforeBind?.type === 'iframe' ? beforeBind.url : undefined).toBe('https://remote.test/app')

getInternalContext(context).setWsEndpoint({ url: 'ws://localhost:4173' })
// The refresh is debounced (0ms in `mode: 'build'`, still a macrotask).
await new Promise(resolve => setTimeout(resolve, 20))

const afterBind = docksState.value()[0]
const afterUrl = afterBind?.type === 'iframe' ? afterBind.url : ''
expect(afterUrl).not.toBe('https://remote.test/app')
expect(afterUrl).toContain('https://remote.test/app')

getInternalContext(context).setWsEndpoint(undefined)
})
})

describe('served context remote endpoint metadata', () => {
it('sets and clears the internal websocket endpoint', async () => {
const context = await createHostContext({
Expand Down
8 changes: 8 additions & 0 deletions packages/hub/src/node/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { DevframeMessageEntry, DevframeMessageEntryInput, DevframeMessagesH
import type { DevframeTerminalsHost } from '../types/terminals'
import type { InstallDevframeOptions } from './install-devframe'
import { createHostContext } from 'devframe/node'
import { getInternalContext } from 'devframe/node/hub-internals'
import { debounce } from 'perfect-debounce'
import { DevframeCommandsHost as CommandsHostImpl } from './host-commands'
import { DevframeDocksHost as DocksHostImpl } from './host-docks'
Expand Down Expand Up @@ -155,6 +156,13 @@ export async function createHubContext(options: CreateHubContextOptions): Promis
docksSharedState.mutate(() => docks.values())
}, debounceMs)
docks.events.on('dock:entry:updated', refreshDocks)
// A remote iframe dock registered before the WS transport finishes binding
// (the common case: `initHub` installs devframes — and their docks — before
// resolving an async side-car/shared-server port) gets projected without a
// connection URL, since `wsEndpoint` isn't set yet. Nothing re-registers
// that dock once the port resolves, so re-project every dock once the
// endpoint becomes known (or is torn down) instead of leaving it stale.
getInternalContext(context).onWsEndpointChange(refreshDocks)
docksSharedState.mutate(() => docks.values())

// Cross-iframe dock activation. A dock activation is a discrete user intent
Expand Down
4 changes: 2 additions & 2 deletions tests/helpers/serve-test-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export async function serveTestContext(options: ServeTestContextOptions): Promis
// Publish the dialable socket URL on the context, mirroring the shell's own
// binding, so surfaces that hand out a complete endpoint work in tests too.
const wsUrl = `ws://${formatHostForUrl(bindHost)}:${resolvedPort}`
getInternalContext(context).wsEndpoint = { url: wsUrl }
getInternalContext(context).setWsEndpoint({ url: wsUrl })

function connectionMeta(): ConnectionMeta {
const jsonSerializableMethods: string[] = []
Expand All @@ -98,7 +98,7 @@ export async function serveTestContext(options: ServeTestContextOptions): Promis
await closeWs()
await new Promise<void>(r => httpServer.close(() => r()))
if (getInternalContext(context).wsEndpoint?.url === wsUrl)
getInternalContext(context).wsEndpoint = undefined
getInternalContext(context).setWsEndpoint(undefined)
},
}
}
Loading