Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
refactor(web): Replace the old split router with the next one (#7433)
dev-rbfb0fc1362afb
diff --git a/apps/web/biome.jsonc b/apps/web/biome.jsoncindex 0368154192..6c0e8c1cff 100644--- a/apps/web/biome.jsonc+++ b/apps/web/biome.jsonc@@ -50,9 +50,9 @@},{"includes": [- "src/lib/split-router/next/routes/**",- "src/lib/split-router/next/router/run.ts",- "src/lib/split-router/next/router/url-gate.ts"+ "src/lib/split-router/routes/**",+ "src/lib/split-router/router/run.ts",+ "src/lib/split-router/router/url-gate.ts"],"linter": {"rules": {diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsxindex 17f656d981..112bb7b4de 100644--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx@@ -1,5 +1,5 @@+import { useSplitRouter } from '@app/lib/split-router';import { setGlobalSplitManager } from '@app/signal/splitLayout';-import { useSplitRouter } from '@app/split-router';import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';import { Resize } from '@core/component/Resize';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsxindex 79a89f6a1a..2a607dbcd3 100644--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx@@ -7,7 +7,7 @@ import type { DriveState } from '@app/features/drive-view/core/types';import { useSoup } from '@app/features/next-soup/soup-context';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';import { projectRouteId } from '@app/features/projects/core/route';-import { type PaneId, useSplitRouter } from '@app/split-router';+import { type PaneId, useSplitRouter } from '@app/lib/split-router';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { type BlockName, NonDocumentBlockTypes } from '@core/block';import {diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsxindex a1f0b3bfc1..eae476b3a9 100644--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx@@ -2,8 +2,8 @@ import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';import { createSoupState } from '@app/features/next-soup/create-soup-state';import { SoupContextProvider } from '@app/features/next-soup/soup-context';import { SoupViewContextProvider } from '@app/features/next-soup/soup-view/soup-view-context';+import { type PaneId, SplitRouter } from '@app/lib/split-router';import { globalSplitManager } from '@app/signal/splitLayout';-import { type PaneId, SplitRouter } from '@app/split-router';import { ContentLoading } from '@components/app/ContentLoading';import { MobileTopEdgeFade } from '@components/app/mobile/MobileEdgeFade';import { MobilePageActionRow } from '@components/app/mobile/MobilePageActionRow';diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.tsindex 264cc44a2c..d6eafbb57f 100644--- a/apps/web/src/components/app/split-layout/layoutManager.ts+++ b/apps/web/src/components/app/split-layout/layoutManager.ts@@ -9,7 +9,7 @@ import type {SplitNavigateOptions,SplitRouter,SplitSearchUpdate,-} from '@app/split-router';+} from '@app/lib/split-router';import type {BlockAlias,BlockAliasContext,diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.tsindex 3c3543e048..a006bfe1f3 100644--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts@@ -14,7 +14,6 @@ import { driveDocumentBlockType } from '@app/features/drive-view/primitives/drivimport { driveSearch } from '@app/features/drive-view/primitives/drive-search';import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';import { EMAIL_DETAIL_SEARCH_NAMESPACE } from '@app/features/email-view/email-route';-import { paneRootMatch } from '@app/routes/app-route';import {replacePaneSearchParams,routeParams,@@ -22,7 +21,8 @@ import {type SplitRouterMiddleware,type SplitRouterMiddlewareContext,type SplitRouterMiddlewareResult,-} from '@app/split-router';+} from '@app/lib/split-router';+import { paneRootMatch } from '@app/routes/app-route';import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';diff --git a/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts b/apps/web/src/components/app/split-layout/split-router/app-pane-policy.tsindex 42d0c06ff2..08193ac914 100644--- a/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts@@ -1,6 +1,10 @@import { parseAgentsRoute } from '@app/features/agents-view/core/route';+import type {+ PaneId,+ SplitLocation,+ SplitPanePolicy,+} from '@app/lib/split-router';import { paneRootMatch } from '@app/routes/app-route';-import type { PaneId, SplitLocation, SplitPanePolicy } from '@app/split-router';import type { SplitContent, SplitId, SplitManager } from '../layoutManager';type AppPanePolicyOptions = {diff --git a/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx b/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsxindex 2cfd1168af..89a434959b 100644--- a/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx+++ b/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx@@ -1,5 +1,5 @@import { useAnalytics } from '@app/lib/analytics/analytics-context';-import { isRecord, type PaneId, useSplitRouter } from '@app/split-router';+import { isRecord, type PaneId, useSplitRouter } from '@app/lib/split-router';import { useIsAuthenticated } from '@core/auth';import { LoadingBlock } from '@core/component/LoadingBlock';import { isTouchDevice } from '@core/mobile/isTouchDevice';diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.tsindex 6db3512dd1..d72b50f1cd 100644--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts@@ -18,11 +18,6 @@ import {reminderDetailContent,reminderIdFromDetailContent,} from '@app/features/reminders/reminder-navigation';-import {- NOT_FOUND_ROUTE_ID,- paneRootMatch,- paneRoute,-} from '@app/routes/app-route';import {canonicalRoute,decodePane,@@ -35,7 +30,12 @@ import {type SplitRoutesManifest,type SplitSearchState,splitPanePaths,-} from '@app/split-router';+} from '@app/lib/split-router';+import {+ NOT_FOUND_ROUTE_ID,+ paneRootMatch,+ paneRoute,+} from '@app/routes/app-route';import { CALENDAR_BLOCK_ID } from '@block-calendar/types';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import type { BlockAlias, BlockName } from '@core/block';diff --git a/apps/web/src/components/app/split-layout/split-router/mention-links.ts b/apps/web/src/components/app/split-layout/split-router/mention-links.tsindex 8a90890cfe..415cf7e915 100644--- a/apps/web/src/components/app/split-layout/split-router/mention-links.ts+++ b/apps/web/src/components/app/split-layout/split-router/mention-links.ts@@ -11,7 +11,7 @@ import {type SplitRoutesManifest,splitPanePaths,useOptionalSplitRouter,-} from '@app/split-router';+} from '@app/lib/split-router';import type { BlockAlias, BlockName } from '@core/block';import { parseInternalAppLink } from '@core/util/macroAppUrl';import { z } from 'zod';diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsxindex b200f49c01..88b79c4464 100644--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx@@ -27,8 +27,8 @@ vi.mock('@service-connection/websocket', () => ({createConnectionBlockWebsocketEffect: vi.fn(),createConnectionWebsocketEffect: vi.fn(),}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),useSplitRouter: () => ({ entry: () => undefined }),}));vi.mock('@core/auth', () => ({diff --git a/apps/web/src/components/app/split-layout/tests/fixtures.ts b/apps/web/src/components/app/split-layout/tests/fixtures.tsindex 45bd6ea76e..e7d42328e3 100644--- a/apps/web/src/components/app/split-layout/tests/fixtures.ts+++ b/apps/web/src/components/app/split-layout/tests/fixtures.ts@@ -1,3 +1,11 @@+import {+ createMemoryHistory,+ createMemoryPaneStore,+ createSplitRouter,+ type Entry,+ type SplitLocation,+ type SplitRoutes,+} from '@app/lib/split-router';import { paneRoute } from '@app/routes/app-route';import {appRoute,@@ -7,14 +15,6 @@ import {legacyContentRoute,notFoundRoute,} from '@app/routes/routes';-import {- createMemoryHistory,- createMemoryPaneStore,- createSplitRouter,- type Entry,- type SplitLocation,- type SplitRoutes,-} from '@app/split-router';import type { BlockOrchestrator } from '@core/orchestrator';import { createSplitLayout, type SplitManager } from '../layoutManager';import { createAppPanePolicy } from '../split-router/app-pane-policy';diff --git a/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts b/apps/web/src/components/app/split-layout/tests/stacked-panes.test.tsindex cfd3ad4387..f00c225a53 100644--- a/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts+++ b/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts@@ -1,3 +1,10 @@+import {+ createMemoryHistory,+ createMemoryPaneStore,+ createSplitRouter,+ type Entry,+ type SplitRoutes,+} from '@app/lib/split-router';import { paneRoute } from '@app/routes/app-route';import {appRoute,@@ -6,13 +13,6 @@ import {notFoundRoute,settingsRoute,} from '@app/routes/routes';-import {- createMemoryHistory,- createMemoryPaneStore,- createSplitRouter,- type Entry,- type SplitRoutes,-} from '@app/split-router';import type { BlockOrchestrator } from '@core/orchestrator';import { createRoot } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';diff --git a/apps/web/src/features/agent-changes/pane-view-state.ts b/apps/web/src/features/agent-changes/pane-view-state.tsindex 86d0c371ea..853490f53d 100644--- a/apps/web/src/features/agent-changes/pane-view-state.ts+++ b/apps/web/src/features/agent-changes/pane-view-state.ts@@ -1,4 +1,7 @@-import { createSearchParams, useOwnsSearchNamespace } from '@app/split-router';+import {+ createSearchParams,+ useOwnsSearchNamespace,+} from '@app/lib/split-router';import { createSignal } from 'solid-js';import { changesSearch } from './changes-search';import type { PaneViewState } from './context/agent-changes-context';diff --git a/apps/web/src/features/agents-view/route-views.test.tsx b/apps/web/src/features/agents-view/route-views.test.tsxindex bc5f1a2ec6..d20e81e07c 100644--- a/apps/web/src/features/agents-view/route-views.test.tsx+++ b/apps/web/src/features/agents-view/route-views.test.tsx@@ -17,8 +17,8 @@ const state = vi.hoisted(() => ({vi.mock('@app/lib/analytics/posthog', () => ({useFeatureFlag: () => state.flag,}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),defineRoute: (route: unknown) => route,}));vi.mock('@components/app/split-layout/layoutUtils', () => ({diff --git a/apps/web/src/features/block-agent/agent-route.ts b/apps/web/src/features/block-agent/agent-route.tsindex 96de03eb10..4ec83c07b3 100644--- a/apps/web/src/features/block-agent/agent-route.ts+++ b/apps/web/src/features/block-agent/agent-route.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';export const agentDetailSearch = {diff --git a/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts b/apps/web/src/features/block-agent/primitives/create-agent-route-target.tsindex 42de129c40..7f2d537e40 100644--- a/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts+++ b/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts@@ -1,4 +1,4 @@-import { createSearchParams } from '@app/split-router';+import { createSearchParams } from '@app/lib/split-router';import { createMemo } from 'solid-js';import { agentDetailSearch } from '../agent-route';import type { AgentMessageTarget } from '../core/search-location';diff --git a/apps/web/src/features/block-call/call-route.ts b/apps/web/src/features/block-call/call-route.tsindex 6b4fef3f15..c6d6762c98 100644--- a/apps/web/src/features/block-call/call-route.ts+++ b/apps/web/src/features/block-call/call-route.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';export const callDetailSearch = {diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsxindex 76464e5499..c222f28d6d 100644--- a/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx@@ -9,8 +9,8 @@ const state = vi.hoisted(() => ({setSearch: vi.fn(),navigate: (_params: CallBlockProps) => {},}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),createSearchParams: () => [state.search, state.setSearch],}));vi.mock('@app/signal/splitLayout', () => ({diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.tsxindex e7331ee22f..33254c3f73 100644--- a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.tsx@@ -1,5 +1,5 @@+import { createSearchParams } from '@app/lib/split-router';import { globalSplitManager } from '@app/signal/splitLayout';-import { createSearchParams } from '@app/split-router';import {type CallBlockProps,type CallTranscriptTarget,diff --git a/apps/web/src/features/block-call/route-views.tsx b/apps/web/src/features/block-call/route-views.tsxindex 91f6a3f137..6183d58374 100644--- a/apps/web/src/features/block-call/route-views.tsx+++ b/apps/web/src/features/block-call/route-views.tsx@@ -1,6 +1,6 @@import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { createSearchParams, useRouteParams } from '@app/lib/split-router';import { callDetailRoute } from '@app/routes/routes';-import { createSearchParams, useRouteParams } from '@app/split-router';import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';import { lazy, onMount } from 'solid-js';import { callDetailSearch } from './call-route';diff --git a/apps/web/src/features/block-call/views/CallDetailView.test.tsx b/apps/web/src/features/block-call/views/CallDetailView.test.tsxindex bf9f3da4a3..4d2a7ac0bc 100644--- a/apps/web/src/features/block-call/views/CallDetailView.test.tsx+++ b/apps/web/src/features/block-call/views/CallDetailView.test.tsx@@ -23,7 +23,7 @@ const mocks = vi.hoisted(() => ({},}));-vi.mock('@app/split-router', () => ({+vi.mock('@app/lib/split-router', () => ({createSearchParams: () => [{}, mocks.setSearch],}));vi.mock('../call-route', () => ({diff --git a/apps/web/src/features/block-call/views/CallDetailView.tsx b/apps/web/src/features/block-call/views/CallDetailView.tsxindex f3275095ad..a54bf122ab 100644--- a/apps/web/src/features/block-call/views/CallDetailView.tsx+++ b/apps/web/src/features/block-call/views/CallDetailView.tsx@@ -1,5 +1,5 @@import { ViewShell } from '@app/components/view-shell';-import { createSearchParams } from '@app/split-router';+import { createSearchParams } from '@app/lib/split-router';import { SidePanel } from '@components/app/side-panel';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsxindex 830dfd6ed9..b3ed8e7a6d 100644--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx@@ -9,8 +9,8 @@ const state = vi.hoisted(() => ({navigate: (_params: Record<string, unknown>) => {},latest: () => {},}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),createSearchParams: () => [state.search],}));vi.mock('@app/signal/splitLayout', () => ({diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsxindex dffeb9bfc5..02f263b879 100644--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx@@ -8,8 +8,8 @@ import {makeRenameAction,useBlockEntityCommands,} from '@app/features/next-soup/actions';+import { createSearchParams } from '@app/lib/split-router';import { globalSplitManager } from '@app/signal/splitLayout';-import { createSearchParams } from '@app/split-router';import { URL_PARAMS } from '@block-channel/constants';import { ChannelAttachmentsTab } from '@channel/Attachments/ChannelAttachmentsTab';import { useChannelBotManagement } from '@channel/Bots/use-channel-bot-management';diff --git a/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx b/apps/web/src/features/block-email/EmailBlockAdapter.test.tsxindex a4624a197b..304fb7cd60 100644--- a/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx+++ b/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx@@ -10,8 +10,8 @@ const state = vi.hoisted(() => ({navigate: (_params: Record<string, unknown>) => {},host: undefined as EmailThreadHost | undefined,}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),createSearchParams: () => [state.search],}));vi.mock('@solidjs/router', () => ({ useSearchParams: () => [{}] }));diff --git a/apps/web/src/features/block-email/EmailBlockAdapter.tsx b/apps/web/src/features/block-email/EmailBlockAdapter.tsxindex 555e393e2b..83b37c866b 100644--- a/apps/web/src/features/block-email/EmailBlockAdapter.tsx+++ b/apps/web/src/features/block-email/EmailBlockAdapter.tsx@@ -4,7 +4,7 @@ import type {} from '@app/features/email-thread/context/email-thread-context';import { URL_PARAMS } from '@app/features/email-thread/core/location';import { emailDetailSearch } from '@app/features/email-view/email-route';-import { createSearchParams } from '@app/split-router';+import { createSearchParams } from '@app/lib/split-router';import {useCanAutofocusSplitContent,useSplitPanel,diff --git a/apps/web/src/features/block-md/markdown-route.ts b/apps/web/src/features/block-md/markdown-route.tsindex a03d4e4386..ac8bb0f733 100644--- a/apps/web/src/features/block-md/markdown-route.ts+++ b/apps/web/src/features/block-md/markdown-route.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';export const markdownDetailSearch = {diff --git a/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts b/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.tsindex ff79a8e444..90a949923e 100644--- a/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts+++ b/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts@@ -1,4 +1,4 @@-import { createSearchParams } from '@app/split-router';+import { createSearchParams } from '@app/lib/split-router';import { type Accessor, createEffect, on } from 'solid-js';import { URL_PARAMS } from '../constants';import { markdownDetailSearch } from '../markdown-route';diff --git a/apps/web/src/features/block-pdf/pdf-route.ts b/apps/web/src/features/block-pdf/pdf-route.tsindex 002b41577e..317da88acc 100644--- a/apps/web/src/features/block-pdf/pdf-route.ts+++ b/apps/web/src/features/block-pdf/pdf-route.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';export const pdfDetailSearch = {diff --git a/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts b/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.tsindex a10cc73863..3c4d25982a 100644--- a/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts+++ b/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts@@ -1,4 +1,4 @@-import { createSearchParams } from '@app/split-router';+import { createSearchParams } from '@app/lib/split-router';import { type Accessor, createMemo } from 'solid-js';import { URL_PARAMS } from '../constants';import { pdfDetailSearch } from '../pdf-route';diff --git a/apps/web/src/features/block-pr/route-views.tsx b/apps/web/src/features/block-pr/route-views.tsxindex 1c0181ade4..00cf16149e 100644--- a/apps/web/src/features/block-pr/route-views.tsx+++ b/apps/web/src/features/block-pr/route-views.tsx@@ -1,5 +1,5 @@import { useAnalytics } from '@app/lib/analytics/analytics-context';-import { useParams } from '@app/split-router';+import { useParams } from '@app/lib/split-router';import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';import { lazy, onMount } from 'solid-js';diff --git a/apps/web/src/features/calendar-view/calendar-url.ts b/apps/web/src/features/calendar-view/calendar-url.tsindex 9cf31845b1..8d1d17a792 100644--- a/apps/web/src/features/calendar-view/calendar-url.ts+++ b/apps/web/src/features/calendar-view/calendar-url.ts@@ -1,5 +1,5 @@import type { CalendarPeriodView } from '@app/features/calendar/types';-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';import { createCalendarRange } from './calendar-range';import type { CalendarViewTarget } from './types';diff --git a/apps/web/src/features/calendar-view/calendar-view.tsx b/apps/web/src/features/calendar-view/calendar-view.tsxindex 578aeadcba..75132aa3d7 100644--- a/apps/web/src/features/calendar-view/calendar-view.tsx+++ b/apps/web/src/features/calendar-view/calendar-view.tsx@@ -4,7 +4,11 @@ import type { CalendarPeriodView } from '@app/features/calendar/types';import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { usePosthog } from '@app/lib/analytics/posthog';-import { createSearchParams, useNavigate, useParams } from '@app/split-router';+import {+ createSearchParams,+ useNavigate,+ useParams,+} from '@app/lib/split-router';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { LoadingBlock } from '@core/component/LoadingBlock';import { useUserId } from '@core/context/user';diff --git a/apps/web/src/features/channels-view/channels-route.ts b/apps/web/src/features/channels-view/channels-route.tsindex acaff090a7..aae666c972 100644--- a/apps/web/src/features/channels-view/channels-route.ts+++ b/apps/web/src/features/channels-view/channels-route.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';import type { ChannelsQueryScope, ChannelsTab } from './types';diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsxindex 0782809c6a..ee96086cc4 100644--- a/apps/web/src/features/channels-view/channels-view-context.tsx+++ b/apps/web/src/features/channels-view/channels-view-context.tsx@@ -5,12 +5,12 @@ import {} from '@app/features/next-soup/utils';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { makePersistedState } from '@app/lib/persistence';-import { channelDetailRoute, channelsSplitRoute } from '@app/routes/routes';import {createSearchParams,useNavigate,useRouteParams,-} from '@app/split-router';+} from '@app/lib/split-router';+import { channelDetailRoute, channelsSplitRoute } from '@app/routes/routes';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { enableChannelThreadsPreview } from '@core/constant/featureFlags';diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsxindex 38e244d1a8..46728f11c9 100644--- a/apps/web/src/features/channels-view/channels-view.test.tsx+++ b/apps/web/src/features/channels-view/channels-view.test.tsx@@ -42,7 +42,7 @@ vi.mock('@queries/soup/search', () => ({useSearchSoupQuery: () => ({ isSuccess: false, isLoading: false }),validateSearchServiceText: (text: string) => text.length >= 3,}));-vi.mock('@app/split-router', () => ({+vi.mock('@app/lib/split-router', () => ({SplitRouter: {Outlet: (props: { fallback: () => JSX.Element }) => (<Show when={mocks.selectedId()} fallback={props.fallback()}>diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsxindex fea0783685..5deab72c27 100644--- a/apps/web/src/features/channels-view/channels-view.tsx+++ b/apps/web/src/features/channels-view/channels-view.tsx@@ -5,7 +5,7 @@ import { markChannelNotificationsSeenOnOpen } from '@app/features/next-soup/utilimport { MaybeSoupEntityActionDrawerManager } from '@app/features/soup';import { withEntityNotifications } from '@app/features/soup/entity-notifications';import { ViewTour } from '@app/features/tours/ViewTour';-import { SplitRouter } from '@app/split-router';+import { SplitRouter } from '@app/lib/split-router';import { DebugSuspense } from '@channel/DebugSuspense';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsxindex 9182d67522..afe9a75f42 100644--- a/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx@@ -7,8 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({routeSearch: vi.fn((): { seek?: string } => ({})),}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),createSearchParams: () => [mocks.routeSearch()],}));vi.mock('@app/features/next-soup/actions', () => ({diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.tsxindex e524ee75de..bdb005d5bd 100644--- a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx@@ -1,5 +1,5 @@import { useBlockEntityCommands } from '@app/features/next-soup/actions';-import { createSearchParams } from '@app/split-router';+import { createSearchParams } from '@app/lib/split-router';import {ChannelDetail,ChannelDetailTopBar,diff --git a/apps/web/src/features/channels-view/route-views.tsx b/apps/web/src/features/channels-view/route-views.tsxindex 3903a76771..81a8751356 100644--- a/apps/web/src/features/channels-view/route-views.tsx+++ b/apps/web/src/features/channels-view/route-views.tsx@@ -1,4 +1,4 @@-import { createSearchParams, useParams } from '@app/split-router';+import { createSearchParams, useParams } from '@app/lib/split-router';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import type { SplitContent } from '@components/app/split-layout/layoutManager';import {diff --git a/apps/web/src/features/drive-view/drive-detail-navigation.tsx b/apps/web/src/features/drive-view/drive-detail-navigation.tsxindex d1a0206b01..4df045b49c 100644--- a/apps/web/src/features/drive-view/drive-detail-navigation.tsx+++ b/apps/web/src/features/drive-view/drive-detail-navigation.tsx@@ -4,8 +4,8 @@ import type {EntityDetailNavigationOptions,EntityDetailTarget,} from '@app/components/entity-detail/entity-detail-target';+import { useNavigate, useParams, useRouteState } from '@app/lib/split-router';import { driveSplitRoute } from '@app/routes/routes';-import { useNavigate, useParams, useRouteState } from '@app/split-router';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';import { isTouchDevice } from '@core/mobile/isTouchDevice';import {diff --git a/apps/web/src/features/drive-view/drive-hosted-content.ts b/apps/web/src/features/drive-view/drive-hosted-content.tsindex 1081638c65..612d70709a 100644--- a/apps/web/src/features/drive-view/drive-hosted-content.ts+++ b/apps/web/src/features/drive-view/drive-hosted-content.ts@@ -1,5 +1,5 @@+import type { SplitLocation, SplitRouteMatch } from '@app/lib/split-router';import { paneRoute } from '@app/routes/app-route';-import type { SplitLocation, SplitRouteMatch } from '@app/split-router';import type { SplitContent } from '@components/app/split-layout/layoutManager';import type { DriveLocation } from './core/types';import {diff --git a/apps/web/src/features/drive-view/drive-location-menu.tsx b/apps/web/src/features/drive-view/drive-location-menu.tsxindex 6651e116dc..479019b636 100644--- a/apps/web/src/features/drive-view/drive-location-menu.tsx+++ b/apps/web/src/features/drive-view/drive-location-menu.tsx@@ -1,5 +1,5 @@+import { useNavigate } from '@app/lib/split-router';import { globalSplitManager } from '@app/signal/splitLayout';-import { useNavigate } from '@app/split-router';import { SidebarOpenInSplitMenu } from '@components/app/app-sidebar/sidebar';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { batch, type ParentProps, Show } from 'solid-js';diff --git a/apps/web/src/features/drive-view/primitives/drive-route-state.ts b/apps/web/src/features/drive-view/primitives/drive-route-state.tsindex 0fa338c926..21b1d83972 100644--- a/apps/web/src/features/drive-view/primitives/drive-route-state.ts+++ b/apps/web/src/features/drive-view/primitives/drive-route-state.ts@@ -7,7 +7,7 @@ import {type SplitNavigateOptions,useNavigate,useParams,-} from '@app/split-router';+} from '@app/lib/split-router';import { useEntryState } from '@components/app/split-layout/entry-state';import deepEqual from 'fast-deep-equal';import {diff --git a/apps/web/src/features/drive-view/primitives/drive-route.ts b/apps/web/src/features/drive-view/primitives/drive-route.tsindex 3aa4e17d04..bc833bda5e 100644--- a/apps/web/src/features/drive-view/primitives/drive-route.ts+++ b/apps/web/src/features/drive-view/primitives/drive-route.ts@@ -1,4 +1,4 @@-import type { SplitRouteParams } from '@app/split-router';+import type { SplitRouteParams } from '@app/lib/split-router';import { fileTypeToBlockName } from '@core/constant/allBlocks';import { z } from 'zod';import type { DriveLocation, DriveTab } from '../core/types';diff --git a/apps/web/src/features/drive-view/primitives/drive-search.ts b/apps/web/src/features/drive-view/primitives/drive-search.tsindex e25204c6c6..0490fd39cf 100644--- a/apps/web/src/features/drive-view/primitives/drive-search.ts+++ b/apps/web/src/features/drive-view/primitives/drive-search.ts@@ -8,7 +8,7 @@ import {isSafeName,type SerializedSearchParams,takeLast,-} from '@app/split-router';+} from '@app/lib/split-router';import { z } from 'zod';const searchSchema = z.object({diff --git a/apps/web/src/features/drive-view/route-views.tsx b/apps/web/src/features/drive-view/route-views.tsxindex 8ed32c0ef4..b70a693918 100644--- a/apps/web/src/features/drive-view/route-views.tsx+++ b/apps/web/src/features/drive-view/route-views.tsx@@ -1,5 +1,5 @@+import { createSearchParams, useRouteParams } from '@app/lib/split-router';import { driveCallRoute } from '@app/routes/routes';-import { createSearchParams, useRouteParams } from '@app/split-router';import { callDetailSearch } from '@block-call/call-route';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import {diff --git a/apps/web/src/features/drive-view/views/drive-workspace.tsx b/apps/web/src/features/drive-view/views/drive-workspace.tsxindex 8db6a1a82d..99c679d9a1 100644--- a/apps/web/src/features/drive-view/views/drive-workspace.tsx+++ b/apps/web/src/features/drive-view/views/drive-workspace.tsx@@ -1,5 +1,5 @@import { useViewTabHotkeys, ViewShell } from '@app/components/view-shell';-import { SplitRouter } from '@app/split-router';+import { SplitRouter } from '@app/lib/split-router';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';import SpinnerIcon from '@phosphor/spinner.svg';diff --git a/apps/web/src/features/email-view/components/EmailDetailView.tsx b/apps/web/src/features/email-view/components/EmailDetailView.tsxindex be8865a163..23bb72c62d 100644--- a/apps/web/src/features/email-view/components/EmailDetailView.tsx+++ b/apps/web/src/features/email-view/components/EmailDetailView.tsx@@ -5,8 +5,8 @@ import { displaySubject } from '@app/features/email-compose/core/subject-text';import type { EmailThreadHost } from '@app/features/email-thread/context/email-thread-context';import { createEmailThreadSource } from '@app/features/email-thread/queries/thread-source';import { useBlockEntityCommands } from '@app/features/next-soup/actions';+import { createSearchParams, useRouteParams } from '@app/lib/split-router';import { emailThreadRoute } from '@app/routes/routes';-import { createSearchParams, useRouteParams } from '@app/split-router';import { EmailThreadControls } from '@block-email/component/EmailThreadControls';import { EmailThreadLoadGate } from '@block-email/component/EmailThreadLoadGate';import {diff --git a/apps/web/src/features/email-view/email-route.ts b/apps/web/src/features/email-view/email-route.tsindex 72a9cd34db..38781dd50b 100644--- a/apps/web/src/features/email-view/email-route.ts+++ b/apps/web/src/features/email-view/email-route.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';import type { EmailTab } from './types';diff --git a/apps/web/src/features/email-view/email-view-context.test.tsx b/apps/web/src/features/email-view/email-view-context.test.tsxindex ceabdee686..b463cd2178 100644--- a/apps/web/src/features/email-view/email-view-context.test.tsx+++ b/apps/web/src/features/email-view/email-view-context.test.tsx@@ -33,8 +33,8 @@ vi.mock('@app/features/soup/collection/list-navigation-source', () => ({vi.mock('@app/lib/persistence', () => ({makePersistedState: <T,>(store: T) => store,}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),useNavigate: () => mocks.navigate,useRouteParams: () => mocks.useRouteParams(),createSearchParams: () => [diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsxindex a7d082105d..48d3bedf65 100644--- a/apps/web/src/features/email-view/email-view-context.tsx+++ b/apps/web/src/features/email-view/email-view-context.tsx@@ -11,12 +11,12 @@ import { normalizeFacetSelection } from '@app/features/soup';import { registerListNavigationSource } from '@app/features/soup/collection/list-navigation-source';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { makePersistedState } from '@app/lib/persistence';-import { emailSplitRoute, emailThreadRoute } from '@app/routes/routes';import {createSearchParams,useNavigate,useRouteParams,-} from '@app/split-router';+} from '@app/lib/split-router';+import { emailSplitRoute, emailThreadRoute } from '@app/routes/routes';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';import {useSplitPanelOrThrow,diff --git a/apps/web/src/features/email-view/email-view.tsx b/apps/web/src/features/email-view/email-view.tsxindex 64615f664c..c5d9c4f260 100644--- a/apps/web/src/features/email-view/email-view.tsx+++ b/apps/web/src/features/email-view/email-view.tsx@@ -1,7 +1,7 @@import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';import { ViewTour } from '@app/features/tours/ViewTour';import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { SplitRouter } from '@app/split-router';+import { SplitRouter } from '@app/lib/split-router';import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';diff --git a/apps/web/src/features/email-view/route-views.tsx b/apps/web/src/features/email-view/route-views.tsxindex 7f90a99b97..4c40504045 100644--- a/apps/web/src/features/email-view/route-views.tsx+++ b/apps/web/src/features/email-view/route-views.tsx@@ -1,4 +1,4 @@-import { createSearchParams, useParams } from '@app/split-router';+import { createSearchParams, useParams } from '@app/lib/split-router';import type { SplitContent } from '@components/app/split-layout/layoutManager';import {AppView,diff --git a/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx b/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsxindex 7c1e2fdff8..7f014641a8 100644--- a/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx+++ b/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx@@ -5,7 +5,7 @@ import {import type { EntityDetailTarget } from '@app/components/entity-detail/entity-detail-target';import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';import { channelsSearch } from '@app/features/channels-view/channels-route';-import { createSearchParams, useParams } from '@app/split-router';+import { createSearchParams, useParams } from '@app/lib/split-router';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import { ChannelDetailTopBar } from '@channel/Channel/ChannelDetail';import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';diff --git a/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsx b/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsxindex 6e56a982bf..1880d56e2a 100644--- a/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsx+++ b/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsx@@ -1,6 +1,6 @@import { ReminderDetails } from '@app/features/reminders/ReminderEditorSplit';import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { useParams } from '@app/split-router';+import { useParams } from '@app/lib/split-router';import { PreviewFrame } from '@components/app/PreviewPanel';import {useSplitDisplayName,diff --git a/apps/web/src/features/home/home-calendar-preview.ts b/apps/web/src/features/home/home-calendar-preview.tsindex 2fdceac965..6334285ac2 100644--- a/apps/web/src/features/home/home-calendar-preview.ts+++ b/apps/web/src/features/home/home-calendar-preview.ts@@ -4,13 +4,13 @@ import {calendarTargetSearch,} from '@app/features/calendar-view/calendar-url';import type { CalendarPreviewSelection } from '@app/features/next-soup/utils';-import { homeCalendarRoute } from '@app/routes/routes';import {createSearchParams,type SerializedSearchParams,useNavigate,useRouteParams,-} from '@app/split-router';+} from '@app/lib/split-router';+import { homeCalendarRoute } from '@app/routes/routes';import { previewCalendarTarget } from '@components/app/previewTarget';import {enableCalendarUi,diff --git a/apps/web/src/features/home/home-preview-navigation.ts b/apps/web/src/features/home/home-preview-navigation.tsindex 147609585c..fc50b496db 100644--- a/apps/web/src/features/home/home-preview-navigation.ts+++ b/apps/web/src/features/home/home-preview-navigation.ts@@ -19,7 +19,7 @@ import {driveSearchCodec,} from '@app/features/drive-view/primitives/drive-search';import { emailDetailSearch } from '@app/features/email-view/email-route';-import type { SerializedSearchParams } from '@app/split-router';+import type { SerializedSearchParams } from '@app/lib/split-router';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';diff --git a/apps/web/src/features/home/home-tab-search.ts b/apps/web/src/features/home/home-tab-search.tsindex d098c05f0b..90040dff30 100644--- a/apps/web/src/features/home/home-tab-search.ts+++ b/apps/web/src/features/home/home-tab-search.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';import type { HomeTab } from './types';diff --git a/apps/web/src/features/home/home-view-context.tsx b/apps/web/src/features/home/home-view-context.tsxindex f503138030..8c4748cb28 100644--- a/apps/web/src/features/home/home-view-context.tsx+++ b/apps/web/src/features/home/home-view-context.tsx@@ -4,6 +4,12 @@ import { driveSearch } from '@app/features/drive-view/primitives/drive-search';import { reminderSourceContent } from '@app/features/reminders/reminder-source';import type { FacetSelection } from '@app/features/soup/filters/facets/types';import { makePersistedState } from '@app/lib/persistence';+import {+ createSearchParams,+ type SerializedSearchParams,+ useNavigate,+ useParams,+} from '@app/lib/split-router';import {homeChannelRoute,homeDocumentRoute,@@ -11,12 +17,6 @@ import {homeReminderRoute,homeSplitRoute,} from '@app/routes/routes';-import {- createSearchParams,- type SerializedSearchParams,- useNavigate,- useParams,-} from '@app/split-router';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';import {type PreviewBlockTarget,diff --git a/apps/web/src/features/home/home-view.tsx b/apps/web/src/features/home/home-view.tsxindex 596e8bd20b..fadb5a3fdc 100644--- a/apps/web/src/features/home/home-view.tsx+++ b/apps/web/src/features/home/home-view.tsx@@ -2,8 +2,8 @@ import { useViewShell, ViewShell } from '@app/components/view-shell';import { calendarSearch } from '@app/features/calendar-view/calendar-url';import { CalendarView } from '@app/features/calendar-view/calendar-view';import { ViewTour } from '@app/features/tours/ViewTour';+import { createSearchParams, SplitRouter } from '@app/lib/split-router';import { homeCalendarRoute } from '@app/routes/routes';-import { createSearchParams, SplitRouter } from '@app/split-router';import { DebugSuspense } from '@channel/DebugSuspense';import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';import { PreviewFrame, PreviewPanel } from '@components/app/PreviewPanel';diff --git a/apps/web/src/features/home/route-views.tsx b/apps/web/src/features/home/route-views.tsxindex 29ea2d3e78..ce27099933 100644--- a/apps/web/src/features/home/route-views.tsx+++ b/apps/web/src/features/home/route-views.tsx@@ -2,7 +2,7 @@ import type { CalendarPeriodView } from '@app/features/calendar/types';import { calendarSearch } from '@app/features/calendar-view/calendar-url';import { channelsSearch } from '@app/features/channels-view/channels-route';import { driveSearch } from '@app/features/drive-view/primitives/drive-search';-import { createSearchParams, useParams } from '@app/split-router';+import { createSearchParams, useParams } from '@app/lib/split-router';import {AppView,RedirectSplit,diff --git a/apps/web/src/features/next-soup/search-navigation-readers.test.tsx b/apps/web/src/features/next-soup/search-navigation-readers.test.tsxindex e532dd76c4..559a3aee74 100644--- a/apps/web/src/features/next-soup/search-navigation-readers.test.tsx+++ b/apps/web/src/features/next-soup/search-navigation-readers.test.tsx@@ -9,7 +9,7 @@ import {replacePaneSearchParams,type SplitPanePolicy,SplitRouter,-} from '@app/split-router';+} from '@app/lib/split-router';import type { SearchLocation } from '@entity';import { cleanup, render } from '@solidjs/testing-library';import { type Accessor, createSignal, onCleanup } from 'solid-js';diff --git a/apps/web/src/features/next-soup/search-navigation.test.ts b/apps/web/src/features/next-soup/search-navigation.test.tsindex f0f50f8d60..54bb569b70 100644--- a/apps/web/src/features/next-soup/search-navigation.test.ts+++ b/apps/web/src/features/next-soup/search-navigation.test.ts@@ -4,8 +4,8 @@ import { markdownDetailSearchCodec } from '@app/features/block-md/markdown-routeimport { pdfDetailSearchCodec } from '@app/features/block-pdf/pdf-route';import { channelsSearchCodec } from '@app/features/channels-view/channels-route';import { emailDetailSearchCodec } from '@app/features/email-view/email-route';-import { parsePaneSearch } from '@app/lib/split-router/next/routes/search';-import { replacePaneSearchParams } from '@app/split-router';+import { replacePaneSearchParams } from '@app/lib/split-router';+import { parsePaneSearch } from '@app/lib/split-router/routes/search';import type { SearchLocation } from '@entity';import { describe, expect, it } from 'vitest';import {diff --git a/apps/web/src/features/next-soup/search-navigation.ts b/apps/web/src/features/next-soup/search-navigation.tsindex 3eb18af6d9..2b7a732778 100644--- a/apps/web/src/features/next-soup/search-navigation.ts+++ b/apps/web/src/features/next-soup/search-navigation.ts@@ -25,7 +25,7 @@ import {import type {SerializedSearchParams,SplitSearchUpdate,-} from '@app/split-router';+} from '@app/lib/split-router';import type { SearchLocation } from '@entity';import { match } from 'ts-pattern';diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.tsindex fec79698bc..2cb1f65638 100644--- a/apps/web/src/features/next-soup/utils.test.ts+++ b/apps/web/src/features/next-soup/utils.test.ts@@ -151,9 +151,9 @@ vi.mock('@core/constant/featureFlags', async (importOriginal) => {};});+import type { SerializedSearchParams } from '@app/lib/split-router';import { paneRoute } from '@app/routes/app-route';import { setGlobalSplitManager } from '@app/signal/splitLayout';-import type { SerializedSearchParams } from '@app/split-router';import type {OpenWithSplitOptions,SplitManager,diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.tsindex d889204ff2..a7b249d3c2 100644--- a/apps/web/src/features/next-soup/utils.ts+++ b/apps/web/src/features/next-soup/utils.ts@@ -28,8 +28,8 @@ import {getEntityNotifications,scopeChannelNotificationsForEntity,} from '@app/features/soup/entity-notifications';+import { replacePaneSearchParams } from '@app/lib/split-router';import { globalSplitManager } from '@app/signal/splitLayout';-import { replacePaneSearchParams } from '@app/split-router';import { CALENDAR_BLOCK_ID } from '@block-calendar/types';import {goToChannelLatest,diff --git a/apps/web/src/features/projects/project-detail.tsx b/apps/web/src/features/projects/project-detail.tsxindex e3972a5b0d..ddf1eb533c 100644--- a/apps/web/src/features/projects/project-detail.tsx+++ b/apps/web/src/features/projects/project-detail.tsx@@ -1,11 +1,11 @@import { EntityDetailTopBar } from '@app/components/entity-detail/EntityDetailTopBar';import { ViewBreadcrumbs } from '@app/components/view-shell';+import { useNavigate } from '@app/lib/split-router';import {projectDetailRoute,projectTaskRoute,tasksSplitRoute,} from '@app/routes/routes';-import { useNavigate } from '@app/split-router';import type { ComposeTaskProps } from '@block-md/component/ComposeTask';import { useSplitLayout } from '@components/app/split-layout/layout';import {diff --git a/apps/web/src/features/projects/project-view.test.tsx b/apps/web/src/features/projects/project-view.test.tsxindex 66461d7672..f4c0cb18e7 100644--- a/apps/web/src/features/projects/project-view.test.tsx+++ b/apps/web/src/features/projects/project-view.test.tsx@@ -34,7 +34,7 @@ vi.mock('@app/routes/routes', () => ({projectDetailRoute: {},tasksProjectsRoute: {},}));-vi.mock('@app/split-router', () => ({+vi.mock('@app/lib/split-router', () => ({useNavigate: () => fixtures.navigate,usePaneHistory: () => () =>fixtures.routed() ? { entries: [], index: 0 } : undefined,diff --git a/apps/web/src/features/projects/project-view.tsx b/apps/web/src/features/projects/project-view.tsxindex 151bfb8552..f5e55df036 100644--- a/apps/web/src/features/projects/project-view.tsx+++ b/apps/web/src/features/projects/project-view.tsx@@ -1,5 +1,5 @@+import { useNavigate, usePaneHistory } from '@app/lib/split-router';import { projectDetailRoute, tasksProjectsRoute } from '@app/routes/routes';-import { useNavigate, usePaneHistory } from '@app/split-router';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';diff --git a/apps/web/src/features/reminders/route-views.tsx b/apps/web/src/features/reminders/route-views.tsxindex 5f96f1aaea..95d3d7d0ef 100644--- a/apps/web/src/features/reminders/route-views.tsx+++ b/apps/web/src/features/reminders/route-views.tsx@@ -1,6 +1,6 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useRouteParams } from '@app/lib/split-router';import { reminderDetailRoute } from '@app/routes/routes';-import { useRouteParams } from '@app/split-router';import {useSplitDisplayName,useSplitPanelOrThrow,diff --git a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsxindex cba7c6c58d..660a5da638 100644--- a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx+++ b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx@@ -1,7 +1,7 @@import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { useRouteParams } from '@app/lib/split-router';import { reviewsPrRoute } from '@app/routes/routes';-import { useRouteParams } from '@app/split-router';import { PrChangesProvider } from '@block-pr/component/PrChanges';import { PrStatusIcon } from '@block-pr/component/PrStatus';import { prDisplayName, prHtmlUrl } from '@block-pr/util/prKey';diff --git a/apps/web/src/features/reviews-view/reviews-hosted-content.ts b/apps/web/src/features/reviews-view/reviews-hosted-content.tsindex c4febf79e9..7ec8f2e84d 100644--- a/apps/web/src/features/reviews-view/reviews-hosted-content.ts+++ b/apps/web/src/features/reviews-view/reviews-hosted-content.ts@@ -1,5 +1,5 @@+import type { SplitLocation, SplitRouteMatch } from '@app/lib/split-router';import { paneRoute } from '@app/routes/app-route';-import type { SplitLocation, SplitRouteMatch } from '@app/split-router';import type { SplitContent } from '@components/app/split-layout/layoutManager';const hostedDetailRoutes = {diff --git a/apps/web/src/features/reviews-view/reviews-tab-search.ts b/apps/web/src/features/reviews-view/reviews-tab-search.tsindex 813f638fa4..9f8242985d 100644--- a/apps/web/src/features/reviews-view/reviews-tab-search.ts+++ b/apps/web/src/features/reviews-view/reviews-tab-search.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';import type { ReviewsScope } from './reviews-types';diff --git a/apps/web/src/features/reviews-view/reviews-view.tsx b/apps/web/src/features/reviews-view/reviews-view.tsxindex 2d034ece3c..96b1252686 100644--- a/apps/web/src/features/reviews-view/reviews-view.tsx+++ b/apps/web/src/features/reviews-view/reviews-view.tsx@@ -3,13 +3,13 @@ import {ViewBreadcrumbs,ViewShell,} from '@app/components/view-shell';-import { reviewsPrRoute, reviewsSplitRoute } from '@app/routes/routes';import {createSearchParams,SplitRouter,useNavigate,useParams,-} from '@app/split-router';+} from '@app/lib/split-router';+import { reviewsPrRoute, reviewsSplitRoute } from '@app/routes/routes';import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';diff --git a/apps/web/src/features/reviews-view/route-views.tsx b/apps/web/src/features/reviews-view/route-views.tsxindex fd726840ed..24b34ca3ea 100644--- a/apps/web/src/features/reviews-view/route-views.tsx+++ b/apps/web/src/features/reviews-view/route-views.tsx@@ -1,6 +1,6 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useNavigate, useParams } from '@app/lib/split-router';import { tasksSplitRoute } from '@app/routes/routes';-import { useNavigate, useParams } from '@app/split-router';import {usePageViewTracking,withAuth,diff --git a/apps/web/src/features/settings/Settings.tsx b/apps/web/src/features/settings/Settings.tsxindex dc3823575a..f655ca3ea0 100644--- a/apps/web/src/features/settings/Settings.tsx+++ b/apps/web/src/features/settings/Settings.tsx@@ -1,4 +1,7 @@-import { useParams, useNavigate as useSplitNavigate } from '@app/split-router';+import {+ useParams,+ useNavigate as useSplitNavigate,+} from '@app/lib/split-router';import { PillTabs } from '@components/app/mobile/PillTabs';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';import {diff --git a/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsx b/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsxindex 59c4ac1ec3..ea457fbab2 100644--- a/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsx+++ b/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsx@@ -27,8 +27,8 @@ vi.mock('@app/components/view-shell', () => ({vi.mock('@app/components/entity-detail/EntityDetailBreadcrumbSkeleton', () => ({EntityDetailBreadcrumbSkeleton: () => null,}));-vi.mock('@app/split-router', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/split-router')>()),+vi.mock('@app/lib/split-router', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),useRouteParams: () => ({}),}));vi.mock('@service-storage/websocket', () => ({diff --git a/apps/web/src/features/tasks-view/components/TasksDetailView.tsx b/apps/web/src/features/tasks-view/components/TasksDetailView.tsxindex 43a2fe1c4f..405366d0db 100644--- a/apps/web/src/features/tasks-view/components/TasksDetailView.tsx+++ b/apps/web/src/features/tasks-view/components/TasksDetailView.tsx@@ -3,8 +3,8 @@ import type { EntityDetailTarget } from '@app/components/entity-detail/entity-deimport { useListNavigationHotkeys } from '@app/components/entity-detail/use-list-navigation-hotkeys';import { useListDetailNavigation } from '@app/components/list';import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';+import { useRouteParams } from '@app/lib/split-router';import { taskDetailRoute } from '@app/routes/routes';-import { useRouteParams } from '@app/split-router';import { MarkdownDetailBreadcrumbItem } from '@block-md/component/MarkdownDetailBreadcrumbItem';import { SidePanel } from '@components/app/side-panel';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';diff --git a/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx b/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsxindex cb871c5003..d1a3dac677 100644--- a/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx+++ b/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx@@ -1,6 +1,6 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useNavigate } from '@app/lib/split-router';import { reviewsSplitRoute } from '@app/routes/routes';-import { useNavigate } from '@app/split-router';import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';import { enableTasksReviews } from '@core/constant/featureFlags';import { type JSX, Show } from 'solid-js';diff --git a/apps/web/src/features/tasks-view/components/TasksSidebar.tsx b/apps/web/src/features/tasks-view/components/TasksSidebar.tsxindex 39bb3246c4..d596f9acae 100644--- a/apps/web/src/features/tasks-view/components/TasksSidebar.tsx+++ b/apps/web/src/features/tasks-view/components/TasksSidebar.tsx@@ -7,8 +7,8 @@ import { SidebarCreateHeader } from '@app/components/view-shell/SidebarCreateButimport { FavoriteContextMenu } from '@app/features/favorites/FavoriteContextMenu';import { FavoriteIcon } from '@app/features/favorites/FavoriteIcon';import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useNavigate } from '@app/lib/split-router';import { reviewsSplitRoute } from '@app/routes/routes';-import { useNavigate } from '@app/split-router';import {favoriteSplitContent,useFavoriteDisplayName,diff --git a/apps/web/src/features/tasks-view/route-views.tsx b/apps/web/src/features/tasks-view/route-views.tsxindex 4ca2c541c2..36f2a49749 100644--- a/apps/web/src/features/tasks-view/route-views.tsx+++ b/apps/web/src/features/tasks-view/route-views.tsx@@ -5,18 +5,18 @@ import {import { Projects } from '@app/features/projects/projects';import { ProjectTasksProvider } from '@app/features/projects/views/project-tasks-list';import { useFeatureFlag } from '@app/lib/analytics/posthog';-import {- projectDetailRoute,- projectTaskRoute,- tasksSplitRoute,-} from '@app/routes/routes';import {createSearchParams,SplitRouter,useNavigate,useParams,useRouteParams,-} from '@app/split-router';+} from '@app/lib/split-router';+import {+ projectDetailRoute,+ projectTaskRoute,+ tasksSplitRoute,+} from '@app/routes/routes';import { SidePanel } from '@components/app/side-panel';import {AppView,diff --git a/apps/web/src/features/tasks-view/route.test.tsx b/apps/web/src/features/tasks-view/route.test.tsxindex 8719733004..c07ff5fbed 100644--- a/apps/web/src/features/tasks-view/route.test.tsx+++ b/apps/web/src/features/tasks-view/route.test.tsx@@ -1,10 +1,3 @@-import {- projectDetailRoute,- projectTaskRoute,- taskDetailRoute,- tasksProjectsRoute,- tasksSplitRoute,-} from '@app/routes/routes';import {claimOf,createRoutesManifest,@@ -12,7 +5,14 @@ import {decodePane,formatPanePath,routeParams,-} from '@app/split-router';+} from '@app/lib/split-router';+import {+ projectDetailRoute,+ projectTaskRoute,+ taskDetailRoute,+ tasksProjectsRoute,+ tasksSplitRoute,+} from '@app/routes/routes';import { describe, expect, it, vi } from 'vitest';import { projectDetailSearch } from './project-detail-search';diff --git a/apps/web/src/features/tasks-view/tasks-tab-search.ts b/apps/web/src/features/tasks-view/tasks-tab-search.tsindex a478ea3d4f..0948ecb502 100644--- a/apps/web/src/features/tasks-view/tasks-tab-search.ts+++ b/apps/web/src/features/tasks-view/tasks-tab-search.ts@@ -1,4 +1,4 @@-import { createSearchParamsCodec } from '@app/split-router';+import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';import type { TasksTab } from './types';diff --git a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx b/apps/web/src/features/tasks-view/tasks-view-context.test.tsxindex 33d61c6e89..7a6fd5dd28 100644--- a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx+++ b/apps/web/src/features/tasks-view/tasks-view-context.test.tsx@@ -21,7 +21,7 @@ const mocks = vi.hoisted(() => ({dockOpen: (): boolean => false,dockText: (): string => '',}));-vi.mock('@app/split-router', () => ({+vi.mock('@app/lib/split-router', () => ({useNavigate: () => vi.fn(),useParams: () => ({}),createSearchParams: () => [diff --git a/apps/web/src/features/tasks-view/tasks-view-context.tsx b/apps/web/src/features/tasks-view/tasks-view-context.tsxindex 43d58dda83..084feb937f 100644--- a/apps/web/src/features/tasks-view/tasks-view-context.tsx+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx@@ -11,12 +11,16 @@ import { normalizeFacetSelection } from '@app/features/soup';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableProjects } from '@app/lib/core/constant/featureFlags';import { makePersistedState } from '@app/lib/persistence';+import {+ createSearchParams,+ useNavigate,+ useParams,+} from '@app/lib/split-router';import {taskDetailRoute,tasksProjectsRoute,tasksSplitRoute,} from '@app/routes/routes';-import { createSearchParams, useNavigate, useParams } from '@app/split-router';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';import {useSplitPanelOrThrow,diff --git a/apps/web/src/features/tasks-view/tasks-view.tsx b/apps/web/src/features/tasks-view/tasks-view.tsxindex 680c058553..5be280dec2 100644--- a/apps/web/src/features/tasks-view/tasks-view.tsx+++ b/apps/web/src/features/tasks-view/tasks-view.tsx@@ -2,8 +2,8 @@ import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';import { openProject } from '@app/features/projects/open-project';import { ProjectsTab } from '@app/features/projects/projects';import { ViewTour, ViewTourAction } from '@app/features/tours/ViewTour';+import { SplitRouter, useNavigate, useParams } from '@app/lib/split-router';import { projectDetailRoute } from '@app/routes/routes';-import { SplitRouter, useNavigate, useParams } from '@app/split-router';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';diff --git a/apps/web/src/lib/core/constant/SettingsState.test.tsx b/apps/web/src/lib/core/constant/SettingsState.test.tsxindex 5a379cb278..c16c0d6f36 100644--- a/apps/web/src/lib/core/constant/SettingsState.test.tsx+++ b/apps/web/src/lib/core/constant/SettingsState.test.tsx@@ -2,12 +2,12 @@ import {MobileSettingsProvider,useMobileSettings,} from '@app/features/settings/context/mobile-settings';-import { paneRoute } from '@app/routes/app-route';import {createMemoryHistory,createMemoryPaneStore,createSplitRouter,-} from '@app/split-router';+} from '@app/lib/split-router';+import { paneRoute } from '@app/routes/app-route';import {setActiveTabId as setSplitActiveTabId,activeTabId as splitActiveTabId,diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsxindex 1e32341a7a..fcfa6495b8 100644--- a/apps/web/src/lib/core/constant/SettingsState.tsx+++ b/apps/web/src/lib/core/constant/SettingsState.tsx@@ -1,9 +1,9 @@import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';import { toBaseRelative } from '@app/constants/routerBase';import { useMobileSettings } from '@app/features/settings/context/mobile-settings';+import { routeParams, type SplitLocation } from '@app/lib/split-router';import { paneRootMatch, paneRoute } from '@app/routes/app-route';import { globalSplitManager } from '@app/signal/splitLayout';-import { routeParams, type SplitLocation } from '@app/split-router';import { useSplitLayout } from '@components/app/split-layout/layout';import { isMobile } from '@core/mobile/isMobile';import { isTouchDevice } from '@core/mobile/isTouchDevice';diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.mddeleted file mode 100644index 302623984b..0000000000--- a/apps/web/src/lib/split-router/README.md+++ /dev/null@@ -1,203 +0,0 @@-# Split router--A standalone, route-only router for independently navigable panes. The host supplies-layout and external-location adapters; application content and resource lifecycles-stay outside this library.--## Ownership and routes--- Supply one static `SplitRoutes` declaration tree, or an explicit- `SplitRoutesManifest`. A router compiles its own manifest once and exposes it as- `router.routes`; there is no global runtime cache.-- `defineRoute()` infers node-local callback and synchronous Standard Schema- output types, including `remountKey`, and types descendant references relative- to that root. `defineRoutes()` assembles the static tree and rebinds ancestry.- Both attach a non-enumerable `to(params)` builder to route definitions in place.-- `toReference(params)` optionally describes the matched content as `{ type, id }`- for host consumers. The router does not interpret or invoke it during navigation.-- `useRouteParams(route)` reads only that node's params. `useParams(route)` reads- the merged branch through that node; `useParams()` still reads the entire- active branch.-- Matching follows declaration order, trying canonical patterns before aliases.- Schema and child failures backtrack. Formatting always uses canonical paths.-- Every accepted location has a nonempty, structurally valid match branch.- Resolve persisted/legacy data in the host adapter before returning snapshots.- Runtime schema outputs are not blindly revalidated as schema inputs.-- Nested outlets preserve component identity while their match remains stable.- Use `remountKey` for intentional resets.--## Typed nested routes--```ts-export const folder = defineRoute({- id: 'folder',- path: 'drive/folder/:folderId',- params: z.object({ folderId: z.string() }),- search: ['drive'],- children: [defineRoute({- id: 'document',- path: 'document/:documentId',- params: z.object({ documentId: z.string() }),- remountKey: ({ documentId }) => documentId,- })],-});-export const document = folder.children[0];-export const routes = defineRoutes({ definitions: [folder] });--navigate(document.to({ folderId: 'folder-1', documentId: 'document-1' }));-// Search remains a navigation option, not part of the route target:-navigate(document.to({ folderId: 'folder-1', documentId: 'document-1' }), {- search: { drive: { commentId: ['comment-1'] } },-});-const branch = useParams(document); // folderId + documentId-const local = useRouteParams(document); // documentId only-```--These helpers preserve the same route objects; they do not clone or compile the tree.-`to(params)` returns `{ route, params }` without serializing, validating, or-navigating. It is available on nested declarations and plain nodes assembled by-`defineRoutes()`. TypeScript enforces the complete destination params; navigation-validates them at runtime. Route identity is preserved while the builder is attached-in place. Ancestry metadata exists only in TypeScript. Export root definitions-directly and take descendant references through their named parent; positional-aliases from `routes.definitions` are unnecessary. A separately declared child-variable cannot acquire knowledge of a parent that later adopts it. Use `defineRoute`-at nodes with callbacks so schema outputs provide contextual parameter types.--Parent-bound destinations require the complete branch params, including when opening-another pane. A separately declared child reference knows only its own subtree and-may inherit matching ancestor values from the current pane. Explicit destination params override-those inherited values before each node's serializer runs. Serializers can therefore-receive additional branch fields; serialize the fields owned by that node. Transformed-outputs such as `Date` still require `serializeParams` and are not revalidated as inputs.--`InferSplitRouteParams` is node-local; `InferSplitRouteBranchParams` describes merged-reads; `InferSplitRouteNavigationParams` describes the flat destination bag.-`SplitRouteUnion<typeof routes>` collects references throughout a tree for destination-builders. `SplitRouteNavigationTarget<A | B>` keeps each route paired with its params.--Prefer distinct parameter names across ancestors and descendants, especially when-using claims, which receive the final merged bag. Reads honor child shadowing and-retain parent values when optional child fields are absent. Flat destinations must-satisfy every node's parameter types; incompatible shadows are rejected. Use path-navigation when repeated names need different values at different levels.--Without a schema, literal paths infer strings, optional strings, and `string[]` for-catch-all parameters. Reads include differently named alias params; destinations use-the canonical path's params. Renamed aliases need a schema or serializer that maps-those fields back to canonical names. Widened `string` paths retain untyped params.--## Search and history--- Raw query values are `Record<string, string[]>`; repeated values retain order.- Route namespaces are inherited. URL reads filter unowned namespaces, while- explicit writes reject them.-- `createSearchParams()` binds a synchronous Standard Schema to route-owned raw- search. `createSearchParamsCodec()` is the corresponding pure conversion API.-- Per-pane history belongs to the router. Numeric navigation traverses it;- external/browser history restores the complete positional layout.-- Clearing search retains the route. Ordinary unprefixed external/global search- keys remain distinct from namespaced split search.--### Route-owned entry state--A route may declare a synchronous Standard Schema as `state`. Descendants inherit-that schema unless they declare their own, so a view root can own history state for-its complete route branch. Typed route navigation infers the schema input and output,-and `useRouteState(route)` returns its parsed output. Since browser history stores a-structured clone of that output, schemas with different input/output shapes must also-accept their cloned output when restoring an entry.--Every accepted history entry has a stable router-generated `key`. State supplied to-navigation is parsed by the destination route and structured-cloned before the entry-is accepted. If cloning fails, navigation continues without state. Invalid local-navigation state throws. Invalid browser, persisted, or-host-layout state is discarded without rejecting the route. Middleware redirects-retain state only when it is accepted by the final route. A route without a state-schema cannot retain state.--A route navigation without state starts with no state. Every route navigation receives-a new key, whether it pushes or replaces the browser slot. Search-only writes preserve-already parsed state; a search push receives a new key while a search replacement-retains its key. Values read from entries are immutable snapshots and must not be-mutated.--`router.entry(splitId)` and history snapshots expose complete entries. Numeric-history traversal restores the exact stored entry. The external-location adapters round-trip visible entry keys and parsed state through a namespaced-field in browser `history.state`; the URL remains route-and-search only. Copied or-direct URLs therefore have no entry state, and views must provide a route-derived-fallback. Malformed or positionally mismatched browser metadata is ignored.--Host layout adapters own pane identity and the current location only. Entry keys,-route state, and per-pane history remain router-owned. Key/state-only navigation does-not write layout metadata or remount the view. Opening reports the pane that accepted-the requested location, or reports that no pane was available.--## Claims--A route may return `{ namespace, id }` from `claim(params)`. Providers are checked-from the deepest match toward the root; an undefined child claim allows ancestor-fallback. Claims identify resources independently of URL spelling and search.--### Acquisition policy--Explicit navigation, pane-history traversal, and search changes all check the-**final middleware-resolved destination**. An already accepted owner is activated-instead of committing the contender. The contender's pane and history cursor stay-unchanged. Activation cancels any pending departure of the accepted owner, keeping-that owner on the requested resource.--Changing search or route parameters without changing the target pane's current-claim is not a new acquisition. This preserves independently restored duplicates.-Initial, external, and host-layout reconciliation do not deduplicate entries.--`allowDuplicate` bypasses both accepted-owner checks and pending reservations,-including on numeric history navigation. It does not override duplicate policy in-the host layout. Claims currently cover panes within one router, not previews,-popovers, or other routers.--### Pending requests--Each entry transition tentatively reserves its proposed claim before middleware.-All contenders still run middleware: an original URL's owner must not prevent a-redirect to a different resource. Once the destination is resolved, the reservation-moves to the final claim, releasing the original one.--For a claim with no accepted owner, the first outstanding reservation gets the-first turn. Later contenders wait, then recheck accepted ownership after the prior-request commits, redirects, or exits. This avoids duplicate pending opens without-making completion timing choose the winner. A redirect joins the destination-claim's existing queue rather than jumping ahead.--Reservations are router-owned and released on completion, failure, cancellation,-supersession, layout replacement, or disposal. Cleanup belongs to the individual-transition, so a stale completion cannot release a newer reservation. Middleware-that ignores abort cannot commit after cancellation. Calls after disposal are-ignored.--## Middleware and errors--Middleware runs for proposed entries and may redirect synchronously or-asynchronously. Synchronous navigation stays synchronous when no reservation wait-is necessary. Signals cancel superseded work; middleware should honor them when-possible. For initial and external navigation, `externalSearch` contains the raw-incoming URL query snapshot, unchanged across redirects. Use it for application-compatibility normalization; `to.location.search` remains the proposed pane's-namespaced search. Local navigation does not inherit stale external query data.--Ordinary middleware errors are logged and fall back to the original valid-proposal, which still passes claim arbitration. Abort errors do not fall back.-Malformed proposals cannot enter accepted layout/history state. Async transition-failures are logged and release their reservations.--## Modules--- `routes.ts`, `path.ts`: manifest, matching, params, ownership, and claim derivation.-- `router.ts`, `transitions.ts`, `claims.ts`: orchestration, cancellation, pending claims.-- `history.ts`, `layout.ts`, `location-sync.ts`: pane history and host boundaries.-- `entry-state.ts`: entry identity and browser-history state envelopes.-- `url.ts`, `search.ts`: URL framing and raw search state.-- `search-params-codec.ts`, `create-search-params.ts`: typed search conversion/binding.-- `solid.tsx`: providers, hooks, and nested outlets.-- `integrations/`: memory and Solid Router external-location adapters.diff --git a/apps/web/src/lib/split-router/claims.ts b/apps/web/src/lib/split-router/claims.tsdeleted file mode 100644index 80897ffe2b..0000000000--- a/apps/web/src/lib/split-router/claims.ts+++ /dev/null@@ -1,84 +0,0 @@-import type { SplitRouteClaim } from './types';-import { throwIfAborted } from './utils';--export type ClaimReservation = {- move(claim: SplitRouteClaim | undefined): void;- wait(signal: AbortSignal): void | Promise<void>;- release(): void;-};--/** Pending ownership only. Accepted ownership is read from the host layout. */-export function createClaimReservations() {- type Slot = { key?: string; released: boolean };- const queues = new Map<string, Set<Slot>>();- const listeners = new Set<() => void>();- const notify = () => {- for (const listener of [...listeners]) listener();- };- const remove = (slot: Slot) => {- if (slot.key === undefined) return;- const queue = queues.get(slot.key);- queue?.delete(slot);- if (queue?.size === 0) queues.delete(slot.key);- slot.key = undefined;- };-- return {- reserve(claim: SplitRouteClaim | undefined): ClaimReservation {- const slot: Slot = { released: false };- const ownsTurn = () =>- slot.key === undefined ||- queues.get(slot.key)?.values().next().value === slot;- const reservation: ClaimReservation = {- move(next) {- if (slot.released) return;- const key = next- ? JSON.stringify([next.namespace, next.id])- : undefined;- if (key === slot.key) return;- remove(slot);- if (key !== undefined) {- const queue = queues.get(key) ?? new Set<Slot>();- queue.add(slot);- queues.set(key, queue);- slot.key = key;- }- notify();- },- wait(signal) {- throwIfAborted(signal);- if (ownsTurn()) return;- return new Promise<void>((resolve, reject) => {- const cleanup = () => {- listeners.delete(check);- signal.removeEventListener('abort', abort);- };- const abort = () => {- cleanup();- reject(- signal.reason ?? new DOMException('Aborted', 'AbortError')- );- };- const check = () => {- if (signal.aborted) return abort();- if (!ownsTurn()) return;- cleanup();- resolve();- };- listeners.add(check);- signal.addEventListener('abort', abort, { once: true });- check();- });- },- release() {- if (slot.released) return;- slot.released = true;- remove(slot);- notify();- },- };- reservation.move(claim);- return reservation;- },- };-}diff --git a/apps/web/src/lib/split-router/create-search-params.ts b/apps/web/src/lib/split-router/create-search-params.tsdeleted file mode 100644index e7e9001dbc..0000000000--- a/apps/web/src/lib/split-router/create-search-params.ts+++ /dev/null@@ -1,76 +0,0 @@-import deepEqual from 'fast-deep-equal';-import { createEffect, createMemo, on } from 'solid-js';-import {- createSearchParamsCodec,- type SearchParamsCodecOptions,- type SearchParamsRecord,-} from './search-params-codec';-import { useSplitRouterScope, useSplitRouterState } from './solid';-import type { BrowserHistoryIntent } from './types';-import { reactiveRecord } from './utils';--export type CreateSearchParamsOptions<T extends SearchParamsRecord> =- SearchParamsCodecOptions<T> & { namespace: string };--export type SetSearchParamsOptions = {- mode?: 'merge' | 'replace';- history?: BrowserHistoryIntent;-};--export type SearchParamsPatch<T extends SearchParamsRecord> = {- [Key in keyof T]?: T[Key] | undefined;-};--export type SetSearchParams<T extends SearchParamsRecord> = (- next: SearchParamsPatch<T> | ((current: T) => SearchParamsPatch<T>),- options?: SetSearchParamsOptions-) => void;--export function createSearchParams<T extends SearchParamsRecord>(- options: CreateSearchParamsOptions<T>-): [T, SetSearchParams<T>] {- const { router, search } = useSplitRouterState<unknown>();- const splitId = useSplitRouterScope<unknown>();- const codec = createSearchParamsCodec(options);- const raw = () => search(splitId(), options.namespace);- const parsed = createMemo(() => codec.parse(raw()));-- createEffect(- on([parsed, raw], ([current, rawParams]) => {- const canonical = current.valid- ? codec.serialize(current.value)- : undefined;- if (deepEqual(rawParams, canonical)) return;- router.updateSearch(splitId(), options.namespace, canonical, {- history: 'replace',- });- })- );-- const setParams: SetSearchParams<T> = (next, setOptions = {}) => {- const previous = parsed().value;- const patch = typeof next === 'function' ? next(previous) : next;- const candidate: SearchParamsRecord = {- ...(setOptions.mode === 'replace' ? options.defaults : previous),- };- for (const [key, value] of Object.entries(patch)) {- candidate[key] = value === undefined ? options.defaults[key] : value;- }- const nextValue = codec.validate(candidate);- if (!nextValue.success) {- console.error(- `Invalid search params for namespace "${options.namespace}"`,- nextValue.error- );- return;- }- router.updateSearch(- splitId(),- options.namespace,- codec.serialize(nextValue.data),- { history: setOptions.history }- );- };-- return [reactiveRecord(() => parsed().value), setParams];-}diff --git a/apps/web/src/lib/split-router/entry-state.ts b/apps/web/src/lib/split-router/entry-state.tsdeleted file mode 100644index 135d2ebdb2..0000000000--- a/apps/web/src/lib/split-router/entry-state.ts+++ /dev/null@@ -1,75 +0,0 @@-import type { SplitRouterEntry, SplitRouterEntryState } from './types';-import { isRecord } from './utils';--const SPLIT_ROUTER_BROWSER_STATE_KEY = '__macroSplitRouter';--type BrowserEntryState = {- key: string;- state?: SplitRouterEntryState;-};--type BrowserRouterState = {- entries: BrowserEntryState[];-};--let fallbackKeySequence = 0;--export function createEntryKey(): string {- const randomId = globalThis.crypto?.randomUUID?.();- if (randomId) return `split-router:${randomId}`;-- fallbackKeySequence += 1;- return `split-router:${Date.now().toString(36)}:${fallbackKeySequence.toString(36)}`;-}--export function parseBrowserEntries(- state: unknown-): BrowserEntryState[] | undefined {- if (!isRecord(state)) return;-- const value = state[SPLIT_ROUTER_BROWSER_STATE_KEY];- if (!isRecord(value) || !Array.isArray(value.entries)) return;-- const entries: BrowserEntryState[] = [];- for (const candidate of value.entries) {- if (!isRecord(candidate) || typeof candidate.key !== 'string') return;-- const entry: BrowserEntryState = { key: candidate.key };- if (Object.hasOwn(candidate, 'state')) {- entry.state = candidate.state as SplitRouterEntryState;- }- entries.push(entry);- }- return entries;-}--export function mergeBrowserEntries(- previous: unknown,- entries: readonly SplitRouterEntry[]-): unknown {- const result = isRecord(previous) ? { ...previous } : {};- const browserEntries: BrowserEntryState[] = [];-- for (const entry of entries) {- if (!entry.key) {- delete result[SPLIT_ROUTER_BROWSER_STATE_KEY];- if (Object.keys(result).length === 0) return;- return result;- }-- const browserEntry: BrowserEntryState = { key: entry.key };- if (Object.hasOwn(entry, 'state')) browserEntry.state = entry.state;- browserEntries.push(browserEntry);- }-- const routerState: BrowserRouterState = { entries: browserEntries };- result[SPLIT_ROUTER_BROWSER_STATE_KEY] = routerState;- return result;-}--export function browserEntryKeySignature(state: unknown): string {- const entries = parseBrowserEntries(state);- if (!entries) return '';-- return JSON.stringify(entries.map(({ key }) => key));-}diff --git a/apps/web/src/lib/split-router/history.ts b/apps/web/src/lib/split-router/history.tsdeleted file mode 100644index 72c5a37f00..0000000000--- a/apps/web/src/lib/split-router/history.ts+++ /dev/null@@ -1,136 +0,0 @@-export type SplitRouterHistory<TEntry> = {- entries(): readonly TEntry[];- index(): number;- current(): TEntry;- canGo(delta: number): boolean;- peek(delta: number): TEntry | undefined;- go(delta: number): boolean;- push(entry: TEntry): boolean;- replace(entry: TEntry): boolean;- accept(entry: TEntry, intent: 'push' | 'replace'): boolean;-};--export function createSplitRouterHistory<TEntry>(- initial: TEntry,- equals: (left: TEntry, right: TEntry) => boolean,- sameIdentity: (left: TEntry, right: TEntry) => boolean = equals-): SplitRouterHistory<TEntry> {- let items = [initial];- let currentIndex = 0;-- const targetIndex = (delta: number) => {- if (!Number.isSafeInteger(delta) || delta === 0) return;-- const target = currentIndex + delta;- return target >= 0 && target < items.length ? target : undefined;- };-- return {- entries: () => items,- index: () => currentIndex,- current: () => items[currentIndex]!,-- canGo(delta) {- return targetIndex(delta) !== undefined;- },-- peek(delta) {- const target = targetIndex(delta);- return target === undefined ? undefined : items[target];- },-- go(delta) {- const target = targetIndex(delta);- if (target === undefined) return false;-- currentIndex = target;- return true;- },-- push(entry) {- if (equals(items[currentIndex]!, entry)) return false;-- items = [...items.slice(0, currentIndex + 1), entry];- currentIndex = items.length - 1;- return true;- },-- replace(entry) {- if (equals(items[currentIndex]!, entry)) return false;-- items = items.with(currentIndex, entry);- return true;- },-- accept(entry, intent) {- if (equals(items[currentIndex]!, entry)) return false;-- const existingIndex = items.findIndex((candidate) =>- sameIdentity(candidate, entry)- );- if (existingIndex >= 0) {- items = items.with(existingIndex, entry);- currentIndex = existingIndex;- return true;- }-- if (intent === 'replace') {- items = items.with(currentIndex, entry);- } else {- items = [...items.slice(0, currentIndex + 1), entry];- currentIndex = items.length - 1;- }- return true;- },- };-}--export function createSplitRouterHistories<TId, TEntry>(- equals: (left: TEntry, right: TEntry) => boolean,- sameIdentity: (left: TEntry, right: TEntry) => boolean = equals-) {- const histories = new Map<TId, SplitRouterHistory<TEntry>>();- let order: TId[] = [];-- return {- get: (id: TId) => histories.get(id),-- reconcile(- entries: readonly { id: TId; entry: TEntry }[],- intent: 'push' | 'replace',- mode: 'move' | 'write'- ) {- const liveIds = new Set(entries.map(({ id }) => id));- const nextOrder = entries.map(({ id }) => id);-- entries.forEach(({ id, entry }, index) => {- let history = histories.get(id);-- if (!history) {- const previousId = order[index];- if (previousId !== undefined && !liveIds.has(previousId)) {- history = histories.get(previousId);- histories.delete(previousId);- if (history) histories.set(id, history);- }- }-- if (history) {- if (mode === 'move') history.accept(entry, intent);- else if (intent === 'replace') history.replace(entry);- else history.push(entry);- } else {- histories.set(- id,- createSplitRouterHistory(entry, equals, sameIdentity)- );- }- });-- for (const id of histories.keys()) {- if (!liveIds.has(id)) histories.delete(id);- }- order = nextOrder;- },- };-}diff --git a/apps/web/src/lib/split-router/next/history/browser.ts b/apps/web/src/lib/split-router/history/browser.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/history/browser.tsrename to apps/web/src/lib/split-router/history/browser.tsdiff --git a/apps/web/src/lib/split-router/next/history/memory.ts b/apps/web/src/lib/split-router/history/memory.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/history/memory.tsrename to apps/web/src/lib/split-router/history/memory.tsdiff --git a/apps/web/src/lib/split-router/next/history/shared.ts b/apps/web/src/lib/split-router/history/shared.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/history/shared.tsrename to apps/web/src/lib/split-router/history/shared.tsdiff --git a/apps/web/src/lib/split-router/next/history/solid-router.ts b/apps/web/src/lib/split-router/history/solid-router.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/history/solid-router.tsrename to apps/web/src/lib/split-router/history/solid-router.tsdiff --git a/apps/web/src/lib/split-router/next/history/types.ts b/apps/web/src/lib/split-router/history/types.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/history/types.tsrename to apps/web/src/lib/split-router/history/types.tsdiff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.tsindex 99ad75c879..05ccb52b3b 100644--- a/apps/web/src/lib/split-router/index.ts+++ b/apps/web/src/lib/split-router/index.ts@@ -1,136 +1,129 @@-import { SplitRouter as SplitRouterComponents } from './solid';-import type { SplitRouter as SplitRouterContract } from './types';--export type SplitRouter<TSplitId> = SplitRouterContract<TSplitId>;--export const SplitRouter = SplitRouterComponents;-export {- type CreateSearchParamsOptions,- createSearchParams,- type SetSearchParams,- type SetSearchParamsOptions,-} from './create-search-params';+ type BrowserHistoryOptions,+ createBrowserHistory,+} from './history/browser';+export { createMemoryHistory, type MemoryHistory } from './history/memory';export {- createMemorySplitRouterLocation,- type MemorySplitRouterLocation,-} from './integrations/memory';+ createSolidRouterHistory,+ type SolidRouterHistoryOptions,+ useSolidRouterHistory,+} from './history/solid-router';+export type {+ ExternalChange,+ HistoryAdapter,+ InterceptHandler,+} from './history/types';+export { createMemoryPaneStore } from './panes/memory-store';+export type {+ OpenIntent,+ OpenTarget,+ PaneStore,+ Placement,+} from './panes/types';+export type { ClaimHolder } from './router/claims';+export { createSplitRouter } from './router/create-router';+export { PANE_LEVEL } from './router/leave-guards';+export type {+ SplitRouterMiddleware,+ SplitRouterMiddlewareContext,+ SplitRouterMiddlewareResult,+} from './router/middleware';+export type { PendingNavigation } from './router/runner';+export type {+ ClaimOwner,+ LeaveGuard,+ LeaveGuardContext,+ NavigationCause,+ NavigationResult,+ RouteMatchInfo,+ SplitCloseAction,+ SplitNavigateOptions,+ SplitPanePolicy,+ SplitRouterOptions,+} from './router/types';export {- createSolidRouterLocation,- type SolidRouterLocationOptions,-} from './integrations/solid-router';-export { runSplitRouterMiddleware } from './middleware';-export type { RoutePattern } from './path';-export { createSplitRouter } from './router';+ formatLocation,+ formatPanePath,+ parseLocation,+ splitPanePaths,+} from './routes/codec';+export { defineRoute, defineRoutes } from './routes/define';export {+ canonicalRoute,createRoutesManifest,- decodeRoute,- defineRoute,- defineRoutes,- encodeRoute,+ decodePane,+ type SplitRoutesManifest,+} from './routes/manifest';+export { decodeSegment } from './routes/path';+export {+ claimOf,+ externalSearchKeys,filterRouteSearch,- getExternalSearchKeys,- getRouteClaim,- getRouteEntryState,- getRouteId,- getRouteSearchNamespaces,- parseRouteEntryState,- type RouteParamsCodec,- resolveRouteBranch,- rootRouteMatch,routeParams,- type SplitRouteNode,- type SplitRoutesManifest,- validateSplitRoutes,-} from './routes';+} from './routes/queries';+export { replacePaneSearchParams } from './routes/search';export {createSearchParamsCodec,type SearchParamsCodec,type SearchParamsCodecOptions,- type SearchParamsDeserializer,- type SearchParamsSchema,- type SearchParamsSerializer,-} from './search-params-codec';-export {- Outlet,- Root,- Scope,- type SplitRouterOutletProps,- type SplitRouterRootProps,- type SplitRouterScopeProps,- useCanGo,- useNavigate,- useOptionalSplitRouter,- useOwnsSearchNamespace,- useParams,- useRouteParams,- useRouteState,- useSplitHistory,- useSplitRouter,-} from './solid';+ takeLast,+} from './routes/search-params';export type {- BrowserHistoryIntent,DefinedSplitRoute,DefinedSplitRoutes,+ Entry,+ ExternalLocation,InferSplitRouteBranchParams,InferSplitRouteNavigationParams,InferSplitRouteParams,InferSplitRouteState,InferSplitRouteStateInput,+ PaneArrival,+ PaneId,+ PreloadIntent,SerializedSearchParams,SplitLocation,- SplitNavigate,- SplitNavigateOptions,- SplitNavigateTo,- SplitNonRouteNavigateTo,- SplitParentNavigationTarget,+ SplitNavigationTarget,SplitReference,SplitRouteClaim,SplitRouteDefinition,+ SplitRouteInfo,SplitRouteMatch,- SplitRouteNavigateOptions,SplitRouteNavigationTarget,SplitRouteParams,- SplitRouteRawParams,- SplitRouterEntry,- SplitRouterEntryState,- SplitRouterExternalLocation,- SplitRouterExternalLocationValue,- SplitRouterHistorySnapshot,- SplitRouterLayout,- SplitRouterLayoutEntry,- SplitRouterLayoutOpenResult,- SplitRouterLayoutSnapshot,- SplitRouterMiddleware,- SplitRouterMiddlewareConfig,- SplitRouterMiddlewareContext,- SplitRouterMiddlewareRedirect,- SplitRouterMiddlewareRequest,- SplitRouterMiddlewareResult,- SplitRouterMiddlewareRun,- SplitRouterNavigationCause,- SplitRouterOptions,- SplitRouterSettledChange,- SplitRouterStateUpdate,SplitRouteState,SplitRoutes,SplitRouteUnion,SplitSearchState,SplitSearchUpdate,- SplitSearchUpdateOptions,- UnmatchedSplitPathContext,- UnmatchedSplitPathHandler,-} from './types';+ WriteMode,+} from './routes/types';+export { useOptionalSplitRouter, useSplitRouter } from './solid/context';+export {+ type CreateSearchParamsOptions,+ createSearchParams,+ type SetSearchParams,+} from './solid/create-search-params';export {- type DecodedSplitRouterLocation,- decodeRouteLayout,- decodeSplitRouterLocation,- encodeRouteLayout,- externalLocationToString,- formatRoutePathname,- parseExternalLocation,- parseRoutePathname,- SPLIT_PATH_SEPARATOR,- serializeSplitRouterLocation,-} from './url';-export { isSafeName, takeLast } from './utils';+ type SplitNavigate,+ type SplitRouteNavigateOptions,+ useArrival,+ useCanGo,+ useEntryProps,+ useMatches,+ useNavigate,+ useOwnsSearchNamespace,+ usePane,+ usePaneHistory,+ useParams,+ usePendingNavigation,+ useRouteParams,+ useRouteState,+} from './solid/hooks';+export type { OutletProps } from './solid/outlet';+export type { RouteProps } from './solid/route';+export type { RouterProps } from './solid/router';+export { SplitRouter } from './solid/split-router';+export { useBeforeLeave } from './solid/use-before-leave';+export { useClaim } from './solid/use-claim';+export { isRecord, isSafeName } from './utils';diff --git a/apps/web/src/lib/split-router/integrations/memory.ts b/apps/web/src/lib/split-router/integrations/memory.tsdeleted file mode 100644index 3ec6ef3b5e..0000000000--- a/apps/web/src/lib/split-router/integrations/memory.ts+++ /dev/null@@ -1,87 +0,0 @@-import type {- SplitRouterExternalLocation,- SplitRouterExternalLocationValue,-} from '../types';-import { parseExternalLocation } from '../url';--export interface MemorySplitRouterLocation extends SplitRouterExternalLocation {- history(): SplitRouterExternalLocationValue[];- index(): number;- back(): boolean;- forward(): boolean;- set(- location: string | SplitRouterExternalLocationValue,- options?: { replace?: boolean }- ): void;-}--export function createMemorySplitRouterLocation(- initial: string | SplitRouterExternalLocationValue = '/'-): MemorySplitRouterLocation {- let entries = [parseExternalLocation(initial)];- let currentIndex = 0;- const listeners = new Set<- (location: SplitRouterExternalLocationValue) => void- >();-- const notify = () => {- const current = entries[currentIndex]!;-- for (const listener of listeners) listener(current);- };-- const commit = (- location: SplitRouterExternalLocationValue,- replace: boolean- ) => {- const next = parseExternalLocation(location);-- if (replace) {- entries = entries.with(currentIndex, next);- } else {- entries = [...entries.slice(0, currentIndex + 1), next];- currentIndex++;- }-- notify();- };-- return {- read: () => entries[currentIndex]!,-- subscribe(listener) {- listeners.add(listener);-- return () => listeners.delete(listener);- },-- commit(location, options) {- commit(location, options.history === 'replace');- },-- history: () => entries,- index: () => currentIndex,-- back() {- if (currentIndex === 0) return false;-- currentIndex--;- notify();-- return true;- },-- forward() {- if (currentIndex >= entries.length - 1) return false;-- currentIndex++;- notify();-- return true;- },-- set(location, options = {}) {- commit(parseExternalLocation(location), options.replace ?? false);- },- };-}diff --git a/apps/web/src/lib/split-router/integrations/solid-router.ts b/apps/web/src/lib/split-router/integrations/solid-router.tsdeleted file mode 100644index b140a8f2ac..0000000000--- a/apps/web/src/lib/split-router/integrations/solid-router.ts+++ /dev/null@@ -1,112 +0,0 @@-import {- type Accessor,- createEffect,- createRoot,- on,- onCleanup,- untrack,-} from 'solid-js';-import { externalLocationSignature } from '../location-sync';-import type {- SplitRouterExternalLocation,- SplitRouterExternalLocationValue,-} from '../types';-import { externalLocationToString } from '../url';--export type SolidRouterLocationOptions = {- pathname: Accessor<string>;- search?: Accessor<string>;- hash?: Accessor<string>;- state?: Accessor<unknown>;- navigate: (- to: string,- options: { replace: boolean; state?: unknown }- ) => unknown;-};--/**- * Adapts reactive location accessors without depending on app components or- * on a particular Solid Router location object.- */-export function createSolidRouterLocation(- options: SolidRouterLocationOptions-): SplitRouterExternalLocation {- const pendingCommits = new Set<ReturnType<typeof setTimeout>>();- const dispatchedCommits: string[] = [];- let subscriptions = 0;- const read = (): SplitRouterExternalLocationValue => {- const location: SplitRouterExternalLocationValue = {- pathname: options.pathname(),- search: options.search?.() ?? '',- hash: options.hash?.() ?? '',- };- if (options.state) location.state = options.state();- return location;- };- let observedSignature = externalLocationSignature(untrack(read));- const cancelPendingCommits = () => {- for (const timer of pendingCommits) clearTimeout(timer);- pendingCommits.clear();- };-- return {- read,-- subscribe(listener) {- if (subscriptions === 0) {- // The location may have changed while no subscribers were observing it.- observedSignature = externalLocationSignature(untrack(read));- }- subscriptions += 1;- return createRoot((dispose) => {- onCleanup(() => {- subscriptions -= 1;- if (subscriptions > 0) return;- cancelPendingCommits();- dispatchedCommits.length = 0;- });- createEffect(- on(- () => externalLocationSignature(read()),- (signature) => {- // Process each change once even when several subscribers observe it.- if (signature !== observedSignature) {- observedSignature = signature;- const index = dispatchedCommits.lastIndexOf(signature);- if (index >= 0) {- // An echo of our own navigation must not cancel newer writes.- dispatchedCommits.splice(0, index + 1);- } else {- // Back/Forward or another navigator supersedes queued writes.- cancelPendingCommits();- dispatchedCommits.length = 0;- }- }- listener(read());- },- { defer: true }- )- );-- return dispose;- });- },-- commit(location, commitOptions) {- // Zone.js, used for tracing, wraps focus event handlers and can run queued- // microtasks when those handlers finish. Navigating immediately can let- // Solid Router's transition start before the split finishes mounting,- // leaving onMount callbacks unrun and the preview blank. Defer navigation- // to the next event-loop task so the current mount can finish first.- const timer = setTimeout(() => {- pendingCommits.delete(timer);- dispatchedCommits.push(externalLocationSignature(location));- options.navigate(externalLocationToString(location), {- replace: commitOptions.history === 'replace',- state: location.state,- });- }, 0);- pendingCommits.add(timer);- },- };-}diff --git a/apps/web/src/lib/split-router/layout.ts b/apps/web/src/lib/split-router/layout.tsdeleted file mode 100644index b9a4a9bc7a..0000000000--- a/apps/web/src/lib/split-router/layout.ts+++ /dev/null@@ -1,171 +0,0 @@-import deepEqual from 'fast-deep-equal';-import { assertRouteEntry, type SplitRoutesManifest } from './routes';-import type {- SplitRouterEntry,- SplitRouterLayout,- SplitRouterLayoutEntry,-} from './types';--export function createLayoutAdapter<TSplitId>(- layout: SplitRouterLayout<TSplitId>,- routes: SplitRoutesManifest-) {- const snapshot = () => {- const value = layout.snapshot();- for (const entry of value.entries) assertRouteEntry(routes, entry);- return value;- };- const entries = (): SplitRouterEntry[] =>- snapshot().entries.map(({ splitId: _splitId, ...entry }) => entry);-- const find = (- splitId: TSplitId- ): SplitRouterLayoutEntry<TSplitId> | undefined =>- snapshot().entries.find((entry) => Object.is(entry.splitId, splitId));-- const entryEquals = (- left: SplitRouterEntry | undefined,- right: SplitRouterEntry | undefined- ): boolean => {- if (left === right) return true;- if (!left || !right) return false;- if (left.key !== right.key) return false;- if (!deepEqual(left.location, right.location)) return false;- return Object.is(left.state, right.state);- };-- const entryIdentityEquals = (- left: SplitRouterEntry,- right: SplitRouterEntry- ): boolean => {- if (left.key !== undefined && right.key !== undefined) {- return left.key === right.key;- }- return deepEqual(left.location, right.location);- };-- const layoutsEqual = (- left: SplitRouterEntry[],- right: SplitRouterEntry[]- ): boolean =>- left.length === right.length &&- left.every((entry, index) =>- deepEqual(entry.location, right[index]?.location)- );-- const snapshotsEqual = (- left: SplitRouterLayoutEntry<TSplitId>[],- right: SplitRouterLayoutEntry<TSplitId>[]- ) =>- left.length === right.length &&- left.every((entry, index) => {- const candidate = right[index];- return (- candidate !== undefined &&- Object.is(entry.splitId, candidate.splitId) &&- deepEqual(entry.location, candidate.location)- );- });-- const changedIds = (- before: SplitRouterEntry[],- after: SplitRouterEntry[]- ): Set<TSplitId> => {- const visible = snapshot().entries;- const changed = new Set<TSplitId>();-- after.forEach((entry, index) => {- if (deepEqual(before[index]?.location, entry.location)) return;-- const splitId = visible[index]?.splitId;- if (splitId !== undefined) changed.add(splitId);- });-- return changed;- };-- const reconcile = (- current: SplitRouterEntry[],- requested: SplitRouterEntry[]- ): boolean => {- for (const entry of requested) assertRouteEntry(routes, entry);- if (layoutsEqual(current, requested)) return false;-- layout.reconcile(requested.map((entry) => entry.location));- return true;- };-- const apply = (options: {- open?: SplitRouterLayout<TSplitId>['open'];- entry: SplitRouterEntry;- target: TSplitId | 'new-split';- replace: boolean;- requireExistingTarget?: boolean;- }): { changed: boolean; layoutChanged: boolean; splitId?: TSplitId } => {- assertRouteEntry(routes, options.entry);- let targetId: TSplitId | undefined;- let current: SplitRouterLayoutEntry<TSplitId> | undefined;- if (options.target !== 'new-split') {- targetId = options.target;- current = find(targetId);- }-- if (options.requireExistingTarget && !current) {- return { changed: false, layoutChanged: false };- }-- if (!options.open && targetId !== undefined && current) {- if (deepEqual(current.location, options.entry.location)) {- return { changed: true, layoutChanged: false, splitId: targetId };- }-- layout.updateCurrentLocation(- targetId,- () => options.entry.location,- options.replace- );- const applied = find(targetId);- if (!deepEqual(applied?.location, options.entry.location)) {- throw new Error('Split layout did not apply the requested location');- }- return { changed: true, layoutChanged: true, splitId: targetId };- }-- const before = snapshot().entries;- const result = (options.open ?? layout.open)({- location: options.entry.location,- target: options.target,- replace: options.replace,- });- if (result.status === 'unavailable') {- return { changed: false, layoutChanged: false };- }-- const after = snapshot().entries;- const applied = after.find((entry) =>- Object.is(entry.splitId, result.splitId)- );- if (!deepEqual(applied?.location, options.entry.location)) {- throw new Error('Split layout did not apply the requested location');- }- return {- changed: true,- layoutChanged: !snapshotsEqual(before, after),- splitId: result.splitId,- };- };-- return {- activate: (splitId: TSplitId) => layout.activate(splitId),- apply,- changedIds,- entries,- entryEquals,- entryIdentityEquals,- find,- layoutsEqual,- reconcile,- snapshot,- snapshotsEqual,- };-}diff --git a/apps/web/src/lib/split-router/location-sync.ts b/apps/web/src/lib/split-router/location-sync.tsdeleted file mode 100644index 3965e5f0c0..0000000000--- a/apps/web/src/lib/split-router/location-sync.ts+++ /dev/null@@ -1,107 +0,0 @@-import { browserEntryKeySignature } from './entry-state';-import type { SplitRoutesManifest } from './routes';-import type {- BrowserHistoryIntent,- SplitRouterEntry,- SplitRouterExternalLocation,- SplitRouterExternalLocationValue,-} from './types';-import { encodeSplitRouterLocation } from './url';--export function externalLocationSignature(- location: SplitRouterExternalLocationValue-): string {- const query = [...new URLSearchParams(location.search)].sort(- ([leftKey, leftValue], [rightKey, rightValue]) => {- if (leftKey === rightKey) return leftValue.localeCompare(rightValue);- return leftKey.localeCompare(rightKey);- }- );- let pathname = location.pathname || '/';- if (location.pathname.length > 1) {- pathname = location.pathname.replace(/\/+$/g, '');- }-- return JSON.stringify([- pathname,- query,- location.hash,- browserEntryKeySignature(location.state),- ]);-}--export type LocationSync = {- acknowledge(location: SplitRouterExternalLocationValue): boolean;- commit(- entries: SplitRouterEntry[],- options: {- history: BrowserHistoryIntent;- preserveHash: boolean;- preserveExternalSearch?: boolean;- }- ): void;-};--export function createLocationSync(options: {- routes: SplitRoutesManifest;- location: SplitRouterExternalLocation;-}): LocationSync {- const outbound: string[] = [];- let desired = options.location.read();-- const commitExternal = (- next: SplitRouterExternalLocationValue,- history: BrowserHistoryIntent- ) => {- const signature = externalLocationSignature(next);-- if (- (outbound.length === 0 &&- signature === externalLocationSignature(options.location.read())) ||- outbound.at(-1) === signature- ) {- return;- }-- outbound.push(signature);- options.location.commit(next, { history });- };-- return {- acknowledge(external) {- const signature = externalLocationSignature(external);- const index = outbound.lastIndexOf(signature);-- if (index < 0) {- outbound.length = 0;- return false;- }-- // Location adapters may coalesce writes (last transition wins). Once a- // newer write is observed, earlier signatures cannot remain echo tokens:- // a later Back to one of those URLs is genuine external navigation.- outbound.splice(0, index + 1);-- const desiredSignature = externalLocationSignature(desired);- if (- signature !== desiredSignature &&- !outbound.includes(desiredSignature)- ) {- commitExternal(desired, 'replace');- }-- return true;- },-- commit(entries, commitOptions) {- desired = encodeSplitRouterLocation({- routes: options.routes,- entries,- previous: options.location.read(),- preserveHash: commitOptions.preserveHash,- preserveExternalSearch: commitOptions.preserveExternalSearch,- });- commitExternal(desired, commitOptions.history);- },- };-}diff --git a/apps/web/src/lib/split-router/middleware.ts b/apps/web/src/lib/split-router/middleware.tsdeleted file mode 100644index 0d03fe5897..0000000000--- a/apps/web/src/lib/split-router/middleware.ts+++ /dev/null@@ -1,178 +0,0 @@-import { resolveNavigation } from './navigation';-import {- assertRouteEntry,- encodeRoute,- type SplitRoutesManifest,-} from './routes';-import type {- SplitLocation,- SplitRouterEntry,- SplitRouterMiddlewareConfig,- SplitRouterMiddlewareRequest,- SplitRouterMiddlewareResult,- SplitRouterMiddlewareRun,-} from './types';-import { formatRoutePathname } from './url';-import { isAbortError, isPromise, throwIfAborted } from './utils';--type BatchRequest = {- from?: readonly SplitRouterEntry[];- to: SplitRouterEntry[];- cause: SplitRouterMiddlewareRequest['cause'];- externalSearch?: string;- signal: AbortSignal;-};--type PreparedEntries = SplitRouterEntry[] | Promise<SplitRouterEntry[]>;--function withSearch(- entry: SplitRouterEntry,- search: SplitLocation['search']-): SplitRouterEntry {- if (!search || entry.location.search) return entry;-- return {- ...entry,- location: {- ...entry.location,- search,- },- };-}--function entryPath(- routes: SplitRoutesManifest,- entry: SplitRouterEntry-): string {- return formatRoutePathname(routes, encodeRoute(routes, entry));-}--/**- * Runs one proposed entry through middleware, following redirects safely.- * Remains synchronous until a middleware actually returns a Promise.- */-export function runSplitRouterMiddleware(- config: SplitRouterMiddlewareConfig,- request: SplitRouterMiddlewareRequest-): SplitRouterMiddlewareRun {- const visited = new Set<string>();-- const runEntry = (current: SplitRouterEntry): SplitRouterMiddlewareRun => {- throwIfAborted(request.signal);- assertRouteEntry(config.routes, current);-- const path = entryPath(config.routes, current);- const signature = JSON.stringify([path, current.location.search]);- if (visited.has(signature)) {- throw new Error(`Split router middleware redirect loop at ${signature}`);- }- visited.add(signature);-- const handleResult = (- result: SplitRouterMiddlewareResult,- nextIndex: number- ): SplitRouterMiddlewareRun => {- throwIfAborted(request.signal);-- if (!result) return runAt(nextIndex);-- const next = resolveNavigation(- config.routes,- current,- current,- result.to- );- if (!next) {- throw new Error(- `Split router middleware redirected to an invalid route: ${result.to}`- );- }-- const redirected: SplitRouterEntry = {- ...next,- key: current.key,- };- if (Object.hasOwn(current, 'state')) {- redirected.state = current.state;- }- return runEntry(withSearch(redirected, current.location.search));- };-- const runAt = (index: number): SplitRouterMiddlewareRun => {- throwIfAborted(request.signal);-- const handler = config.handlers[index];- if (!handler) {- assertRouteEntry(config.routes, current);- return current;- }-- const result = handler({- from: request.from,- to: current,- path,- externalSearch: request.externalSearch,- cause: request.cause,- signal: request.signal,- redirect: (to) => ({ type: 'redirect', to }),- });-- if (isPromise(result)) {- return result.then((settled) => handleResult(settled, index + 1));- }- return handleResult(result, index + 1);- };-- return runAt(0);- };-- return runEntry(request.to);-}--function recoverFailure(- error: unknown,- config: SplitRouterMiddlewareConfig,- request: SplitRouterMiddlewareRequest-): SplitRouterEntry {- if (isAbortError(error, request.signal)) throw error;- // Failure recovery must never publish a malformed original proposal.- assertRouteEntry(config.routes, request.to);-- console.error('Split router middleware failed; continuing navigation', error);- return request.to;-}--export function prepareEntry(- config: SplitRouterMiddlewareConfig,- request: SplitRouterMiddlewareRequest-): SplitRouterMiddlewareRun {- assertRouteEntry(config.routes, request.to);- try {- const prepared = runSplitRouterMiddleware(config, request);-- if (isPromise(prepared)) {- return prepared.catch((error) => recoverFailure(error, config, request));- }- return prepared;- } catch (error) {- return recoverFailure(error, config, request);- }-}--export function prepareEntries(- config: SplitRouterMiddlewareConfig,- request: BatchRequest-): PreparedEntries {- const prepared = request.to.map((entry, index) =>- prepareEntry(config, {- from: request.from?.[index],- to: entry,- cause: request.cause,- externalSearch: request.externalSearch,- signal: request.signal,- })- );-- if (prepared.some(isPromise)) return Promise.all(prepared);- return prepared as SplitRouterEntry[];-}diff --git a/apps/web/src/lib/split-router/navigation.ts b/apps/web/src/lib/split-router/navigation.tsdeleted file mode 100644index 125c14d789..0000000000--- a/apps/web/src/lib/split-router/navigation.ts+++ /dev/null@@ -1,156 +0,0 @@-import {- decodeRoute,- encodeRoute,- findRouteBranch,- getRouteId,- type SplitRoutesManifest,-} from './routes';-import { parseSplitSearch } from './search';-import type {- SplitLocation,- SplitNavigateTo,- SplitRouteParams,- SplitRouterEntry,- SplitRouteState,-} from './types';-import { parseExternalLocation, parseRoutePathname } from './url';--function resolveRouteTarget(- routes: SplitRoutesManifest,- current: SplitRouterEntry,- target: { route: { id: string }; params?: unknown }-): SplitRouterEntry | undefined {- const routeId = target.route.id;- let targetParams: SplitRouteParams = {};- if (- target.params &&- typeof target.params === 'object' &&- !Array.isArray(target.params)- ) {- targetParams = target.params as SplitRouteParams;- }- const branch = findRouteBranch(routes, routeId);- if (!branch) return;-- const currentMatches = current.location.route.matches;- const matches = branch.map(({ definition }, index) => {- const currentMatch = currentMatches[index];- let params: SplitRouteParams = {};- if (currentMatch?.id === definition.id) params = currentMatch.params;-- return {- id: definition.id,- // Explicit branch params override inherited values at every level before- // each node serializes its own schema output into path segments.- params: { ...params, ...targetParams },- };- });-- const [first, ...rest] = matches;- if (!first) return;-- const route: SplitRouteState = { matches: [first, ...rest] };- return decodeRoute(routes, encodeRoute(routes, { location: { route } }));-}--function resolveParentTarget(- routes: SplitRoutesManifest,- current: SplitRouterEntry,- levels: number | undefined-): SplitRouterEntry | undefined {- const route = current.location.route;- if (route.matches.length === 1) return;-- const count = levels ?? 1;- if (!Number.isSafeInteger(count) || count < 1) return;-- const length = Math.max(1, route.matches.length - count);- const [first, ...rest] = route.matches.slice(0, length);- if (!first) return;-- const parentRoute: SplitRouteState = { matches: [first, ...rest] };- return decodeRoute(- routes,- encodeRoute(routes, { location: { route: parentRoute } })- );-}--function resolvePathTarget(- routes: SplitRoutesManifest,- current: SplitRouterEntry,- to: string-):- | {- entry: SplitRouterEntry;- explicitSearch: SplitLocation['search'];- }- | undefined {- const childRelative = to.startsWith('./');- let value = to;- if (childRelative) value = to.slice(2);-- let pathname = value;- if (!value.startsWith('/')) pathname = `/${value}`;- const targetUrl = parseExternalLocation(pathname);- const requested = parseRoutePathname(routes, targetUrl.pathname);-- if (!requested) return;-- let segments: string[];- if (value.startsWith('/')) {- segments = requested;- } else if (childRelative) {- segments = [...encodeRoute(routes, current), ...requested];- } else if (requested.length > 0) {- segments = [encodeRoute(routes, current)[0]!, ...requested];- } else {- segments = encodeRoute(routes, current);- }-- const entry = decodeRoute(routes, segments);- if (!entry) return;-- return {- entry,- explicitSearch: parseSplitSearch(targetUrl.search).get(0),- };-}--export function resolveNavigation(- routes: SplitRoutesManifest,- current: SplitRouterEntry,- target: SplitRouterEntry | undefined,- to: Exclude<SplitNavigateTo, number>-): SplitRouterEntry | undefined {- let resolved:- | {- entry: SplitRouterEntry | undefined;- explicitSearch: SplitLocation['search'];- }- | undefined;- if (typeof to === 'string') {- resolved = resolvePathTarget(routes, current, to);- } else if ('route' in to) {- resolved = {- entry: resolveRouteTarget(routes, current, to),- explicitSearch: undefined,- };- } else {- resolved = {- entry: resolveParentTarget(routes, current, to.levels),- explicitSearch: undefined,- };- }- if (!resolved) return;- const decoded = resolved.entry;- if (!decoded) return;-- let search = resolved.explicitSearch;- if (!search && target && getRouteId(target) === getRouteId(decoded)) {- search = target.location.search;- }-- const location: SplitLocation = { ...decoded.location };- if (search) location.search = search;- return { location };-}diff --git a/apps/web/src/lib/split-router/next/index.ts b/apps/web/src/lib/split-router/next/index.tsdeleted file mode 100644index 05ccb52b3b..0000000000--- a/apps/web/src/lib/split-router/next/index.ts+++ /dev/null@@ -1,129 +0,0 @@-export {- type BrowserHistoryOptions,- createBrowserHistory,-} from './history/browser';-export { createMemoryHistory, type MemoryHistory } from './history/memory';-export {- createSolidRouterHistory,- type SolidRouterHistoryOptions,- useSolidRouterHistory,-} from './history/solid-router';-export type {- ExternalChange,- HistoryAdapter,- InterceptHandler,-} from './history/types';-export { createMemoryPaneStore } from './panes/memory-store';-export type {- OpenIntent,- OpenTarget,- PaneStore,- Placement,-} from './panes/types';-export type { ClaimHolder } from './router/claims';-export { createSplitRouter } from './router/create-router';-export { PANE_LEVEL } from './router/leave-guards';-export type {- SplitRouterMiddleware,- SplitRouterMiddlewareContext,- SplitRouterMiddlewareResult,-} from './router/middleware';-export type { PendingNavigation } from './router/runner';-export type {- ClaimOwner,- LeaveGuard,- LeaveGuardContext,- NavigationCause,- NavigationResult,- RouteMatchInfo,- SplitCloseAction,- SplitNavigateOptions,- SplitPanePolicy,- SplitRouterOptions,-} from './router/types';-export {- formatLocation,- formatPanePath,- parseLocation,- splitPanePaths,-} from './routes/codec';-export { defineRoute, defineRoutes } from './routes/define';-export {- canonicalRoute,- createRoutesManifest,- decodePane,- type SplitRoutesManifest,-} from './routes/manifest';-export { decodeSegment } from './routes/path';-export {- claimOf,- externalSearchKeys,- filterRouteSearch,- routeParams,-} from './routes/queries';-export { replacePaneSearchParams } from './routes/search';-export {- createSearchParamsCodec,- type SearchParamsCodec,- type SearchParamsCodecOptions,- takeLast,-} from './routes/search-params';-export type {- DefinedSplitRoute,- DefinedSplitRoutes,- Entry,- ExternalLocation,- InferSplitRouteBranchParams,- InferSplitRouteNavigationParams,- InferSplitRouteParams,- InferSplitRouteState,- InferSplitRouteStateInput,- PaneArrival,- PaneId,- PreloadIntent,- SerializedSearchParams,- SplitLocation,- SplitNavigationTarget,- SplitReference,- SplitRouteClaim,- SplitRouteDefinition,- SplitRouteInfo,- SplitRouteMatch,- SplitRouteNavigationTarget,- SplitRouteParams,- SplitRouteState,- SplitRoutes,- SplitRouteUnion,- SplitSearchState,- SplitSearchUpdate,- WriteMode,-} from './routes/types';-export { useOptionalSplitRouter, useSplitRouter } from './solid/context';-export {- type CreateSearchParamsOptions,- createSearchParams,- type SetSearchParams,-} from './solid/create-search-params';-export {- type SplitNavigate,- type SplitRouteNavigateOptions,- useArrival,- useCanGo,- useEntryProps,- useMatches,- useNavigate,- useOwnsSearchNamespace,- usePane,- usePaneHistory,- useParams,- usePendingNavigation,- useRouteParams,- useRouteState,-} from './solid/hooks';-export type { OutletProps } from './solid/outlet';-export type { RouteProps } from './solid/route';-export type { RouterProps } from './solid/router';-export { SplitRouter } from './solid/split-router';-export { useBeforeLeave } from './solid/use-before-leave';-export { useClaim } from './solid/use-claim';-export { isRecord, isSafeName } from './utils';diff --git a/apps/web/src/lib/split-router/next/tests/history.test.ts b/apps/web/src/lib/split-router/next/tests/history.test.tsdeleted file mode 100644index 1d598d4aec..0000000000--- a/apps/web/src/lib/split-router/next/tests/history.test.ts+++ /dev/null@@ -1,300 +0,0 @@-import { createRoot } from 'solid-js';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { createBrowserHistory } from '../history/browser';-import { createMemoryHistory } from '../history/memory';-import { readSlice, STATE_KEY, toMountLocation } from '../history/shared';-import {- createSolidRouterHistory,- type SolidRouterHistoryOptions,-} from '../history/solid-router';-import type { ExternalChange } from '../history/types';-import { decodePanes, parseLocation } from '../routes/codec';-import { createRoutesManifest } from '../routes/manifest';-import type { ExternalLocation, PaneId } from '../routes/types';-import { createFakeSolidRouter } from './fake-solid-router';-import { appRoutes } from './fixtures';--const stateFor = (entry: string) => ({- panes: [{ pane: 'p1' as PaneId, entry }],-});-const at = (path: string, entry = 'e1'): ExternalLocation => ({- ...parseLocation(path),- state: stateFor(entry),-});--afterEach(() => {- vi.useRealTimers();- vi.restoreAllMocks();-});--describe('history helpers', () => {- it('matches the base on a segment boundary', () => {- expect(toMountLocation('/app', '/app')?.path).toBe('/');- expect(toMountLocation('/app/mail', '/app')?.path).toBe('/mail');- expect(toMountLocation('/application', '/app')).toBeUndefined();- });-- it('reads only non-negative whole history indexes', () => {- const slice = (index: unknown) => ({ [STATE_KEY]: { index } });- expect(readSlice(slice(2))?.index).toBe(2);- expect(readSlice(slice(-1))).toBeUndefined();- expect(readSlice(slice(1.5))).toBeUndefined();- expect(readSlice(slice(Number.NaN))).toBeUndefined();- });-});--describe('memory history', () => {- it('never reports its own writes', () => {- const history = createMemoryHistory('/a');- const listener = vi.fn();- history.subscribe(listener);- history.write(at('/b'), { mode: 'push' });- history.write(at('/c'), { mode: 'replace' });- expect(listener).not.toHaveBeenCalled();- expect(history.entries().map((entry) => entry.path)).toEqual(['/a', '/c']);- });-- it('reports traversal and reverts it', () => {- const history = createMemoryHistory('/a');- history.write(at('/b'), { mode: 'push' });- const changes: ExternalChange[] = [];- history.subscribe((change) => changes.push(change));- history.back();- expect(changes.map((change) => change.location.path)).toEqual(['/a']);- changes[0]!.revert();- expect(history.read().path).toBe('/b');- });-- it('lets interceptors veto outside navigations', async () => {- const history = createMemoryHistory('/a');- const listener = vi.fn();- history.subscribe(listener);- const stop = history.intercept(() => false);- await expect(history.navigate('/x')).resolves.toBe(false);- expect(history.read().path).toBe('/a');- stop();- history.intercept(async () => true);- await expect(history.navigate('/y')).resolves.toBe(true);- expect(listener).toHaveBeenCalledOnce();- expect(history.read().path).toBe('/y');- });-});--describe('browser history', () => {- beforeEach(() => window.history.replaceState(null, '', '/app/home'));-- it('reads mount-relative locations and records positions on write', () => {- const history = createBrowserHistory({ base: '/app' });- expect(history.read()).toMatchObject({ path: '/home' });- history.write(at('/mail?x=1'), { mode: 'push' });- expect(window.location.pathname).toBe('/app/mail');- expect(window.history.state.__splitRouter).toEqual({- index: 1,- value: stateFor('e1'),- });- expect(history.read()).toEqual({- path: '/mail',- search: '?x=1',- hash: '',- state: stateFor('e1'),- });- expect(history.href({ path: '/mail', search: '?q=1', hash: '' })).toBe(- '/app/mail?q=1'- );- });-- it('reports back/forward, and a revert returns to the previous entry', async () => {- const history = createBrowserHistory({ base: '/app' });- history.write(at('/home', 'e1'), { mode: 'replace' });- history.write(at('/mail', 'e2'), { mode: 'push' });- const changes: ExternalChange[] = [];- history.subscribe((change) => changes.push(change));-- const popped = () =>- new Promise((resolve) =>- window.addEventListener('popstate', resolve, { once: true })- );- const back = popped();- window.history.back();- await back;- expect(changes.map((change) => change.location.path)).toEqual(['/home']);-- await changes[0]!.revert();- expect(window.location.pathname).toBe('/app/mail');- expect(changes.map((change) => change.location.path)).toEqual([- '/home',- '/mail',- ]);- });-- it('rewrites legacy multi-pane paths through transformPath', () => {- // Pre-`~` URLs listed each pane as a `type/id` pair in one path.- const upgradeLegacy = (path: string) => {- const segments = path.split('/').filter(Boolean);- const pairs = segments.length >= 4 && segments.length % 2 === 0;- if (!pairs) return path;- const panes = [];- for (let index = 0; index < segments.length; index += 2) {- if (!['md', 'pdf', 'channel'].includes(segments[index]!)) return path;- panes.push(`${segments[index]}/${segments[index + 1]}`);- }- return `/${panes.join('/~/')}`;- };- window.history.replaceState(null, '', '/app/md/a/pdf/b');- const history = createBrowserHistory({- base: '/app',- transformPath: upgradeLegacy,- });- const decoded = decodePanes(- createRoutesManifest(appRoutes),- history.read()- );- expect(- decoded.panes.map((pane) => pane.entry.location.route.matches[1]!.params)- ).toEqual([- { type: 'md', id: 'a' },- { type: 'pdf', id: 'b' },- ]);-- window.history.replaceState(null, '', '/app/drive/md/a');- expect(history.read().path).toBe('/drive/md/a');- });-});--describe('Solid Router history', () => {- const adapterFor = (- router: ReturnType<typeof createFakeSolidRouter>,- options: Partial<SolidRouterHistoryOptions> = {}- ) =>- createSolidRouterHistory({- location: router.location,- navigate: router.navigate,- beforeLeave: router.beforeLeave,- base: '/app',- ...options,- });-- it('writes in a later task, merges writes, and skips its own write landing', () => {- vi.useFakeTimers();- const router = createFakeSolidRouter('/app/home');- const listener = vi.fn();- const { history, dispose } = createRoot((dispose) => {- const history = adapterFor(router);- history.subscribe(listener);- return { history, dispose };- });-- history.write(at('/mail'), { mode: 'push' });- history.write(at('/mail/t1'), { mode: 'replace' });- expect(router.calls).toEqual([]);- vi.runAllTimers();-- expect(router.calls).toEqual([- [- '/mail/t1',- {- replace: false,- scroll: false,- state: { __splitRouter: { index: 1, value: stateFor('e1') } },- },- ],- ]);- expect(listener).not.toHaveBeenCalled();- expect(history.read()).toEqual({- path: '/mail/t1',- search: '',- hash: '',- state: stateFor('e1'),- });- dispose();- });-- it('strips the base and applies the path transform', () => {- const router = createFakeSolidRouter('/app/s_abc');- createRoot((dispose) => {- const history = adapterFor(router, {- transformPath: (path) => path.replace('s_abc', 'md/abc'),- });- expect(history.read().path).toBe('/md/abc');- dispose();- });- });-- it('reports back/forward, and a revert settles once it has landed', async () => {- vi.useFakeTimers();- const router = createFakeSolidRouter('/app/home');- const changes: ExternalChange[] = [];- const { history, dispose } = createRoot((dispose) => {- const history = adapterFor(router);- history.subscribe((change) => changes.push(change));- return { history, dispose };- });- history.write(at('/home', 'e1'), { mode: 'replace' });- vi.runAllTimers();- history.write(at('/mail', 'e2'), { mode: 'push' });- vi.runAllTimers();-- router.traverse(-1);- expect(changes.map((change) => change.location.path)).toEqual(['/home']);- const reverted = changes[0]!.revert();- expect(history.read().path).toBe('/home');- await reverted;- expect(router.calls.at(-1)).toEqual([1, undefined]);- expect(history.read().path).toBe('/mail');- expect(changes.map((change) => change.location.path)).toEqual([- '/home',- '/mail',- ]);- dispose();- });-- it('reports every location under its base and ignores the rest', () => {- const router = createFakeSolidRouter('/app/home');- const listener = vi.fn();- const dispose = createRoot((dispose) => {- adapterFor(router).subscribe(listener);- return dispose;- });- router.show('/elsewhere', undefined);- expect(listener).not.toHaveBeenCalled();- router.show('/app/login', undefined);- expect(listener).toHaveBeenCalledOnce();- dispose();- });-- it('intercepts outside navigations through beforeLeave', async () => {- const router = createFakeSolidRouter('/app/home');- const verdicts: (boolean | Promise<boolean>)[] = [- false,- Promise.resolve(true),- true,- ];- const seen: (ExternalLocation | undefined)[] = [];- const dispose = createRoot((dispose) => {- adapterFor(router).intercept?.((location) => {- seen.push(location);- return verdicts.shift()!;- });- return dispose;- });-- const blocked = router.leave('/app/mail/t1');- expect(blocked.preventDefault).toHaveBeenCalled();- expect(seen[0]).toEqual({ path: '/mail/t1', search: '', hash: '' });-- const deferred = router.leave('/elsewhere');- expect(seen[1]).toBeUndefined();- expect(deferred.preventDefault).toHaveBeenCalled();- await Promise.resolve();- await Promise.resolve();- expect(deferred.retry).toHaveBeenCalledWith(true);-- const allowed = router.leave('/app/mail');- expect(allowed.preventDefault).not.toHaveBeenCalled();-- const traversal = router.leave(-1);- expect(traversal.preventDefault).not.toHaveBeenCalled();- expect(seen).toHaveLength(3);- dispose();- });-});diff --git a/apps/web/src/lib/split-router/next/tests/navigation.test.ts b/apps/web/src/lib/split-router/next/tests/navigation.test.tsdeleted file mode 100644index 1dcbc47aa7..0000000000--- a/apps/web/src/lib/split-router/next/tests/navigation.test.ts+++ /dev/null@@ -1,354 +0,0 @@-import { simulate, step } from '@macro-inc/machine';-import { afterEach, describe, expect, it, vi } from 'vitest';-import {- runMiddleware,- type SplitRouterMiddleware,-} from '../router/middleware';-import { IDLE, type State as RunState, runDef } from '../router/run';-import type { Navigation } from '../router/types';-import {- type Event as GateEvent,- type State as GateState,- type UrlOutcome,- urlGateDef,-} from '../router/url-gate';-import { createRoutesManifest, decodePane } from '../routes/manifest';-import type { Entry, PaneId } from '../routes/types';-import { CANCELLED } from '../utils';-import { appRoutes } from './fixtures';--const routes = createRoutesManifest(appRoutes);-const entry = (- id: string,- path: string,- extra: Partial<Entry> = {}-): Entry => ({- id,- location: { route: decodePane(routes, path.split('/').filter(Boolean))! },- ...extra,-});-const signal = () => new AbortController().signal;--const pane = 'p1' as PaneId;-const navigation = (id: string): Navigation => ({- cause: 'navigate',- targets: [{ pane, to: entry(id, '/home') }],- apply: () => ({ status: 'committed', pane }),-});-const first = navigation('e1');-const second = navigation('e2');-const third = navigation('e4');-const entries = [entry('e3', '/mail')];--afterEach(() => vi.restoreAllMocks());--describe('run', () => {- const guards: RunState = { t: 'guards', navigation: first };- const middleware: RunState = { t: 'middleware', navigation: first };- const preload: RunState = { t: 'preload', navigation: first, entries };-- it('moves from guards to middleware to preload, then commits', () => {- const run = simulate(runDef, IDLE, [- { t: 'navigate', navigation: first },- { t: 'allowed' },- { t: 'resolved', entries },- { t: 'preloaded' },- ]);- expect(run.state).toEqual(IDLE);- expect(run.commands).toEqual([{ t: 'commit', navigation: first, entries }]);- });-- it('is turned down by guards or middleware, and fails from any phase', () => {- expect(step(runDef, guards, { t: 'refused' })?.commands).toEqual([- { t: 'cancel', navigation: first, reason: 'refused' },- ]);- expect(- step(runDef, middleware, { t: 'middleware-cancelled' })?.commands- ).toEqual([{ t: 'cancel', navigation: first, reason: 'cancelled' }]);- expect(step(runDef, preload, { t: 'failed' })).toEqual({- state: IDLE,- commands: [{ t: 'cancel', navigation: first, reason: 'failed' }],- });- });-- it('ignores a report from a phase it has left', () => {- expect(step(runDef, middleware, { t: 'allowed' })).toBeUndefined();- expect(step(runDef, preload, { t: 'resolved', entries })).toBeUndefined();- });-- it('lets a newer navigation replace the one in flight', () => {- const run = simulate(runDef, IDLE, [- { t: 'navigate', navigation: first },- { t: 'allowed' },- { t: 'navigate', navigation: second },- ]);- expect(run.state).toEqual({ t: 'guards', navigation: second });- expect(run.commands).toEqual([- { t: 'cancel', navigation: first, reason: 'superseded' },- ]);- });-- it('cancels with the reason it is aborted for', () => {- expect(- step(runDef, preload, { t: 'abort', reason: 'interrupted' })- ).toEqual({- state: IDLE,- commands: [{ t: 'cancel', navigation: first, reason: 'interrupted' }],- });- });-- it('ignores reports and aborts while idle', () => {- expect(- step(runDef, IDLE, { t: 'abort', reason: 'superseded' })- ).toBeUndefined();- expect(step(runDef, IDLE, { t: 'preloaded' })).toBeUndefined();- });-});--describe('URL gate', () => {- const open: GateState = { t: 'open' };- const start = (navigating: Navigation, blocking = false): GateEvent => ({- t: 'start',- navigation: navigating,- blocking,- });- const settled = (navigating: Navigation, outcome: UrlOutcome): GateEvent => ({- t: 'settled',- navigation: navigating,- outcome,- });- const ACTION: GateEvent = { t: 'action' };- const LANDED: GateEvent = { t: 'revert-landed' };- const OPENED = { t: 'opened' };- const runs = (navigating: Navigation) => [- { t: 'cancel-pane-runs' },- { t: 'run', navigation: navigating },- ];- const revert = (navigating: Navigation) => ({- t: 'revert',- navigation: navigating,- });- const abort = (navigating: Navigation, reason: string) => ({- t: 'abort',- navigation: navigating,- reason,- });-- it('lets actions straight through while no URL navigation runs', () => {- expect(step(urlGateDef, open, ACTION)).toEqual({- state: open,- commands: [OPENED],- });- expect(step(urlGateDef, open, start(first))?.commands).toEqual(runs(first));- });-- it('keeps a replaced URL navigation to put back later, and its blocking', () => {- const run = simulate(urlGateDef, open, [start(first, true), start(second)]);- expect(run.state).toEqual({- t: 'navigating',- navigation: second,- blocking: true,- superseded: [first],- });- expect(run.commands).toEqual([...runs(first), ...runs(second)]);- });-- it('opens once the current URL navigation commits, forgetting the ones it replaced', () => {- const run = simulate(urlGateDef, open, [- start(first),- start(second),- settled(second, 'committed'),- ]);- expect(run.state).toEqual(open);- expect(run.commands).toEqual([...runs(first), ...runs(second), OPENED]);- });-- it.each(['refused', 'cancelled'] as const)(- 'puts back a %s URL navigation, then the ones it replaced, newest first',- (outcome) => {- const run = simulate(urlGateDef, open, [- start(first),- start(second),- start(third),- settled(third, outcome),- LANDED,- LANDED,- LANDED,- ]);- expect(run.state).toEqual(open);- expect(run.commands.slice(6)).toEqual([- revert(third),- revert(second),- revert(first),- OPENED,- ]);- }- );-- it('opens after a failed URL navigation without putting its URL back', () => {- const run = simulate(urlGateDef, open, [- start(first),- settled(first, 'failed'),- ]);- expect(run.state).toEqual(open);- expect(run.commands).toEqual([...runs(first), OPENED]);- });-- it('ignores the outcome of a URL navigation that is no longer current', () => {- const navigating: GateState = {- t: 'navigating',- navigation: second,- blocking: false,- superseded: [first],- };- expect(- step(urlGateDef, navigating, settled(first, 'committed'))- ).toBeUndefined();- });-- it('holds an action while a blocking URL navigation runs', () => {- const blocking: GateState = {- t: 'navigating',- navigation: first,- blocking: true,- superseded: [],- };- expect(step(urlGateDef, blocking, ACTION)).toBeUndefined();- });-- it('lets an action take over from any other URL navigation once its URLs are back', () => {- const run = simulate(urlGateDef, open, [- start(first),- start(second),- ACTION,- LANDED,- LANDED,- ]);- expect(run.state).toEqual(open);- expect(run.commands.slice(4)).toEqual([- abort(second, 'interrupted'),- revert(second),- revert(first),- OPENED,- ]);- });-- it('turns away a URL navigation that arrives while reverting and puts it back too', () => {- const run = simulate(urlGateDef, open, [- start(first),- ACTION,- start(second),- LANDED,- LANDED,- ]);- expect(run.state).toEqual(open);- expect(run.commands.slice(2)).toEqual([- abort(first, 'interrupted'),- revert(first),- abort(second, 'interrupted'),- revert(second),- OPENED,- ]);- });-- it('puts back a URL navigation arriving mid-revert before the older ones still queued', () => {- const run = simulate(urlGateDef, open, [- start(first),- start(second),- settled(second, 'refused'),- start(third),- LANDED,- LANDED,- LANDED,- ]);- const reverts = run.commands.filter((command) => command.t === 'revert');-- expect(run.state).toEqual(open);- expect(reverts).toEqual([revert(second), revert(third), revert(first)]);- });-- it('aborts the URL navigation and opens on dispose, then turns everything away', () => {- const run = simulate(urlGateDef, open, [- start(first, true),- { t: 'dispose' },- ACTION,- start(second),- ]);- expect(run.state).toEqual({ t: 'disposed' });- expect(run.commands.slice(2)).toEqual([- abort(first, 'disposed'),- OPENED,- OPENED,- abort(second, 'disposed'),- ]);- });-});--describe('middleware', () => {- const navigatingTo = (to: Entry) => ({- to,- cause: 'navigate' as const,- signal: signal(),- });-- it('follows redirects and keeps the entry identity', () => {- const middleware: SplitRouterMiddleware = (context) =>- context.to.location.route.matches.at(-1)?.id === 'block' &&- context.routes.byId.has('mail-thread')- ? context.redirect('/mail/t1')- : undefined;- const result = runMiddleware(- routes,- [middleware],- navigatingTo(entry('e1', '/md/d1'))- );- expect(result).toMatchObject({- id: 'e1',- location: {- route: {- matches: [{ id: 'app' }, { id: 'mail' }, { id: 'mail-thread' }],- },- },- });- });-- it('cancels when a handler asks to', () => {- const result = runMiddleware(- routes,- [({ cancel }) => cancel()],- navigatingTo(entry('e1', '/home'))- );- expect(result).toBe(CANCELLED);- });-- it('awaits async handlers', async () => {- const result = runMiddleware(- routes,- [- async ({ path, redirect }) =>- path === '/drive' ? undefined : redirect('/drive'),- ],- navigatingTo(entry('e1', '/home'))- );- await expect(result).resolves.toMatchObject({- location: { route: { matches: [{ id: 'app' }, { id: 'drive' }] } },- });- });-- it('falls back to the proposed entry on a redirect loop', () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- const original = entry('e1', '/home');- const result = runMiddleware(- routes,- [- ({ to, redirect }) =>- redirect(- to.location.route.matches[0].id === 'home' ? '/drive' : '/home'- ),- ],- navigatingTo(original)- );- expect(result).toBe(original);- expect(error).toHaveBeenCalled();- });-});diff --git a/apps/web/src/lib/split-router/next/tests/router.test.ts b/apps/web/src/lib/split-router/next/tests/router.test.tsdeleted file mode 100644index 9c9e93e130..0000000000--- a/apps/web/src/lib/split-router/next/tests/router.test.ts+++ /dev/null@@ -1,1404 +0,0 @@-import { createEffect, createRoot, untrack } from 'solid-js';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { createMemoryHistory } from '../history/memory';-import { createSolidRouterHistory } from '../history/solid-router';-import type { HistoryAdapter } from '../history/types';-import { createMemoryPaneStore } from '../panes/memory-store';-import { createSplitRouter } from '../router/create-router';-import { PANE_LEVEL } from '../router/leave-guards';-import type { SplitCloseAction, SplitRouterOptions } from '../router/types';-import { defineRoute } from '../routes/define';-import type {- Entry,- PaneId,- SplitRouteDefinition,- SplitRoutes,-} from '../routes/types';-import { isPromise } from '../utils';-import { createFakeSolidRouter } from './fake-solid-router';-import {- appLocation,- appRoute,- appRoutes,- createTestPolicy,- homeLocation,- loginRoute,-} from './fixtures';--function setup(- url: string,- overrides: Partial<SplitRouterOptions> = {},- testPolicy = createTestPolicy()-) {- const history = createMemoryHistory(url);- const paneStore = createMemoryPaneStore<Entry>();- const { policy, activated, placements } = testPolicy;- let created = 0;- const { router, dispose } = createRoot((dispose) => ({- router: createSplitRouter({- routes: appRoutes,- history,- paneStore,- policy,- createPaneId: () => `pane-${++created}` as PaneId,- ...overrides,- }),- dispose,- }));- return {- router,- history,- paneStore,- activated,- placements,- pane: (index: number) => router.panes()[index]!,- dispose: () => {- router.dispose();- dispose();- },- };-}--/** A router over the Solid Router fake mounted at `/app`. */-function setupSolid(url: string, ahead: readonly string[] = []) {- const solid = createFakeSolidRouter(url, ahead);- return createRoot((dispose) => {- const router = createSplitRouter({- routes: appRoutes,- history: createSolidRouterHistory({- location: solid.location,- navigate: solid.navigate,- base: '/app',- beforeLeave: solid.beforeLeave,- landedPath: solid.landed,- }),- paneStore: createMemoryPaneStore(),- policy: createTestPolicy().policy,- });- return {- router,- solid,- dispose: () => {- router.dispose();- dispose();- },- };- });-}--/** Memory history whose reverts land only when the test says so. */-function slowRevertHistory(url: string) {- const history = createMemoryHistory(url);- const landings: (() => void)[] = [];- const adapter: HistoryAdapter = {- ...history,- subscribe: (listener) =>- history.subscribe((change) =>- listener({- ...change,- revert: () =>- new Promise<void>((resolve) => {- landings.push(() => {- void change.revert();- resolve();- });- }),- })- ),- };-- const landAll = async () => {- for (let attempt = 0; attempt < 8; attempt += 1) {- landings.shift()?.();- await new Promise((resolve) => setTimeout(resolve, 0));- }- };-- return { history, adapter, landAll };-}--/** The level of a pane's first route, below the app route. */-const PANE_ROUTE_LEVEL = 1;-/** The pane route ids below the app route. */-const routeIds = (entry: Entry | undefined) =>- entry?.location.route.matches- .map((match) => match.id)- .filter((id) => id !== 'app');-const location = appLocation;-const withPaneRoutes = (...children: SplitRouteDefinition[]): SplitRoutes => ({- ...appRoutes,- definitions: [- loginRoute,- { ...appRoute, children: [...appRoute.children, ...children] },- ],-});-const never = () => new Promise<boolean>(() => {});--let cleanup: (() => void) | undefined;-const track = <T extends { dispose: () => void }>(context: T) => {- cleanup = context.dispose;- return context;-};--afterEach(() => {- cleanup?.();- cleanup = undefined;- vi.useRealTimers();- vi.restoreAllMocks();-});--describe('split router', () => {- it('starts ready with one pane per URL segment and records pane state in place', () => {- const { router, history } = track(setup('/mail/t1/~/drive'));- expect(router.ready()).toBe(true);- expect(router.panes()).toEqual(['pane-1', 'pane-2']);- expect(history.entries()).toHaveLength(1);- expect(history.read().state?.panes.map((pane) => pane.pane)).toEqual([- 'pane-1',- 'pane-2',- ]);- });-- it('navigates one pane without touching the others', () => {- const { router, history, pane } = track(setup('/home/~/drive'));- const drive = router.entry(pane(1));-- const result = router.navigatePane(pane(0), '/mail/t1');- expect(result).toEqual({ status: 'committed', pane: pane(0) });- expect(router.entry(pane(1))).toBe(drive);- expect(router.arrival(pane(1))).toBe('fresh');- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home/~/drive',- '/mail/t1/~/drive',- ]);- });-- it('replaces a URL whose panes sit under different top-level routes with the default route', () => {- const { router, history } = track(setup('/login/~/home'));- expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([- ['home'],- ]);- expect(history.entries().map((entry) => entry.path)).toEqual(['/home']);- });-- it('turns a pane navigation outside the shared top-level route into a whole-window one, and Back rebuilds the panes', () => {- const { router, history, pane } = track(setup('/home/~/mail'));- router.navigatePane(pane(1), '/login');- expect(- router.panes().map((id) => router.entry(id)?.location.route.matches)- ).toEqual([[{ id: 'login', params: {} }]]);- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home/~/mail',- '/login',- ]);-- history.back();- expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([- ['home'],- ['mail'],- ]);- });-- it('skips entries under another top-level route on pane Back while other panes share the app route', () => {- const { router, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/login');- router.navigatePane(pane(0), '/mail');- router.open('/drive', { newPane: true, source: pane(0) });- expect(router.panes()).toHaveLength(2);-- expect(router.canGo(pane(0), -1)).toBe(true);- router.navigatePane(pane(0), -1);- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- expect(router.canGo(pane(0), -1)).toBe(false);- });-- it('pane back replaces the browser entry and records how the pane arrived', () => {- const { router, history, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/mail');- router.navigatePane(pane(0), -1);- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- expect(router.arrival(pane(0))).toBe('back');- expect(router.canGo(pane(0), 1)).toBe(true);- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home',- '/home',- ]);- });-- it('browser back brings a pane back through its own history', () => {- const { router, history, paneStore, pane } = track(setup('/home/~/drive'));- router.navigatePane(pane(0), '/mail');- const drive = router.entry(pane(1));- history.back();- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- expect(router.arrival(pane(0))).toBe('back');- expect(paneStore.read(pane(0))).toMatchObject({ index: 0 });- expect(paneStore.read(pane(0))?.entries).toHaveLength(2);- expect(router.entry(pane(1))).toBe(drive);- });-- it('a leave guard can refuse browser back, and the URL is put back', () => {- const { router, history, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/mail');- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, () => false);- history.back();- expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);- expect(history.index()).toBe(1);- expect(history.read().path).toBe('/mail');- });-- it('ignores the report of its own revert landing', async () => {- vi.useFakeTimers();- const { router, solid } = track(setupSolid('/app/home'));- vi.runAllTimers();- const pane = router.panes()[0]!;- router.navigatePane(pane, '/mail');- vi.runAllTimers();- const mail = router.entry(pane);- router.registerGuard(pane, PANE_ROUTE_LEVEL, () => false);-- solid.traverse(-1);- await new Promise<void>((resolve) => queueMicrotask(resolve));- vi.runAllTimers();- expect(router.entry(pane)).toBe(mail);- expect(solid.calls.map(([to]) => to)).toEqual(['/home', '/mail', 1]);- expect(solid.location.pathname).toBe('/app/mail');- });-- it('keeps an async-guarded navigation pending until the guard settles', async () => {- const { router, pane } = track(setup('/home'));- let allow: (value: boolean) => void = () => {};- router.registerGuard(- pane(0),- PANE_ROUTE_LEVEL,- () =>- new Promise<boolean>((resolve) => {- allow = resolve;- })- );- const result = router.navigatePane(pane(0), '/mail');- expect(isPromise(result)).toBe(true);- expect(routeIds(router.pending(pane(0))?.to)).toEqual(['mail']);- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- allow(true);- await expect(result).resolves.toMatchObject({ status: 'committed' });- expect(router.pending(pane(0))).toBeUndefined();- expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);- });-- it('a newer navigation in the same pane supersedes a pending one', async () => {- const { router, pane } = track(- setup('/home', {- middleware: [- async ({ path }) => {- if (path === '/mail')- await new Promise((done) => setTimeout(done, 10));- },- ],- })- );- expect(router.ready()).toBe(false);- await router.settled();- expect(router.ready()).toBe(true);- const first = router.navigatePane(pane(0), '/mail');- const second = router.navigatePane(pane(0), '/drive');- await expect(first).resolves.toEqual({ status: 'cancelled' });- await expect(second).resolves.toMatchObject({ status: 'committed' });- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- });-- it('a superseded navigation settles even when its guard never does', async () => {- const { router, pane } = track(setup('/home'));- const unregister = router.registerGuard(pane(0), PANE_ROUTE_LEVEL, never);- const first = router.navigatePane(pane(0), '/mail');- unregister();- const second = router.navigatePane(pane(0), '/drive');- await expect(first).resolves.toEqual({ status: 'cancelled' });- expect(second).toMatchObject({ status: 'committed' });- });-- it('ignores a superseded navigation whose guard answers late', async () => {- const { router, pane } = track(setup('/home'));- const answers: ((allowed: boolean) => void)[] = [];- router.registerGuard(- pane(0),- PANE_ROUTE_LEVEL,- () => new Promise<boolean>((resolve) => answers.push(resolve))- );- const first = router.navigatePane(pane(0), '/mail');- const second = router.navigatePane(pane(0), '/drive');- answers[0]!(true);- answers[1]!(false);- await expect(first).resolves.toEqual({ status: 'cancelled' });- await expect(second).resolves.toEqual({ status: 'cancelled' });- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- });-- it('browser back cancels a pane navigation still in flight', async () => {- const { router, history, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/mail');- let allow: (allowed: boolean) => void = () => {};- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) =>- cause === 'external'- ? true- : new Promise<boolean>((resolve) => {- allow = resolve;- })- );- const drive = router.navigatePane(pane(0), '/drive');- history.back();- allow(true);- await expect(drive).resolves.toEqual({ status: 'cancelled' });- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- });-- it('mounts the URL even when middleware cancels the initial load', () => {- const { router, pane } = track(- setup('/mail', { middleware: [({ cancel }) => cancel()] })- );- expect(router.ready()).toBe(true);- expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);- });-- it('settles commands waiting on the initial load when disposed', async () => {- const { router, dispose } = setup('/home', {- middleware: [() => new Promise<void>(() => {})],- });- const opened = router.open('/mail', { newPane: true });- dispose();- await expect(opened).resolves.toEqual({ status: 'cancelled' });- });-- it('waits for an async initial load before opening a pane', async () => {- const { router } = track(- setup('/home/~/drive', { middleware: [async () => {}] })- );- expect(router.ready()).toBe(false);- const opened = router.open('/mail', { newPane: true });- await expect(opened).resolves.toEqual({- status: 'committed',- pane: 'pane-3',- });- expect(router.ready()).toBe(true);- expect(router.panes()).toEqual(['pane-1', 'pane-2', 'pane-3']);- });-- it('drops commands still waiting on a revert once disposed', async () => {- vi.useFakeTimers();- const { router, solid } = track(setupSolid('/app/home'));- vi.runAllTimers();- const pane = router.panes()[0]!;- router.navigatePane(pane, '/mail');- vi.runAllTimers();- router.registerGuard(pane, PANE_ROUTE_LEVEL, never);- solid.traverse(-1);-- const rewrite = router.rewriteCurrent(pane, '/drive');- router.move(pane, 0);- router.dispose();- await expect(rewrite).resolves.toEqual({ status: 'cancelled' });- vi.runAllTimers();- expect(solid.calls.map(([to]) => to)).toEqual(['/home', '/mail', 1]);- });-- it('a pane command cancels a pending browser back and reverts it first', () => {- const { router, history, pane } = track(setup('/home/~/drive'));- router.navigatePane(pane(0), '/mail');- let guardSignal: AbortSignal | undefined;- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ signal }) => {- guardSignal = signal;- return never();- });- history.back();- expect(routeIds(router.pending(pane(0))?.to)).toEqual(['home']);-- expect(router.navigatePane(pane(1), '/drive/folder/f1')).toMatchObject({- status: 'committed',- });- expect(guardSignal?.aborted).toBe(true);- expect(router.pending(pane(0))).toBeUndefined();- expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home/~/drive',- '/mail/~/drive',- '/mail/~/drive/folder/f1',- ]);- expect(history.index()).toBe(2);- });-- it('writes after the reverted back has landed', async () => {- vi.useFakeTimers();- const { router, solid } = track(setupSolid('/app/home'));- vi.runAllTimers();- const pane = router.panes()[0]!;- router.navigatePane(pane, '/mail');- vi.runAllTimers();- router.registerGuard(pane, PANE_ROUTE_LEVEL, ({ cause }) =>- cause === 'external' ? never() : true- );- solid.traverse(-1);- expect(routeIds(router.pending(pane)?.to)).toEqual(['home']);-- const result = router.navigatePane(pane, '/drive');- expect(isPromise(result)).toBe(true);- await expect(result).resolves.toMatchObject({ status: 'committed' });- vi.runAllTimers();- expect(solid.calls.map(([to]) => to)).toEqual([- '/home',- '/mail',- 1,- '/drive',- ]);- expect(solid.entries().map((entry) => entry.path)).toEqual([- '/app/home',- '/app/mail',- '/app/drive',- ]);- });-- it('reports a pending URL navigation only for the panes it changes', async () => {- let slow = false;- const { router, history, pane } = track(- setup('/home/~/drive', {- middleware: [- ({ path }) =>- slow && path === '/home'- ? new Promise<void>((done) => setTimeout(done, 5))- : undefined,- ],- })- );- router.navigatePane(pane(0), '/mail');- slow = true;- history.back();- expect(routeIds(router.pending(pane(0))?.to)).toEqual(['home']);- expect(router.pending(pane(1))).toBeUndefined();- await router.settled();- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- });-- it('opening something another pane shows activates that pane instead', () => {- const { router, activated, pane } = track(setup('/drive/md/d1/~/home'));- const result = router.navigatePane(pane(1), '/md/d1');- expect(result).toEqual({ status: 'activated', owner: pane(0) });- expect(activated).toEqual([pane(0)]);- expect(routeIds(router.entry(pane(1)))).toEqual(['home']);- expect(- router.navigatePane(pane(1), '/md/d1', { allowDuplicate: true })- ).toMatchObject({ status: 'committed' });- });-- it('tells the policy who shows a new pane’s destination and whether a duplicate is allowed', () => {- const testPolicy = createTestPolicy();- const { router, pane } = track(setup('/md/d1/~/home', {}, testPolicy));- const target = { newPane: true as const, source: pane(1) };-- router.open('/md/d1', target, { allowDuplicate: true });-- expect(testPolicy.placements).toMatchObject([- { holder: pane(0), allowDuplicate: true },- ]);- });-- it('opens a new pane beside the one showing the destination when the policy places it there', () => {- const { router, activated, pane } = track(setup('/md/d1/~/home'));-- const result = router.open('/md/d1', { newPane: true, source: pane(1) });-- expect(result).toMatchObject({ status: 'committed' });- expect(router.panes()).toHaveLength(3);- expect(activated).toEqual([]);- });-- it('brings up a pane that started showing a new pane’s destination after it was placed', async () => {- let release: () => void = () => {};- let held = false;- const holdFirstVisit = ({ path }: { path: string }) => {- if (path !== '/md/d1' || held) return;-- held = true;-- return new Promise<void>((resolve) => {- release = resolve;- });- };- const { router, pane } = track(- setup('/home/~/drive', { middleware: [holdFirstVisit] })- );-- const opened = router.open('/md/d1', { newPane: true, source: pane(1) });- router.navigatePane(pane(0), '/md/d1');- release();-- await expect(opened).resolves.toEqual({- status: 'activated',- owner: pane(0),- });- expect(router.panes()).toHaveLength(2);- });-- it('skips entries another pane shows on Back and Forward, unless duplicates are allowed', () => {- const { router, pane } = track(setup('/home/~/home'));- router.navigatePane(pane(0), '/md/d1');- router.navigatePane(pane(0), '/drive');- router.navigatePane(pane(1), '/md/d1');-- router.navigatePane(pane(0), -1);- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- expect(router.canGo(pane(0), 1)).toBe(true);-- router.navigatePane(pane(0), 1, { allowDuplicate: true });- expect(routeIds(router.entry(pane(0)))).toEqual(['block']);- });-- it('keeps duplicates loaded from a URL', () => {- const { router } = track(setup('/md/d1/~/md/d1'));- expect(router.panes()).toHaveLength(2);- });-- it('changing search in a duplicate keeps it in place', () => {- const { router, activated, pane } = track(- setup('/drive/md/d1/~/drive/md/d1')- );- expect(- router.updateSearch(pane(1), 'drive', { sort: ['name'] })- ).toMatchObject({ status: 'committed', pane: pane(1) });- expect(activated).toEqual([]);- });-- it('browser back brings back a duplicate', () => {- const { router, history, activated, pane } = track(setup('/home/~/md/d1'));- router.navigatePane(pane(0), '/md/d1', { allowDuplicate: true });- router.navigatePane(pane(0), '/drive');- history.back();- expect(routeIds(router.entry(pane(0)))).toEqual(['block']);- expect(activated).toEqual([]);- });-- it('opens and closes panes where the policy places them', () => {- const { router, history } = track(setup('/home/~/drive'));- expect(- router.open('/mail', {- newPane: true,- source: 'pane-1' as PaneId,- })- ).toEqual({ status: 'committed', pane: 'pane-3' });- expect(router.panes()).toEqual(['pane-1', 'pane-3', 'pane-2']);- expect(history.read().path).toBe('/home/~/mail/~/drive');-- expect(router.open('/home', { pane: 'pane-3' as PaneId })).toEqual({- status: 'committed',- pane: 'pane-3',- });- expect(router.close('pane-3' as PaneId)).toBe(true);- expect(router.close('pane-2' as PaneId)).toBe(true);- expect(router.panes()).toEqual(['pane-1']);- expect(history.read().path).toBe('/home');-- expect(router.close('pane-1' as PaneId)).toBe(false);- router.navigatePane('pane-1' as PaneId, '/mail');- expect(router.close('pane-1' as PaneId)).toBe(true);- expect(router.panes()).toEqual(['pane-1']);- expect(history.read().path).toBe('/home');- });-- it('opens several panes at once without one cancelling another', async () => {- const { router } = track(- setup('/home', {- middleware: [- ({ path }) => (path === '/home' ? undefined : Promise.resolve()),- ],- })- );- const source = 'pane-1' as PaneId;- const first = router.open('/mail', { newPane: true, source });- const second = router.open('/drive', { newPane: true, source });- await expect(first).resolves.toEqual({- status: 'committed',- pane: 'pane-2',- });- await expect(second).resolves.toEqual({- status: 'committed',- pane: 'pane-3',- });- expect(router.panes()).toEqual(['pane-1', 'pane-2', 'pane-3']);- });-- it('lets the policy open in an existing pane when enough are open', () => {- const testPolicy = createTestPolicy({ maxPanes: 2 });- const { router } = track(setup('/home/~/drive', {}, testPolicy));- const intent = { replaceWhenFull: true };- expect(- router.open('/mail', {- newPane: true,- source: 'pane-2' as PaneId,- intent,- })- ).toEqual({ status: 'committed', pane: 'pane-2' });- expect(router.panes()).toEqual(['pane-1', 'pane-2']);- expect(routeIds(router.entry('pane-2' as PaneId))).toEqual(['mail']);- expect(testPolicy.placements).toEqual([- {- destination: location('mail'),- source: 'pane-2',- intent,- allowDuplicate: false,- opening: 0,- panes: ['pane-1', 'pane-2'],- },- ]);- });-- it('keeps a pane the policy pins, without asking its guards', () => {- const { router } = track(- setup(- '/home/~/mail',- {},- createTestPolicy({ pinned: ['pane-1' as PaneId] })- )- );- const guard = vi.fn(() => true);- router.registerGuard('pane-1' as PaneId, PANE_ROUTE_LEVEL, guard);- expect(router.close('pane-1' as PaneId)).toBe(false);- expect(router.panes()).toEqual(['pane-1', 'pane-2']);- expect(guard).not.toHaveBeenCalled();- });-- it('navigates from the base, keeping the pane that already shows the destination', () => {- const { router, history } = track(setup('/home/~/mail/~/drive'));- const [home, mail, drive] = router.panes();- const mailEntry = router.entry(mail!);- let allowDrive = false;- router.registerGuard(drive!, PANE_LEVEL, () => allowDrive);-- expect(router.navigate('/mail')).toMatchObject({ status: 'cancelled' });- expect(router.panes()).toEqual([home, mail, drive]);-- allowDrive = true;- expect(router.navigate('/mail')).toMatchObject({ status: 'committed' });- expect(router.panes()).toEqual([mail]);- expect(router.entry(mail!)).toBe(mailEntry);- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home/~/mail/~/drive',- '/mail',- ]);- });-- it('keeps panes that already show their entry when a base navigation reorders them', () => {- const { router, history } = track(setup('/home/~/mail'));- const [home] = router.panes();-- router.navigate('/drive/~/home');- expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([- ['drive'],- ['home'],- ]);- expect(router.panes()[1]).toBe(home);- expect(history.read().path).toBe('/drive/~/home');-- router.navigate({ location: location('mail') });- expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([- ['mail'],- ]);- });-- it('closing the last pane can go back to an earlier entry', () => {- const closeLast: SplitCloseAction = {- type: 'back-to',- to: (entry) => routeIds(entry)?.[0] === 'mail',- otherwise: { type: 'navigate', destination: homeLocation, replace: true },- };- const { router, pane } = track(- setup('/mail', {}, createTestPolicy({ closeLast }))- );- router.navigatePane(pane(0), '/drive');- expect(router.close(pane(0))).toBe(true);- expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);- expect(router.canGo(pane(0), 1)).toBe(true);- });-- it('closing the last pane can replace it without a back entry', () => {- const closeLast: SplitCloseAction = {- type: 'back-to',- to: (entry) => routeIds(entry)?.[0] === 'mail',- otherwise: { type: 'navigate', destination: homeLocation, replace: true },- };- const { router, history, pane } = track(- setup('/drive', {}, createTestPolicy({ closeLast }))- );- expect(router.close(pane(0))).toBe(true);- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- expect(router.canGo(pane(0), -1)).toBe(false);- expect(history.entries()).toHaveLength(1);- });-- it('keeps the hash of the URL it follows through a redirect', () => {- const { history } = track(- setup('/home#focus', {- middleware: [- ({ path, redirect }) =>- path === '/home' ? redirect('/mail') : undefined,- ],- })- );- expect(history.read()).toMatchObject({ path: '/mail', hash: '#focus' });- });-- it('writes an outside navigation with its own hash and global search', async () => {- const { history } = track(setup('/home?referral_code=old#top'));- await history.navigate('/mail/t2?referral_code=new#frag');- expect(history.read()).toMatchObject({- path: '/mail/t2',- search: '?referral_code=new',- hash: '#frag',- });- });-- it('a leave guard can keep a pane open', () => {- const { router } = track(setup('/home/~/mail'));- router.registerGuard('pane-2' as PaneId, PANE_ROUTE_LEVEL, () => false);- expect(router.close('pane-2' as PaneId)).toBe(false);- expect(router.panes()).toHaveLength(2);- });-- it('shows the catch-all route in an unmatched pane and loads the others', () => {- const { router, pane } = track(setup('/mail/t1/~/no/such'));- expect(routeIds(router.entry(pane(0)))).toEqual(['mail', 'mail-thread']);- expect(routeIds(router.entry(pane(1)))).toEqual(['not-found']);- });-- it('takes over outside navigations into the panes', async () => {- const { router, history, pane } = track(setup('/home'));- await expect(history.navigate('/mail/t2')).resolves.toBe(false);- expect(routeIds(router.entry(pane(0)))).toEqual(['mail', 'mail-thread']);- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home',- '/mail/t2',- ]);- });-- it('commits in the same tick without data preloads and waits for them within a budget', async () => {- const preload = vi.fn(() => new Promise(() => {}));- const routes = withPaneRoutes(- defineRoute({ id: 'slow', path: 'slow', preload })- );- const { router, pane } = track(- setup('/home', { routes, preloadBudgetMs: 5 })- );- expect(isPromise(router.navigatePane(pane(0), '/mail'))).toBe(false);-- const result = router.navigatePane(pane(0), '/slow');- expect(isPromise(result)).toBe(true);- expect(preload).toHaveBeenCalledWith(- expect.objectContaining({ intent: 'navigate', params: {} })- );- await expect(result).resolves.toMatchObject({ status: 'committed' });- expect(routeIds(router.entry(pane(0)))).toEqual(['slow']);- });-- it('logs a preload that throws and still navigates', () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- const routes = withPaneRoutes(- defineRoute({- id: 'broken',- path: 'broken',- preload: () => {- throw new Error('boom');- },- })- );- const { router, pane } = track(setup('/home', { routes }));- expect(router.navigatePane(pane(0), '/broken')).toEqual({- status: 'committed',- pane: pane(0),- });- expect(error).toHaveBeenCalledWith(- 'Split route "broken" preload failed',- expect.any(Error)- );- });-- it('writes search as a new entry or in place', () => {- const { router, history, pane } = track(setup('/drive'));- const first = router.entry(pane(0))!.id;- router.updateSearch(- pane(0),- 'drive',- { sort: ['name'] },- { history: 'replace' }- );- expect(router.entry(pane(0))!.id).toBe(first);- expect(history.read().search).toBe('?s0.drive.sort=name');- expect(history.entries()).toHaveLength(1);-- router.updateSearch(pane(0), 'drive', { sort: ['date'] });- expect(router.entry(pane(0))!.id).not.toBe(first);- expect(history.entries()).toHaveLength(2);- });-- it('jumps back to the nearest matching entry', () => {- const { router, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/mail');- router.navigatePane(pane(0), '/drive');- expect(- router.goBackTo(pane(0), (entry) => routeIds(entry)?.[0] === 'home')- ).toBe(true);- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- expect(router.goBackTo(pane(0), () => true)).toBe(false);- });-- it('removing entries cancels a pending traversal in that pane', async () => {- const { router, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/mail');- router.navigatePane(pane(0), '/drive');- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, never);- const back = router.navigatePane(pane(0), -1);- expect(routeIds(router.pending(pane(0))?.to)).toEqual(['mail']);-- const isMail = (entry: Entry) => routeIds(entry)?.[0] === 'mail';- expect(router.removeEntries(pane(0), isMail)).toBe(true);- await expect(back).resolves.toEqual({ status: 'cancelled' });- expect(router.pending(pane(0))).toBeUndefined();- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- expect(router.canGo(pane(0), -1)).toBe(true);- expect(router.removeEntries(pane(0), isMail)).toBe(false);- });-- it('rewrites the current entry in place', () => {- const { router, history, pane } = track(setup('/md/draft'));- const id = router.entry(pane(0))!.id;- router.rewriteCurrent(pane(0), '/md/real');- expect(router.entry(pane(0))!.id).toBe(id);- expect(history.read().path).toBe('/md/real');- expect(history.entries()).toHaveLength(1);- });-- it('builds a single-pane href', () => {- const { router, pane } = track(setup('/home/~/mail/t1'));- expect(router.href(pane(1))).toBe('/mail/t1');- });-});--describe('split router while other work is in flight', () => {- it('keeps the entry an outside navigation came from when the new view redirects in place', async () => {- const { router, history, pane } = track(setup('/home'));- const stopRedirecting = createRoot((dispose) => {- createEffect(() => {- const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';- if (!showsDrive) return;-- untrack(() => router.navigatePane(pane(0), '/mail', { replace: true }));- });-- return dispose;- });-- await history.navigate('/drive');- await router.settled();- stopRedirecting();-- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home',- '/mail',- ]);- expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);- });-- it('lets an outside navigation replace an async initial load, then runs the open waiting on it', async () => {- const { router, history, pane } = track(- setup('/home', { middleware: [async () => {}] })- );- const opened = router.open('/mail', { newPane: true });- void history.navigate('/drive');-- await expect(opened).resolves.toMatchObject({ status: 'committed' });- await router.settled();- expect(router.ready()).toBe(true);- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- expect(routeIds(router.entry(pane(1)))).toEqual(['mail']);- });-- it('holds an open that follows an outside navigation during the initial load', async () => {- const { router, history } = track(- setup('/home', { middleware: [async () => {}] })- );- void history.navigate('/drive');- const opened = router.open('/mail', { newPane: true });-- await expect(opened).resolves.toMatchObject({ status: 'committed' });- await router.settled();- expect(router.ready()).toBe(true);- expect(router.panes().map((id) => routeIds(router.entry(id))?.[0])).toEqual(- ['drive', 'mail']- );- });-- it('asks guards registered above the first route before closing the pane', () => {- const { router, pane } = track(setup('/home/~/mail'));- router.registerGuard(pane(1), PANE_LEVEL, () => false);-- expect(router.close(pane(1))).toBe(false);- expect(router.panes()).toHaveLength(2);- });-- it('puts the URL back past every Back that a refused Back replaced', async () => {- const { router, history, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/mail');- router.navigatePane(pane(0), '/drive');- const answers: ((allowed: boolean) => void)[] = [];- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {- if (cause !== 'external') return true;-- return new Promise<boolean>((resolve) => answers.push(resolve));- });-- history.back();- history.back();- answers[1]!(false);- await router.settled();-- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- expect(history.index()).toBe(2);- expect(history.read().path).toBe('/drive');- });-- it('cancels the pending departure of a pane it activates for a claim', async () => {- const { router, activated, pane } = track(setup('/md/d1/~/home'));- let leave: (allowed: boolean) => void = () => {};- router.registerGuard(- pane(0),- PANE_ROUTE_LEVEL,- () =>- new Promise<boolean>((resolve) => {- leave = resolve;- })- );-- const departure = router.navigatePane(pane(0), '/drive');- expect(router.navigatePane(pane(1), '/md/d1')).toEqual({- status: 'activated',- owner: pane(0),- });- leave(true);-- await expect(departure).resolves.toEqual({ status: 'cancelled' });- expect(routeIds(router.entry(pane(0)))).toEqual(['block']);- expect(activated).toEqual([pane(0)]);- });-- it('carries the search a navigation asked for to the pane already showing its resource', async () => {- const { router, activated, pane } = track(setup('/drive/md/d1/~/home'));-- expect(- router.navigatePane(pane(1), '/drive/md/d1', {- search: { drive: { sort: ['name'] } },- })- ).toEqual({ status: 'activated', owner: pane(0) });- await router.settled();-- expect(activated).toEqual([pane(0)]);- expect(router.entry(pane(0))?.location.search).toEqual({- drive: { sort: ['name'] },- });- expect(routeIds(router.entry(pane(1)))).toEqual(['home']);- });-- it('keeps an owner’s pending navigation that stays on the claimed resource', async () => {- let release: () => void = () => {};- const { router, pane } = track(- setup('/drive/md/d1/~/home', {- middleware: [- ({ cause }) => {- if (cause !== 'search') return;-- return new Promise<void>((resolve) => {- release = resolve;- });- },- ],- })- );- await router.settled();-- const sorting = router.updateSearch(pane(0), 'drive', { sort: ['date'] });- router.navigatePane(pane(1), '/drive/md/d1');- release();-- await expect(sorting).resolves.toMatchObject({ status: 'committed' });- expect(router.entry(pane(0))?.location.search).toEqual({- drive: { sort: ['date'] },- });- });-- it('counts opens still in flight against the policy’s limit', async () => {- const { router } = track(- setup(- '/home',- {- middleware: [- ({ path }) => (path === '/home' ? undefined : Promise.resolve()),- ],- },- createTestPolicy({ maxPanes: 2 })- )- );- const source = 'pane-1' as PaneId;-- const first = router.open('/mail', { newPane: true, source });- const second = router.open('/drive', { newPane: true, source });- await Promise.all([first, second]);-- expect(router.panes()).toHaveLength(2);- });-- it('turns down a location it cannot write, leaving the pane and later writes intact', () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- const { router, history, pane } = track(setup('/drive'));- const tooLong = 'x'.repeat(17_000);-- expect(router.updateSearch(pane(0), 'drive', { sort: [tooLong] })).toEqual({- status: 'cancelled',- });- expect(- router.rewriteCurrent(pane(0), { route: { id: 'missing' } })- ).toEqual({- status: 'cancelled',- });- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- expect(router.entry(pane(0))?.location.search).toBeUndefined();-- expect(router.navigatePane(pane(0), '/mail')).toMatchObject({- status: 'committed',- });- expect(history.read().path).toBe('/mail');- expect(error).toHaveBeenCalled();- expect(error).not.toHaveBeenCalledWith(- 'Split router could not commit a navigation',- expect.anything()- );- });-- it('drops a search value from the URL that is too long to write back', () => {- const tooLong = 'x'.repeat(17_000);- const { router, pane } = track(setup(`/drive?s0.drive.sort=${tooLong}`));-- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- expect(router.entry(pane(0))?.location.search).toBeUndefined();- });-- it('reports a refused jump back as false, and a back-to close then keeps the pane', async () => {- const closeLast: SplitCloseAction = {- type: 'back-to',- to: (entry) => routeIds(entry)?.[0] === 'home',- otherwise: {- type: 'navigate',- destination: location('mail'),- replace: true,- },- };- const { router, pane } = track(- setup('/home', {}, createTestPolicy({ closeLast }))- );- router.navigatePane(pane(0), '/drive');- router.registerGuard(- pane(0),- PANE_ROUTE_LEVEL,- ({ to }) => routeIds(to)?.[0] !== 'home'- );-- const isHome = (entry: Entry) => routeIds(entry)?.[0] === 'home';- expect(await router.goBackTo(pane(0), isHome)).toBe(false);- expect(await router.close(pane(0))).toBe(false);- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- });-- it('turns down a close action that leads to no route', async () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- const closeLast: SplitCloseAction = {- type: 'navigate',- destination: location('missing'),- };- const { router, history, pane } = track(- setup('/drive', {}, createTestPolicy({ closeLast }))- );-- expect(await router.close(pane(0))).toBe(false);- expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);- expect(history.read().path).toBe('/drive');- expect(error).toHaveBeenCalledWith(- 'Split router close action leads to no route',- closeLast.destination- );- });-- it('writes a replace another pane makes while one commits after that commit’s push', async () => {- const { router, history, pane } = track(setup('/home/~/home'));- const stopRedirecting = createRoot((dispose) => {- createEffect(() => {- const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';- if (!showsDrive) return;-- untrack(() => router.navigatePane(pane(1), '/mail', { replace: true }));- });-- return dispose;- });-- router.navigatePane(pane(0), '/drive');- await router.settled();- stopRedirecting();-- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home/~/home',- '/drive/~/mail',- ]);- });-- it('keeps a Back whose view redirects in place as it mounts', async () => {- const { router, history, pane } = track(setup('/drive'));- router.navigatePane(pane(0), '/mail');- let armed = false;- const stopRedirecting = createRoot((dispose) => {- createEffect(() => {- const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';- const redirects = armed && showsDrive;- if (!redirects) return;-- untrack(() => router.navigatePane(pane(0), '/home', { replace: true }));- });-- return dispose;- });- armed = true;-- history.back();- await router.settled();- stopRedirecting();-- expect(history.index()).toBe(0);- expect(history.entries().map((entry) => entry.path)).toEqual([- '/home',- '/mail',- ]);- expect(routeIds(router.entry(pane(0)))).toEqual(['home']);- });-- it('keeps navigating after the history adapter fails a write', () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- const history = createMemoryHistory('/home');- let failNext = false;- const flaky: HistoryAdapter = {- ...history,- write(location, writeOptions) {- if (failNext) {- failNext = false;- throw new Error('write failed');- }-- history.write(location, writeOptions);- },- };- const { router, pane } = track(setup('/home', { history: flaky }));-- failNext = true;- expect(router.navigatePane(pane(0), '/mail')).toEqual({- status: 'cancelled',- });- expect(router.navigatePane(pane(0), '/drive')).toMatchObject({- status: 'committed',- });- expect(history.read().path).toBe('/drive');- expect(error).toHaveBeenCalledWith(- 'Split router could not commit a navigation',- expect.any(Error)- );- });-- it('settles a URL navigation that arrives while an earlier one is being put back', async () => {- const { history, adapter, landAll } = slowRevertHistory('/home');- const { router, pane } = track(setup('/home', { history: adapter }));- router.navigatePane(pane(0), '/mail');- router.navigatePane(pane(0), '/drive');- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) =>- cause === 'external' ? never() : true- );-- history.back();- const navigated = router.navigatePane(pane(0), '/drive/folder/f1');- history.back();- await landAll();-- await expect(navigated).resolves.toMatchObject({ status: 'committed' });- await expect(router.settled()).resolves.toBeUndefined();- expect(history.read().path).toBe('/drive/folder/f1');- expect(routeIds(router.entry(pane(0)))).toEqual(['drive', 'drive-folder']);- });-- it('puts back a Back that arrives while others are put back before them', async () => {- const { history, adapter, landAll } = slowRevertHistory('/home');- const { router, pane } = track(setup('/home', { history: adapter }));- router.navigatePane(pane(0), '/mail');- router.navigatePane(pane(0), '/drive');- router.navigatePane(pane(0), '/md/d1');- let refuse: () => void = () => {};- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {- if (cause !== 'external') return true;-- return new Promise<boolean>((resolve) => {- refuse = () => resolve(false);- });- });-- history.back();- history.back();- refuse();- await new Promise((resolve) => setTimeout(resolve, 0));- history.back();- await landAll();- await router.settled();-- expect(history.index()).toBe(3);- expect(history.read().path).toBe('/md/d1');- expect(routeIds(router.entry(pane(0)))).toEqual(['block']);- });-- it('opens a pane that already shows the destination by activating it', () => {- const { router, activated, pane } = track(setup('/mail/t1/~/home'));-- expect(router.open('/mail/t1', { pane: pane(0) })).toEqual({- status: 'activated',- owner: pane(0),- });- expect(activated).toEqual([pane(0)]);- });-- it('checks again before running a waiting action that a new Back overtook', async () => {- const { router, history, pane, paneStore } = track(setup('/home'));- router.navigatePane(pane(0), '/mail');- let allow: (allowed: boolean) => void = () => {};- router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {- if (cause !== 'external') return true;-- return new Promise<boolean>((resolve) => {- allow = resolve;- });- });- let redirected = false;- const stopRedirecting = createRoot((dispose) => {- createEffect(() => {- const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';- const redirects = showsDrive && !redirected;- if (!redirects) return;-- redirected = true;- untrack(() =>- router.navigatePane(pane(0), '/drive/folder/f1', { replace: true })- );- });-- return dispose;- });-- router.navigatePane(pane(0), '/drive');- history.back();- await Promise.resolve();- await Promise.resolve();- allow(true);- await router.settled();- stopRedirecting();-- expect(routeIds(router.entry(pane(0)))).toEqual(['drive', 'drive-folder']);- expect(history.index()).toBe(2);- expect(history.read().path).toBe('/drive/folder/f1');- expect(paneStore.read(pane(0))?.index).toBe(2);- });-- it('writes the URL again after the history adapter failed to write it', () => {- vi.spyOn(console, 'error').mockImplementation(() => {});- const history = createMemoryHistory('/home');- let failNext = false;- const flaky: HistoryAdapter = {- ...history,- write(location, writeOptions) {- if (failNext) {- failNext = false;- throw new Error('write failed');- }-- history.write(location, writeOptions);- },- };- const { router, pane } = track(setup('/home', { history: flaky }));-- failNext = true;- router.navigatePane(pane(0), '/mail');- router.rewriteCurrent(pane(0), '/mail');-- expect(history.read().path).toBe('/mail');- });-- it('ignores a host location outside the router’s base', () => {- vi.useFakeTimers();- const { router, solid } = track(setupSolid('/app/mail'));- vi.runAllTimers();-- solid.show('/elsewhere', undefined);- vi.runAllTimers();-- expect(routeIds(router.entry(router.panes()[0]!))).toEqual(['mail']);- });-- it('drops a URL write still queued when the router is disposed', () => {- vi.useFakeTimers();- const { router, solid, dispose } = setupSolid('/app/home');- vi.runAllTimers();-- router.navigatePane(router.panes()[0]!, '/mail');- dispose();- vi.runAllTimers();-- expect(solid.calls.map(([to]) => to)).toEqual(['/home']);- });-- it('asks leave guards when Back or Forward leaves the router’s routes', () => {- vi.useFakeTimers();- const { router, solid } = track(setupSolid('/app/home', ['/settings']));- vi.runAllTimers();- const guard = vi.fn(() => false);- router.registerGuard(router.panes()[0]!, PANE_ROUTE_LEVEL, guard);-- expect(solid.pop(1).defaultPrevented).toBe(true);- expect(guard).toHaveBeenCalledTimes(1);- expect(solid.landed()).toBe('/app/home');-- guard.mockReturnValue(true);- expect(solid.pop(1).defaultPrevented).toBe(false);- expect(solid.landed()).toBe('/settings');- });-- it('drops a queued write when a navigation leaves the router’s routes', () => {- vi.useFakeTimers();- const { router, solid } = track(setupSolid('/app/home'));- vi.runAllTimers();-- router.navigatePane(router.panes()[0]!, '/mail');- expect(solid.leave('/settings').defaultPrevented).toBe(false);- vi.runAllTimers();-- expect(solid.calls.map(([to]) => to)).toEqual(['/home']);- });-- it('moves the cursor on Back to an entry that looks like the current one', () => {- const { router, history, paneStore, pane } = track(setup('/home'));- router.navigatePane(pane(0), '/home', { props: { note: 1 } });- expect(paneStore.read(pane(0))?.entries).toHaveLength(2);-- history.back();- expect(paneStore.read(pane(0))?.index).toBe(0);- expect(router.canGo(pane(0), -1)).toBe(false);-- history.forward();- expect(paneStore.read(pane(0))?.index).toBe(1);- expect(router.arrival(pane(0))).toBe('forward');- });-});diff --git a/apps/web/src/lib/split-router/next/tests/routes.test.ts b/apps/web/src/lib/split-router/next/tests/routes.test.tsdeleted file mode 100644index 82d3f9a99c..0000000000--- a/apps/web/src/lib/split-router/next/tests/routes.test.ts+++ /dev/null@@ -1,365 +0,0 @@-import { describe, expect, it } from 'vitest';-import {- decodePanes,- encodePanes,- formatPanePath,- splitPanePaths,-} from '../routes/codec';-import { defineRoute } from '../routes/define';-import {- canonicalRoute,- createRoutesManifest,- decodePane,- formatPane,-} from '../routes/manifest';-import { compileRoutePattern } from '../routes/path';-import { claimOf, externalSearchKeys, ownsNamespace } from '../routes/queries';-import { resolveTarget } from '../routes/targets';-import type { PaneId, SplitLocation, SplitRouteState } from '../routes/types';-import {- appRoutes,- documentRoute,- driveRoute,- folderRoute,- mailRoute,- notFoundRoute,-} from './fixtures';--const routes = createRoutesManifest(appRoutes);-const matchIds = (route: SplitRouteState | undefined) =>- route?.matches.map((match) => match.id);-/** The pane route ids below the app route. */-const ids = (route: SplitRouteState | undefined) =>- matchIds(route)?.filter((id) => id !== 'app');-const decodeUrl = (path: string, search = '') =>- decodePanes(routes, { path, search, hash: '' }).panes.map((pane) =>- matchIds(pane.entry.location.route)- );-const at = (path: string): SplitLocation => ({- route: decodePane(routes, path.split('/').filter(Boolean))!,-});--describe('route matching', () => {- it('prefers specific routes regardless of declaration order', () => {- expect(ids(decodePane(routes, ['mail', 't1']))).toEqual([- 'mail',- 'mail-thread',- ]);- expect(ids(decodePane(routes, ['md', 'doc']))).toEqual(['block']);- expect(ids(decodePane(routes, ['drive', 'md', 'doc']))).toEqual([- 'drive',- 'drive-document',- ]);- expect(ids(decodePane(routes, ['drive', 'folder']))).toEqual([- 'drive',- 'drive-folder',- ]);- expect(decodePane(routes, ['drive', 'folder', 'f1'])?.matches[2]).toEqual({- id: 'drive-folder',- params: { folderId: 'f1' },- });- });-- it('moves to the next branch when a params schema rejects the match', () => {- expect(ids(decodePane(routes, ['drive', 'garbage']))).toEqual([- 'not-found',- ]);- expect(ids(decodePane(routes, ['video', 'x']))).toEqual(['not-found']);- });-- it('matches static segments case-insensitively and formats the declared casing', () => {- const route = decodePane(routes, ['DRIVE', 'Folder']);- expect(ids(route)).toEqual(['drive', 'drive-folder']);- expect(formatPane(routes, route!)).toEqual(['drive', 'folder']);- });-- it('ranks a nested catch-all above the root catch-all', () => {- const driveMissing = defineRoute({ id: 'drive-missing', path: '*rest' });- const nested = createRoutesManifest({- ...appRoutes,- definitions: [- notFoundRoute,- { ...driveRoute, children: [folderRoute, documentRoute, driveMissing] },- ],- });- expect(ids(decodePane(nested, ['drive', 'garbage']))).toEqual([- 'drive',- 'drive-missing',- ]);- expect(ids(decodePane(nested, ['elsewhere']))).toEqual(['not-found']);- });-- it('matches a route without a path only through its children', () => {- expect(matchIds(decodePane(routes, ['home']))).toEqual(['app', 'home']);- expect(decodePane(routes, [])).toBeUndefined();- expect(formatPane(routes, decodePane(routes, ['mail', 't1'])!)).toEqual([- 'mail',- 't1',- ]);- });-- it('matches an empty pane with an empty path', () => {- const withBase = createRoutesManifest({- ...appRoutes,- definitions: [- defineRoute({ id: 'base', path: '' }),- ...appRoutes.definitions,- ],- });- expect(matchIds(decodePane(withBase, []))).toEqual(['base']);- expect(formatPanePath(withBase, decodePane(withBase, [])!)).toBe('/');- });-- it('expands adjacent optional params into prefixes only', () => {- const pattern = compileRoutePattern({ path: 'a/:b?/:c?' });- expect(pattern.alternatives.map((tokens) => tokens.length)).toEqual([- 1, 2, 3,- ]);- });-- it('rejects invalid declarations', () => {- const home = defineRoute({ id: 'home', path: 'home' });- expect(() =>- createRoutesManifest({ ...appRoutes, definitions: [home, home] })- ).toThrow(/Duplicate split route id/);- expect(() =>- createRoutesManifest({- ...appRoutes,- definitions: [home, defineRoute({ id: 'other', path: '/home/' })],- })- ).toThrow(/Duplicate sibling split route path/);- expect(() =>- createRoutesManifest({- ...appRoutes,- definitions: [defineRoute({ id: 'bad', path: '*rest/after' })],- })- ).toThrow(/catch-all/);- expect(() =>- createRoutesManifest({ ...appRoutes, definitions: [{ id: 'empty' }] })- ).toThrow(/has no path, so it needs children/);- expect(() =>- createRoutesManifest({- ...appRoutes,- definitions: [- home,- defineRoute({- id: 'layout',- children: [defineRoute({ id: 'nested-home', path: 'home' })],- }),- ],- })- ).toThrow(/Duplicate sibling split route path/);- });-});--describe('route queries', () => {- it('uses the deepest claim and falls back to ancestors', () => {- expect(claimOf(routes, at('/drive/md/d1').route)).toBe('block:md:d1');- expect(claimOf(routes, at('/mail/t1').route)).toBe('block:email:t1');- expect(claimOf(routes, at('/mail').route)).toBeUndefined();- });-- it('restricts search only where a route lists namespaces', () => {- const drive = at('/drive/folder/f1').route;- expect(ownsNamespace(routes, drive, 'drive')).toBe(true);- expect(ownsNamespace(routes, drive, 'mail')).toBe(false);- expect(ownsNamespace(routes, at('/mail/t1').route, 'anything')).toBe(true);- });-- it('keeps global and route-owned unprefixed search keys', () => {- const withExternal = createRoutesManifest({- ...appRoutes,- definitions: [- ...appRoutes.definitions,- defineRoute({ id: 'pdf', path: 'viewer', externalSearch: ['page'] }),- ],- });- const keys = externalSearchKeys(withExternal, [- { id: 'e', location: { route: decodePane(withExternal, ['viewer'])! } },- ]);- expect([...keys].sort()).toEqual(['page', 'referral_code']);- });-});--describe('panes codec', () => {- it('decodes each pane on its own, so an unmatched app pane is not found', () => {- const decoded = decodePanes(routes, {- path: '/mail/t1/~/no/such/place/~/drive',- search: '',- hash: '',- });- expect(decoded.panes.map((pane) => ids(pane.entry.location.route))).toEqual(- [['mail', 'mail-thread'], ['not-found'], ['drive']]- );- expect(decoded.panes[1]!.entry.location.route.matches[1]!.params).toEqual({- segments: ['no', 'such', 'place'],- });- });-- it('redirects a URL no top-level route handles to the default route', () => {- const home = [['app', 'home']];- expect(decodeUrl('/no/such/place')).toEqual(home);- expect(decodeUrl('/')).toEqual(home);- expect(decodeUrl('/login/~/home')).toEqual(home);- expect(decodeUrl('/mail/~/login')).toEqual(home);- expect(decodeUrl('/login')).toEqual([['login']]);- });-- it('shows a top-level catch-all as the 404 page', () => {- const withPage = createRoutesManifest({- ...appRoutes,- definitions: [- ...appRoutes.definitions,- defineRoute({ id: 'page-not-found', path: '*path' }),- ],- });- const decode = (path: string) =>- decodePanes(withPage, { path, search: '', hash: '' }).panes.map((pane) =>- matchIds(pane.entry.location.route)- );- expect(decode('/no/such/place')).toEqual([['page-not-found']]);- expect(decode('/home')).toEqual([['app', 'home']]);- expect(decode('/no/such/place/~/home')).toEqual([['app', 'home']]);- });-- it('reads pane and entry ids back only when the pane count matches', () => {- const state = {- panes: [- { pane: 'p1' as PaneId, entry: 'e1' },- { pane: 'p2' as PaneId, entry: 'e2' },- ],- };- const matching = decodePanes(routes, {- path: '/home/~/mail',- search: '',- hash: '',- state,- });- expect(matching.panes.map((pane) => [pane.paneId, pane.entry.id])).toEqual([- ['p1', 'e1'],- ['p2', 'e2'],- ]);- const mismatched = decodePanes(routes, {- path: '/home',- search: '',- hash: '',- state,- });- expect(mismatched.panes[0]!.paneId).toBeUndefined();- });-- it('frames search by pane and drops namespaces a route does not own', () => {- const decoded = decodePanes(routes, {- path: '/drive/~/mail',- search: '?s0.drive.sort=name&s0.other.x=1&s1.mail.tab=inbox',- hash: '',- });- expect(decoded.panes.map((pane) => pane.entry.location.search)).toEqual([- { drive: { sort: ['name'] } },- { mail: { tab: ['inbox'] } },- ]);- });-- it('encodes panes, keeps owned unprefixed keys, and keeps the hash while the path is unchanged', () => {- const entry = {- id: 'e1',- location: {- ...at('/drive/folder/f1'),- search: { drive: { sort: ['name'] } },- },- };- const mail = { id: 'e2', location: at('/mail/t1') };- const encoded = encodePanes(- routes,- [- { paneId: 'p1' as PaneId, entry },- { paneId: 'p2' as PaneId, entry: mail },- ],- {- path: '/drive/folder/f1/~/mail/t1',- search: '?referral_code=r&junk=1',- hash: '#h',- }- );- expect(encoded).toEqual({- path: '/drive/folder/f1/~/mail/t1',- search: '?referral_code=r&s0.drive.sort=name',- hash: '#h',- state: {- panes: [- { pane: 'p1', entry: 'e1' },- { pane: 'p2', entry: 'e2' },- ],- },- });- expect(- encodePanes(routes, [{ paneId: 'p2' as PaneId, entry: mail }], encoded)- .hash- ).toBe('');- });-- it('keeps every unprefixed key while a route with externalSearch "*" shows', () => {- const login = { id: 'e1', location: at('/login') };- const encoded = encodePanes(- routes,- [{ paneId: 'p1' as PaneId, entry: login }],- { path: '/home', search: '?email=a&next=b&s0.drive.sort=name', hash: '' }- );- expect(encoded.search).toBe('?email=a&next=b');- });-- it('escapes a literal separator value so it round-trips', () => {- const route = canonicalRoute(routes, {- matches: [- { id: 'app', params: {} },- { id: 'block', params: { type: 'md', id: '~' } },- ],- })!;- const path = formatPanePath(routes, route);- expect(path).toBe('/md/%7E');- expect(splitPanePaths(path)).toEqual([['md', '%7E']]);- expect(- decodePanes(routes, { path, search: '', hash: '' }).panes[0]!.entry- .location.route.matches[1]!.params- ).toEqual({ type: 'md', id: '~' });- });-});--describe('target resolution', () => {- const folder: SplitLocation = {- ...at('/drive/folder/f1'),- search: { drive: { sort: ['name'] } },- };-- it('resolves relative paths against the calling route', () => {- expect(- ids(resolveTarget(routes, folder, 'md/d1', { depth: 2 })?.route)- ).toEqual(['drive', 'drive-document']);- expect(- resolveTarget(routes, folder, '../f2', { depth: 3 })?.route.matches[2]- ).toEqual({ id: 'drive-folder', params: { folderId: 'f2' } });- expect(ids(resolveTarget(routes, folder, '/mail/t2')?.route)).toEqual([- 'mail',- 'mail-thread',- ]);- });-- it('inherits ancestor params and carries search only within the same root', () => {- const document = resolveTarget(routes, folder, {- route: documentRoute,- params: { documentType: 'md', documentId: 'd1' },- });- expect(ids(document?.route)).toEqual(['drive', 'drive-document']);- expect(document?.search).toEqual({ drive: { sort: ['name'] } });- expect(- resolveTarget(routes, folder, { route: mailRoute })?.search- ).toBeUndefined();- });-- it('applies search updates and drops namespaces the destination does not own', () => {- const location = resolveTarget(routes, folder, '/drive', {- search: { drive: { view: ['grid'] }, mail: { tab: ['x'] } },- });- expect(location?.search).toEqual({ drive: { view: ['grid'] } });- });-});diff --git a/apps/web/src/lib/split-router/next/tests/solid.test.tsx b/apps/web/src/lib/split-router/next/tests/solid.test.tsxdeleted file mode 100644index 1cda67a5f0..0000000000--- a/apps/web/src/lib/split-router/next/tests/solid.test.tsx+++ /dev/null@@ -1,523 +0,0 @@-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { createEffect, For, type JSX, onCleanup, onMount } from 'solid-js';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { z } from 'zod';-import { createMemoryHistory, type MemoryHistory } from '../history/memory';-import { createMemoryPaneStore } from '../panes/memory-store';-import { createSplitRouter, type SplitRouter } from '../router/create-router';-import { defineRoute } from '../routes/define';-import type {- Entry,- PaneId,- SplitRouteState,- SplitRoutes,-} from '../routes/types';-import { SplitRouterProvider, useSplitRouter } from '../solid/context';-import { createSearchParams } from '../solid/create-search-params';-import {- useCanGo,- useMatches,- useNavigate,- usePane,- usePendingNavigation,- useRouteParams,-} from '../solid/hooks';-import { Outlet } from '../solid/outlet';-import { PaneScope } from '../solid/pane-scope';-import { Route } from '../solid/route';-import { Router } from '../solid/router';-import { useBeforeLeave } from '../solid/use-before-leave';-import { createTestPolicy } from './fixtures';--const counts = { drive: 0, document: 0 };-const documentTypeReads = vi.fn();-let allowLeave = true;--const documentRoute = defineRoute({- id: 'document',- path: ':documentType/:documentId',- params: z.object({- documentType: z.enum(['md', 'pdf']),- documentId: z.string().min(1),- }),- remountKey: ({ documentType }) => documentType,- component: DocumentView,-});--function DocumentView() {- const params = useRouteParams(documentRoute);- onMount(() => {- counts.document += 1;- });- createEffect(() => documentTypeReads(params.documentType));- return (- <p data-testid="document">{`${params.documentType}:${params.documentId}`}</p>- );-}--function DriveView() {- const navigate = useNavigate();- onMount(() => {- counts.drive += 1;- });- return (- <div>- <button type="button" onClick={() => navigate('md/d3')}>- relative- </button>- <Outlet />- </div>- );-}--function GuardedView() {- useBeforeLeave(() => allowLeave);- return <p data-testid="guarded">guarded</p>;-}--function ListView() {- const [search, setSearch] = createSearchParams({- namespace: 'list',- schema: z.object({ sort: z.enum(['name', 'date']) }),- defaults: { sort: 'name' as 'name' | 'date' },- });- return (- <button type="button" onClick={() => setSearch({ sort: 'date' })}>- {`sort:${search.sort}`}- </button>- );-}--const runs: Record<string, number> = {};-const bump = (key: string) => {- runs[key] = (runs[key] ?? 0) + 1;-};--/** Counts every reader a search change could wake, per pane. */-function ProbeView() {- const pane = usePane();- const [probe, setProbe] = createSearchParams({- namespace: 'probe',- schema: z.object({- sort: z.enum(['name', 'date']),- tags: z.array(z.string()),- }),- defaults: { sort: 'name' as 'name' | 'date', tags: ['all'] },- });- const [other] = createSearchParams({- namespace: 'other',- schema: z.object({ tab: z.enum(['a', 'b']) }),- defaults: { tab: 'a' as 'a' | 'b' },- });- const matches = useMatches();- const pending = usePendingNavigation();- const canGoForward = useCanGo(1);- const count = (reader: string) => bump(`${pane()}:${reader}`);-- onMount(() => count('mount'));- createEffect(() => count(`sort=${probe.sort}`));- createEffect(() => count(`tags=${probe.tags.join()}`));- createEffect(() => count(`tab=${other.tab}`));- createEffect(() => count(`matches=${matches().length}`));- createEffect(() => count(`pending=${pending()?.phase ?? 'none'}`));- createEffect(() => count(`canGo=${canGoForward()}`));-- const toggle = () => {- const sort = probe.sort === 'name' ? 'date' : 'name';-- setProbe({ sort }, { history: 'replace' });- };-- return (- <button type="button" onClick={toggle}>- {`probe:${pane()}`}- </button>- );-}--const paneRoutes = [- defineRoute({- id: 'drive',- path: 'drive',- component: DriveView,- children: [documentRoute],- }),- defineRoute({- id: 'probe',- path: 'probe',- search: ['probe', 'other'],- component: ProbeView,- }),- defineRoute({ id: 'home', path: 'home', component: () => <p>home</p> }),- defineRoute({ id: 'guarded', path: 'guarded', component: GuardedView }),- defineRoute({- id: 'list',- path: 'list',- search: ['list'],- component: ListView,- }),-];--const routes: SplitRoutes = {- definitions: [- defineRoute({ id: 'login', path: 'login', component: () => <p>login</p> }),- defineRoute({ id: 'app', children: paneRoutes }),- ],- defaultRoute: () => ({- matches: [- { id: 'app', params: {} },- { id: 'home', params: {} },- ],- }),-};--function PanelHeader() {- const matches = useMatches();- const canGoBack = useCanGo(-1);- const trail = () => matches().map((match) => match.id);-- return (- <header data-testid="header">- {`${trail().join('/')} back:${canGoBack()}`}- </header>- );-}--function GuardedChrome() {- useBeforeLeave(() => allowLeave);-- return null;-}--function Panel(props: { pane: PaneId }) {- return (- <PaneScope pane={props.pane}>- <PanelHeader />- <Outlet />- </PaneScope>- );-}--function renderRouter(- url: string,- view: (router: SplitRouter) => JSX.Element,- routeTable: SplitRoutes = routes-) {- const history: MemoryHistory = createMemoryHistory(url);- let router: SplitRouter | undefined;- render(() => {- const created = createSplitRouter({- routes: routeTable,- history,- paneStore: createMemoryPaneStore(),- policy: createTestPolicy().policy,- });- router = created;- onCleanup(() => created.dispose());- return (- <SplitRouterProvider router={created}>- {view(created)}- </SplitRouterProvider>- );- });- return { history, router: router! };-}--function renderPanes(- url: string,- renderPane: (pane: PaneId) => JSX.Element = (pane) => <Outlet pane={pane} />-) {- return renderRouter(url, (router) => (- <For each={router.panes()}>{renderPane}</For>- ));-}--beforeEach(() => {- counts.drive = 0;- counts.document = 0;- documentTypeReads.mockClear();- allowLeave = true;-- for (const key of Object.keys(runs)) {- delete runs[key];- }-});--afterEach(() => {- cleanup();- vi.restoreAllMocks();-});--describe('split router Solid bindings', () => {- it('keeps a view mounted while its remount key holds and updates params in place', () => {- const { router } = renderPanes('/drive/md/d1');- const pane = router.panes()[0]!;- expect(screen.getByTestId('document').textContent).toBe('md:d1');-- router.navigatePane(pane, '/drive/md/d2');- expect(screen.getByTestId('document').textContent).toBe('md:d2');- expect(counts).toEqual({ drive: 1, document: 1 });- expect(documentTypeReads).toHaveBeenCalledTimes(1);-- router.navigatePane(pane, '/drive/pdf/d2');- expect(counts).toEqual({ drive: 1, document: 2 });- });-- it('lets panel chrome around a prop-less outlet use the hooks', () => {- const { router } = renderPanes('/drive/md/d1', (pane) => (- <Panel pane={pane} />- ));- const pane = router.panes()[0]!;- expect(screen.getByTestId('header').textContent).toBe(- 'app/drive/document back:false'- );- expect(screen.getByTestId('document').textContent).toBe('md:d1');-- router.navigatePane(pane, '/home');- expect(screen.getByTestId('header').textContent).toBe('app/home back:true');- expect(screen.getByText('home')).toBeTruthy();- });-- it('asks a guard in pane chrome before the pane closes, not on navigations inside it', async () => {- const { router } = renderPanes('/home/~/drive/md/d1', (pane) => (- <PaneScope pane={pane}>- <GuardedChrome />- <Outlet />- </PaneScope>- ));- const second = router.panes()[1]!;- allowLeave = false;-- expect(router.navigatePane(second, '/home')).toMatchObject({- status: 'committed',- });- expect(await router.close(second)).toBe(false);-- allowLeave = true;- expect(await router.close(second)).toBe(true);- expect(router.panes()).toHaveLength(1);- });-- it('renders the first pane’s top-level route at the root, and a layout route renders each pane below it', async () => {- function PaneLayout() {- const router = useSplitRouter();- return (- <For each={router.panes()}>- {(pane) => (- <section data-testid="pane">- <PaneScope pane={pane}>- <GuardedChrome />- <Outlet />- </PaneScope>- </section>- )}- </For>- );- }- const layoutRoutes: SplitRoutes = {- ...routes,- definitions: [- routes.definitions[0]!,- defineRoute({ id: 'app', component: PaneLayout, children: paneRoutes }),- ],- };- const { router, history } = renderRouter(- '/home/~/drive',- () => <Outlet />,- layoutRoutes- );- expect(screen.getAllByTestId('pane')).toHaveLength(2);- expect(screen.getByText('home')).toBeTruthy();- expect(counts.drive).toBe(1);-- allowLeave = false;- const second = router.panes()[1]!;- expect(router.navigatePane(second, '/home')).toMatchObject({- status: 'committed',- });- expect(screen.getAllByText('home')).toHaveLength(2);- expect(await router.close(second)).toBe(false);-- allowLeave = true;- await router.navigatePane(router.panes()[0]!, '/login');- expect(screen.getByText('login')).toBeTruthy();- expect(screen.queryAllByTestId('pane')).toHaveLength(0);- expect(history.read().path).toBe('/login');- });-- it('re-runs only the readers of the search field that changed', () => {- let paneRenders = 0;- const { router } = renderPanes('/probe/~/probe', (pane) => {- paneRenders += 1;-- return <Outlet pane={pane} />;- });- const [first, second] = router.panes();- const before = { ...runs };-- fireEvent.click(screen.getByText(`probe:${first}`));-- const woken = Object.keys(runs).filter((key) => runs[key] !== before[key]);- expect(woken).toEqual([`${first}:sort=date`]);- expect(paneRenders).toBe(2);- expect(runs[`${second}:mount`]).toBe(1);- });-- it('resolves relative paths against the calling route', () => {- renderPanes('/drive/md/d1');- fireEvent.click(screen.getByText('relative'));- expect(screen.getByTestId('document').textContent).toBe('md:d3');- });-- it('runs leave guards before unmounting a view but not for search changes', () => {- const { router, history } = renderPanes('/guarded');- const pane = router.panes()[0]!;- allowLeave = false;- router.navigatePane(pane, '/home');- expect(screen.getByTestId('guarded')).toBeTruthy();- router.updateSearch(pane, 'anything', { x: ['1'] });- expect(history.read().search).toBe('?s0.anything.x=1');- allowLeave = true;- router.navigatePane(pane, '/home');- expect(screen.queryByTestId('guarded')).toBeNull();- });-- it('reads and writes one search namespace and rewrites invalid values', () => {- const { history } = renderPanes('/list?s0.list.sort=bogus');- expect(screen.getByRole('button').textContent).toBe('sort:name');- expect(history.read().search).toBe('');- fireEvent.click(screen.getByRole('button'));- expect(screen.getByRole('button').textContent).toBe('sort:date');- expect(history.read().search).toBe('?s0.list.sort=date');- });-});--describe('<SplitRouter.Router>', () => {- const login = defineRoute({ id: 'login', path: 'login' });- const app = defineRoute({ id: 'app' });- const home = defineRoute({ id: 'home', path: 'home' });- const inbox = defineRoute({ id: 'inbox', path: 'inbox' });- const defaultRoute = (): SplitRouteState => ({- matches: [- { id: 'app', params: {} },- { id: 'home', params: {} },- ],- });-- function AppLayout() {- const router = useSplitRouter();- return (- <For each={router.panes()}>- {(pane) => (- <section data-testid="pane">- <Outlet pane={pane} />- </section>- )}- </For>- );- }-- it('builds the route tree from its children and renders the first pane’s top-level route', async () => {- let router: SplitRouter | undefined;- function Layout() {- router = useSplitRouter();- return <AppLayout />;- }- const history = createMemoryHistory('/home/~/inbox');- render(() => (- <Router- history={history}- paneStore={createMemoryPaneStore()}- policy={createTestPolicy().policy}- defaultRoute={defaultRoute}- >- <Route definition={login} component={() => <p>login</p>} />- <Route definition={app} component={Layout}>- <Route definition={home} component={() => <p>home</p>} />- <Route definition={inbox} component={() => <p>inbox</p>} />- </Route>- </Router>- ));-- expect(screen.getAllByTestId('pane')).toHaveLength(2);- expect(screen.getByText('inbox')).toBeTruthy();- expect(home).not.toHaveProperty('component');-- await router!.navigatePane(router!.panes()[0]!, '/login');- expect(screen.getByText('login')).toBeTruthy();- expect(screen.queryAllByTestId('pane')).toHaveLength(0);- expect(history.read().path).toBe('/login');- });-- it('reads routes from arrays and drops false children', () => {- const extra = [inbox].map((definition) => (- <Route definition={definition} component={() => <p>inbox</p>} />- ));- render(() => (- <Router- history={createMemoryHistory('/inbox')}- paneStore={createMemoryPaneStore()}- policy={createTestPolicy().policy}- defaultRoute={defaultRoute}- >- {false}- <Route definition={app} component={AppLayout}>- <Route definition={home} component={() => <p>home</p>} />- {extra}- </Route>- </Router>- ));- expect(screen.getByText('inbox')).toBeTruthy();- });-- it('passes the compiled routes to a history factory', () => {- const seen: string[] = [];- render(() => (- <Router- history={(routes) => {- seen.push(...routes.byId.keys());- return createMemoryHistory('/home');- }}- paneStore={createMemoryPaneStore()}- policy={createTestPolicy().policy}- defaultRoute={defaultRoute}- >- <Route definition={app} component={AppLayout}>- <Route definition={home} component={() => <p>home</p>} />- </Route>- </Router>- ));- expect(seen).toEqual(['app', 'home']);- });-- it('rejects definitions that already set children or a component', () => {- const withComponent = defineRoute({- id: 'bound',- path: 'bound',- component: () => null,- });- const options = {- history: createMemoryHistory('/bound'),- paneStore: createMemoryPaneStore<Entry>(),- policy: createTestPolicy().policy,- defaultRoute: (): SplitRouteState => ({- matches: [{ id: 'bound', params: {} }],- }),- };- expect(() =>- render(() => (- <Router {...options}>- {/* @ts-expect-error definitions passed to Route carry no component */}- <Route definition={withComponent} />- </Router>- ))- ).toThrow(/must not set children or component/);- expect(() =>- render(() => (- <Router {...options}>- <p>not a route</p>- </Router>- ))- ).toThrow(/must be <SplitRouter.Route> elements/);- });-});diff --git a/apps/web/src/lib/split-router/next/utils.ts b/apps/web/src/lib/split-router/next/utils.tsdeleted file mode 100644index 137aa6059a..0000000000--- a/apps/web/src/lib/split-router/next/utils.ts+++ /dev/null@@ -1,110 +0,0 @@-const SAFE_NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;-const MAX_NAME_LENGTH = 64;--/** Bounded identifier that is safe to use as an ordinary object key. */-export function isSafeName(value: string): boolean {- const reserved = value === 'constructor' || value === 'prototype';- const bounded = value.length <= MAX_NAME_LENGTH;-- return bounded && !reserved && SAFE_NAME.test(value);-}--export function isRecord(value: unknown): value is Record<string, unknown> {- const isObject = value !== null && typeof value === 'object';-- return isObject && !Array.isArray(value);-}--/** For work nothing can call off, such as hover preloads; it never aborts. */-export const UNCANCELLABLE: AbortSignal = new AbortController().signal;--export function isAbortError(error: unknown, signal?: AbortSignal): boolean {- if (signal?.aborted) return true;-- return error instanceof DOMException && error.name === 'AbortError';-}--let fallbackSequence = 0;--export function createId(prefix: string): string {- const random = globalThis.crypto?.randomUUID?.();- if (random) return `${prefix}_${random}`;-- fallbackSequence += 1;- const time = Date.now().toString(36);- const sequence = fallbackSequence.toString(36);-- return `${prefix}_${time}${sequence}`;-}--/** A value now, or later; only real promises leave the current tick. */-export type MaybePromise<T> = T | Promise<T>;--export function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {- return value instanceof Promise;-}--/** Applies `fn` now, or once `value` settles. */-export function mapMaybe<T, R>(- value: MaybePromise<T>,- fn: (value: T) => MaybePromise<R>-): MaybePromise<R> {- if (!isPromise(value)) return fn(value);-- return value.then(fn);-}--/** Runs `run`, turning a synchronous throw or a rejection into `onError`'s result. */-export function settleMaybe<T>(- run: () => MaybePromise<T>,- onError: (error: unknown) => T-): MaybePromise<T> {- let value: MaybePromise<T>;-- try {- value = run();- } catch (error) {- return onError(error);- }-- if (!isPromise(value)) return value;-- return value.catch(onError);-}--export const CANCELLED: unique symbol = Symbol('split-router.cancelled');--export type Cancelled = typeof CANCELLED;--/** A value, possibly async, or `CANCELLED` when the work was called off. */-export type Outcome<T> = MaybePromise<T | Cancelled>;--/**- * The next step, skipped once cancelled. Not named `then`: a module- * exporting `then` is a thenable, which breaks `await import()`.- */-export function andThen<T, R>(- value: Outcome<T>,- step: (value: T) => Outcome<R>-): Outcome<R> {- return mapMaybe(value, (resolved): Outcome<R> => {- if (resolved === CANCELLED) return CANCELLED;-- return step(resolved);- });-}--function unlessCancelled<T>(- resolved: readonly (T | Cancelled)[]-): T[] | Cancelled {- if (resolved.includes(CANCELLED)) return CANCELLED;-- return resolved as T[];-}--export function all<T>(values: readonly Outcome<T>[]): Outcome<T[]> {- const waiting = values.some(isPromise);- if (!waiting) return unlessCancelled(values as (T | Cancelled)[]);-- return mapMaybe(Promise.all(values), unlessCancelled);-}diff --git a/apps/web/src/lib/split-router/next/panes/diff.ts b/apps/web/src/lib/split-router/panes/diff.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/panes/diff.tsrename to apps/web/src/lib/split-router/panes/diff.tsdiff --git a/apps/web/src/lib/split-router/next/panes/history.ts b/apps/web/src/lib/split-router/panes/history.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/panes/history.tsrename to apps/web/src/lib/split-router/panes/history.tsdiff --git a/apps/web/src/lib/split-router/next/panes/index.ts b/apps/web/src/lib/split-router/panes/index.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/panes/index.tsrename to apps/web/src/lib/split-router/panes/index.tsdiff --git a/apps/web/src/lib/split-router/next/panes/memory-store.ts b/apps/web/src/lib/split-router/panes/memory-store.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/panes/memory-store.tsrename to apps/web/src/lib/split-router/panes/memory-store.tsdiff --git a/apps/web/src/lib/split-router/next/panes/panes.ts b/apps/web/src/lib/split-router/panes/panes.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/panes/panes.tsrename to apps/web/src/lib/split-router/panes/panes.tsdiff --git a/apps/web/src/lib/split-router/next/panes/types.ts b/apps/web/src/lib/split-router/panes/types.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/panes/types.tsrename to apps/web/src/lib/split-router/panes/types.tsdiff --git a/apps/web/src/lib/split-router/path.ts b/apps/web/src/lib/split-router/path.tsdeleted file mode 100644index 27fd319e3c..0000000000--- a/apps/web/src/lib/split-router/path.ts+++ /dev/null@@ -1,169 +0,0 @@-import type { SplitRouteParams, SplitRouteRawParams } from './types';--type PathToken =- | { type: 'static'; value: string }- | { type: 'param'; name: string; optional: boolean }- | { type: 'catchAll'; name: string };--type PatternMatch = {- params: SplitRouteRawParams;- consumed: number;-};--const PARAM_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;--function patternSegments(pattern: string): string[] {- return pattern- .replace(/^\/+|\/+$/g, '')- .split('/')- .filter(Boolean);-}--function routePatternTokens(pattern: string): readonly PathToken[] {- const tokens = patternSegments(pattern).map((segment): PathToken => {- if (segment.startsWith(':')) {- const optional = segment.endsWith('?');- const name = segment.slice(1, optional ? -1 : undefined);- if (!PARAM_NAME.test(name)) {- throw new Error(`Invalid split route parameter "${segment}"`);- }- return { type: 'param', name, optional };- }-- if (segment.startsWith('*')) {- const name = segment.slice(1);- if (!PARAM_NAME.test(name)) {- throw new Error(`Invalid split route catch-all parameter "${segment}"`);- }- return { type: 'catchAll', name };- }-- if (segment === '~') {- throw new Error(`Invalid split route path "${pattern}"`);- }-- return { type: 'static', value: segment };- });-- const catchAllIndex = tokens.findIndex((token) => token.type === 'catchAll');- if (catchAllIndex >= 0 && catchAllIndex !== tokens.length - 1) {- throw new Error(- `Split route catch-all parameter must be the final segment in "${pattern}"`- );- }-- return tokens;-}--export type RoutePattern = {- match(segments: readonly string[]): IterableIterator<PatternMatch>;- format(params: SplitRouteParams): string[];-};--export function compileRoutePattern(options: {- path: string;- aliases?: readonly string[];-}): RoutePattern {- const canonical = routePatternTokens(options.path);- const alternatives = [- canonical,- ...(options.aliases ?? []).map(routePatternTokens),- ];- return {- *match(segments) {- // Stay lazy: only try aliases if canonical matching/validation/children fail.- for (const tokens of alternatives) yield* matchTokens(tokens, segments);- },- format: (params) => formatTokens(canonical, params),- };-}--function matchTokens(- tokens: readonly PathToken[],- segments: readonly string[]-): PatternMatch[] {- const matches: PatternMatch[] = [];-- const visit = (- tokenIndex: number,- segmentIndex: number,- params: SplitRouteRawParams- ) => {- const token = tokens[tokenIndex];- if (!token) {- matches.push({ params, consumed: segmentIndex });- return;- }-- if (token.type === 'static') {- if (segments[segmentIndex] !== token.value) return;- visit(tokenIndex + 1, segmentIndex + 1, params);- return;- }-- if (token.type === 'catchAll') {- const value = segments.slice(segmentIndex);- if (value.length === 0) return;- visit(tokens.length, segments.length, { ...params, [token.name]: value });- return;- }-- const value = segments[segmentIndex];- if (value !== undefined) {- visit(tokenIndex + 1, segmentIndex + 1, {- ...params,- [token.name]: value,- });- }- if (token.optional) visit(tokenIndex + 1, segmentIndex, params);- };-- visit(0, 0, {});- return matches;-}--function serializeValue(value: unknown, name: string): string {- if (- typeof value === 'string' ||- typeof value === 'number' ||- typeof value === 'boolean' ||- typeof value === 'bigint'- ) {- return String(value);- }-- throw new Error(`Split route parameter "${name}" requires serializeParams`);-}--function formatTokens(- tokens: readonly PathToken[],- params: SplitRouteParams-): string[] {- const segments: string[] = [];-- for (const token of tokens) {- if (token.type === 'static') {- segments.push(token.value);- continue;- }-- const value = params[token.name];- if (token.type === 'catchAll') {- if (!Array.isArray(value) || value.length === 0) {- throw new Error(- `Missing split route catch-all parameter "${token.name}"`- );- }- segments.push(...value.map((item) => serializeValue(item, token.name)));- continue;- }-- if (value === undefined) {- if (token.optional) continue;- throw new Error(`Missing split route parameter "${token.name}"`);- }- segments.push(serializeValue(value, token.name));- }-- return segments;-}diff --git a/apps/web/src/lib/split-router/router.ts b/apps/web/src/lib/split-router/router.tsdeleted file mode 100644index 63de7751a8..0000000000--- a/apps/web/src/lib/split-router/router.ts+++ /dev/null@@ -1,974 +0,0 @@-import deepEqual from 'fast-deep-equal';-import { createClaimReservations } from './claims';-import { createEntryKey } from './entry-state';-import { createSplitRouterHistories } from './history';-import { createLayoutAdapter } from './layout';-import { createLocationSync } from './location-sync';-import { prepareEntries, prepareEntry } from './middleware';-import { resolveNavigation } from './navigation';-import {- assertRouteEntry,- assertSearchNamespacesAllowed,- createRoutesManifest,- filterRouteSearch,- getRouteClaim,- getRouteSearchNamespaces,- parseRouteEntryState,- type SplitRouteNode,- type SplitRoutesManifest,-} from './routes';-import {- assertSafeSearchName,- parseSplitSearch,- updateSearchState,-} from './search';-import { createTransitionManager, type Transition } from './transitions';-import type {- BrowserHistoryIntent,- SplitNavigateOptions,- SplitNavigateTo,- SplitRouteClaim,- SplitRouter,- SplitRouterEntry,- SplitRouterEntryState,- SplitRouterExternalLocationValue,- SplitRouterLayoutSnapshot,- SplitRouterOptions,- SplitRouterStateUpdate,- SplitSearchUpdate,-} from './types';-import {- decodeSplitRouterLocation,- parseExternalLocation,- serializeSplitRouterLocation,-} from './url';-import { isPromise, throwIfAborted } from './utils';--type CommitOptions = {- history: BrowserHistoryIntent;- preserveHash: boolean;- preserveExternalSearch?: boolean;-};--type LayoutTransition = {- entries: SplitRouterEntry[];- cause: 'initial' | 'external' | 'layout';- externalSearch?: string;- apply: (entries: SplitRouterEntry[]) => void;-};--type ApplyOptions<TSplitId> = {- open?: SplitNavigateOptions<TSplitId>['open'];- entry: SplitRouterEntry;- target: TSplitId | 'new-split';- replace: boolean;- history: BrowserHistoryIntent;- preserveHash: boolean;- requireTarget?: boolean;- recordHistory?: boolean;-};--type EntryTransition<TSplitId> = {- key: unknown;- splitId?: TSplitId;- entry: SplitRouterEntry;- from: SplitRouterEntry | undefined;- cause: 'navigate' | 'history' | 'search';- allowDuplicate?: boolean;- apply: (entry: SplitRouterEntry) => boolean;- onReuse?: (splitId: TSplitId, entry: SplitRouterEntry) => boolean;- onApplied?: () => void;-};--const GLOBAL_TRANSITION = Symbol('split-router-global-transition');--function resolveNavigationEntryState(- routes: SplitRoutesManifest,- route: SplitRouterEntry['location']['route'],- current: SplitRouterEntry | undefined,- update: SplitRouterStateUpdate-): SplitRouterEntryState | undefined {- const destinationRouteId = route.matches.at(-1)!.id;- const destinationSchema = routes.byId.get(destinationRouteId)?.state;- let currentSchema: SplitRouteNode['state'];- if (current) {- const currentRouteId = current.location.route.matches.at(-1)!.id;- currentSchema = routes.byId.get(currentRouteId)?.state;- }-- let currentState: SplitRouterEntryState;- if (current && currentSchema === destinationSchema) {- currentState = current.state;- }-- let value = update;- if (typeof update === 'function') value = update(currentState);- const parsed = parseRouteEntryState(routes, route, value);- if (!parsed.success) {- const routeId = route.matches.at(-1)?.id ?? 'unknown';- throw new Error(`Split route "${routeId}" rejected navigation state`);- }- if (parsed.value === undefined) return;-- try {- return structuredClone(parsed.value);- } catch (error) {- console.warn(- 'Split route state could not be cloned; continuing without state',- error- );- return;- }-}--export function createSplitRouter<TSplitId>(- options: SplitRouterOptions<TSplitId>-): SplitRouter<TSplitId> {- let routes: SplitRoutesManifest;- if ('definitions' in options.routes) {- routes = createRoutesManifest(options.routes);- } else {- routes = options.routes;- }-- const middleware = options.middleware ?? [];- const claims = createClaimReservations();- const entryControllers = new Map<unknown, AbortController>();- const subscribers = new Set<(splitId: TSplitId | undefined) => void>();- let accepted: SplitRouterEntry[] = [];- let acceptedIds: TSplitId[] = [];- let expectedLayout: SplitRouterLayoutSnapshot<TSplitId> | undefined;- let layoutChangeQueued = false;- let queuedHistory: BrowserHistoryIntent = 'push';- let ready = false;- let disposed = false;-- const locationSync = createLocationSync({- routes,- location: options.location,- });- const middlewareConfig = { routes, handlers: middleware };- const layout = createLayoutAdapter(options.layout, routes);- const histories = createSplitRouterHistories<TSplitId, SplitRouterEntry>(- layout.entryEquals,- layout.entryIdentityEquals- );-- const reconcileHistories = (- intent: BrowserHistoryIntent,- mode: 'move' | 'write'- ) => {- histories.reconcile(- accepted.map((entry, index) => ({ id: acceptedIds[index]!, entry })),- intent,- mode- );- };-- const notify = (splitId?: TSplitId) => {- for (const listener of subscribers) listener(splitId);- };-- const normalizeEntry = (- entry: SplitRouterEntry,- previous?: SplitRouterEntry- ): SplitRouterEntry => {- const preservePrevious =- !entry.key &&- previous !== undefined &&- deepEqual(previous.location, entry.location);- const hasEntryState = Object.hasOwn(entry, 'state');- let parsedState: SplitRouterEntry['state'];- if (!hasEntryState && preservePrevious && previous) {- parsedState = previous.state;- } else {- const state = hasEntryState ? entry.state : undefined;- const parsed = parseRouteEntryState(routes, entry.location.route, state);- if (parsed.success && parsed.value !== undefined) {- try {- parsedState = structuredClone(parsed.value);- } catch {- parsedState = undefined;- }- }- }- let key = entry.key;- if (!key && preservePrevious && previous) key = previous.key;- if (!key) key = createEntryKey();-- const { state: _state, ...rest } = entry;- const normalized: SplitRouterEntry = { ...rest, key };- if (parsedState !== undefined) normalized.state = parsedState;- return normalized;- };-- const normalizeEntries = (- entries: SplitRouterEntry[],- previous: readonly (SplitRouterEntry | undefined)[] = []- ) => entries.map((entry, index) => normalizeEntry(entry, previous[index]));-- const acceptedById = () => {- const entries = new Map<TSplitId, SplitRouterEntry>();- accepted.forEach((entry, index) => {- entries.set(acceptedIds[index] as TSplitId, entry);- });- return entries;- };-- const acceptedInLayoutOrder = () => {- const byId = acceptedById();- return layout.snapshot().entries.map(({ splitId, location }) => {- const entry = byId.get(splitId);- if (!entry || !deepEqual(entry.location, location)) return;- return entry;- });- };-- const bindAccepted = (entries: SplitRouterEntry[]) => {- const snapshot = layout.snapshot().entries;- accepted = snapshot.map(({ location }, index) => {- const entry = entries[index];- if (entry && deepEqual(entry.location, location)) return entry;- return normalizeEntry({ location });- });- acceptedIds = snapshot.map(({ splitId }) => splitId);- };-- const validateRedirectedState = (- entry: SplitRouterEntry,- proposed: SplitRouterEntry- ) => {- const entryRouteId = entry.location.route.matches.at(-1)!.id;- const proposedRouteId = proposed.location.route.matches.at(-1)!.id;- const entrySchema = routes.byId.get(entryRouteId)?.state;- const proposedSchema = routes.byId.get(proposedRouteId)?.state;-- if (entrySchema === proposedSchema) return entry;- return normalizeEntry(entry);- };-- const transitions = createTransitionManager<TSplitId, SplitRouterEntry>({- onError(error) {- console.error('Split router transition failed', error);- },- onSettled(splitId, publicStateChanged) {- const becameReady = !ready;- ready = true;- if (becameReady) {- notify();- } else if (publicStateChanged) {- notify(splitId);- }- },- });- const findEntry = (splitId: TSplitId) => {- const pending = transitions.pending(splitId);- if (pending) return pending;-- const index = acceptedIds.findIndex((id) => Object.is(id, splitId));- if (index < 0) return;- return accepted[index];- };- // A settled destination with the same URL and route state needs no new key,- // transition, history entry, or middleware run.- const isCurrentDestination = (splitId: TSplitId, entry: SplitRouterEntry) => {- if (transitions.has(GLOBAL_TRANSITION) || transitions.pending(splitId))- return false;- const current = findEntry(splitId);- return (- current !== undefined &&- deepEqual(current.location, entry.location) &&- Object.is(current.state, entry.state)- );- };-- const findClaimedSplit = (- claim: SplitRouteClaim,- targetId: TSplitId | undefined- ) =>- layout- .snapshot()- .entries.find(- (candidate) =>- !Object.is(candidate.splitId, targetId) &&- deepEqual(getRouteClaim(routes, candidate.location.route), claim)- );-- const claimToAcquire = (- entry: SplitRouterEntry,- config: EntryTransition<TSplitId>- ) => {- if (config.allowDuplicate) return;- const claim = getRouteClaim(routes, entry.location.route);- let current: SplitRouterEntry | undefined;- if (config.splitId !== undefined) current = layout.find(config.splitId);- // Updating an existing owner is not a new acquisition. In particular,- // search/parameter updates must not collapse restored duplicate panes.- if (- current &&- deepEqual(getRouteClaim(routes, current.location.route), claim)- )- return;- return claim;- };-- const notifyLayoutChanges = (- before: SplitRouterEntry[],- after: SplitRouterEntry[]- ) => {- for (const splitId of layout.changedIds(before, after)) {- notify(splitId);- }- };-- const expectLayoutEcho = () => {- expectedLayout = layout.snapshot();- };-- const reconcileEntries = (- current: SplitRouterEntry[],- requested: SplitRouterEntry[]- ): boolean => {- if (!layout.reconcile(current, requested)) {- return false;- }-- expectLayoutEcho();- return true;- };-- const commitLayout = (commit: CommitOptions) => {- locationSync.commit(accepted, commit);- };-- const abortAllTransitions = (publish = true) => {- for (const controller of [...entryControllers.values()]) controller.abort();- const hadPendingEntries = transitions.abortAll();- if (publish && hadPendingEntries) notify();- };-- const cancelTargetTransition = (key: unknown) => {- if (transitions.has(GLOBAL_TRANSITION)) abortAllTransitions();- entryControllers.get(key)?.abort();- transitions.cancel(key);- };-- const applyDecoded = (entries: SplitRouterEntry[]) => {- const layoutChanged = reconcileEntries(layout.entries(), entries);- bindAccepted(entries);- reconcileHistories('replace', 'move');- commitLayout({ history: 'replace', preserveHash: true });- const becameReady = !ready;- ready = true;- if (layoutChanged || becameReady) notify();- };-- const transitionLayout = (transition: LayoutTransition) => {- abortAllTransitions();- let previous: Array<SplitRouterEntry | undefined> = [];- if (transition.cause === 'layout') {- previous = acceptedInLayoutOrder();- } else if (transition.cause === 'external') {- previous = accepted.map((entry) => {- if (Object.hasOwn(entry, 'state')) return;- return entry;- });- }- const entries = normalizeEntries(transition.entries, previous);- if (middleware.length === 0) {- transition.apply(entries);- return;- }-- const controller = new AbortController();- const validatePrepared = (prepared: SplitRouterEntry[]) =>- prepared.map((entry, index) =>- validateRedirectedState(entry, entries[index]!)- );- let from: SplitRouterEntry[] | undefined = accepted;- if (transition.cause === 'initial') from = undefined;-- const prepared = prepareEntries(middlewareConfig, {- from,- to: entries,- cause: transition.cause,- externalSearch: transition.externalSearch,- signal: controller.signal,- });-- if (!isPromise(prepared)) {- transition.apply(validatePrepared(prepared));- return;- }-- void transitions.start(GLOBAL_TRANSITION, {- controller,- async run() {- const result = await prepared;- throwIfAborted(controller.signal);- transition.apply(validatePrepared(result));- },- });- };-- const applyInbound = (- external: SplitRouterExternalLocationValue,- cause: 'initial' | 'external'- ) => {- if (cause === 'external' && locationSync.acknowledge(external)) return;-- const decoded = decodeSplitRouterLocation({- routes,- location: external,- });-- transitionLayout({- entries: decoded.entries,- cause,- externalSearch: decoded.externalLocation.search,- apply: applyDecoded,- });- };-- bindAccepted(normalizeEntries(layout.entries()));-- const applyPrepared = (- original: SplitRouterEntry[],- prepared: SplitRouterEntry[],- history: BrowserHistoryIntent- ) => {- const before = accepted;-- reconcileEntries(original, prepared);- bindAccepted(prepared);- reconcileHistories(history, 'move');- commitLayout({- history,- preserveHash: false,- preserveExternalSearch: false,- });- const becameReady = !ready;- ready = true;- if (becameReady) notify();- else notifyLayoutChanges(before, accepted);- };-- const onLayoutChange = (history: BrowserHistoryIntent) => {- if (disposed) return;-- const snapshot = layout.snapshot();- const entries = snapshot.entries.map(- ({ splitId: _splitId, ...entry }) => entry- );- if (- expectedLayout &&- layout.snapshotsEqual(expectedLayout.entries, snapshot.entries)- ) {- expectedLayout = undefined;- return;- }- expectedLayout = undefined;-- transitionLayout({- entries,- cause: 'layout',- apply: (prepared) => applyPrepared(entries, prepared, history),- });- };-- const applyEntry = (config: ApplyOptions<TSplitId>): boolean => {- const previousById = acceptedById();- const result = layout.apply({- open: config.open,- entry: config.entry,- target: config.target,- replace: config.replace,- requireExistingTarget: config.requireTarget,- });- if (!result.changed) return false;-- if (result.layoutChanged) expectLayoutEcho();-- const snapshot = layout.snapshot().entries;- accepted = snapshot.map(({ splitId, location }) => {- if (Object.is(result.splitId, splitId)) return config.entry;-- const previous = previousById.get(splitId);- if (previous && deepEqual(previous.location, location)) return previous;- return normalizeEntry({ location });- });- acceptedIds = snapshot.map(({ splitId }) => splitId);- if (config.recordHistory !== false) {- reconcileHistories(config.history, 'write');- }- commitLayout({- history: config.history,- preserveHash: config.preserveHash,- preserveExternalSearch: false,- });- return true;- };-- const publishEntry = (- transition: EntryTransition<TSplitId>,- entry: SplitRouterEntry- ) => {- const changed = transition.apply(entry);- if (changed) notify(transition.splitId);- if (changed) transition.onApplied?.();- return changed;- };-- const startAsyncEntry = (- config: EntryTransition<TSplitId>,- controller: AbortController,- prepared: Promise<SplitRouterEntry | undefined>,- finish: () => void,- checkClaim: (entry: SplitRouterEntry) => SplitRouterEntry | undefined- ) => {- const { splitId } = config;- let pending: SplitRouterEntry | undefined;- let onSettled:- | ((transition: Transition<SplitRouterEntry>) => boolean)- | undefined;- if (splitId !== undefined) {- pending = config.entry;- onSettled = (transition) =>- !layout.entryEquals(transition.pending, layout.find(splitId));- }-- void transitions.start(config.key, {- controller,- target: splitId,- pending,- async run(transition) {- try {- const entry = await prepared;- throwIfAborted(controller.signal);- if (!entry) return;- assertRouteEntry(routes, entry);-- if (- splitId !== undefined &&- !layout.entryEquals(transition.pending, entry)- ) {- transition.pending = entry;- notify(splitId);- }-- // Pending-state subscribers may navigate or create another owner.- // Recheck synchronously at the actual commit boundary.- throwIfAborted(controller.signal);- if (!checkClaim(entry)) return;- throwIfAborted(controller.signal);- const changed = config.apply(entry);- if (changed && splitId === undefined) notify();- if (changed) config.onApplied?.();- } finally {- finish();- }- },- onSettled,- });-- if (splitId !== undefined) notify(splitId);- };-- const transitionEntry = (config: EntryTransition<TSplitId>) => {- const hadPending = transitions.pending(config.key) !== undefined;- cancelTargetTransition(config.key);- const controller = new AbortController();- const reservation = claims.reserve(undefined);- entryControllers.set(config.key, controller);- const finish = () => {- reservation.release();- controller.signal.removeEventListener('abort', finish);- if (entryControllers.get(config.key) === controller) {- entryControllers.delete(config.key);- }- };- controller.signal.addEventListener('abort', finish, { once: true });-- const reuseOrAccept = (- entry: SplitRouterEntry,- claim: SplitRouteClaim | undefined- ) => {- throwIfAborted(controller.signal);- const owner = claim && findClaimedSplit(claim, config.splitId);- if (!owner) return entry;- // Keep the accepted owner on the requested resource rather than allowing- // an in-flight departure to replace it immediately after activation.- const hadPending = transitions.pending(owner.splitId) !== undefined;- cancelTargetTransition(owner.splitId);- const updated = config.onReuse?.(owner.splitId, entry) ?? false;- layout.activate(owner.splitId);- if (hadPending || updated) notify(owner.splitId);- config.onApplied?.();- };- const waitForClaim = async (- turn: Promise<void>,- entry: SplitRouterEntry,- claim: SplitRouteClaim | undefined- ) => {- await turn;- // The earlier request may have committed, redirected, or failed.- return reuseOrAccept(entry, claim);- };- const accept = (entry: SplitRouterEntry) => {- throwIfAborted(controller.signal);- assertRouteEntry(routes, entry);- const normalized = validateRedirectedState(entry, config.entry);- const claim = claimToAcquire(normalized, config);- reservation.move(claim);- if (claim && findClaimedSplit(claim, config.splitId)) {- return reuseOrAccept(normalized, claim);- }- const turn = reservation.wait(controller.signal);- if (!isPromise(turn)) return reuseOrAccept(normalized, claim);- return waitForClaim(turn, normalized, claim);- };- try {- reservation.move(claimToAcquire(config.entry, config));- let prepared: SplitRouterEntry | Promise<SplitRouterEntry> = config.entry;- if (middleware.length > 0) {- prepared = prepareEntry(middlewareConfig, {- from: config.from,- to: config.entry,- cause: config.cause,- signal: controller.signal,- });- }-- let resolved:- | SplitRouterEntry- | Promise<SplitRouterEntry | undefined>- | undefined;- if (isPromise(prepared)) {- resolved = (async () => accept(await prepared))();- } else {- resolved = accept(prepared);- }- if (isPromise(resolved)) {- assertRouteEntry(routes, config.entry);- startAsyncEntry(config, controller, resolved, finish, (entry) =>- reuseOrAccept(entry, claimToAcquire(entry, config))- );- } else {- try {- let changed = false;- if (resolved) changed = publishEntry(config, resolved);- if (!changed && hadPending) notify(config.splitId);- } finally {- finish();- }- }- } catch (error) {- finish();- if (hadPending) notify(config.splitId);- throw error;- }- };-- const navigateHistory = (- splitId: TSplitId,- delta: number,- current: SplitRouterEntry,- navigateOptions: SplitNavigateOptions<TSplitId>- ) => {- if (- navigateOptions.target !== undefined &&- navigateOptions.target !== 'current'- ) {- return;- }- if (navigateOptions.search !== undefined) return;-- const history = histories.get(splitId);- if (!history) return;- const historical = history.peek(delta);- if (!historical) return;-- transitionEntry({- key: splitId,- splitId,- entry: historical,- from: current,- cause: 'history',- allowDuplicate: navigateOptions.allowDuplicate,- apply: (entry) => {- if (!layout.find(splitId)) return false;-- const changed = applyEntry({- entry,- target: splitId,- replace: true,- history: 'replace',- preserveHash: true,- requireTarget: true,- recordHistory: false,- });- const moved = history.go(delta);- if (moved && !layout.entryEquals(history.current(), entry)) {- history.replace(entry);- }- reconcileHistories('replace', 'write');-- return changed || moved;- },- });- };-- const unsubscribeLayout = options.layout.subscribe((change) => {- queuedHistory = change.history;- if (layoutChangeQueued) return;-- layoutChangeQueued = true;- queueMicrotask(() => {- layoutChangeQueued = false;- onLayoutChange(queuedHistory);- });- });- const unsubscribeLocation = options.location.subscribe((external) =>- applyInbound(external, 'external')- );-- const router: SplitRouter<TSplitId> = {- routes,- entry: (splitId) => findEntry(splitId),-- route(splitId) {- const entry = findEntry(splitId);- return entry?.location.route;- },-- location: (splitId) => findEntry(splitId)?.location,-- search(splitId, namespace) {- assertSafeSearchName(namespace, 'namespace');-- const search = findEntry(splitId)?.location.search;- if (!search || !Object.hasOwn(search, namespace)) return;- return search[namespace];- },-- canGo(splitId, delta) {- return histories.get(splitId)?.canGo(delta) ?? false;- },-- history(splitId) {- const history = histories.get(splitId);- if (!history) return;-- return {- entries: history.entries(),- index: history.index(),- };- },-- navigate(- splitId: TSplitId,- to: SplitNavigateTo,- navigateOptions: SplitNavigateOptions<TSplitId> = {}- ) {- if (disposed) return;- const current = findEntry(splitId);-- if (!current) return;-- if (typeof to === 'number') {- navigateHistory(splitId, to, current, navigateOptions);- return;- }-- let target: TSplitId | 'new-split' = splitId;- if (- navigateOptions.target !== undefined &&- navigateOptions.target !== 'current'- ) {- target = navigateOptions.target;- }-- let targetEntry: SplitRouterEntry | undefined;- if (target !== 'new-split') targetEntry = findEntry(target);- const decoded = resolveNavigation(routes, current, targetEntry, to);-- if (!decoded) return;-- assertSearchNamespacesAllowed(- routes,- decoded.location.route,- Object.keys(navigateOptions.search ?? {})- );-- const explicitSearch =- typeof to === 'string'- ? filterRouteSearch(- routes,- decoded.location.route,- parseSplitSearch(parseExternalLocation(to).search).get(0)- )- : undefined;- let history: BrowserHistoryIntent = 'push';- if (navigateOptions.replace) history = 'replace';-- let state: SplitRouterEntryState;- if (Object.hasOwn(navigateOptions, 'state')) {- state = resolveNavigationEntryState(- routes,- decoded.location.route,- targetEntry,- navigateOptions.state- );- }-- const next: SplitRouterEntry = {- key: createEntryKey(),- location: updateSearchState(decoded.location, navigateOptions.search),- };- if (state !== undefined) next.state = state;-- const targetId =- target === 'new-split' ? undefined : (target as TSplitId);- if (targetId !== undefined && isCurrentDestination(targetId, next)) {- navigateOptions.onApplied?.();- return;- }- transitionEntry({- key: targetId ?? Symbol('new-split-transition'),- splitId: targetId,- entry: next,- from: targetEntry,- cause: 'navigate',- allowDuplicate: navigateOptions.allowDuplicate,- onApplied: navigateOptions.onApplied,- onReuse(ownerId, entry) {- const owner = acceptedById().get(ownerId);- if (!owner) return false;- const redirected = !deepEqual(- entry.location.search,- next.location.search- );- const search = redirected- ? filterRouteSearch(- routes,- entry.location.route,- entry.location.search- )- : explicitSearch;- const patches = redirected ? undefined : navigateOptions.search;- if (!search && !patches) return false;- const owned = getRouteSearchNamespaces(routes, owner.location.route);- const compatible = (values?: Record<string, SplitSearchUpdate>) =>- Object.fromEntries(- Object.entries(values ?? {}).filter(- ([name]) => owned.has('*') || owned.has(name)- )- ) as Record<string, SplitSearchUpdate>;- const location = updateSearchState(- updateSearchState(owner.location, compatible(search)),- compatible(patches)- );- if (deepEqual(owner.location, location)) return false;- return applyEntry({- entry: { ...owner, key: createEntryKey(), location },- target: ownerId,- replace: navigateOptions.replace ?? false,- history,- preserveHash: false,- requireTarget: true,- });- },- apply: (entry) =>- applyEntry({- open: navigateOptions.open,- entry,- target,- replace: navigateOptions.replace ?? false,- history,- preserveHash: false,- }),- });- },-- updateSearch(splitId, namespace, update, updateOptions = {}) {- if (disposed) return;- assertSafeSearchName(namespace, 'namespace');- const entry = findEntry(splitId);- if (!entry) return;- assertSearchNamespacesAllowed(routes, entry.location.route, [namespace]);-- const history = updateOptions.history ?? 'push';- let key = entry.key;- if (history !== 'replace' || !key) key = createEntryKey();-- const next: SplitRouterEntry = {- ...entry,- key,- location: updateSearchState(entry.location, {- [namespace]: update,- }),- };- if (isCurrentDestination(splitId, next)) return;-- transitionEntry({- key: splitId,- splitId,- entry: next,- from: entry,- cause: 'search',- apply: (prepared) =>- applyEntry({- entry: prepared,- target: splitId,- replace: history === 'replace',- history,- preserveHash: true,- requireTarget: true,- }),- });- },-- href(splitId) {- const entry = findEntry(splitId);-- if (!entry) return '';-- return serializeSplitRouterLocation({- routes,- entries: [entry],- previous: options.location.read(),- preserveHash: true,- });- },-- isReady: () => ready,-- async settled() {- do {- await Promise.resolve();- await Promise.all(transitions.promises());- } while (layoutChangeQueued || transitions.size > 0);- },-- subscribe(listener) {- subscribers.add(listener);-- return () => subscribers.delete(listener);- },-- dispose() {- if (disposed) return;-- disposed = true;- subscribers.clear();- abortAllTransitions(false);- unsubscribeLayout();- unsubscribeLocation();- },- };-- // Observe synchronous canonicalization writes during initialization, so their- // echoes cannot later be mistaken for a browser Back navigation.- applyInbound(options.location.read(), 'initial');- return router;-}diff --git a/apps/web/src/lib/split-router/next/router/claims.ts b/apps/web/src/lib/split-router/router/claims.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/claims.tsrename to apps/web/src/lib/split-router/router/claims.tsdiff --git a/apps/web/src/lib/split-router/next/router/create-router.ts b/apps/web/src/lib/split-router/router/create-router.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/create-router.tsrename to apps/web/src/lib/split-router/router/create-router.tsdiff --git a/apps/web/src/lib/split-router/next/router/entries.ts b/apps/web/src/lib/split-router/router/entries.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/entries.tsrename to apps/web/src/lib/split-router/router/entries.tsdiff --git a/apps/web/src/lib/split-router/next/router/leave-guards.ts b/apps/web/src/lib/split-router/router/leave-guards.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/leave-guards.tsrename to apps/web/src/lib/split-router/router/leave-guards.tsdiff --git a/apps/web/src/lib/split-router/next/router/middleware.ts b/apps/web/src/lib/split-router/router/middleware.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/middleware.tsrename to apps/web/src/lib/split-router/router/middleware.tsdiff --git a/apps/web/src/lib/split-router/next/router/pane-list.ts b/apps/web/src/lib/split-router/router/pane-list.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/pane-list.tsrename to apps/web/src/lib/split-router/router/pane-list.tsdiff --git a/apps/web/src/lib/split-router/next/router/pane-navigation.ts b/apps/web/src/lib/split-router/router/pane-navigation.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/pane-navigation.tsrename to apps/web/src/lib/split-router/router/pane-navigation.tsdiff --git a/apps/web/src/lib/split-router/next/router/phases.ts b/apps/web/src/lib/split-router/router/phases.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/phases.tsrename to apps/web/src/lib/split-router/router/phases.tsdiff --git a/apps/web/src/lib/split-router/next/router/preload.ts b/apps/web/src/lib/split-router/router/preload.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/preload.tsrename to apps/web/src/lib/split-router/router/preload.tsdiff --git a/apps/web/src/lib/split-router/next/router/run.ts b/apps/web/src/lib/split-router/router/run.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/run.tsrename to apps/web/src/lib/split-router/router/run.tsdiff --git a/apps/web/src/lib/split-router/next/router/runner.ts b/apps/web/src/lib/split-router/router/runner.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/runner.tsrename to apps/web/src/lib/split-router/router/runner.tsdiff --git a/apps/web/src/lib/split-router/next/router/types.ts b/apps/web/src/lib/split-router/router/types.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/types.tsrename to apps/web/src/lib/split-router/router/types.tsdiff --git a/apps/web/src/lib/split-router/next/router/url-gate.ts b/apps/web/src/lib/split-router/router/url-gate.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/url-gate.tsrename to apps/web/src/lib/split-router/router/url-gate.tsdiff --git a/apps/web/src/lib/split-router/next/router/url-navigation.ts b/apps/web/src/lib/split-router/router/url-navigation.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/url-navigation.tsrename to apps/web/src/lib/split-router/router/url-navigation.tsdiff --git a/apps/web/src/lib/split-router/next/router/url.ts b/apps/web/src/lib/split-router/router/url.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/router/url.tsrename to apps/web/src/lib/split-router/router/url.tsdiff --git a/apps/web/src/lib/split-router/routes.ts b/apps/web/src/lib/split-router/routes.tsdeleted file mode 100644index ca0717f46c..0000000000--- a/apps/web/src/lib/split-router/routes.ts+++ /dev/null@@ -1,655 +0,0 @@-import type { StandardSchemaV1 } from '@standard-schema/spec';-import { compileRoutePattern, type RoutePattern } from './path';-import { assertSafeSearchName } from './search';-import type {- DefinedSplitRoute,- DefinedSplitRoutes,- InferSplitRouteParams,- InferSplitRoutePathParams,- InferSplitRouteState,- SplitReference,- SplitRouteClaim,- SplitRouteDefinition,- SplitRouteMatch,- SplitRouteParams,- SplitRouteRawParams,- SplitRouterEntry,- SplitRouterEntryState,- SplitRouteState,- SplitRoutes,- SplitSearchState,- UnmatchedSplitPathHandler,-} from './types';-import { isRecord, isSafeName, takeLast } from './utils';--type SplitRouteDefinitionConstraint = {- id: string;- path: string;- aliases?: readonly string[];- component?: unknown;- children?: readonly SplitRouteDefinitionConstraint[];- params?: StandardSchemaV1;- state?: StandardSchemaV1;- serializeParams?: unknown;- claim?: unknown;- toReference?: unknown;- search?: readonly string[] | '*';- externalSearch?: SplitRouteDefinition['externalSearch'];- remountKey?: unknown;-};--type RouteParamCallbacks<TParams> = {- serializeParams?: (params: TParams) => SplitRouteRawParams;- claim?: (params: TParams) => SplitRouteClaim | undefined;- toReference?: (params: TParams) => SplitReference | undefined;- remountKey?: (params: TParams) => string | number | undefined;-};--type KeysOfUnion<T> = T extends unknown ? keyof T : never;-type RequiredKeys<T> = {- [K in keyof T]-?: {} extends Pick<T, K> ? never : K;-}[keyof T];--// Schemas may narrow or coerce raw string values. The declaration boundary-// therefore compares parameter names and requiredness, not value domains.-type CompatibleSchemaInputs<TPathParams, TSchemaInput> =- TSchemaInput extends unknown- ? Exclude<keyof TPathParams, keyof TSchemaInput> extends never- ? Exclude<- RequiredKeys<TPathParams>,- RequiredKeys<TSchemaInput>- > extends never- ? Exclude<- RequiredKeys<TSchemaInput>,- RequiredKeys<TPathParams>- > extends never- ? TSchemaInput- : never- : never- : never- : never;--type InvalidSchemaPathParams<TPathParams, TSchemaInput> =- TPathParams extends unknown- ? [CompatibleSchemaInputs<TPathParams, TSchemaInput>] extends [never]- ? TPathParams- : never- : never;--type RouteParamsSchemaIssue<- TPath extends string,- TAliases extends readonly string[] | undefined,- TSchema extends StandardSchemaV1,-> =- InferSplitRoutePathParams<TPath, TAliases> extends infer TPathParams- ? InvalidSchemaPathParams<- TPathParams,- StandardSchemaV1.InferInput<TSchema>- > extends infer TInvalidPathParams- ? [TInvalidPathParams] extends [never]- ? never- : {- path: TPath;- aliases: TAliases;- pathParams: TPathParams;- schemaInput: StandardSchemaV1.InferInput<TSchema>;- missingSchemaKeys: Exclude<- KeysOfUnion<TPathParams>,- KeysOfUnion<StandardSchemaV1.InferInput<TSchema>>- >;- incompatiblePathParams: TInvalidPathParams;- }- : never- : never;--type RouteParamsSchemaConstraint<- TPath extends string,- TAliases extends readonly string[] | undefined,- TSchema extends StandardSchemaV1,-> = [RouteParamsSchemaIssue<TPath, TAliases, TSchema>] extends [never]- ? unknown- : {- readonly 'ERROR: params schema keys and optionality must match path and aliases': RouteParamsSchemaIssue<- TPath,- TAliases,- TSchema- >;- };--type DefinitionAliases<TDefinition> = TDefinition extends {- aliases: infer TAliases extends readonly string[];-}- ? TAliases- : undefined;--type SplitRouteDefinitionRemainder = Omit<- SplitRouteDefinitionConstraint,- 'path' | 'params'->;--type RouteDefinitionParamsSchemaIssues<TDefinition> =- | (TDefinition extends {- id: infer TId;- path: infer TPath extends string;- params: infer TSchema extends StandardSchemaV1;- }- ? RouteParamsSchemaIssue<- TPath,- DefinitionAliases<TDefinition>,- TSchema- > extends infer TIssue- ? [TIssue] extends [never]- ? never- : TIssue & { routeId: TId }- : never- : never)- | (TDefinition extends {- children: infer TChildren extends readonly unknown[];- }- ? RouteDefinitionsParamsSchemaIssues<TChildren>- : never);--type RouteDefinitionsParamsSchemaIssues<- TDefinitions extends readonly unknown[],-> = TDefinitions[number] extends infer TDefinition- ? RouteDefinitionParamsSchemaIssues<TDefinition>- : never;--type RouteDefinitionsParamsSchemaConstraint<- TDefinitions extends readonly unknown[],-> = [RouteDefinitionsParamsSchemaIssues<TDefinitions>] extends [never]- ? unknown- : {- readonly 'ERROR: route params schema keys and optionality must match paths and aliases': RouteDefinitionsParamsSchemaIssues<TDefinitions>;- };--/** Attach the builder in place so declarations retain their route identity. */-function attachRouteBuilders(- definitions: readonly SplitRouteDefinitionConstraint[]-): void {- for (const definition of definitions) {- if (!Object.hasOwn(definition, 'to')) {- Object.defineProperty(definition, 'to', {- value: (params: SplitRouteParams = {}) => ({- route: definition,- params,- }),- });- }- attachRouteBuilders(definition.children ?? []);- }-}-export function defineRoute<- const TPath extends string,- const TAliases extends readonly string[] | undefined,- const TDefinition extends SplitRouteDefinitionConstraint,->(- definition: TDefinition & {- path: TPath;- aliases: TAliases;- params?: undefined;- } & RouteParamCallbacks<- InferSplitRouteParams<{ path: TPath; aliases: TAliases }>- >-): DefinedSplitRoute<- TDefinition & {- path: TPath;- aliases: TAliases;- params?: undefined;- } & RouteParamCallbacks<- InferSplitRouteParams<{ path: TPath; aliases: TAliases }>- >->;-export function defineRoute<- const TPath extends string,- const TDefinition extends SplitRouteDefinitionConstraint,->(- definition: TDefinition & {- path: TPath;- aliases?: undefined;- params?: undefined;- } & RouteParamCallbacks<InferSplitRouteParams<{ path: TPath }>>-): DefinedSplitRoute<- TDefinition & {- path: TPath;- aliases?: undefined;- params?: undefined;- } & RouteParamCallbacks<InferSplitRouteParams<{ path: TPath }>>->;-export function defineRoute<- const TPath extends string,- const TParamsSchema extends StandardSchemaV1,- const TDefinition extends SplitRouteDefinitionRemainder,->(- definition: TDefinition & {- path: TPath;- params: TParamsSchema;- } & RouteParamsSchemaConstraint<- NoInfer<TPath>,- DefinitionAliases<NoInfer<TDefinition>>,- NoInfer<TParamsSchema>- > &- RouteParamCallbacks<StandardSchemaV1.InferOutput<TParamsSchema>>-): DefinedSplitRoute<- TDefinition & { path: TPath; params: TParamsSchema } & RouteParamCallbacks<- StandardSchemaV1.InferOutput<TParamsSchema>- >->;-export function defineRoute(- definition: SplitRouteDefinitionConstraint-): unknown {- attachRouteBuilders([definition]);- return definition;-}--/** Preserve the declaration tree and infer ancestry without constructing runtime state. */-export function defineRoutes<- const TRoutes extends Omit<SplitRoutes, 'definitions'> & {- definitions: readonly SplitRouteDefinitionConstraint[];- },->(- routes: TRoutes &- (NoInfer<TRoutes> extends SplitRoutes ? unknown : SplitRoutes) &- RouteDefinitionsParamsSchemaConstraint<NoInfer<TRoutes>['definitions']>-): DefinedSplitRoutes<TRoutes> {- attachRouteBuilders(routes.definitions);- return routes as DefinedSplitRoutes<TRoutes>;-}--export type RouteParamsCodec = {- parse(params: SplitRouteRawParams): SplitRouteParams | undefined;- serialize(params: SplitRouteParams): SplitRouteParams;-};--function createRouteParamsCodec(- definition: SplitRouteDefinition-): RouteParamsCodec {- const schema = definition.params;- const serialize = definition.serializeParams?.bind(definition);- return {- parse: (params) => validateRouteParams(schema, params),- // Without a custom serializer, the pattern encodes its primitive fields.- serialize: (params) => serialize?.(params) ?? params,- };-}--export type SplitRouteNode<TComponent = unknown> = {- readonly definition: SplitRouteDefinition<TComponent>;- readonly parent?: SplitRouteNode<TComponent>;- readonly branch: readonly SplitRouteNode<TComponent>[];- readonly pattern: RoutePattern;- readonly params: RouteParamsCodec;- readonly children: readonly SplitRouteNode<TComponent>[];- readonly search: ReadonlySet<string>;- readonly claims: readonly SplitRouteDefinition<TComponent>[];- readonly externalSearch: readonly SplitRouteDefinition<TComponent>[];- readonly state?: StandardSchemaV1;-};--/** Runtime route state owned by a router, or explicitly supplied by its host. */-export type SplitRoutesManifest<TComponent = unknown> = {- readonly roots: readonly SplitRouteNode<TComponent>[];- readonly byId: ReadonlyMap<string, SplitRouteNode<TComponent>>;- readonly basePath: readonly string[];- readonly globalSearch: ReadonlySet<string>;- readonly unmatchedPathHandlers: readonly UnmatchedSplitPathHandler[];- readonly defaultEntry?: SplitRoutes['defaultEntry'];-};--function routeSearchNamespaces(- search: SplitRouteDefinition['search']-): Set<string> {- if (search === '*') return new Set(['*']);- const namespaces = new Set<string>();- for (const namespace of search ?? []) {- assertSafeSearchName(namespace, 'namespace');- if (namespaces.has(namespace)) {- throw new Error(`Duplicate split route search namespace "${namespace}"`);- }- namespaces.add(namespace);- }- return namespaces;-}--/** Compile static definitions into independent, caller-owned runtime state. */-export function createRoutesManifest<TComponent>(- routes: SplitRoutes<TComponent>-): SplitRoutesManifest<TComponent> {- const byId = new Map<string, SplitRouteNode<TComponent>>();- const globalSearch = new Set(routes.globalSearch ?? []);- for (const key of globalSearch) {- if (!isSafeName(key)) {- throw new Error(`Invalid global search key "${key}"`);- }- }-- const visit = (- definitions: readonly SplitRouteDefinition<TComponent>[],- parent?: SplitRouteNode<TComponent>- ): SplitRouteNode<TComponent>[] => {- const siblingPaths = new Set<string>();- return definitions.map((definition) => {- if (!isSafeName(definition.id)) {- throw new Error(`Invalid split route id "${definition.id}"`);- }- if (byId.has(definition.id)) {- throw new Error(`Duplicate split route id "${definition.id}"`);- }-- for (const path of [definition.path, ...(definition.aliases ?? [])]) {- if (!path) throw new Error(`Invalid split route path "${path}"`);- const normalized = path.replace(/^\/+|\/+$/g, '');- if (siblingPaths.has(normalized)) {- throw new Error(`Duplicate sibling split route path "${normalized}"`);- }- siblingPaths.add(normalized);- }-- const namespaces = routeSearchNamespaces(definition.search);- const branch = [...(parent?.branch ?? [])];- const children: SplitRouteNode<TComponent>[] = [];- const node: SplitRouteNode<TComponent> = {- definition,- parent,- branch,- pattern: compileRoutePattern(definition),- params: createRouteParamsCodec(definition),- children,- search: new Set([...(parent?.search ?? []), ...namespaces]),- claims: [- ...(parent?.claims ?? []),- ...(definition.claim ? [definition] : []),- ],- externalSearch: [- ...(parent?.externalSearch ?? []),- ...(definition.externalSearch ? [definition] : []),- ],- state: definition.state ?? parent?.state,- };- branch.push(node);- byId.set(definition.id, node);- children.push(...visit(definition.children ?? [], node));- return node;- });- };-- return {- roots: visit(routes.definitions),- byId,- basePath:- typeof routes.basePath === 'string'- ? routes.basePath.split('/').filter(Boolean)- : [...(routes.basePath ?? [])],- globalSearch,- unmatchedPathHandlers: [...(routes.unmatchedPathHandlers ?? [])],- defaultEntry: routes.defaultEntry,- };-}--export function validateSplitRoutes<TComponent>(- routes: SplitRoutes<TComponent>-): void {- createRoutesManifest(routes);-}--/** Root pattern match only, including partial paths rejected by schema/children. */-export function findMatchingRouteId(- routes: SplitRoutesManifest,- segments: readonly string[]-): string | undefined {- return routes.roots.find((node) => !node.pattern.match(segments).next().done)- ?.definition.id;-}--export function validateRouteParams(- schema: StandardSchemaV1 | undefined,- params: SplitRouteParams-): SplitRouteParams | undefined {- if (!schema) return params;- const result = schema['~standard'].validate(params);- if (result instanceof Promise) {- throw new Error('Split route parameter schemas must be synchronous');- }- if (result.issues) return;- if (- !result.value ||- typeof result.value !== 'object' ||- Array.isArray(result.value)- ) {- throw new Error('Split route parameter schemas must return an object');- }- return result.value as SplitRouteParams;-}--export function rootRouteMatch(route: SplitRouteState | undefined) {- return route?.matches[0];-}--export function routeParams<- TParams extends SplitRouteParams = SplitRouteParams,->(route: SplitRouteState | undefined): TParams {- return Object.assign(- {},- ...(route?.matches.map((match) => match.params) ?? [])- ) as TParams;-}--export function findRouteBranch<TComponent>(- routes: SplitRoutesManifest<TComponent>,- routeId: string-): readonly SplitRouteNode<TComponent>[] | undefined {- return routes.byId.get(routeId)?.branch;-}--/** Validate host/persisted state without treating schema outputs as schema inputs. */-export function assertRouteState(- routes: SplitRoutesManifest,- route: unknown-): asserts route is SplitRouteState {- if (- !isRecord(route) ||- !Array.isArray(route.matches) ||- route.matches.length === 0- ) {- throw new Error('Split route state requires a nonempty match branch');- }- let parent: SplitRouteNode | undefined;- for (const match of route.matches) {- if (- !isRecord(match) ||- typeof match.id !== 'string' ||- !isRecord(match.params)- ) {- throw new Error('Split route state contains an invalid match');- }- const node = routes.byId.get(match.id);- if (!node || node.parent !== parent) {- throw new Error('Split route state contains an invalid match branch');- }- parent = node;- }-}--export function assertRouteEntry(- routes: SplitRoutesManifest,- entry: SplitRouterEntry-): void {- assertRouteState(routes, entry?.location?.route);-}--function resolveRouteNode<TComponent>(- routes: SplitRoutesManifest<TComponent>,- route: SplitRouteState-): SplitRouteNode<TComponent> {- const leaf = takeLast(route.matches)!;- const node = routes.byId.get(leaf.id);- if (- !node ||- node.branch.length !== route.matches.length ||- node.branch.some(- (ancestor, index) => ancestor.definition.id !== route.matches[index]!.id- )- ) {- throw new Error('Split route state contains an invalid match branch');- }- return node;-}--export function resolveRouteBranch<TComponent>(- routes: SplitRoutesManifest<TComponent>,- route: SplitRouteState-): readonly SplitRouteNode<TComponent>[] {- return resolveRouteNode(routes, route).branch;-}--export type SplitRouteEntryStateResult =- | { success: true; value: SplitRouterEntryState }- | { success: false };--export function parseRouteEntryState(- routes: SplitRoutesManifest,- route: SplitRouteState,- state: unknown-): SplitRouteEntryStateResult {- if (state === undefined) return { success: true, value: undefined };- const schema = resolveRouteNode(routes, route).state;- if (!schema) return { success: false };-- const result = schema['~standard'].validate(state);- if (result instanceof Promise) {- throw new Error('Split route state schemas must be synchronous');- }- if (result.issues) return { success: false };- return {- success: true,- value: result.value as SplitRouterEntryState,- };-}--export function getRouteEntryState<const TRoute extends { id: string }>(- routes: SplitRoutesManifest,- entry: SplitRouterEntry | undefined,- route: TRoute-): InferSplitRouteState<TRoute> | undefined {- if (!entry) return;- const active = resolveRouteNode(routes, entry.location.route);- const requested = routes.byId.get(route.id);- if (!requested) return;- if (!active.branch.includes(requested)) return;- if (requested.state !== active.state) return;- return entry.state as InferSplitRouteState<TRoute> | undefined;-}--export function getRouteClaim(- routes: SplitRoutesManifest,- route: SplitRouteState-): SplitRouteClaim | undefined {- const claims = resolveRouteNode(routes, route).claims;- const params = routeParams(route);- for (let index = claims.length - 1; index >= 0; index -= 1) {- const claim = claims[index]?.claim?.(params);- if (!claim) continue;- if (!isSafeName(claim.namespace) || claim.id.length === 0) {- throw new Error('Split route returned an invalid claim');- }- return claim;- }-}--function decodeRouteBranch<TComponent>(- nodes: readonly SplitRouteNode<TComponent>[],- segments: string[]-): SplitRouteState | undefined {- for (const node of nodes) {- for (const patternMatch of node.pattern.match(segments)) {- const params = node.params.parse(patternMatch.params);- if (!params) continue;- const match: SplitRouteMatch = { id: node.definition.id, params };- const childSegments = segments.slice(patternMatch.consumed);- if (childSegments.length === 0) return { matches: [match] };- const child = decodeRouteBranch(node.children, childSegments);- if (child) return { matches: [match, ...child.matches] };- }- }-}--export function decodeRoute(- routes: SplitRoutesManifest,- segments: string[]-): SplitRouterEntry | undefined {- const route = decodeRouteBranch(routes.roots, segments);- return route ? { location: { route } } : undefined;-}--export function encodeRoute(- routes: SplitRoutesManifest,- entry: SplitRouterEntry-): string[] {- const route = entry.location.route;- const node = resolveRouteNode(routes, route);- return node.branch.flatMap((ancestor, index) =>- ancestor.pattern.format(- ancestor.params.serialize(route.matches[index]!.params)- )- );-}--export function getRouteId(entry: SplitRouterEntry): string {- return entry.location.route.matches[0].id;-}--export function getRouteSearchNamespaces<TComponent>(- routes: SplitRoutesManifest<TComponent>,- route: SplitRouteState-): ReadonlySet<string> {- return resolveRouteNode(routes, route).search;-}--export function assertSearchNamespacesAllowed(- routes: SplitRoutesManifest,- route: SplitRouteState,- namespaces: readonly string[]-): void {- const owned = getRouteSearchNamespaces(routes, route);- for (const namespace of namespaces) {- assertSafeSearchName(namespace, 'namespace');- if (!owned.has('*') && !owned.has(namespace)) {- throw new Error(- `Split route does not own search namespace "${namespace}"`- );- }- }-}--export function filterRouteSearch<TComponent>(- routes: SplitRoutesManifest<TComponent>,- route: SplitRouteState,- search: SplitSearchState | undefined-): SplitSearchState | undefined {- if (!search) return;- const owned = getRouteSearchNamespaces(routes, route);- if (owned.has('*')) return search;- const filtered = Object.fromEntries(- Object.entries(search).filter(([namespace]) => owned.has(namespace))- );- return Object.keys(filtered).length > 0 ? filtered : undefined;-}--export function getExternalSearchKeys(- routes: SplitRoutesManifest,- entries: SplitRouterEntry[]-): Set<string> {- const result = new Set(routes.globalSearch);- for (const entry of entries) {- for (const definition of resolveRouteNode(routes, entry.location.route)- .externalSearch) {- const externalSearch = definition.externalSearch;- const keys =- typeof externalSearch === 'function'- ? externalSearch(entry)- : (externalSearch ?? []);- for (const key of keys) result.add(key);- }- }- return result;-}diff --git a/apps/web/src/lib/split-router/next/routes/codec.ts b/apps/web/src/lib/split-router/routes/codec.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/codec.tsrename to apps/web/src/lib/split-router/routes/codec.tsdiff --git a/apps/web/src/lib/split-router/next/routes/define.ts b/apps/web/src/lib/split-router/routes/define.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/define.tsrename to apps/web/src/lib/split-router/routes/define.tsdiff --git a/apps/web/src/lib/split-router/next/routes/manifest.ts b/apps/web/src/lib/split-router/routes/manifest.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/manifest.tsrename to apps/web/src/lib/split-router/routes/manifest.tsdiff --git a/apps/web/src/lib/split-router/next/routes/path.ts b/apps/web/src/lib/split-router/routes/path.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/path.tsrename to apps/web/src/lib/split-router/routes/path.tsdiff --git a/apps/web/src/lib/split-router/next/routes/queries.ts b/apps/web/src/lib/split-router/routes/queries.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/queries.tsrename to apps/web/src/lib/split-router/routes/queries.tsdiff --git a/apps/web/src/lib/split-router/next/routes/search-params.ts b/apps/web/src/lib/split-router/routes/search-params.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/search-params.tsrename to apps/web/src/lib/split-router/routes/search-params.tsdiff --git a/apps/web/src/lib/split-router/next/routes/search.ts b/apps/web/src/lib/split-router/routes/search.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/search.tsrename to apps/web/src/lib/split-router/routes/search.tsdiff --git a/apps/web/src/lib/split-router/next/routes/targets.ts b/apps/web/src/lib/split-router/routes/targets.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/targets.tsrename to apps/web/src/lib/split-router/routes/targets.tsdiff --git a/apps/web/src/lib/split-router/next/routes/types.ts b/apps/web/src/lib/split-router/routes/types.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/routes/types.tsrename to apps/web/src/lib/split-router/routes/types.tsdiff --git a/apps/web/src/lib/split-router/search-params-codec.ts b/apps/web/src/lib/split-router/search-params-codec.tsdeleted file mode 100644index b386d47457..0000000000--- a/apps/web/src/lib/split-router/search-params-codec.ts+++ /dev/null@@ -1,123 +0,0 @@-import type { StandardSchemaV1 } from '@standard-schema/spec';-import deepEqual from 'fast-deep-equal';-import type { SerializedSearchParams } from './types';-import { takeLast } from './utils';--export type SearchParamsRecord = Record<string, unknown>;-export type SearchParamsSchema<T> = StandardSchemaV1<unknown, T>;-export type SearchParamsSerializer<T> = (- value: T,- context: { defaults: T }-) => SerializedSearchParams | undefined;-export type SearchParamsDeserializer<T> = (- params: SerializedSearchParams-) => Partial<T>;--export type SearchParamsCodecOptions<T extends SearchParamsRecord> = {- schema: SearchParamsSchema<T>;- defaults: T;-} & (- | { serialize?: never; deserialize?: never }- | {- serialize: SearchParamsSerializer<T>;- deserialize: SearchParamsDeserializer<T>;- }-);--type ValidationResult<T> =- | { success: true; data: T }- | { success: false; error: unknown };--export type SearchParamsCodec<T> = {- parse(params: SerializedSearchParams | undefined): {- value: T;- valid: boolean;- };- serialize(value: T): SerializedSearchParams | undefined;- validate(value: unknown): ValidationResult<T>;-};--function defaultDeserialize<T extends SearchParamsRecord>(- params: SerializedSearchParams | undefined,- defaults: T-): Partial<T> {- if (!params) return {};- const result: SearchParamsRecord = {};- for (const key of Object.keys(defaults)) {- const values = params[key];- if (!values || values.length === 0) continue;- const fallback = defaults[key];- if (Array.isArray(fallback)) {- result[key] = values.length === 1 && values[0] === '' ? [] : [...values];- } else if (typeof fallback === 'number') {- result[key] = Number(takeLast(values));- } else if (typeof fallback === 'boolean') {- result[key] = takeLast(values) === 'true';- } else {- result[key] = takeLast(values);- }- }- return result as Partial<T>;-}--function defaultSerialize<T extends SearchParamsRecord>(- value: T,- defaults: T-): SerializedSearchParams | undefined {- const result: SerializedSearchParams = {};- for (const [key, field] of Object.entries(value)) {- if (field === undefined || deepEqual(field, defaults[key])) continue;- if (Array.isArray(field)) {- result[key] =- field.length === 0 ? [''] : field.map((item) => String(item));- } else {- result[key] = [String(field)];- }- }- return Object.keys(result).length > 0 ? result : undefined;-}--export function createSearchParamsCodec<T extends SearchParamsRecord>(- options: SearchParamsCodecOptions<T>-): SearchParamsCodec<T> {- const validate = (value: unknown): ValidationResult<T> => {- const result = options.schema['~standard'].validate(value);- if (result instanceof Promise) {- throw new Error('Search parameter schemas must be synchronous');- }- return result.issues- ? { success: false, error: result.issues }- : { success: true, data: result.value };- };-- if (!validate(options.defaults).success) {- throw new Error('Invalid defaults for search params');- }-- return {- validate,- parse(params) {- try {- const decoded = options.deserialize- ? options.deserialize(params ?? {})- : defaultDeserialize(params, options.defaults);- const parsed = validate({ ...options.defaults, ...decoded });- if (parsed.success) return { value: parsed.data, valid: true };- } catch {- // Invalid inbound URL state falls back to defaults and is canonicalized.- }- return { value: options.defaults, valid: false };- },- serialize(value) {- if (deepEqual(value, options.defaults)) return;- if (!options.serialize) return defaultSerialize(value, options.defaults);- const params = options.serialize(value, { defaults: options.defaults });- // Keep the codec's result separate from mutable/custom serializer state.- const entries = Object.entries(params ?? {}).map(([key, values]) => [- key,- [...values],- ]);- return entries.length > 0 ? Object.fromEntries(entries) : undefined;- },- };-}diff --git a/apps/web/src/lib/split-router/search.ts b/apps/web/src/lib/split-router/search.tsdeleted file mode 100644index da3cc43882..0000000000--- a/apps/web/src/lib/split-router/search.ts+++ /dev/null@@ -1,173 +0,0 @@-import type {- SerializedSearchParams,- SplitLocation,- SplitSearchState,- SplitSearchUpdate,-} from './types';-import { isRecord, isSafeName } from './utils';--const SPLIT_SEARCH_PREFIX = /^s\d+\./;-const SPLIT_SEARCH_KEY =- /^s(\d+)\.([A-Za-z][A-Za-z0-9_-]*)\.([A-Za-z][A-Za-z0-9_-]*)$/;-const MAX_SEARCH_VALUE_LENGTH = 16_384;--export function isSplitSearchKey(key: string): boolean {- return SPLIT_SEARCH_PREFIX.test(key);-}--export function assertSafeSearchName(- value: string,- kind: 'namespace' | 'field'-): void {- if (!isSafeName(value)) {- throw new Error(`Invalid split search ${kind} "${value}"`);- }-}--export function parseSplitSearch(value: string): Map<number, SplitSearchState> {- const splits = new Map<number, SplitSearchState>();-- for (const [key, fieldValue] of new URLSearchParams(value)) {- const match = SPLIT_SEARCH_KEY.exec(key);-- if (!match || fieldValue.length > MAX_SEARCH_VALUE_LENGTH) continue;-- const splitIndex = Number(match[1]);- const namespace = match[2]!;- const field = match[3]!;-- if (- !Number.isSafeInteger(splitIndex) ||- !isSafeName(namespace) ||- !isSafeName(field)- ) {- continue;- }-- const namespaces = splits.get(splitIndex) ?? {};- const fields = Object.hasOwn(namespaces, namespace)- ? namespaces[namespace]!- : {};-- const values = Object.hasOwn(fields, field) ? fields[field]! : [];- fields[field] = [...values, fieldValue];- namespaces[namespace] = fields;- splits.set(splitIndex, namespaces);- }-- return splits;-}--/** Recover compatible fields from untrusted persisted search metadata. */-export function parseSearchState(value: unknown): SplitSearchState | undefined {- if (!isRecord(value)) return;- const search: SplitSearchState = {};- for (const [namespace, rawFields] of Object.entries(value)) {- if (!isSafeName(namespace) || !isRecord(rawFields)) continue;- const fields: SerializedSearchParams = {};- for (const [field, rawValues] of Object.entries(rawFields)) {- if (!isSafeName(field) || !Array.isArray(rawValues)) continue;- const values = rawValues.filter(- (item): item is string =>- typeof item === 'string' && item.length <= MAX_SEARCH_VALUE_LENGTH- );- if (values.length > 0) fields[field] = values;- }- if (Object.keys(fields).length > 0) search[namespace] = fields;- }- return Object.keys(search).length > 0 ? search : undefined;-}--/** Replaces split-owned keys in the query, preserving other search params. */-export function replaceSplitSearchParams(- query: URLSearchParams,- entries: Array<{ location?: { search?: SplitSearchState } }>-): void {- for (const key of [...query.keys()]) {- if (isSplitSearchKey(key)) query.delete(key);- }-- entries.forEach((entry, splitIndex) => {- const search = entry.location?.search;-- if (!search) return;-- for (const namespace of Object.keys(search).sort()) {- assertSafeSearchName(namespace, 'namespace');-- const params = search[namespace];-- if (!params) continue;-- for (const field of Object.keys(params).sort()) {- assertSafeSearchName(field, 'field');-- for (const value of params[field] ?? []) {- if (value.length > MAX_SEARCH_VALUE_LENGTH) {- throw new Error(`Split search value for "${field}" is too long`);- }-- query.append(`s${splitIndex}.${namespace}.${field}`, value);- }- }- }- });-}--export function normalizeSearchParams(- params: SerializedSearchParams | undefined-): SerializedSearchParams | undefined {- if (!params) return;-- const result: Record<string, string[]> = {};-- for (const field of Object.keys(params).sort()) {- assertSafeSearchName(field, 'field');-- const values = params[field];-- if (values?.length) result[field] = [...values];- }-- return Object.keys(result).length ? result : undefined;-}--export function withSearchNamespace(- current: SplitLocation,- namespace: string,- params: SerializedSearchParams | undefined-): SplitLocation {- const search = { ...(current.search ?? {}) };-- if (params && Object.keys(params).length > 0) search[namespace] = params;- else delete search[namespace];-- return Object.keys(search).length > 0- ? { route: current.route, search }- : { route: current.route };-}--export function updateSearchState(- location: SplitLocation,- updates: Record<string, SplitSearchUpdate> | undefined-): SplitLocation {- let next = location;-- for (const [namespace, update] of Object.entries(updates ?? {})) {- assertSafeSearchName(namespace, 'namespace');-- const current =- next.search && Object.hasOwn(next.search, namespace)- ? next.search[namespace]- : undefined;- const requested = typeof update === 'function' ? update(current) : update;-- next = withSearchNamespace(- next,- namespace,- normalizeSearchParams(requested)- );- }-- return next;-}diff --git a/apps/web/src/lib/split-router/solid.tsx b/apps/web/src/lib/split-router/solid.tsxdeleted file mode 100644index ab323817ab..0000000000--- a/apps/web/src/lib/split-router/solid.tsx+++ /dev/null@@ -1,363 +0,0 @@-import {- type Accessor,- type Component,- createContext,- createMemo,- createSignal,- type JSX,- onCleanup,- Show,- type Signal,- useContext,-} from 'solid-js';-import { Dynamic } from 'solid-js/web';-import { createSplitRouter } from './router';-import {- getRouteEntryState,- getRouteSearchNamespaces,- resolveRouteBranch,- routeParams,- type SplitRoutesManifest,-} from './routes';-import type {- InferSplitRouteBranchParams,- InferSplitRouteParams,- InferSplitRouteState,- SplitNavigate,- SplitNavigateOptions,- SplitNavigateTo,- SplitRouteParams,- SplitRouter as SplitRouterController,- SplitRouterExternalLocation,- SplitRouterLayout,- SplitRouterMiddleware,- SplitRouteState,- SplitRoutes,-} from './types';-import { reactiveRecord } from './utils';--type UnknownSplitRouter = SplitRouterController<unknown>;--export type SplitRouterContextValue = {- router: UnknownSplitRouter;- globalRevision: Accessor<number>;- track: (splitId: unknown) => void;-};--type SplitRouterOutletContextValue = {- splitId: Accessor<unknown>;- depth: Accessor<number>;-};--export const SplitRouterContext = createContext<SplitRouterContextValue>();-export const SplitRouterScopeContext = createContext<Accessor<unknown>>();-const SplitRouterOutletContext = createContext<SplitRouterOutletContextValue>();--function useSplitRouterContext() {- const context = useContext(SplitRouterContext);-- if (!context) {- throw new Error(- 'Split router hooks must be used inside <SplitRouter.Root>'- );- }-- return context;-}--export function useSplitRouter<TSplitId>(): SplitRouterController<TSplitId> {- return useSplitRouterContext()- .router as unknown as SplitRouterController<TSplitId>;-}--export function useOptionalSplitRouter<TSplitId>() {- return useContext(SplitRouterContext)?.router as- | SplitRouterController<TSplitId>- | undefined;-}--export function useSplitRouterState<TSplitId>() {- const context = useSplitRouterContext();- const router = context.router as unknown as SplitRouterController<TSplitId>;-- return {- router,- canGo(splitId: TSplitId, delta: number) {- context.track(splitId);-- return router.canGo(splitId, delta);- },- entry(splitId: TSplitId) {- context.track(splitId);-- return router.entry(splitId);- },- history(splitId: TSplitId) {- context.track(splitId);-- return router.history(splitId);- },- route(splitId: TSplitId) {- context.track(splitId);-- return router.route(splitId);- },- location(splitId: TSplitId) {- context.track(splitId);-- return router.location(splitId);- },- search(splitId: TSplitId, namespace: string) {- context.track(splitId);-- return router.search(splitId, namespace);- },- };-}--export function useSplitRouterScope<TSplitId>(): Accessor<TSplitId> {- const splitId = useContext(SplitRouterScopeContext);-- if (!splitId) {- throw new Error(- 'Split router hooks must be used inside <SplitRouter.Scope> or <SplitRouter.Outlet>'- );- }-- return splitId as Accessor<TSplitId>;-}--/**- * Whether the enclosing split's current route owns search `namespace`, so- * `createSearchParams` may write it. False outside a split.- */-export function useOwnsSearchNamespace(namespace: string): Accessor<boolean> {- const context = useContext(SplitRouterContext);- const splitId = useContext(SplitRouterScopeContext);- if (!context || !splitId) return () => false;- return () => {- context.track(splitId());- const route = context.router.route(splitId());- if (!route) return false;- const owned = getRouteSearchNamespaces(context.router.routes, route);- return owned.has('*') || owned.has(namespace);- };-}--export function useNavigate<TSplitId = unknown>(): SplitNavigate<TSplitId> {- const router = useSplitRouter<TSplitId>();- const splitId = useSplitRouterScope<TSplitId>();-- const navigate = router.navigate as (- splitId: TSplitId,- to: SplitNavigateTo,- options?: SplitNavigateOptions<TSplitId>- ) => void;-- return ((to: SplitNavigateTo, options: SplitNavigateOptions<TSplitId> = {}) =>- navigate(splitId(), to, options)) as SplitNavigate<TSplitId>;-}--export function useCanGo(delta: number): Accessor<boolean> {- const router = useSplitRouterState<unknown>();- const splitId = useSplitRouterScope<unknown>();-- return () => router.canGo(splitId(), delta);-}--export function useRouteState<const TRoute extends { id: string }>(- route: TRoute-): Accessor<InferSplitRouteState<TRoute> | undefined> {- const state = useSplitRouterState<unknown>();- const splitId = useSplitRouterScope<unknown>();-- return () =>- getRouteEntryState(state.router.routes, state.entry(splitId()), route);-}--export function useSplitHistory() {- const router = useSplitRouterState<unknown>();- const splitId = useSplitRouterScope<unknown>();-- return () => router.history(splitId());-}--export function useParams<const TRoute extends { id: string }>(- route: TRoute-): InferSplitRouteBranchParams<TRoute>;-export function useParams<T extends SplitRouteParams = SplitRouteParams>(): T;-export function useParams(through?: { id: string }): SplitRouteParams {- const router = useSplitRouterState<unknown>();- const splitId = useSplitRouterScope<unknown>();- const params = createMemo(() => {- const route = router.route(splitId());- if (!through || !route) return routeParams(route);- const index = route.matches.findIndex((match) => match.id === through.id);- if (index < 0) return {};- const [first, ...rest] = route.matches;- return routeParams({ matches: [first, ...rest.slice(0, index)] });- });-- return reactiveRecord(params);-}--export function useRouteParams<const TRoute extends { id: string }>(- route: TRoute-): InferSplitRouteParams<TRoute> {- const router = useSplitRouterState<unknown>();- const splitId = useSplitRouterScope<unknown>();- const params = createMemo(- () =>- router.route(splitId())?.matches.find((match) => match.id === route.id)- ?.params ?? {}- );-- return reactiveRecord(params) as InferSplitRouteParams<TRoute>;-}--export type SplitRouterRootProps<TSplitId, TComponent = unknown> = {- layout: SplitRouterLayout<TSplitId>;- routes: SplitRoutes<TComponent> | SplitRoutesManifest<TComponent>;- location: SplitRouterExternalLocation;- middleware?: readonly SplitRouterMiddleware[];- children?: JSX.Element;-};--export function Root<TSplitId, TComponent = unknown>(- props: SplitRouterRootProps<TSplitId, TComponent>-) {- const router = createSplitRouter({- layout: props.layout,- routes: props.routes,- location: props.location,- middleware: props.middleware,- });- const [globalRevision, setGlobalRevision] = createSignal(0);- const splitRevisions = new Map<unknown, Signal<number>>();- const splitRevision = (splitId: unknown) => {- let revision = splitRevisions.get(splitId);-- if (!revision) {- revision = createSignal(0);- splitRevisions.set(splitId, revision);- }-- return revision;- };-- router.subscribe((splitId) => {- if (splitId === undefined) {- setGlobalRevision((value) => value + 1);- return;- }-- splitRevision(splitId)[1]((value) => value + 1);- });- onCleanup(() => router.dispose());-- const ready = () => {- globalRevision();-- return router.isReady();- };-- return (- <SplitRouterContext.Provider- value={{- router: router as unknown as SplitRouterController<unknown>,- globalRevision,- track: (splitId) => {- globalRevision();- splitRevision(splitId)[0]();- },- }}- >- <Show when={ready()}>{props.children}</Show>- </SplitRouterContext.Provider>- );-}--export type SplitRouterScopeProps<TSplitId> = {- splitId: TSplitId;- children?: JSX.Element;-};--export function Scope<TSplitId>(props: SplitRouterScopeProps<TSplitId>) {- return (- <SplitRouterScopeContext.Provider value={() => props.splitId}>- {props.children}- </SplitRouterScopeContext.Provider>- );-}--export type SplitRouterOutletProps<TSplitId> = {- splitId?: TSplitId;- fallback?: () => JSX.Element;-};--export function Outlet<TSplitId>(props: SplitRouterOutletProps<TSplitId>) {- const context = useSplitRouterContext();- const parent = useContext(SplitRouterOutletContext);- const scope = useContext(SplitRouterScopeContext);- const splitId: Accessor<unknown> = () => {- if (props.splitId !== undefined) return props.splitId;- if (parent) return parent.splitId();- if (scope) return scope();-- throw new Error(- 'SplitRouter.Outlet requires a splitId or <SplitRouter.Scope>'- );- };- const startDepth = () =>- props.splitId === undefined && parent ? parent.depth() : 0;- const route = (): SplitRouteState | undefined => {- context.track(splitId());- return context.router.route(splitId());- };- const resolved = createMemo(() => {- const currentRoute = route();- if (!currentRoute) return;- const branch = resolveRouteBranch(context.router.routes, currentRoute);-- for (let index = startDepth(); index < branch.length; index += 1) {- const definition = branch[index]?.definition;- const component = definition?.component;- if (definition && typeof component === 'function') {- const remountKey = definition.remountKey?.(- currentRoute.matches[index]!.params- );-- return {- component: component as Component,- renderKey: JSON.stringify([definition.id, remountKey ?? null]),- nextDepth: index + 1,- };- }- }- });- const component = () => resolved()?.component;- const renderKey = () => resolved()?.renderKey;- const outletContext: SplitRouterOutletContextValue = {- splitId,- depth: () => resolved()?.nextDepth ?? startDepth(),- };- const Fallback = () => props.fallback?.();-- return (- <SplitRouterScopeContext.Provider value={splitId}>- <Show keyed when={renderKey()} fallback={<Fallback />}>- {(_key) => (- <SplitRouterOutletContext.Provider value={outletContext}>- <Dynamic component={component()} />- </SplitRouterOutletContext.Provider>- )}- </Show>- </SplitRouterScopeContext.Provider>- );-}--export const SplitRouter = {- Root,- Scope,- Outlet,-};diff --git a/apps/web/src/lib/split-router/next/solid/context.tsx b/apps/web/src/lib/split-router/solid/context.tsxsimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/context.tsxrename to apps/web/src/lib/split-router/solid/context.tsxdiff --git a/apps/web/src/lib/split-router/next/solid/create-search-params.ts b/apps/web/src/lib/split-router/solid/create-search-params.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/create-search-params.tsrename to apps/web/src/lib/split-router/solid/create-search-params.tsdiff --git a/apps/web/src/lib/split-router/next/solid/hooks.ts b/apps/web/src/lib/split-router/solid/hooks.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/hooks.tsrename to apps/web/src/lib/split-router/solid/hooks.tsdiff --git a/apps/web/src/lib/split-router/next/solid/memo-record.ts b/apps/web/src/lib/split-router/solid/memo-record.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/memo-record.tsrename to apps/web/src/lib/split-router/solid/memo-record.tsdiff --git a/apps/web/src/lib/split-router/next/solid/outlet.tsx b/apps/web/src/lib/split-router/solid/outlet.tsxsimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/outlet.tsxrename to apps/web/src/lib/split-router/solid/outlet.tsxdiff --git a/apps/web/src/lib/split-router/next/solid/pane-scope.tsx b/apps/web/src/lib/split-router/solid/pane-scope.tsxsimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/pane-scope.tsxrename to apps/web/src/lib/split-router/solid/pane-scope.tsxdiff --git a/apps/web/src/lib/split-router/next/solid/route.tsx b/apps/web/src/lib/split-router/solid/route.tsxsimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/route.tsxrename to apps/web/src/lib/split-router/solid/route.tsxdiff --git a/apps/web/src/lib/split-router/next/solid/router.tsx b/apps/web/src/lib/split-router/solid/router.tsxsimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/router.tsxrename to apps/web/src/lib/split-router/solid/router.tsxdiff --git a/apps/web/src/lib/split-router/next/solid/split-router.tsx b/apps/web/src/lib/split-router/solid/split-router.tsxsimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/split-router.tsxrename to apps/web/src/lib/split-router/solid/split-router.tsxdiff --git a/apps/web/src/lib/split-router/next/solid/use-before-leave.ts b/apps/web/src/lib/split-router/solid/use-before-leave.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/use-before-leave.tsrename to apps/web/src/lib/split-router/solid/use-before-leave.tsdiff --git a/apps/web/src/lib/split-router/next/solid/use-claim.ts b/apps/web/src/lib/split-router/solid/use-claim.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/solid/use-claim.tsrename to apps/web/src/lib/split-router/solid/use-claim.tsdiff --git a/apps/web/src/lib/split-router/tests/claims.test.ts b/apps/web/src/lib/split-router/tests/claims.test.tsdeleted file mode 100644index 26fd999d62..0000000000--- a/apps/web/src/lib/split-router/tests/claims.test.ts+++ /dev/null@@ -1,96 +0,0 @@-import { describe, expect, it } from 'vitest';-import { createClaimReservations } from '../claims';--const one = { namespace: 'document', id: 'one' };-const two = { namespace: 'document', id: 'two' };--describe('pending claim reservations', () => {- it('grants contenders turns in reservation order', async () => {- const claims = createClaimReservations();- const first = claims.reserve(one);- const second = claims.reserve(one);- const third = claims.reserve(one);- const signal = new AbortController().signal;- expect(first.wait(signal)).toBeUndefined();- const secondTurn = second.wait(signal);- let thirdReady = false;- const thirdTurn = (async () => {- await third.wait(signal);- thirdReady = true;- })();- first.release();- await secondTurn;- expect(thirdReady).toBe(false);- second.release();- await thirdTurn;- expect(thirdReady).toBe(true);- third.release();- });-- it('moves redirected reservations without blocking the original claim', async () => {- const claims = createClaimReservations();- const first = claims.reserve(one);- const second = claims.reserve(one);- const other = claims.reserve(two);- const signal = new AbortController().signal;- const secondTurn = second.wait(signal);- first.move(two);- await secondTurn;- let firstReady = false;- const firstTurn = (async () => {- await first.wait(signal);- firstReady = true;- })();- await Promise.resolve();- expect(firstReady).toBe(false);- other.release();- await firstTurn;- first.release();- second.release();- });-- it('does not let an obsolete release remove a newer reservation', () => {- const claims = createClaimReservations();- const stale = claims.reserve(one);- stale.release();- const owner = claims.reserve(one);- const waiter = claims.reserve(one);- stale.release();- stale.move(one);- expect(owner.wait(new AbortController().signal)).toBeUndefined();- const controller = new AbortController();- const waiting = waiter.wait(controller.signal);- expect(waiting).toBeInstanceOf(Promise);- controller.abort();- owner.release();- waiter.release();- return expect(waiting).rejects.toMatchObject({ name: 'AbortError' });- });-- it('removes aborted wait listeners and distinguishes namespaces and IDs', async () => {- const claims = createClaimReservations();- const owner = claims.reserve(one);- const waiter = claims.reserve(one);- const controller = new AbortController();- const waiting = waiter.wait(controller.signal);- controller.abort();- await expect(waiting).rejects.toMatchObject({ name: 'AbortError' });- waiter.release();- owner.release();- const other = claims.reserve({ namespace: 'folder', id: one.id });- const document = claims.reserve(one);- expect(other.wait(new AbortController().signal)).toBeUndefined();- expect(document.wait(new AbortController().signal)).toBeUndefined();- other.release();- document.release();- });-- it('keeps reservation state local to each router owner', () => {- const first = createClaimReservations().reserve(one);- const second = createClaimReservations().reserve(one);- expect(first.wait(new AbortController().signal)).toBeUndefined();- expect(second.wait(new AbortController().signal)).toBeUndefined();- first.release();- second.release();- });-});diff --git a/apps/web/src/lib/split-router/next/tests/fake-solid-router.ts b/apps/web/src/lib/split-router/tests/fake-solid-router.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/tests/fake-solid-router.tsrename to apps/web/src/lib/split-router/tests/fake-solid-router.tsdiff --git a/apps/web/src/lib/split-router/next/tests/fixtures.ts b/apps/web/src/lib/split-router/tests/fixtures.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/tests/fixtures.tsrename to apps/web/src/lib/split-router/tests/fixtures.tsdiff --git a/apps/web/src/lib/split-router/tests/history.test.ts b/apps/web/src/lib/split-router/tests/history.test.tsindex ba4c1660ba..1d598d4aec 100644--- a/apps/web/src/lib/split-router/tests/history.test.ts+++ b/apps/web/src/lib/split-router/tests/history.test.ts@@ -1,71 +1,300 @@-import { describe, expect, it } from 'vitest';+import { createRoot } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createBrowserHistory } from '../history/browser';+import { createMemoryHistory } from '../history/memory';+import { readSlice, STATE_KEY, toMountLocation } from '../history/shared';import {- createSplitRouterHistories,- createSplitRouterHistory,-} from '../history';--describe('split router history', () => {- it('pushes, replaces, and traverses entries', () => {- const history = createSplitRouterHistory<string>('one', Object.is);-- expect(history.push('two')).toBe(true);- expect(history.push('three')).toBe(true);- expect(history.entries()).toEqual(['one', 'two', 'three']);- expect(history.canGo(-2)).toBe(true);- expect(history.go(-1)).toBe(true);- expect(history.current()).toBe('two');- expect(history.replace('second')).toBe(true);- expect(history.entries()).toEqual(['one', 'second', 'three']);- expect(history.go(1)).toBe(true);- expect(history.current()).toBe('three');- });+ createSolidRouterHistory,+ type SolidRouterHistoryOptions,+} from '../history/solid-router';+import type { ExternalChange } from '../history/types';+import { decodePanes, parseLocation } from '../routes/codec';+import { createRoutesManifest } from '../routes/manifest';+import type { ExternalLocation, PaneId } from '../routes/types';+import { createFakeSolidRouter } from './fake-solid-router';+import { appRoutes } from './fixtures';++const stateFor = (entry: string) => ({+ panes: [{ pane: 'p1' as PaneId, entry }],+});+const at = (path: string, entry = 'e1'): ExternalLocation => ({+ ...parseLocation(path),+ state: stateFor(entry),+});- it('truncates forward entries after a push', () => {- const history = createSplitRouterHistory<string>('one', Object.is);+afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});- history.push('two');- history.push('three');- history.go(-2);- history.push('four');+describe('history helpers', () => {+ it('matches the base on a segment boundary', () => {+ expect(toMountLocation('/app', '/app')?.path).toBe('/');+ expect(toMountLocation('/app/mail', '/app')?.path).toBe('/mail');+ expect(toMountLocation('/application', '/app')).toBeUndefined();+ });- expect(history.entries()).toEqual(['one', 'four']);- expect(history.canGo(1)).toBe(false);+ it('reads only non-negative whole history indexes', () => {+ const slice = (index: unknown) => ({ [STATE_KEY]: { index } });+ expect(readSlice(slice(2))?.index).toBe(2);+ expect(readSlice(slice(-1))).toBeUndefined();+ expect(readSlice(slice(1.5))).toBeUndefined();+ expect(readSlice(slice(Number.NaN))).toBeUndefined();});+});- it('accepts an existing entry by moving the index', () => {- const history = createSplitRouterHistory<string>('one', Object.is);+describe('memory history', () => {+ it('never reports its own writes', () => {+ const history = createMemoryHistory('/a');+ const listener = vi.fn();+ history.subscribe(listener);+ history.write(at('/b'), { mode: 'push' });+ history.write(at('/c'), { mode: 'replace' });+ expect(listener).not.toHaveBeenCalled();+ expect(history.entries().map((entry) => entry.path)).toEqual(['/a', '/c']);+ });- history.push('two');- history.push('three');+ it('reports traversal and reverts it', () => {+ const history = createMemoryHistory('/a');+ history.write(at('/b'), { mode: 'push' });+ const changes: ExternalChange[] = [];+ history.subscribe((change) => changes.push(change));+ history.back();+ expect(changes.map((change) => change.location.path)).toEqual(['/a']);+ changes[0]!.revert();+ expect(history.read().path).toBe('/b');+ });- expect(history.accept('one', 'replace')).toBe(true);- expect(history.index()).toBe(0);- expect(history.entries()).toEqual(['one', 'two', 'three']);+ it('lets interceptors veto outside navigations', async () => {+ const history = createMemoryHistory('/a');+ const listener = vi.fn();+ history.subscribe(listener);+ const stop = history.intercept(() => false);+ await expect(history.navigate('/x')).resolves.toBe(false);+ expect(history.read().path).toBe('/a');+ stop();+ history.intercept(async () => true);+ await expect(history.navigate('/y')).resolves.toBe(true);+ expect(listener).toHaveBeenCalledOnce();+ expect(history.read().path).toBe('/y');});+});- it('transfers positional history when a layout replaces an id', () => {- const histories = createSplitRouterHistories<string, string>(Object.is);+describe('browser history', () => {+ beforeEach(() => window.history.replaceState(null, '', '/app/home'));++ it('reads mount-relative locations and records positions on write', () => {+ const history = createBrowserHistory({ base: '/app' });+ expect(history.read()).toMatchObject({ path: '/home' });+ history.write(at('/mail?x=1'), { mode: 'push' });+ expect(window.location.pathname).toBe('/app/mail');+ expect(window.history.state.__splitRouter).toEqual({+ index: 1,+ value: stateFor('e1'),+ });+ expect(history.read()).toEqual({+ path: '/mail',+ search: '?x=1',+ hash: '',+ state: stateFor('e1'),+ });+ expect(history.href({ path: '/mail', search: '?q=1', hash: '' })).toBe(+ '/app/mail?q=1'+ );+ });- histories.reconcile([{ id: 'first', entry: 'one' }], 'replace', 'move');- histories.reconcile([{ id: 'first', entry: 'two' }], 'push', 'write');- histories.reconcile([{ id: 'second', entry: 'two' }], 'replace', 'move');+ it('reports back/forward, and a revert returns to the previous entry', async () => {+ const history = createBrowserHistory({ base: '/app' });+ history.write(at('/home', 'e1'), { mode: 'replace' });+ history.write(at('/mail', 'e2'), { mode: 'push' });+ const changes: ExternalChange[] = [];+ history.subscribe((change) => changes.push(change));- expect(histories.get('first')).toBeUndefined();- expect(histories.get('second')?.entries()).toEqual(['one', 'two']);+ const popped = () =>+ new Promise((resolve) =>+ window.addEventListener('popstate', resolve, { once: true })+ );+ const back = popped();+ window.history.back();+ await back;+ expect(changes.map((change) => change.location.path)).toEqual(['/home']);- histories.reconcile([], 'replace', 'move');- expect(histories.get('second')).toBeUndefined();+ await changes[0]!.revert();+ expect(window.location.pathname).toBe('/app/mail');+ expect(changes.map((change) => change.location.path)).toEqual([+ '/home',+ '/mail',+ ]);});- it('ignores invalid deltas and structurally equal writes', () => {- const history = createSplitRouterHistory(- { value: 'one' },- (left, right) => left.value === right.value+ it('rewrites legacy multi-pane paths through transformPath', () => {+ // Pre-`~` URLs listed each pane as a `type/id` pair in one path.+ const upgradeLegacy = (path: string) => {+ const segments = path.split('/').filter(Boolean);+ const pairs = segments.length >= 4 && segments.length % 2 === 0;+ if (!pairs) return path;+ const panes = [];+ for (let index = 0; index < segments.length; index += 2) {+ if (!['md', 'pdf', 'channel'].includes(segments[index]!)) return path;+ panes.push(`${segments[index]}/${segments[index + 1]}`);+ }+ return `/${panes.join('/~/')}`;+ };+ window.history.replaceState(null, '', '/app/md/a/pdf/b');+ const history = createBrowserHistory({+ base: '/app',+ transformPath: upgradeLegacy,+ });+ const decoded = decodePanes(+ createRoutesManifest(appRoutes),+ history.read());+ expect(+ decoded.panes.map((pane) => pane.entry.location.route.matches[1]!.params)+ ).toEqual([+ { type: 'md', id: 'a' },+ { type: 'pdf', id: 'b' },+ ]);++ window.history.replaceState(null, '', '/app/drive/md/a');+ expect(history.read().path).toBe('/drive/md/a');+ });+});++describe('Solid Router history', () => {+ const adapterFor = (+ router: ReturnType<typeof createFakeSolidRouter>,+ options: Partial<SolidRouterHistoryOptions> = {}+ ) =>+ createSolidRouterHistory({+ location: router.location,+ navigate: router.navigate,+ beforeLeave: router.beforeLeave,+ base: '/app',+ ...options,+ });++ it('writes in a later task, merges writes, and skips its own write landing', () => {+ vi.useFakeTimers();+ const router = createFakeSolidRouter('/app/home');+ const listener = vi.fn();+ const { history, dispose } = createRoot((dispose) => {+ const history = adapterFor(router);+ history.subscribe(listener);+ return { history, dispose };+ });++ history.write(at('/mail'), { mode: 'push' });+ history.write(at('/mail/t1'), { mode: 'replace' });+ expect(router.calls).toEqual([]);+ vi.runAllTimers();++ expect(router.calls).toEqual([+ [+ '/mail/t1',+ {+ replace: false,+ scroll: false,+ state: { __splitRouter: { index: 1, value: stateFor('e1') } },+ },+ ],+ ]);+ expect(listener).not.toHaveBeenCalled();+ expect(history.read()).toEqual({+ path: '/mail/t1',+ search: '',+ hash: '',+ state: stateFor('e1'),+ });+ dispose();+ });++ it('strips the base and applies the path transform', () => {+ const router = createFakeSolidRouter('/app/s_abc');+ createRoot((dispose) => {+ const history = adapterFor(router, {+ transformPath: (path) => path.replace('s_abc', 'md/abc'),+ });+ expect(history.read().path).toBe('/md/abc');+ dispose();+ });+ });++ it('reports back/forward, and a revert settles once it has landed', async () => {+ vi.useFakeTimers();+ const router = createFakeSolidRouter('/app/home');+ const changes: ExternalChange[] = [];+ const { history, dispose } = createRoot((dispose) => {+ const history = adapterFor(router);+ history.subscribe((change) => changes.push(change));+ return { history, dispose };+ });+ history.write(at('/home', 'e1'), { mode: 'replace' });+ vi.runAllTimers();+ history.write(at('/mail', 'e2'), { mode: 'push' });+ vi.runAllTimers();++ router.traverse(-1);+ expect(changes.map((change) => change.location.path)).toEqual(['/home']);+ const reverted = changes[0]!.revert();+ expect(history.read().path).toBe('/home');+ await reverted;+ expect(router.calls.at(-1)).toEqual([1, undefined]);+ expect(history.read().path).toBe('/mail');+ expect(changes.map((change) => change.location.path)).toEqual([+ '/home',+ '/mail',+ ]);+ dispose();+ });++ it('reports every location under its base and ignores the rest', () => {+ const router = createFakeSolidRouter('/app/home');+ const listener = vi.fn();+ const dispose = createRoot((dispose) => {+ adapterFor(router).subscribe(listener);+ return dispose;+ });+ router.show('/elsewhere', undefined);+ expect(listener).not.toHaveBeenCalled();+ router.show('/app/login', undefined);+ expect(listener).toHaveBeenCalledOnce();+ dispose();+ });++ it('intercepts outside navigations through beforeLeave', async () => {+ const router = createFakeSolidRouter('/app/home');+ const verdicts: (boolean | Promise<boolean>)[] = [+ false,+ Promise.resolve(true),+ true,+ ];+ const seen: (ExternalLocation | undefined)[] = [];+ const dispose = createRoot((dispose) => {+ adapterFor(router).intercept?.((location) => {+ seen.push(location);+ return verdicts.shift()!;+ });+ return dispose;+ });++ const blocked = router.leave('/app/mail/t1');+ expect(blocked.preventDefault).toHaveBeenCalled();+ expect(seen[0]).toEqual({ path: '/mail/t1', search: '', hash: '' });++ const deferred = router.leave('/elsewhere');+ expect(seen[1]).toBeUndefined();+ expect(deferred.preventDefault).toHaveBeenCalled();+ await Promise.resolve();+ await Promise.resolve();+ expect(deferred.retry).toHaveBeenCalledWith(true);++ const allowed = router.leave('/app/mail');+ expect(allowed.preventDefault).not.toHaveBeenCalled();- expect(history.push({ value: 'one' })).toBe(false);- expect(history.replace({ value: 'one' })).toBe(false);- expect(history.canGo(0)).toBe(false);- expect(history.go(Number.NaN)).toBe(false);+ const traversal = router.leave(-1);+ expect(traversal.preventDefault).not.toHaveBeenCalled();+ expect(seen).toHaveLength(3);+ dispose();});});diff --git a/apps/web/src/lib/split-router/tests/location-sync.test.ts b/apps/web/src/lib/split-router/tests/location-sync.test.tsdeleted file mode 100644index 5829fd8d94..0000000000--- a/apps/web/src/lib/split-router/tests/location-sync.test.ts+++ /dev/null@@ -1,113 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import { createLocationSync } from '../location-sync';-import { createRoutesManifest, decodeRoute } from '../routes';-import type { SplitRouterExternalLocationValue } from '../types';-import { parseExternalLocation } from '../url';--const routes = createRoutesManifest({- definitions: [{ id: 'item', path: 'item/:id' }],-});--function setup() {- let current = parseExternalLocation('/item/initial');- const commit = vi.fn();- const sync = createLocationSync({- routes,- location: {- read: () => current,- commit,- subscribe: () => () => {},- },- });- const acknowledge = (next: SplitRouterExternalLocationValue) => {- current = next;- return sync.acknowledge(next);- };- const navigate = (id: string) =>- sync.commit([decodeRoute(routes, ['item', id])!], {- history: 'push',- preserveHash: false,- });- return { sync, commit, acknowledge, navigate };-}--describe('external location synchronization', () => {- it('does not recommit the current location or an outstanding request', () => {- const { commit, navigate, acknowledge } = setup();- navigate('initial');- expect(commit).not.toHaveBeenCalled();- navigate('next');- navigate('next');- expect(commit).toHaveBeenCalledTimes(1);- expect(acknowledge(parseExternalLocation('/item/next/'))).toBe(true);- expect(acknowledge(parseExternalLocation('/item/external'))).toBe(false);- });-- it('expires coalesced writes so a later Back is not swallowed', () => {- const { commit, navigate, acknowledge } = setup();- navigate('first');- navigate('second');- expect(acknowledge(parseExternalLocation('/item/second'))).toBe(true);- expect(acknowledge(parseExternalLocation('/item/first'))).toBe(false);- expect(commit).toHaveBeenCalledTimes(2);- });-- it('accepts ordered echoes without additional writes', () => {- const { commit, navigate, acknowledge } = setup();- navigate('first');- navigate('second');- expect(acknowledge(parseExternalLocation('/item/first'))).toBe(true);- expect(acknowledge(parseExternalLocation('/item/second'))).toBe(true);- expect(acknowledge(parseExternalLocation('/item/first'))).toBe(false);- expect(commit).toHaveBeenCalledTimes(2);- });-- it('allows a newer request to supersede an outstanding write even at the current URL', () => {- const { commit, navigate, acknowledge } = setup();- navigate('first');- navigate('initial');- expect(commit).toHaveBeenCalledTimes(2);- expect(acknowledge(parseExternalLocation('/item/initial'))).toBe(true);- expect(acknowledge(parseExternalLocation('/item/first'))).toBe(false);- });-- it('expires older duplicate signatures when the latest request repeats a URL', () => {- const { commit, navigate, acknowledge } = setup();- navigate('first');- navigate('second');- navigate('first');- expect(commit).toHaveBeenCalledTimes(3);- expect(acknowledge(parseExternalLocation('/item/first'))).toBe(true);- expect(acknowledge(parseExternalLocation('/item/second'))).toBe(false);- });-- it('distinguishes commits with the same URL by entry identity', () => {- const current = parseExternalLocation('/item/initial');- const commit = vi.fn();- const sync = createLocationSync({- routes,- location: {- read: () => current,- commit,- subscribe: () => () => {},- },- });- const entry = decodeRoute(routes, ['item', 'same'])!;-- sync.commit([{ ...entry, key: 'entry-1', state: { feature: 'first' } }], {- history: 'push',- preserveHash: false,- });- sync.commit([{ ...entry, key: 'entry-2', state: { feature: 'second' } }], {- history: 'push',- preserveHash: false,- });-- expect(commit).toHaveBeenCalledTimes(2);- expect(commit.mock.calls[0]?.[0].pathname).toBe('/item/same');- expect(commit.mock.calls[1]?.[0].pathname).toBe('/item/same');- expect(commit.mock.calls[0]?.[0].state).not.toEqual(- commit.mock.calls[1]?.[0].state- );- });-});diff --git a/apps/web/src/lib/split-router/tests/middleware.test.ts b/apps/web/src/lib/split-router/tests/middleware.test.tsdeleted file mode 100644index ce770ed762..0000000000--- a/apps/web/src/lib/split-router/tests/middleware.test.ts+++ /dev/null@@ -1,201 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import { z } from 'zod';-import { prepareEntry, runSplitRouterMiddleware } from '../middleware';-import {- createRoutesManifest,- defineRoute,- rootRouteMatch,- routeParams,-} from '../routes';-import type { SplitRouterMiddleware } from '../types';--const routes = createRoutesManifest({- definitions: [- defineRoute({- id: 'drive',- path: 'drive',- children: [- {- id: 'drive-document',- path: 'md/:documentId',- params: z.object({ documentId: z.string() }),- },- ],- }),- {- id: 'legacy',- path: 'legacy/:id',- params: z.object({ id: z.string() }),- },- ],-});--const legacyEntry = {- location: {- route: {- matches: [{ id: 'legacy', params: { id: 'document-1' } }] as const,- },- search: { view: { mode: ['compact'] } },- },-};--describe('split router middleware', () => {- it('stays synchronous when every middleware is synchronous', () => {- const result = runSplitRouterMiddleware(- {- routes,- handlers: [- ({ to, redirect }) =>- rootRouteMatch(to.location.route)?.id === 'legacy'- ? redirect(`/drive/md/${routeParams(to.location.route).id}`)- : undefined,- ],- },- {- to: {- ...legacyEntry,- key: 'entry-1',- state: { feature: 'state' },- },- cause: 'navigate',- signal: new AbortController().signal,- }- );-- expect(result).not.toBeInstanceOf(Promise);- expect(result).toMatchObject({- key: 'entry-1',- state: { feature: 'state' },- location: {- route: {- matches: [- { id: 'drive', params: {} },- {- id: 'drive-document',- params: { documentId: 'document-1' },- },- ],- },- },- });- });-- it('awaits middleware and restarts the pipeline after a redirect', async () => {- const visits: string[] = [];- const searches: (string | undefined)[] = [];- const middleware: SplitRouterMiddleware[] = [- async ({ path, externalSearch }) => {- await Promise.resolve();- visits.push(`preload:${path}`);- searches.push(externalSearch);- },- ({ to, redirect }) => {- const routeId = rootRouteMatch(to.location.route)?.id;- visits.push(`redirect:${routeId}`);- if (routeId === 'legacy') {- return redirect(`/drive/md/${routeParams(to.location.route).id}`);- }- },- ];-- const result = await runSplitRouterMiddleware(- { routes, handlers: middleware },- {- to: legacyEntry,- externalSearch: '?legacy=first&legacy=last',- cause: 'external',- signal: new AbortController().signal,- }- );-- expect(visits).toEqual([- 'preload:/legacy/document-1',- 'redirect:legacy',- 'preload:/drive/md/document-1',- 'redirect:drive',- ]);- expect(searches).toEqual([- '?legacy=first&legacy=last',- '?legacy=first&legacy=last',- ]);- expect(result).toEqual({- location: {- route: {- matches: [- { id: 'drive', params: {} },- {- id: 'drive-document',- params: { documentId: 'document-1' },- },- ],- },- search: { view: { mode: ['compact'] } },- },- });- });-- it('passes cancellation to pending preload work', async () => {- const controller = new AbortController();- const observed = vi.fn();- const pending = runSplitRouterMiddleware(- {- routes,- handlers: [- ({ signal }) =>- new Promise<void>((_resolve, reject) => {- signal.addEventListener('abort', () => {- observed();- reject(signal.reason);- });- }),- ],- },- {- to: legacyEntry,- cause: 'external',- signal: controller.signal,- }- );-- controller.abort(new DOMException('Superseded', 'AbortError'));-- await expect(pending).rejects.toMatchObject({ name: 'AbortError' });- expect(observed).toHaveBeenCalledOnce();- });-- it('rejects invalid asynchronous results instead of recovering to a malformed proposal', async () => {- const pending = prepareEntry(- {- routes,- handlers: [- async ({ to }) => {- await Promise.resolve();- to.location.route = { matches: [{ id: 'missing', params: {} }] };- },- ],- },- {- to: { location: { route: { matches: [{ id: 'drive', params: {} }] } } },- cause: 'navigate',- signal: new AbortController().signal,- }- );- await expect(pending).rejects.toThrow('invalid match branch');- });-- it('rejects redirect loops', () => {- expect(() =>- runSplitRouterMiddleware(- {- routes,- handlers: [({ path, redirect }) => redirect(path)],- },- {- to: legacyEntry,- cause: 'navigate',- signal: new AbortController().signal,- }- )- ).toThrow('redirect loop');- });-});diff --git a/apps/web/src/lib/split-router/tests/navigation.test.ts b/apps/web/src/lib/split-router/tests/navigation.test.tsindex 616684cea0..1dcbc47aa7 100644--- a/apps/web/src/lib/split-router/tests/navigation.test.ts+++ b/apps/web/src/lib/split-router/tests/navigation.test.ts@@ -1,252 +1,354 @@-import { describe, expect, expectTypeOf, it } from 'vitest';-import { z } from 'zod';-import { resolveNavigation } from '../navigation';+import { simulate, step } from '@macro-inc/machine';+import { afterEach, describe, expect, it, vi } from 'vitest';import {- createRoutesManifest,- decodeRoute,- defineRoute,- defineRoutes,- routeParams,-} from '../routes';-import type {- SplitNavigate,- SplitRouteNavigationTarget,- SplitRouterEntry,- SplitRouteUnion,-} from '../types';--const workspaceDetailRoute = defineRoute({- id: 'workspace-detail',- path: 'detail/:documentId',- params: z.object({ documentId: z.string() }),-});+ runMiddleware,+ type SplitRouterMiddleware,+} from '../router/middleware';+import { IDLE, type State as RunState, runDef } from '../router/run';+import type { Navigation } from '../router/types';+import {+ type Event as GateEvent,+ type State as GateState,+ type UrlOutcome,+ urlGateDef,+} from '../router/url-gate';+import { createRoutesManifest, decodePane } from '../routes/manifest';+import type { Entry, PaneId } from '../routes/types';+import { CANCELLED } from '../utils';+import { appRoutes } from './fixtures';-const workspacePageRoute = defineRoute({- id: 'workspace-page',- path: 'page/:page',- params: z.object({ page: z.coerce.number().int().positive() }),+const routes = createRoutesManifest(appRoutes);+const entry = (+ id: string,+ path: string,+ extra: Partial<Entry> = {}+): Entry => ({+ id,+ location: { route: decodePane(routes, path.split('/').filter(Boolean))! },+ ...extra,});+const signal = () => new AbortController().signal;-const workspaceFolderRoute = defineRoute({- id: 'workspace-folder',- path: 'folder/:folderId',- params: z.object({ folderId: z.string() }),- children: [workspaceDetailRoute],+const pane = 'p1' as PaneId;+const navigation = (id: string): Navigation => ({+ cause: 'navigate',+ targets: [{ pane, to: entry(id, '/home') }],+ apply: () => ({ status: 'committed', pane }),});+const first = navigation('e1');+const second = navigation('e2');+const third = navigation('e4');+const entries = [entry('e3', '/mail')];-const workspaceRoute = defineRoute({- id: 'workspace',- path: 'workspace',- search: ['workspace'],- children: [workspaceFolderRoute, workspacePageRoute],-});+afterEach(() => vi.restoreAllMocks());++describe('run', () => {+ const guards: RunState = { t: 'guards', navigation: first };+ const middleware: RunState = { t: 'middleware', navigation: first };+ const preload: RunState = { t: 'preload', navigation: first, entries };++ it('moves from guards to middleware to preload, then commits', () => {+ const run = simulate(runDef, IDLE, [+ { t: 'navigate', navigation: first },+ { t: 'allowed' },+ { t: 'resolved', entries },+ { t: 'preloaded' },+ ]);+ expect(run.state).toEqual(IDLE);+ expect(run.commands).toEqual([{ t: 'commit', navigation: first, entries }]);+ });++ it('is turned down by guards or middleware, and fails from any phase', () => {+ expect(step(runDef, guards, { t: 'refused' })?.commands).toEqual([+ { t: 'cancel', navigation: first, reason: 'refused' },+ ]);+ expect(+ step(runDef, middleware, { t: 'middleware-cancelled' })?.commands+ ).toEqual([{ t: 'cancel', navigation: first, reason: 'cancelled' }]);+ expect(step(runDef, preload, { t: 'failed' })).toEqual({+ state: IDLE,+ commands: [{ t: 'cancel', navigation: first, reason: 'failed' }],+ });+ });++ it('ignores a report from a phase it has left', () => {+ expect(step(runDef, middleware, { t: 'allowed' })).toBeUndefined();+ expect(step(runDef, preload, { t: 'resolved', entries })).toBeUndefined();+ });++ it('lets a newer navigation replace the one in flight', () => {+ const run = simulate(runDef, IDLE, [+ { t: 'navigate', navigation: first },+ { t: 'allowed' },+ { t: 'navigate', navigation: second },+ ]);+ expect(run.state).toEqual({ t: 'guards', navigation: second });+ expect(run.commands).toEqual([+ { t: 'cancel', navigation: first, reason: 'superseded' },+ ]);+ });++ it('cancels with the reason it is aborted for', () => {+ expect(+ step(runDef, preload, { t: 'abort', reason: 'interrupted' })+ ).toEqual({+ state: IDLE,+ commands: [{ t: 'cancel', navigation: first, reason: 'interrupted' }],+ });+ });-const stateRoute = defineRoute({- id: 'state-root',- path: 'state',- state: z- .object({ trail: z.array(z.string()) })- .transform((state) => ({ ...state, length: state.trail.length })),- children: [{ id: 'state-child', path: 'child' }],+ it('ignores reports and aborts while idle', () => {+ expect(+ step(runDef, IDLE, { t: 'abort', reason: 'superseded' })+ ).toBeUndefined();+ expect(step(runDef, IDLE, { t: 'preloaded' })).toBeUndefined();+ });});-const stateChildRoute = stateRoute.children[0];--const tree = defineRoutes({ definitions: [workspaceRoute] });-const routes = createRoutesManifest(tree);-const boundDetail = tree.definitions[0].children[0].children[0];-const boundPage = tree.definitions[0].children[1];--function entry(path: string[]): SplitRouterEntry {- return decodeRoute(routes, path)!;-}--function assertTypedRouteTargets(navigate: SplitNavigate<string>) {- navigate({- route: workspaceDetailRoute,- params: { documentId: 'document-1' },- });- navigate({ route: workspaceRoute });- navigate({ route: stateChildRoute }, { state: { trail: ['first'] } });- navigate(- { route: stateChildRoute },- {- state: (current) => ({- trail: [...(current?.trail ?? []), String(current?.length ?? 0)],- }),- }- );- // @ts-expect-error Routes without a state schema reject navigation state.- navigate({ route: workspaceRoute }, { state: { trail: [] } });- // @ts-expect-error Navigation uses the route state schema's input type.- navigate({ route: stateChildRoute }, { state: { length: 1 } });- navigate({ route: workspacePageRoute, params: { page: 2 } });- navigate({- route: boundDetail,- params: { folderId: 'folder', documentId: 'doc' },- });- // @ts-expect-error A tree-bound destination requires its ancestor params too.- navigate({ route: boundDetail, params: { documentId: 'doc' } });- // @ts-expect-error Ancestor fields keep their schema output types.- navigate({ route: boundDetail, params: { folderId: 4, documentId: 'doc' } });- // @ts-expect-error A route union cannot pair one route with another route's params.- const mismatched: SplitRouteNavigationTarget<- typeof boundDetail | typeof boundPage- > = { route: boundPage, params: { folderId: 'folder', documentId: 'doc' } };- void mismatched;- const destination: SplitRouteNavigationTarget<SplitRouteUnion<typeof tree>> =- { route: boundDetail, params: { folderId: 'folder', documentId: 'doc' } };- navigate(destination);- // @ts-expect-error navigation uses the schema output type- navigate({ route: workspacePageRoute, params: { page: '2' } });- // @ts-expect-error documentId is required by the route schema- navigate({ route: workspaceDetailRoute });- // @ts-expect-error documentId must be a string- navigate({- route: workspaceDetailRoute,- params: { documentId: 1 },- });-}--describe('split route navigation', () => {- it('requires params inferred from typed route schemas', () => {- expectTypeOf(assertTypedRouteTargets).toBeFunction();- });-- it('round trips typed navigation params through route schemas', () => {- const current = entry(['workspace']);- const next = resolveNavigation(routes, current, current, {- route: workspacePageRoute,- params: { page: 2 },++describe('URL gate', () => {+ const open: GateState = { t: 'open' };+ const start = (navigating: Navigation, blocking = false): GateEvent => ({+ t: 'start',+ navigation: navigating,+ blocking,+ });+ const settled = (navigating: Navigation, outcome: UrlOutcome): GateEvent => ({+ t: 'settled',+ navigation: navigating,+ outcome,+ });+ const ACTION: GateEvent = { t: 'action' };+ const LANDED: GateEvent = { t: 'revert-landed' };+ const OPENED = { t: 'opened' };+ const runs = (navigating: Navigation) => [+ { t: 'cancel-pane-runs' },+ { t: 'run', navigation: navigating },+ ];+ const revert = (navigating: Navigation) => ({+ t: 'revert',+ navigation: navigating,+ });+ const abort = (navigating: Navigation, reason: string) => ({+ t: 'abort',+ navigation: navigating,+ reason,+ });++ it('lets actions straight through while no URL navigation runs', () => {+ expect(step(urlGateDef, open, ACTION)).toEqual({+ state: open,+ commands: [OPENED],});+ expect(step(urlGateDef, open, start(first))?.commands).toEqual(runs(first));+ });- expect(next?.location?.route?.matches).toEqual([- { id: 'workspace', params: {} },- { id: 'workspace-page', params: { page: 2 } },+ it('keeps a replaced URL navigation to put back later, and its blocking', () => {+ const run = simulate(urlGateDef, open, [start(first, true), start(second)]);+ expect(run.state).toEqual({+ t: 'navigating',+ navigation: second,+ blocking: true,+ superseded: [first],+ });+ expect(run.commands).toEqual([...runs(first), ...runs(second)]);+ });++ it('opens once the current URL navigation commits, forgetting the ones it replaced', () => {+ const run = simulate(urlGateDef, open, [+ start(first),+ start(second),+ settled(second, 'committed'),]);+ expect(run.state).toEqual(open);+ expect(run.commands).toEqual([...runs(first), ...runs(second), OPENED]);});- it.each([['workspace'], ['workspace', 'folder', 'old-folder']])(- 'uses explicit ancestor params from %j',- (...path) => {- const current = entry(path);- const next = resolveNavigation(routes, current, undefined, {- route: boundDetail,- params: { folderId: 'new-folder', documentId: 'document-1' },- });- expect(next?.location.route.matches).toEqual([- { id: 'workspace', params: {} },- { id: 'workspace-folder', params: { folderId: 'new-folder' } },- { id: 'workspace-detail', params: { documentId: 'document-1' } },+ it.each(['refused', 'cancelled'] as const)(+ 'puts back a %s URL navigation, then the ones it replaced, newest first',+ (outcome) => {+ const run = simulate(urlGateDef, open, [+ start(first),+ start(second),+ start(third),+ settled(third, outcome),+ LANDED,+ LANDED,+ LANDED,+ ]);+ expect(run.state).toEqual(open);+ expect(run.commands.slice(6)).toEqual([+ revert(third),+ revert(second),+ revert(first),+ OPENED,]);});- it('serializes transformed ancestor outputs without validating them as inputs', () => {- const dated = defineRoutes({- definitions: [- defineRoute({- id: 'day',- path: 'day/:date',- params: z.object({- date: z.string().transform((date) => new Date(date)),- }),- serializeParams: ({ date }) => ({- date: date.toISOString().slice(0, 10),- }),- children: [- defineRoute({- id: 'day-item',- path: 'item/:id',- params: z.object({ id: z.string() }),- }),- ],- }),- ],- });- const manifest = createRoutesManifest({- definitions: [...tree.definitions, ...dated.definitions],- });- const current = decodeRoute(manifest, ['workspace'])!;- const date = new Date('2026-01-02T00:00:00Z');- const next = resolveNavigation(manifest, current, undefined, {- route: dated.definitions[0].children[0],- params: { date, id: 'one' },- });- expect(next?.location.route.matches).toEqual([- { id: 'day', params: { date } },- { id: 'day-item', params: { id: 'one' } },+ it('opens after a failed URL navigation without putting its URL back', () => {+ const run = simulate(urlGateDef, open, [+ start(first),+ settled(first, 'failed'),]);+ expect(run.state).toEqual(open);+ expect(run.commands).toEqual([...runs(first), OPENED]);});- it('appends explicit child-relative paths to the current route', () => {- const current = entry(['workspace', 'folder', 'folder-1']);- const next = resolveNavigation(- routes,- current,- current,- './detail/document-1'- );+ it('ignores the outcome of a URL navigation that is no longer current', () => {+ const navigating: GateState = {+ t: 'navigating',+ navigation: second,+ blocking: false,+ superseded: [first],+ };+ expect(+ step(urlGateDef, navigating, settled(first, 'committed'))+ ).toBeUndefined();+ });- expect(next?.location?.route?.matches).toEqual([- { id: 'workspace', params: {} },- { id: 'workspace-folder', params: { folderId: 'folder-1' } },- { id: 'workspace-detail', params: { documentId: 'document-1' } },+ it('holds an action while a blocking URL navigation runs', () => {+ const blocking: GateState = {+ t: 'navigating',+ navigation: first,+ blocking: true,+ superseded: [],+ };+ expect(step(urlGateDef, blocking, ACTION)).toBeUndefined();+ });++ it('lets an action take over from any other URL navigation once its URLs are back', () => {+ const run = simulate(urlGateDef, open, [+ start(first),+ start(second),+ ACTION,+ LANDED,+ LANDED,+ ]);+ expect(run.state).toEqual(open);+ expect(run.commands.slice(4)).toEqual([+ abort(second, 'interrupted'),+ revert(second),+ revert(first),+ OPENED,]);});- it('navigates to a parent while preserving its params and search', () => {- const current = entry([- 'workspace',- 'folder',- 'folder-1',- 'detail',- 'document-1',+ it('turns away a URL navigation that arrives while reverting and puts it back too', () => {+ const run = simulate(urlGateDef, open, [+ start(first),+ ACTION,+ start(second),+ LANDED,+ LANDED,+ ]);+ expect(run.state).toEqual(open);+ expect(run.commands.slice(2)).toEqual([+ abort(first, 'interrupted'),+ revert(first),+ abort(second, 'interrupted'),+ revert(second),+ OPENED,]);- current.location = {- ...current.location,- search: { workspace: { sort: ['name'] } },- };- const next = resolveNavigation(routes, current, current, { parent: true });-- expect(next?.location).toEqual({- route: {- matches: [- { id: 'workspace', params: {} },- { id: 'workspace-folder', params: { folderId: 'folder-1' } },- ],- },- search: { workspace: { sort: ['name'] } },- });});- it('navigates by a typed route and preserves matching ancestor params', () => {- const current = entry(['workspace', 'folder', 'folder-1']);- const next = resolveNavigation(routes, current, current, {- route: workspaceDetailRoute,- params: { documentId: 'document-2' },- });+ it('puts back a URL navigation arriving mid-revert before the older ones still queued', () => {+ const run = simulate(urlGateDef, open, [+ start(first),+ start(second),+ settled(second, 'refused'),+ start(third),+ LANDED,+ LANDED,+ LANDED,+ ]);+ const reverts = run.commands.filter((command) => command.t === 'revert');++ expect(run.state).toEqual(open);+ expect(reverts).toEqual([revert(second), revert(third), revert(first)]);+ });- expect(next?.location?.route?.matches).toEqual([- { id: 'workspace', params: {} },- { id: 'workspace-folder', params: { folderId: 'folder-1' } },- { id: 'workspace-detail', params: { documentId: 'document-2' } },+ it('aborts the URL navigation and opens on dispose, then turns everything away', () => {+ const run = simulate(urlGateDef, open, [+ start(first, true),+ { t: 'dispose' },+ ACTION,+ start(second),+ ]);+ expect(run.state).toEqual({ t: 'disposed' });+ expect(run.commands.slice(2)).toEqual([+ abort(first, 'disposed'),+ OPENED,+ OPENED,+ abort(second, 'disposed'),]);- expect(routeParams(next?.location?.route)).toEqual({- folderId: 'folder-1',- documentId: 'document-2',+ });+});++describe('middleware', () => {+ const navigatingTo = (to: Entry) => ({+ to,+ cause: 'navigate' as const,+ signal: signal(),+ });++ it('follows redirects and keeps the entry identity', () => {+ const middleware: SplitRouterMiddleware = (context) =>+ context.to.location.route.matches.at(-1)?.id === 'block' &&+ context.routes.byId.has('mail-thread')+ ? context.redirect('/mail/t1')+ : undefined;+ const result = runMiddleware(+ routes,+ [middleware],+ navigatingTo(entry('e1', '/md/d1'))+ );+ expect(result).toMatchObject({+ id: 'e1',+ location: {+ route: {+ matches: [{ id: 'app' }, { id: 'mail' }, { id: 'mail-thread' }],+ },+ },});});- it('returns undefined for invalid parent and route destinations', () => {- const current = entry(['workspace']);+ it('cancels when a handler asks to', () => {+ const result = runMiddleware(+ routes,+ [({ cancel }) => cancel()],+ navigatingTo(entry('e1', '/home'))+ );+ expect(result).toBe(CANCELLED);+ });- expect(- resolveNavigation(routes, current, current, { parent: true })- ).toBeUndefined();- expect(- resolveNavigation(routes, current, current, {- route: { id: 'missing' },- })- ).toBeUndefined();+ it('awaits async handlers', async () => {+ const result = runMiddleware(+ routes,+ [+ async ({ path, redirect }) =>+ path === '/drive' ? undefined : redirect('/drive'),+ ],+ navigatingTo(entry('e1', '/home'))+ );+ await expect(result).resolves.toMatchObject({+ location: { route: { matches: [{ id: 'app' }, { id: 'drive' }] } },+ });+ });++ it('falls back to the proposed entry on a redirect loop', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ const original = entry('e1', '/home');+ const result = runMiddleware(+ routes,+ [+ ({ to, redirect }) =>+ redirect(+ to.location.route.matches[0].id === 'home' ? '/drive' : '/home'+ ),+ ],+ navigatingTo(original)+ );+ expect(result).toBe(original);+ expect(error).toHaveBeenCalled();});});diff --git a/apps/web/src/lib/split-router/next/tests/panes.test.ts b/apps/web/src/lib/split-router/tests/panes.test.tssimilarity index 100%rename from apps/web/src/lib/split-router/next/tests/panes.test.tsrename to apps/web/src/lib/split-router/tests/panes.test.tsdiff --git a/apps/web/src/lib/split-router/tests/path.test.ts b/apps/web/src/lib/split-router/tests/path.test.tsdeleted file mode 100644index 14f6955687..0000000000--- a/apps/web/src/lib/split-router/tests/path.test.ts+++ /dev/null@@ -1,96 +0,0 @@-import { describe, expect, it } from 'vitest';-import { compileRoutePattern } from '../path';--describe('split route path patterns', () => {- it('matches required and optional parameters', () => {- const required = compileRoutePattern({ path: 'folder/:folderId' });- const optional = compileRoutePattern({ path: 'folder/:folderId?' });- expect([...required.match(['folder', 'one'])]).toEqual([- { params: { folderId: 'one' }, consumed: 2 },- ]);- expect([...optional.match(['folder'])]).toEqual([- { params: {}, consumed: 1 },- ]);- expect(optional.format({})).toEqual(['folder']);- });-- it('matches and formats a final catch-all parameter', () => {- const pattern = compileRoutePattern({ path: 'files/*remaining' });- expect([...pattern.match(['files', 'a', 'b'])]).toEqual([- { params: { remaining: ['a', 'b'] }, consumed: 3 },- ]);- expect([...pattern.match(['files'])]).toEqual([]);- expect(() => pattern.format({ remaining: [] })).toThrow(- 'Missing split route catch-all parameter "remaining"'- );- expect(pattern.format({ remaining: ['a', 'b'] })).toEqual([- 'files',- 'a',- 'b',- ]);- });-- it('rejects malformed canonical paths and aliases', () => {- expect(() => compileRoutePattern({ path: 'folder/:' })).toThrow(- 'Invalid split route parameter'- );- expect(() => compileRoutePattern({ path: 'files/*' })).toThrow(- 'Invalid split route catch-all parameter "*"'- );- expect(() =>- compileRoutePattern({ path: 'files/*remaining/edit' })- ).toThrow('catch-all parameter must be the final segment');- expect(() =>- compileRoutePattern({ path: 'folder', aliases: ['folder/~/child'] })- ).toThrow('Invalid split route path');- });-- it('matches canonical paths and aliases but formats only canonical segments', () => {- const pattern = compileRoutePattern({- path: 'document/:id',- aliases: ['doc/:id'],- });- expect([...pattern.match(['document', 'a/b c'])]).toEqual([- { params: { id: 'a/b c' }, consumed: 2 },- ]);- expect([...pattern.match(['doc', 'a/b c'])]).toEqual([- { params: { id: 'a/b c' }, consumed: 2 },- ]);- // Percent-encoding belongs to the full URL layer, not the pattern.- expect(pattern.format({ id: 'a/b c' })).toEqual(['document', 'a/b c']);- });-- it('tries the canonical pattern before aliases in declaration order', () => {- const pattern = compileRoutePattern({- path: ':first',- aliases: [':second', '*rest'],- });- expect([...pattern.match(['one'])]).toEqual([- { params: { first: 'one' }, consumed: 1 },- { params: { second: 'one' }, consumed: 1 },- { params: { rest: ['one'] }, consumed: 1 },- ]);- });-- it('formats URL-safe primitive parameters', () => {- const pattern = compileRoutePattern({- path: 'item/:id/:enabled/:revision',- });- expect(pattern.format({ id: 42, enabled: true, revision: 3n })).toEqual([- 'item',- '42',- 'true',- '3',- ]);- });-- it('requires transformed values to be serialized before formatting', () => {- const pattern = compileRoutePattern({ path: 'calendar/:day' });- const day = new Date('2026-01-02T00:00:00.000Z');- expect(() => pattern.format({ day })).toThrow('requires serializeParams');- expect(pattern.format({ day: day.toISOString().slice(0, 10) })).toEqual([- 'calendar',- '2026-01-02',- ]);- });-});diff --git a/apps/web/src/lib/split-router/tests/router.test.ts b/apps/web/src/lib/split-router/tests/router.test.tsindex 50f10ba2d9..9c9e93e130 100644--- a/apps/web/src/lib/split-router/tests/router.test.ts+++ b/apps/web/src/lib/split-router/tests/router.test.ts@@ -1,2092 +1,1404 @@+import { createEffect, createRoot, untrack } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';-import { z } from 'zod';-import { createMemorySplitRouterLocation } from '../integrations/memory';-import * as path from '../path';-import { createSplitRouter } from '../router';-import { defineRoute, rootRouteMatch, routeParams } from '../routes';+import { createMemoryHistory } from '../history/memory';+import { createSolidRouterHistory } from '../history/solid-router';+import type { HistoryAdapter } from '../history/types';+import { createMemoryPaneStore } from '../panes/memory-store';+import { createSplitRouter } from '../router/create-router';+import { PANE_LEVEL } from '../router/leave-guards';+import type { SplitCloseAction, SplitRouterOptions } from '../router/types';+import { defineRoute } from '../routes/define';import type {- SplitLocation,- SplitRouterExternalLocation,- SplitRouterExternalLocationValue,- SplitRouterLayout,- SplitRouterLayoutSnapshot,- SplitRouterMiddleware,- SplitRouterSettledChange,+ Entry,+ PaneId,+ SplitRouteDefinition,SplitRoutes,-} from '../types';--type Layout = SplitRouterLayout<string> & {- reconcileCount(): number;- updateCount(): number;- activatedSplitId(): string | undefined;- swapEntries(): void;-};--const driveFolderRoute = defineRoute({- id: 'drive-folder',- path: 'folder/:folderId',- params: z.object({ folderId: z.string() }),- claim: ({ folderId }) => ({ namespace: 'folder', id: folderId }),-});--const routes: SplitRoutes = {- definitions: [- defineRoute({- id: 'drive',- path: 'drive',- search: ['drive'],- state: z.record(z.string(), z.unknown()),- children: [driveFolderRoute],+} from '../routes/types';+import { isPromise } from '../utils';+import { createFakeSolidRouter } from './fake-solid-router';+import {+ appLocation,+ appRoute,+ appRoutes,+ createTestPolicy,+ homeLocation,+ loginRoute,+} from './fixtures';++function setup(+ url: string,+ overrides: Partial<SplitRouterOptions> = {},+ testPolicy = createTestPolicy()+) {+ const history = createMemoryHistory(url);+ const paneStore = createMemoryPaneStore<Entry>();+ const { policy, activated, placements } = testPolicy;+ let created = 0;+ const { router, dispose } = createRoot((dispose) => ({+ router: createSplitRouter({+ routes: appRoutes,+ history,+ paneStore,+ policy,+ createPaneId: () => `pane-${++created}` as PaneId,+ ...overrides,}),- {- id: 'legacy',- path: 'legacy/:id',- params: z.object({ id: z.string() }),- },- ],- globalSearch: ['referral_code'],-};--function createLayout(): Layout {- let nextId = 0;- let reconciliations = 0;- let updates = 0;- let activatedSplitId: string | undefined;- let entries: SplitRouterLayoutSnapshot<string>['entries'] = [];- const listeners = new Set<(change: SplitRouterSettledChange) => void>();-- const notify = (history: 'push' | 'replace' = 'push') => {- for (const listener of listeners) {- listener({ history });- }- };-+ dispose,+ }));return {- snapshot: () => ({ entries }),-- updateCurrentLocation(splitId, update) {- updates += 1;- entries = entries.map((entry) => {- if (entry.splitId !== splitId) return entry;- return { splitId, location: update(entry) };- });- notify();- },-- open({ target, replace, ...entry }) {- const next = {- splitId: `split-${++nextId}`,- ...entry,- };- let openedId = next.splitId;- if (target === 'new-split' || !target) {- entries = [...entries, next];- } else {- const index = entries.findIndex((entry) => entry.splitId === target);-- if (index < 0) {- entries = [...entries, next];- } else {- openedId = entries[index]!.splitId;- entries = entries.with(index, {- ...next,- splitId: openedId,- });- }- }- notify(replace ? 'replace' : 'push');- return { status: 'applied', splitId: openedId };- },-- reconcile(nextLocations) {- reconciliations++;- entries = nextLocations.map((location, index) => {- const current = entries[index];-- return {- splitId: current?.splitId ?? `split-${++nextId}`,- location,- };- });- notify('replace');- },-- activate(splitId) {- activatedSplitId = splitId;- },-- subscribe(listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },-- reconcileCount: () => reconciliations,- updateCount: () => updates,- activatedSplitId: () => activatedSplitId,- swapEntries() {- entries = entries.toReversed();- notify();+ router,+ history,+ paneStore,+ activated,+ placements,+ pane: (index: number) => router.panes()[index]!,+ dispose: () => {+ router.dispose();+ dispose();},};}-const settle = () => new Promise<void>((resolve) => queueMicrotask(resolve));--afterEach(() => vi.restoreAllMocks());--describe('split router', () => {- it('runs the host opening policy only after acceptance and ignores superseded requests', async () => {- const gate = Promise.withResolvers<void>();- const layout = createLayout();+/** A router over the Solid Router fake mounted at `/app`. */+function setupSolid(url: string, ahead: readonly string[] = []) {+ const solid = createFakeSolidRouter(url, ahead);+ return createRoot((dispose) => {const router = createSplitRouter({- layout,- routes,- location: createMemorySplitRouterLocation('/drive'),- middleware: [- ({ cause, to }) =>- cause === 'navigate' &&- routeParams(to.location.route).folderId === 'slow'- ? gate.promise- : undefined,- ],- });- await router.settled();- const source = layout.snapshot().entries[0].splitId;- const open = vi.fn((request: Parameters<Layout['open']>[0]) =>- layout.open({ ...request, target: 'new-split' })- );- const cancelled = vi.fn();- const applied = vi.fn();- router.navigate(source, '/drive/folder/slow', {- open,- onApplied: cancelled,- });- await settle();- expect(open).not.toHaveBeenCalled();- expect(cancelled).not.toHaveBeenCalled();- router.navigate(source, '/drive/folder/accepted', {- open,- onApplied: applied,- });- await settle();- expect(open).toHaveBeenCalledOnce();- expect(layout.snapshot().entries).toHaveLength(2);- expect(routeParams(router.route('split-2')!).folderId).toBe('accepted');- gate.resolve();- await router.settled();- expect(open).toHaveBeenCalledOnce();- expect(applied).toHaveBeenCalledOnce();- expect(cancelled).not.toHaveBeenCalled();- router.dispose();+ routes: appRoutes,+ history: createSolidRouterHistory({+ location: solid.location,+ navigate: solid.navigate,+ base: '/app',+ beforeLeave: solid.beforeLeave,+ landedPath: solid.landed,+ }),+ paneStore: createMemoryPaneStore(),+ policy: createTestPolicy().policy,+ });+ return {+ router,+ solid,+ dispose: () => {+ router.dispose();+ dispose();+ },+ };});+}- it('updates an existing claim owner without invoking the host opening policy', async () => {- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location: createMemorySplitRouterLocation('/drive/~/drive/folder/owned'),- });- await router.settled();- const [source, owner] = layout.snapshot().entries;- const open = vi.fn(layout.open);- const onApplied = vi.fn();- router.navigate(source.splitId, '/drive/folder/owned', {- open,- onApplied,- search: { drive: { query: ['new target'] } },- });- await router.settled();- expect(open).not.toHaveBeenCalled();- expect(router.search(owner.splitId, 'drive')).toEqual({- query: ['new target'],- });- expect(router.route(source.splitId)?.matches).toHaveLength(1);- expect(onApplied).toHaveBeenCalledOnce();- router.dispose();- });+/** Memory history whose reverts land only when the test says so. */+function slowRevertHistory(url: string) {+ const history = createMemoryHistory(url);+ const landings: (() => void)[] = [];+ const adapter: HistoryAdapter = {+ ...history,+ subscribe: (listener) =>+ history.subscribe((change) =>+ listener({+ ...change,+ revert: () =>+ new Promise<void>((resolve) => {+ landings.push(() => {+ void change.revert();+ resolve();+ });+ }),+ })+ ),+ };- it('reports an already-current destination as applied', async () => {- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location: createMemorySplitRouterLocation('/drive'),- });- await router.settled();- const source = layout.snapshot().entries[0].splitId;- const open = vi.fn(layout.open);- const onApplied = vi.fn();+ const landAll = async () => {+ for (let attempt = 0; attempt < 8; attempt += 1) {+ landings.shift()?.();+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ };- router.navigate(source, '/drive', { open, onApplied });+ return { history, adapter, landAll };+}- expect(open).not.toHaveBeenCalled();- expect(onApplied).toHaveBeenCalledOnce();- expect(layout.snapshot().entries).toHaveLength(1);- router.dispose();- });+/** The level of a pane's first route, below the app route. */+const PANE_ROUTE_LEVEL = 1;+/** The pane route ids below the app route. */+const routeIds = (entry: Entry | undefined) =>+ entry?.location.route.matches+ .map((match) => match.id)+ .filter((id) => id !== 'app');+const location = appLocation;+const withPaneRoutes = (...children: SplitRouteDefinition[]): SplitRoutes => ({+ ...appRoutes,+ definitions: [+ loginRoute,+ { ...appRoute, children: [...appRoute.children, ...children] },+ ],+});+const never = () => new Promise<boolean>(() => {});- it('does not report navigation applied when the host cannot open a pane', async () => {- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location: createMemorySplitRouterLocation('/drive'),- });- await router.settled();- const onApplied = vi.fn();- router.navigate(- layout.snapshot().entries[0].splitId,- '/drive/folder/missing',- {- open: () => ({ status: 'unavailable' }),- onApplied,- }- );- await router.settled();- expect(onApplied).not.toHaveBeenCalled();- expect(layout.snapshot().entries).toHaveLength(1);- router.dispose();- });+let cleanup: (() => void) | undefined;+const track = <T extends { dispose: () => void }>(context: T) => {+ cleanup = context.dispose;+ return context;+};- it('becomes ready when a synchronous layout change supersedes async initialization', async () => {- const layout = createLayout();- let release!: () => void;- let initialSignal: AbortSignal | undefined;- const initial = new Promise<void>((resolve) => {- release = resolve;- });- const router = createSplitRouter({- routes,- layout,- location: createMemorySplitRouterLocation('/drive'),- middleware: [- ({ cause, signal }) => {- if (cause === 'initial') {- initialSignal = signal;- return initial;- }- },- ],- });- expect(router.isReady()).toBe(false);- // Pending cancellation may also notify before the replacement commits.- const readiness: boolean[] = [];- router.subscribe(() => readiness.push(router.isReady()));- layout.open({- location: {- route: { matches: [{ id: 'legacy', params: { id: 'replacement' } }] },- },- target: 'new-split',- replace: false,- });- await settle();- expect(initialSignal?.aborted).toBe(true);- expect(router.isReady()).toBe(true);- expect(readiness.at(-1)).toBe(true);- release();- await router.settled();- expect(router.isReady()).toBe(true);- expect(layout.snapshot().entries[0].location.route.matches[0].id).toBe(- 'legacy'- );- router.dispose();- });- it('observes initial canonicalization echoes without swallowing browser Back', async () => {- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/legacy/one?referral_code=code'- );- const requests: { cause: string; externalSearch?: string }[] = [];- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ to, cause, externalSearch, redirect }) => {- requests.push({ cause, externalSearch });- if (rootRouteMatch(to.location.route)?.id === 'legacy') {- return redirect(- `/drive/folder/${routeParams(to.location.route).id}`- );- }- },- ],- });- await router.settled();- const splitId = layout.snapshot().entries[0].splitId;- expect(location.read().pathname).toBe('/drive/folder/one');- expect(requests).toEqual([- { cause: 'initial', externalSearch: '?referral_code=code' },- { cause: 'initial', externalSearch: '?referral_code=code' },- ]);+afterEach(() => {+ cleanup?.();+ cleanup = undefined;+ vi.useRealTimers();+ vi.restoreAllMocks();+});- router.navigate(splitId, '/drive/folder/two');- await router.settled();- expect(requests.at(-1)).toEqual({- cause: 'navigate',- externalSearch: undefined,- });- expect(location.history()).toHaveLength(2);- expect(location.back()).toBe(true);- await router.settled();- expect(routeParams(router.route(splitId)!)).toEqual({ folderId: 'one' });- expect(location.read().pathname).toBe('/drive/folder/one');- router.dispose();+describe('split router', () => {+ it('starts ready with one pane per URL segment and records pane state in place', () => {+ const { router, history } = track(setup('/mail/t1/~/drive'));+ expect(router.ready()).toBe(true);+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);+ expect(history.entries()).toHaveLength(1);+ expect(history.read().state?.panes.map((pane) => pane.pane)).toEqual([+ 'pane-1',+ 'pane-2',+ ]);});- it('owns one manifest per router and only shares explicitly supplied state', async () => {- const compile = vi.spyOn(path, 'compileRoutePattern');- const layout = createLayout();- const first = createSplitRouter({- layout,- routes,- location: createMemorySplitRouterLocation('/drive/folder/one'),- });- const manifest = first.routes;- expect(compile).toHaveBeenCalledTimes(3);- const splitId = layout.snapshot().entries[0]!.splitId;- first.navigate(splitId, {- route: driveFolderRoute,- params: { folderId: 'two' },- });- await first.settled();- first.updateSearch(splitId, 'drive', { sort: ['name'] });- await first.settled();- expect(first.href(splitId)).toBe('/drive/folder/two?s0.drive.sort=name');- expect(first.routes).toBe(manifest);- expect(compile).toHaveBeenCalledTimes(3);-- const second = createSplitRouter({- layout: createLayout(),- routes,- location: createMemorySplitRouterLocation('/drive'),- });- expect(second.routes).not.toBe(manifest);- expect(second.routes.byId).not.toBe(manifest.byId);- expect(compile).toHaveBeenCalledTimes(6);-- const adopted = createSplitRouter({- layout: createLayout(),- routes: manifest,- location: createMemorySplitRouterLocation('/drive'),- });- expect(adopted.routes).toBe(manifest);- expect(compile).toHaveBeenCalledTimes(6);- first.dispose();- second.dispose();- adopted.dispose();- });- it('rejects unresolved host snapshots before accepting state or committing a URL', () => {- const layout = createLayout();- layout.reconcile([{} as SplitLocation]);- const location = createMemorySplitRouterLocation('/drive');- expect(() => createSplitRouter({ layout, routes, location })).toThrow(- 'nonempty match branch'- );- expect(location.history()).toHaveLength(1);+ it('navigates one pane without touching the others', () => {+ const { router, history, pane } = track(setup('/home/~/drive'));+ const drive = router.entry(pane(1));++ const result = router.navigatePane(pane(0), '/mail/t1');+ expect(result).toEqual({ status: 'committed', pane: pane(0) });+ expect(router.entry(pane(1))).toBe(drive);+ expect(router.arrival(pane(1))).toBe('fresh');+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home/~/drive',+ '/mail/t1/~/drive',+ ]);});- it('does not accept malformed middleware proposals into layout or history', () => {- const layout = createLayout();- const location = createMemorySplitRouterLocation('/drive');- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ to, cause }) => {- if (cause === 'navigate')- to.location.route = { matches: [{ id: 'missing', params: {} }] };- },- ],- });- const splitId = layout.snapshot().entries[0]!.splitId;- expect(() => router.navigate(splitId, 'folder/one')).toThrow(- 'invalid match branch'- );- expect(router.route(splitId)?.matches[0].id).toBe('drive');- expect(router.history(splitId)?.entries).toHaveLength(1);- expect(location.read().pathname).toBe('/drive');- expect(router.location('missing')).toBeUndefined();- router.dispose();+ it('replaces a URL whose panes sit under different top-level routes with the default route', () => {+ const { router, history } = track(setup('/login/~/home'));+ expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([+ ['home'],+ ]);+ expect(history.entries().map((entry) => entry.path)).toEqual(['/home']);});- it('keeps same-route search state during relative navigation', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one?s0.drive.sort=created_at'- );- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;-- router.navigate(splitId, 'folder/two');- await settle();-- expect(location.read()).toMatchObject({- pathname: '/drive/folder/two',- search: '?s0.drive.sort=created_at',- hash: '',- });+ it('turns a pane navigation outside the shared top-level route into a whole-window one, and Back rebuilds the panes', () => {+ const { router, history, pane } = track(setup('/home/~/mail'));+ router.navigatePane(pane(1), '/login');+ expect(+ router.panes().map((id) => router.entry(id)?.location.route.matches)+ ).toEqual([[{ id: 'login', params: {} }]]);+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home/~/mail',+ '/login',+ ]);- location.back();- expect(routeParams(router.location(splitId)?.route).folderId).toBe('one');- expect(router.canGo(splitId, 1)).toBe(true);- location.forward();- expect(routeParams(router.location(splitId)?.route).folderId).toBe('two');- expect(router.canGo(splitId, -1)).toBe(true);+ history.back();+ expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([+ ['home'],+ ['mail'],+ ]);});- it('navigates to a typed route with typed params', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;-- router.navigate(splitId, driveFolderRoute.to({ folderId: 'two' }));- await router.settled();-- expect(location.read().pathname).toBe('/drive/folder/two');+ it('skips entries under another top-level route on pane Back while other panes share the app route', () => {+ const { router, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/login');+ router.navigatePane(pane(0), '/mail');+ router.open('/drive', { newPane: true, source: pane(0) });+ expect(router.panes()).toHaveLength(2);++ expect(router.canGo(pane(0), -1)).toBe(true);+ router.navigatePane(pane(0), -1);+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);+ expect(router.canGo(pane(0), -1)).toBe(false);});- it('activates an existing split that owns the same route claim', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const [first, second] = layout.snapshot().entries;-- router.navigate(second!.splitId, {- route: driveFolderRoute,- params: { folderId: 'one' },- });- await router.settled();-- expect(layout.activatedSplitId()).toBe(first!.splitId);- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/two'- );+ it('pane back replaces the browser entry and records how the pane arrived', () => {+ const { router, history, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/mail');+ router.navigatePane(pane(0), -1);+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);+ expect(router.arrival(pane(0))).toBe('back');+ expect(router.canGo(pane(0), 1)).toBe(true);+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home',+ '/home',+ ]);});- it('allows callers to bypass a route claim explicitly', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const second = layout.snapshot().entries[1]!;-- router.navigate(- second.splitId,- {- route: driveFolderRoute,- params: { folderId: 'one' },- },- { allowDuplicate: true }- );- await router.settled();+ it('browser back brings a pane back through its own history', () => {+ const { router, history, paneStore, pane } = track(setup('/home/~/drive'));+ router.navigatePane(pane(0), '/mail');+ const drive = router.entry(pane(1));+ history.back();+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);+ expect(router.arrival(pane(0))).toBe('back');+ expect(paneStore.read(pane(0))).toMatchObject({ index: 0 });+ expect(paneStore.read(pane(0))?.entries).toHaveLength(2);+ expect(router.entry(pane(1))).toBe(drive);+ });- expect(layout.activatedSplitId()).toBeUndefined();- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/one'- );+ it('a leave guard can refuse browser back, and the URL is put back', () => {+ const { router, history, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/mail');+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, () => false);+ history.back();+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);+ expect(history.index()).toBe(1);+ expect(history.read().path).toBe('/mail');});- it.each([false, true])(- 'checks final claims after middleware (async: %s)',- async (asyncMiddleware) => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path, redirect }) => {- if (cause !== 'navigate' || path !== '/drive/folder/three') return;- const result = redirect('/drive/folder/one');- return asyncMiddleware ? Promise.resolve(result) : result;- },- ],- });- const [first, second] = layout.snapshot().entries;- router.navigate(second!.splitId, '/drive/folder/three');- await router.settled();- expect(layout.activatedSplitId()).toBe(first!.splitId);- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/two'- );- expect(router.history(second!.splitId)?.entries).toHaveLength(1);- router.dispose();- }- );-- it.each([false, true])(- 'rechecks reentrant navigation at the async commit boundary (new owner: %s)',- async (newOwner) => {- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path, redirect }) => {- if (cause === 'navigate' && path === '/drive/folder/three') {- return Promise.resolve(redirect('/drive/folder/shared'));- }- },- ],- });- const [first, second] = layout.snapshot().entries;- let handled = false;- router.subscribe((splitId) => {- if (- handled ||- splitId !== first!.splitId ||- routeParams(router.route(splitId)).folderId !== 'shared'- )- return;- handled = true;- if (newOwner) {- router.navigate(second!.splitId, '/drive/folder/shared', {- allowDuplicate: true,- });- } else {- router.navigate(first!.splitId, '/drive/folder/other');- }- });- router.navigate(first!.splitId, '/drive/folder/three');- await router.settled();- expect(handled).toBe(true);- expect(location.read().pathname).toBe(- newOwner- ? '/drive/folder/one/~/drive/folder/shared'- : '/drive/folder/other/~/drive/folder/two'- );- if (newOwner) {- expect(layout.activatedSplitId()).toBe(second!.splitId);- expect(router.history(first!.splitId)?.entries).toHaveLength(1);- }- router.dispose();- }- );+ it('ignores the report of its own revert landing', async () => {+ vi.useFakeTimers();+ const { router, solid } = track(setupSolid('/app/home'));+ vi.runAllTimers();+ const pane = router.panes()[0]!;+ router.navigatePane(pane, '/mail');+ vi.runAllTimers();+ const mail = router.entry(pane);+ router.registerGuard(pane, PANE_ROUTE_LEVEL, () => false);++ solid.traverse(-1);+ await new Promise<void>((resolve) => queueMicrotask(resolve));+ vi.runAllTimers();+ expect(router.entry(pane)).toBe(mail);+ expect(solid.calls.map(([to]) => to)).toEqual(['/home', '/mail', 1]);+ expect(solid.location.pathname).toBe('/app/mail');+ });- it('does not activate the original claim when middleware redirects away', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'+ it('keeps an async-guarded navigation pending until the guard settles', async () => {+ const { router, pane } = track(setup('/home'));+ let allow: (value: boolean) => void = () => {};+ router.registerGuard(+ pane(0),+ PANE_ROUTE_LEVEL,+ () =>+ new Promise<boolean>((resolve) => {+ allow = resolve;+ }));- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path, redirect }) => {- if (cause === 'navigate' && path === '/drive/folder/one')- return redirect('/drive/folder/three');- },- ],- });- const second = layout.snapshot().entries[1]!;- router.navigate(second.splitId, '/drive/folder/one');- await router.settled();- expect(layout.activatedSplitId()).toBeUndefined();- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/three'- );- router.dispose();+ const result = router.navigatePane(pane(0), '/mail');+ expect(isPromise(result)).toBe(true);+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['mail']);+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);+ allow(true);+ await expect(result).resolves.toMatchObject({ status: 'committed' });+ expect(router.pending(pane(0))).toBeUndefined();+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);});- it.each(['current', 'new-split'] as const)(- 'reserves concurrent claims in request order (%s)',- async (target) => {- const gates = [- Promise.withResolvers<void>(),- Promise.withResolvers<void>(),- ];- let requests = 0;- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two/~/drive/folder/three'- );- const router = createSplitRouter({- layout,- routes,- location,+ it('a newer navigation in the same pane supersedes a pending one', async () => {+ const { router, pane } = track(+ setup('/home', {middleware: [- ({ cause }) => {- if (cause === 'navigate') return gates[requests++]!.promise;+ async ({ path }) => {+ if (path === '/mail')+ await new Promise((done) => setTimeout(done, 10));},],- });- const [, second, third] = layout.snapshot().entries;- router.navigate(second!.splitId, '/drive/folder/shared', { target });- router.navigate(third!.splitId, '/drive/folder/shared', { target });- gates[1]!.resolve();- await settle();- await settle();- expect(location.read().pathname).not.toContain('shared');- gates[0]!.resolve();- await router.settled();- const entries = layout.snapshot().entries;- const owners = entries.filter(- (entry) => routeParams(entry.location.route).folderId === 'shared'- );- expect(owners).toHaveLength(1);- expect(entries).toHaveLength(target === 'new-split' ? 4 : 3);- expect(layout.activatedSplitId()).toBe(owners[0]!.splitId);- if (target === 'current') {- expect(owners[0]!.splitId).toBe(second!.splitId);- expect(router.history(third!.splitId)?.entries).toHaveLength(1);- }- router.dispose();- }- );-- it('releases the old reservation when its owner redirects elsewhere', async () => {- const gate = Promise.withResolvers<void>();- let requests = 0;- const layout = createLayout();- const location = createMemorySplitRouterLocation('/drive');- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- async ({ cause, path, redirect }) => {- if (cause !== 'navigate' || path !== '/drive/folder/shared') return;- if (++requests === 1) {- await gate.promise;- return redirect('/drive/folder/other');- }- },- ],- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- gate.resolve();- await router.settled();- expect(- layout- .snapshot()- .entries.map((entry) => routeParams(entry.location.route).folderId)- ).toEqual([undefined, 'other', 'shared']);- router.dispose();- });-- it('releases superseded claims even when the old middleware ignores abort', async () => {- const gate = Promise.withResolvers<void>();- let requests = 0;- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path }) => {- if (- cause === 'navigate' &&- path === '/drive/folder/shared' &&- ++requests === 1- )- return gate.promise;- },- ],- });- const [first, second] = layout.snapshot().entries;- router.navigate(first!.splitId, '/drive/folder/shared');- router.navigate(second!.splitId, '/drive/folder/shared');- router.navigate(first!.splitId, '/drive/folder/other');- await router.settled();- expect(location.read().pathname).toBe(- '/drive/folder/other/~/drive/folder/shared'- );- gate.resolve();- await settle();- await settle();- expect(location.read().pathname).toBe(- '/drive/folder/other/~/drive/folder/shared'- );- router.dispose();- });-- it('releases a failed transition claim so its next contender can commit', async () => {- vi.spyOn(console, 'error').mockImplementation(() => {});- const gate = Promise.withResolvers<void>();- let requests = 0;- const layout = createLayout();- const location = createMemorySplitRouterLocation('/drive');- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- async ({ cause, to }) => {- if (cause !== 'navigate' || ++requests !== 1) return;- await gate.promise;- to.location.route = { matches: [{ id: 'missing', params: {} }] };- },- ],- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- gate.resolve();- await router.settled();- expect(location.read().pathname).toBe('/drive/~/drive/folder/shared');- expect(console.error).toHaveBeenCalledWith(- 'Split router transition failed',- expect.any(Error)- );- router.dispose();- });-- it('bypasses pending and redirected claims with allowDuplicate', async () => {- const gate = Promise.withResolvers<void>();- let requests = 0;- const layout = createLayout();- const location = createMemorySplitRouterLocation('/drive');- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path, redirect }) => {- if (cause !== 'navigate') return;- if (path === '/drive/folder/alias')- return redirect('/drive/folder/shared');- if (path === '/drive/folder/shared' && ++requests === 1)- return gate.promise;- },- ],- });- const splitId = layout.snapshot().entries[0]!.splitId;- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- router.navigate(splitId, '/drive/folder/alias', {- target: 'new-split',- allowDuplicate: true,- });- await settle();- expect(location.read().pathname).toBe('/drive/~/drive/folder/shared');- gate.resolve();- await router.settled();- expect(location.read().pathname).toBe('/drive/~/drive/folder/shared');- router.navigate(splitId, '/drive/folder/alias', {- target: 'new-split',- allowDuplicate: true,- });- await router.settled();- expect(location.read().pathname).toBe(- '/drive/~/drive/folder/shared/~/drive/folder/shared'+ }));- router.dispose();+ expect(router.ready()).toBe(false);+ await router.settled();+ expect(router.ready()).toBe(true);+ const first = router.navigatePane(pane(0), '/mail');+ const second = router.navigatePane(pane(0), '/drive');+ await expect(first).resolves.toEqual({ status: 'cancelled' });+ await expect(second).resolves.toMatchObject({ status: 'committed' });+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);});- it('checks history claims without moving the cursor when another pane owns the destination', async () => {- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const router = createSplitRouter({ layout, routes, location });- const [first, second] = layout.snapshot().entries;- router.navigate(first!.splitId, '/drive/folder/three');- router.navigate(second!.splitId, '/drive/folder/one');- await router.settled();- router.navigate(first!.splitId, -1);- await router.settled();- expect(layout.activatedSplitId()).toBe(second!.splitId);- expect(router.history(first!.splitId)?.index).toBe(1);- expect(location.read().pathname).toBe(- '/drive/folder/three/~/drive/folder/one'- );- router.navigate(first!.splitId, -1, { allowDuplicate: true });- await router.settled();- expect(router.history(first!.splitId)?.index).toBe(0);- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/one'- );- router.dispose();+ it('a superseded navigation settles even when its guard never does', async () => {+ const { router, pane } = track(setup('/home'));+ const unregister = router.registerGuard(pane(0), PANE_ROUTE_LEVEL, never);+ const first = router.navigatePane(pane(0), '/mail');+ unregister();+ const second = router.navigatePane(pane(0), '/drive');+ await expect(first).resolves.toEqual({ status: 'cancelled' });+ expect(second).toMatchObject({ status: 'committed' });});- it('keeps same-claim navigation search in its restored duplicate pane', async () => {- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/one'+ it('ignores a superseded navigation whose guard answers late', async () => {+ const { router, pane } = track(setup('/home'));+ const answers: ((allowed: boolean) => void)[] = [];+ router.registerGuard(+ pane(0),+ PANE_ROUTE_LEVEL,+ () => new Promise<boolean>((resolve) => answers.push(resolve)));- const router = createSplitRouter({ layout, routes, location });- const [first, second] = layout.snapshot().entries;-- router.navigate(second!.splitId, '/drive/folder/one', {- search: { drive: { sort: ['name'] } },- });- await router.settled();-- expect(router.search(first!.splitId, 'drive')).toBeUndefined();- expect(router.search(second!.splitId, 'drive')).toEqual({ sort: ['name'] });- expect(layout.activatedSplitId()).toBeUndefined();- expect(router.history(second!.splitId)?.entries).toHaveLength(2);- router.dispose();+ const first = router.navigatePane(pane(0), '/mail');+ const second = router.navigatePane(pane(0), '/drive');+ answers[0]!(true);+ answers[1]!(false);+ await expect(first).resolves.toEqual({ status: 'cancelled' });+ await expect(second).resolves.toEqual({ status: 'cancelled' });+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);});- it('checks search redirects but preserves same-claim updates in restored duplicate panes', async () => {- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/one/~/drive/folder/two'+ it('browser back cancels a pane navigation still in flight', async () => {+ const { router, history, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/mail');+ let allow: (allowed: boolean) => void = () => {};+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) =>+ cause === 'external'+ ? true+ : new Promise<boolean>((resolve) => {+ allow = resolve;+ }));- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path, redirect }) => {- if (cause === 'search' && path === '/drive/folder/two')- return redirect('/drive/folder/one');- },- ],- });- const [first, second, third] = layout.snapshot().entries;- router.updateSearch(second!.splitId, 'drive', { sort: ['name'] });- await router.settled();- expect(router.search(second!.splitId, 'drive')).toEqual({ sort: ['name'] });- expect(layout.activatedSplitId()).toBeUndefined();- router.updateSearch(third!.splitId, 'drive', { sort: ['name'] });- await router.settled();- expect(layout.activatedSplitId()).toBe(first!.splitId);- expect(router.search(third!.splitId, 'drive')).toBeUndefined();- expect(router.history(third!.splitId)?.entries).toHaveLength(1);- router.dispose();+ const drive = router.navigatePane(pane(0), '/drive');+ history.back();+ allow(true);+ await expect(drive).resolves.toEqual({ status: 'cancelled' });+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);});- it('cancels an accepted owner’s pending departure when activating its claim', async () => {- const gate = Promise.withResolvers<void>();- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path }) => {- if (cause === 'navigate' && path === '/drive/folder/three')- return gate.promise;- },- ],- });- const [first, second] = layout.snapshot().entries;- router.navigate(first!.splitId, '/drive/folder/three');- expect(routeParams(router.route(first!.splitId)).folderId).toBe('three');- router.navigate(second!.splitId, '/drive/folder/one');- expect(routeParams(router.route(first!.splitId)).folderId).toBe('one');- gate.resolve();- await router.settled();- expect(layout.activatedSplitId()).toBe(first!.splitId);- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/two'+ it('mounts the URL even when middleware cancels the initial load', () => {+ const { router, pane } = track(+ setup('/mail', { middleware: [({ cancel }) => cancel()] }));- router.dispose();+ expect(router.ready()).toBe(true);+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);});- it('restores external duplicates while canceling reservations and permits a fresh acquisition', async () => {- const gate = Promise.withResolvers<void>();- let requests = 0;- const layout = createLayout();- const location = createMemorySplitRouterLocation('/drive');- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause }) => {- if (cause === 'navigate' && ++requests === 1) return gate.promise;- },- ],+ it('settles commands waiting on the initial load when disposed', async () => {+ const { router, dispose } = setup('/home', {+ middleware: [() => new Promise<void>(() => {})],});- const splitId = layout.snapshot().entries[0]!.splitId;- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- location.set('/drive/folder/one/~/drive/folder/one');- await router.settled();- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/one'- );- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- await router.settled();- gate.resolve();- await settle();- await settle();- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/one/~/drive/folder/shared'- );- router.dispose();+ const opened = router.open('/mail', { newPane: true });+ dispose();+ await expect(opened).resolves.toEqual({ status: 'cancelled' });});- it('updates compatible search on an existing claim owner without replacing its route', async () => {- const contextualRoutes: SplitRoutes = {- ...routes,- definitions: [- ...routes.definitions,- defineRoute({- id: 'inbox-folder',- path: 'inbox/:folderId',- params: z.object({ folderId: z.string() }),- search: ['drive', 'inbox'],- claim: ({ folderId }) => ({ namespace: 'folder', id: folderId }),- }),- ],- };- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two?s0.drive.sort=name'- );- const layout = createLayout();- const router = createSplitRouter({- layout,- routes: contextualRoutes,- location,- });- const [owner, caller] = layout.snapshot().entries;-- router.navigate(caller!.splitId, '/inbox/one', {- search: {- drive: (current) => ({ ...current, message_id: ['target'] }),- inbox: { tab: ['unread'] },- },- });- await router.settled();-- expect(layout.activatedSplitId()).toBe(owner!.splitId);- expect(router.route(owner!.splitId)?.matches.at(-1)?.id).toBe(- 'drive-folder'- );- expect(router.search(owner!.splitId, 'drive')).toEqual({- sort: ['name'],- message_id: ['target'],- });- expect(router.search(owner!.splitId, 'inbox')).toBeUndefined();- expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');- expect(router.history(caller!.splitId)?.entries).toHaveLength(1);- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/two'+ it('waits for an async initial load before opening a pane', async () => {+ const { router } = track(+ setup('/home/~/drive', { middleware: [async () => {}] }));- router.dispose();+ expect(router.ready()).toBe(false);+ const opened = router.open('/mail', { newPane: true });+ await expect(opened).resolves.toEqual({+ status: 'committed',+ pane: 'pane-3',+ });+ expect(router.ready()).toBe(true);+ expect(router.panes()).toEqual(['pane-1', 'pane-2', 'pane-3']);});- it('ignores URL search that the claimed destination route does not own', async () => {- const contextualRoutes: SplitRoutes = {- ...routes,- definitions: [- ...routes.definitions,- defineRoute({- id: 'inbox-folder',- path: 'inbox/:folderId',- params: z.object({ folderId: z.string() }),- search: ['inbox'],- claim: ({ folderId }) => ({ namespace: 'folder', id: folderId }),- }),- ],- };- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two?s0.drive.sort=name'- );- const layout = createLayout();- const router = createSplitRouter({- layout,- routes: contextualRoutes,- location,- });- const [owner, caller] = layout.snapshot().entries;-- router.navigate(- caller!.splitId,- '/inbox/one?s0.drive.sort=bad&s0.inbox.tab=unread'- );- await router.settled();-- expect(layout.activatedSplitId()).toBe(owner!.splitId);- expect(router.search(owner!.splitId, 'drive')).toEqual({ sort: ['name'] });- expect(router.search(owner!.splitId, 'inbox')).toBeUndefined();- expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');- expect(router.history(caller!.splitId)?.entries).toHaveLength(1);+ it('drops commands still waiting on a revert once disposed', async () => {+ vi.useFakeTimers();+ const { router, solid } = track(setupSolid('/app/home'));+ vi.runAllTimers();+ const pane = router.panes()[0]!;+ router.navigatePane(pane, '/mail');+ vi.runAllTimers();+ router.registerGuard(pane, PANE_ROUTE_LEVEL, never);+ solid.traverse(-1);++ const rewrite = router.rewriteCurrent(pane, '/drive');+ router.move(pane, 0);router.dispose();+ await expect(rewrite).resolves.toEqual({ status: 'cancelled' });+ vi.runAllTimers();+ expect(solid.calls.map(([to]) => to)).toEqual(['/home', '/mail', 1]);});- it('applies explicit URL search to an existing claim owner', async () => {- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two?s0.drive.sort=name'- );- const router = createSplitRouter({ layout, routes, location });- const [owner, caller] = layout.snapshot().entries;-- router.navigate(- caller!.splitId,- '/drive/folder/one?s0.drive.message_id=target'- );- await router.settled();-- expect(layout.activatedSplitId()).toBe(owner!.splitId);- expect(router.search(owner!.splitId, 'drive')).toEqual({- message_id: ['target'],- });- expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');-- const historyLength = location.history().length;- router.navigate(caller!.splitId, '/drive/folder/one');- await router.settled();- expect(router.search(owner!.splitId, 'drive')).toEqual({- message_id: ['target'],- });- expect(location.history()).toHaveLength(historyLength);- router.dispose();+ it('a pane command cancels a pending browser back and reverts it first', () => {+ const { router, history, pane } = track(setup('/home/~/drive'));+ router.navigatePane(pane(0), '/mail');+ let guardSignal: AbortSignal | undefined;+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ signal }) => {+ guardSignal = signal;+ return never();+ });+ history.back();+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['home']);++ expect(router.navigatePane(pane(1), '/drive/folder/f1')).toMatchObject({+ status: 'committed',+ });+ expect(guardSignal?.aborted).toBe(true);+ expect(router.pending(pane(0))).toBeUndefined();+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home/~/drive',+ '/mail/~/drive',+ '/mail/~/drive/folder/f1',+ ]);+ expect(history.index()).toBe(2);});- it('forwards middleware search targets to an existing owner', async () => {- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'+ it('writes after the reverted back has landed', async () => {+ vi.useFakeTimers();+ const { router, solid } = track(setupSolid('/app/home'));+ vi.runAllTimers();+ const pane = router.panes()[0]!;+ router.navigatePane(pane, '/mail');+ vi.runAllTimers();+ router.registerGuard(pane, PANE_ROUTE_LEVEL, ({ cause }) =>+ cause === 'external' ? never() : true);- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path, redirect }) => {- if (cause === 'navigate' && path === '/legacy/one') {- return redirect('/drive/folder/one?s0.drive.message_id=target');- }- },- ],- });- const [owner, caller] = layout.snapshot().entries;-- router.navigate(caller!.splitId, '/legacy/one');- await router.settled();-- expect(layout.activatedSplitId()).toBe(owner!.splitId);- expect(router.search(owner!.splitId, 'drive')).toEqual({- message_id: ['target'],- });- expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');- router.dispose();+ solid.traverse(-1);+ expect(routeIds(router.pending(pane)?.to)).toEqual(['home']);++ const result = router.navigatePane(pane, '/drive');+ expect(isPromise(result)).toBe(true);+ await expect(result).resolves.toMatchObject({ status: 'committed' });+ vi.runAllTimers();+ expect(solid.calls.map(([to]) => to)).toEqual([+ '/home',+ '/mail',+ 1,+ '/drive',+ ]);+ expect(solid.entries().map((entry) => entry.path)).toEqual([+ '/app/home',+ '/app/mail',+ '/app/drive',+ ]);});- it('publishes pending-state removal when a replacement navigation reuses another owner', async () => {- const gate = Promise.withResolvers<void>();- const layout = createLayout();- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'+ it('reports a pending URL navigation only for the panes it changes', async () => {+ let slow = false;+ const { router, history, pane } = track(+ setup('/home/~/drive', {+ middleware: [+ ({ path }) =>+ slow && path === '/home'+ ? new Promise<void>((done) => setTimeout(done, 5))+ : undefined,+ ],+ }));- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause, path }) => {- if (cause === 'navigate' && path === '/drive/folder/three')- return gate.promise;- },- ],- });- const [first, second] = layout.snapshot().entries;- const seen: unknown[] = [];- router.subscribe((splitId) => {- if (splitId === second!.splitId)- seen.push(routeParams(router.route(splitId)).folderId);- });- router.navigate(second!.splitId, '/drive/folder/three');- router.navigate(second!.splitId, '/drive/folder/one');- expect(seen).toEqual(['three', 'two']);- expect(layout.activatedSplitId()).toBe(first!.splitId);- gate.resolve();+ router.navigatePane(pane(0), '/mail');+ slow = true;+ history.back();+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['home']);+ expect(router.pending(pane(1))).toBeUndefined();await router.settled();- router.dispose();+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);});- it('cancels pending reservations on disposal and ignores subsequent navigation', async () => {- const gate = Promise.withResolvers<void>();- let requests = 0;- const layout = createLayout();- const location = createMemorySplitRouterLocation('/drive');- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause }) => {- if (cause === 'navigate' && ++requests === 1) return gate.promise;- },- ],- });- const splitId = layout.snapshot().entries[0]!.splitId;- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- router.navigate(splitId, '/drive/folder/shared', { target: 'new-split' });- router.dispose();- gate.resolve();- await router.settled();- router.navigate(splitId, '/drive/folder/other');- router.updateSearch(splitId, 'drive', { sort: ['name'] });- expect(location.read().pathname).toBe('/drive');- expect(location.read().search).toBe('');+ it('opening something another pane shows activates that pane instead', () => {+ const { router, activated, pane } = track(setup('/drive/md/d1/~/home'));+ const result = router.navigatePane(pane(1), '/md/d1');+ expect(result).toEqual({ status: 'activated', owner: pane(0) });+ expect(activated).toEqual([pane(0)]);+ expect(routeIds(router.entry(pane(1)))).toEqual(['home']);+ expect(+ router.navigatePane(pane(1), '/md/d1', { allowDuplicate: true })+ ).toMatchObject({ status: 'committed' });});- it('traverses route history without changing another split', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/other'- );- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const [first, second] = layout.snapshot().entries;+ it('tells the policy who shows a new pane’s destination and whether a duplicate is allowed', () => {+ const testPolicy = createTestPolicy();+ const { router, pane } = track(setup('/md/d1/~/home', {}, testPolicy));+ const target = { newPane: true as const, source: pane(1) };- router.navigate(first!.splitId, '/drive/folder/two');- router.navigate(first!.splitId, '/drive/folder/three');- await router.settled();+ router.open('/md/d1', target, { allowDuplicate: true });- expect(router.canGo(first!.splitId, -2)).toBe(true);- router.navigate(first!.splitId, -1);- await router.settled();-- expect(routeParams(router.route(first!.splitId)).folderId).toBe('two');- expect(routeParams(router.route(second!.splitId)).folderId).toBe('other');- expect(router.canGo(first!.splitId, 1)).toBe(true);- expect(router.history(first!.splitId)?.index).toBe(1);- expect(router.history(first!.splitId)?.entries).toHaveLength(3);-- router.navigate(first!.splitId, 1);- await router.settled();- expect(routeParams(router.route(first!.splitId)).folderId).toBe('three');+ expect(testPolicy.placements).toMatchObject([+ { holder: pane(0), allowDuplicate: true },+ ]);});- it('ignores navigation and search writes that resolve to the current destination', async () => {- const middleware = vi.fn<SplitRouterMiddleware>(() => undefined);- const location = createMemorySplitRouterLocation(- '/drive/folder/one?s0.drive.sort=name'- );- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [middleware],- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;- const listener = vi.fn();- router.subscribe(listener);- middleware.mockClear();- const committed = location.history().length;-- router.navigate(splitId, '/drive/folder/one');- router.navigate(splitId, {- route: driveFolderRoute,- params: { folderId: 'one' },- });- router.navigate(splitId, '/drive/folder/one', { replace: true });- router.updateSearch(splitId, 'drive', { sort: ['name'] });- await router.settled();+ it('opens a new pane beside the one showing the destination when the policy places it there', () => {+ const { router, activated, pane } = track(setup('/md/d1/~/home'));- expect(middleware).not.toHaveBeenCalled();- expect(listener).not.toHaveBeenCalled();- expect(location.history()).toHaveLength(committed);- expect(router.canGo(splitId, -1)).toBe(false);+ const result = router.open('/md/d1', { newPane: true, source: pane(1) });- // A real change still transitions.- router.updateSearch(splitId, 'drive', { sort: ['size'] });- await router.settled();- expect(middleware).toHaveBeenCalledOnce();- expect(location.read().search).toBe('?s0.drive.sort=size');+ expect(result).toMatchObject({ status: 'committed' });+ expect(router.panes()).toHaveLength(3);+ expect(activated).toEqual([]);});- it('pushes a repeated route as a new history entry', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('brings up a pane that started showing a new pane’s destination after it was placed', async () => {+ let release: () => void = () => {};+ let held = false;+ const holdFirstVisit = ({ path }: { path: string }) => {+ if (path !== '/md/d1' || held) return;- router.navigate(splitId, '/drive/folder/two');- await router.settled();- router.navigate(splitId, '/drive/folder/one');- await router.settled();- router.navigate(splitId, -1);- await router.settled();-- expect(routeParams(router.route(splitId)).folderId).toBe('two');- });+ held = true;- it('restores distinct state for duplicate URLs across browser Back and Forward', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ return new Promise<void>((resolve) => {+ release = resolve;+ });+ };+ const { router, pane } = track(+ setup('/home/~/drive', { middleware: [holdFirstVisit] })+ );- router.navigate(splitId, '/drive/folder/one', {- state: { breadcrumb: 'first' },- });- await router.settled();- router.navigate(splitId, '/drive/folder/one', {- state: { breadcrumb: 'second' },+ const opened = router.open('/md/d1', { newPane: true, source: pane(1) });+ router.navigatePane(pane(0), '/md/d1');+ release();++ await expect(opened).resolves.toEqual({+ status: 'activated',+ owner: pane(0),});- await router.settled();+ expect(router.panes()).toHaveLength(2);+ });- expect(layout.updateCount()).toBe(0);- const entries = router.history(splitId)!.entries;- expect(entries).toHaveLength(3);- expect(entries[1]?.key).not.toBe(entries[2]?.key);- expect(router.entry(splitId)?.state).toEqual({ breadcrumb: 'second' });+ it('skips entries another pane shows on Back and Forward, unless duplicates are allowed', () => {+ const { router, pane } = track(setup('/home/~/home'));+ router.navigatePane(pane(0), '/md/d1');+ router.navigatePane(pane(0), '/drive');+ router.navigatePane(pane(1), '/md/d1');- expect(location.back()).toBe(true);- await router.settled();- expect(router.entry(splitId)?.state).toEqual({ breadcrumb: 'first' });+ router.navigatePane(pane(0), -1);+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);+ expect(router.canGo(pane(0), 1)).toBe(true);- expect(location.forward()).toBe(true);- await router.settled();- expect(router.entry(splitId)?.state).toEqual({ breadcrumb: 'second' });+ router.navigatePane(pane(0), 1, { allowDuplicate: true });+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);+ });- router.navigate(splitId, '/drive/folder/one', {- replace: true,- state: { breadcrumb: 'replacement' },- });- await router.settled();- expect(location.history()).toHaveLength(3);- expect(router.entry(splitId)?.state).toEqual({- breadcrumb: 'replacement',- });- expect(location.back()).toBe(true);- await router.settled();- expect(location.forward()).toBe(true);- await router.settled();- expect(router.entry(splitId)?.state).toEqual({- breadcrumb: 'replacement',- });+ it('keeps duplicates loaded from a URL', () => {+ const { router } = track(setup('/md/d1/~/md/d1'));+ expect(router.panes()).toHaveLength(2);});- it('preserves router metadata when duplicate-URL panes swap', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/one'+ it('changing search in a duplicate keeps it in place', () => {+ const { router, activated, pane } = track(+ setup('/drive/md/d1/~/drive/md/d1'));- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const [first, second] = layout.snapshot().entries;-- router.navigate(first!.splitId, '/drive/folder/one', {- state: { breadcrumb: 'first' },- });- router.navigate(second!.splitId, '/drive/folder/one', {- state: { breadcrumb: 'second' },- });- await router.settled();- const browserStateBeforeSwap = location.read().state;-- layout.swapEntries();- await router.settled();+ expect(+ router.updateSearch(pane(1), 'drive', { sort: ['name'] })+ ).toMatchObject({ status: 'committed', pane: pane(1) });+ expect(activated).toEqual([]);+ });- expect(layout.snapshot().entries.map((entry) => entry.splitId)).toEqual([- second!.splitId,- first!.splitId,- ]);- expect(router.entry(first!.splitId)?.state).toEqual({- breadcrumb: 'first',- });- expect(router.entry(second!.splitId)?.state).toEqual({- breadcrumb: 'second',- });- expect(location.read().state).not.toEqual(browserStateBeforeSwap);+ it('browser back brings back a duplicate', () => {+ const { router, history, activated, pane } = track(setup('/home/~/md/d1'));+ router.navigatePane(pane(0), '/md/d1', { allowDuplicate: true });+ router.navigatePane(pane(0), '/drive');+ history.back();+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);+ expect(activated).toEqual([]);});- it('observes a duplicate-pane swap during a queued layout echo', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const first = layout.snapshot().entries[0]!;+ it('opens and closes panes where the policy places them', () => {+ const { router, history } = track(setup('/home/~/drive'));+ expect(+ router.open('/mail', {+ newPane: true,+ source: 'pane-1' as PaneId,+ })+ ).toEqual({ status: 'committed', pane: 'pane-3' });+ expect(router.panes()).toEqual(['pane-1', 'pane-3', 'pane-2']);+ expect(history.read().path).toBe('/home/~/mail/~/drive');++ expect(router.open('/home', { pane: 'pane-3' as PaneId })).toEqual({+ status: 'committed',+ pane: 'pane-3',+ });+ expect(router.close('pane-3' as PaneId)).toBe(true);+ expect(router.close('pane-2' as PaneId)).toBe(true);+ expect(router.panes()).toEqual(['pane-1']);+ expect(history.read().path).toBe('/home');++ expect(router.close('pane-1' as PaneId)).toBe(false);+ router.navigatePane('pane-1' as PaneId, '/mail');+ expect(router.close('pane-1' as PaneId)).toBe(true);+ expect(router.panes()).toEqual(['pane-1']);+ expect(history.read().path).toBe('/home');+ });- router.navigate(first.splitId, '/drive/folder/one', {- state: { breadcrumb: 'first' },- });- await router.settled();- router.navigate(first.splitId, '/drive/folder/one', {- target: 'new-split',- allowDuplicate: true,- state: { breadcrumb: 'second' },- });- const browserStateBeforeSwap = location.read().state;+ it('opens several panes at once without one cancelling another', async () => {+ const { router } = track(+ setup('/home', {+ middleware: [+ ({ path }) => (path === '/home' ? undefined : Promise.resolve()),+ ],+ })+ );+ const source = 'pane-1' as PaneId;+ const first = router.open('/mail', { newPane: true, source });+ const second = router.open('/drive', { newPane: true, source });+ await expect(first).resolves.toEqual({+ status: 'committed',+ pane: 'pane-2',+ });+ await expect(second).resolves.toEqual({+ status: 'committed',+ pane: 'pane-3',+ });+ expect(router.panes()).toEqual(['pane-1', 'pane-2', 'pane-3']);+ });- layout.swapEntries();- await router.settled();+ it('lets the policy open in an existing pane when enough are open', () => {+ const testPolicy = createTestPolicy({ maxPanes: 2 });+ const { router } = track(setup('/home/~/drive', {}, testPolicy));+ const intent = { replaceWhenFull: true };+ expect(+ router.open('/mail', {+ newPane: true,+ source: 'pane-2' as PaneId,+ intent,+ })+ ).toEqual({ status: 'committed', pane: 'pane-2' });+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);+ expect(routeIds(router.entry('pane-2' as PaneId))).toEqual(['mail']);+ expect(testPolicy.placements).toEqual([+ {+ destination: location('mail'),+ source: 'pane-2',+ intent,+ allowDuplicate: false,+ opening: 0,+ panes: ['pane-1', 'pane-2'],+ },+ ]);+ });- expect(location.read().state).not.toEqual(browserStateBeforeSwap);- const second = layout- .snapshot()- .entries.find((entry) => entry.splitId !== first.splitId)!;- expect(layout.snapshot().entries[0]?.splitId).toBe(second.splitId);- expect(router.entry(first.splitId)?.state).toEqual({- breadcrumb: 'first',- });- expect(router.entry(second.splitId)?.state).toEqual({- breadcrumb: 'second',- });+ it('keeps a pane the policy pins, without asking its guards', () => {+ const { router } = track(+ setup(+ '/home/~/mail',+ {},+ createTestPolicy({ pinned: ['pane-1' as PaneId] })+ )+ );+ const guard = vi.fn(() => true);+ router.registerGuard('pane-1' as PaneId, PANE_ROUTE_LEVEL, guard);+ expect(router.close('pane-1' as PaneId)).toBe(false);+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);+ expect(guard).not.toHaveBeenCalled();});- it('snapshots cloneable state and drops state that cannot be cloned', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;- const state = { breadcrumbs: ['one'] };+ it('navigates from the base, keeping the pane that already shows the destination', () => {+ const { router, history } = track(setup('/home/~/mail/~/drive'));+ const [home, mail, drive] = router.panes();+ const mailEntry = router.entry(mail!);+ let allowDrive = false;+ router.registerGuard(drive!, PANE_LEVEL, () => allowDrive);++ expect(router.navigate('/mail')).toMatchObject({ status: 'cancelled' });+ expect(router.panes()).toEqual([home, mail, drive]);++ allowDrive = true;+ expect(router.navigate('/mail')).toMatchObject({ status: 'committed' });+ expect(router.panes()).toEqual([mail]);+ expect(router.entry(mail!)).toBe(mailEntry);+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home/~/mail/~/drive',+ '/mail',+ ]);+ });- router.navigate(splitId, '/drive/folder/two', { state });- state.breadcrumbs.push('mutated');- await router.settled();+ it('keeps panes that already show their entry when a base navigation reorders them', () => {+ const { router, history } = track(setup('/home/~/mail'));+ const [home] = router.panes();- expect(router.entry(splitId)?.state).toEqual({ breadcrumbs: ['one'] });+ router.navigate('/drive/~/home');+ expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([+ ['drive'],+ ['home'],+ ]);+ expect(router.panes()[1]).toBe(home);+ expect(history.read().path).toBe('/drive/~/home');- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- router.navigate(splitId, '/drive/folder/three', {- state: { callback: () => undefined },- });- await router.settled();+ router.navigate({ location: location('mail') });+ expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([+ ['mail'],+ ]);+ });- expect(routeParams(router.route(splitId)).folderId).toBe('three');- expect(router.entry(splitId)?.state).toBeUndefined();- expect(warn).toHaveBeenCalledOnce();+ it('closing the last pane can go back to an earlier entry', () => {+ const closeLast: SplitCloseAction = {+ type: 'back-to',+ to: (entry) => routeIds(entry)?.[0] === 'mail',+ otherwise: { type: 'navigate', destination: homeLocation, replace: true },+ };+ const { router, pane } = track(+ setup('/mail', {}, createTestPolicy({ closeLast }))+ );+ router.navigatePane(pane(0), '/drive');+ expect(router.close(pane(0))).toBe(true);+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);+ expect(router.canGo(pane(0), 1)).toBe(true);});- it('passes parsed output to state updaters without reparsing it', async () => {- let parses = 0;- const stateRoute = defineRoute({- id: 'state',- path: 'state',- state: z.object({ value: z.string() }).transform(({ value }) => ({- value,- parseNumber: ++parses,- })),- });- const location = createMemorySplitRouterLocation('/state');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes: { definitions: [stateRoute] },- location,- });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('closing the last pane can replace it without a back entry', () => {+ const closeLast: SplitCloseAction = {+ type: 'back-to',+ to: (entry) => routeIds(entry)?.[0] === 'mail',+ otherwise: { type: 'navigate', destination: homeLocation, replace: true },+ };+ const { router, history, pane } = track(+ setup('/drive', {}, createTestPolicy({ closeLast }))+ );+ expect(router.close(pane(0))).toBe(true);+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);+ expect(router.canGo(pane(0), -1)).toBe(false);+ expect(history.entries()).toHaveLength(1);+ });- router.navigate(splitId, '/state', { state: { value: 'first' } });- await router.settled();- expect(router.entry(splitId)?.state).toEqual({- value: 'first',- parseNumber: 1,- });+ it('keeps the hash of the URL it follows through a redirect', () => {+ const { history } = track(+ setup('/home#focus', {+ middleware: [+ ({ path, redirect }) =>+ path === '/home' ? redirect('/mail') : undefined,+ ],+ })+ );+ expect(history.read()).toMatchObject({ path: '/mail', hash: '#focus' });+ });- router.navigate(splitId, '/state', {- state: (current) => ({- value: `${(current as { value: string }).value}-second`,- }),- });- await router.settled();- expect(router.entry(splitId)?.state).toEqual({- value: 'first-second',- parseNumber: 2,+ it('writes an outside navigation with its own hash and global search', async () => {+ const { history } = track(setup('/home?referral_code=old#top'));+ await history.navigate('/mail/t2?referral_code=new#frag');+ expect(history.read()).toMatchObject({+ path: '/mail/t2',+ search: '?referral_code=new',+ hash: '#frag',});});- it('rejects local state that the destination route does not accept', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('a leave guard can keep a pane open', () => {+ const { router } = track(setup('/home/~/mail'));+ router.registerGuard('pane-2' as PaneId, PANE_ROUTE_LEVEL, () => false);+ expect(router.close('pane-2' as PaneId)).toBe(false);+ expect(router.panes()).toHaveLength(2);+ });- expect(() =>- router.navigate(splitId, '/drive/folder/two', { state: 'invalid' })- ).toThrow('rejected navigation state');- expect(() =>- router.navigate(splitId, '/legacy/one', {- state: { unsupported: true },- })- ).toThrow('rejected navigation state');- expect(routeParams(router.route(splitId)).folderId).toBe('one');+ it('shows the catch-all route in an unmatched pane and loads the others', () => {+ const { router, pane } = track(setup('/mail/t1/~/no/such'));+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail', 'mail-thread']);+ expect(routeIds(router.entry(pane(1)))).toEqual(['not-found']);});- it('validates navigation state against a middleware redirect destination', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ path, redirect }) =>- path === '/drive/folder/two' ? redirect('/legacy/two') : undefined,- ],- });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('takes over outside navigations into the panes', async () => {+ const { router, history, pane } = track(setup('/home'));+ await expect(history.navigate('/mail/t2')).resolves.toBe(false);+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail', 'mail-thread']);+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home',+ '/mail/t2',+ ]);+ });- router.navigate(splitId, '/drive/folder/two', {- state: { breadcrumb: 'two' },- });- await router.settled();+ it('commits in the same tick without data preloads and waits for them within a budget', async () => {+ const preload = vi.fn(() => new Promise(() => {}));+ const routes = withPaneRoutes(+ defineRoute({ id: 'slow', path: 'slow', preload })+ );+ const { router, pane } = track(+ setup('/home', { routes, preloadBudgetMs: 5 })+ );+ expect(isPromise(router.navigatePane(pane(0), '/mail'))).toBe(false);- expect(rootRouteMatch(router.route(splitId))?.id).toBe('legacy');- expect(router.entry(splitId)?.state).toBeUndefined();+ const result = router.navigatePane(pane(0), '/slow');+ expect(isPromise(result)).toBe(true);+ expect(preload).toHaveBeenCalledWith(+ expect.objectContaining({ intent: 'navigate', params: {} })+ );+ await expect(result).resolves.toMatchObject({ status: 'committed' });+ expect(routeIds(router.entry(pane(0)))).toEqual(['slow']);});- it('drops restored state that the destination route does not accept', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;-- location.set(- {- pathname: '/drive/folder/two',- search: '',- hash: '',- state: {- __macroSplitRouter: {- entries: [{ key: 'restored-entry', state: 'invalid' }],- },+ it('logs a preload that throws and still navigates', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ const routes = withPaneRoutes(+ defineRoute({+ id: 'broken',+ path: 'broken',+ preload: () => {+ throw new Error('boom');},- },- { replace: true }+ }));- await router.settled();+ const { router, pane } = track(setup('/home', { routes }));+ expect(router.navigatePane(pane(0), '/broken')).toEqual({+ status: 'committed',+ pane: pane(0),+ });+ expect(error).toHaveBeenCalledWith(+ 'Split route "broken" preload failed',+ expect.any(Error)+ );+ });++ it('writes search as a new entry or in place', () => {+ const { router, history, pane } = track(setup('/drive'));+ const first = router.entry(pane(0))!.id;+ router.updateSearch(+ pane(0),+ 'drive',+ { sort: ['name'] },+ { history: 'replace' }+ );+ expect(router.entry(pane(0))!.id).toBe(first);+ expect(history.read().search).toBe('?s0.drive.sort=name');+ expect(history.entries()).toHaveLength(1);- expect(routeParams(router.route(splitId)).folderId).toBe('two');- expect(router.entry(splitId)?.state).toBeUndefined();+ router.updateSearch(pane(0), 'drive', { sort: ['date'] });+ expect(router.entry(pane(0))!.id).not.toBe(first);+ expect(history.entries()).toHaveLength(2);});- it('treats an external URL without state as a fresh entry', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('jumps back to the nearest matching entry', () => {+ const { router, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/mail');+ router.navigatePane(pane(0), '/drive');+ expect(+ router.goBackTo(pane(0), (entry) => routeIds(entry)?.[0] === 'home')+ ).toBe(true);+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);+ expect(router.goBackTo(pane(0), () => true)).toBe(false);+ });- router.navigate(splitId, '/drive/folder/one', {- replace: true,- state: { breadcrumb: 'stored' },- });- await router.settled();- const storedKey = router.entry(splitId)?.key;+ it('removing entries cancels a pending traversal in that pane', async () => {+ const { router, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/mail');+ router.navigatePane(pane(0), '/drive');+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, never);+ const back = router.navigatePane(pane(0), -1);+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['mail']);++ const isMail = (entry: Entry) => routeIds(entry)?.[0] === 'mail';+ expect(router.removeEntries(pane(0), isMail)).toBe(true);+ await expect(back).resolves.toEqual({ status: 'cancelled' });+ expect(router.pending(pane(0))).toBeUndefined();+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);+ expect(router.canGo(pane(0), -1)).toBe(true);+ expect(router.removeEntries(pane(0), isMail)).toBe(false);+ });- location.set('/drive/folder/one', { replace: true });- await router.settled();+ it('rewrites the current entry in place', () => {+ const { router, history, pane } = track(setup('/md/draft'));+ const id = router.entry(pane(0))!.id;+ router.rewriteCurrent(pane(0), '/md/real');+ expect(router.entry(pane(0))!.id).toBe(id);+ expect(history.read().path).toBe('/md/real');+ expect(history.entries()).toHaveLength(1);+ });- expect(router.entry(splitId)?.key).not.toBe(storedKey);- expect(router.entry(splitId)?.state).toBeUndefined();+ it('builds a single-pane href', () => {+ const { router, pane } = track(setup('/home/~/mail/t1'));+ expect(router.href(pane(1))).toBe('/mail/t1');});+});++describe('split router while other work is in flight', () => {+ it('keeps the entry an outside navigation came from when the new view redirects in place', async () => {+ const { router, history, pane } = track(setup('/home'));+ const stopRedirecting = createRoot((dispose) => {+ createEffect(() => {+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';+ if (!showsDrive) return;- it('preserves entry state through search pushes and replacements', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ untrack(() => router.navigatePane(pane(0), '/mail', { replace: true }));+ });- router.navigate(splitId, '/drive/folder/two', {- state: (current) => ({ previous: current, breadcrumb: 'two' }),+ return dispose;});- await router.settled();- const routeKey = router.entry(splitId)?.key;- const state = router.entry(splitId)?.state;- router.updateSearch(splitId, 'drive', { sort: ['name'] });+ await history.navigate('/drive');await router.settled();- const pushedKey = router.entry(splitId)?.key;- expect(pushedKey).not.toBe(routeKey);- expect(router.entry(splitId)?.state).toBe(state);+ stopRedirecting();- router.updateSearch(- splitId,- 'drive',- { sort: ['created_at'] },- { history: 'replace' }+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home',+ '/mail',+ ]);+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);+ });++ it('lets an outside navigation replace an async initial load, then runs the open waiting on it', async () => {+ const { router, history, pane } = track(+ setup('/home', { middleware: [async () => {}] }));+ const opened = router.open('/mail', { newPane: true });+ void history.navigate('/drive');++ await expect(opened).resolves.toMatchObject({ status: 'committed' });await router.settled();- expect(router.entry(splitId)?.key).toBe(pushedKey);- expect(router.entry(splitId)?.state).toBe(state);+ expect(router.ready()).toBe(true);+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);+ expect(routeIds(router.entry(pane(1)))).toEqual(['mail']);});- it('restores search state during history traversal', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('holds an open that follows an outside navigation during the initial load', async () => {+ const { router, history } = track(+ setup('/home', { middleware: [async () => {}] })+ );+ void history.navigate('/drive');+ const opened = router.open('/mail', { newPane: true });- router.updateSearch(splitId, 'drive', { sort: ['name'] });+ await expect(opened).resolves.toMatchObject({ status: 'committed' });await router.settled();- expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });+ expect(router.ready()).toBe(true);+ expect(router.panes().map((id) => routeIds(router.entry(id))?.[0])).toEqual(+ ['drive', 'mail']+ );+ });- router.navigate(splitId, -1);- await router.settled();- expect(router.search(splitId, 'drive')).toBeUndefined();+ it('asks guards registered above the first route before closing the pane', () => {+ const { router, pane } = track(setup('/home/~/mail'));+ router.registerGuard(pane(1), PANE_LEVEL, () => false);- router.navigate(splitId, 1);- await router.settled();- expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });+ expect(router.close(pane(1))).toBe(false);+ expect(router.panes()).toHaveLength(2);});- it('replaces history and truncates forward entries', async () => {- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('puts the URL back past every Back that a refused Back replaced', async () => {+ const { router, history, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/mail');+ router.navigatePane(pane(0), '/drive');+ const answers: ((allowed: boolean) => void)[] = [];+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {+ if (cause !== 'external') return true;- router.navigate(splitId, '/drive/folder/two', { replace: true });- await router.settled();- expect(router.canGo(splitId, -1)).toBe(false);+ return new Promise<boolean>((resolve) => answers.push(resolve));+ });- router.navigate(splitId, '/drive/folder/three');- await router.settled();- router.navigate(splitId, -1);- await router.settled();- router.navigate(splitId, '/drive/folder/four');+ history.back();+ history.back();+ answers[1]!(false);await router.settled();- expect(router.canGo(splitId, 1)).toBe(false);- expect(routeParams(router.route(splitId)).folderId).toBe('four');+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);+ expect(history.index()).toBe(2);+ expect(history.read().path).toBe('/drive');});- it('runs history traversal through middleware', async () => {- const causes: string[] = [];- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause }) => {- causes.push(cause);- },- ],+ it('cancels the pending departure of a pane it activates for a claim', async () => {+ const { router, activated, pane } = track(setup('/md/d1/~/home'));+ let leave: (allowed: boolean) => void = () => {};+ router.registerGuard(+ pane(0),+ PANE_ROUTE_LEVEL,+ () =>+ new Promise<boolean>((resolve) => {+ leave = resolve;+ })+ );++ const departure = router.navigatePane(pane(0), '/drive');+ expect(router.navigatePane(pane(1), '/md/d1')).toEqual({+ status: 'activated',+ owner: pane(0),});- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;+ leave(true);- router.navigate(splitId, '/drive/folder/two');- await router.settled();- router.navigate(splitId, -1);+ await expect(departure).resolves.toEqual({ status: 'cancelled' });+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);+ expect(activated).toEqual([pane(0)]);+ });++ it('carries the search a navigation asked for to the pane already showing its resource', async () => {+ const { router, activated, pane } = track(setup('/drive/md/d1/~/home'));++ expect(+ router.navigatePane(pane(1), '/drive/md/d1', {+ search: { drive: { sort: ['name'] } },+ })+ ).toEqual({ status: 'activated', owner: pane(0) });await router.settled();- expect(causes).toContain('history');- expect(routeParams(router.route(splitId)).folderId).toBe('one');+ expect(activated).toEqual([pane(0)]);+ expect(router.entry(pane(0))?.location.search).toEqual({+ drive: { sort: ['name'] },+ });+ expect(routeIds(router.entry(pane(1)))).toEqual(['home']);});- it('waits for async middleware before applying history traversal', async () => {- let release!: () => void;- let blockHistory = false;- const preload = new Promise<void>((resolve) => {- release = resolve;- });- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ cause }) =>- cause === 'history' && blockHistory ? preload : undefined,- ],- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;+ it('keeps an owner’s pending navigation that stays on the claimed resource', async () => {+ let release: () => void = () => {};+ const { router, pane } = track(+ setup('/drive/md/d1/~/home', {+ middleware: [+ ({ cause }) => {+ if (cause !== 'search') return;- router.navigate(splitId, '/drive/folder/two');+ return new Promise<void>((resolve) => {+ release = resolve;+ });+ },+ ],+ })+ );await router.settled();- blockHistory = true;- router.navigate(splitId, -1);-- expect(location.read().pathname).toBe('/drive/folder/two');- expect(routeParams(router.route(splitId)).folderId).toBe('one');+ const sorting = router.updateSearch(pane(0), 'drive', { sort: ['date'] });+ router.navigatePane(pane(1), '/drive/md/d1');release();- await router.settled();- expect(location.read().pathname).toBe('/drive/folder/one');- expect(routeParams(router.route(splitId)).folderId).toBe('one');+ await expect(sorting).resolves.toMatchObject({ status: 'committed' });+ expect(router.entry(pane(0))?.location.search).toEqual({+ drive: { sort: ['date'] },+ });});- it('commits route and search updates together', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one?s0.drive.scope=all&s0.drive.sort=created_at'+ it('counts opens still in flight against the policy’s limit', async () => {+ const { router } = track(+ setup(+ '/home',+ {+ middleware: [+ ({ path }) => (path === '/home' ? undefined : Promise.resolve()),+ ],+ },+ createTestPolicy({ maxPanes: 2 })+ ));- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ const source = 'pane-1' as PaneId;- router.navigate(splitId, 'folder/two', {- search: {- drive(current = {}) {- const next = { ...current };+ const first = router.open('/mail', { newPane: true, source });+ const second = router.open('/drive', { newPane: true, source });+ await Promise.all([first, second]);- delete next.scope;+ expect(router.panes()).toHaveLength(2);+ });- return next;- },- },+ it('turns down a location it cannot write, leaving the pane and later writes intact', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ const { router, history, pane } = track(setup('/drive'));+ const tooLong = 'x'.repeat(17_000);++ expect(router.updateSearch(pane(0), 'drive', { sort: [tooLong] })).toEqual({+ status: 'cancelled',+ });+ expect(+ router.rewriteCurrent(pane(0), { route: { id: 'missing' } })+ ).toEqual({+ status: 'cancelled',});- await settle();+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);+ expect(router.entry(pane(0))?.location.search).toBeUndefined();- expect(location.history()).toHaveLength(2);- expect(location.read()).toMatchObject({- pathname: '/drive/folder/two',- search: '?s0.drive.sort=created_at',- hash: '',+ expect(router.navigatePane(pane(0), '/mail')).toMatchObject({+ status: 'committed',});+ expect(history.read().path).toBe('/mail');+ expect(error).toHaveBeenCalled();+ expect(error).not.toHaveBeenCalledWith(+ 'Split router could not commit a navigation',+ expect.anything()+ );});- it('applies search writes without losing the latest value', async () => {- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('drops a search value from the URL that is too long to write back', () => {+ const tooLong = 'x'.repeat(17_000);+ const { router, pane } = track(setup(`/drive?s0.drive.sort=${tooLong}`));- router.updateSearch(- splitId,- 'drive',- { sort: ['name'] },- { history: 'replace' }+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);+ expect(router.entry(pane(0))?.location.search).toBeUndefined();+ });++ it('reports a refused jump back as false, and a back-to close then keeps the pane', async () => {+ const closeLast: SplitCloseAction = {+ type: 'back-to',+ to: (entry) => routeIds(entry)?.[0] === 'home',+ otherwise: {+ type: 'navigate',+ destination: location('mail'),+ replace: true,+ },+ };+ const { router, pane } = track(+ setup('/home', {}, createTestPolicy({ closeLast })));- router.updateSearch(- splitId,- 'drive',- { sort: ['created_at'] },- { history: 'push' }+ router.navigatePane(pane(0), '/drive');+ router.registerGuard(+ pane(0),+ PANE_ROUTE_LEVEL,+ ({ to }) => routeIds(to)?.[0] !== 'home');- await settle();- expect(location.history()).toHaveLength(2);- expect(location.read().search).toBe('?s0.drive.sort=created_at');+ const isHome = (entry: Entry) => routeIds(entry)?.[0] === 'home';+ expect(await router.goBackTo(pane(0), isHome)).toBe(false);+ expect(await router.close(pane(0))).toBe(false);+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);});- it('drops unowned route search and rejects writes to it', async () => {- const location = createMemorySplitRouterLocation(- '/drive?s0.drive.sort=name&s0.other.value=ignored'+ it('turns down a close action that leads to no route', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ const closeLast: SplitCloseAction = {+ type: 'navigate',+ destination: location('missing'),+ };+ const { router, history, pane } = track(+ setup('/drive', {}, createTestPolicy({ closeLast })));- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;- await settle();-- expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });- expect(router.search(splitId, 'other')).toBeUndefined();- expect(location.read().search).toBe('?s0.drive.sort=name');- expect(() =>- router.updateSearch(splitId, 'other', { value: ['nope'] })- ).toThrow('Split route does not own search namespace "other"');- expect(() =>- router.navigate(splitId, 'folder/one', {- search: { other: { value: ['nope'] } },- })- ).toThrow('Split route does not own search namespace "other"');- expect(() => router.updateSearch('missing', 'bad.name', {})).toThrow(- 'Invalid split search namespace "bad.name"'++ expect(await router.close(pane(0))).toBe(false);+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);+ expect(history.read().path).toBe('/drive');+ expect(error).toHaveBeenCalledWith(+ 'Split router close action leads to no route',+ closeLast.destination);- expect(location.read().pathname).toBe('/drive');- expect(location.read().search).toBe('?s0.drive.sort=name');});- it('merges rapid search writes while middleware is pending', async () => {- const middleware: SplitRouterMiddleware[] = [- async ({ cause }) => {- if (cause === 'search') await Promise.resolve();- },- ];- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware,- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;-- router.updateSearch(splitId, 'drive', { sort: ['name'] });- router.updateSearch(splitId, 'drive', (current = {}) => ({- ...current,- type: ['pdf'],- }));- await router.settled();+ it('writes a replace another pane makes while one commits after that commit’s push', async () => {+ const { router, history, pane } = track(setup('/home/~/home'));+ const stopRedirecting = createRoot((dispose) => {+ createEffect(() => {+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';+ if (!showsDrive) return;- expect(router.search(splitId, 'drive')).toEqual({- sort: ['name'],- type: ['pdf'],- });- expect(location.read().search).toBe(- '?s0.drive.sort=name&s0.drive.type=pdf'- );- });+ untrack(() => router.navigatePane(pane(1), '/mail', { replace: true }));+ });- it('publishes one state change for synchronous search middleware', async () => {- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [() => undefined],+ return dispose;});- const splitId = layout.snapshot().entries[0]!.splitId;- const notifications: Array<string | undefined> = [];- router.subscribe((notifiedSplitId) => notifications.push(notifiedSplitId));- router.updateSearch(splitId, 'drive', { type: ['pdf'] });+ router.navigatePane(pane(0), '/drive');await router.settled();+ stopRedirecting();- expect(notifications).toEqual([splitId]);- expect(location.read().search).toBe('?s0.drive.type=pdf');+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home/~/home',+ '/drive/~/mail',+ ]);});- it('scopes direct layout reconciliation to the changed split', async () => {- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [- ({ to, redirect }) =>- rootRouteMatch(to.location.route)?.id === 'legacy'- ? redirect('/drive/folder/redirected')- : undefined,- ],- });- const notifications: Array<string | undefined> = [];- router.subscribe((splitId) => notifications.push(splitId));+ it('keeps a Back whose view redirects in place as it mounts', async () => {+ const { router, history, pane } = track(setup('/drive'));+ router.navigatePane(pane(0), '/mail');+ let armed = false;+ const stopRedirecting = createRoot((dispose) => {+ createEffect(() => {+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';+ const redirects = armed && showsDrive;+ if (!redirects) return;++ untrack(() => router.navigatePane(pane(0), '/home', { replace: true }));+ });- layout.open({- location: {- route: {- matches: [{ id: 'legacy', params: { id: 'document' } }],- },- },- target: 'new-split',+ return dispose;});+ armed = true;++ history.back();await router.settled();+ stopRedirecting();- const changedSplitId = layout.snapshot().entries[1]!.splitId;- expect(notifications).toEqual([changedSplitId]);+ expect(history.index()).toBe(0);+ expect(history.entries().map((entry) => entry.path)).toEqual([+ '/home',+ '/mail',+ ]);+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);});- it('evaluates functional navigation search updates once', async () => {- let calls = 0;- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [() => undefined],- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;+ it('keeps navigating after the history adapter fails a write', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ const history = createMemoryHistory('/home');+ let failNext = false;+ const flaky: HistoryAdapter = {+ ...history,+ write(location, writeOptions) {+ if (failNext) {+ failNext = false;+ throw new Error('write failed');+ }- router.navigate(splitId, '/drive/folder/two', {- search: {- drive(current = {}) {- calls++;- return { ...current, count: [String(calls)] };- },+ history.write(location, writeOptions);},- });- await router.settled();-- expect(calls).toBe(1);- expect(location.read().search).toBe('?s0.drive.count=1');- });+ };+ const { router, pane } = track(setup('/home', { history: flaky }));- it('waits for async middleware before programmatic navigation', async () => {- let release!: () => void;- const preload = new Promise<void>((resolve) => {- release = resolve;+ failNext = true;+ expect(router.navigatePane(pane(0), '/mail')).toEqual({+ status: 'cancelled',});- const middleware: SplitRouterMiddleware[] = [- ({ cause }) => (cause === 'navigate' ? preload : undefined),- ];- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware,+ expect(router.navigatePane(pane(0), '/drive')).toMatchObject({+ status: 'committed',});- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;-- router.navigate(splitId, '/drive/folder/two');+ expect(history.read().path).toBe('/drive');+ expect(error).toHaveBeenCalledWith(+ 'Split router could not commit a navigation',+ expect.any(Error)+ );+ });- expect(location.read().pathname).toBe('/drive/folder/one');- expect(- routeParams(layout.snapshot().entries[0]?.location?.route).folderId- ).toBe('one');- expect(routeParams(router.location(splitId)?.route).folderId).toBe('two');+ it('settles a URL navigation that arrives while an earlier one is being put back', async () => {+ const { history, adapter, landAll } = slowRevertHistory('/home');+ const { router, pane } = track(setup('/home', { history: adapter }));+ router.navigatePane(pane(0), '/mail');+ router.navigatePane(pane(0), '/drive');+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) =>+ cause === 'external' ? never() : true+ );- release();- await router.settled();+ history.back();+ const navigated = router.navigatePane(pane(0), '/drive/folder/f1');+ history.back();+ await landAll();- expect(location.read().pathname).toBe('/drive/folder/two');- expect(routeParams(router.location(splitId)?.route).folderId).toBe('two');+ await expect(navigated).resolves.toMatchObject({ status: 'committed' });+ await expect(router.settled()).resolves.toBeUndefined();+ expect(history.read().path).toBe('/drive/folder/f1');+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive', 'drive-folder']);});- it('does not cancel middleware running for another split', async () => {- let releaseFirst!: () => void;- const firstPreload = new Promise<void>((resolve) => {- releaseFirst = resolve;- });- let firstSignal: AbortSignal | undefined;- const middleware: SplitRouterMiddleware[] = [- ({ cause, path, signal }) => {- if (cause === 'navigate' && path.endsWith('/one')) {- firstSignal = signal;- return firstPreload;- }- },- ];- const location = createMemorySplitRouterLocation('/drive/~/drive');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware,+ it('puts back a Back that arrives while others are put back before them', async () => {+ const { history, adapter, landAll } = slowRevertHistory('/home');+ const { router, pane } = track(setup('/home', { history: adapter }));+ router.navigatePane(pane(0), '/mail');+ router.navigatePane(pane(0), '/drive');+ router.navigatePane(pane(0), '/md/d1');+ let refuse: () => void = () => {};+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {+ if (cause !== 'external') return true;++ return new Promise<boolean>((resolve) => {+ refuse = () => resolve(false);+ });});- await router.settled();- const [first, second] = layout.snapshot().entries;-- router.navigate(first!.splitId, '/drive/folder/one');- router.navigate(second!.splitId, '/drive/folder/two');- await settle();- await settle();- expect(firstSignal?.aborted).toBe(false);- expect(location.read().pathname).toBe('/drive/~/drive/folder/two');-- releaseFirst();+ history.back();+ history.back();+ refuse();+ await new Promise((resolve) => setTimeout(resolve, 0));+ history.back();+ await landAll();await router.settled();- expect(location.read().pathname).toBe(- '/drive/folder/one/~/drive/folder/two'- );+ expect(history.index()).toBe(3);+ expect(history.read().path).toBe('/md/d1');+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);});- it('cancels stale middleware when a newer navigation starts', async () => {- let firstSignal: AbortSignal | undefined;- const middleware: SplitRouterMiddleware[] = [- ({ cause, path, signal }) => {- if (cause !== 'navigate' || !path.endsWith('/one')) return;+ it('opens a pane that already shows the destination by activating it', () => {+ const { router, activated, pane } = track(setup('/mail/t1/~/home'));- firstSignal = signal;- return new Promise<void>((_resolve, reject) => {- signal.addEventListener('abort', () => reject(signal.reason));- });- },- ];- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware,+ expect(router.open('/mail/t1', { pane: pane(0) })).toEqual({+ status: 'activated',+ owner: pane(0),});- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;-- router.navigate(splitId, '/drive/folder/one');- router.navigate(splitId, '/drive/folder/two');- await router.settled();-- expect(firstSignal?.aborted).toBe(true);- expect(location.read().pathname).toBe('/drive/folder/two');+ expect(activated).toEqual([pane(0)]);});- it('delays Back/Forward reconciliation until middleware settles', async () => {- let release!: () => void;- let blockExternal = false;- const preload = new Promise<void>((resolve) => {- release = resolve;- });- const middleware: SplitRouterMiddleware[] = [- ({ cause }) =>- cause === 'external' && blockExternal ? preload : undefined,- ];- const location = createMemorySplitRouterLocation('/drive/folder/one');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware,- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;+ it('checks again before running a waiting action that a new Back overtook', async () => {+ const { router, history, pane, paneStore } = track(setup('/home'));+ router.navigatePane(pane(0), '/mail');+ let allow: (allowed: boolean) => void = () => {};+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {+ if (cause !== 'external') return true;- router.navigate(splitId, '/drive/folder/two');- await router.settled();- blockExternal = true;- location.back();+ return new Promise<boolean>((resolve) => {+ allow = resolve;+ });+ });+ let redirected = false;+ const stopRedirecting = createRoot((dispose) => {+ createEffect(() => {+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';+ const redirects = showsDrive && !redirected;+ if (!redirects) return;++ redirected = true;+ untrack(() =>+ router.navigatePane(pane(0), '/drive/folder/f1', { replace: true })+ );+ });- expect(location.read().pathname).toBe('/drive/folder/one');- expect(- routeParams(layout.snapshot().entries[0]?.location?.route).folderId- ).toBe('two');+ return dispose;+ });- release();+ router.navigatePane(pane(0), '/drive');+ history.back();+ await Promise.resolve();+ await Promise.resolve();+ allow(true);await router.settled();+ stopRedirecting();- expect(- routeParams(layout.snapshot().entries[0]?.location?.route).folderId- ).toBe('one');+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive', 'drive-folder']);+ expect(history.index()).toBe(2);+ expect(history.read().path).toBe('/drive/folder/f1');+ expect(paneStore.read(pane(0))?.index).toBe(2);});- it('accepts Back to a URL whose outbound write was coalesced', async () => {- let current: SplitRouterExternalLocationValue = {- pathname: '/drive',- search: '',- hash: '',- };- const pending: SplitRouterExternalLocationValue[] = [];- const listeners = new Set<- (location: SplitRouterExternalLocationValue) => void- >();- const location: SplitRouterExternalLocation = {- read: () => current,- commit: (next) => pending.push(next),- subscribe(listener) {- listeners.add(listener);- return () => listeners.delete(listener);+ it('writes the URL again after the history adapter failed to write it', () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const history = createMemoryHistory('/home');+ let failNext = false;+ const flaky: HistoryAdapter = {+ ...history,+ write(location, writeOptions) {+ if (failNext) {+ failNext = false;+ throw new Error('write failed');+ }++ history.write(location, writeOptions);},};- const flush = (index = 0) => {- current = pending.splice(index, 1)[0]!;- for (const listener of listeners) listener(current);- };- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;- // Initialization adds the router's opaque entry metadata with replacement.- flush();-- router.updateSearch(splitId, 'drive', { sort: ['name'] });- router.updateSearch(splitId, 'drive', { sort: ['created_at'] });-- const earlier = pending[0]!;- flush(1);- pending.length = 0; // The adapter discards the superseded write.- expect(router.search(splitId, 'drive')).toEqual({ sort: ['created_at'] });-- // A later browser Back reaches the same URL as that superseded write.- current = earlier;- for (const listener of listeners) listener(current);- await settle();-- expect(pending).toHaveLength(0);- expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });- expect(location.read().search).toBe('?s0.drive.sort=name');- });-- it('skips layout reconciliation for an identical external location', () => {- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- createSplitRouter({- layout,- routes,- location,- middleware: [() => undefined],- });+ const { router, pane } = track(setup('/home', { history: flaky }));- expect(layout.reconcileCount()).toBe(1);+ failNext = true;+ router.navigatePane(pane(0), '/mail');+ router.rewriteCurrent(pane(0), '/mail');- location.set('/drive', { replace: true });-- expect(layout.reconcileCount()).toBe(1);+ expect(history.read().path).toBe('/mail');});- it('restores duplicate routes by visible position', () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one/~/drive/folder/two'- );- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const [first, second] = layout.snapshot().entries;+ it('ignores a host location outside the router’s base', () => {+ vi.useFakeTimers();+ const { router, solid } = track(setupSolid('/app/mail'));+ vi.runAllTimers();- location.set('/drive/folder/three/~/drive/folder/four', { replace: true });+ solid.show('/elsewhere', undefined);+ vi.runAllTimers();- expect(routeParams(router.location(first!.splitId)?.route).folderId).toBe(- 'three'- );- expect(routeParams(router.location(second!.splitId)?.route).folderId).toBe(- 'four'- );+ expect(routeIds(router.entry(router.panes()[0]!))).toEqual(['mail']);});- it('opens an explicitly requested new split', async () => {- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({ layout, routes, location });- const splitId = layout.snapshot().entries[0]!.splitId;+ it('drops a URL write still queued when the router is disposed', () => {+ vi.useFakeTimers();+ const { router, solid, dispose } = setupSolid('/app/home');+ vi.runAllTimers();- router.navigate(splitId, 'folder/two', {- target: 'new-split',- });- await settle();+ router.navigatePane(router.panes()[0]!, '/mail');+ dispose();+ vi.runAllTimers();- expect(layout.snapshot().entries).toHaveLength(2);- expect(location.read().pathname).toBe('/drive/~/drive/folder/two');+ expect(solid.calls.map(([to]) => to)).toEqual(['/home']);});- it('waits for async middleware before opening a new split', async () => {- let release!: () => void;- const preload = new Promise<void>((resolve) => {- release = resolve;- });- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const router = createSplitRouter({- layout,- routes,- location,- middleware: [({ cause }) => (cause === 'navigate' ? preload : undefined)],- });- await router.settled();- const splitId = layout.snapshot().entries[0]!.splitId;+ it('asks leave guards when Back or Forward leaves the router’s routes', () => {+ vi.useFakeTimers();+ const { router, solid } = track(setupSolid('/app/home', ['/settings']));+ vi.runAllTimers();+ const guard = vi.fn(() => false);+ router.registerGuard(router.panes()[0]!, PANE_ROUTE_LEVEL, guard);++ expect(solid.pop(1).defaultPrevented).toBe(true);+ expect(guard).toHaveBeenCalledTimes(1);+ expect(solid.landed()).toBe('/app/home');- const onApplied = vi.fn();- router.navigate(splitId, 'folder/two', { target: 'new-split', onApplied });+ guard.mockReturnValue(true);+ expect(solid.pop(1).defaultPrevented).toBe(false);+ expect(solid.landed()).toBe('/settings');+ });- expect(layout.snapshot().entries).toHaveLength(1);- expect(onApplied).not.toHaveBeenCalled();+ it('drops a queued write when a navigation leaves the router’s routes', () => {+ vi.useFakeTimers();+ const { router, solid } = track(setupSolid('/app/home'));+ vi.runAllTimers();- release();- await router.settled();+ router.navigatePane(router.panes()[0]!, '/mail');+ expect(solid.leave('/settings').defaultPrevented).toBe(false);+ vi.runAllTimers();- expect(layout.snapshot().entries).toHaveLength(2);- expect(location.read().pathname).toBe('/drive/~/drive/folder/two');- expect(onApplied).toHaveBeenCalledOnce();+ expect(solid.calls.map(([to]) => to)).toEqual(['/home']);});- it('retains declared global search and drops unowned keys', async () => {- const location = createMemorySplitRouterLocation(- '/drive?referral_code=abc&temporary=value'- );- const layout = createLayout();- createSplitRouter({ layout, routes, location });+ it('moves the cursor on Back to an entry that looks like the current one', () => {+ const { router, history, paneStore, pane } = track(setup('/home'));+ router.navigatePane(pane(0), '/home', { props: { note: 1 } });+ expect(paneStore.read(pane(0))?.entries).toHaveLength(2);- await settle();+ history.back();+ expect(paneStore.read(pane(0))?.index).toBe(0);+ expect(router.canGo(pane(0), -1)).toBe(false);- expect(location.read().search).toBe('?referral_code=abc');+ history.forward();+ expect(paneStore.read(pane(0))?.index).toBe(1);+ expect(router.arrival(pane(0))).toBe('forward');});});diff --git a/apps/web/src/lib/split-router/tests/routes-manifest.test.ts b/apps/web/src/lib/split-router/tests/routes-manifest.test.tsdeleted file mode 100644index 81389a9f34..0000000000--- a/apps/web/src/lib/split-router/tests/routes-manifest.test.ts+++ /dev/null@@ -1,437 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest';-import { z } from 'zod';-import * as path from '../path';-import {- assertRouteState,- assertSearchNamespacesAllowed,- createRoutesManifest,- decodeRoute,- defineRoute,- encodeRoute,- filterRouteSearch,- findRouteBranch,- getExternalSearchKeys,- getRouteClaim,- getRouteSearchNamespaces,- resolveRouteBranch,- routeParams,-} from '../routes';-import type { SplitRouterEntry, SplitRouteState, SplitRoutes } from '../types';-import {- decodeSplitRouterLocation,- serializeSplitRouterLocation,-} from '../url';--afterEach(() => vi.restoreAllMocks());--describe('split routes manifests', () => {- it('compiles once per explicit manifest, retaining original definition identity', () => {- const compile = vi.spyOn(path, 'compileRoutePattern');- const detail = defineRoute({ id: 'detail', path: 'document/:id' });- const workspace = defineRoute({- id: 'workspace',- path: 'workspace',- aliases: ['w'],- children: [detail],- search: ['workspace'],- });- const readDefinitions = vi.fn(() => [workspace]);- const routes: SplitRoutes = {- get definitions() {- return readDefinitions();- },- basePath: '/app',- };- const manifest = createRoutesManifest(routes);- expect(compile).toHaveBeenCalledTimes(2);- expect(readDefinitions).toHaveBeenCalledOnce();- expect(manifest.basePath).toEqual(['app']);-- for (const id of ['one', 'two', 'three']) {- const entry = decodeSplitRouterLocation({- routes: manifest,- location: `/app/w/document/${id}`,- }).entries[0]!;- expect(- serializeSplitRouterLocation({- routes: manifest,- entries: [entry],- previous: '/',- })- ).toBe(`/app/workspace/document/${id}`);- const branch = resolveRouteBranch(manifest, entry.location.route);- expect(branch).toBe(findRouteBranch(manifest, 'detail'));- expect(branch[0]?.definition).toBe(workspace);- expect(branch[1]?.definition).toBe(detail);- expect(getRouteSearchNamespaces(manifest, entry.location.route)).toEqual(- new Set(['workspace'])- );- expect(getRouteClaim(manifest, entry.location.route)).toBeUndefined();- expect(getExternalSearchKeys(manifest, [entry])).toEqual(new Set());- }- expect(readDefinitions).toHaveBeenCalledOnce();- expect(compile).toHaveBeenCalledTimes(2);-- // Identical definitions do not imply shared runtime state across owners.- const independent = createRoutesManifest(routes);- expect(independent).not.toBe(manifest);- expect(independent.byId).not.toBe(manifest.byId);- expect(findRouteBranch(independent, 'detail')).not.toBe(- findRouteBranch(manifest, 'detail')- );- expect(compile).toHaveBeenCalledTimes(4);- });-- it('rejects unresolved runtime states without parsing schema outputs again', () => {- const parse = vi.fn((value: string) => new Date(value));- const manifest = createRoutesManifest({- definitions: [- defineRoute({- id: 'day',- path: 'day/:day',- params: z.object({ day: z.string().transform(parse) }),- serializeParams: ({ day }) => ({- day: day.toISOString().slice(0, 10),- }),- }),- ],- });- const entry = decodeRoute(manifest, ['day', '2026-01-02'])!;- expect(() =>- assertRouteState(manifest, entry.location.route)- ).not.toThrow();- expect(parse).toHaveBeenCalledTimes(1);- for (const state of [- undefined,- null,- {},- { matches: [] },- { matches: 'day' },- { matches: [{ id: 'missing', params: {} }] },- { matches: [{ id: 'day', params: [] }] },- { matches: [{ id: 'day' }] },- ]) {- expect(() => assertRouteState(manifest, state)).toThrow(- 'Split route state'- );- }- });-- it('validates the whole manifest before matching, including unused branches', () => {- expect(() =>- createRoutesManifest({- definitions: [- { id: 'home', path: 'home' },- {- id: 'other',- path: 'other',- children: [{ id: 'home', path: 'child' }],- },- ],- })- ).toThrow('Duplicate split route id "home"');- expect(() =>- createRoutesManifest({- definitions: [{ id: 'bad', path: 'files/*rest/edit' }],- })- ).toThrow('must be the final segment');- });-- it('keeps schema validation per match and falls through in declaration order', () => {- const parseId = vi.fn((id: number) => id);- const manifest = createRoutesManifest({- definitions: [- defineRoute({- id: 'number',- path: ':id',- params: z.object({ id: z.coerce.number().transform(parseId) }),- }),- { id: 'text', path: '*rest' },- ],- });- expect(parseId).not.toHaveBeenCalled();- expect(routeParams(decodeRoute(manifest, ['42'])?.location.route)).toEqual({- id: 42,- });- expect(routeParams(decodeRoute(manifest, ['43'])?.location.route)).toEqual({- id: 43,- });- expect(parseId).toHaveBeenCalledTimes(2);- expect(- decodeRoute(manifest, ['text'])?.location.route?.matches[0]?.id- ).toBe('text');- });-- it('serializes transformed params per entry through the node codec', () => {- const serializeParams = vi.fn(({ day }: { day: Date }) => ({- day: day.toISOString().slice(0, 10),- }));- const manifest = createRoutesManifest({- definitions: [- defineRoute({- id: 'calendar',- path: 'calendar/:day',- params: z.object({ day: z.coerce.date() }),- serializeParams,- }),- ],- });- expect(serializeParams).not.toHaveBeenCalled();- for (const day of ['2026-01-02', '2026-02-03']) {- const entry = decodeRoute(manifest, ['calendar', day])!;- expect(encodeRoute(manifest, entry)).toEqual(['calendar', day]);- expect(serializeParams).toHaveBeenLastCalledWith({- day: new Date(`${day}T00:00:00.000Z`),- });- }- expect(serializeParams).toHaveBeenCalledTimes(2);- });-- it('keeps primitive params usable without a custom serializer', () => {- const manifest = createRoutesManifest({- definitions: [- defineRoute({- id: 'page',- path: 'page/:id',- params: z.object({ id: z.coerce.number() }),- }),- ],- });- const node = manifest.byId.get('page')!;- const params = node.params.parse({ id: '42' })!;- expect(params).toEqual({ id: 42 });- expect(node.pattern.format(node.params.serialize(params))).toEqual([- 'page',- '42',- ]);- expect(node.params.parse({ id: 'invalid' })).toBeUndefined();- });-- it('retains optional-parameter backtracking into children and canonical branch formatting', () => {- const manifest = createRoutesManifest({- definitions: [- {- id: 'workspace',- path: 'workspace/:workspaceId?',- aliases: ['w/:workspaceId?'],- children: [- { id: 'settings', path: 'settings/:tab', aliases: ['s/:tab'] },- ],- },- ],- });- const entry = decodeRoute(manifest, ['w', 's', 'account'])!;- expect(entry.location.route?.matches).toEqual([- { id: 'workspace', params: {} },- { id: 'settings', params: { tab: 'account' } },- ]);- expect(encodeRoute(manifest, entry)).toEqual([- 'workspace',- 'settings',- 'account',- ]);- });-- it('tries later aliases after schema rejection but stops after the first valid match', () => {- const validate = vi.fn((params: { value: string }) => params);- const manifest = createRoutesManifest({- definitions: [- defineRoute({- id: 'item',- path: 'item/:invalid',- aliases: ['item/:value', ':prefix/:value'],- params: z- .union([- z.object({ invalid: z.string() }).refine(() => false),- z.object({ value: z.string() }),- z.object({ prefix: z.string(), value: z.string() }),- ])- .transform((params) =>- 'value' in params- ? validate({ value: params.value })- : { value: params.invalid }- ),- }),- ],- });- expect(- routeParams(decodeRoute(manifest, ['item', 'one'])?.location.route)- ).toEqual({ value: 'one' });- expect(validate).toHaveBeenCalledTimes(1);- });-- it('evaluates deepest-first claims with current merged params and ancestor fallback', () => {- const parentClaim = vi.fn(({ workspaceId }: { workspaceId: string }) => ({- namespace: 'workspace',- id: workspaceId,- }));- const childClaim = vi.fn(- ({ workspaceId, id }: { workspaceId: string; id: string }) =>- id === 'none'- ? undefined- : { namespace: 'document', id: `${workspaceId}/${id}` }- );- const manifest = createRoutesManifest({- definitions: [- {- id: 'workspace',- path: 'workspace/:workspaceId',- claim: parentClaim,- children: [{ id: 'detail', path: 'document/:id', claim: childClaim }],- },- ],- });- expect(parentClaim).not.toHaveBeenCalled();- expect(childClaim).not.toHaveBeenCalled();- const first = decodeRoute(manifest, [- 'workspace',- 'one',- 'document',- 'first',- ])!;- expect(getRouteClaim(manifest, first.location.route)).toEqual({- namespace: 'document',- id: 'one/first',- });- expect(parentClaim).not.toHaveBeenCalled();- const second = decodeRoute(manifest, [- 'workspace',- 'two',- 'document',- 'none',- ])!;- expect(getRouteClaim(manifest, second.location.route)).toEqual({- namespace: 'workspace',- id: 'two',- });- expect(childClaim).toHaveBeenLastCalledWith({- workspaceId: 'two',- id: 'none',- });- expect(parentClaim).toHaveBeenLastCalledWith({- workspaceId: 'two',- id: 'none',- });- });-- it('reuses inherited search ownership but evaluates dynamic external search per entry', () => {- const externalSearch = vi.fn((entry: SplitRouterEntry) => [- String(routeParams(entry.location.route).id),- ]);- const manifest = createRoutesManifest({- globalSearch: ['global'],- definitions: [- {- id: 'workspace',- path: 'workspace',- search: ['workspace'],- externalSearch: ['action'],- children: [- {- id: 'detail',- path: 'document/:id',- search: ['detail'],- externalSearch,- },- { id: 'legacy', path: 'legacy', search: '*' },- ],- },- ],- });- expect(externalSearch).not.toHaveBeenCalled();- const first = decodeRoute(manifest, ['workspace', 'document', 'one'])!;- const second = decodeRoute(manifest, ['workspace', 'document', 'two'])!;- expect(getRouteSearchNamespaces(manifest, first.location.route)).toBe(- getRouteSearchNamespaces(manifest, second.location.route)- );- expect(getRouteSearchNamespaces(manifest, first.location.route)).toEqual(- new Set(['workspace', 'detail'])- );- expect([...getExternalSearchKeys(manifest, [first])]).toEqual([- 'global',- 'action',- 'one',- ]);- expect([...getExternalSearchKeys(manifest, [second])]).toEqual([- 'global',- 'action',- 'two',- ]);- expect(externalSearch).toHaveBeenCalledTimes(2);- const search = {- workspace: { sort: ['name'] },- detail: { mode: ['edit'] },- extra: { x: ['1'] },- };- expect(filterRouteSearch(manifest, first.location.route, search)).toEqual({- workspace: search.workspace,- detail: search.detail,- });- const legacy = decodeRoute(manifest, ['workspace', 'legacy'])!;- expect(filterRouteSearch(manifest, legacy.location.route, search)).toBe(- search- );- });-- it('validates namespace writes against inherited ownership or the legacy wildcard', () => {- const manifest = createRoutesManifest({- definitions: [- {- id: 'parent',- path: 'parent',- search: ['parent'],- children: [{ id: 'child', path: 'child', search: ['child'] }],- },- { id: 'legacy', path: 'legacy', search: '*' },- ],- });- const child = decodeRoute(manifest, ['parent', 'child'])!.location.route;- expect(() =>- assertSearchNamespacesAllowed(manifest, child, ['parent', 'child'])- ).not.toThrow();- expect(() =>- assertSearchNamespacesAllowed(manifest, child, ['other'])- ).toThrow('Split route does not own search namespace "other"');- const legacy = decodeRoute(manifest, ['legacy'])!.location.route;- expect(() =>- assertSearchNamespacesAllowed(manifest, legacy, ['other'])- ).not.toThrow();- for (const route of [child, legacy]) {- expect(() =>- assertSearchNamespacesAllowed(manifest, route, ['constructor'])- ).toThrow('Invalid split search namespace "constructor"');- }- });-- it('rejects known IDs in the wrong branch rather than keeping a partial match', () => {- const root = {- id: 'root',- path: 'root',- children: [{ id: 'child', path: 'child' }],- };- const other = {- id: 'other',- path: 'other',- children: [{ id: 'other-child', path: 'child' }],- };- const manifest = createRoutesManifest({ definitions: [root, other] });- const invalid: SplitRouteState = {- matches: [- { id: 'root', params: {} },- { id: 'other-child', params: {} },- ],- };- expect(() => resolveRouteBranch(manifest, invalid)).toThrow(- 'invalid match branch'- );- expect(() => assertRouteState(manifest, invalid)).toThrow(- 'invalid match branch'- );- expect(() =>- encodeRoute(manifest, { location: { route: invalid } })- ).toThrow('invalid match branch');- expect(() =>- resolveRouteBranch(manifest, { matches: [{ id: 'child', params: {} }] })- ).toThrow('invalid match branch');- });-});diff --git a/apps/web/src/lib/split-router/tests/routes.test.ts b/apps/web/src/lib/split-router/tests/routes.test.tsindex 6b3264f782..82d3f9a99c 100644--- a/apps/web/src/lib/split-router/tests/routes.test.ts+++ b/apps/web/src/lib/split-router/tests/routes.test.ts@@ -1,673 +1,365 @@-import { describe, expect, expectTypeOf, it } from 'vitest';-import { z } from 'zod';+import { describe, expect, it } from 'vitest';import {+ decodePanes,+ encodePanes,+ formatPanePath,+ splitPanePaths,+} from '../routes/codec';+import { defineRoute } from '../routes/define';+import {+ canonicalRoute,createRoutesManifest,- decodeRoute,- defineRoute,- defineRoutes,- encodeRoute,- findRouteBranch,- getExternalSearchKeys,- getRouteClaim,- getRouteEntryState,- parseRouteEntryState,- routeParams,- validateRouteParams,- validateSplitRoutes,-} from '../routes';-import type {- InferSplitRouteBranchParams,- InferSplitRouteNavigationParams,- InferSplitRouteParams,- InferSplitRouteState,- InferSplitRouteStateInput,- SplitNavigate,- SplitRoutes,-} from '../types';--const documentClaim = ({ documentId }: { documentId: string }) => ({- namespace: 'document',- id: documentId,+ decodePane,+ formatPane,+} from '../routes/manifest';+import { compileRoutePattern } from '../routes/path';+import { claimOf, externalSearchKeys, ownsNamespace } from '../routes/queries';+import { resolveTarget } from '../routes/targets';+import type { PaneId, SplitLocation, SplitRouteState } from '../routes/types';+import {+ appRoutes,+ documentRoute,+ driveRoute,+ folderRoute,+ mailRoute,+ notFoundRoute,+} from './fixtures';++const routes = createRoutesManifest(appRoutes);+const matchIds = (route: SplitRouteState | undefined) =>+ route?.matches.map((match) => match.id);+/** The pane route ids below the app route. */+const ids = (route: SplitRouteState | undefined) =>+ matchIds(route)?.filter((id) => id !== 'app');+const decodeUrl = (path: string, search = '') =>+ decodePanes(routes, { path, search, hash: '' }).panes.map((pane) =>+ matchIds(pane.entry.location.route)+ );+const at = (path: string): SplitLocation => ({+ route: decodePane(routes, path.split('/').filter(Boolean))!,});-const driveRoute = defineRoute({- id: 'drive',- path: 'drive',- aliases: ['files'],- params: z.object({}),- search: ['drive'],- state: z.object({ trail: z.array(z.string()) }),- externalSearch: ['action'],- children: [- {+describe('route matching', () => {+ it('prefers specific routes regardless of declaration order', () => {+ expect(ids(decodePane(routes, ['mail', 't1']))).toEqual([+ 'mail',+ 'mail-thread',+ ]);+ expect(ids(decodePane(routes, ['md', 'doc']))).toEqual(['block']);+ expect(ids(decodePane(routes, ['drive', 'md', 'doc']))).toEqual([+ 'drive',+ 'drive-document',+ ]);+ expect(ids(decodePane(routes, ['drive', 'folder']))).toEqual([+ 'drive',+ 'drive-folder',+ ]);+ expect(decodePane(routes, ['drive', 'folder', 'f1'])?.matches[2]).toEqual({id: 'drive-folder',- path: 'folder/:folderId',- params: z.object({ folderId: z.string() }),- children: [- {- id: 'drive-folder-detail',- path: 'pdf/:documentId',- params: z.object({ documentId: z.string() }),- claim: documentClaim,- externalSearch: ['preview'],- },- ],- },- {- id: 'drive-detail',- path: 'pdf/:documentId',- params: z.object({ documentId: z.string() }),- claim: documentClaim,- externalSearch: ['preview'],- },- ],-});--const routes = createRoutesManifest({- definitions: [- driveRoute,- {- id: 'legacy',- path: 'legacy/:id',- params: z.object({ id: z.string() }),- },- ],- globalSearch: ['referral_code'],-});--describe('split route parameter schemas', () => {- const issueRoute = defineRoute({- id: 'issue',- path: 'issue/:issueId',- params: z.object({ issueId: z.coerce.number().int().positive() }),- remountKey: ({ issueId }) => issueId.toFixed(0),- toReference: ({ issueId }) => ({ type: 'issue', id: issueId.toFixed(0) }),- });-- it('coerces URL strings to typed runtime values', () => {- const entry = decodeRoute(- createRoutesManifest({ definitions: [issueRoute] }),- ['issue', '42']- );-- expect(routeParams(entry?.location.route)).toEqual({ issueId: 42 });- expectTypeOf(issueRoute.id).toEqualTypeOf<'issue'>();- expectTypeOf<InferSplitRouteParams<typeof issueRoute>>().toEqualTypeOf<{- issueId: number;- }>();- });-- it('keeps the route reference callback on the matched definition', () => {- const manifest = createRoutesManifest({ definitions: [issueRoute] });- expect(manifest.byId.get(issueRoute.id)?.definition).toBe(issueRoute);- expect(issueRoute.toReference({ issueId: 42 })).toEqual({- type: 'issue',- id: '42',+ params: { folderId: 'f1' },});});- it('rejects invalid values', () => {- expect(- validateRouteParams(issueRoute.params, { issueId: 'not-a-number' })- ).toBeUndefined();- });-- it('rejects asynchronous schemas', () => {- const schema = z.object({ id: z.string() }).transform(async ({ id }) => ({- id,- }));-- expect(() => validateRouteParams(schema, { id: 'one' })).toThrow(- 'must be synchronous'- );+ it('moves to the next branch when a params schema rejects the match', () => {+ expect(ids(decodePane(routes, ['drive', 'garbage']))).toEqual([+ 'not-found',+ ]);+ expect(ids(decodePane(routes, ['video', 'x']))).toEqual(['not-found']);});-});-function assertInvalidRouteDeclarations() {- // @ts-expect-error Invalid callbacks are rejected by the declaration boundary.- defineRoutes({ definitions: [{ id: 'bad', path: 'bad', claim: 42 }] });- defineRoutes({- // @ts-expect-error Route parameter schemas must produce objects.- definitions: [defineRoute({ id: 'bad', path: 'bad', params: z.string() })],- });- // @ts-expect-error Schema keys must match the path parameter keys.- defineRoute({- id: 'mismatched-key',- path: 'issue/:issueId',- params: z.object({ id: z.string() }),- });- // @ts-expect-error Schema keys must cover every alias parameter key.- defineRoute({- id: 'mismatched-alias-key',- path: 'issue/:issueId',- aliases: ['issues/:legacyId'],- params: z.object({ issueId: z.string() }),- });- // @ts-expect-error Optional path parameters require optional schema input.- defineRoute({- id: 'mismatched-optionality',- path: 'issue/:issueId?',- params: z.object({ issueId: z.string() }),- });- // @ts-expect-error Schemas cannot require input that the path never provides.- defineRoute({- id: 'extra-required-input',- path: 'issue/:issueId',- params: z.object({ issueId: z.string(), revision: z.string() }),- });- // @ts-expect-error Nested declarations receive the same schema validation.- defineRoutes({- definitions: [- {- id: 'parent',- path: 'parent',- children: [- {- id: 'mismatched-child',- path: ':childId',- params: z.object({ id: z.string() }),- },- ],- },- ],+ it('matches static segments case-insensitively and formats the declared casing', () => {+ const route = decodePane(routes, ['DRIVE', 'Folder']);+ expect(ids(route)).toEqual(['drive', 'drive-folder']);+ expect(formatPane(routes, route!)).toEqual(['drive', 'folder']);});- // @ts-expect-error Route builders require every ancestor's destination params.- driveRoute.children[0].children[0].to({ documentId: 'document-1' });- defineRoute({- id: 'number',- path: ':id',- params: z.object({ id: z.coerce.number() }),- }).to({- // @ts-expect-error Route builders use the schema's output type.- id: '1',- });-}-function assertNestedRouteBuilderNavigation(navigate: SplitNavigate<string>) {- navigate(- driveRoute.children[0].children[0].to({- folderId: 'folder-1',- documentId: 'document-1',- })- );-}-describe('route entry state schemas', () => {- it('parses inherited state and exposes it through the owning branch', () => {- const entry = decodeRoute(routes, [+ it('ranks a nested catch-all above the root catch-all', () => {+ const driveMissing = defineRoute({ id: 'drive-missing', path: '*rest' });+ const nested = createRoutesManifest({+ ...appRoutes,+ definitions: [+ notFoundRoute,+ { ...driveRoute, children: [folderRoute, documentRoute, driveMissing] },+ ],+ });+ expect(ids(decodePane(nested, ['drive', 'garbage']))).toEqual(['drive',- 'folder',- 'folder-id',- 'pdf',- 'document-id',- ])!;- const state = { trail: ['first', 'second'] };- const parsed = parseRouteEntryState(routes, entry.location.route, state);+ 'drive-missing',+ ]);+ expect(ids(decodePane(nested, ['elsewhere']))).toEqual(['not-found']);+ });- expect(parsed).toEqual({ success: true, value: state });- expect(- getRouteEntryState(- routes,- { ...entry, state: parsed.success ? parsed.value : undefined },- driveRoute.children[0].children[0]- )- ).toEqual(state);+ it('matches a route without a path only through its children', () => {+ expect(matchIds(decodePane(routes, ['home']))).toEqual(['app', 'home']);+ expect(decodePane(routes, [])).toBeUndefined();+ expect(formatPane(routes, decodePane(routes, ['mail', 't1'])!)).toEqual([+ 'mail',+ 't1',+ ]);});- it('uses the deepest state schema and does not expose it through an overridden owner', () => {- const root = defineRoute({- id: 'root-state',- path: 'root',- state: z.object({ root: z.string() }),- children: [- {- id: 'child-state',- path: 'child',- state: z.object({ child: z.number() }),- },+ it('matches an empty pane with an empty path', () => {+ const withBase = createRoutesManifest({+ ...appRoutes,+ definitions: [+ defineRoute({ id: 'base', path: '' }),+ ...appRoutes.definitions,],});- const child = root.children[0];- const manifest = createRoutesManifest({ definitions: [root] });- const entry = {- ...decodeRoute(manifest, ['root', 'child'])!,- state: { child: 1 },- };-- expect(getRouteEntryState(manifest, entry, root)).toBeUndefined();- expect(getRouteEntryState(manifest, entry, child)).toEqual({ child: 1 });- expectTypeOf<InferSplitRouteState<typeof child>>().toEqualTypeOf<{- child: number;- }>();+ expect(matchIds(decodePane(withBase, []))).toEqual(['base']);+ expect(formatPanePath(withBase, decodePane(withBase, [])!)).toBe('/');});- it('rejects state outside an owning branch or outside its schema', () => {- const drive = decodeRoute(routes, ['drive'])!;- const legacy = decodeRoute(routes, ['legacy', 'one'])!;-- expect(- parseRouteEntryState(routes, drive.location.route, { trail: 42 })- ).toEqual({ success: false });- expect(- parseRouteEntryState(routes, legacy.location.route, { trail: [] })- ).toEqual({ success: false });- });-});--describe('typed route trees', () => {- it('checks declaration contracts without widening node inference', () => {- expectTypeOf(assertInvalidRouteDeclarations).toBeFunction();- expectTypeOf(assertNestedRouteBuilderNavigation).toBeFunction();- });- it('preserves declaration and schema identity while typing descendant ancestry', () => {- const declarations = {- definitions: [driveRoute] as const,- globalSearch: ['referral_code'] as const,- };- const tree = defineRoutes(declarations);- const detail = tree.definitions[0].children[0].children[0];- expect(tree).toBe(declarations);- expect(tree.definitions[0]).toBe(driveRoute);- expect(detail).toBe(driveRoute.children[0].children[0]);- expect(detail.params).toBe(driveRoute.children[0].children[0].params);- expect(createRoutesManifest(tree).byId.get(detail.id)?.definition).toBe(- detail- );- expectTypeOf(tree).toExtend<SplitRoutes>();- expectTypeOf<InferSplitRouteParams<typeof driveRoute>>().toEqualTypeOf<- z.output<typeof driveRoute.params>- >();- expectTypeOf(detail.id).toEqualTypeOf<'drive-folder-detail'>();- expectTypeOf<InferSplitRouteParams<typeof detail>>().toEqualTypeOf<{- documentId: string;- }>();- expectTypeOf<InferSplitRouteBranchParams<typeof detail>>().toEqualTypeOf<{- folderId: string;- documentId: string;- }>();- expectTypeOf<InferSplitRouteState<typeof detail>>().toEqualTypeOf<{- trail: string[];- }>();- expectTypeOf<InferSplitRouteStateInput<typeof detail>>().toEqualTypeOf<{- trail: string[];- }>();+ it('expands adjacent optional params into prefixes only', () => {+ const pattern = compileRoutePattern({ path: 'a/:b?/:c?' });+ expect(pattern.alternatives.map((tokens) => tokens.length)).toEqual([+ 1, 2, 3,+ ]);});- it('builds typed targets while preserving nested route references', () => {- const detail = driveRoute.children[0].children[0];- const params = { folderId: 'folder-1', documentId: 'document-1' };- expect(detail.to(params)).toEqual({ route: detail, params });- expect(detail.to(params).route).toBe(detail);- expect(Object.keys(detail)).not.toContain('to');- expect(driveRoute.to()).toEqual({ route: driveRoute, params: {} });-- const tree = defineRoutes({- definitions: [{ id: 'plain', path: 'plain/:id' }],- });- const plain = tree.definitions[0];- expect(plain.to({ id: '1' })).toEqual({- route: plain,- params: { id: '1' },- });+ it('rejects invalid declarations', () => {+ const home = defineRoute({ id: 'home', path: 'home' });+ expect(() =>+ createRoutesManifest({ ...appRoutes, definitions: [home, home] })+ ).toThrow(/Duplicate split route id/);+ expect(() =>+ createRoutesManifest({+ ...appRoutes,+ definitions: [home, defineRoute({ id: 'other', path: '/home/' })],+ })+ ).toThrow(/Duplicate sibling split route path/);+ expect(() =>+ createRoutesManifest({+ ...appRoutes,+ definitions: [defineRoute({ id: 'bad', path: '*rest/after' })],+ })+ ).toThrow(/catch-all/);+ expect(() =>+ createRoutesManifest({ ...appRoutes, definitions: [{ id: 'empty' }] })+ ).toThrow(/has no path, so it needs children/);+ expect(() =>+ createRoutesManifest({+ ...appRoutes,+ definitions: [+ home,+ defineRoute({+ id: 'layout',+ children: [defineRoute({ id: 'nested-home', path: 'home' })],+ }),+ ],+ })+ ).toThrow(/Duplicate sibling split route path/);});+});- it('types descendants directly from a named definition before assembly', () => {- const detail = driveRoute.children[0].children[0];- expectTypeOf<InferSplitRouteParams<typeof detail>>().toEqualTypeOf<{- documentId: string;- }>();- expectTypeOf<- InferSplitRouteNavigationParams<typeof detail>- >().toEqualTypeOf<{- folderId: string;- documentId: string;- }>();- expectTypeOf<InferSplitRouteBranchParams<typeof detail>>().toEqualTypeOf<{- folderId: string;- documentId: string;- }>();- const definition = {- id: 'named',- path: 'named/:id',- children: [{ id: 'child', path: ':childId' }],- } as const;- const named = defineRoute(definition);- expect(named).toBe(definition);- expect(named.children[0]).toBe(definition.children[0]);- expectTypeOf<- InferSplitRouteNavigationParams<(typeof named.children)[0]>- >().toEqualTypeOf<{ id: string; childId: string }>();- const tree = defineRoutes({ definitions: [named] });- expect(tree.definitions[0]).toBe(named);+describe('route queries', () => {+ it('uses the deepest claim and falls back to ancestors', () => {+ expect(claimOf(routes, at('/drive/md/d1').route)).toBe('block:md:d1');+ expect(claimOf(routes, at('/mail/t1').route)).toBe('block:email:t1');+ expect(claimOf(routes, at('/mail').route)).toBeUndefined();});- it('rebinds ancestry when an existing reference is composed into another tree', () => {- const tree = defineRoutes({ definitions: [driveRoute] });- const detail = tree.definitions[0].children[0].children[0];- const rebound = defineRoutes({ definitions: [detail] });- const root = rebound.definitions[0];- expect(root).toBe(detail);- expectTypeOf<InferSplitRouteBranchParams<typeof root>>().toEqualTypeOf<{- documentId: string;- }>();- expectTypeOf<InferSplitRouteNavigationParams<typeof root>>().toEqualTypeOf<{- documentId: string;- }>();- expect(root.to({ documentId: 'document-1' })).toEqual({- route: root,- params: { documentId: 'document-1' },- });- const widened: SplitRoutes = tree;- const redefined = defineRoutes(widened);- expectTypeOf(redefined.definitions[0]?.children).toEqualTypeOf<- SplitRoutes['definitions'][number]['children']- >();+ it('restricts search only where a route lists namespaces', () => {+ const drive = at('/drive/folder/f1').route;+ expect(ownsNamespace(routes, drive, 'drive')).toBe(true);+ expect(ownsNamespace(routes, drive, 'mail')).toBe(false);+ expect(ownsNamespace(routes, at('/mail/t1').route, 'anything')).toBe(true);});- it('infers schema-less path params, including optional and catch-all fields', () => {- const raw = defineRoute({- id: 'raw',- path: 'raw/:id/:tab?/*rest',- remountKey: ({ id, tab, rest }) => `${id}:${tab ?? ''}:${rest.join('/')}`,+ it('keeps global and route-owned unprefixed search keys', () => {+ const withExternal = createRoutesManifest({+ ...appRoutes,+ definitions: [+ ...appRoutes.definitions,+ defineRoute({ id: 'pdf', path: 'viewer', externalSearch: ['page'] }),+ ],});- expectTypeOf<InferSplitRouteParams<typeof raw>>().toEqualTypeOf<{- id: string;- tab?: string;- rest: string[];- }>();- expect(raw.remountKey({ id: 'one', rest: ['a', 'b'] })).toBe('one::a/b');- expectTypeOf<InferSplitRouteParams<{ id: 'bare' }>>().toEqualTypeOf<- Record<string, unknown>- >();+ const keys = externalSearchKeys(withExternal, [+ { id: 'e', location: { route: decodePane(withExternal, ['viewer'])! } },+ ]);+ expect([...keys].sort()).toEqual(['page', 'referral_code']);});+});- it('types differently named alias reads separately from canonical destinations', () => {- const route = defineRoute({- id: 'alias',- path: 'item/:id',- aliases: ['old/:legacyId'],- serializeParams: (params) => ({- id: 'id' in params ? params.id : params.legacyId,- }),- remountKey: (params) => ('id' in params ? params.id : params.legacyId),+describe('panes codec', () => {+ it('decodes each pane on its own, so an unmatched app pane is not found', () => {+ const decoded = decodePanes(routes, {+ path: '/mail/t1/~/no/such/place/~/drive',+ search: '',+ hash: '',});- expectTypeOf<InferSplitRouteParams<typeof route>>().toEqualTypeOf<- { id: string } | { legacyId: string }- >();- expectTypeOf<- InferSplitRouteNavigationParams<typeof route>- >().toEqualTypeOf<{ id: string }>();- const manifest = createRoutesManifest(- defineRoutes({ definitions: [route] })+ expect(decoded.panes.map((pane) => ids(pane.entry.location.route))).toEqual(+ [['mail', 'mail-thread'], ['not-found'], ['drive']]);- const entry = decodeRoute(manifest, ['old', 'one'])!;- expect(routeParams(entry.location.route)).toEqual({ legacyId: 'one' });- expect(encodeRoute(manifest, entry)).toEqual(['item', 'one']);+ expect(decoded.panes[1]!.entry.location.route.matches[1]!.params).toEqual({+ segments: ['no', 'such', 'place'],+ });});- it('retains optional ancestor fields and transformed schema outputs', () => {- const tree = defineRoutes({- definitions: [- defineRoute({- id: 'parent',- path: 'parent/:workspace?',- params: z.object({ workspace: z.string().optional() }),- children: [- defineRoute({- id: 'child',- path: ':page',- params: z.object({ page: z.coerce.number() }),- }),- ],- }),- ],- });- const child = tree.definitions[0].children[0];- expectTypeOf<InferSplitRouteBranchParams<typeof child>>().toEqualTypeOf<{- workspace?: string;- page: number;- }>();- expectTypeOf<- InferSplitRouteNavigationParams<typeof child>- >().toEqualTypeOf<{ workspace?: string; page: number }>();+ it('redirects a URL no top-level route handles to the default route', () => {+ const home = [['app', 'home']];+ expect(decodeUrl('/no/such/place')).toEqual(home);+ expect(decodeUrl('/')).toEqual(home);+ expect(decodeUrl('/login/~/home')).toEqual(home);+ expect(decodeUrl('/mail/~/login')).toEqual(home);+ expect(decodeUrl('/login')).toEqual([['login']]);});- it('retains required parent values when optional child fields are absent', () => {- const tree = defineRoutes({+ it('shows a top-level catch-all as the 404 page', () => {+ const withPage = createRoutesManifest({+ ...appRoutes,definitions: [- defineRoute({- id: 'parent',- path: ':id',- params: z.object({ id: z.string() }),- children: [- defineRoute({- id: 'child',- path: 'child/:id?',- params: z.object({ id: z.coerce.number().optional() }),- }),- ],- }),+ ...appRoutes.definitions,+ defineRoute({ id: 'page-not-found', path: '*path' }),],});- const child = tree.definitions[0].children[0];- expectTypeOf<InferSplitRouteBranchParams<typeof child>>().toEqualTypeOf<{- id: string | number | undefined;- }>();- const manifest = createRoutesManifest(tree);- expect(- routeParams(decodeRoute(manifest, ['parent', 'child'])?.location.route)- ).toEqual({ id: 'parent' });- expect(- routeParams(- decodeRoute(manifest, ['parent', 'child', '2'])?.location.route- )- ).toEqual({ id: 2 });- });-- it('models shadowed reads but rejects incompatible flat navigation params', () => {- const tree = defineRoutes({- definitions: [- defineRoute({- id: 'parent',- path: ':id',- params: z.object({ id: z.string() }),- children: [- defineRoute({- id: 'child',- path: ':id',- params: z.object({ id: z.coerce.number() }),- }),- ],- }),+ const decode = (path: string) =>+ decodePanes(withPage, { path, search: '', hash: '' }).panes.map((pane) =>+ matchIds(pane.entry.location.route)+ );+ expect(decode('/no/such/place')).toEqual([['page-not-found']]);+ expect(decode('/home')).toEqual([['app', 'home']]);+ expect(decode('/no/such/place/~/home')).toEqual([['app', 'home']]);+ });++ it('reads pane and entry ids back only when the pane count matches', () => {+ const state = {+ panes: [+ { pane: 'p1' as PaneId, entry: 'e1' },+ { pane: 'p2' as PaneId, entry: 'e2' },],+ };+ const matching = decodePanes(routes, {+ path: '/home/~/mail',+ search: '',+ hash: '',+ state,});- const child = tree.definitions[0].children[0];- expectTypeOf<InferSplitRouteBranchParams<typeof child>>().toEqualTypeOf<{- id: number;- }>();- expectTypeOf<- InferSplitRouteNavigationParams<typeof child>- >().toEqualTypeOf<{ id: never }>();- });-});--describe('split route operations', () => {- it('finds a route with its ancestors in manifest order', () => {- const branch = findRouteBranch(routes, 'drive-folder-detail');- expect(branch?.map(({ definition }) => definition.id)).toEqual([- 'drive',- 'drive-folder',- 'drive-folder-detail',+ expect(matching.panes.map((pane) => [pane.paneId, pane.entry.id])).toEqual([+ ['p1', 'e1'],+ ['p2', 'e2'],]);- expect(branch?.[0]?.definition).toBe(driveRoute);- expect(findRouteBranch(routes, 'missing')).toBeUndefined();- });-- it('matches by declaration order rather than path specificity', () => {- const definitions = [- defineRoute({ id: 'dynamic', path: ':id' }),- defineRoute({ id: 'static', path: 'recent' }),- ];- expect(- decodeRoute(createRoutesManifest({ definitions }), ['recent'])?.location- .route?.matches- ).toEqual([{ id: 'dynamic', params: { id: 'recent' } }]);+ const mismatched = decodePanes(routes, {+ path: '/home',+ search: '',+ hash: '',+ state,+ });+ expect(mismatched.panes[0]!.paneId).toBeUndefined();});- it('round trips nested feature paths', () => {- const entry = decodeRoute(routes, [- 'drive',- 'folder',- 'folder-1',- 'pdf',- 'document-1',- ]);-- expect(entry?.location?.route).toEqual({- matches: [- { id: 'drive', params: {} },- { id: 'drive-folder', params: { folderId: 'folder-1' } },- {- id: 'drive-folder-detail',- params: { documentId: 'document-1' },- },- ],+ it('frames search by pane and drops namespaces a route does not own', () => {+ const decoded = decodePanes(routes, {+ path: '/drive/~/mail',+ search: '?s0.drive.sort=name&s0.other.x=1&s1.mail.tab=inbox',+ hash: '',});- expect(encodeRoute(routes, entry!)).toEqual([- 'drive',- 'folder',- 'folder-1',- 'pdf',- 'document-1',+ expect(decoded.panes.map((pane) => pane.entry.location.search)).toEqual([+ { drive: { sort: ['name'] } },+ { mail: { tab: ['inbox'] } },]);});- it('merges params across a nested match branch', () => {+ it('encodes panes, keeps owned unprefixed keys, and keeps the hash while the path is unchanged', () => {const entry = {+ id: 'e1',location: {- route: {- matches: [- { id: 'drive', params: {} },- { id: 'drive-folder', params: { folderId: 'folder-1' } },- {- id: 'drive-folder-detail',- params: { documentId: 'document-1' },- },- ] as const,- },+ ...at('/drive/folder/f1'),+ search: { drive: { sort: ['name'] } },},};-- expect(routeParams(entry.location.route)).toEqual({- folderId: 'folder-1',- documentId: 'document-1',+ const mail = { id: 'e2', location: at('/mail/t1') };+ const encoded = encodePanes(+ routes,+ [+ { paneId: 'p1' as PaneId, entry },+ { paneId: 'p2' as PaneId, entry: mail },+ ],+ {+ path: '/drive/folder/f1/~/mail/t1',+ search: '?referral_code=r&junk=1',+ hash: '#h',+ }+ );+ expect(encoded).toEqual({+ path: '/drive/folder/f1/~/mail/t1',+ search: '?referral_code=r&s0.drive.sort=name',+ hash: '#h',+ state: {+ panes: [+ { pane: 'p1', entry: 'e1' },+ { pane: 'p2', entry: 'e2' },+ ],+ },});- expect(encodeRoute(routes, entry)).toEqual([- 'drive',- 'folder',- 'folder-1',- 'pdf',- 'document-1',- ]);+ expect(+ encodePanes(routes, [{ paneId: 'p2' as PaneId, entry: mail }], encoded)+ .hash+ ).toBe('');});- it('round trips transformed params with custom serialization', () => {- const calendarRoute = defineRoute({- id: 'calendar',- path: 'calendar/:day',- params: z.object({ day: z.coerce.date() }),- serializeParams: ({ day }) => ({ day: day.toISOString().slice(0, 10) }),- });- const calendarRoutes = createRoutesManifest({- definitions: [calendarRoute],- });- const entry = decodeRoute(calendarRoutes, ['calendar', '2026-01-02']);-- expect(entry?.location?.route?.matches[0]?.params.day).toEqual(- new Date('2026-01-02T00:00:00.000Z')+ it('keeps every unprefixed key while a route with externalSearch "*" shows', () => {+ const login = { id: 'e1', location: at('/login') };+ const encoded = encodePanes(+ routes,+ [{ paneId: 'p1' as PaneId, entry: login }],+ { path: '/home', search: '?email=a&next=b&s0.drive.sort=name', hash: '' });- expect(encodeRoute(calendarRoutes, entry!)).toEqual([- 'calendar',- '2026-01-02',- ]);+ expect(encoded.search).toBe('?email=a&next=b');});- it('decodes aliases and encodes their canonical path', () => {- const entry = decodeRoute(routes, ['files', 'folder', 'folder-1']);-- expect(entry?.location?.route?.matches[0]?.id).toBe('drive');- expect(encodeRoute(routes, entry!)).toEqual([- 'drive',- 'folder',- 'folder-1',- ]);- });-- it('separates URL identity from claimed content identity', () => {- const direct = decodeRoute(routes, ['drive', 'pdf', 'document-1'])!;- const nested = decodeRoute(routes, [- 'drive',- 'folder',- 'folder-1',- 'pdf',- 'document-1',- ])!;-- expect(getRouteClaim(routes, direct.location.route)).toEqual({- namespace: 'document',- id: 'document-1',- });- expect(getRouteClaim(routes, nested.location.route)).toEqual(- getRouteClaim(routes, direct.location.route)- );+ it('escapes a literal separator value so it round-trips', () => {+ const route = canonicalRoute(routes, {+ matches: [+ { id: 'app', params: {} },+ { id: 'block', params: { type: 'md', id: '~' } },+ ],+ })!;+ const path = formatPanePath(routes, route);+ expect(path).toBe('/md/%7E');+ expect(splitPanePaths(path)).toEqual([['md', '%7E']]);+ expect(+ decodePanes(routes, { path, search: '', hash: '' }).panes[0]!.entry+ .location.route.matches[1]!.params+ ).toEqual({ type: 'md', id: '~' });});+});- it('returns only query keys owned by the proposed layout', () => {- const legacy = decodeRoute(routes, ['legacy', 'mail-1'])!;- const drive = decodeRoute(routes, ['drive'])!;- const detail = decodeRoute(routes, ['drive', 'pdf', 'document-1'])!;+describe('target resolution', () => {+ const folder: SplitLocation = {+ ...at('/drive/folder/f1'),+ search: { drive: { sort: ['name'] } },+ };- expect([...getExternalSearchKeys(routes, [legacy])]).toEqual([- 'referral_code',- ]);- expect([...getExternalSearchKeys(routes, [drive])]).toEqual([- 'referral_code',- 'action',- ]);- expect([...getExternalSearchKeys(routes, [detail])]).toEqual([- 'referral_code',- 'action',- 'preview',+ it('resolves relative paths against the calling route', () => {+ expect(+ ids(resolveTarget(routes, folder, 'md/d1', { depth: 2 })?.route)+ ).toEqual(['drive', 'drive-document']);+ expect(+ resolveTarget(routes, folder, '../f2', { depth: 3 })?.route.matches[2]+ ).toEqual({ id: 'drive-folder', params: { folderId: 'f2' } });+ expect(ids(resolveTarget(routes, folder, '/mail/t2')?.route)).toEqual([+ 'mail',+ 'mail-thread',]);});- it('rejects a partial feature route instead of guessing', () => {- expect(decodeRoute(routes, ['drive', 'folder'])).toBeUndefined();+ it('inherits ancestor params and carries search only within the same root', () => {+ const document = resolveTarget(routes, folder, {+ route: documentRoute,+ params: { documentType: 'md', documentId: 'd1' },+ });+ expect(ids(document?.route)).toEqual(['drive', 'drive-document']);+ expect(document?.search).toEqual({ drive: { sort: ['name'] } });+ expect(+ resolveTarget(routes, folder, { route: mailRoute })?.search+ ).toBeUndefined();});- it('rejects ambiguous or invalid route manifests', () => {- expect(() =>- validateSplitRoutes({- definitions: [- { id: 'one', path: 'same' },- { id: 'two', path: 'other', aliases: ['same'] },- ],- })- ).toThrow('Duplicate sibling split route path "same"');- expect(() =>- validateSplitRoutes({- definitions: [- {- id: 'one',- path: 'one',- children: [{ id: 'one', path: 'child' }],- },- ],- })- ).toThrow('Duplicate split route id "one"');- expect(() =>- validateSplitRoutes({- definitions: [{ id: 'one', path: 'one', search: ['not.safe'] }],- })- ).toThrow('Invalid split search namespace "not.safe"');+ it('applies search updates and drops namespaces the destination does not own', () => {+ const location = resolveTarget(routes, folder, '/drive', {+ search: { drive: { view: ['grid'] }, mail: { tab: ['x'] } },+ });+ expect(location?.search).toEqual({ drive: { view: ['grid'] } });});});diff --git a/apps/web/src/lib/split-router/tests/search-params-codec.test.ts b/apps/web/src/lib/split-router/tests/search-params-codec.test.tsdeleted file mode 100644index afc8ad01f1..0000000000--- a/apps/web/src/lib/split-router/tests/search-params-codec.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import { describe, expect, it } from 'vitest';-import { z } from 'zod';-import { createSearchParamsCodec } from '../search-params-codec';--const defaults = { sort: 'name', page: 1, enabled: true, tags: ['default'] };-const schema = z.object({- sort: z.enum(['name', 'recent']),- page: z.number().int().positive(),- enabled: z.boolean(),- tags: z.array(z.string()),-});--// No Solid owner or router is needed to exercise conversion and validation.-describe('search params codec', () => {- it('uses the last scalar value while preserving repeated array values', () => {- const codec = createSearchParamsCodec({ schema, defaults });- const parsed = codec.parse({- sort: ['name', 'recent'],- page: ['2', '3'],- enabled: ['true', 'false'],- tags: ['b', 'a', 'b'],- });- expect(parsed).toEqual({- value: { sort: 'recent', page: 3, enabled: false, tags: ['b', 'a', 'b'] },- valid: true,- });- expect(codec.serialize(parsed.value)).toEqual({- sort: ['recent'],- page: ['3'],- enabled: ['false'],- tags: ['b', 'a', 'b'],- });- });-- it('omits defaults and preserves the explicit empty-array marker', () => {- const codec = createSearchParamsCodec({ schema, defaults });- expect(codec.parse(undefined)).toEqual({ value: defaults, valid: true });- expect(codec.serialize(defaults)).toBeUndefined();- const empty = { ...defaults, tags: [] };- expect(codec.serialize(empty)).toEqual({ tags: [''] });- expect(codec.parse({ tags: [''] })).toEqual({ value: empty, valid: true });- expect(codec.parse({ tags: [] })).toEqual({ value: defaults, valid: true });- });-- it('falls back on invalid inbound state and rejects invalid write candidates', () => {- const codec = createSearchParamsCodec({ schema, defaults });- expect(codec.parse({ page: ['not-a-number'] })).toEqual({- value: defaults,- valid: false,- });- expect(codec.validate({ ...defaults, page: -1 }).success).toBe(false);- expect(codec.validate({ ...defaults, page: 2 })).toEqual({- success: true,- data: { ...defaults, page: 2 },- });- expect(codec.parse({ unknown: ['ignored'] })).toEqual({- value: defaults,- valid: true,- });- });-- it('passes the same array-valued representation to custom codecs', () => {- const codec = createSearchParamsCodec({- schema: z.object({ tags: z.array(z.string()) }),- defaults: { tags: [] as string[] },- deserialize: (params) => ({ tags: params.labels ?? [] }),- serialize: (value) => ({ labels: value.tags }),- });- const parsed = codec.parse({ labels: ['one', 'two', 'one'] });- expect(parsed).toEqual({- value: { tags: ['one', 'two', 'one'] },- valid: true,- });- const serialized = codec.serialize(parsed.value);- expect(serialized).toEqual({ labels: ['one', 'two', 'one'] });- expect(serialized?.labels).not.toBe(parsed.value.tags);- expect(codec.serialize({ tags: [] })).toBeUndefined();- });-- it('falls back if a custom deserializer throws', () => {- const codec = createSearchParamsCodec({- schema,- defaults,- deserialize: () => {- throw new Error('bad URL');- },- serialize: () => undefined,- });- expect(codec.parse({ page: ['broken'] })).toEqual({- value: defaults,- valid: false,- });- });-- it('accepts Standard Schema implementations without a safeParse method', () => {- const codec = createSearchParamsCodec({- defaults: { value: 'default' },- schema: {- '~standard': {- version: 1,- vendor: 'test',- validate: (value) => ({ value: value as { value: string } }),- },- },- });- expect(codec.parse({ value: ['one', 'two'] })).toEqual({- value: { value: 'two' },- valid: true,- });- });-- it('rejects invalid defaults and asynchronous schemas at creation', () => {- expect(() =>- createSearchParamsCodec({ schema, defaults: { ...defaults, page: -1 } })- ).toThrow('Invalid defaults for search params');- expect(() =>- createSearchParamsCodec({- schema: schema.transform(async (value) => value),- defaults,- })- ).toThrow('must be synchronous');- });-});diff --git a/apps/web/src/lib/split-router/tests/search.test.ts b/apps/web/src/lib/split-router/tests/search.test.tsdeleted file mode 100644index d01e003abd..0000000000--- a/apps/web/src/lib/split-router/tests/search.test.ts+++ /dev/null@@ -1,122 +0,0 @@-import { describe, expect, it } from 'vitest';-import {- normalizeSearchParams,- parseSearchState,- parseSplitSearch,- replaceSplitSearchParams,- updateSearchState,-} from '../search';-import type { SplitLocation } from '../types';--describe('split search state', () => {- it.each(['toString', 'valueOf', 'hasOwnProperty'])(- 'treats %s as an own search key without mutating Object.prototype functions',- (name) => {- const inherited = Object.getOwnPropertyDescriptor(- Object.prototype,- name- )!.value;- const before = Object.getOwnPropertyDescriptors(inherited);- const query = new URLSearchParams([- [`s0.${name}.target`, 'one'],- [`s0.${name}.target`, 'two'],- [`s0.drive.${name}`, 'value'],- ]);- const parsed = parseSplitSearch(query.toString());- expect(parsed.get(0)).toEqual({- [name]: { target: ['one', 'two'] },- drive: { [name]: ['value'] },- });- expect(Object.getOwnPropertyDescriptors(inherited)).toEqual(before);- const roundtrip = new URLSearchParams();- replaceSplitSearchParams(roundtrip, [- { location: { search: parsed.get(0) } },- ]);- expect(parseSplitSearch(roundtrip.toString())).toEqual(parsed);- const route: SplitLocation['route'] = {- matches: [{ id: 'drive', params: {} }],- };- updateSearchState(- { route, search: {} },- {- [name]: (current) => {- expect(current).toBeUndefined();- return { target: ['value'] };- },- }- );- }- );- it('round trips repeated values and removes stale namespaced query keys', () => {- const query = new URLSearchParams('referral_code=ref&s9.old.value=stale');- const search = { drive: { tags: ['one', 'two'], sort: ['name'] } };- replaceSplitSearchParams(query, [{ location: { search } }]);-- expect(query.get('referral_code')).toBe('ref');- expect(query.has('s9.old.value')).toBe(false);- expect(query.getAll('s0.drive.tags')).toEqual(['one', 'two']);- expect(parseSplitSearch(query.toString())).toEqual(new Map([[0, search]]));- });-- it('ignores unsafe names and oversized inbound values', () => {- const query = new URLSearchParams({- 's0.constructor.value': 'unsafe',- 's0.drive.prototype': 'unsafe',- 's0.drive.large': 'x'.repeat(16_385),- 's0.drive.valid': 'ok',- });- expect(parseSplitSearch(query.toString())).toEqual(- new Map([[0, { drive: { valid: ['ok'] } }]])- );- expect(() => normalizeSearchParams({ constructor: ['unsafe'] })).toThrow(- 'Invalid split search field'- );- });-- it('recovers only safe array-valued fields from persisted metadata', () => {- expect(- parseSearchState({- drive: {- tags: ['one', 42, 'two'],- bad: 'scalar',- prototype: ['unsafe'],- huge: ['x'.repeat(16_385)],- },- constructor: { field: ['unsafe'] },- other: { ok: ['value'] },- })- ).toEqual({ drive: { tags: ['one', 'two'] }, other: { ok: ['value'] } });- expect(parseSearchState(null)).toBeUndefined();- expect(parseSearchState({ drive: [] })).toBeUndefined();- });-- it('updates namespaces without changing routes or sibling search', () => {- const location: SplitLocation = {- route: { matches: [{ id: 'drive', params: {} }] },- search: { drive: { tags: ['one'] }, sidebar: { view: ['tree'] } },- };- let calls = 0;- const next = updateSearchState(location, {- drive: (current) => {- calls += 1;- return { tags: [...(current?.tags ?? []), 'two'] };- },- });- expect(calls).toBe(1);- expect(next.route).toBe(location.route);- expect(next.search).toEqual({- drive: { tags: ['one', 'two'] },- sidebar: { view: ['tree'] },- });- expect(location.search?.drive.tags).toEqual(['one']);- expect(updateSearchState(next, { drive: undefined }).search).toEqual({- sidebar: { view: ['tree'] },- });- const cleared = updateSearchState(next, {- drive: undefined,- sidebar: undefined,- });- expect(cleared).toEqual({ route: location.route });- expect(cleared.route).toBe(location.route);- });-});diff --git a/apps/web/src/lib/split-router/tests/solid-router-location.test.ts b/apps/web/src/lib/split-router/tests/solid-router-location.test.tsdeleted file mode 100644index 79cac88b2a..0000000000--- a/apps/web/src/lib/split-router/tests/solid-router-location.test.ts+++ /dev/null@@ -1,205 +0,0 @@-import { createSignal, startTransition } from 'solid-js';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { createSolidRouterLocation } from '../integrations/solid-router';-import { createLocationSync } from '../location-sync';-import { createRoutesManifest, decodeRoute } from '../routes';-import type { SplitRouterExternalLocationValue } from '../types';-import { parseExternalLocation } from '../url';--const disposers: Array<() => void> = [];--afterEach(() => {- for (const dispose of disposers.splice(0)) dispose();- vi.useRealTimers();-});--function setup() {- vi.useFakeTimers();- const [external, setExternal] =- createSignal<SplitRouterExternalLocationValue>(- parseExternalLocation('/item/current')- );- const navigate = vi.fn((url: string, options: { state?: unknown }) => {- setExternal({ ...parseExternalLocation(url), state: options.state });- });- const location = createSolidRouterLocation({- pathname: () => external().pathname,- search: () => external().search,- hash: () => external().hash,- state: () => external().state,- navigate,- });- const listener = vi.fn();- const unsubscribe = location.subscribe(listener);- disposers.push(unsubscribe);- const commit = (url: string) =>- location.commit(parseExternalLocation(url), { history: 'push' });- return {- external,- setExternal,- navigate,- location,- listener,- commit,- unsubscribe,- };-}--describe('deferred Solid Router location commits', () => {- it('cancels pending commits on Back after reconnecting subscribers', async () => {- const { external, setExternal, navigate, location, commit, unsubscribe } =- setup();- const original = external();- unsubscribe();- setExternal(parseExternalLocation('/item/away'));- const listener = vi.fn();- disposers.push(location.subscribe(listener));-- commit('/item/queued');- setExternal(original);- await vi.runAllTimersAsync();-- expect(navigate).not.toHaveBeenCalled();- expect(external()).toEqual(original);- expect(listener).toHaveBeenLastCalledWith(original);- });-- it.each([- parseExternalLocation('/item/back'),- parseExternalLocation('/item/current?filter=unread'),- parseExternalLocation('/item/current#message'),- {- ...parseExternalLocation('/item/current'),- state: { __macroSplitRouter: { entries: [{ key: 'older-entry' }] } },- },- ])(- 'cancels pending commits when external navigation changes to %j',- async (back) => {- const { external, setExternal, navigate, listener, commit } = setup();- commit('/item/first');- commit('/item/second');-- setExternal(back);- await vi.runAllTimersAsync();-- expect(navigate).not.toHaveBeenCalled();- expect(external()).toEqual(back);- expect(listener).toHaveBeenLastCalledWith(back);-- commit('/item/fresh');- await vi.runAllTimersAsync();- expect(navigate).toHaveBeenCalledExactlyOnceWith('/item/fresh', {- replace: false,- state: undefined,- });- }- );-- it.each(['synchronous', 'transition'])(- 'preserves newer queued commits when its own %s navigation is observed by multiple subscribers',- async (mode) => {- const { external, setExternal, navigate, location, commit } = setup();- if (mode === 'transition') {- navigate.mockImplementation((url, options) => {- void startTransition(() =>- setExternal({ ...parseExternalLocation(url), state: options.state })- );- });- }- const secondListener = vi.fn();- disposers.push(location.subscribe(secondListener));-- commit('/item/first');- commit('/item/second');- await vi.runAllTimersAsync();-- expect(navigate.mock.calls.map(([url]) => url)).toEqual([- '/item/first',- '/item/second',- ]);- expect(external().pathname).toBe('/item/second');- expect(secondListener).toHaveBeenCalledTimes(2);- }- );-- it('expires coalesced echoes so Back to an older commit cancels a pending write', async () => {- const { external, setExternal, navigate, commit } = setup();- navigate.mockImplementation(() => {});- commit('/item/first');- commit('/item/second');- await vi.runAllTimersAsync();- setExternal(parseExternalLocation('/item/second'));- navigate.mockClear();-- commit('/item/third');- setExternal(parseExternalLocation('/item/first'));- await vi.runAllTimersAsync();-- expect(navigate).not.toHaveBeenCalled();- expect(external().pathname).toBe('/item/first');- });-- it('lets Back supersede a queued commit after an earlier commit has been observed', async () => {- const { external, setExternal, navigate, commit } = setup();- navigate.mockImplementationOnce((url, options) => {- setExternal({ ...parseExternalLocation(url), state: options.state });- setExternal(parseExternalLocation('/item/back'));- });-- commit('/item/first');- commit('/item/second');- await vi.runAllTimersAsync();-- expect(navigate).toHaveBeenCalledTimes(1);- expect(external().pathname).toBe('/item/back');- });-- it('keeps location-sync acknowledgements consistent when Back cancels a queued commit', async () => {- const { external, setExternal, navigate, location } = setup();- const routes = createRoutesManifest({- definitions: [{ id: 'item', path: 'item/:id' }],- });- const sync = createLocationSync({ routes, location });- const acknowledge = vi.fn((next: SplitRouterExternalLocationValue) =>- sync.acknowledge(next)- );- disposers.push(location.subscribe(acknowledge));- const commit = (id: string) =>- sync.commit([{ ...decodeRoute(routes, ['item', id])!, key: id }], {- history: 'push',- preserveHash: false,- });-- commit('first');- await vi.runAllTimersAsync();- const first = external();- commit('second');- commit('third');- await vi.runAllTimersAsync();- expect(navigate.mock.calls.map(([url]) => url)).toEqual([- '/item/first',- '/item/second',- '/item/third',- ]);- expect(acknowledge.mock.results.map(({ value }) => value)).toEqual([- true,- true,- true,- ]);-- navigate.mockClear();- commit('fourth');- setExternal(first);- await vi.runAllTimersAsync();- expect(acknowledge).toHaveLastReturnedWith(false);- expect(navigate).not.toHaveBeenCalled();- expect(external()).toEqual(first);-- // A cancelled request must not prevent a later attempt at the same destination.- commit('fourth');- await vi.runAllTimersAsync();- expect(navigate).toHaveBeenCalledTimes(1);- expect(external().pathname).toBe('/item/fourth');- expect(acknowledge).toHaveLastReturnedWith(true);- });-});diff --git a/apps/web/src/lib/split-router/tests/solid.test.tsx b/apps/web/src/lib/split-router/tests/solid.test.tsxindex 09be2b67a6..1cda67a5f0 100644--- a/apps/web/src/lib/split-router/tests/solid.test.tsx+++ b/apps/web/src/lib/split-router/tests/solid.test.tsx@@ -1,641 +1,523 @@-import { cleanup, fireEvent, render } from '@solidjs/testing-library';-import {- type Accessor,- createSignal,- onCleanup,- onMount,- startTransition,-} from 'solid-js';-import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createEffect, For, type JSX, onCleanup, onMount } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { z } from 'zod';+import { createMemoryHistory, type MemoryHistory } from '../history/memory';+import { createMemoryPaneStore } from '../panes/memory-store';+import { createSplitRouter, type SplitRouter } from '../router/create-router';+import { defineRoute } from '../routes/define';+import type {+ Entry,+ PaneId,+ SplitRouteState,+ SplitRoutes,+} from '../routes/types';+import { SplitRouterProvider, useSplitRouter } from '../solid/context';+import { createSearchParams } from '../solid/create-search-params';import {- createSearchParams,- type SetSearchParams,-} from '../create-search-params';-import { createMemorySplitRouterLocation } from '../integrations/memory';-import { createSolidRouterLocation } from '../integrations/solid-router';-import { defineRoute, defineRoutes } from '../routes';-import {- SplitRouter,useCanGo,+ useMatches,useNavigate,- useOwnsSearchNamespace,- useParams,+ usePane,+ usePendingNavigation,useRouteParams,- useRouteState,- useSplitHistory,- useSplitRouter,-} from '../solid';-import type {- SplitRouterHistorySnapshot,- SplitRouterLayout,- SplitRouterLayoutEntry,- SplitRouterSettledChange,- SplitRoutes,-} from '../types';--const coercedParamsRoute = defineRoute({- id: 'coerced-params',- path: 'coerced/:count',- params: z.object({ count: z.coerce.number() }),- component: CoercedParamsView,+} from '../solid/hooks';+import { Outlet } from '../solid/outlet';+import { PaneScope } from '../solid/pane-scope';+import { Route } from '../solid/route';+import { Router } from '../solid/router';+import { useBeforeLeave } from '../solid/use-before-leave';+import { createTestPolicy } from './fixtures';++const counts = { drive: 0, document: 0 };+const documentTypeReads = vi.fn();+let allowLeave = true;++const documentRoute = defineRoute({+ id: 'document',+ path: ':documentType/:documentId',+ params: z.object({+ documentType: z.enum(['md', 'pdf']),+ documentId: z.string().min(1),+ }),+ remountKey: ({ documentType }) => documentType,+ component: DocumentView,});-function CoercedParamsView() {- const params = useRouteParams(coercedParamsRoute);- return <div>{`${typeof params.count}:${params.count}`}</div>;+function DocumentView() {+ const params = useRouteParams(documentRoute);+ onMount(() => {+ counts.document += 1;+ });+ createEffect(() => documentTypeReads(params.documentType));+ return (+ <p data-testid="document">{`${params.documentType}:${params.documentId}`}</p>+ );+}++function DriveView() {+ const navigate = useNavigate();+ onMount(() => {+ counts.drive += 1;+ });+ return (+ <div>+ <button type="button" onClick={() => navigate('md/d3')}>+ relative+ </button>+ <Outlet />+ </div>+ );}-function createLayout(): SplitRouterLayout<string> {- let entry: SplitRouterLayoutEntry<string> | undefined;- const listeners = new Set<(change: SplitRouterSettledChange) => void>();- const notify = () => {- for (const listener of listeners) {- listener({ history: 'push' });- }- };+function GuardedView() {+ useBeforeLeave(() => allowLeave);+ return <p data-testid="guarded">guarded</p>;+}- return {- snapshot: () => ({- entries: entry ? [entry] : [],+function ListView() {+ const [search, setSearch] = createSearchParams({+ namespace: 'list',+ schema: z.object({ sort: z.enum(['name', 'date']) }),+ defaults: { sort: 'name' as 'name' | 'date' },+ });+ return (+ <button type="button" onClick={() => setSearch({ sort: 'date' })}>+ {`sort:${search.sort}`}+ </button>+ );+}++const runs: Record<string, number> = {};+const bump = (key: string) => {+ runs[key] = (runs[key] ?? 0) + 1;+};++/** Counts every reader a search change could wake, per pane. */+function ProbeView() {+ const pane = usePane();+ const [probe, setProbe] = createSearchParams({+ namespace: 'probe',+ schema: z.object({+ sort: z.enum(['name', 'date']),+ tags: z.array(z.string()),}),- updateCurrentLocation(_splitId, update) {- if (!entry) return;- entry = { splitId: entry.splitId, location: update(entry) };- notify();- },- open: () => ({ status: 'unavailable' }),- reconcile(locations) {- const location = locations[0];- entry = location ? { splitId: 'split', location } : undefined;- notify();- },- activate: () => {},- subscribe(listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },+ defaults: { sort: 'name' as 'name' | 'date', tags: ['all'] },+ });+ const [other] = createSearchParams({+ namespace: 'other',+ schema: z.object({ tab: z.enum(['a', 'b']) }),+ defaults: { tab: 'a' as 'a' | 'b' },+ });+ const matches = useMatches();+ const pending = usePendingNavigation();+ const canGoForward = useCanGo(1);+ const count = (reader: string) => bump(`${pane()}:${reader}`);++ onMount(() => count('mount'));+ createEffect(() => count(`sort=${probe.sort}`));+ createEffect(() => count(`tags=${probe.tags.join()}`));+ createEffect(() => count(`tab=${other.tab}`));+ createEffect(() => count(`matches=${matches().length}`));+ createEffect(() => count(`pending=${pending()?.phase ?? 'none'}`));+ createEffect(() => count(`canGo=${canGoForward()}`));++ const toggle = () => {+ const sort = probe.sort === 'name' ? 'date' : 'name';++ setProbe({ sort }, { history: 'replace' });};++ return (+ <button type="button" onClick={toggle}>+ {`probe:${pane()}`}+ </button>+ );}+const paneRoutes = [+ defineRoute({+ id: 'drive',+ path: 'drive',+ component: DriveView,+ children: [documentRoute],+ }),+ defineRoute({+ id: 'probe',+ path: 'probe',+ search: ['probe', 'other'],+ component: ProbeView,+ }),+ defineRoute({ id: 'home', path: 'home', component: () => <p>home</p> }),+ defineRoute({ id: 'guarded', path: 'guarded', component: GuardedView }),+ defineRoute({+ id: 'list',+ path: 'list',+ search: ['list'],+ component: ListView,+ }),+];+const routes: SplitRoutes = {definitions: [- defineRoute({- id: 'drive',- path: 'drive',- search: ['drive'],- children: [- {- id: 'drive-folder',- path: 'folder/:folderId',- params: z.object({ folderId: z.string() }),- },- ],- }),+ defineRoute({ id: 'login', path: 'login', component: () => <p>login</p> }),+ defineRoute({ id: 'app', children: paneRoutes }),],+ defaultRoute: () => ({+ matches: [+ { id: 'app', params: {} },+ { id: 'home', params: {} },+ ],+ }),};-type SearchState = {- sort: 'updated_at' | 'created_at';- tags: string[];-};+function PanelHeader() {+ const matches = useMatches();+ const canGoBack = useCanGo(-1);+ const trail = () => matches().map((match) => match.id);++ return (+ <header data-testid="header">+ {`${trail().join('/')} back:${canGoBack()}`}+ </header>+ );+}++function GuardedChrome() {+ useBeforeLeave(() => allowLeave);++ return null;+}++function Panel(props: { pane: PaneId }) {+ return (+ <PaneScope pane={props.pane}>+ <PanelHeader />+ <Outlet />+ </PaneScope>+ );+}++function renderRouter(+ url: string,+ view: (router: SplitRouter) => JSX.Element,+ routeTable: SplitRoutes = routes+) {+ const history: MemoryHistory = createMemoryHistory(url);+ let router: SplitRouter | undefined;+ render(() => {+ const created = createSplitRouter({+ routes: routeTable,+ history,+ paneStore: createMemoryPaneStore(),+ policy: createTestPolicy().policy,+ });+ router = created;+ onCleanup(() => created.dispose());+ return (+ <SplitRouterProvider router={created}>+ {view(created)}+ </SplitRouterProvider>+ );+ });+ return { history, router: router! };+}-const schema = z.object({- sort: z.enum(['updated_at', 'created_at']),- tags: z- .unknown()- .transform((value) => (Array.isArray(value) ? value.map(String) : [])),+function renderPanes(+ url: string,+ renderPane: (pane: PaneId) => JSX.Element = (pane) => <Outlet pane={pane} />+) {+ return renderRouter(url, (router) => (+ <For each={router.panes()}>{renderPane}</For>+ ));+}++beforeEach(() => {+ counts.drive = 0;+ counts.document = 0;+ documentTypeReads.mockClear();+ allowLeave = true;++ for (const key of Object.keys(runs)) {+ delete runs[key];+ }});afterEach(() => {cleanup();vi.restoreAllMocks();- vi.useRealTimers();});-describe('Solid split router hooks', () => {- it('reads inherited route state and types navigation state', () => {- const root = defineRoute({- id: 'state-root',- path: 'state',- state: z- .object({ trail: z.array(z.string()) })- .transform((state) => ({ ...state, length: state.trail.length })),- children: [{ id: 'state-child', path: 'item/:id' }],- });- const child = root.children[0];-- function StateView() {- const state = useRouteState(root);- const navigate = useNavigate();- expectTypeOf(state()).toEqualTypeOf<- { trail: string[]; length: number } | undefined- >();- return (- <button- type="button"- onClick={() =>- navigate(- { route: child, params: { id: 'one' } },- {- state: (current) => ({- trail: [- ...(current?.trail ?? []),- `one-${current?.length ?? 0}`,- ],- }),- }- )- }- >- {state()?.trail.join('/') ?? 'empty'}- </button>- );- }-- const result = render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={{ definitions: [root] }}- location={createMemorySplitRouterLocation('/state')}- >- <SplitRouter.Scope splitId="split">- <StateView />- </SplitRouter.Scope>- </SplitRouter.Root>- ));+describe('split router Solid bindings', () => {+ it('keeps a view mounted while its remount key holds and updates params in place', () => {+ const { router } = renderPanes('/drive/md/d1');+ const pane = router.panes()[0]!;+ expect(screen.getByTestId('document').textContent).toBe('md:d1');- fireEvent.click(result.getByRole('button'));- expect(result.getByRole('button').textContent).toBe('one-0');- });+ router.navigatePane(pane, '/drive/md/d2');+ expect(screen.getByTestId('document').textContent).toBe('md:d2');+ expect(counts).toEqual({ drive: 1, document: 1 });+ expect(documentTypeReads).toHaveBeenCalledTimes(1);- it('reads typed branch params only through the referenced node and stays reactive', () => {- const tree = defineRoutes({- definitions: [- defineRoute({- id: 'workspace',- path: 'workspace/:workspaceId/:id',- params: z.object({ workspaceId: z.string(), id: z.string() }),- children: [- defineRoute({- id: 'count',- path: 'count/:id',- params: z.object({ id: z.coerce.number() }),- }),- ],- }),- ],- });- const parent = tree.definitions[0];- const child = parent.children[0];- function ParamsView() {- const parentParams = useParams(parent);- const childParams = useParams(child);- const localParams = useRouteParams(child);- const missing = useParams(- defineRoute({ id: 'absent', path: 'absent/:id' })- );- expectTypeOf(parentParams).toEqualTypeOf<{- workspaceId: string;- id: string;- }>();- expectTypeOf(childParams).toEqualTypeOf<{- workspaceId: string;- id: number;- }>();- expectTypeOf(localParams).toEqualTypeOf<{ id: number }>();- return (- <div>{`${parentParams.workspaceId}:${parentParams.id}:${childParams.id}:${localParams.id}:${JSON.stringify(missing)}`}</div>- );- }- const location = createMemorySplitRouterLocation(- '/workspace/a/parent-a/count/2'- );- const result = render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={tree}- location={location}- >- <SplitRouter.Scope splitId="split">- <ParamsView />- </SplitRouter.Scope>- </SplitRouter.Root>- ));- expect(result.getByText('a:parent-a:2:2:{}')).toBeTruthy();- location.set('/workspace/b/parent-b/count/3');- expect(result.getByText('b:parent-b:3:3:{}')).toBeTruthy();+ router.navigatePane(pane, '/drive/pdf/d2');+ expect(counts).toEqual({ drive: 1, document: 2 });});- it('renders the outlet fallback for a missing split without a route-less entry', () => {- const layout = createLayout();- const view = render(() => (- <SplitRouter.Root- layout={layout}- routes={routes}- location={createMemorySplitRouterLocation('/unmatched')}- >- <SplitRouter.Outlet- splitId="missing"- fallback={() => <div>No split</div>}- />- </SplitRouter.Root>- ));- expect(layout.snapshot().entries).toEqual([]);- expect(view.getByText('No split')).toBeTruthy();- });- it('returns schema-coerced values from typed route params', () => {- const location = createMemorySplitRouterLocation('/coerced/42');- const layout = createLayout();- const routes: SplitRoutes = {- definitions: [coercedParamsRoute],- };- const result = render(() => (- <SplitRouter.Root layout={layout} routes={routes} location={location}>- <SplitRouter.Outlet splitId="split" />- </SplitRouter.Root>+ it('lets panel chrome around a prop-less outlet use the hooks', () => {+ const { router } = renderPanes('/drive/md/d1', (pane) => (+ <Panel pane={pane} />));+ const pane = router.panes()[0]!;+ expect(screen.getByTestId('header').textContent).toBe(+ 'app/drive/document back:false'+ );+ expect(screen.getByTestId('document').textContent).toBe('md:d1');- expect(result.getByText('number:42')).toBeTruthy();+ router.navigatePane(pane, '/home');+ expect(screen.getByTestId('header').textContent).toBe('app/home back:true');+ expect(screen.getByText('home')).toBeTruthy();});- it('renders the pinned mount fallback when the route has no component', () => {- const location = createMemorySplitRouterLocation('/drive');- const layout = createLayout();- const result = render(() => (- <SplitRouter.Root layout={layout} routes={routes} location={location}>- <SplitRouter.Outlet- splitId="split"- fallback={() => <div>pinned mount</div>}- />- </SplitRouter.Root>+ it('asks a guard in pane chrome before the pane closes, not on navigations inside it', async () => {+ const { router } = renderPanes('/home/~/drive/md/d1', (pane) => (+ <PaneScope pane={pane}>+ <GuardedChrome />+ <Outlet />+ </PaneScope>));+ const second = router.panes()[1]!;+ allowLeave = false;- expect(result.getByText('pinned mount')).toBeTruthy();- });+ expect(router.navigatePane(second, '/home')).toMatchObject({+ status: 'committed',+ });+ expect(await router.close(second)).toBe(false);- it('keeps matched ancestors mounted when nested params change', async () => {- let parentMounts = 0;- let parentDisposals = 0;- let childMounts = 0;- let childDisposals = 0;- let router: ReturnType<typeof useSplitRouter<string>> | undefined;-- const Child = () => {- childMounts += 1;- onCleanup(() => {- childDisposals += 1;- });- const params = useParams<{ itemId?: string }>();-- return <div data-testid="child">{params.itemId}</div>;- };- const Parent = () => {- parentMounts += 1;- onCleanup(() => {- parentDisposals += 1;- });- router = useSplitRouter<string>();+ allowLeave = true;+ expect(await router.close(second)).toBe(true);+ expect(router.panes()).toHaveLength(1);+ });+ it('renders the first pane’s top-level route at the root, and a layout route renders each pane below it', async () => {+ function PaneLayout() {+ const router = useSplitRouter();return (- <div>- <div>parent</div>- <SplitRouter.Outlet />- </div>+ <For each={router.panes()}>+ {(pane) => (+ <section data-testid="pane">+ <PaneScope pane={pane}>+ <GuardedChrome />+ <Outlet />+ </PaneScope>+ </section>+ )}+ </For>);- };- const nestedRoutes: SplitRoutes = {+ }+ const layoutRoutes: SplitRoutes = {+ ...routes,definitions: [- defineRoute({- id: 'parent',- path: 'parent',- component: Parent,- children: [- {- id: 'child',- path: 'child/:itemId',- params: z.object({ itemId: z.string() }),- component: Child,- },- ],- }),+ routes.definitions[0]!,+ defineRoute({ id: 'app', component: PaneLayout, children: paneRoutes }),],};- const location = createMemorySplitRouterLocation('/parent/child/one');- const layout = createLayout();- const result = render(() => (- <SplitRouter.Root- layout={layout}- routes={nestedRoutes}- location={location}- >- <SplitRouter.Outlet splitId="split" />- </SplitRouter.Root>- ));+ const { router, history } = renderRouter(+ '/home/~/drive',+ () => <Outlet />,+ layoutRoutes+ );+ expect(screen.getAllByTestId('pane')).toHaveLength(2);+ expect(screen.getByText('home')).toBeTruthy();+ expect(counts.drive).toBe(1);++ allowLeave = false;+ const second = router.panes()[1]!;+ expect(router.navigatePane(second, '/home')).toMatchObject({+ status: 'committed',+ });+ expect(screen.getAllByText('home')).toHaveLength(2);+ expect(await router.close(second)).toBe(false);++ allowLeave = true;+ await router.navigatePane(router.panes()[0]!, '/login');+ expect(screen.getByText('login')).toBeTruthy();+ expect(screen.queryAllByTestId('pane')).toHaveLength(0);+ expect(history.read().path).toBe('/login');+ });- const setChild = (itemId: string) => {- layout.updateCurrentLocation('split', (entry) => ({- ...entry.location,- route: {- matches: [- { id: 'parent', params: {} },- { id: 'child', params: { itemId } },- ],- },- }));- };+ it('re-runs only the readers of the search field that changed', () => {+ let paneRenders = 0;+ const { router } = renderPanes('/probe/~/probe', (pane) => {+ paneRenders += 1;++ return <Outlet pane={pane} />;+ });+ const [first, second] = router.panes();+ const before = { ...runs };- expect(result.getByText('parent')).toBeTruthy();- expect(parentMounts).toBe(1);-- setChild('one');- await router?.settled();- expect(result.getByTestId('child').textContent).toBe('one');- expect(childMounts).toBe(1);-- setChild('two');- await router?.settled();- expect(result.getByTestId('child').textContent).toBe('two');- expect(parentMounts).toBe(1);- expect(parentDisposals).toBe(0);- expect(childMounts).toBe(1);- expect(childDisposals).toBe(0);+ fireEvent.click(screen.getByText(`probe:${first}`));++ const woken = Object.keys(runs).filter((key) => runs[key] !== before[key]);+ expect(woken).toEqual([`${first}:sort=date`]);+ expect(paneRenders).toBe(2);+ expect(runs[`${second}:mount`]).toBe(1);});- it('remounts a route component only when its remount key changes', async () => {- let mounts = 0;- let disposals = 0;- let router: ReturnType<typeof useSplitRouter<string>> | undefined;- const View = () => {- mounts += 1;- onCleanup(() => {- disposals += 1;- });- router = useSplitRouter<string>();-- return <div>remountable</div>;- };- const remountRoutes: SplitRoutes = {- definitions: [- {- id: 'remountable',- path: 'remountable/:version',- params: z.object({ version: z.string() }),- component: View,- remountKey: (params) =>- typeof params.version === 'string' ? params.version : undefined,- },- ],- };- const location = createMemorySplitRouterLocation('/remountable/one');- const layout = createLayout();- render(() => (- <SplitRouter.Root- layout={layout}- routes={remountRoutes}- location={location}- >- <SplitRouter.Outlet splitId="split" />- </SplitRouter.Root>- ));+ it('resolves relative paths against the calling route', () => {+ renderPanes('/drive/md/d1');+ fireEvent.click(screen.getByText('relative'));+ expect(screen.getByTestId('document').textContent).toBe('md:d3');+ });- expect(mounts).toBe(1);- router?.navigate('split', '/remountable/two');- await router?.settled();+ it('runs leave guards before unmounting a view but not for search changes', () => {+ const { router, history } = renderPanes('/guarded');+ const pane = router.panes()[0]!;+ allowLeave = false;+ router.navigatePane(pane, '/home');+ expect(screen.getByTestId('guarded')).toBeTruthy();+ router.updateSearch(pane, 'anything', { x: ['1'] });+ expect(history.read().search).toBe('?s0.anything.x=1');+ allowLeave = true;+ router.navigatePane(pane, '/home');+ expect(screen.queryByTestId('guarded')).toBeNull();+ });- expect(mounts).toBe(2);- expect(disposals).toBe(1);+ it('reads and writes one search namespace and rewrites invalid values', () => {+ const { history } = renderPanes('/list?s0.list.sort=bogus');+ expect(screen.getByRole('button').textContent).toBe('sort:name');+ expect(history.read().search).toBe('');+ fireEvent.click(screen.getByRole('button'));+ expect(screen.getByRole('button').textContent).toBe('sort:date');+ expect(history.read().search).toBe('?s0.list.sort=date');});+});- it('mounts keyed details before synchronizing their browser URLs', async () => {- vi.useFakeTimers();- const [external, setExternal] = createSignal({- pathname: '/detail/one',- state: undefined as unknown,- });- let mountedId: string | undefined;- let router!: ReturnType<typeof useSplitRouter<string>>;- const commits: Array<{ url: string; mountedId: string | undefined }> = [];- const location = createSolidRouterLocation({- pathname: () => external().pathname,- state: () => external().state,- navigate: (url, options) => {- commits.push({ url, mountedId });- return startTransition(() =>- setExternal({ pathname: url, state: options.state })- );- },- });- const View = () => {- router = useSplitRouter<string>();- const { id } = useParams<{ id: string }>();- onMount(() => {- mountedId = id;- });- onCleanup(() => {- mountedId = undefined;- });- return <article>{id}</article>;- };- const view = render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={{- definitions: [- {- id: 'detail',- path: 'detail/:id',- component: View,- remountKey: (params) =>- typeof params.id === 'string' ? params.id : undefined,- },- ],- }}- location={location}- >- <SplitRouter.Outlet splitId="split" />- </SplitRouter.Root>- ));- await vi.runAllTimersAsync();- commits.length = 0;-- for (const id of ['two', 'three', 'two', 'one']) {- router.navigate('split', `/detail/${id}`);- expect(view.getByRole('article').textContent).toBe(id);- await vi.runAllTimersAsync();- expect(commits.at(-1)).toEqual({ url: `/detail/${id}`, mountedId: id });- }- expect(commits).toHaveLength(4);+describe('<SplitRouter.Router>', () => {+ const login = defineRoute({ id: 'login', path: 'login' });+ const app = defineRoute({ id: 'app' });+ const home = defineRoute({ id: 'home', path: 'home' });+ const inbox = defineRoute({ id: 'inbox', path: 'inbox' });+ const defaultRoute = (): SplitRouteState => ({+ matches: [+ { id: 'app', params: {} },+ { id: 'home', params: {} },+ ],});- it('cancels pending browser URL updates when the router is disposed', async () => {- vi.useFakeTimers();- const navigate = vi.fn();- const location = createSolidRouterLocation({- pathname: () => '/drive',- navigate,- });- const unsubscribe = location.subscribe(() => {});- location.commit(- { pathname: '/drive/folder/one', search: '', hash: '' },- { history: 'push' }+ function AppLayout() {+ const router = useSplitRouter();+ return (+ <For each={router.panes()}>+ {(pane) => (+ <section data-testid="pane">+ <Outlet pane={pane} />+ </section>+ )}+ </For>);- unsubscribe();- await vi.runAllTimersAsync();- expect(navigate).not.toHaveBeenCalled();- });+ }- it('reports which search namespaces the split route owns', () => {- const Harness = () => {- const drive = useOwnsSearchNamespace('drive');- const other = useOwnsSearchNamespace('other');- return <div>{`${drive()}:${other()}`}</div>;- };- const view = render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={routes}- location={createMemorySplitRouterLocation('/drive/folder/one')}+ it('builds the route tree from its children and renders the first pane’s top-level route', async () => {+ let router: SplitRouter | undefined;+ function Layout() {+ router = useSplitRouter();+ return <AppLayout />;+ }+ const history = createMemoryHistory('/home/~/inbox');+ render(() => (+ <Router+ history={history}+ paneStore={createMemoryPaneStore()}+ policy={createTestPolicy().policy}+ defaultRoute={defaultRoute}>- <SplitRouter.Scope splitId="split">- <Harness />- </SplitRouter.Scope>- <span data-testid="outside">- {`${useOwnsSearchNamespace('drive')()}`}- </span>- </SplitRouter.Root>+ <Route definition={login} component={() => <p>login</p>} />+ <Route definition={app} component={Layout}>+ <Route definition={home} component={() => <p>home</p>} />+ <Route definition={inbox} component={() => <p>inbox</p>} />+ </Route>+ </Router>));- expect(view.getByText('true:false')).toBeTruthy();- expect(view.getByTestId('outside').textContent).toBe('false');- });- it.each(['invalid', 'updated_at'])(- 'canonicalizes %s search with replacement rather than a new history entry',- async (sort) => {- const location = createMemorySplitRouterLocation(- `/drive?s0.drive.sort=${sort}`- );- const Harness = () => {- const [search] = createSearchParams<SearchState>({- namespace: 'drive',- schema,- defaults: { sort: 'updated_at', tags: [] },- });- return <div>{search.sort}</div>;- };- const view = render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={routes}- location={location}- >- <SplitRouter.Scope splitId="split">- <Harness />- </SplitRouter.Scope>- </SplitRouter.Root>- ));- await new Promise<void>((resolve) => queueMicrotask(resolve));- expect(view.getByText('updated_at')).toBeTruthy();- expect(location.read().search).toBe('');- expect(location.history()).toHaveLength(1);- }- );+ expect(screen.getAllByTestId('pane')).toHaveLength(2);+ expect(screen.getByText('inbox')).toBeTruthy();+ expect(home).not.toHaveProperty('component');- it('replaces typed search from defaults and rejects invalid setter values', async () => {- const location = createMemorySplitRouterLocation(- '/drive?s0.drive.sort=created_at&s0.drive.tags=old'- );- let setSearch: SetSearchParams<SearchState> | undefined;- const Harness = () => {- const [search, set] = createSearchParams<SearchState>({- namespace: 'drive',- schema,- defaults: { sort: 'updated_at', tags: [] },- });- setSearch = set;- return <div>{search.sort}</div>;- };+ await router!.navigatePane(router!.panes()[0]!, '/login');+ expect(screen.getByText('login')).toBeTruthy();+ expect(screen.queryAllByTestId('pane')).toHaveLength(0);+ expect(history.read().path).toBe('/login');+ });++ it('reads routes from arrays and drops false children', () => {+ const extra = [inbox].map((definition) => (+ <Route definition={definition} component={() => <p>inbox</p>} />+ ));render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={routes}- location={location}+ <Router+ history={createMemoryHistory('/inbox')}+ paneStore={createMemoryPaneStore()}+ policy={createTestPolicy().policy}+ defaultRoute={defaultRoute}>- <SplitRouter.Scope splitId="split">- <Harness />- </SplitRouter.Scope>- </SplitRouter.Root>+ {false}+ <Route definition={app} component={AppLayout}>+ <Route definition={home} component={() => <p>home</p>} />+ {extra}+ </Route>+ </Router>));- setSearch?.({ tags: ['new'] }, { mode: 'replace' });- await new Promise<void>((resolve) => queueMicrotask(resolve));- expect(location.read().search).toBe('?s0.drive.tags=new');- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- // @ts-expect-error Reject untyped/invalid callers at runtime too.- setSearch?.({ sort: 'invalid' });- expect(error).toHaveBeenCalledOnce();- expect(location.read().search).toBe('?s0.drive.tags=new');+ expect(screen.getByText('inbox')).toBeTruthy();});- it('reads route and typed search state from the current split', async () => {- const location = createMemorySplitRouterLocation(- '/drive/folder/one?s0.drive.sort=created_at&s0.drive.tags=a&s0.drive.tags=b'- );- const layout = createLayout();- let folderId: string | undefined;- let search: { sort: string; tags: string[] } | undefined;- let setSearch:- | ((- value: Partial<{- sort: 'updated_at' | 'created_at';- tags: string[];- }>- ) => void)- | undefined;- let navigate: ((to: string) => void) | undefined;- let canGoBack: Accessor<boolean> | undefined;- let history: Accessor<SplitRouterHistorySnapshot | undefined> | undefined;-- const Harness = () => {- const params = useParams<{ folderId?: string }>();- [search, setSearch] = createSearchParams<SearchState>({- namespace: 'drive',- schema,- defaults: { sort: 'updated_at', tags: [] },- });- navigate = useNavigate();- canGoBack = useCanGo(-1);- history = useSplitHistory();- folderId = params.folderId;- return null;- };-+ it('passes the compiled routes to a history factory', () => {+ const seen: string[] = [];render(() => (- <SplitRouter.Root layout={layout} routes={routes} location={location}>- <SplitRouter.Scope splitId="split">- <Harness />- </SplitRouter.Scope>- </SplitRouter.Root>+ <Router+ history={(routes) => {+ seen.push(...routes.byId.keys());+ return createMemoryHistory('/home');+ }}+ paneStore={createMemoryPaneStore()}+ policy={createTestPolicy().policy}+ defaultRoute={defaultRoute}+ >+ <Route definition={app} component={AppLayout}>+ <Route definition={home} component={() => <p>home</p>} />+ </Route>+ </Router>));+ expect(seen).toEqual(['app', 'home']);+ });- expect(folderId).toBe('one');- expect(search?.sort).toBe('created_at');- expect(search?.tags).toEqual(['a', 'b']);- expect(canGoBack?.()).toBe(false);-- setSearch?.({ tags: ['c'] });- await new Promise<void>((resolve) => queueMicrotask(resolve));- expect(location.read().search).toBe(- '?s0.drive.sort=created_at&s0.drive.tags=c'- );-- setSearch?.({ sort: undefined, tags: undefined });- await new Promise<void>((resolve) => queueMicrotask(resolve));- expect(location.read().search).toBe('');-- navigate?.('folder/two');- await new Promise<void>((resolve) => queueMicrotask(resolve));- expect(location.read().pathname).toBe('/drive/folder/two');- expect(canGoBack?.()).toBe(true);- expect(history?.()?.index).toBe((history?.()?.entries.length ?? 0) - 1);+ it('rejects definitions that already set children or a component', () => {+ const withComponent = defineRoute({+ id: 'bound',+ path: 'bound',+ component: () => null,+ });+ const options = {+ history: createMemoryHistory('/bound'),+ paneStore: createMemoryPaneStore<Entry>(),+ policy: createTestPolicy().policy,+ defaultRoute: (): SplitRouteState => ({+ matches: [{ id: 'bound', params: {} }],+ }),+ };+ expect(() =>+ render(() => (+ <Router {...options}>+ {/* @ts-expect-error definitions passed to Route carry no component */}+ <Route definition={withComponent} />+ </Router>+ ))+ ).toThrow(/must not set children or component/);+ expect(() =>+ render(() => (+ <Router {...options}>+ <p>not a route</p>+ </Router>+ ))+ ).toThrow(/must be <SplitRouter.Route> elements/);});});diff --git a/apps/web/src/lib/split-router/tests/url.test.ts b/apps/web/src/lib/split-router/tests/url.test.tsdeleted file mode 100644index 910eca1f83..0000000000--- a/apps/web/src/lib/split-router/tests/url.test.ts+++ /dev/null@@ -1,227 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import { z } from 'zod';-import { createRoutesManifest, decodeRoute, routeParams } from '../routes';-import type { SplitRouterEntry, SplitRoutes } from '../types';-import {- decodeRouteLayout,- decodeSplitRouterLocation,- encodeRouteLayout,- encodeSplitRouterLocation,- formatRoutePathname,- parseRoutePathname,- serializeSplitRouterLocation,-} from '../url';--const routeDefinitions: SplitRoutes = {- definitions: [- {- id: 'drive',- path: 'drive',- search: ['drive'],- state: z.record(z.string(), z.unknown()),- children: [{ id: 'folder', path: 'folder/:folderId' }],- },- { id: 'legacy', path: 'legacy/:id' },- ],- globalSearch: ['referral_code'],-};-const routes = createRoutesManifest(routeDefinitions);--describe('split layout URLs', () => {- it('frames feature routes alongside legacy splits', () => {- const drive = decodeRoute(routes, ['drive'])!;- expect(- encodeRouteLayout(routes, [- decodeRoute(routes, ['legacy', 'mail-1'])!,- drive,- ])- ).toEqual(['legacy', 'mail-1', '~', 'drive']);- });-- it('runs unmatched path handlers until one handles the URL', () => {- const legacyRoutes = createRoutesManifest({- ...routeDefinitions,- unmatchedPathHandlers: [- () => undefined,- ({ segments }) => {- if (segments.length < 2 || segments.length % 2 !== 0) return;- const entries: SplitRouterEntry[] = [];- for (let index = 0; index < segments.length; index += 2) {- if (segments[index] !== 'legacy') return;- entries.push(- decodeRoute(routes, segments.slice(index, index + 2))!- );- }- return entries;- },- ],- });- const entries = decodeRouteLayout(legacyRoutes, [- 'legacy',- 'mail-1',- 'legacy',- 'mail-2',- ]);-- expect(- entries.map((entry) => routeParams(entry.location.route).id)- ).toEqual(['mail-1', 'mail-2']);- expect(encodeRouteLayout(legacyRoutes, entries)).toEqual([- 'legacy',- 'mail-1',- '~',- 'legacy',- 'mail-2',- ]);- });-- it('reports the partial root match to recovery before falling back', () => {- const recover = vi.fn(() => undefined);- const fallback = decodeRoute(routes, ['drive'])!;- const defaultEntry = vi.fn(() => fallback);- const recoveryRoutes = createRoutesManifest({- definitions: [- {- id: 'settings',- path: 'settings/:tab',- params: z.object({ tab: z.literal('account') }),- },- ...routeDefinitions.definitions,- ],- unmatchedPathHandlers: [recover],- defaultEntry,- });-- expect(decodeRouteLayout(recoveryRoutes, ['settings', 'invalid'])).toEqual([- fallback,- ]);- expect(recover).toHaveBeenCalledWith({- segments: ['settings', 'invalid'],- matchedRouteId: 'settings',- });- expect(defaultEntry).toHaveBeenCalledOnce();- });-- it('rejects unresolved default and recovered entries before returning a layout', () => {- const unresolved = { location: {} } as SplitRouterEntry;- const invalidBranch: SplitRouterEntry = {- location: {- route: { matches: [{ id: 'folder', params: { folderId: 'one' } }] },- },- };- for (const entry of [unresolved, invalidBranch]) {- const fallbackRoutes = createRoutesManifest({- ...routeDefinitions,- defaultEntry: () => entry,- });- expect(() => decodeRouteLayout(fallbackRoutes, ['unmatched'])).toThrow(- 'Split route state'- );- const recoveryRoutes = createRoutesManifest({- ...routeDefinitions,- unmatchedPathHandlers: [() => [entry]],- });- expect(() => decodeRouteLayout(recoveryRoutes, ['unmatched'])).toThrow(- 'Split route state'- );- }- expect(decodeRouteLayout(routes, ['unmatched'])).toEqual([]);- });-- it('keeps framed duplicate routes in visible order', () => {- const parts = ['drive', '~', 'drive'];- const entries = decodeRouteLayout(routes, parts);- expect(entries).toHaveLength(2);- expect(encodeRouteLayout(routes, entries)).toEqual(parts);- });-- it('round trips encoded segments with a base path', () => {- const basedRoutes = createRoutesManifest({- ...routeDefinitions,- basePath: '/app',- });- const segments = ['drive', 'folder', 'a/b c'];- const pathname = formatRoutePathname(basedRoutes, segments);- expect(pathname).toBe('/app/drive/folder/a%2Fb%20c');- expect(parseRoutePathname(basedRoutes, pathname)).toEqual(segments);- expect(- parseRoutePathname(basedRoutes, '/app/drive/%E0%A4%A')- ).toBeUndefined();- });-- it('round trips route entry state outside the serialized URL', () => {- const entry = {- ...decodeRoute(routes, ['drive', 'folder', 'one'])!,- key: 'entry-1',- state: { feature: { root: 'document-1' } },- };- const external = encodeSplitRouterLocation({- routes,- entries: [entry],- previous: {- pathname: '/drive',- search: '',- hash: '',- state: { unrelated: 'preserved' },- },- });-- expect(external.state).toMatchObject({- unrelated: 'preserved',- __macroSplitRouter: {- entries: [- {- key: 'entry-1',- state: { feature: { root: 'document-1' } },- },- ],- },- });- expect(- serializeSplitRouterLocation({- routes,- entries: [entry],- previous: external,- })- ).toBe('/drive/folder/one');- expect(- decodeSplitRouterLocation({ routes, location: external }).entries[0]- ).toEqual(entry);- });-- it('ignores malformed browser entry state', () => {- const decoded = decodeSplitRouterLocation({- routes,- location: {- pathname: '/drive',- search: '',- hash: '',- state: {- __macroSplitRouter: {- entries: [{ key: 42, state: { ignored: true } }],- },- },- },- });-- expect(decoded.entries).toEqual([decodeRoute(routes, ['drive'])!]);- });-- it('preserves owned query values and hashes without keeping unrelated search', () => {- const previous =- '/drive/folder/one?s0.drive.tags=b&s0.drive.tags=a&s0.other.x=1&referral_code=ref&unowned=1#heading';- const parsed = decodeSplitRouterLocation({ routes, location: previous });- expect(parsed.entries[0]?.location.search).toEqual({- drive: { tags: ['b', 'a'] },- });- expect(- serializeSplitRouterLocation({- routes,- entries: parsed.entries,- previous,- })- ).toBe(- '/drive/folder/one?referral_code=ref&s0.drive.tags=b&s0.drive.tags=a#heading'- );- });-});diff --git a/apps/web/src/lib/split-router/transitions.ts b/apps/web/src/lib/split-router/transitions.tsdeleted file mode 100644index b56358c23c..0000000000--- a/apps/web/src/lib/split-router/transitions.ts+++ /dev/null@@ -1,87 +0,0 @@-import { isAbortError } from './utils';--export type Transition<TPending> = {- controller: AbortController;- promise: Promise<void>;- pending?: TPending;-};--export function createTransitionManager<TTarget, TPending>(callbacks: {- onSettled: (target: TTarget | undefined, publicStateChanged: boolean) => void;- onError?: (error: unknown) => void;-}) {- const transitions = new Map<unknown, Transition<TPending>>();-- return {- has(key: unknown): boolean {- return transitions.has(key);- },-- pending(key: unknown): TPending | undefined {- return transitions.get(key)?.pending;- },-- cancel(key: unknown): void {- transitions.get(key)?.controller.abort();- transitions.delete(key);- },-- abortAll(): boolean {- let hadPending = false;-- for (const transition of transitions.values()) {- transition.controller.abort();- hadPending ||= transition.pending !== undefined;- }- transitions.clear();-- return hadPending;- },-- start(- key: unknown,- options: {- controller: AbortController;- target?: TTarget;- pending?: TPending;- run: (transition: Transition<TPending>) => Promise<void>;- onSettled?: (transition: Transition<TPending>) => boolean;- }- ): Promise<void> {- transitions.get(key)?.controller.abort();-- const transition: Transition<TPending> = {- controller: options.controller,- pending: options.pending,- promise: Promise.resolve(),- };-- transitions.set(key, transition);- transition.promise = (async () => {- try {- await options.run(transition);- } catch (error) {- if (!isAbortError(error, options.controller.signal)) {- callbacks.onError?.(error);- }- } finally {- if (transitions.get(key) === transition) {- const publicStateChanged = options.onSettled?.(transition) ?? false;- transitions.delete(key);- callbacks.onSettled(options.target, publicStateChanged);- }- }- })();-- return transition.promise;- },-- promises(): Promise<void>[] {- return [...transitions.values()].map((transition) => transition.promise);- },-- get size(): number {- return transitions.size;- },- };-}diff --git a/apps/web/src/lib/split-router/types.ts b/apps/web/src/lib/split-router/types.tsdeleted file mode 100644index 0d8e1f0cd1..0000000000--- a/apps/web/src/lib/split-router/types.ts+++ /dev/null@@ -1,576 +0,0 @@-import type { StandardSchemaV1 } from '@standard-schema/spec';-import type { SplitRoutesManifest } from './routes';--export type BrowserHistoryIntent = 'push' | 'replace';-export type SplitRouteParams = Record<string, unknown>;-export type SplitRouteRawParams = Record<string, string | string[] | undefined>;-export type SerializedSearchParams = Record<string, string[]>;--export type SplitSearchUpdate =- | SerializedSearchParams- | undefined- | ((- current: SerializedSearchParams | undefined- ) => SerializedSearchParams | undefined);--export type SplitSearchUpdateOptions = {- history?: BrowserHistoryIntent;-};--export type SplitRouterNavigationCause =- | 'initial'- | 'external'- | 'navigate'- | 'history'- | 'search'- | 'layout';--export type SplitRouterMiddlewareRedirect = {- type: 'redirect';- to: string;-};--export type SplitRouterMiddlewareContext = {- /** The currently accepted entry at this visible split position, if any. */- from: Readonly<SplitRouterEntry> | undefined;- /** The proposed entry. It has not been applied to the layout yet. */- to: Readonly<SplitRouterEntry>;- /** Canonical single-split pathname for `to`. */- path: string;- /** Raw incoming URL search on initial/external navigation, retained across redirects. */- externalSearch?: string;- cause: SplitRouterNavigationCause;- signal: AbortSignal;- redirect: (to: string) => SplitRouterMiddlewareRedirect;-};--export type SplitRouterMiddlewareResult =- | SplitRouterMiddlewareRedirect- | undefined- | void;--export type SplitRouterMiddleware = (- context: SplitRouterMiddlewareContext-) => SplitRouterMiddlewareResult | Promise<SplitRouterMiddlewareResult>;--export type SplitRouterMiddlewareConfig = {- routes: SplitRoutesManifest;- handlers: readonly SplitRouterMiddleware[];-};--export type SplitRouterMiddlewareRequest = {- from?: SplitRouterEntry;- to: SplitRouterEntry;- externalSearch?: string;- cause: SplitRouterNavigationCause;- signal: AbortSignal;-};--export type SplitRouterMiddlewareRun =- | SplitRouterEntry- | Promise<SplitRouterEntry>;--type SplitRouteReference = {- id: string;- params?: StandardSchemaV1;- state?: StandardSchemaV1;-};--type SplitRouteTargetParams<TRoute extends SplitRouteReference> =- {} extends InferSplitRouteNavigationParams<TRoute>- ? { params?: InferSplitRouteNavigationParams<TRoute> }- : { params: InferSplitRouteNavigationParams<TRoute> };--export type SplitRouteNavigationTarget<- TRoute extends SplitRouteReference = SplitRouteReference,-> = TRoute extends unknown- ? { route: TRoute } & SplitRouteTargetParams<NoInfer<TRoute>>- : never;--export type SplitParentNavigationTarget = {- parent: true;- levels?: number;-};--export type SplitNonRouteNavigateTo =- | number- | string- | SplitParentNavigationTarget;--export type SplitNavigateTo =- | SplitNonRouteNavigateTo- | {- route: { id: string };- params?: unknown;- };--export type SplitRouterEntryState =- | object- | string- | number- | bigint- | boolean- | null- | undefined;--export type SplitRouterStateUpdate<- TInput = SplitRouterEntryState,- TOutput = TInput,-> = TInput | ((current: TOutput | undefined) => TInput);--export type SplitNavigateOptions<- TSplitId,- TStateInput = SplitRouterEntryState,- TStateOutput = TStateInput,-> = {- /** Host opening policy, invoked after middleware accepts a new destination.- * Existing claim owners are updated in place without invoking this callback. */- open?: SplitRouterLayout<TSplitId>['open'];- /** Runs after the destination is applied or an existing owner is activated. */- onApplied?: () => void;- replace?: boolean;- target?: 'current' | 'new-split' | TSplitId;- search?: Record<string, SplitSearchUpdate>;- /** State parsed by the destination route's synchronous state schema. */- state?: SplitRouterStateUpdate<TStateInput, TStateOutput>;- /** Bypasses final-destination claims and pending reservations, including history- * traversal. The host layout may still enforce stricter duplicate policy. */- allowDuplicate?: boolean;-};--export type SplitRouteClaim = {- namespace: string;- id: string;-};--/** App-defined identity for a matched route, independent of its pane claim. */-export type SplitReference = {- type: string;- id: string;-};--export type SplitRouteMatch = {- id: string;- params: SplitRouteParams;-};--export type SplitRouteState = {- matches: readonly [SplitRouteMatch, ...SplitRouteMatch[]];-};--export type SplitSearchState = Record<string, SerializedSearchParams>;--export type SplitLocation = {- route: SplitRouteState;- search?: SplitSearchState;-};--export type SplitRouterEntry = {- /** Stable identity for this history entry. Generated by the router when omitted. */- key?: string;- location: SplitLocation;- /** Immutable output of the active route's state schema. */- state?: SplitRouterEntryState;-};--type SplitRouteParamCallback<TParams, TResult> = {- bivarianceHack(params: TParams): TResult;-}['bivarianceHack'];--export type SplitRouteDefinition<- TComponent = unknown,- TParamsSchema extends StandardSchemaV1 = StandardSchemaV1<- unknown,- SplitRouteParams- >,-> = {- id: string;- path: string;- aliases?: readonly string[];- component?: TComponent;- children?: readonly SplitRouteDefinition<TComponent>[];- params?: TParamsSchema;- state?: StandardSchemaV1;- serializeParams?: SplitRouteParamCallback<- StandardSchemaV1.InferOutput<TParamsSchema>,- SplitRouteRawParams- >;- claim?: SplitRouteParamCallback<- StandardSchemaV1.InferOutput<TParamsSchema>,- SplitRouteClaim | undefined- >;- toReference?: SplitRouteParamCallback<- StandardSchemaV1.InferOutput<TParamsSchema>,- SplitReference | undefined- >;- search?: readonly string[] | '*';- externalSearch?:- | readonly string[]- | ((entry: Readonly<SplitRouterEntry>) => readonly string[]);- remountKey?: SplitRouteParamCallback<- StandardSchemaV1.InferOutput<TParamsSchema>,- string | number | undefined- >;-};--type PathSegmentParams<TSegment extends string> =- TSegment extends `:${infer TName}?`- ? { [K in TName]?: string }- : TSegment extends `:${infer TName}`- ? { [K in TName]: string }- : TSegment extends `*${infer TName}`- ? { [K in TName]: string[] }- : {};--type PathParams<TPath extends string> = TPath extends unknown- ? string extends TPath- ? SplitRouteParams- : TPath extends `${infer TSegment}/${infer TRest}`- ? PathSegmentParams<TSegment> & PathParams<TRest>- : PathSegmentParams<TPath>- : never;--/** Raw parameters produced by a route's canonical path and aliases. */-export type InferSplitRoutePathParams<- TPath extends string,- TAliases extends readonly string[] | undefined = undefined,-> = PathParams<- TPath | (TAliases extends readonly string[] ? TAliases[number] : never)->;--type Simplify<T> = { [K in keyof T]: T[K] };-type RequiredParamKeys<T> = {- [K in keyof T]-?: {} extends Pick<T, K> ? never : K;-}[keyof T];-type MergedParam<- TParent,- TLocal,- K extends PropertyKey,-> = K extends keyof TLocal- ? {} extends Pick<TLocal, K>- ? K extends keyof TParent- ? TParent[K] | TLocal[K]- : TLocal[K]- : TLocal[K]- : K extends keyof TParent- ? TParent[K]- : never;--// Object.assign retains the parent value when an optional child field is absent.-type MergeRouteParams<TParent, TLocal> = TParent extends unknown- ? TLocal extends unknown- ? Simplify<- {- [K in- | RequiredParamKeys<TParent>- | RequiredParamKeys<TLocal>]: MergedParam<TParent, TLocal, K>;- } & {- [K in Exclude<- keyof TParent | keyof TLocal,- RequiredParamKeys<TParent> | RequiredParamKeys<TLocal>- >]?: MergedParam<TParent, TLocal, K>;- }- >- : never- : never;--/** The schema output (or raw path params) owned by this node alone. */-export type InferSplitRouteParams<TRoute> = TRoute extends {- params: infer TSchema extends StandardSchemaV1;-}- ? StandardSchemaV1.InferOutput<TSchema>- : TRoute extends { path: infer TPath extends string }- ? MergeRouteParams<- {},- InferSplitRoutePathParams<- TPath,- TRoute extends { aliases: infer TAliases }- ? Extract<TAliases, readonly string[]>- : undefined- >- >- : SplitRouteParams;--type LocalNavigationParams<TRoute> = TRoute extends { params: StandardSchemaV1 }- ? InferSplitRouteParams<TRoute>- : TRoute extends { path: infer TPath extends string }- ? MergeRouteParams<{}, PathParams<TPath>>- : SplitRouteParams;--// Type-only ancestry. Declaration helpers never add properties to supplied objects.-declare const branchParams: unique symbol;--type LocalRouteStateSchema<TRoute> = TRoute extends {- state: infer TSchema extends StandardSchemaV1;-}- ? TSchema- : undefined;--type EffectiveRouteStateSchema<TRoute, TParentSchema> =- LocalRouteStateSchema<TRoute> extends StandardSchemaV1- ? LocalRouteStateSchema<TRoute>- : TParentSchema;--type InferSplitRouteStateSchema<TRoute> = TRoute extends {- readonly [branchParams]: { state: infer TSchema };-}- ? TSchema- : LocalRouteStateSchema<TRoute>;--export type InferSplitRouteState<TRoute> =- InferSplitRouteStateSchema<TRoute> extends infer TSchema extends- StandardSchemaV1- ? StandardSchemaV1.InferOutput<TSchema>- : never;--export type InferSplitRouteStateInput<TRoute> =- InferSplitRouteStateSchema<TRoute> extends infer TSchema extends- StandardSchemaV1- ? StandardSchemaV1.InferInput<TSchema>- : never;--/** Params accumulated through this node, with child fields overriding ancestors. */-export type InferSplitRouteBranchParams<TRoute> = TRoute extends {- readonly [branchParams]: { read: infer TParams };-}- ? TParams- : InferSplitRouteParams<TRoute>;--/** A flat destination bag must satisfy every ancestor's serializer. */-export type InferSplitRouteNavigationParams<TRoute> = TRoute extends {- readonly [branchParams]: { navigate: infer TParams };-}- ? TParams- : LocalNavigationParams<TRoute>;--// Empty object schemas can infer an index signature of never. It must not-// prohibit the fields supplied by other nodes in the same branch.-type BranchParams<TParams> =- TParams extends Record<string, never>- ? {- [K in keyof TParams as string extends K- ? never- : number extends K- ? never- : K]: TParams[K];- }- : TParams;--/** Builds a typed route target without resolving the route against a router. */-type RouteTo<TRoute, TParams> = {} extends TParams- ? (params?: TParams) => { route: TRoute; params: TParams }- : (params: TParams) => { route: TRoute; params: TParams };--type DefinedRoute<TRoute, TParent, TParentNavigation, TParentStateSchema> =- TRoute extends unknown- ? Omit<TRoute, 'children' | 'to' | typeof branchParams> & {- readonly [branchParams]: {- read: MergeRouteParams<- TParent,- BranchParams<InferSplitRouteParams<TRoute>>- >;- navigate: MergeRouteParams<- {},- TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>- >;- state: EffectiveRouteStateSchema<TRoute, TParentStateSchema>;- };- to: RouteTo<- DefinedRoute<TRoute, TParent, TParentNavigation, TParentStateSchema>,- MergeRouteParams<- {},- TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>- >- >;- } & (TRoute extends {- children: infer TChildren extends readonly unknown[];- }- ? {- readonly children: DefinedRouteList<- TChildren,- MergeRouteParams<- TParent,- BranchParams<InferSplitRouteParams<TRoute>>- >,- TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>,- EffectiveRouteStateSchema<TRoute, TParentStateSchema>- >;- }- : Pick<TRoute, Extract<keyof TRoute, 'children'>>)- : never;--type DefinedRouteList<- TDefinitions extends readonly unknown[],- TParent,- TParentNavigation,- TParentStateSchema,-> = {- [K in keyof TDefinitions]: DefinedRoute<- TDefinitions[K],- TParent,- TParentNavigation,- TParentStateSchema- >;-};--/** One original definition with descendant ancestry inferred from this root. */-export type DefinedSplitRoute<TRoute> = DefinedRoute<TRoute, {}, {}, undefined>;--/** The original static tree, with ancestry available on references from that tree. */-export type DefinedSplitRoutes<- TRoutes extends { definitions: readonly unknown[] },-> = Omit<TRoutes, 'definitions'> & {- readonly definitions: DefinedRouteList<- TRoutes['definitions'],- {},- {},- undefined- >;-};--type RouteUnion<TRoute> = TRoute extends { children: readonly (infer TChild)[] }- ? TRoute | RouteUnion<TChild>- : TRoute;--export type SplitRouteUnion<TRoutes extends SplitRoutes> = RouteUnion<- TRoutes['definitions'][number]->;--export type UnmatchedSplitPathContext = {- segments: string[];- matchedRouteId?: string;-};--export type UnmatchedSplitPathHandler = (- context: UnmatchedSplitPathContext-) => SplitRouterEntry[] | undefined;--/** Static route declarations. Do not mutate them during a router's lifetime. */-export type SplitRoutes<TComponent = unknown> = {- definitions: readonly SplitRouteDefinition<TComponent>[];- unmatchedPathHandlers?: readonly UnmatchedSplitPathHandler[];- defaultEntry?: () => SplitRouterEntry;- globalSearch?: readonly string[];- basePath?: string | readonly string[];-};--export type SplitRouterLayoutEntry<TSplitId> = {- splitId: TSplitId;- location: SplitLocation;-};--export type SplitRouterLayoutSnapshot<TSplitId> = {- entries: SplitRouterLayoutEntry<TSplitId>[];-};--export type SplitRouterSettledChange = {- history: BrowserHistoryIntent;-};--export type SplitRouterHistorySnapshot = {- entries: readonly SplitRouterEntry[];- index: number;-};--export type SplitRouterLayoutOpenResult<TSplitId> =- | { status: 'applied'; splitId: TSplitId }- | { status: 'unavailable' };--export interface SplitRouterLayout<TSplitId> {- snapshot(): SplitRouterLayoutSnapshot<TSplitId>;- /** The replace flag controls split history when mounted content changes. */- updateCurrentLocation(- splitId: TSplitId,- update: (current: SplitRouterLayoutEntry<TSplitId>) => SplitLocation,- replace?: boolean- ): void;- open(request: {- location: SplitLocation;- target?: TSplitId | 'new-split';- replace?: boolean;- }): SplitRouterLayoutOpenResult<TSplitId>;- reconcile(locations: SplitLocation[]): void;- activate(splitId: TSplitId): void;- subscribe(listener: (change: SplitRouterSettledChange) => void): () => void;-}--export type SplitRouterExternalLocationValue = {- pathname: string;- search: string;- hash: string;- /** Opaque browser history state. It is never encoded into the URL. */- state?: unknown;-};--export interface SplitRouterExternalLocation {- read(): SplitRouterExternalLocationValue;- subscribe(- listener: (location: SplitRouterExternalLocationValue) => void- ): () => void;- commit(- location: SplitRouterExternalLocationValue,- options: { history: BrowserHistoryIntent }- ): void;-}--export type SplitRouterOptions<TSplitId> = {- layout: SplitRouterLayout<TSplitId>;- routes: SplitRoutes | SplitRoutesManifest;- location: SplitRouterExternalLocation;- middleware?: readonly SplitRouterMiddleware[];-};--export type SplitRouteNavigateOptions<TSplitId, TRoute> = Omit<- SplitNavigateOptions<TSplitId>,- 'state'-> &- ([InferSplitRouteStateInput<TRoute>] extends [never]- ? { state?: never }- : {- state?: SplitRouterStateUpdate<- InferSplitRouteStateInput<TRoute>,- InferSplitRouteState<TRoute>- >;- });--export type SplitNavigate<TSplitId> = {- <const TTarget extends { route: SplitRouteReference }>(- to: TTarget & SplitRouteNavigationTarget<NoInfer<TTarget['route']>>,- options?: SplitRouteNavigateOptions<TSplitId, TTarget['route']>- ): void;- (to: SplitNonRouteNavigateTo, options?: SplitNavigateOptions<TSplitId>): void;-};--export interface SplitRouter<TSplitId> {- readonly routes: SplitRoutesManifest;- entry(splitId: TSplitId): SplitRouterEntry | undefined;- route(splitId: TSplitId): SplitRouteState | undefined;- location(splitId: TSplitId): SplitLocation | undefined;- search(- splitId: TSplitId,- namespace: string- ): SerializedSearchParams | undefined;- navigate<const TTarget extends { route: SplitRouteReference }>(- splitId: TSplitId,- to: TTarget & SplitRouteNavigationTarget<NoInfer<TTarget['route']>>,- options?: SplitRouteNavigateOptions<TSplitId, TTarget['route']>- ): void;- navigate(- splitId: TSplitId,- to: SplitNonRouteNavigateTo,- options?: SplitNavigateOptions<TSplitId>- ): void;- canGo(splitId: TSplitId, delta: number): boolean;- history(splitId: TSplitId): SplitRouterHistorySnapshot | undefined;- updateSearch(- splitId: TSplitId,- namespace: string,- update: SplitSearchUpdate,- options?: SplitSearchUpdateOptions- ): void;- href(splitId: TSplitId): string;- isReady(): boolean;- settled(): Promise<void>;- subscribe(listener: (splitId: TSplitId | undefined) => void): () => void;- dispose(): void;-}diff --git a/apps/web/src/lib/split-router/url.ts b/apps/web/src/lib/split-router/url.tsdeleted file mode 100644index 99a558870c..0000000000--- a/apps/web/src/lib/split-router/url.ts+++ /dev/null@@ -1,260 +0,0 @@-import { mergeBrowserEntries, parseBrowserEntries } from './entry-state';-import {- assertRouteEntry,- decodeRoute,- encodeRoute,- filterRouteSearch,- findMatchingRouteId,- getExternalSearchKeys,- type SplitRoutesManifest,-} from './routes';-import {- isSplitSearchKey,- parseSplitSearch,- replaceSplitSearchParams,-} from './search';-import type {- SplitRouterEntry,- SplitRouterExternalLocationValue,-} from './types';--export const SPLIT_PATH_SEPARATOR = '~';--function addPrefix(value: string, prefix: '?' | '#'): string {- if (!value || value.startsWith(prefix)) return value;-- return `${prefix}${value}`;-}--export function externalLocationToString(- location: SplitRouterExternalLocationValue-): string {- const search = addPrefix(location.search, '?');- const hash = addPrefix(location.hash, '#');-- return `${location.pathname || '/'}${search}${hash}`;-}--export function parseExternalLocation(- value: string | SplitRouterExternalLocationValue-): SplitRouterExternalLocationValue {- if (typeof value !== 'string') {- const location: SplitRouterExternalLocationValue = {- pathname: value.pathname || '/',- search: addPrefix(value.search, '?'),- hash: addPrefix(value.hash, '#'),- };- if (Object.hasOwn(value, 'state')) location.state = value.state;- return location;- }-- const parsed = new URL(value, 'https://split-router.invalid');-- return {- pathname: parsed.pathname,- search: parsed.search,- hash: parsed.hash,- };-}--export function parseRoutePathname(- routes: SplitRoutesManifest,- pathname: string-): string[] | undefined {- const raw = pathname- .replace(/^\/+|\/+$/g, '')- .split('/')- .filter(Boolean);- const base = routes.basePath;- let segments = raw;- const startsWithBase = base.every((part, index) => raw[index] === part);- if (base.length > 0 && startsWithBase) segments = raw.slice(base.length);-- try {- return segments.map(decodeURIComponent);- } catch {- return;- }-}--export function formatRoutePathname(- routes: SplitRoutesManifest,- segments: string[]-): string {- return `/${[...routes.basePath, ...segments]- .map(encodeURIComponent)- .join('/')}`;-}--function framedParts(segments: string[]): string[][] {- const parts: string[][] = [[]];-- for (const segment of segments) {- if (segment === SPLIT_PATH_SEPARATOR) {- parts.push([]);- } else {- parts.at(-1)!.push(segment);- }- }-- return parts.filter((part) => part.length > 0);-}--export function decodeRouteLayout(- routes: SplitRoutesManifest,- segments: string[]-): SplitRouterEntry[] {- let parts = [segments];- if (segments.includes(SPLIT_PATH_SEPARATOR)) {- parts = framedParts(segments);- }- const decoded = parts.map((part) => decodeRoute(routes, part));-- if (decoded.length > 0 && decoded.every(Boolean)) {- return decoded as SplitRouterEntry[];- }-- for (const handle of routes.unmatchedPathHandlers ?? []) {- const recovered = handle({- segments,- matchedRouteId: findMatchingRouteId(routes, segments),- });-- if (recovered) {- for (const entry of recovered) assertRouteEntry(routes, entry);- return recovered;- }- }-- if (!routes.defaultEntry) return [];- const entry = routes.defaultEntry();- assertRouteEntry(routes, entry);- return [entry];-}--export function encodeRouteLayout(- routes: SplitRoutesManifest,- entries: SplitRouterEntry[]-): string[] {- return entries.flatMap((entry, index) => {- const segments = encodeRoute(routes, entry);-- if (index === 0) return segments;- return [SPLIT_PATH_SEPARATOR, ...segments];- });-}--export type DecodedSplitRouterLocation = {- entries: SplitRouterEntry[];- externalLocation: SplitRouterExternalLocationValue;-};--export function decodeSplitRouterLocation(options: {- routes: SplitRoutesManifest;- location: string | SplitRouterExternalLocationValue;-}): DecodedSplitRouterLocation {- const externalLocation = parseExternalLocation(options.location);- const segments = parseRoutePathname(- options.routes,- externalLocation.pathname- );- const search = parseSplitSearch(externalLocation.search);- const browserEntries = parseBrowserEntries(externalLocation.state);- const decodedEntries = decodeRouteLayout(options.routes, segments ?? []);- let entryState: typeof browserEntries;- if (browserEntries?.length === decodedEntries.length) {- entryState = browserEntries;- }- const entries = decodedEntries.map((entry, index) => {- const route = entry.location.route;- const splitSearch = filterRouteSearch(- options.routes,- route,- search.get(index)- );- const browserEntry = entryState?.[index];- const decoded: SplitRouterEntry = {- location: { ...entry.location },- };- if (splitSearch) decoded.location.search = splitSearch;- if (browserEntry?.key) decoded.key = browserEntry.key;- if (browserEntry && Object.hasOwn(browserEntry, 'state')) {- decoded.state = browserEntry.state;- }- return decoded;- });-- return { entries, externalLocation };-}--export function encodeSplitRouterLocation(options: {- routes: SplitRoutesManifest;- entries: SplitRouterEntry[];- previous: SplitRouterExternalLocationValue;- preserveHash?: boolean;- preserveExternalSearch?: boolean;-}): SplitRouterExternalLocationValue {- const pathname = formatRoutePathname(- options.routes,- encodeRouteLayout(options.routes, options.entries)- );- let ownedSearch: ReadonlySet<string>;- if (options.preserveExternalSearch === false) {- ownedSearch = new Set(options.routes.globalSearch ?? []);- } else {- ownedSearch = getExternalSearchKeys(options.routes, options.entries);- }- const query = new URLSearchParams();-- for (const [key, value] of new URLSearchParams(options.previous.search)) {- if (!isSplitSearchKey(key) && ownedSearch.has(key)) {- query.append(key, value);- }- }-- replaceSplitSearchParams(- query,- options.entries.map((entry) => ({- location: {- search: filterRouteSearch(- options.routes,- entry.location.route,- entry.location.search- ),- },- }))- );- query.sort();-- const search = query.toString();- const pathChanged =- pathname.replace(/\/+$/g, '') !==- options.previous.pathname.replace(/\/+$/g, '');-- const encoded: SplitRouterExternalLocationValue = {- pathname,- search: '',- hash: '',- state: mergeBrowserEntries(options.previous.state, options.entries),- };- if (search) encoded.search = `?${search}`;- if (!pathChanged || options.preserveHash) {- encoded.hash = options.previous.hash;- }- return encoded;-}--export function serializeSplitRouterLocation(options: {- routes: SplitRoutesManifest;- entries: SplitRouterEntry[];- previous: string | SplitRouterExternalLocationValue;- preserveHash?: boolean;- preserveExternalSearch?: boolean;-}): string {- return externalLocationToString(- encodeSplitRouterLocation({- ...options,- previous: parseExternalLocation(options.previous),- })- );-}diff --git a/apps/web/src/lib/split-router/utils.ts b/apps/web/src/lib/split-router/utils.tsindex cd55b41d4e..137aa6059a 100644--- a/apps/web/src/lib/split-router/utils.ts+++ b/apps/web/src/lib/split-router/utils.ts@@ -1,53 +1,110 @@const SAFE_NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;+const MAX_NAME_LENGTH = 64;-/** Bounded identifier safe to use as an ordinary object key. */+/** Bounded identifier that is safe to use as an ordinary object key. */export function isSafeName(value: string): boolean {- return (- value.length <= 64 &&- value !== 'constructor' &&- value !== 'prototype' &&- SAFE_NAME.test(value)- );+ const reserved = value === 'constructor' || value === 'prototype';+ const bounded = value.length <= MAX_NAME_LENGTH;++ return bounded && !reserved && SAFE_NAME.test(value);}export function isRecord(value: unknown): value is Record<string, unknown> {- return value !== null && typeof value === 'object' && !Array.isArray(value);+ const isObject = value !== null && typeof value === 'object';++ return isObject && !Array.isArray(value);}-export function takeLast<T>(values: readonly T[] | undefined): T | undefined {- return values?.at(-1);+/** For work nothing can call off, such as hover preloads; it never aborts. */+export const UNCANCELLABLE: AbortSignal = new AbortController().signal;++export function isAbortError(error: unknown, signal?: AbortSignal): boolean {+ if (signal?.aborted) return true;++ return error instanceof DOMException && error.name === 'AbortError';}-export function isPromise<T>(value: T | Promise<T>): value is Promise<T> {+let fallbackSequence = 0;++export function createId(prefix: string): string {+ const random = globalThis.crypto?.randomUUID?.();+ if (random) return `${prefix}_${random}`;++ fallbackSequence += 1;+ const time = Date.now().toString(36);+ const sequence = fallbackSequence.toString(36);++ return `${prefix}_${time}${sequence}`;+}++/** A value now, or later; only real promises leave the current tick. */+export type MaybePromise<T> = T | Promise<T>;++export function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {return value instanceof Promise;}-export function throwIfAborted(signal: AbortSignal): void {- if (!signal.aborted) return;+/** Applies `fn` now, or once `value` settles. */+export function mapMaybe<T, R>(+ value: MaybePromise<T>,+ fn: (value: T) => MaybePromise<R>+): MaybePromise<R> {+ if (!isPromise(value)) return fn(value);- throw signal.reason ?? new DOMException('Aborted', 'AbortError');+ return value.then(fn);}-export function isAbortError(error: unknown, signal: AbortSignal): boolean {- return (- signal.aborted ||- (error instanceof DOMException && error.name === 'AbortError')- );+/** Runs `run`, turning a synchronous throw or a rejection into `onError`'s result. */+export function settleMaybe<T>(+ run: () => MaybePromise<T>,+ onError: (error: unknown) => T+): MaybePromise<T> {+ let value: MaybePromise<T>;++ try {+ value = run();+ } catch (error) {+ return onError(error);+ }++ if (!isPromise(value)) return value;++ return value.catch(onError);}-export function reactiveRecord<T extends object>(read: () => T): T {- return new Proxy({} as T, {- get: (_target, key) => read()[key as keyof T],- has: (_target, key) => key in read(),- ownKeys: () => Reflect.ownKeys(read()),- getOwnPropertyDescriptor: (_target, key) => {- if (!(key in read())) return;+export const CANCELLED: unique symbol = Symbol('split-router.cancelled');++export type Cancelled = typeof CANCELLED;- return {- configurable: true,- enumerable: true,- value: read()[key as keyof T],- };- },+/** A value, possibly async, or `CANCELLED` when the work was called off. */+export type Outcome<T> = MaybePromise<T | Cancelled>;++/**+ * The next step, skipped once cancelled. Not named `then`: a module+ * exporting `then` is a thenable, which breaks `await import()`.+ */+export function andThen<T, R>(+ value: Outcome<T>,+ step: (value: T) => Outcome<R>+): Outcome<R> {+ return mapMaybe(value, (resolved): Outcome<R> => {+ if (resolved === CANCELLED) return CANCELLED;++ return step(resolved);});}++function unlessCancelled<T>(+ resolved: readonly (T | Cancelled)[]+): T[] | Cancelled {+ if (resolved.includes(CANCELLED)) return CANCELLED;++ return resolved as T[];+}++export function all<T>(values: readonly Outcome<T>[]): Outcome<T[]> {+ const waiting = values.some(isPromise);+ if (!waiting) return unlessCancelled(values as (T | Cancelled)[]);++ return mapMaybe(Promise.all(values), unlessCancelled);+}diff --git a/apps/web/src/routes/app-route.ts b/apps/web/src/routes/app-route.tsindex 30ce61eabf..472d4563de 100644--- a/apps/web/src/routes/app-route.ts+++ b/apps/web/src/routes/app-route.ts@@ -1,4 +1,4 @@-import type { SplitRouteMatch, SplitRouteState } from '@app/split-router';+import type { SplitRouteMatch, SplitRouteState } from '@app/lib/split-router';/** The route without a path whose children are the pane routes. */export const APP_ROUTE_ID = 'app';diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsxindex 7bbe822940..d226a04d2b 100644--- a/apps/web/src/routes/app-router-view.tsx+++ b/apps/web/src/routes/app-router-view.tsx@@ -49,12 +49,12 @@ import {TasksRouteView,} from '@app/features/tasks-view/route-views';import { TeamInviteAcceptance } from '@app/features/team-invitations/TeamInviteAcceptance';-import { globalSplitManager } from '@app/signal/splitLayout';import {createMemoryPaneStore,SplitRouter,useSolidRouterHistory,-} from '@app/split-router';+} from '@app/lib/split-router';+import { globalSplitManager } from '@app/signal/splitLayout';import { SplitLayout } from '@components/app/split-layout/SplitLayout';import { createAppSplitRouterMiddleware } from '@components/app/split-layout/split-router/app-middleware';import { createAppPanePolicy } from '@components/app/split-layout/split-router/app-pane-policy';diff --git a/apps/web/src/routes/pages.tsx b/apps/web/src/routes/pages.tsxindex 2766493086..a1151277c3 100644--- a/apps/web/src/routes/pages.tsx+++ b/apps/web/src/routes/pages.tsx@@ -8,7 +8,7 @@ import {} from '@app/features/scheduling/public-booking';import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';-import { useRouteParams } from '@app/split-router';+import { useRouteParams } from '@app/lib/split-router';import { publishLoginSuccess } from '@core/auth/login-events';import { LoadingBlock } from '@core/component/LoadingBlock';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex 0617a22982..25fa22ae8e 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -25,7 +25,7 @@ import {REMINDER_DETAIL_ROUTE_ID,} from '@app/features/reminders/reminder-navigation';import { reviewsTabSearch } from '@app/features/reviews-view/reviews-tab-search';-import { defineRoute, type Entry, routeParams } from '@app/split-router';+import { defineRoute, type Entry, routeParams } from '@app/lib/split-router';import { callDetailSearch } from '@block-call/call-route';import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';diff --git a/apps/web/src/split-router/index.ts b/apps/web/src/split-router/index.tsdeleted file mode 100644index 5c46323c3a..0000000000--- a/apps/web/src/split-router/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from '@app/lib/split-router/next';