/** * vapor-chamber/router - router for Vue 3.6 over a server-owned catch-all. * * It follows the package peer range: the entry loads on Vue 3.5 * (tests/vue35-entries.test.ts), and only ./router/vapor needs 3.6. Rows come * from a server-side route generator emitting the RouteRecord schema (types.ts). * The server owns one catch-all (`/admin/{any?}` -> Blade shell -> one island); * this router owns every URL inside it. Path = navigation, query = state. * * Route table delivery: * routes: adminRoutes // generated TS module - primary * routes: { inline: '#vcr-routes' } // Blade-inlined, per-user filtered * routes: { url: '/api/vc/routes' } // admin tasks / router.reload() * * Data delivery: each row's `load` string is resolved by a loader PRESET (see * loaders.ts SPI) - `vapor-chamber/router-fetch` (in-box, plain JSON backends) * or your own LoaderHandlers for any other backend convention. * * `createRouter()` is pure - IO and listeners begin at start()/app.use(). */ import { type AnnounceOption, installRouteAnnouncer } from './announce'; import { DEV } from '../dev'; import { _report } from '../report'; // TYPE-ONLY. The client is never built here - it arrives via `options.http`, // or not at all. See the comment at `http` in createRouter below. import type { HttpClient } from '../http'; import { computed, getCurrentScope, onScopeDispose, shallowRef } from 'vue'; import { installDomIntegration, preheatIdle, stampActiveLinks } from './dom'; import { createEngine } from './engine'; import { HARD_NAV_CODES, isRouterError, routerError } from './errors'; import { type RouterHistory, canUseWebHistory, createMemoryHistory, createWebHistory, normalizeBase, stripBase, } from './history'; import { ROUTER_KEY } from './keys'; import { type LoaderHandlers, _routerClients, defaultAffects, runLoaders } from './loaders'; import type { Router } from './router-type'; import { type RouteTable, createRouteTable } from './table'; import type { ComponentMap, QueryParamDef, QueryPatch, RenderEntry, RouteLocation, RouteLocationRaw, RouteRecord, RoutesPayload, TableRecord, } from './types'; import { resolveQueryHistory } from './url'; // ---- public surface ------------------------------------------------------------ // NOTE: RouterOutlet / makeBladeComponent are deliberately NOT re-exported // here - they live in `vapor-chamber/router/vdom`. A static re-export is a // static reference: it drags defineComponent/h into this entry's chunk (and // degrades the on-demand blade import below into a static one), which puts // Vue's vDOM runtime in every consumer's bundle. See ./vdom.ts. export { onBeforeLeave, useBreadcrumbs, useMenu, useQueryParam, useRoute, useRouteData, useRouteError, useRouter, usePagination, } from './composables'; export type { Pagination, PaginationOptions, QueryParamHandle } from './composables'; export { buildBreadcrumbs, buildMenu } from './menu'; export type { Breadcrumb, MenuItem } from './menu'; export { preheatIdle, stampActiveLinks, type IdlePreheatOptions } from './dom'; export type { HistoryListener } from './history'; export { START_LOCATION } from './engine'; export { HARD_NAV_CODES, isRouterError, routerError } from './errors'; export type { RouterError, RouterErrorCode } from './errors'; export { canUseWebHistory, createMemoryHistory, createWebHistory, normalizeBase, resolveBase, stripBase } from './history'; export type { ResolveBaseOptions } from './history'; export type { RouterHistory } from './history'; export { defaultAffects, interpolateLoad, runLoaders } from './loaders'; // Mutation-driven revalidation. Exported from THIS entry rather than minted as // its own subpath: it imports nothing the router core does not already have // (loaders, errors, types, shallowRef), so a subpath would isolate no cost - // which is the only thing the subpath convention exists to do. It is a pure // function export and tree-shakes away for consumers that never call it. export { revalidateRoutes } from './revalidate'; export type { RevalidateMap, RevalidateOptions, RevalidatePlugin } from './revalidate'; // Navigation facts on a bus. From this entry, as `revalidateRoutes`: it // imports only router types, and tree-shakes away when not called. export { routerFacts } from './facts'; export type { FactSink, RouterFailedFact, RouterFlagFact, RouterNavigatedFact } from './facts'; export type { LoaderContext, LoaderHandlers, PrefixHandler, UrlHandler } from './loaders'; export type { Router } from './router-type'; export { compilePath, createRouteTable } from './table'; export type { RouteTable } from './table'; export type * from './types'; export { decodeQueryParam, encodeQueryParam, parseQuery, pathActivity, resolveQueryHistory, stringifyQuery } from './url'; export type RoutesSource = | readonly RouteRecord[] | RoutesPayload | { inline: string } | { url: string }; export type RouterOptions = { /** Mount base, e.g. '/admin'. Falls back to the payload's base, then ''. */ base?: string; routes: RoutesSource; /** component key -> component | () => import(...) */ components?: ComponentMap; /** Loader preset resolving `load` values - vapor-chamber/router-fetch (in-box) * or your own LoaderHandlers. Routes without `load` never need this. */ loaders?: LoaderHandlers; /** Override history (createMemoryHistory for tests/SSR). Default: web. */ history?: RouterHistory; /** The app's http client, for every request the router makes: the * `routes: { url }` table (REQUIRED for that source), its loaders * (`LoaderContext.http`) and blade rows (`fetchBlade`'s second argument). * `routerHttp()` from `vapor-chamber/router/remote` marks it as router * traffic, and any `HttpClient` works. */ http?: HttpClient; /** Document-level link interception + active stamping + hover and focus warm-up. * Default: true in the browser. */ links?: boolean; /** Selector scoping data-active stamping (e.g. the admin shell) - stamping * walks only this subtree instead of the whole document. Interception * stays document-level. */ linksRoot?: string; /** Island hooks for blade rows - app conventions injected, never assumed. */ hydrate?: (el: Element) => unknown; dehydrate?: (el: Element) => unknown; /** Fetch server HTML for blade rows. REQUIRED if the table has any; * `bladeFetcher()` from `vapor-chamber/router/remote` is the in-box one. A * blade row with no fetcher is a coded `router:missing:fetchBlade`. `http` * is the router's client, undefined when it has none. */ fetchBlade?: (href: string, http?: HttpClient) => Promise; /** Terminal error handler. Default: hard-navigate on HARD_NAV_CODES, log * the rest. */ onError?: (error: unknown, to: RouteLocation) => void; /** Scroll to top after committed push navigations. Default: true. */ scroll?: boolean; /** Announce each client-side navigation to assistive technology, in an * assertive live region: `document.title`, else the first `

`, else the * path. `false` turns it off; a function returns the text. Not on the * initial load or a query-only change. Default: true. See announce.ts. */ announce?: AnnounceOption; /** CSS selector of a SMALL element (a heading, a skip link) to focus after * each client-side navigation; made focusable with tabindex="-1" only if it * is not already. Default: none (focus is not moved). See announce.ts. */ focusOnNavigate?: string; }; /** * A routes payload as a read answers it: plain JSON, the table itself. A * failure is a non-2xx problem, which the http client throws; an envelope * (`{ state }`, a 2xx `{ problem }`) is off-protocol. */ export function readRoutesPayload(raw: unknown): RoutesPayload { const candidate = raw as RoutesPayload | null; if (!candidate || !Array.isArray(candidate.routes)) { throw routerError('unexpected:routes', 'routes payload has no routes array'); } return candidate; } // ---- assembly --------------------------------------------------------------------- /** * Read an inline route payload synchronously, for the one thing that cannot * wait: `base`, which the history needs before anything else happens. * * Deliberately total - a missing element, malformed JSON or a non-DOM * environment all return null and leave the real diagnosis to * `loadInlineTable()` during start(), which throws a coded router error. This * runs inside the constructor, and the constructor is documented as pure. */ function readInlinePayload(selector: string): RoutesPayload | null { if (typeof document === 'undefined') return null; try { const text = document.querySelector(selector)?.textContent; return text ? readRoutesPayload(JSON.parse(text)) : null; } catch { return null; } } export function createRouter(options: RouterOptions): Router { const hasWindow = typeof window !== 'undefined'; const source = options.routes; const syncPayload: RoutesPayload | null = Array.isArray(source) ? { routes: source } : 'routes' in (source as RoutesPayload) ? (source as RoutesPayload) : 'inline' in (source as { inline?: string }) ? // An inline payload is already in the DOM, so read it NOW rather than // at start(): `base` has to be known before the history is created, // and a payload-declared base that arrives later never applies - every // link would fall outside base '', and every in-app navigation would // be a full page load. readInlinePayload((source as { inline: string }).inline) : null; const base = options.base ?? syncPayload?.base ?? ''; // Probe before touching the History API: sandboxed/srcdoc iframes and // data: documents throw SecurityError on replaceState. Embedded contexts // degrade to a memory history seeded from the (still readable) location, // so a preview renders the right route without crashing at boot. const history = options.history ?? (hasWindow && canUseWebHistory() ? createWebHistory(base) : createMemoryHistory( base, hasWindow ? // The SAME normalizer `createMemoryHistory` applies to `base` on // the line above: a lookalike that disagreed on `'admin/'` would // make the strip return null and seed `'/'`, so an embedded // preview would render the wrong route. (stripBase(window.location.pathname, normalizeBase(base)) ?? '/') + window.location.search + window.location.hash : '/', )); /** * The http client is SUPPLIED, never built here. * * Only two features need one - loading a `{ url }` route table and fetching a * blade row - and the primary documented setup, a generated route module with * no blade rows, uses neither. Building it here would put the whole client * (CSRF, interceptors, retry, cache) in every consumer's graph: 8.5 KB raw / * 3.4 KB brotli, about a quarter of this subpath, for code most apps never * execute - and a dynamic import would still charge a bundler that does not * code split, with `createRouter` choosing a dependency for its caller. * * `vapor-chamber/router/remote` provides `routerHttp()` and `bladeFetcher()` * for the common case. Neither is privileged - any `HttpClient` works. */ // The app's one client for every request the router makes: the table, its // loaders (LoaderContext.http) and blade rows (`fetchBlade`'s second argument). const http: HttpClient | undefined = options.http; const loaders: LoaderHandlers = options.loaders ?? {}; // The affect policy is resolved once: loaders are fixed for the router's life // (setRoutes swaps rows, never loaders), so there is nothing to recompute per // navigation or per table swap. const affects: (record: TableRecord, keys: readonly string[]) => boolean = loaders.affects ?? ((record, keys) => defaultAffects(record, keys, loaders)); // A ref so table projections (router.routes -> useMenu) track swaps from // start()/{ url } loads, setRoutes() and reload(). const tableRef = shallowRef(syncPayload ? createRouteTable(syncPayload.routes) : null); // ---- render resolution (component cache + blade wrapping) ------------------ const componentCache = new Map(); // A lazy component's load in flight, by key: the promise the app's loader // returned, shared until it settles. Each caller awaits it in its own `try`, // so a failure carries that caller's `to`. Sharing loadComponent's own // promise would give a click the warm-up's `to`, the page on screen. When the // load settles, `drop` and the first caller's `await` run back to back, so // nobody starts a second load before the cache is written. A failed load // leaves, and the next caller loads again. tests/router/load-once.test.ts. const componentLoads = new Map>(); async function loadComponent(record: TableRecord, to: RouteLocation): Promise { const key = record.component as string; const cached = componentCache.get(key); if (cached !== undefined) return cached; // `Object.hasOwn`, not `components?.[key]`: `key` is `record.component`, // which arrives in the ROUTES PAYLOAD - a string from outside. A plain-object // lookup answers for keys nobody registered: a row naming `constructor` // would resolve to `Object`, be called as a lazy import and RENDER as a // blank component instead of a coded error. See `../dict`. const entry = options.components && Object.hasOwn(options.components, key) ? options.components[key] : undefined; if (entry === undefined) { throw routerError('missing:component', `no component registered for key "${key}"`, { to }); } if (typeof entry === 'function' && !isComponentLike(entry)) { let mod: unknown; try { let load = componentLoads.get(key); if (load === undefined) { // `Promise.resolve`: an entry may hand back a plain module object. load = Promise.resolve((entry as () => Promise)()); componentLoads.set(key, load); const drop = () => componentLoads.delete(key); load.then(drop, drop); } mod = await load; } catch (cause) { // Stale chunk after a deploy - default handler hard-navigates. throw routerError('failed:component', `failed to load component "${key}"`, { to, cause }); } const component = unwrapModule(mod); componentCache.set(key, component); return component; } componentCache.set(key, entry); return entry; } const fetchBlade = options.fetchBlade; async function resolveRender(records: readonly TableRecord[], to: RouteLocation): Promise { return Promise.all( records.map(async (record): Promise => { if (record.blade) { if (!fetchBlade) { throw routerError('missing:fetchBlade', `blade route "${record.name}" hit but no fetchBlade available`, { to, }); } let html: string; try { html = await fetchBlade(history.createHref(to.fullPath), http); } catch (cause) { throw routerError('failed:blade', `blade fetch failed for "${to.fullPath}"`, { to, cause }); } // Imported here, not at module scope: blade.ts is a vDOM component // (defineComponent/h/onMounted). A static import would put the vDOM // runtime in every consumer's graph, including Vapor apps that never // declare a blade row. This function is already async, so the only // cost is one extra chunk fetched the first time a blade row is hit. const { makeBladeComponent } = await import('./blade'); return { record, component: makeBladeComponent(html, { hydrate: options.hydrate, dehydrate: options.dehydrate }), }; } return { record, component: await loadComponent(record, to) }; }), ); } // ---- engine + errors --------------------------------------------------------- const errorSubscribers = new Set<(error: unknown, to: RouteLocation) => void>(); const lastError = shallowRef(null); function dispatchError(error: unknown, to: RouteLocation): void { lastError.value = error; for (const subscriber of errorSubscribers) subscriber(error, to); if (options.onError) { options.onError(error, to); return; } if (hasWindow && isRouterError(error) && HARD_NAV_CODES.has(error.code)) { const href = history.createHref(to.fullPath); // Handing the URL back to the server only helps if the server can answer // it differently. Under the catch-all this router is built for, it // cannot: the shell comes back, the router says `missing:route` again, and // location.assign() fires again - an endless reload storm that survives // refreshes, because the offending URL stays in the address bar. // Hard-navigate only when it actually moves us somewhere else. const here = window.location.pathname + window.location.search + window.location.hash; if (href !== here) { window.location.assign(href); return; } if (DEV) { _report('error', error.code, `"${href}" is already the current URL, so the router does not hard-navigate (it would reload forever behind a catch-all). Add a catch-all row (path: "/*") so the client can render its own 404.`, error, { path: href }, ); return; } } if (isRouterError(error)) _report('error', error.code, `the navigation to "${to.fullPath}" failed`, error, { path: to.fullPath }); else _report('error', 'router:failed:navigation', `the navigation to "${to.fullPath}" failed`, error, { path: to.fullPath }); } // Each record's groups, as its last read named them (LoaderContext.cacheGroups). const groupsOf = new Map(); const remember = (recordName: string, groups: readonly string[]): void => void groupsOf.set(recordName, groups); const engine = createEngine({ getTable: () => tableRef.value, history, resolveRender, runLoaders: (records, to, signal) => runLoaders(loaders, records, to, signal, (recordName, revalidation, at) => engine.trackRevalidation(recordName, revalidation, at), false, http, remember, ), loadAffectedBy: (records, keys) => records.filter((record) => affects(record, keys)), onError: dispatchError, onCommit: (snapshot, _from, info) => { if (options.scroll === false || !hasWindow) return; const hash = snapshot.location.hash; if (hash) { try { const anchor = document.querySelector(hash); if (anchor) { anchor.scrollIntoView(); return; } } catch { /* invalid selector in hash - fall through */ } } if (!info.popstate) window.scrollTo({ top: 0, behavior: 'instant' as ScrollBehavior }); }, }); // ---- cache groups (RFC 9875): the server says which reads a write made stale ---- // A refresh in flight per record: a newer one aborts it, so the later read lands. const refreshing = new Map(); /** * The client invalidated `group`: the records on screen whose read named it * refresh, past every cache, as a stale read's refresh does * (`trackRevalidation`: `isRevalidating`, dropped if the page moved on, kept * stale if it fails). The router hears it from its client, never the bus. * tests/router/cache-groups.test.ts. */ function refreshGroup(group: string): void { const at = engine.snapshot.value.location; const leaf = at.matched[at.matched.length - 1]; for (const record of leaf ? leaf.loadChain : []) { if (!groupsOf.get(record.name)?.includes(group)) continue; refreshing.get(record.name)?.abort(); const own = new AbortController(); refreshing.set(record.name, own); const fresh = runLoaders(loaders, [record], at, own.signal, undefined, true, http, remember).then((data) => data.get(record.name)); void fresh.then(() => {}, () => {}).finally(() => { if (refreshing.get(record.name) === own) refreshing.delete(record.name); }); engine.trackRevalidation(record.name, fresh, at); } } // ---- start (all IO and listeners - the constructor is pure) ------------------- let started: Promise | null = null; const teardowns: Array<() => void> = []; /** Set by dispose(). start() is async (the table load, the first * navigation), and anything it installed after dispose() ran its teardowns * would never be removed. tests/router/dispose-during-start.test.ts. */ let disposed = false; async function loadRemoteTable(url: string): Promise { try { if (!http) { throw routerError( 'missing:http', `routes: { url: "${url}" } needs an http client - pass \`http: routerHttp()\` from vapor-chamber/router/remote (or any HttpClient of your own)`, ); } const response = await http.get(url); const payload = readRoutesPayload(response.data); if (DEV) warnRemoteBase(payload); tableRef.value = createRouteTable(payload.routes); } catch (cause) { throw isRouterError(cause) ? cause : routerError('failed:routes', `could not load routes from "${url}"`, { cause }); } } function loadInlineTable(selector: string): void { if (typeof document === 'undefined') { throw routerError('missing:inline', 'inline routes need a DOM - pass rows or { url } instead'); } const el = document.querySelector(selector); if (!el?.textContent) { throw routerError('missing:inline', `no inline routes element matches "${selector}"`); } let raw: unknown; try { raw = JSON.parse(el.textContent); } catch (cause) { // The router reading its own input: coded like the element's other two // failures. tests/router/inline-routes-json.test.ts. throw routerError('unexpected:routes', `inline routes in "${selector}" are not JSON`, { cause }); } tableRef.value = createRouteTable(readRoutesPayload(raw).routes); } /** Remote payloads cannot inform `base` - the history exists before the * fetch resolves. Say so loudly in dev instead of running on the wrong * base, which manifests as "no link is ever intercepted". */ function warnRemoteBase(payload: RoutesPayload): void { if (payload.base && payload.base !== history.base && options.base === undefined) { _report('warn', 'router:conflict:base', `the fetched route payload declares base "${payload.base}", but the router was already created with base "${history.base}". A remote payload arrives after the history is built - pass \`base\` to createRouter() explicitly (or deliver the table inline).`, ); } } function preheatPath(path: string): void { const hit = tableRef.value?.resolve(path); if (!hit) return; for (const record of hit.record.renderChain) { if (record.component && record.meta.preheat !== false && !componentCache.has(record.component)) { void loadComponent(record, engine.snapshot.value.location).catch(() => {}); } } } function start(): Promise { if (started) return started; started = (async () => { if (!tableRef.value) { if ('inline' in (source as { inline?: string })) loadInlineTable((source as { inline: string }).inline); else await loadRemoteTable((source as { url: string }).url); } if (disposed) return; teardowns.push(history.listen((fullPath, info) => engine.handlePop(fullPath, { delta: info.delta }))); if (http) { teardowns.push(http.onInvalidateGroup(refreshGroup), () => { for (const ctrl of refreshing.values()) ctrl.abort(); refreshing.clear(); }); } // Idle preheat: rows flagged meta.preheat load their lazy components // after the page settles (saveData/2g-aware, aborts on interaction). // Re-armable - the original wiring is tied to the page's `load` event, // which never fires again on a bfcache restore (`pageshow` instead) - // onRestore below calls this again for any record still uncached. let stopIdlePreheat: (() => void) | null = null; // ONE teardown, registered once and reading the current canceller - an // entry per arming would grow `teardowns` on every bfcache restore. teardowns.push(() => stopIdlePreheat?.()); const armIdlePreheat = () => { if (!hasWindow || !tableRef.value) return; stopIdlePreheat?.(); const flagged = tableRef.value.records.filter( (record) => record.meta.preheat === true && record.component && !componentCache.has(record.component), ); if (flagged.length === 0) return; stopIdlePreheat = preheatIdle(flagged.map((record) => () => loadComponent(record, engine.snapshot.value.location))); }; if (hasWindow && options.links !== false) { const stampRoot = (options.linksRoot ? document.querySelector(options.linksRoot) : null) ?? document; // NOTE (measured, 2026-08-10): active-link stamping runs ONLY on path // changes. `afterEach` does not fire on query-only commits - the // engine's query fast path (`commitQueryLocation` + `refetchAffected`, // and `setQuery` likewise) returns before the after-hook loop - so the // per-keystroke full-document walk that a `setQuery`-driven search box // would imply does not happen, and no memo is needed here. That is // also correct: `data-active`/`data-exact-active` derive from // `location.path` alone, so a query-only commit cannot move any stamp. // `tests/perf.bench.ts` carries the walk's cost per commit, so the // trade-off is a number rather than an assumption if stamping ever // moves onto the query path. const stamp = () => stampActiveLinks(history.base, engine.snapshot.value.location.path, stampRoot); teardowns.push( installDomIntegration({ base: history.base, canHandle: (path) => tableRef.value !== null && tableRef.value.resolve(path) !== null, navigate: (fullPath, replace) => void engine.navigate(fullPath, { replace }), preheat: preheatPath, // The frozen page's active-link stamps and any still-uncached // preheat targets are exactly as stale as they were at freeze // time - nothing here re-runs on its own otherwise. onRestore: () => { stamp(); armIdlePreheat(); }, }), ); const stampOnCommit = engine.afterEach(stamp); teardowns.push(stampOnCommit); } await engine.navigate(history.location(), { replace: true }); if (disposed) return; // After the initial navigation has settled, committed or not: the page // the browser loaded is never announced, and every later commit is, the // first one included (tests/router/announce.test.ts, audit RA-3). if (hasWindow) { teardowns.push( installRouteAnnouncer((hook) => engine.afterEach(hook), { announce: options.announce, focusOnNavigate: options.focusOnNavigate, }), ); } armIdlePreheat(); })(); started.catch((error) => dispatchError(error, engine.snapshot.value.location)); return started; } // ---- the router object ----------------------------------------------------------- function currentLeafDefs(): Record { const matched = engine.snapshot.value.location.matched; return matched[matched.length - 1]?.queryDefs ?? {}; } /** Auto-dispose with the surrounding Vue scope; no-op outside. */ function scoped(off: () => void): () => void { if (getCurrentScope()) onScopeDispose(off); return off; } const noRecords: readonly TableRecord[] = Object.freeze([]); const routes = computed(() => tableRef.value?.records ?? noRecords); const router: Router = { currentRoute: engine.snapshot, routes, base: history.base, isLoading: engine.isLoading, isRevalidating: engine.isRevalidating, lastError, push: (to: RouteLocationRaw) => engine.navigate(to), replace: (to: RouteLocationRaw) => engine.navigate(to, { replace: true }), back: () => history.go(-1), forward: () => history.go(1), go: (delta) => history.go(delta), setQuery: (patch: QueryPatch, opts = {}) => engine.setQuery(patch, opts, (key) => resolveQueryHistory(key, currentLeafDefs()[key])), setRouteData: engine.setRouteData, beforeEach: (guard) => scoped(engine.beforeEach(guard)), afterEach: (hook) => scoped(engine.afterEach(hook)), onError: (handler) => { errorSubscribers.add(handler); return scoped(() => void errorSubscribers.delete(handler)); }, setRoutes: (rows: readonly RouteRecord[]) => { tableRef.value = createRouteTable(rows); }, reload: async () => { if (!('url' in (source as { url?: string }))) { throw routerError('missing:url', 'reload() needs a { url } routes source'); } await loadRemoteTable((source as { url: string }).url); }, start, isReady: () => start(), resolve: (to) => { // Full normalization (params inheritance, typed query, hash) when the // table is ready; graceful degradation before start(). try { return history.createHref(engine.resolveLocation(to).fullPath); } catch { if (typeof to === 'string') return history.createHref(to); return history.createHref(to.path ?? '/'); } }, install: (app) => { app.provide(ROUTER_KEY, router); // Deliberately NOT app.component('RouterOutlet', ...). A global // registration is a live reference from the router to a vDOM component, // which pins Vue's virtual-DOM runtime into every consumer's bundle - // including Vapor apps that never render one. Import // where you use it. (vue-router hit the same wall; see docs/router.md // "Why the outlet is a separate subpath".) void start(); }, dispose: () => { disposed = true; engine.cancel(); for (const teardown of teardowns.splice(0)) teardown(); history.dispose(); }, }; if (http) _routerClients.set(router, http); return router as Router; } // ---- helpers ------------------------------------------------------------------------ function isComponentLike(fn: unknown): boolean { const candidate = fn as { render?: unknown; setup?: unknown; __vccOpts?: unknown }; return Boolean(candidate.render || candidate.setup || candidate.__vccOpts); } function unwrapModule(mod: unknown): unknown { const candidate = mod as { default?: unknown }; return candidate && typeof candidate === 'object' && 'default' in candidate ? candidate.default : mod; }