aa20dbe73e
2,248 lines of gateway REST client become twelve modules by domain, with hermes.ts left as a barrel so all 144 importers stay put. The import graph is a star — every domain module imports only ./client, and client imports nothing back — so there are no cycles. The barrel names client's public exports rather than re-exporting it wholesale. Splitting a module forces its private helpers into exports so siblings can reach them, and export * would then republish them: profileScoped, connectionScoped and capabilityScoped were private to hermes.ts and have to stay that way, or a call site can assemble its own request scope and drift from the api layer.
129 lines
4.8 KiB
TypeScript
129 lines
4.8 KiB
TypeScript
import type { HermesConnection } from '@/global'
|
|
import { reconnectBackoffDelayMs } from '@/lib/reconnect-backoff'
|
|
|
|
import { getApiRequestConnection, getApiRequestProfile, hermesApi, profileScoped } from './client'
|
|
|
|
/** Resolve the ACTIVE backend's connection descriptor, (connectionId,
|
|
* profile)-scoped — mirroring how store/profile resolves $connection: a
|
|
* registry agent's descriptor comes from getConnectionFor (its SOURCE
|
|
* connection), everything else from the profile-keyed local pool. The
|
|
* getConnectionFor bridge is optional (older Desktop mains); without it the
|
|
* profile-scoped pool lookup is the best available answer. */
|
|
async function activeConnection(): Promise<HermesConnection> {
|
|
const getConnectionFor = window.hermesDesktop.getConnectionFor
|
|
const connectionId = getApiRequestConnection()
|
|
|
|
if (connectionId && getConnectionFor) {
|
|
return getConnectionFor({ connectionId, profile: getApiRequestProfile() })
|
|
}
|
|
|
|
return window.hermesDesktop.getConnection(getApiRequestProfile())
|
|
}
|
|
|
|
/** Options for a plugin REST call — mirrors the app's own `hermesDesktop.api`
|
|
* shape, minus the path (which is namespace-derived). */
|
|
export interface PluginRestOptions {
|
|
method?: string
|
|
body?: unknown
|
|
/** Single-file multipart upload (see HermesApiRequest.upload). */
|
|
upload?: { filename: string; contentType?: string; bytes: ArrayBuffer }
|
|
timeoutMs?: number
|
|
}
|
|
|
|
// Normalize `path` to a leading-slash suffix relative to `/api/plugins/<id>`.
|
|
// The namespace is the boundary — reject `..` so a relative segment can't
|
|
// normalize out into another plugin's API or a core route. Check the path
|
|
// portion only (before any query/hash).
|
|
function pluginPathSuffix(caller: string, path: string): string {
|
|
const suffix = path.startsWith('/') ? path : `/${path}`
|
|
|
|
if (suffix.split(/[?#]/, 1)[0].split('/').includes('..')) {
|
|
throw new Error(`${caller}: illegal path traversal in "${path}"`)
|
|
}
|
|
|
|
return suffix
|
|
}
|
|
|
|
/** The plugin REST door. Every call is scoped BY CONSTRUCTION to the plugin's
|
|
* own backend namespace — `path` is relative to `/api/plugins/<pluginId>`
|
|
* ('/board' → `/api/plugins/kanban/board`), so a plugin can't address another
|
|
* plugin's API or a core route through it. Profile-aware like every desktop
|
|
* REST call. Broader reach (core endpoints, another namespace) is the future
|
|
* declared-capability seam; today the namespace IS the boundary. */
|
|
export async function pluginRest<T>(pluginId: string, path: string, opts: PluginRestOptions = {}): Promise<T> {
|
|
if (!window.hermesDesktop?.api) {
|
|
throw new Error('Hermes desktop bridge unavailable')
|
|
}
|
|
|
|
const suffix = pluginPathSuffix('pluginRest', path)
|
|
|
|
return hermesApi<T>({
|
|
path: `/api/plugins/${pluginId}${suffix}`,
|
|
method: opts.method,
|
|
body: opts.body,
|
|
upload: opts.upload,
|
|
timeoutMs: opts.timeoutMs,
|
|
...profileScoped()
|
|
})
|
|
}
|
|
|
|
/** The plugin WebSocket door — the live twin of `pluginRest`, scoped the same
|
|
* way: `path` is relative to `/api/plugins/<pluginId>` ('/events' → the
|
|
* plugin's own event stream). Token-mode backends auth via the same query
|
|
* credential the app's own sockets use; OAuth remotes resolve null (callers
|
|
* keep their polling fallback — every consumer must have one anyway, since a
|
|
* socket can drop). Auto-reconnects with backoff until disposed. */
|
|
export function pluginSocket(pluginId: string, path: string, onMessage: (data: unknown) => void): () => void {
|
|
const suffix = pluginPathSuffix('pluginSocket', path)
|
|
|
|
let socket: null | WebSocket = null
|
|
let disposed = false
|
|
let attempt = 0
|
|
|
|
const connect = async () => {
|
|
const connection = await activeConnection().catch(() => null)
|
|
|
|
// No bridge / OAuth cookie auth (WS tickets are single-use, core-managed):
|
|
// stay on the polling fallback rather than half-working.
|
|
if (disposed || !connection || connection.authMode === 'oauth') {
|
|
return
|
|
}
|
|
|
|
const base = connection.baseUrl.replace(/^http/, 'ws')
|
|
const join = suffix.includes('?') ? '&' : '?'
|
|
socket = new WebSocket(
|
|
`${base}/api/plugins/${pluginId}${suffix}${join}token=${encodeURIComponent(connection.token)}`
|
|
)
|
|
|
|
socket.onmessage = event => {
|
|
attempt = 0
|
|
|
|
try {
|
|
onMessage(JSON.parse(String(event.data)))
|
|
} catch {
|
|
// Non-JSON frame — plugin streams are JSON by contract; skip it.
|
|
}
|
|
}
|
|
|
|
socket.onclose = () => {
|
|
socket = null
|
|
|
|
if (!disposed) {
|
|
// Full-jitter exponential backoff: same rationale as the gateway
|
|
// socket reconnect loops — an immediate-retry loop across many
|
|
// desktop clients floods the gateway with connection attempts
|
|
// during a restart.
|
|
window.setTimeout(() => void connect(), reconnectBackoffDelayMs(attempt, { baseDelayMs: 500, capMs: 30_000 }))
|
|
attempt += 1
|
|
}
|
|
}
|
|
}
|
|
|
|
void connect()
|
|
|
|
return () => {
|
|
disposed = true
|
|
socket?.close()
|
|
}
|
|
}
|