@timber-js/app 0.2.0-alpha.86 → 0.2.0-alpha.88
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/index.d.ts +44 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/link.d.ts +7 -44
- package/dist/client/link.d.ts.map +1 -1
- package/dist/config-types.d.ts +39 -0
- package/dist/config-types.d.ts.map +1 -1
- package/dist/fonts/bundle.d.ts +48 -0
- package/dist/fonts/bundle.d.ts.map +1 -0
- package/dist/fonts/dev-middleware.d.ts +22 -0
- package/dist/fonts/dev-middleware.d.ts.map +1 -0
- package/dist/fonts/pipeline.d.ts +138 -0
- package/dist/fonts/pipeline.d.ts.map +1 -0
- package/dist/fonts/transform.d.ts +72 -0
- package/dist/fonts/transform.d.ts.map +1 -0
- package/dist/fonts/types.d.ts +45 -1
- package/dist/fonts/types.d.ts.map +1 -1
- package/dist/fonts/virtual-modules.d.ts +59 -0
- package/dist/fonts/virtual-modules.d.ts.map +1 -0
- package/dist/index.js +773 -574
- package/dist/index.js.map +1 -1
- package/dist/plugins/dev-error-overlay.d.ts +1 -0
- package/dist/plugins/dev-error-overlay.d.ts.map +1 -1
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/plugins/fonts.d.ts +16 -83
- package/dist/plugins/fonts.d.ts.map +1 -1
- package/dist/server/action-client.d.ts +8 -0
- package/dist/server/action-client.d.ts.map +1 -1
- package/dist/server/action-handler.d.ts +7 -0
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/index.js +158 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/route-matcher.d.ts +7 -0
- package/dist/server/route-matcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/sensitive-fields.d.ts +74 -0
- package/dist/server/sensitive-fields.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/client/index.ts +77 -1
- package/src/client/link.tsx +15 -65
- package/src/config-types.ts +39 -0
- package/src/fonts/bundle.ts +142 -0
- package/src/fonts/dev-middleware.ts +74 -0
- package/src/fonts/pipeline.ts +275 -0
- package/src/fonts/transform.ts +353 -0
- package/src/fonts/types.ts +50 -1
- package/src/fonts/virtual-modules.ts +159 -0
- package/src/plugins/dev-error-overlay.ts +47 -3
- package/src/plugins/entries.ts +37 -0
- package/src/plugins/fonts.ts +102 -704
- package/src/plugins/routing.ts +6 -5
- package/src/server/action-client.ts +34 -4
- package/src/server/action-handler.ts +32 -2
- package/src/server/route-matcher.ts +7 -0
- package/src/server/rsc-entry/index.ts +19 -3
- package/src/server/sensitive-fields.ts +230 -0
package/dist/client/index.d.ts
CHANGED
|
@@ -1,8 +1,51 @@
|
|
|
1
1
|
export type { RenderErrorDigest } from './types';
|
|
2
|
+
import type { JSX } from 'react';
|
|
3
|
+
import type { SearchParamsDefinition } from '../search-params/define.js';
|
|
4
|
+
import type { LinkBaseProps } from './link';
|
|
2
5
|
export { Link, interpolateParams, resolveHref, validateLinkHref, buildLinkProps } from './link';
|
|
3
6
|
export { mergePreservedSearchParams } from '../shared/merge-search-params.js';
|
|
4
|
-
export type {
|
|
7
|
+
export type { LinkProps, LinkPropsWithHref, LinkPropsWithParams, LinkBaseProps } from './link';
|
|
5
8
|
export type { LinkSegmentParams, OnNavigateHandler, OnNavigateEvent } from './link';
|
|
9
|
+
/**
|
|
10
|
+
* Href types accepted by the catch-all (non-route) call signature.
|
|
11
|
+
*
|
|
12
|
+
* - External protocols: https://, http://, mailto:, tel:, ftp://
|
|
13
|
+
* - Hash-only and query-only links: #section, ?param=value
|
|
14
|
+
* - Computed `string` variables (non-literal)
|
|
15
|
+
*
|
|
16
|
+
* Internal path literals like "/typo-route" do NOT match — they must
|
|
17
|
+
* be a known route (from codegen) or stored in a `string` variable.
|
|
18
|
+
* This catches wrong hrefs at the type level.
|
|
19
|
+
*/
|
|
20
|
+
type ExternalHref = `http://${string}` | `https://${string}` | `mailto:${string}` | `tel:${string}` | `ftp://${string}` | `//${string}` | `#${string}` | `?${string}`;
|
|
21
|
+
/**
|
|
22
|
+
* Callable interface for the Link component.
|
|
23
|
+
*
|
|
24
|
+
* Two kinds of call signatures:
|
|
25
|
+
* 1. Per-route (added by codegen via interface merging): DIRECT types
|
|
26
|
+
* for segmentParams — preserves TypeScript excess property checking.
|
|
27
|
+
* 2. Catch-all (below): accepts external hrefs and computed `string`
|
|
28
|
+
* variables. Does NOT accept internal path literals — those must
|
|
29
|
+
* match a known route from the codegen.
|
|
30
|
+
*/
|
|
31
|
+
export interface LinkFunction {
|
|
32
|
+
(props: LinkBaseProps & {
|
|
33
|
+
href: ExternalHref;
|
|
34
|
+
segmentParams?: never;
|
|
35
|
+
searchParams?: {
|
|
36
|
+
definition: SearchParamsDefinition<Record<string, unknown>>;
|
|
37
|
+
values: Record<string, unknown>;
|
|
38
|
+
};
|
|
39
|
+
}): JSX.Element;
|
|
40
|
+
<H extends string>(props: string extends H ? LinkBaseProps & {
|
|
41
|
+
href: H;
|
|
42
|
+
segmentParams?: Record<string, string | number | string[]>;
|
|
43
|
+
searchParams?: {
|
|
44
|
+
definition: SearchParamsDefinition<Record<string, unknown>>;
|
|
45
|
+
values: Record<string, unknown>;
|
|
46
|
+
};
|
|
47
|
+
} : never): JSX.Element;
|
|
48
|
+
}
|
|
6
49
|
export { usePendingNavigation } from './use-pending-navigation';
|
|
7
50
|
export { useLinkStatus, LinkStatusContext } from './use-link-status';
|
|
8
51
|
export type { LinkStatus } from './use-link-status';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AASA,YAAY,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAGjD,OAAO,EAAE,IAAI,EAAE,iBAAiB,EAAE,WAAW,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MA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,YAAY,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/client/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/client/use-link-status.ts","../../src/client/nav-link-store.ts","../../src/client/navigation-api.ts","../../src/client/link.tsx","../../src/client/use-pending-navigation.ts","../../src/client/use-router.ts","../../src/client/use-pathname.ts","../../src/client/use-search-params.ts","../../src/client/use-selected-layout-segment.ts","../../src/client/form.tsx","../../src/client/use-cookie.ts","../../src/client/index.ts"],"sourcesContent":["'use client';\n\n// useLinkStatus — returns { isPending: true } while the nearest parent <Link>'s\n// navigation is in flight. No arguments — scoped via React context.\n// See design/19-client-navigation.md §\"useLinkStatus()\"\n\nimport { useContext, createContext } from 'react';\n\nexport interface LinkStatus {\n isPending: boolean;\n}\n\n/**\n * React context provided by <Link>. Holds the pending status\n * for that specific link's navigation.\n */\nexport const LinkStatusContext = createContext<LinkStatus>({ isPending: false });\n\n/**\n * Returns `{ isPending: true }` while the nearest parent `<Link>` component's\n * navigation is in flight. Must be used inside a `<Link>` component's children.\n *\n * Unlike `usePendingNavigation()` which is global, this hook is scoped to\n * the nearest parent `<Link>` — only the link the user clicked shows pending.\n *\n * ```tsx\n * 'use client'\n * import { Link, useLinkStatus } from '@timber-js/app/client'\n *\n * function Hint() {\n * const { isPending } = useLinkStatus()\n * return <span className={isPending ? 'opacity-50' : ''} />\n * }\n *\n * export function NavLink({ href, children }) {\n * return (\n * <Link href={href}>\n * {children} <Hint />\n * </Link>\n * )\n * }\n * ```\n */\nexport function useLinkStatus(): LinkStatus {\n return useContext(LinkStatusContext);\n}\n","/**\n * Navigation Link Store — passes per-link metadata from Link's onClick\n * to the Navigation API's navigate event handler.\n *\n * When the Navigation API is active, Link does NOT call event.preventDefault()\n * or router.navigate(). Instead it stores metadata (scroll option, link\n * pending instance) here, and lets the <a> click propagate naturally.\n * The navigate event handler reads this metadata to configure the RSC\n * navigation with the correct options.\n *\n * This store is consumed once per navigation — after reading, the metadata\n * is cleared. If no metadata is present (e.g., a plain <a> tag without\n * our Link component), the navigate handler uses default options.\n *\n * See design/19-client-navigation.md §\"Navigation API Integration\"\n */\n\nimport type { LinkPendingInstance } from './link-pending-store.js';\n\nexport interface NavLinkMetadata {\n /** Whether to scroll to top after navigation. Default: true. */\n scroll: boolean;\n /** The Link's pending state instance for per-link status tracking. */\n linkInstance: LinkPendingInstance | null;\n}\n\nlet pendingMetadata: NavLinkMetadata | null = null;\n\n/**\n * Store metadata from Link's onClick for the next navigate event.\n * Called synchronously in the click handler — the navigate event\n * fires synchronously after onClick returns.\n */\nexport function setNavLinkMetadata(metadata: NavLinkMetadata): void {\n pendingMetadata = metadata;\n}\n\n/**\n * Consume the stored metadata. Returns null if no Link onClick\n * preceded this navigation (e.g., plain <a> tag, programmatic nav).\n * Clears the store after reading.\n */\nexport function consumeNavLinkMetadata(): NavLinkMetadata | null {\n const metadata = pendingMetadata;\n pendingMetadata = null;\n return metadata;\n}\n","/**\n * Navigation API integration — progressive enhancement for client navigation.\n *\n * When the Navigation API (`window.navigation`) is available, this module\n * provides an intercept-based navigation model that replaces the separate\n * popstate + click handler approach with a single navigate event listener.\n *\n * Key benefits:\n * - Intercepts ALL navigations (link clicks, form submissions, back/forward)\n * - Built-in AbortSignal per navigation (auto-aborts in-flight fetches)\n * - Per-entry state via NavigationHistoryEntry.getState()\n * - navigation.transition for progress tracking\n *\n * When unavailable, all functions are no-ops and the History API fallback\n * in browser-entry.ts handles navigation.\n *\n * See design/19-client-navigation.md\n */\n\nimport type { NavigationApi, NavigateEvent } from './navigation-api-types.js';\nimport { consumeNavLinkMetadata } from './nav-link-store.js';\nimport { isHardNavigating } from './navigation-root.js';\n\n// ─── Feature Detection ───────────────────────────────────────────\n\n/**\n * Returns true if the Navigation API is available in the current environment.\n * Feature-detected at runtime — no polyfill.\n */\nexport function hasNavigationApi(): boolean {\n return (\n typeof window !== 'undefined' &&\n 'navigation' in window &&\n (window as unknown as { navigation: unknown }).navigation != null\n );\n}\n\n/**\n * Get the Navigation API instance. Returns null if unavailable.\n * Uses type assertion — we never import Navigation API types unconditionally.\n */\nexport function getNavigationApi(): NavigationApi | null {\n if (!hasNavigationApi()) return null;\n return (window as unknown as { navigation: NavigationApi }).navigation;\n}\n\n// ─── Navigation API Controller ───────────────────────────────────\n\n/**\n * Callbacks for the Navigation API event handler.\n *\n * When the Navigation API intercepts a navigation, it delegates to these\n * callbacks which run the RSC fetch + render pipeline.\n */\nexport interface NavigationApiCallbacks {\n /**\n * Handle a push/replace navigation intercepted by the Navigation API.\n * This covers both Link <a> clicks (user-initiated, with metadata from\n * nav-link-store) and external navigations (plain <a> tags, programmatic).\n * The Navigation API handles the URL update via event.intercept().\n */\n onExternalNavigate: (\n url: string,\n options: { replace: boolean; signal: AbortSignal; scroll?: boolean }\n ) => Promise<void>;\n\n /**\n * Handle a traversal (back/forward button). The Navigation API intercepts\n * the traversal and delegates to us for RSC replay/fetch.\n */\n onTraverse: (url: string, scrollY: number, signal: AbortSignal) => Promise<void>;\n}\n\n/**\n * Controller returned by setupNavigationApi. Provides methods to\n * coordinate between the router and the navigate event listener.\n */\nexport interface NavigationApiController {\n /**\n * Set the router-navigating flag. When `true`, the next navigate event\n * (from pushState/replaceState) is recognized as router-initiated. The\n * handler still intercepts it — but ties the browser's native loading\n * state to a deferred promise instead of running the RSC pipeline again.\n *\n * This means `navigation.transition` is active for the full duration of\n * every router-initiated navigation, giving the browser a native loading\n * indicator (tab spinner, address bar) aligned with the TopLoader.\n *\n * Must be called synchronously around pushState/replaceState:\n * controller.setRouterNavigating(true);\n * history.pushState(...); // navigate event fires, intercepted\n * controller.setRouterNavigating(false); // flag off, deferred stays open\n */\n setRouterNavigating: (value: boolean) => void;\n\n /**\n * Resolve the deferred promise created by setRouterNavigating(true),\n * clearing the browser's native loading state. Call this when the\n * navigation fully completes — aligned with when the TopLoader's\n * pendingUrl clears (same finally block in router.navigate).\n */\n completeRouterNavigation: () => void;\n\n /**\n * Initiate a navigation via the Navigation API (`navigation.navigate()`).\n * Unlike `history.pushState()`, this fires the navigate event BEFORE\n * committing the URL — allowing Chrome to show its native loading\n * indicator while the intercept handler runs.\n *\n * Must be called with setRouterNavigating(true) active so the handler\n * recognizes it as router-initiated and uses the deferred promise.\n */\n navigate: (url: string, replace: boolean) => void;\n\n /**\n * Save scroll position into the current navigation entry's state.\n * Uses navigation.updateCurrentEntry() for per-entry scroll storage.\n */\n saveScrollPosition: (scrollY: number) => void;\n\n /**\n * Check if the Navigation API has an active transition.\n * Returns the transition object if available, null otherwise.\n */\n hasActiveTransition: () => boolean;\n\n /** Remove the navigate event listener. */\n cleanup: () => void;\n}\n\n/**\n * Set up the Navigation API navigate event listener.\n *\n * Intercepts same-origin navigations and delegates to the provided callbacks.\n * Router-initiated navigations (pushState from router.navigate) are detected\n * via a synchronous flag and NOT intercepted — the router already handles them.\n *\n * Returns a controller for coordinating with the router.\n */\nexport function setupNavigationApi(callbacks: NavigationApiCallbacks): NavigationApiController {\n const nav = getNavigationApi()!;\n\n let routerNavigating = false;\n\n // Deferred promise for router-initiated navigations. Created when\n // setRouterNavigating(true) is called, resolved by completeRouterNavigation().\n // The navigate event handler intercepts with this promise so the browser's\n // native loading state (tab spinner) stays active until the navigation\n // completes — aligned with TopLoader's pendingUrl lifecycle.\n let routerNavDeferred: { promise: Promise<void>; resolve: () => void } | null = null;\n\n function handleNavigate(event: NavigateEvent): void {\n // Skip non-interceptable navigations (cross-origin, etc.)\n if (!event.canIntercept) return;\n\n // Hard navigation guard: when the router has triggered a full page\n // load (500 error, version skew), skip interception entirely so the\n // browser performs the MPA navigation. Without this guard, setting\n // window.location.href fires a navigate event that we'd intercept,\n // running the RSC pipeline again → 500 → window.location.href →\n // navigate event → infinite loop.\n // See design/19-client-navigation.md §\"Hard Navigation Guard\"\n if (isHardNavigating()) return;\n\n // Skip download requests\n if (event.downloadRequest) return;\n\n // Skip hash-only changes — let the browser handle scroll-to-anchor\n if (event.hashChange) return;\n\n // Shallow URL updates (e.g., nuqs search param changes). The navigation\n // only changes the URL — no server round trip needed. Intercept with a\n // no-op handler so the Navigation API commits the URL change without\n // triggering a full page navigation (which is the default if we don't\n // intercept). The info property is the Navigation API's built-in\n // per-navigation metadata — no side-channel flags needed.\n const info = event.info as { shallow?: boolean } | null | undefined;\n if (info?.shallow) {\n event.intercept({\n handler: () => Promise.resolve(),\n focusReset: 'manual',\n scroll: 'manual',\n });\n return;\n }\n\n // Skip form submissions with a body (POST/PUT/etc.). These need the\n // browser's native form handling to send the request body to the server.\n // Intercepting would convert them into GET RSC navigations, dropping\n // the form data. Server actions use fetch() directly (not form navigation),\n // so they are unaffected by this check.\n if (event.formData) return;\n\n // Skip cross-origin (defense-in-depth — canIntercept covers this)\n const destUrl = new URL(event.destination.url);\n if (destUrl.origin !== location.origin) return;\n\n // Router-initiated navigation (Link click → router.navigate → pushState).\n // The router is already running the RSC pipeline — don't run it again.\n // Instead, intercept with the deferred promise so the browser's native\n // loading state tracks the navigation's full lifecycle. This aligns the\n // tab spinner / address bar indicator with the TopLoader.\n if (routerNavigating && routerNavDeferred) {\n event.intercept({\n scroll: 'manual',\n focusReset: 'manual',\n handler: () => routerNavDeferred!.promise,\n });\n return;\n }\n\n // Skip reload navigations — let the browser handle full page reload\n if (event.navigationType === 'reload') return;\n\n const url = destUrl.pathname + destUrl.search;\n\n if (event.navigationType === 'traverse') {\n // Back/forward button — intercept and delegate to router.\n // Read scroll position from the destination entry's state.\n const entryState = event.destination.getState() as\n | { scrollY?: number; timber?: boolean }\n | null\n | undefined;\n const scrollY = entryState && typeof entryState.scrollY === 'number' ? entryState.scrollY : 0;\n\n event.intercept({\n // Manual scroll — we handle scroll restoration ourselves\n // via afterPaint (same as the History API path).\n scroll: 'manual',\n focusReset: 'manual',\n async handler() {\n await callbacks.onTraverse(url, scrollY, event.signal);\n },\n });\n } else if (event.navigationType === 'push' || event.navigationType === 'replace') {\n // Push/replace — either a Link <a> click (with metadata in\n // nav-link-store) or an external navigation (plain <a>, programmatic).\n // Consume link metadata if present — tells us scroll preference\n // and which Link component to track pending state for.\n const linkMeta = consumeNavLinkMetadata();\n\n // Save the departing page's scroll position BEFORE event.intercept()\n // commits the URL change. Once intercept() is called, currentEntry\n // switches to the new (destination) entry — any updateCurrentEntry()\n // call after that would save to the wrong entry.\n // See: router.navigate() also calls saveNavigationEntryScroll(), but\n // for Navigation API <a> click navigations (where Link does NOT call\n // router.navigate directly), the router's save runs inside the\n // intercept handler — too late, currentEntry has already switched.\n try {\n const currentState = (nav.currentEntry?.getState() ?? {}) as Record<string, unknown>;\n nav.updateCurrentEntry({\n state: { ...currentState, timber: true, scrollY: window.scrollY },\n });\n } catch {\n // Ignore — entry may be disposed\n }\n\n event.intercept({\n scroll: 'manual',\n focusReset: 'manual',\n async handler() {\n await callbacks.onExternalNavigate(url, {\n replace: event.navigationType === 'replace',\n signal: event.signal,\n scroll: linkMeta?.scroll,\n });\n },\n });\n }\n }\n\n nav.addEventListener('navigate', handleNavigate as EventListener);\n\n return {\n setRouterNavigating(value: boolean): void {\n routerNavigating = value;\n if (value) {\n // Create a new deferred promise. The navigate event handler will\n // intercept and tie the browser's loading state to this promise.\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n routerNavDeferred = { promise, resolve };\n } else {\n // Flag off — but DON'T resolve the deferred here. The navigation\n // is still in flight (RSC fetch + render). completeRouterNavigation()\n // resolves it when the navigation fully completes.\n routerNavigating = false;\n }\n },\n\n completeRouterNavigation(): void {\n if (routerNavDeferred) {\n routerNavDeferred.resolve();\n routerNavDeferred = null;\n }\n },\n\n navigate(url: string, replace: boolean): void {\n // Use navigation.navigate() instead of history.pushState().\n // This fires the navigate event BEFORE committing the URL,\n // which lets Chrome show its native loading indicator while\n // the intercept handler (deferred promise) is pending.\n // history.pushState() commits the URL synchronously, so Chrome\n // sees the navigation as already complete and skips the indicator.\n nav.navigate(url, {\n history: replace ? 'replace' : 'push',\n });\n },\n\n saveScrollPosition(scrollY: number): void {\n try {\n const currentState = (nav.currentEntry?.getState() ?? {}) as Record<string, unknown>;\n nav.updateCurrentEntry({\n state: { ...currentState, timber: true, scrollY },\n });\n } catch {\n // Ignore errors — updateCurrentEntry may throw if entry is disposed\n }\n },\n\n hasActiveTransition(): boolean {\n return nav.transition != null;\n },\n\n cleanup(): void {\n nav.removeEventListener('navigate', handleNavigate as EventListener);\n },\n };\n}\n","'use client';\n\n// Link component — client-side navigation with progressive enhancement\n// See design/19-client-navigation.md § Progressive Enhancement\n//\n// Without JavaScript, <Link> renders as a plain <a> tag — standard browser\n// navigation. With JavaScript, the Link component's onClick handler triggers\n// RSC-based client navigation via the router.\n//\n// Each Link owns its own click handler — no global event delegation.\n// This keeps navigation within React's component tree, ensuring pending\n// state (useLinkStatus) updates atomically with the navigation.\n//\n// Typed Link: design/09-typescript.md §\"Typed Link\"\n// - href validated against known routes (via codegen overloads, not runtime)\n// - params prop typed per-route, URL interpolated at runtime\n// - searchParams prop serialized via SearchParamsDefinition\n// - params and fully-resolved string href are mutually exclusive\n// - searchParams and inline query string are mutually exclusive\n\nimport {\n useOptimistic,\n useEffect,\n useRef,\n type AnchorHTMLAttributes,\n type JSX,\n type ReactNode,\n type MouseEvent as ReactMouseEvent,\n} from 'react';\nimport type { SearchParamsDefinition } from '../search-params/define.js';\nimport { classifyUrlSegment, type UrlSegment } from '../routing/segment-classify.js';\nimport { LinkStatusContext } from './use-link-status.js';\nimport { getRouterOrNull } from './router-ref.js';\nimport { getSsrData } from './ssr-data.js';\nimport { mergePreservedSearchParams } from '../shared/merge-search-params.js';\nimport {\n setLinkForCurrentNavigation,\n unmountLinkForCurrentNavigation,\n LINK_IDLE,\n type LinkPendingInstance,\n} from './link-pending-store.js';\nimport { setNavLinkMetadata } from './nav-link-store.js';\nimport { hasNavigationApi } from './navigation-api.js';\n\n// ─── Current Search Params ────────────────────────────────────────\n\n/**\n * Read the current URL's search string without requiring a React hook.\n * On the client, reads window.location.search. During SSR, reads from\n * the request context (getSsrData). Returns empty string if unavailable.\n */\nfunction getCurrentSearch(): string {\n if (typeof window !== 'undefined') return window.location.search;\n const data = getSsrData();\n if (!data) return '';\n const sp = new URLSearchParams(data.searchParams);\n const str = sp.toString();\n return str ? `?${str}` : '';\n}\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport type OnNavigateEvent = {\n preventDefault: () => void;\n};\n\nexport type OnNavigateHandler = (e: OnNavigateEvent) => void;\n\n/**\n * Base props shared by all Link variants.\n */\ninterface LinkBaseProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {\n /** Prefetch the RSC payload on hover */\n prefetch?: boolean;\n /**\n * Scroll to top on navigation. Defaults to true.\n * Set to false for tabbed interfaces where content changes within a fixed layout.\n */\n scroll?: boolean;\n /**\n * Preserve search params from the current URL across navigation.\n *\n * - `true` — preserve ALL current search params (target params take precedence)\n * - `string[]` — preserve only the named params (e.g. `['private', 'token']`)\n *\n * Useful for route-group gating where a search param (e.g. `?private=access`)\n * must persist across internal navigations. The target href's own search params\n * always take precedence over preserved ones.\n *\n * During SSR, reads search params from the request context. On the client,\n * reads from the current URL and updates reactively when the URL changes.\n */\n preserveSearchParams?: true | string[];\n /**\n * Called before client-side navigation commits. Call `e.preventDefault()`\n * to cancel the default navigation — the caller is then responsible for\n * navigating (e.g. via `router.push()`).\n *\n * Only fires for client-side SPA navigations, not full page loads.\n * Has no effect during SSR.\n */\n onNavigate?: OnNavigateHandler;\n children?: ReactNode;\n}\n\n// ─── Typed Link Props ────────────────────────────────────────────\n\n/**\n * Widen server-side string params to string | number for Link convenience.\n * Exported for use by codegen-generated overloads.\n */\nexport type LinkSegmentParams<T> = {\n [K in keyof T]: [string] extends [T[K]] ? string | number : T[K];\n};\n\n// ─── External Href Types ─────────────────────────────────────────\n\n/**\n * Href types accepted by the catch-all (non-route) call signature.\n *\n * - External protocols: https://, http://, mailto:, tel:, ftp://\n * - Hash-only and query-only links: #section, ?param=value\n * - Computed `string` variables (non-literal)\n *\n * Internal path literals like \"/typo-route\" do NOT match — they must\n * be a known route (from codegen) or stored in a `string` variable.\n * This catches wrong hrefs at the type level. See TIM-624.\n */\ntype ExternalHref =\n | `http://${string}`\n | `https://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `ftp://${string}`\n | `//${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * Callable interface for the Link component.\n *\n * Two kinds of call signatures:\n * 1. Per-route (added by codegen via interface merging): DIRECT types\n * for segmentParams — preserves TypeScript excess property checking.\n * 2. Catch-all (below): accepts external hrefs and computed `string`\n * variables. Does NOT accept internal path literals — those must\n * match a known route from the codegen.\n *\n * See TIM-624.\n */\nexport interface LinkFunction {\n // External links (literal protocol hrefs)\n (\n props: LinkBaseProps & {\n href: ExternalHref;\n segmentParams?: never;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n }\n ): JSX.Element;\n // Computed/variable href (non-literal string) — e.g. href={myVar}\n // `string extends H` is true only when H is the wide `string` type,\n // not a specific literal. Template literal hrefs like `/blog/${slug}`\n // are handled by resolved-pattern signatures in the codegen.\n <H extends string>(\n props: string extends H\n ? LinkBaseProps & {\n href: H;\n segmentParams?: Record<string, string | number | string[]>;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n }\n : never\n ): JSX.Element;\n}\n\n/**\n * Runtime-only loose props used internally by the Link implementation.\n * Not exposed to callers — the public API uses LinkFunction.\n */\ninterface LinkRuntimeProps extends LinkBaseProps {\n href: string;\n segmentParams?: Record<string, string | number | string[]>;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n}\n\n// Legacy exports for backward compat (used by buildLinkProps, tests, etc.)\nexport type LinkPropsWithHref = LinkBaseProps & {\n href: string;\n segmentParams?: never;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n};\nexport type LinkPropsWithParams = LinkRuntimeProps & {\n segmentParams: Record<string, string | number | string[]>;\n};\nexport type LinkProps = LinkRuntimeProps;\n\n// ─── Dangerous URL Scheme Detection ──────────────────────────────\n\n/**\n * Reject dangerous URL schemes that could execute script.\n * Security: design/13-security.md § Link scheme injection (test #9)\n */\nconst DANGEROUS_SCHEMES = /^\\s*(javascript|data|vbscript):/i;\n\nexport function validateLinkHref(href: string): void {\n if (DANGEROUS_SCHEMES.test(href)) {\n throw new Error(\n `<Link> received a dangerous href: \"${href}\". ` +\n 'javascript:, data:, and vbscript: URLs are not allowed.'\n );\n }\n}\n\n// ─── Internal Link Detection ─────────────────────────────────────\n\n/** Returns true if the href is an internal path (not an external URL) */\nexport function isInternalHref(href: string): boolean {\n // Relative paths, root-relative paths, and hash links are internal\n if (href.startsWith('/') || href.startsWith('#') || href.startsWith('?')) {\n return true;\n }\n // Anything with a protocol scheme is external\n if (/^[a-z][a-z0-9+.-]*:/i.test(href)) {\n return false;\n }\n // Bare relative paths (e.g., \"dashboard\") are internal\n return true;\n}\n\n// ─── URL Interpolation ──────────────────────────────────────────\n\n/**\n * Interpolate dynamic segments in a route pattern with actual values.\n * e.g. interpolateParams(\"/products/[id]\", { id: \"123\" }) → \"/products/123\"\n *\n * Supports:\n * - [param] → single segment\n * - [...param] → catch-all (joined with /)\n * - [[...param]] → optional catch-all (omitted if undefined/empty)\n */\n/**\n * Parse a route pattern's path portion into classified segments.\n * Exported for testing. Uses the shared character-based classifier.\n */\nexport function parseSegments(pattern: string): UrlSegment[] {\n return pattern.split('/').filter(Boolean).map(classifyUrlSegment);\n}\n\n/**\n * Resolve a single classified segment into its string representation.\n * Returns null for optional catch-all with no value (filtered out before join).\n */\nfunction resolveSegment(\n seg: UrlSegment,\n params: Record<string, string | number | string[]>,\n pattern: string\n): string | null {\n switch (seg.kind) {\n case 'static':\n return seg.value;\n\n case 'optional-catch-all': {\n const value = params[seg.name];\n if (value === undefined || (Array.isArray(value) && value.length === 0)) {\n return null;\n }\n const segments = Array.isArray(value) ? value : [value];\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'catch-all': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(\n `<Link> missing required catch-all param \"${seg.name}\" for pattern \"${pattern}\".`\n );\n }\n const segments = Array.isArray(value) ? value : [value];\n if (segments.length === 0) {\n throw new Error(\n `<Link> catch-all param \"${seg.name}\" must have at least one segment for pattern \"${pattern}\".`\n );\n }\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'dynamic': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(`<Link> missing required param \"${seg.name}\" for pattern \"${pattern}\".`);\n }\n if (Array.isArray(value)) {\n throw new Error(\n `<Link> param \"${seg.name}\" expected a string but received an array for pattern \"${pattern}\".`\n );\n }\n return encodeURIComponent(String(value));\n }\n }\n}\n\n/**\n * Split a URL pattern into the path portion and any trailing ?query/#hash suffix.\n * Uses URL parsing for correctness rather than manual index arithmetic.\n */\nfunction splitPatternSuffix(pattern: string): [path: string, suffix: string] {\n if (!pattern.includes('?') && !pattern.includes('#')) {\n return [pattern, ''];\n }\n const url = new URL(pattern, 'http://x');\n const suffix = url.search + url.hash;\n const path = pattern.slice(0, pattern.length - suffix.length);\n return [path, suffix];\n}\n\nexport function interpolateParams(\n pattern: string,\n params: Record<string, string | number | string[]>\n): string {\n const [pathPart, suffix] = splitPatternSuffix(pattern);\n\n const resolved = parseSegments(pathPart)\n .map((seg) => resolveSegment(seg, params, pattern))\n .filter((s): s is string => s !== null);\n return ('/' + resolved.join('/') || '/') + suffix;\n}\n\n// ─── Resolve Href ───────────────────────────────────────────────\n\n/**\n * Resolve the final href string from Link props.\n *\n * Handles:\n * - params interpolation into route patterns\n * - searchParams serialization via SearchParamsDefinition\n * - Validation that searchParams and inline query strings are exclusive\n */\nexport function resolveHref(\n href: string,\n params?: Record<string, string | number | string[]>,\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n }\n): string {\n let resolvedPath = href;\n\n // Interpolate params if provided\n if (params) {\n resolvedPath = interpolateParams(href, params);\n }\n\n // Serialize searchParams if provided\n if (searchParams) {\n // Validate: searchParams prop and inline query string are mutually exclusive\n if (resolvedPath.includes('?')) {\n throw new Error(\n '<Link> received both a searchParams prop and a query string in href. ' +\n 'These are mutually exclusive — use one or the other.'\n );\n }\n\n const qs = searchParams.definition.serialize(searchParams.values);\n if (qs) {\n resolvedPath = `${resolvedPath}?${qs}`;\n }\n }\n\n return resolvedPath;\n}\n\n// ─── Build Props ─────────────────────────────────────────────────\n\ninterface LinkOutputProps {\n href: string;\n}\n\n/**\n * Build the HTML attributes for a Link. Separated from the component\n * for testability — the component just spreads these onto an <a>.\n */\nexport function buildLinkProps(\n props: Pick<LinkPropsWithHref, 'href'> & {\n params?: Record<string, string | number | string[]>;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n }\n): LinkOutputProps {\n const resolvedHref = resolveHref(props.href, props.params, props.searchParams);\n validateLinkHref(resolvedHref);\n return { href: resolvedHref };\n}\n\n// ─── Click Handler ───────────────────────────────────────────────\n\n/**\n * Should this click be intercepted for SPA navigation?\n *\n * Returns false (pass through to browser) when:\n * - Modified keys are held (Ctrl, Meta, Shift, Alt) — open in new tab\n * - The click is not the primary button\n * - The event was already prevented by a parent handler\n * - The link has target=\"_blank\" or similar\n * - The link has a download attribute\n * - The href is external\n */\nfunction shouldInterceptClick(\n event: ReactMouseEvent<HTMLAnchorElement>,\n resolvedHref: string\n): boolean {\n if (event.button !== 0) return false;\n if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;\n if (event.defaultPrevented) return false;\n\n const anchor = event.currentTarget;\n if (anchor.target && anchor.target !== '_self') return false;\n if (anchor.hasAttribute('download')) return false;\n\n if (!isInternalHref(resolvedHref)) return false;\n\n return true;\n}\n\n// ─── Link Component ──────────────────────────────────────────────\n\n/**\n * Navigation link with progressive enhancement.\n *\n * Renders as a plain `<a>` tag — works without JavaScript. When the client\n * runtime is active, the Link's onClick handler triggers RSC-based client\n * navigation via the router. No global event delegation — each Link owns\n * its own click handling.\n *\n * Supports typed routes via the Routes interface (populated by codegen).\n * At runtime:\n * - `segmentParams` prop interpolates dynamic segments in the href pattern\n * - `searchParams` prop serializes query parameters via a SearchParamsDefinition\n *\n * Typed via the LinkFunction callable interface. The base call signature\n * forbids segmentParams; per-route signatures are added by codegen via\n * interface merging. See TIM-624.\n */\n// Cast to LinkFunction — the callable interface provides the public type,\n// but the implementation destructures LinkRuntimeProps internally.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const Link: LinkFunction = function LinkImpl(props: any) {\n const {\n href,\n prefetch,\n scroll,\n segmentParams,\n searchParams,\n preserveSearchParams,\n onNavigate,\n onClick: userOnClick,\n onMouseEnter: userOnMouseEnter,\n children,\n ...rest\n } = props as LinkRuntimeProps;\n const { href: baseHref } = buildLinkProps({ href, params: segmentParams, searchParams });\n\n // ─── Per-link pending state (useOptimistic) ────────────────────────\n // Each Link has its own pending state. Only the clicked link's\n // setter is invoked during navigation — zero other links re-render.\n //\n // Link click stores the instance; NavigationRoot activates inside startTransition.\n // useOptimistic auto-reverts to LINK_IDLE when the navigation\n // startTransition — batched with the new tree commit.\n //\n // See design/19-client-navigation.md §\"Per-Link Pending State\"\n const [linkStatus, setIsPending] = useOptimistic(LINK_IDLE);\n\n // Build the link instance ref for the pending store.\n // The ref is stable across renders — we update the setter on each\n // render to keep it current.\n const linkInstanceRef = useRef<LinkPendingInstance | null>(null);\n if (!linkInstanceRef.current) {\n linkInstanceRef.current = { setIsPending };\n } else {\n linkInstanceRef.current.setIsPending = setIsPending;\n }\n\n // Clean up if this link unmounts while it's the current navigation link.\n // Prevents calling setOptimistic on an unmounted component.\n useEffect(() => {\n const instance = linkInstanceRef.current;\n return () => {\n if (instance) {\n unmountLinkForCurrentNavigation(instance);\n }\n };\n }, []);\n\n // Preserve search params from the current URL when requested.\n // useSearchParams() works during both SSR (reads from request context)\n // and on the client (reads from window.location, reactive to URL changes).\n // We read current search params directly to avoid unconditional hook calls.\n // On the client, window.location.search is always current; during SSR,\n // getSsrData() provides the request's search params.\n const resolvedHref = preserveSearchParams\n ? mergePreservedSearchParams(baseHref, getCurrentSearch(), preserveSearchParams)\n : baseHref;\n\n const internal = isInternalHref(resolvedHref);\n\n // ─── Click handler ───────────────────────────────────────────\n // Each Link component owns its click handling. The router is\n // accessed via the singleton ref — during SSR, getRouterOrNull()\n // returns null and onClick is a no-op (the <a> works as a plain link).\n const handleClick = internal\n ? (event: ReactMouseEvent<HTMLAnchorElement>) => {\n // Call user's onClick first (e.g., analytics)\n userOnClick?.(event);\n\n if (!shouldInterceptClick(event, resolvedHref)) return;\n\n // Call onNavigate if provided — allows caller to cancel\n if (onNavigate) {\n let prevented = false;\n onNavigate({\n preventDefault: () => {\n prevented = true;\n },\n });\n if (prevented) {\n event.preventDefault();\n return;\n }\n }\n\n const router = getRouterOrNull();\n if (!router) return; // SSR or pre-hydration — fall through to browser nav\n\n const shouldScroll = scroll !== false;\n\n // Register this link in the pending store. The actual\n // setIsPending(LINK_PENDING) call happens inside NavigationRoot's\n // async startTransition via activateLinkPending().\n\n setLinkForCurrentNavigation(linkInstanceRef.current);\n\n // When Navigation API is active, let the <a> click propagate\n // naturally — do NOT call preventDefault(). The navigate event\n // handler intercepts it and runs the RSC pipeline. This is a\n // user-initiated navigation, so Chrome shows the native loading\n // indicator (tab spinner). Metadata (scroll, link instance) is\n // passed via nav-link-store so the handler can configure the nav.\n //\n // Without Navigation API (fallback), preventDefault and drive\n // navigation through the router as before.\n if (hasNavigationApi()) {\n setNavLinkMetadata({\n scroll: shouldScroll,\n linkInstance: linkInstanceRef.current,\n });\n // Don't preventDefault — let the <a> click fire the navigate event\n return;\n }\n\n // History API fallback — prevent default and navigate via router\n event.preventDefault();\n\n // Re-merge preserved search params at click time to pick up any\n // URL changes since render (e.g. from other navigations or pushState).\n const navHref = preserveSearchParams\n ? mergePreservedSearchParams(baseHref, getCurrentSearch(), preserveSearchParams)\n : resolvedHref;\n\n void router.navigate(navHref, { scroll: shouldScroll });\n }\n : userOnClick; // External links — just pass through user's onClick\n\n // ─── Hover prefetch ──────────────────────────────────────────\n const handleMouseEnter =\n internal && prefetch\n ? (event: ReactMouseEvent<HTMLAnchorElement>) => {\n userOnMouseEnter?.(event);\n const router = getRouterOrNull();\n if (router) {\n // Re-merge preserved search params at hover time for fresh prefetch URL\n const prefetchHref = preserveSearchParams\n ? mergePreservedSearchParams(baseHref, getCurrentSearch(), preserveSearchParams)\n : resolvedHref;\n router.prefetch(prefetchHref);\n }\n }\n : userOnMouseEnter;\n\n return (\n <a {...rest} href={resolvedHref} onClick={handleClick} onMouseEnter={handleMouseEnter}>\n <LinkStatusContext.Provider value={linkStatus}>{children}</LinkStatusContext.Provider>\n </a>\n );\n};\n","// usePendingNavigation — returns true while an RSC navigation is in flight.\n// See design/19-client-navigation.md §\"usePendingNavigation()\"\n//\n// Reads from PendingNavigationContext (provided by NavigationRoot) so the\n// pending state shows immediately (urgent update) and clears atomically\n// with the new tree (same startTransition commit).\n\nimport { usePendingNavigationUrl } from './navigation-context.js';\n\n/**\n * Returns true while an RSC navigation is in flight.\n *\n * The pending state is true from the moment the RSC fetch starts until\n * React reconciliation completes. This includes the fetch itself,\n * RSC stream parsing, and React tree reconciliation.\n *\n * It does NOT include Suspense streaming after the shell — only the\n * initial shell reconciliation.\n *\n * ```tsx\n * 'use client'\n * import { usePendingNavigation } from '@timber-js/app/client'\n *\n * export function NavBar() {\n * const isPending = usePendingNavigation()\n * return (\n * <nav className={isPending ? 'opacity-50' : ''}>\n * <Link href=\"/dashboard\">Dashboard</Link>\n * </nav>\n * )\n * }\n * ```\n */\nexport function usePendingNavigation(): boolean {\n const pendingUrl = usePendingNavigationUrl();\n // During SSR or outside PendingNavigationProvider, no navigation is pending\n return pendingUrl !== null;\n}\n","/**\n * useRouter() — client-side hook for programmatic navigation.\n *\n * Returns a router instance with push, replace, refresh, back, forward,\n * and prefetch methods. Compatible with Next.js's `useRouter()` from\n * `next/navigation` (App Router).\n *\n * This wraps timber's internal RouterInstance in the Next.js-compatible\n * AppRouterInstance shape that ecosystem libraries expect.\n *\n * NOTE: Unlike Next.js, these methods do NOT wrap navigation in\n * startTransition. In Next.js, router state is React state (useReducer)\n * so startTransition defers the update and provides isPending tracking.\n * In timber, navigation calls reactRoot.render() which is a root-level\n * render — startTransition has no effect on root renders.\n *\n * Navigation state (params, pathname) is delivered atomically via\n * NavigationContext embedded in the element tree passed to\n * reactRoot.render(). See design/19-client-navigation.md §\"NavigationContext\".\n *\n * For loading UI during navigation, use:\n * - useLinkStatus() — per-link pending indicator (inside <Link>)\n * - usePendingNavigation() — global navigation pending state\n */\n\nimport { getRouterOrNull } from './router-ref.js';\n\nexport interface AppRouterInstance {\n /** Navigate to a URL, pushing a new history entry */\n push(href: string, options?: { scroll?: boolean }): void;\n /** Navigate to a URL, replacing the current history entry */\n replace(href: string, options?: { scroll?: boolean }): void;\n /** Refresh the current page (re-fetch RSC payload) */\n refresh(): void;\n /** Navigate back in history */\n back(): void;\n /** Navigate forward in history */\n forward(): void;\n /** Prefetch an RSC payload for a URL */\n prefetch(href: string): void;\n}\n\n/**\n * Get a router instance for programmatic navigation.\n *\n * Compatible with Next.js's `useRouter()` from `next/navigation`.\n *\n * Methods lazily resolve the global router when invoked (during user\n * interaction) rather than capturing it at render time. This is critical\n * because during hydration, React synchronously executes component render\n * functions *before* the router is bootstrapped in browser-entry.ts.\n * If we eagerly captured the router during render, components would get\n * a null reference and be stuck with silent no-ops forever.\n *\n * Returns safe no-ops during SSR or before bootstrap. The `typeof window`\n * check is insufficient because Vite's client SSR environment defines\n * `window`, so we use a try/catch on getRouter() — but only at method\n * invocation time, not at render time.\n */\nexport function useRouter(): AppRouterInstance {\n return {\n push(href: string, options?: { scroll?: boolean }) {\n const router = getRouterOrNull();\n if (!router) {\n if (process.env.NODE_ENV === 'development') {\n console.error(\n '[timber] useRouter().push() called but router is not initialized. This is a bug — please report it.'\n );\n }\n return;\n }\n void router.navigate(href, { scroll: options?.scroll });\n },\n replace(href: string, options?: { scroll?: boolean }) {\n const router = getRouterOrNull();\n if (!router) {\n if (process.env.NODE_ENV === 'development') {\n console.error('[timber] useRouter().replace() called but router is not initialized.');\n }\n return;\n }\n void router.navigate(href, { scroll: options?.scroll, replace: true });\n },\n refresh() {\n const router = getRouterOrNull();\n if (!router) {\n if (process.env.NODE_ENV === 'development') {\n console.error('[timber] useRouter().refresh() called but router is not initialized.');\n }\n return;\n }\n void router.refresh();\n },\n back() {\n if (typeof window !== 'undefined') window.history.back();\n },\n forward() {\n if (typeof window !== 'undefined') window.history.forward();\n },\n prefetch(href: string) {\n const router = getRouterOrNull();\n if (!router) return; // Silent — prefetch failure is non-fatal\n router.prefetch(href);\n },\n };\n}\n","/**\n * usePathname() — client-side hook for reading the current pathname.\n *\n * Returns the pathname portion of the current URL (e.g. '/dashboard/settings').\n * Updates when client-side navigation changes the URL.\n *\n * On the client, reads from NavigationContext which is updated atomically\n * with the RSC tree render. This replaces the previous useSyncExternalStore\n * approach which only subscribed to popstate events — meaning usePathname()\n * did NOT re-render on forward navigation (pushState). The context approach\n * fixes this: pathname updates in the same render pass as the new tree.\n *\n * During SSR, reads the request pathname from the SSR ALS context\n * (populated by ssr-entry.ts) instead of window.location.\n *\n * Compatible with Next.js's `usePathname()` from `next/navigation`.\n */\n\nimport { getSsrData } from './ssr-data.js';\nimport { useNavigationContext } from './navigation-context.js';\n\n/**\n * Read the current URL pathname.\n *\n * On the client, reads from NavigationContext (provided by\n * NavigationProvider in renderRoot). During SSR, reads from the\n * ALS-backed SSR data context. Falls back to window.location.pathname\n * when called outside a React component (e.g., in tests).\n */\nexport function usePathname(): string {\n // Try reading from NavigationContext (client-side, inside React tree).\n // During SSR, no NavigationProvider is mounted, so this returns null.\n try {\n const navContext = useNavigationContext();\n if (navContext !== null) {\n return navContext.pathname;\n }\n } catch {\n // No React dispatcher available (called outside a component).\n // Fall through to SSR/fallback below.\n }\n\n // SSR path: read from ALS-backed SSR data context.\n const ssrData = getSsrData();\n if (ssrData) return ssrData.pathname ?? '/';\n\n // Final fallback: window.location (tests, edge cases).\n if (typeof window !== 'undefined') return window.location.pathname;\n return '/';\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * This is a thin wrapper over window.location.search, provided for\n * Next.js API compatibility (libraries like nuqs import useSearchParams\n * from next/navigation).\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * During SSR, reads the request search params from the SSR ALS context\n * (populated by ssr-entry.ts) instead of window.location.\n *\n * All mutable state is delegated to client/state.ts for singleton guarantees.\n * See design/18-build-system.md §\"Singleton State Registry\"\n */\n\nimport { useSyncExternalStore } from 'react';\nimport { getSsrData } from './ssr-data.js';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.js';\n\nfunction getSearch(): string {\n if (typeof window !== 'undefined') return window.location.search;\n const data = getSsrData();\n if (!data) return '';\n const sp = new URLSearchParams(data.searchParams);\n const str = sp.toString();\n return str ? `?${str}` : '';\n}\n\nfunction getServerSearch(): string {\n const data = getSsrData();\n if (!data) return '';\n const sp = new URLSearchParams(data.searchParams);\n const str = sp.toString();\n return str ? `?${str}` : '';\n}\n\nfunction subscribe(callback: () => void): () => void {\n window.addEventListener('popstate', callback);\n return () => window.removeEventListener('popstate', callback);\n}\n\n// Cache the last search string and its parsed URLSearchParams to avoid\n// creating a new object on every render when the URL hasn't changed.\n// State lives in client/state.ts for singleton guarantees.\n\nfunction getSearchParams(): URLSearchParams {\n const search = getSearch();\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\nfunction getServerSearchParams(): URLSearchParams {\n const data = getSsrData();\n return data ? new URLSearchParams(data.searchParams) : new URLSearchParams();\n}\n\n/**\n * Read the current URL search params.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n // useSyncExternalStore needs a primitive snapshot for comparison.\n // We use the raw search string as the snapshot, then return the\n // parsed URLSearchParams.\n useSyncExternalStore(subscribe, getSearch, getServerSearch);\n return typeof window !== 'undefined' ? getSearchParams() : getServerSearchParams();\n}\n","/**\n * useSelectedLayoutSegment / useSelectedLayoutSegments — client-side hooks\n * for reading the active segment(s) below the current layout.\n *\n * These hooks are used by navigation UIs to highlight active sections.\n * They match Next.js's API from next/navigation.\n *\n * How they work:\n * 1. Each layout is wrapped with a SegmentProvider that records its depth\n * (the URL segments from root to that layout level).\n * 2. The hooks read the current URL pathname via usePathname().\n * 3. They compare the layout's segment depth against the full URL segments\n * to determine which child segments are \"selected\" below.\n *\n * Example: For URL \"/dashboard/settings/profile\"\n * - Root layout (depth 0, segments: ['']): selected segment = \"dashboard\"\n * - Dashboard layout (depth 1, segments: ['', 'dashboard']): selected = \"settings\"\n * - Settings layout (depth 2, segments: ['', 'dashboard', 'settings']): selected = \"profile\"\n *\n * Design docs: design/19-client-navigation.md, design/14-ecosystem.md\n */\n\n'use client';\n\nimport { useSegmentContext } from './segment-context.js';\nimport { usePathname } from './use-pathname.js';\n\n/**\n * Split a pathname into URL segments.\n * \"/\" → [\"\"]\n * \"/dashboard\" → [\"\", \"dashboard\"]\n * \"/dashboard/settings\" → [\"\", \"dashboard\", \"settings\"]\n */\nexport function pathnameToSegments(pathname: string): string[] {\n return pathname.split('/');\n}\n\n/**\n * Pure function: compute the selected child segment given a layout's segment\n * depth and the current URL pathname.\n *\n * @param contextSegments — segments from root to the calling layout, or null if no context\n * @param pathname — current URL pathname\n * @returns the active child segment one level below, or null if at the leaf\n */\nexport function getSelectedSegment(\n contextSegments: string[] | null,\n pathname: string\n): string | null {\n const urlSegments = pathnameToSegments(pathname);\n\n if (!contextSegments) {\n return urlSegments[1] || null;\n }\n\n const depth = contextSegments.length;\n return urlSegments[depth] || null;\n}\n\n/**\n * Pure function: compute all selected segments below a layout's depth.\n *\n * @param contextSegments — segments from root to the calling layout, or null if no context\n * @param pathname — current URL pathname\n * @returns all active segments below the layout\n */\nexport function getSelectedSegments(contextSegments: string[] | null, pathname: string): string[] {\n const urlSegments = pathnameToSegments(pathname);\n\n if (!contextSegments) {\n return urlSegments.slice(1).filter(Boolean);\n }\n\n const depth = contextSegments.length;\n return urlSegments.slice(depth).filter(Boolean);\n}\n\n/**\n * Returns the active child segment one level below the layout where this\n * hook is called. Returns `null` if the layout is the leaf (no child segment).\n *\n * Compatible with Next.js's `useSelectedLayoutSegment()` from `next/navigation`.\n *\n * @param parallelRouteKey — Optional parallel route key. Currently unused\n * (parallel route segment tracking is not yet implemented). Accepted for\n * API compatibility with Next.js.\n */\nexport function useSelectedLayoutSegment(parallelRouteKey?: string): string | null {\n void parallelRouteKey;\n const context = useSegmentContext();\n const pathname = usePathname();\n return getSelectedSegment(context?.segments ?? null, pathname);\n}\n\n/**\n * Returns all active segments below the layout where this hook is called.\n * Returns an empty array if the layout is the leaf (no child segments).\n *\n * Compatible with Next.js's `useSelectedLayoutSegments()` from `next/navigation`.\n *\n * @param parallelRouteKey — Optional parallel route key. Currently unused\n * (parallel route segment tracking is not yet implemented). Accepted for\n * API compatibility with Next.js.\n */\nexport function useSelectedLayoutSegments(parallelRouteKey?: string): string[] {\n void parallelRouteKey;\n const context = useSegmentContext();\n const pathname = usePathname();\n return getSelectedSegments(context?.segments ?? null, pathname);\n}\n","/**\n * Client-side form utilities for server actions.\n *\n * Exports a typed `useActionState` that understands the action builder's result shape.\n * Result is typed to:\n * { data: T } | { validationErrors: Record<string, string[]> } | { serverError: { code, data? } } | null\n *\n * The action builder emits a function that satisfies both the direct call signature\n * and React's `(prevState, formData) => Promise<State>` contract.\n *\n * See design/08-forms-and-actions.md §\"Client-Side Form Mechanics\"\n */\n\nimport { useActionState as reactUseActionState, useTransition } from 'react';\nimport type { ActionFn, ActionResult, InputHint, ValidationErrors } from '../server/action-client';\nimport type { FormFlashData } from '../server/form-flash';\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\n/**\n * The action function type accepted by useActionState.\n * Must satisfy React's (prevState, formData) => Promise<State> contract.\n */\nexport type UseActionStateFn<TData> = (\n prevState: ActionResult<TData> | null,\n formData: FormData\n) => Promise<ActionResult<TData>>;\n\n/**\n * Return type of useActionState — matches React 19's useActionState return.\n * [result, formAction, isPending]\n */\nexport type UseActionStateReturn<TData> = [\n result: ActionResult<TData> | null,\n formAction: (formData: FormData) => void,\n isPending: boolean,\n];\n\n// ─── useActionState ──────────────────────────────────────────────────────\n\n/**\n * Typed wrapper around React 19's `useActionState` that understands\n * the timber action builder's result shape.\n *\n * @param action - A server action created with createActionClient or a raw 'use server' function.\n * @param initialState - Initial state, typically `null`. Pass `getFormFlash()` for no-JS\n * progressive enhancement — the flash seeds the initial state so the form has a\n * single source of truth for both with-JS and no-JS paths.\n * @param permalink - Optional permalink for progressive enhancement (no-JS fallback URL).\n *\n * @example\n * ```tsx\n * 'use client'\n * import { useActionState } from '@timber-js/app/client'\n * import { createTodo } from './actions'\n *\n * export function NewTodoForm({ flash }) {\n * const [result, action, isPending] = useActionState(createTodo, flash)\n * return (\n * <form action={action}>\n * <input name=\"title\" />\n * {result?.validationErrors?.title && <p>{result.validationErrors.title}</p>}\n * <button disabled={isPending}>Add</button>\n * </form>\n * )\n * }\n * ```\n */\nexport function useActionState<TData>(\n action: UseActionStateFn<TData>,\n initialState: ActionResult<TData> | FormFlashData | null,\n permalink?: string\n): UseActionStateReturn<TData> {\n // FormFlashData is structurally compatible with ActionResult at runtime —\n // the cast satisfies React's generic inference which would otherwise widen TData.\n return reactUseActionState(action, initialState as ActionResult<TData> | null, permalink);\n}\n\n// ─── useFormAction ───────────────────────────────────────────────────────\n\n/**\n * Hook for calling a server action imperatively (not via a form).\n * Returns [execute, isPending] where execute accepts the input directly.\n *\n * @example\n * ```tsx\n * const [deleteTodo, isPending] = useFormAction(deleteTodoAction)\n * <button onClick={() => deleteTodo({ id: todo.id })} disabled={isPending}>\n * Delete\n * </button>\n * ```\n */\nexport function useFormAction<TData = unknown, TInput = unknown>(\n action: ActionFn<TData, TInput> | ((input: TInput) => Promise<ActionResult<TData>>)\n): [\n (\n ...args: undefined extends TInput ? [input?: InputHint<TInput>] : [input: InputHint<TInput>]\n ) => Promise<ActionResult<TData>>,\n boolean,\n] {\n const [isPending, startTransition] = useTransition();\n\n const execute = (input?: InputHint<TInput>): Promise<ActionResult<TData>> => {\n return new Promise((resolve) => {\n startTransition(async () => {\n const result = await (action as (input: InputHint<TInput>) => Promise<ActionResult<TData>>)(\n input as InputHint<TInput>\n );\n resolve(result);\n });\n });\n };\n\n return [execute, isPending];\n}\n\n// ─── useFormErrors ──────────────────────────────────────────────────────\n\n/** Return type of useFormErrors(). */\nexport interface FormErrorsResult {\n /** Per-field validation errors keyed by field name. */\n fieldErrors: Record<string, string[]>;\n /** Form-level errors (from `_root` key). */\n formErrors: string[];\n /** Server error if the action threw an ActionError. */\n serverError: { code: string; data?: Record<string, unknown> } | null;\n /** Whether any errors are present. */\n hasErrors: boolean;\n /** Get the first error message for a field, or null. */\n getFieldError: (field: string) => string | null;\n}\n\n/**\n * Extract per-field and form-level errors from an ActionResult.\n *\n * Pure function (no internal hooks) — follows React naming convention\n * since it's used in render. Accepts the result from `useActionState`\n * or flash data from `getFormFlash()`.\n *\n * @example\n * ```tsx\n * const [result, action, isPending] = useActionState(createTodo, null)\n * const errors = useFormErrors(result)\n *\n * return (\n * <form action={action}>\n * <input name=\"title\" />\n * {errors.getFieldError('title') && <p>{errors.getFieldError('title')}</p>}\n * {errors.formErrors.map(e => <p key={e}>{e}</p>)}\n * </form>\n * )\n * ```\n */\nexport function useFormErrors<TData>(\n result:\n | ActionResult<TData>\n | {\n validationErrors?: ValidationErrors;\n serverError?: { code: string; data?: Record<string, unknown> };\n }\n | null\n): FormErrorsResult {\n const empty: FormErrorsResult = {\n fieldErrors: {},\n formErrors: [],\n serverError: null,\n hasErrors: false,\n getFieldError: () => null,\n };\n\n if (!result) return empty;\n\n const validationErrors = result.validationErrors as ValidationErrors | undefined;\n const serverError = result.serverError as\n | { code: string; data?: Record<string, unknown> }\n | undefined;\n\n if (!validationErrors && !serverError) return empty;\n\n // Separate _root (form-level) errors from field errors\n const fieldErrors: Record<string, string[]> = {};\n const formErrors: string[] = [];\n\n if (validationErrors) {\n for (const [key, messages] of Object.entries(validationErrors)) {\n if (key === '_root') {\n formErrors.push(...messages);\n } else {\n fieldErrors[key] = messages;\n }\n }\n }\n\n const hasErrors =\n Object.keys(fieldErrors).length > 0 || formErrors.length > 0 || serverError != null;\n\n return {\n fieldErrors,\n formErrors,\n serverError: serverError ?? null,\n hasErrors,\n getFieldError(field: string): string | null {\n const errs = fieldErrors[field];\n return errs && errs.length > 0 ? errs[0] : null;\n },\n };\n}\n","/**\n * useCookie — reactive client-side cookie hook.\n *\n * Uses useSyncExternalStore for SSR-safe, reactive cookie access.\n * All components reading the same cookie name re-render on change.\n * No cross-tab sync (intentional — see design/29-cookies.md).\n *\n * See design/29-cookies.md §\"useCookie(name) Hook\"\n */\n\nimport { useSyncExternalStore } from 'react';\nimport { getSsrData } from './ssr-data.js';\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\nexport interface ClientCookieOptions {\n /** URL path scope. Default: '/'. */\n path?: string;\n /** Domain scope. Default: omitted (current domain). */\n domain?: string;\n /** Max age in seconds. */\n maxAge?: number;\n /** Expiration date. */\n expires?: Date;\n /** Cross-site policy. Default: 'lax'. */\n sameSite?: 'strict' | 'lax' | 'none';\n /** Only send over HTTPS. Default: true in production. */\n secure?: boolean;\n}\n\nexport type CookieSetter = (value: string, options?: ClientCookieOptions) => void;\n\n// ─── Module-Level Cookie Store ────────────────────────────────────────────\n\ntype Listener = () => void;\n\n/** Per-name subscriber sets. */\nconst listeners = new Map<string, Set<Listener>>();\n\n/** Parse a cookie name from document.cookie. */\nfunction getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n const match = document.cookie.match(\n new RegExp('(?:^|;\\\\s*)' + name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') + '\\\\s*=\\\\s*([^;]*)')\n );\n return match ? decodeURIComponent(match[1]) : undefined;\n}\n\n/** Serialize options into a cookie string suffix. */\nfunction serializeOptions(options?: ClientCookieOptions): string {\n if (!options) return '; Path=/; SameSite=Lax';\n const parts: string[] = [];\n parts.push(`Path=${options.path ?? '/'}`);\n if (options.domain) parts.push(`Domain=${options.domain}`);\n if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);\n if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);\n const sameSite = options.sameSite ?? 'lax';\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);\n if (options.secure) parts.push('Secure');\n return '; ' + parts.join('; ');\n}\n\n/** Notify all subscribers for a given cookie name. */\nfunction notify(name: string): void {\n const subs = listeners.get(name);\n if (subs) {\n for (const fn of subs) fn();\n }\n}\n\n// ─── Hook ─────────────────────────────────────────────────────────────────\n\n/**\n * Reactive hook for reading/writing a client-side cookie.\n *\n * Returns `[value, setCookie, deleteCookie]`:\n * - `value`: current cookie value (string | undefined)\n * - `setCookie`: sets the cookie and triggers re-renders\n * - `deleteCookie`: deletes the cookie and triggers re-renders\n *\n * @param name - Cookie name.\n * @param defaultOptions - Default options for setCookie calls.\n */\nexport function useCookie(\n name: string,\n defaultOptions?: ClientCookieOptions\n): [value: string | undefined, setCookie: CookieSetter, deleteCookie: () => void] {\n const subscribe = (callback: Listener): (() => void) => {\n let subs = listeners.get(name);\n if (!subs) {\n subs = new Set();\n listeners.set(name, subs);\n }\n subs.add(callback);\n return () => {\n subs!.delete(callback);\n if (subs!.size === 0) listeners.delete(name);\n };\n };\n\n const getSnapshot = (): string | undefined => getCookieValue(name);\n const getServerSnapshot = (): string | undefined => getSsrData()?.cookies.get(name);\n\n const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n\n const setCookie: CookieSetter = (newValue: string, options?: ClientCookieOptions) => {\n const merged = { ...defaultOptions, ...options };\n document.cookie = `${name}=${encodeURIComponent(newValue)}${serializeOptions(merged)}`;\n notify(name);\n };\n\n const deleteCookie = (): void => {\n const path = defaultOptions?.path ?? '/';\n const domain = defaultOptions?.domain;\n let cookieStr = `${name}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=${path}`;\n if (domain) cookieStr += `; Domain=${domain}`;\n document.cookie = cookieStr;\n notify(name);\n };\n\n return [value, setCookie, deleteCookie];\n}\n","// @timber-js/app/client — Client-side primitives\n// These are the primary imports for client components.\n//\n// Framework-internal bootstrap, SSR bridge, and segment plumbing is in\n// #client-internal (Node package import).\n// Design doc: design/triage/api-naming-spike.md §8.5\n\n// JsonSerializable moved to @timber-js/app/codec as the single canonical path.\n// Re-export removed per TIM-721.\nexport type { RenderErrorDigest } from './types';\n\n// Navigation\nexport { Link, interpolateParams, resolveHref, validateLinkHref, buildLinkProps } from './link';\nexport { mergePreservedSearchParams } from '../shared/merge-search-params.js';\nexport type { LinkFunction, LinkProps, LinkPropsWithHref, LinkPropsWithParams } from './link';\nexport type { LinkSegmentParams, OnNavigateHandler, OnNavigateEvent } from './link';\nexport { usePendingNavigation } from './use-pending-navigation';\nexport { useLinkStatus, LinkStatusContext } from './use-link-status';\nexport type { LinkStatus } from './use-link-status';\nexport { useRouter } from './use-router';\nexport type { AppRouterInstance } from './use-router';\nexport { usePathname } from './use-pathname';\nexport { useSearchParams } from './use-search-params';\nexport { useSelectedLayoutSegment, useSelectedLayoutSegments } from './use-selected-layout-segment';\n\n// Forms\nexport { useActionState, useFormAction, useFormErrors } from './form';\nexport type { UseActionStateFn, UseActionStateReturn, FormErrorsResult } from './form';\n\n// Params\nexport { useSegmentParams } from './use-params';\n\n// Query states (URL-synced search params)\nexport { useQueryStates } from './use-query-states';\n\n// Cookies\nexport { useCookie } from './use-cookie';\nexport type { ClientCookieOptions, CookieSetter } from './use-cookie';\n\n// Register the client cookie module with defineCookie's lazy reference.\n// This runs at module load time in the client/SSR environment, wiring up\n// the useCookie hook without a top-level import in define-cookie.ts.\nimport * as _useCookieMod from './use-cookie.js';\nimport { _registerUseCookieModule } from '../cookies/define-cookie.js';\n_registerUseCookieModule(_useCookieMod);\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,IAAa,oBAAoB,cAA0B,EAAE,WAAW,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BhF,SAAgB,gBAA4B;AAC1C,QAAO,WAAW,kBAAkB;;;;;;;ACXtC,SAAgB,mBAAmB,UAAiC;;;;;;;ACJpE,SAAgB,mBAA4B;AAC1C,QACE,OAAO,WAAW,eAClB,gBAAgB,UACf,OAA8C,cAAc;;;;;;;;;ACkBjE,SAAS,mBAA2B;AAClC,KAAI,OAAO,WAAW,YAAa,QAAO,OAAO,SAAS;CAC1D,MAAM,OAAO,YAAY;AACzB,KAAI,CAAC,KAAM,QAAO;CAElB,MAAM,MADK,IAAI,gBAAgB,KAAK,aAAa,CAClC,UAAU;AACzB,QAAO,MAAM,IAAI,QAAQ;;;;;;AA4J3B,IAAM,oBAAoB;AAE1B,SAAgB,iBAAiB,MAAoB;AACnD,KAAI,kBAAkB,KAAK,KAAK,CAC9B,OAAM,IAAI,MACR,sCAAsC,KAAK,4DAE5C;;;AAOL,SAAgB,eAAe,MAAuB;AAEpD,KAAI,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI,CACtE,QAAO;AAGT,KAAI,uBAAuB,KAAK,KAAK,CACnC,QAAO;AAGT,QAAO;;;;;;;;;;;;;;;AAkBT,SAAgB,cAAc,SAA+B;AAC3D,QAAO,QAAQ,MAAM,IAAI,CAAC,OAAO,QAAQ,CAAC,IAAI,mBAAmB;;;;;;AAOnE,SAAS,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,KAAI;;;;;;;;;;;;;AAiB/B,SAAgB,UACd,MACA,gBACgF;CAChF,MAAM,aAAa,aAAqC;EACtD,IAAI,OAAO,UAAU,IAAI,KAAK;AAC9B,MAAI,CAAC,MAAM;AACT,0BAAO,IAAI,KAAK;AAChB,aAAU,IAAI,MAAM,KAAK;;AAE3B,OAAK,IAAI,SAAS;AAClB,eAAa;AACX,QAAM,OAAO,SAAS;AACtB,OAAI,KAAM,SAAS,EAAG,WAAU,OAAO,KAAK;;;CAIhD,MAAM,oBAAwC,eAAe,KAAK;CAClE,MAAM,0BAA8C,YAAY,EAAE,QAAQ,IAAI,KAAK;CAEnF,MAAM,QAAQ,qBAAqB,WAAW,aAAa,kBAAkB;CAE7E,MAAM,aAA2B,UAAkB,YAAkC;EACnF,MAAM,SAAS;GAAE,GAAG;GAAgB,GAAG;GAAS;AAChD,WAAS,SAAS,GAAG,KAAK,GAAG,mBAAmB,SAAS,GAAG,iBAAiB,OAAO;AACpF,SAAO,KAAK;;CAGd,MAAM,qBAA2B;EAC/B,MAAM,OAAO,gBAAgB,QAAQ;EACrC,MAAM,SAAS,gBAAgB;EAC/B,IAAI,YAAY,GAAG,KAAK,4DAA4D;AACpF,MAAI,OAAQ,cAAa,YAAY;AACrC,WAAS,SAAS;AAClB,SAAO,KAAK;;AAGd,QAAO;EAAC;EAAO;EAAW;EAAa;;;;AC5EzC,yBAAyB,mBAAc"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/client/use-link-status.ts","../../src/client/nav-link-store.ts","../../src/client/navigation-api.ts","../../src/client/link.tsx","../../src/client/use-pending-navigation.ts","../../src/client/use-router.ts","../../src/client/use-pathname.ts","../../src/client/use-search-params.ts","../../src/client/use-selected-layout-segment.ts","../../src/client/form.tsx","../../src/client/use-cookie.ts","../../src/client/index.ts"],"sourcesContent":["'use client';\n\n// useLinkStatus — returns { isPending: true } while the nearest parent <Link>'s\n// navigation is in flight. No arguments — scoped via React context.\n// See design/19-client-navigation.md §\"useLinkStatus()\"\n\nimport { useContext, createContext } from 'react';\n\nexport interface LinkStatus {\n isPending: boolean;\n}\n\n/**\n * React context provided by <Link>. Holds the pending status\n * for that specific link's navigation.\n */\nexport const LinkStatusContext = createContext<LinkStatus>({ isPending: false });\n\n/**\n * Returns `{ isPending: true }` while the nearest parent `<Link>` component's\n * navigation is in flight. Must be used inside a `<Link>` component's children.\n *\n * Unlike `usePendingNavigation()` which is global, this hook is scoped to\n * the nearest parent `<Link>` — only the link the user clicked shows pending.\n *\n * ```tsx\n * 'use client'\n * import { Link, useLinkStatus } from '@timber-js/app/client'\n *\n * function Hint() {\n * const { isPending } = useLinkStatus()\n * return <span className={isPending ? 'opacity-50' : ''} />\n * }\n *\n * export function NavLink({ href, children }) {\n * return (\n * <Link href={href}>\n * {children} <Hint />\n * </Link>\n * )\n * }\n * ```\n */\nexport function useLinkStatus(): LinkStatus {\n return useContext(LinkStatusContext);\n}\n","/**\n * Navigation Link Store — passes per-link metadata from Link's onClick\n * to the Navigation API's navigate event handler.\n *\n * When the Navigation API is active, Link does NOT call event.preventDefault()\n * or router.navigate(). Instead it stores metadata (scroll option, link\n * pending instance) here, and lets the <a> click propagate naturally.\n * The navigate event handler reads this metadata to configure the RSC\n * navigation with the correct options.\n *\n * This store is consumed once per navigation — after reading, the metadata\n * is cleared. If no metadata is present (e.g., a plain <a> tag without\n * our Link component), the navigate handler uses default options.\n *\n * See design/19-client-navigation.md §\"Navigation API Integration\"\n */\n\nimport type { LinkPendingInstance } from './link-pending-store.js';\n\nexport interface NavLinkMetadata {\n /** Whether to scroll to top after navigation. Default: true. */\n scroll: boolean;\n /** The Link's pending state instance for per-link status tracking. */\n linkInstance: LinkPendingInstance | null;\n}\n\nlet pendingMetadata: NavLinkMetadata | null = null;\n\n/**\n * Store metadata from Link's onClick for the next navigate event.\n * Called synchronously in the click handler — the navigate event\n * fires synchronously after onClick returns.\n */\nexport function setNavLinkMetadata(metadata: NavLinkMetadata): void {\n pendingMetadata = metadata;\n}\n\n/**\n * Consume the stored metadata. Returns null if no Link onClick\n * preceded this navigation (e.g., plain <a> tag, programmatic nav).\n * Clears the store after reading.\n */\nexport function consumeNavLinkMetadata(): NavLinkMetadata | null {\n const metadata = pendingMetadata;\n pendingMetadata = null;\n return metadata;\n}\n","/**\n * Navigation API integration — progressive enhancement for client navigation.\n *\n * When the Navigation API (`window.navigation`) is available, this module\n * provides an intercept-based navigation model that replaces the separate\n * popstate + click handler approach with a single navigate event listener.\n *\n * Key benefits:\n * - Intercepts ALL navigations (link clicks, form submissions, back/forward)\n * - Built-in AbortSignal per navigation (auto-aborts in-flight fetches)\n * - Per-entry state via NavigationHistoryEntry.getState()\n * - navigation.transition for progress tracking\n *\n * When unavailable, all functions are no-ops and the History API fallback\n * in browser-entry.ts handles navigation.\n *\n * See design/19-client-navigation.md\n */\n\nimport type { NavigationApi, NavigateEvent } from './navigation-api-types.js';\nimport { consumeNavLinkMetadata } from './nav-link-store.js';\nimport { isHardNavigating } from './navigation-root.js';\n\n// ─── Feature Detection ───────────────────────────────────────────\n\n/**\n * Returns true if the Navigation API is available in the current environment.\n * Feature-detected at runtime — no polyfill.\n */\nexport function hasNavigationApi(): boolean {\n return (\n typeof window !== 'undefined' &&\n 'navigation' in window &&\n (window as unknown as { navigation: unknown }).navigation != null\n );\n}\n\n/**\n * Get the Navigation API instance. Returns null if unavailable.\n * Uses type assertion — we never import Navigation API types unconditionally.\n */\nexport function getNavigationApi(): NavigationApi | null {\n if (!hasNavigationApi()) return null;\n return (window as unknown as { navigation: NavigationApi }).navigation;\n}\n\n// ─── Navigation API Controller ───────────────────────────────────\n\n/**\n * Callbacks for the Navigation API event handler.\n *\n * When the Navigation API intercepts a navigation, it delegates to these\n * callbacks which run the RSC fetch + render pipeline.\n */\nexport interface NavigationApiCallbacks {\n /**\n * Handle a push/replace navigation intercepted by the Navigation API.\n * This covers both Link <a> clicks (user-initiated, with metadata from\n * nav-link-store) and external navigations (plain <a> tags, programmatic).\n * The Navigation API handles the URL update via event.intercept().\n */\n onExternalNavigate: (\n url: string,\n options: { replace: boolean; signal: AbortSignal; scroll?: boolean }\n ) => Promise<void>;\n\n /**\n * Handle a traversal (back/forward button). The Navigation API intercepts\n * the traversal and delegates to us for RSC replay/fetch.\n */\n onTraverse: (url: string, scrollY: number, signal: AbortSignal) => Promise<void>;\n}\n\n/**\n * Controller returned by setupNavigationApi. Provides methods to\n * coordinate between the router and the navigate event listener.\n */\nexport interface NavigationApiController {\n /**\n * Set the router-navigating flag. When `true`, the next navigate event\n * (from pushState/replaceState) is recognized as router-initiated. The\n * handler still intercepts it — but ties the browser's native loading\n * state to a deferred promise instead of running the RSC pipeline again.\n *\n * This means `navigation.transition` is active for the full duration of\n * every router-initiated navigation, giving the browser a native loading\n * indicator (tab spinner, address bar) aligned with the TopLoader.\n *\n * Must be called synchronously around pushState/replaceState:\n * controller.setRouterNavigating(true);\n * history.pushState(...); // navigate event fires, intercepted\n * controller.setRouterNavigating(false); // flag off, deferred stays open\n */\n setRouterNavigating: (value: boolean) => void;\n\n /**\n * Resolve the deferred promise created by setRouterNavigating(true),\n * clearing the browser's native loading state. Call this when the\n * navigation fully completes — aligned with when the TopLoader's\n * pendingUrl clears (same finally block in router.navigate).\n */\n completeRouterNavigation: () => void;\n\n /**\n * Initiate a navigation via the Navigation API (`navigation.navigate()`).\n * Unlike `history.pushState()`, this fires the navigate event BEFORE\n * committing the URL — allowing Chrome to show its native loading\n * indicator while the intercept handler runs.\n *\n * Must be called with setRouterNavigating(true) active so the handler\n * recognizes it as router-initiated and uses the deferred promise.\n */\n navigate: (url: string, replace: boolean) => void;\n\n /**\n * Save scroll position into the current navigation entry's state.\n * Uses navigation.updateCurrentEntry() for per-entry scroll storage.\n */\n saveScrollPosition: (scrollY: number) => void;\n\n /**\n * Check if the Navigation API has an active transition.\n * Returns the transition object if available, null otherwise.\n */\n hasActiveTransition: () => boolean;\n\n /** Remove the navigate event listener. */\n cleanup: () => void;\n}\n\n/**\n * Set up the Navigation API navigate event listener.\n *\n * Intercepts same-origin navigations and delegates to the provided callbacks.\n * Router-initiated navigations (pushState from router.navigate) are detected\n * via a synchronous flag and NOT intercepted — the router already handles them.\n *\n * Returns a controller for coordinating with the router.\n */\nexport function setupNavigationApi(callbacks: NavigationApiCallbacks): NavigationApiController {\n const nav = getNavigationApi()!;\n\n let routerNavigating = false;\n\n // Deferred promise for router-initiated navigations. Created when\n // setRouterNavigating(true) is called, resolved by completeRouterNavigation().\n // The navigate event handler intercepts with this promise so the browser's\n // native loading state (tab spinner) stays active until the navigation\n // completes — aligned with TopLoader's pendingUrl lifecycle.\n let routerNavDeferred: { promise: Promise<void>; resolve: () => void } | null = null;\n\n function handleNavigate(event: NavigateEvent): void {\n // Skip non-interceptable navigations (cross-origin, etc.)\n if (!event.canIntercept) return;\n\n // Hard navigation guard: when the router has triggered a full page\n // load (500 error, version skew), skip interception entirely so the\n // browser performs the MPA navigation. Without this guard, setting\n // window.location.href fires a navigate event that we'd intercept,\n // running the RSC pipeline again → 500 → window.location.href →\n // navigate event → infinite loop.\n // See design/19-client-navigation.md §\"Hard Navigation Guard\"\n if (isHardNavigating()) return;\n\n // Skip download requests\n if (event.downloadRequest) return;\n\n // Skip hash-only changes — let the browser handle scroll-to-anchor\n if (event.hashChange) return;\n\n // Shallow URL updates (e.g., nuqs search param changes). The navigation\n // only changes the URL — no server round trip needed. Intercept with a\n // no-op handler so the Navigation API commits the URL change without\n // triggering a full page navigation (which is the default if we don't\n // intercept). The info property is the Navigation API's built-in\n // per-navigation metadata — no side-channel flags needed.\n const info = event.info as { shallow?: boolean } | null | undefined;\n if (info?.shallow) {\n event.intercept({\n handler: () => Promise.resolve(),\n focusReset: 'manual',\n scroll: 'manual',\n });\n return;\n }\n\n // Skip form submissions with a body (POST/PUT/etc.). These need the\n // browser's native form handling to send the request body to the server.\n // Intercepting would convert them into GET RSC navigations, dropping\n // the form data. Server actions use fetch() directly (not form navigation),\n // so they are unaffected by this check.\n if (event.formData) return;\n\n // Skip cross-origin (defense-in-depth — canIntercept covers this)\n const destUrl = new URL(event.destination.url);\n if (destUrl.origin !== location.origin) return;\n\n // Router-initiated navigation (Link click → router.navigate → pushState).\n // The router is already running the RSC pipeline — don't run it again.\n // Instead, intercept with the deferred promise so the browser's native\n // loading state tracks the navigation's full lifecycle. This aligns the\n // tab spinner / address bar indicator with the TopLoader.\n if (routerNavigating && routerNavDeferred) {\n event.intercept({\n scroll: 'manual',\n focusReset: 'manual',\n handler: () => routerNavDeferred!.promise,\n });\n return;\n }\n\n // Skip reload navigations — let the browser handle full page reload\n if (event.navigationType === 'reload') return;\n\n const url = destUrl.pathname + destUrl.search;\n\n if (event.navigationType === 'traverse') {\n // Back/forward button — intercept and delegate to router.\n // Read scroll position from the destination entry's state.\n const entryState = event.destination.getState() as\n | { scrollY?: number; timber?: boolean }\n | null\n | undefined;\n const scrollY = entryState && typeof entryState.scrollY === 'number' ? entryState.scrollY : 0;\n\n event.intercept({\n // Manual scroll — we handle scroll restoration ourselves\n // via afterPaint (same as the History API path).\n scroll: 'manual',\n focusReset: 'manual',\n async handler() {\n await callbacks.onTraverse(url, scrollY, event.signal);\n },\n });\n } else if (event.navigationType === 'push' || event.navigationType === 'replace') {\n // Push/replace — either a Link <a> click (with metadata in\n // nav-link-store) or an external navigation (plain <a>, programmatic).\n // Consume link metadata if present — tells us scroll preference\n // and which Link component to track pending state for.\n const linkMeta = consumeNavLinkMetadata();\n\n // Save the departing page's scroll position BEFORE event.intercept()\n // commits the URL change. Once intercept() is called, currentEntry\n // switches to the new (destination) entry — any updateCurrentEntry()\n // call after that would save to the wrong entry.\n // See: router.navigate() also calls saveNavigationEntryScroll(), but\n // for Navigation API <a> click navigations (where Link does NOT call\n // router.navigate directly), the router's save runs inside the\n // intercept handler — too late, currentEntry has already switched.\n try {\n const currentState = (nav.currentEntry?.getState() ?? {}) as Record<string, unknown>;\n nav.updateCurrentEntry({\n state: { ...currentState, timber: true, scrollY: window.scrollY },\n });\n } catch {\n // Ignore — entry may be disposed\n }\n\n event.intercept({\n scroll: 'manual',\n focusReset: 'manual',\n async handler() {\n await callbacks.onExternalNavigate(url, {\n replace: event.navigationType === 'replace',\n signal: event.signal,\n scroll: linkMeta?.scroll,\n });\n },\n });\n }\n }\n\n nav.addEventListener('navigate', handleNavigate as EventListener);\n\n return {\n setRouterNavigating(value: boolean): void {\n routerNavigating = value;\n if (value) {\n // Create a new deferred promise. The navigate event handler will\n // intercept and tie the browser's loading state to this promise.\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n routerNavDeferred = { promise, resolve };\n } else {\n // Flag off — but DON'T resolve the deferred here. The navigation\n // is still in flight (RSC fetch + render). completeRouterNavigation()\n // resolves it when the navigation fully completes.\n routerNavigating = false;\n }\n },\n\n completeRouterNavigation(): void {\n if (routerNavDeferred) {\n routerNavDeferred.resolve();\n routerNavDeferred = null;\n }\n },\n\n navigate(url: string, replace: boolean): void {\n // Use navigation.navigate() instead of history.pushState().\n // This fires the navigate event BEFORE committing the URL,\n // which lets Chrome show its native loading indicator while\n // the intercept handler (deferred promise) is pending.\n // history.pushState() commits the URL synchronously, so Chrome\n // sees the navigation as already complete and skips the indicator.\n nav.navigate(url, {\n history: replace ? 'replace' : 'push',\n });\n },\n\n saveScrollPosition(scrollY: number): void {\n try {\n const currentState = (nav.currentEntry?.getState() ?? {}) as Record<string, unknown>;\n nav.updateCurrentEntry({\n state: { ...currentState, timber: true, scrollY },\n });\n } catch {\n // Ignore errors — updateCurrentEntry may throw if entry is disposed\n }\n },\n\n hasActiveTransition(): boolean {\n return nav.transition != null;\n },\n\n cleanup(): void {\n nav.removeEventListener('navigate', handleNavigate as EventListener);\n },\n };\n}\n","'use client';\n\n// Link component — client-side navigation with progressive enhancement\n// See design/19-client-navigation.md § Progressive Enhancement\n//\n// Without JavaScript, <Link> renders as a plain <a> tag — standard browser\n// navigation. With JavaScript, the Link component's onClick handler triggers\n// RSC-based client navigation via the router.\n//\n// Each Link owns its own click handler — no global event delegation.\n// This keeps navigation within React's component tree, ensuring pending\n// state (useLinkStatus) updates atomically with the navigation.\n//\n// Typed Link: design/09-typescript.md §\"Typed Link\"\n// - href validated against known routes (via codegen overloads, not runtime)\n// - params prop typed per-route, URL interpolated at runtime\n// - searchParams prop serialized via SearchParamsDefinition\n// - params and fully-resolved string href are mutually exclusive\n// - searchParams and inline query string are mutually exclusive\n\nimport {\n useOptimistic,\n useEffect,\n useRef,\n type AnchorHTMLAttributes,\n type ReactNode,\n type MouseEvent as ReactMouseEvent,\n} from 'react';\nimport type { SearchParamsDefinition } from '../search-params/define.js';\nimport type { LinkFunction } from './index.js';\nimport { classifyUrlSegment, type UrlSegment } from '../routing/segment-classify.js';\nimport { LinkStatusContext } from './use-link-status.js';\nimport { getRouterOrNull } from './router-ref.js';\nimport { getSsrData } from './ssr-data.js';\nimport { mergePreservedSearchParams } from '../shared/merge-search-params.js';\nimport {\n setLinkForCurrentNavigation,\n unmountLinkForCurrentNavigation,\n LINK_IDLE,\n type LinkPendingInstance,\n} from './link-pending-store.js';\nimport { setNavLinkMetadata } from './nav-link-store.js';\nimport { hasNavigationApi } from './navigation-api.js';\n\n// ─── Current Search Params ────────────────────────────────────────\n\n/**\n * Read the current URL's search string without requiring a React hook.\n * On the client, reads window.location.search. During SSR, reads from\n * the request context (getSsrData). Returns empty string if unavailable.\n */\nfunction getCurrentSearch(): string {\n if (typeof window !== 'undefined') return window.location.search;\n const data = getSsrData();\n if (!data) return '';\n const sp = new URLSearchParams(data.searchParams);\n const str = sp.toString();\n return str ? `?${str}` : '';\n}\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport type OnNavigateEvent = {\n preventDefault: () => void;\n};\n\nexport type OnNavigateHandler = (e: OnNavigateEvent) => void;\n\n/**\n * Base props shared by all Link variants.\n *\n * Exported so the public `LinkFunction` interface (declared in\n * `./index.ts`, where module augmentation can merge into it) can\n * compose this without duplication.\n */\nexport interface LinkBaseProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {\n /** Prefetch the RSC payload on hover */\n prefetch?: boolean;\n /**\n * Scroll to top on navigation. Defaults to true.\n * Set to false for tabbed interfaces where content changes within a fixed layout.\n */\n scroll?: boolean;\n /**\n * Preserve search params from the current URL across navigation.\n *\n * - `true` — preserve ALL current search params (target params take precedence)\n * - `string[]` — preserve only the named params (e.g. `['private', 'token']`)\n *\n * Useful for route-group gating where a search param (e.g. `?private=access`)\n * must persist across internal navigations. The target href's own search params\n * always take precedence over preserved ones.\n *\n * During SSR, reads search params from the request context. On the client,\n * reads from the current URL and updates reactively when the URL changes.\n */\n preserveSearchParams?: true | string[];\n /**\n * Called before client-side navigation commits. Call `e.preventDefault()`\n * to cancel the default navigation — the caller is then responsible for\n * navigating (e.g. via `router.push()`).\n *\n * Only fires for client-side SPA navigations, not full page loads.\n * Has no effect during SSR.\n */\n onNavigate?: OnNavigateHandler;\n children?: ReactNode;\n}\n\n// ─── Typed Link Props ────────────────────────────────────────────\n\n/**\n * Widen server-side string params to string | number for Link convenience.\n * Exported for use by codegen-generated overloads.\n */\nexport type LinkSegmentParams<T> = {\n [K in keyof T]: [string] extends [T[K]] ? string | number : T[K];\n};\n\n// ─── External Href Types ─────────────────────────────────────────\n//\n// `ExternalHref` and the public `LinkFunction` interface live in\n// `./index.ts` rather than this file. They MUST be originally declared\n// in the same module that the codegen augments (`@timber-js/app/client`)\n// so that codegen-generated per-route call signatures merge with the\n// same interface that types the `Link` constant. Re-exporting an\n// interface via `export type {}` does NOT participate in module\n// augmentation merging — only originally-declared interfaces do.\n// See TIM-624.\n\n/**\n * Runtime-only loose props used internally by the Link implementation.\n * Not exposed to callers — the public API uses LinkFunction.\n */\ninterface LinkRuntimeProps extends LinkBaseProps {\n href: string;\n segmentParams?: Record<string, string | number | string[]>;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n}\n\n// Legacy exports for backward compat (used by buildLinkProps, tests, etc.)\nexport type LinkPropsWithHref = LinkBaseProps & {\n href: string;\n segmentParams?: never;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n};\nexport type LinkPropsWithParams = LinkRuntimeProps & {\n segmentParams: Record<string, string | number | string[]>;\n};\nexport type LinkProps = LinkRuntimeProps;\n\n// ─── Dangerous URL Scheme Detection ──────────────────────────────\n\n/**\n * Reject dangerous URL schemes that could execute script.\n * Security: design/13-security.md § Link scheme injection (test #9)\n */\nconst DANGEROUS_SCHEMES = /^\\s*(javascript|data|vbscript):/i;\n\nexport function validateLinkHref(href: string): void {\n if (DANGEROUS_SCHEMES.test(href)) {\n throw new Error(\n `<Link> received a dangerous href: \"${href}\". ` +\n 'javascript:, data:, and vbscript: URLs are not allowed.'\n );\n }\n}\n\n// ─── Internal Link Detection ─────────────────────────────────────\n\n/** Returns true if the href is an internal path (not an external URL) */\nexport function isInternalHref(href: string): boolean {\n // Relative paths, root-relative paths, and hash links are internal\n if (href.startsWith('/') || href.startsWith('#') || href.startsWith('?')) {\n return true;\n }\n // Anything with a protocol scheme is external\n if (/^[a-z][a-z0-9+.-]*:/i.test(href)) {\n return false;\n }\n // Bare relative paths (e.g., \"dashboard\") are internal\n return true;\n}\n\n// ─── URL Interpolation ──────────────────────────────────────────\n\n/**\n * Interpolate dynamic segments in a route pattern with actual values.\n * e.g. interpolateParams(\"/products/[id]\", { id: \"123\" }) → \"/products/123\"\n *\n * Supports:\n * - [param] → single segment\n * - [...param] → catch-all (joined with /)\n * - [[...param]] → optional catch-all (omitted if undefined/empty)\n */\n/**\n * Parse a route pattern's path portion into classified segments.\n * Exported for testing. Uses the shared character-based classifier.\n */\nexport function parseSegments(pattern: string): UrlSegment[] {\n return pattern.split('/').filter(Boolean).map(classifyUrlSegment);\n}\n\n/**\n * Resolve a single classified segment into its string representation.\n * Returns null for optional catch-all with no value (filtered out before join).\n */\nfunction resolveSegment(\n seg: UrlSegment,\n params: Record<string, string | number | string[]>,\n pattern: string\n): string | null {\n switch (seg.kind) {\n case 'static':\n return seg.value;\n\n case 'optional-catch-all': {\n const value = params[seg.name];\n if (value === undefined || (Array.isArray(value) && value.length === 0)) {\n return null;\n }\n const segments = Array.isArray(value) ? value : [value];\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'catch-all': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(\n `<Link> missing required catch-all param \"${seg.name}\" for pattern \"${pattern}\".`\n );\n }\n const segments = Array.isArray(value) ? value : [value];\n if (segments.length === 0) {\n throw new Error(\n `<Link> catch-all param \"${seg.name}\" must have at least one segment for pattern \"${pattern}\".`\n );\n }\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'dynamic': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(`<Link> missing required param \"${seg.name}\" for pattern \"${pattern}\".`);\n }\n if (Array.isArray(value)) {\n throw new Error(\n `<Link> param \"${seg.name}\" expected a string but received an array for pattern \"${pattern}\".`\n );\n }\n return encodeURIComponent(String(value));\n }\n }\n}\n\n/**\n * Split a URL pattern into the path portion and any trailing ?query/#hash suffix.\n * Uses URL parsing for correctness rather than manual index arithmetic.\n */\nfunction splitPatternSuffix(pattern: string): [path: string, suffix: string] {\n if (!pattern.includes('?') && !pattern.includes('#')) {\n return [pattern, ''];\n }\n const url = new URL(pattern, 'http://x');\n const suffix = url.search + url.hash;\n const path = pattern.slice(0, pattern.length - suffix.length);\n return [path, suffix];\n}\n\nexport function interpolateParams(\n pattern: string,\n params: Record<string, string | number | string[]>\n): string {\n const [pathPart, suffix] = splitPatternSuffix(pattern);\n\n const resolved = parseSegments(pathPart)\n .map((seg) => resolveSegment(seg, params, pattern))\n .filter((s): s is string => s !== null);\n return ('/' + resolved.join('/') || '/') + suffix;\n}\n\n// ─── Resolve Href ───────────────────────────────────────────────\n\n/**\n * Resolve the final href string from Link props.\n *\n * Handles:\n * - params interpolation into route patterns\n * - searchParams serialization via SearchParamsDefinition\n * - Validation that searchParams and inline query strings are exclusive\n */\nexport function resolveHref(\n href: string,\n params?: Record<string, string | number | string[]>,\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n }\n): string {\n let resolvedPath = href;\n\n // Interpolate params if provided\n if (params) {\n resolvedPath = interpolateParams(href, params);\n }\n\n // Serialize searchParams if provided\n if (searchParams) {\n // Validate: searchParams prop and inline query string are mutually exclusive\n if (resolvedPath.includes('?')) {\n throw new Error(\n '<Link> received both a searchParams prop and a query string in href. ' +\n 'These are mutually exclusive — use one or the other.'\n );\n }\n\n const qs = searchParams.definition.serialize(searchParams.values);\n if (qs) {\n resolvedPath = `${resolvedPath}?${qs}`;\n }\n }\n\n return resolvedPath;\n}\n\n// ─── Build Props ─────────────────────────────────────────────────\n\ninterface LinkOutputProps {\n href: string;\n}\n\n/**\n * Build the HTML attributes for a Link. Separated from the component\n * for testability — the component just spreads these onto an <a>.\n */\nexport function buildLinkProps(\n props: Pick<LinkPropsWithHref, 'href'> & {\n params?: Record<string, string | number | string[]>;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n }\n): LinkOutputProps {\n const resolvedHref = resolveHref(props.href, props.params, props.searchParams);\n validateLinkHref(resolvedHref);\n return { href: resolvedHref };\n}\n\n// ─── Click Handler ───────────────────────────────────────────────\n\n/**\n * Should this click be intercepted for SPA navigation?\n *\n * Returns false (pass through to browser) when:\n * - Modified keys are held (Ctrl, Meta, Shift, Alt) — open in new tab\n * - The click is not the primary button\n * - The event was already prevented by a parent handler\n * - The link has target=\"_blank\" or similar\n * - The link has a download attribute\n * - The href is external\n */\nfunction shouldInterceptClick(\n event: ReactMouseEvent<HTMLAnchorElement>,\n resolvedHref: string\n): boolean {\n if (event.button !== 0) return false;\n if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;\n if (event.defaultPrevented) return false;\n\n const anchor = event.currentTarget;\n if (anchor.target && anchor.target !== '_self') return false;\n if (anchor.hasAttribute('download')) return false;\n\n if (!isInternalHref(resolvedHref)) return false;\n\n return true;\n}\n\n// ─── Link Component ──────────────────────────────────────────────\n\n/**\n * Navigation link with progressive enhancement.\n *\n * Renders as a plain `<a>` tag — works without JavaScript. When the client\n * runtime is active, the Link's onClick handler triggers RSC-based client\n * navigation via the router. No global event delegation — each Link owns\n * its own click handling.\n *\n * Supports typed routes via the Routes interface (populated by codegen).\n * At runtime:\n * - `segmentParams` prop interpolates dynamic segments in the href pattern\n * - `searchParams` prop serializes query parameters via a SearchParamsDefinition\n *\n * Typed via the LinkFunction callable interface. The base call signature\n * forbids segmentParams; per-route signatures are added by codegen via\n * interface merging. See TIM-624.\n */\n// Cast to LinkFunction — the callable interface provides the public type,\n// but the implementation destructures LinkRuntimeProps internally.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const Link: LinkFunction = function LinkImpl(props: any) {\n const {\n href,\n prefetch,\n scroll,\n segmentParams,\n searchParams,\n preserveSearchParams,\n onNavigate,\n onClick: userOnClick,\n onMouseEnter: userOnMouseEnter,\n children,\n ...rest\n } = props as LinkRuntimeProps;\n const { href: baseHref } = buildLinkProps({ href, params: segmentParams, searchParams });\n\n // ─── Per-link pending state (useOptimistic) ────────────────────────\n // Each Link has its own pending state. Only the clicked link's\n // setter is invoked during navigation — zero other links re-render.\n //\n // Link click stores the instance; NavigationRoot activates inside startTransition.\n // useOptimistic auto-reverts to LINK_IDLE when the navigation\n // startTransition — batched with the new tree commit.\n //\n // See design/19-client-navigation.md §\"Per-Link Pending State\"\n const [linkStatus, setIsPending] = useOptimistic(LINK_IDLE);\n\n // Build the link instance ref for the pending store.\n // The ref is stable across renders — we update the setter on each\n // render to keep it current.\n const linkInstanceRef = useRef<LinkPendingInstance | null>(null);\n if (!linkInstanceRef.current) {\n linkInstanceRef.current = { setIsPending };\n } else {\n linkInstanceRef.current.setIsPending = setIsPending;\n }\n\n // Clean up if this link unmounts while it's the current navigation link.\n // Prevents calling setOptimistic on an unmounted component.\n useEffect(() => {\n const instance = linkInstanceRef.current;\n return () => {\n if (instance) {\n unmountLinkForCurrentNavigation(instance);\n }\n };\n }, []);\n\n // Preserve search params from the current URL when requested.\n // useSearchParams() works during both SSR (reads from request context)\n // and on the client (reads from window.location, reactive to URL changes).\n // We read current search params directly to avoid unconditional hook calls.\n // On the client, window.location.search is always current; during SSR,\n // getSsrData() provides the request's search params.\n const resolvedHref = preserveSearchParams\n ? mergePreservedSearchParams(baseHref, getCurrentSearch(), preserveSearchParams)\n : baseHref;\n\n const internal = isInternalHref(resolvedHref);\n\n // ─── Click handler ───────────────────────────────────────────\n // Each Link component owns its click handling. The router is\n // accessed via the singleton ref — during SSR, getRouterOrNull()\n // returns null and onClick is a no-op (the <a> works as a plain link).\n const handleClick = internal\n ? (event: ReactMouseEvent<HTMLAnchorElement>) => {\n // Call user's onClick first (e.g., analytics)\n userOnClick?.(event);\n\n if (!shouldInterceptClick(event, resolvedHref)) return;\n\n // Call onNavigate if provided — allows caller to cancel\n if (onNavigate) {\n let prevented = false;\n onNavigate({\n preventDefault: () => {\n prevented = true;\n },\n });\n if (prevented) {\n event.preventDefault();\n return;\n }\n }\n\n const router = getRouterOrNull();\n if (!router) return; // SSR or pre-hydration — fall through to browser nav\n\n const shouldScroll = scroll !== false;\n\n // Register this link in the pending store. The actual\n // setIsPending(LINK_PENDING) call happens inside NavigationRoot's\n // async startTransition via activateLinkPending().\n\n setLinkForCurrentNavigation(linkInstanceRef.current);\n\n // When Navigation API is active, let the <a> click propagate\n // naturally — do NOT call preventDefault(). The navigate event\n // handler intercepts it and runs the RSC pipeline. This is a\n // user-initiated navigation, so Chrome shows the native loading\n // indicator (tab spinner). Metadata (scroll, link instance) is\n // passed via nav-link-store so the handler can configure the nav.\n //\n // Without Navigation API (fallback), preventDefault and drive\n // navigation through the router as before.\n if (hasNavigationApi()) {\n setNavLinkMetadata({\n scroll: shouldScroll,\n linkInstance: linkInstanceRef.current,\n });\n // Don't preventDefault — let the <a> click fire the navigate event\n return;\n }\n\n // History API fallback — prevent default and navigate via router\n event.preventDefault();\n\n // Re-merge preserved search params at click time to pick up any\n // URL changes since render (e.g. from other navigations or pushState).\n const navHref = preserveSearchParams\n ? mergePreservedSearchParams(baseHref, getCurrentSearch(), preserveSearchParams)\n : resolvedHref;\n\n void router.navigate(navHref, { scroll: shouldScroll });\n }\n : userOnClick; // External links — just pass through user's onClick\n\n // ─── Hover prefetch ──────────────────────────────────────────\n const handleMouseEnter =\n internal && prefetch\n ? (event: ReactMouseEvent<HTMLAnchorElement>) => {\n userOnMouseEnter?.(event);\n const router = getRouterOrNull();\n if (router) {\n // Re-merge preserved search params at hover time for fresh prefetch URL\n const prefetchHref = preserveSearchParams\n ? mergePreservedSearchParams(baseHref, getCurrentSearch(), preserveSearchParams)\n : resolvedHref;\n router.prefetch(prefetchHref);\n }\n }\n : userOnMouseEnter;\n\n return (\n <a {...rest} href={resolvedHref} onClick={handleClick} onMouseEnter={handleMouseEnter}>\n <LinkStatusContext.Provider value={linkStatus}>{children}</LinkStatusContext.Provider>\n </a>\n );\n};\n","// usePendingNavigation — returns true while an RSC navigation is in flight.\n// See design/19-client-navigation.md §\"usePendingNavigation()\"\n//\n// Reads from PendingNavigationContext (provided by NavigationRoot) so the\n// pending state shows immediately (urgent update) and clears atomically\n// with the new tree (same startTransition commit).\n\nimport { usePendingNavigationUrl } from './navigation-context.js';\n\n/**\n * Returns true while an RSC navigation is in flight.\n *\n * The pending state is true from the moment the RSC fetch starts until\n * React reconciliation completes. This includes the fetch itself,\n * RSC stream parsing, and React tree reconciliation.\n *\n * It does NOT include Suspense streaming after the shell — only the\n * initial shell reconciliation.\n *\n * ```tsx\n * 'use client'\n * import { usePendingNavigation } from '@timber-js/app/client'\n *\n * export function NavBar() {\n * const isPending = usePendingNavigation()\n * return (\n * <nav className={isPending ? 'opacity-50' : ''}>\n * <Link href=\"/dashboard\">Dashboard</Link>\n * </nav>\n * )\n * }\n * ```\n */\nexport function usePendingNavigation(): boolean {\n const pendingUrl = usePendingNavigationUrl();\n // During SSR or outside PendingNavigationProvider, no navigation is pending\n return pendingUrl !== null;\n}\n","/**\n * useRouter() — client-side hook for programmatic navigation.\n *\n * Returns a router instance with push, replace, refresh, back, forward,\n * and prefetch methods. Compatible with Next.js's `useRouter()` from\n * `next/navigation` (App Router).\n *\n * This wraps timber's internal RouterInstance in the Next.js-compatible\n * AppRouterInstance shape that ecosystem libraries expect.\n *\n * NOTE: Unlike Next.js, these methods do NOT wrap navigation in\n * startTransition. In Next.js, router state is React state (useReducer)\n * so startTransition defers the update and provides isPending tracking.\n * In timber, navigation calls reactRoot.render() which is a root-level\n * render — startTransition has no effect on root renders.\n *\n * Navigation state (params, pathname) is delivered atomically via\n * NavigationContext embedded in the element tree passed to\n * reactRoot.render(). See design/19-client-navigation.md §\"NavigationContext\".\n *\n * For loading UI during navigation, use:\n * - useLinkStatus() — per-link pending indicator (inside <Link>)\n * - usePendingNavigation() — global navigation pending state\n */\n\nimport { getRouterOrNull } from './router-ref.js';\n\nexport interface AppRouterInstance {\n /** Navigate to a URL, pushing a new history entry */\n push(href: string, options?: { scroll?: boolean }): void;\n /** Navigate to a URL, replacing the current history entry */\n replace(href: string, options?: { scroll?: boolean }): void;\n /** Refresh the current page (re-fetch RSC payload) */\n refresh(): void;\n /** Navigate back in history */\n back(): void;\n /** Navigate forward in history */\n forward(): void;\n /** Prefetch an RSC payload for a URL */\n prefetch(href: string): void;\n}\n\n/**\n * Get a router instance for programmatic navigation.\n *\n * Compatible with Next.js's `useRouter()` from `next/navigation`.\n *\n * Methods lazily resolve the global router when invoked (during user\n * interaction) rather than capturing it at render time. This is critical\n * because during hydration, React synchronously executes component render\n * functions *before* the router is bootstrapped in browser-entry.ts.\n * If we eagerly captured the router during render, components would get\n * a null reference and be stuck with silent no-ops forever.\n *\n * Returns safe no-ops during SSR or before bootstrap. The `typeof window`\n * check is insufficient because Vite's client SSR environment defines\n * `window`, so we use a try/catch on getRouter() — but only at method\n * invocation time, not at render time.\n */\nexport function useRouter(): AppRouterInstance {\n return {\n push(href: string, options?: { scroll?: boolean }) {\n const router = getRouterOrNull();\n if (!router) {\n if (process.env.NODE_ENV === 'development') {\n console.error(\n '[timber] useRouter().push() called but router is not initialized. This is a bug — please report it.'\n );\n }\n return;\n }\n void router.navigate(href, { scroll: options?.scroll });\n },\n replace(href: string, options?: { scroll?: boolean }) {\n const router = getRouterOrNull();\n if (!router) {\n if (process.env.NODE_ENV === 'development') {\n console.error('[timber] useRouter().replace() called but router is not initialized.');\n }\n return;\n }\n void router.navigate(href, { scroll: options?.scroll, replace: true });\n },\n refresh() {\n const router = getRouterOrNull();\n if (!router) {\n if (process.env.NODE_ENV === 'development') {\n console.error('[timber] useRouter().refresh() called but router is not initialized.');\n }\n return;\n }\n void router.refresh();\n },\n back() {\n if (typeof window !== 'undefined') window.history.back();\n },\n forward() {\n if (typeof window !== 'undefined') window.history.forward();\n },\n prefetch(href: string) {\n const router = getRouterOrNull();\n if (!router) return; // Silent — prefetch failure is non-fatal\n router.prefetch(href);\n },\n };\n}\n","/**\n * usePathname() — client-side hook for reading the current pathname.\n *\n * Returns the pathname portion of the current URL (e.g. '/dashboard/settings').\n * Updates when client-side navigation changes the URL.\n *\n * On the client, reads from NavigationContext which is updated atomically\n * with the RSC tree render. This replaces the previous useSyncExternalStore\n * approach which only subscribed to popstate events — meaning usePathname()\n * did NOT re-render on forward navigation (pushState). The context approach\n * fixes this: pathname updates in the same render pass as the new tree.\n *\n * During SSR, reads the request pathname from the SSR ALS context\n * (populated by ssr-entry.ts) instead of window.location.\n *\n * Compatible with Next.js's `usePathname()` from `next/navigation`.\n */\n\nimport { getSsrData } from './ssr-data.js';\nimport { useNavigationContext } from './navigation-context.js';\n\n/**\n * Read the current URL pathname.\n *\n * On the client, reads from NavigationContext (provided by\n * NavigationProvider in renderRoot). During SSR, reads from the\n * ALS-backed SSR data context. Falls back to window.location.pathname\n * when called outside a React component (e.g., in tests).\n */\nexport function usePathname(): string {\n // Try reading from NavigationContext (client-side, inside React tree).\n // During SSR, no NavigationProvider is mounted, so this returns null.\n try {\n const navContext = useNavigationContext();\n if (navContext !== null) {\n return navContext.pathname;\n }\n } catch {\n // No React dispatcher available (called outside a component).\n // Fall through to SSR/fallback below.\n }\n\n // SSR path: read from ALS-backed SSR data context.\n const ssrData = getSsrData();\n if (ssrData) return ssrData.pathname ?? '/';\n\n // Final fallback: window.location (tests, edge cases).\n if (typeof window !== 'undefined') return window.location.pathname;\n return '/';\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * This is a thin wrapper over window.location.search, provided for\n * Next.js API compatibility (libraries like nuqs import useSearchParams\n * from next/navigation).\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * During SSR, reads the request search params from the SSR ALS context\n * (populated by ssr-entry.ts) instead of window.location.\n *\n * All mutable state is delegated to client/state.ts for singleton guarantees.\n * See design/18-build-system.md §\"Singleton State Registry\"\n */\n\nimport { useSyncExternalStore } from 'react';\nimport { getSsrData } from './ssr-data.js';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.js';\n\nfunction getSearch(): string {\n if (typeof window !== 'undefined') return window.location.search;\n const data = getSsrData();\n if (!data) return '';\n const sp = new URLSearchParams(data.searchParams);\n const str = sp.toString();\n return str ? `?${str}` : '';\n}\n\nfunction getServerSearch(): string {\n const data = getSsrData();\n if (!data) return '';\n const sp = new URLSearchParams(data.searchParams);\n const str = sp.toString();\n return str ? `?${str}` : '';\n}\n\nfunction subscribe(callback: () => void): () => void {\n window.addEventListener('popstate', callback);\n return () => window.removeEventListener('popstate', callback);\n}\n\n// Cache the last search string and its parsed URLSearchParams to avoid\n// creating a new object on every render when the URL hasn't changed.\n// State lives in client/state.ts for singleton guarantees.\n\nfunction getSearchParams(): URLSearchParams {\n const search = getSearch();\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\nfunction getServerSearchParams(): URLSearchParams {\n const data = getSsrData();\n return data ? new URLSearchParams(data.searchParams) : new URLSearchParams();\n}\n\n/**\n * Read the current URL search params.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n // useSyncExternalStore needs a primitive snapshot for comparison.\n // We use the raw search string as the snapshot, then return the\n // parsed URLSearchParams.\n useSyncExternalStore(subscribe, getSearch, getServerSearch);\n return typeof window !== 'undefined' ? getSearchParams() : getServerSearchParams();\n}\n","/**\n * useSelectedLayoutSegment / useSelectedLayoutSegments — client-side hooks\n * for reading the active segment(s) below the current layout.\n *\n * These hooks are used by navigation UIs to highlight active sections.\n * They match Next.js's API from next/navigation.\n *\n * How they work:\n * 1. Each layout is wrapped with a SegmentProvider that records its depth\n * (the URL segments from root to that layout level).\n * 2. The hooks read the current URL pathname via usePathname().\n * 3. They compare the layout's segment depth against the full URL segments\n * to determine which child segments are \"selected\" below.\n *\n * Example: For URL \"/dashboard/settings/profile\"\n * - Root layout (depth 0, segments: ['']): selected segment = \"dashboard\"\n * - Dashboard layout (depth 1, segments: ['', 'dashboard']): selected = \"settings\"\n * - Settings layout (depth 2, segments: ['', 'dashboard', 'settings']): selected = \"profile\"\n *\n * Design docs: design/19-client-navigation.md, design/14-ecosystem.md\n */\n\n'use client';\n\nimport { useSegmentContext } from './segment-context.js';\nimport { usePathname } from './use-pathname.js';\n\n/**\n * Split a pathname into URL segments.\n * \"/\" → [\"\"]\n * \"/dashboard\" → [\"\", \"dashboard\"]\n * \"/dashboard/settings\" → [\"\", \"dashboard\", \"settings\"]\n */\nexport function pathnameToSegments(pathname: string): string[] {\n return pathname.split('/');\n}\n\n/**\n * Pure function: compute the selected child segment given a layout's segment\n * depth and the current URL pathname.\n *\n * @param contextSegments — segments from root to the calling layout, or null if no context\n * @param pathname — current URL pathname\n * @returns the active child segment one level below, or null if at the leaf\n */\nexport function getSelectedSegment(\n contextSegments: string[] | null,\n pathname: string\n): string | null {\n const urlSegments = pathnameToSegments(pathname);\n\n if (!contextSegments) {\n return urlSegments[1] || null;\n }\n\n const depth = contextSegments.length;\n return urlSegments[depth] || null;\n}\n\n/**\n * Pure function: compute all selected segments below a layout's depth.\n *\n * @param contextSegments — segments from root to the calling layout, or null if no context\n * @param pathname — current URL pathname\n * @returns all active segments below the layout\n */\nexport function getSelectedSegments(contextSegments: string[] | null, pathname: string): string[] {\n const urlSegments = pathnameToSegments(pathname);\n\n if (!contextSegments) {\n return urlSegments.slice(1).filter(Boolean);\n }\n\n const depth = contextSegments.length;\n return urlSegments.slice(depth).filter(Boolean);\n}\n\n/**\n * Returns the active child segment one level below the layout where this\n * hook is called. Returns `null` if the layout is the leaf (no child segment).\n *\n * Compatible with Next.js's `useSelectedLayoutSegment()` from `next/navigation`.\n *\n * @param parallelRouteKey — Optional parallel route key. Currently unused\n * (parallel route segment tracking is not yet implemented). Accepted for\n * API compatibility with Next.js.\n */\nexport function useSelectedLayoutSegment(parallelRouteKey?: string): string | null {\n void parallelRouteKey;\n const context = useSegmentContext();\n const pathname = usePathname();\n return getSelectedSegment(context?.segments ?? null, pathname);\n}\n\n/**\n * Returns all active segments below the layout where this hook is called.\n * Returns an empty array if the layout is the leaf (no child segments).\n *\n * Compatible with Next.js's `useSelectedLayoutSegments()` from `next/navigation`.\n *\n * @param parallelRouteKey — Optional parallel route key. Currently unused\n * (parallel route segment tracking is not yet implemented). Accepted for\n * API compatibility with Next.js.\n */\nexport function useSelectedLayoutSegments(parallelRouteKey?: string): string[] {\n void parallelRouteKey;\n const context = useSegmentContext();\n const pathname = usePathname();\n return getSelectedSegments(context?.segments ?? null, pathname);\n}\n","/**\n * Client-side form utilities for server actions.\n *\n * Exports a typed `useActionState` that understands the action builder's result shape.\n * Result is typed to:\n * { data: T } | { validationErrors: Record<string, string[]> } | { serverError: { code, data? } } | null\n *\n * The action builder emits a function that satisfies both the direct call signature\n * and React's `(prevState, formData) => Promise<State>` contract.\n *\n * See design/08-forms-and-actions.md §\"Client-Side Form Mechanics\"\n */\n\nimport { useActionState as reactUseActionState, useTransition } from 'react';\nimport type { ActionFn, ActionResult, InputHint, ValidationErrors } from '../server/action-client';\nimport type { FormFlashData } from '../server/form-flash';\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\n/**\n * The action function type accepted by useActionState.\n * Must satisfy React's (prevState, formData) => Promise<State> contract.\n */\nexport type UseActionStateFn<TData> = (\n prevState: ActionResult<TData> | null,\n formData: FormData\n) => Promise<ActionResult<TData>>;\n\n/**\n * Return type of useActionState — matches React 19's useActionState return.\n * [result, formAction, isPending]\n */\nexport type UseActionStateReturn<TData> = [\n result: ActionResult<TData> | null,\n formAction: (formData: FormData) => void,\n isPending: boolean,\n];\n\n// ─── useActionState ──────────────────────────────────────────────────────\n\n/**\n * Typed wrapper around React 19's `useActionState` that understands\n * the timber action builder's result shape.\n *\n * @param action - A server action created with createActionClient or a raw 'use server' function.\n * @param initialState - Initial state, typically `null`. Pass `getFormFlash()` for no-JS\n * progressive enhancement — the flash seeds the initial state so the form has a\n * single source of truth for both with-JS and no-JS paths.\n * @param permalink - Optional permalink for progressive enhancement (no-JS fallback URL).\n *\n * @example\n * ```tsx\n * 'use client'\n * import { useActionState } from '@timber-js/app/client'\n * import { createTodo } from './actions'\n *\n * export function NewTodoForm({ flash }) {\n * const [result, action, isPending] = useActionState(createTodo, flash)\n * return (\n * <form action={action}>\n * <input name=\"title\" />\n * {result?.validationErrors?.title && <p>{result.validationErrors.title}</p>}\n * <button disabled={isPending}>Add</button>\n * </form>\n * )\n * }\n * ```\n */\nexport function useActionState<TData>(\n action: UseActionStateFn<TData>,\n initialState: ActionResult<TData> | FormFlashData | null,\n permalink?: string\n): UseActionStateReturn<TData> {\n // FormFlashData is structurally compatible with ActionResult at runtime —\n // the cast satisfies React's generic inference which would otherwise widen TData.\n return reactUseActionState(action, initialState as ActionResult<TData> | null, permalink);\n}\n\n// ─── useFormAction ───────────────────────────────────────────────────────\n\n/**\n * Hook for calling a server action imperatively (not via a form).\n * Returns [execute, isPending] where execute accepts the input directly.\n *\n * @example\n * ```tsx\n * const [deleteTodo, isPending] = useFormAction(deleteTodoAction)\n * <button onClick={() => deleteTodo({ id: todo.id })} disabled={isPending}>\n * Delete\n * </button>\n * ```\n */\nexport function useFormAction<TData = unknown, TInput = unknown>(\n action: ActionFn<TData, TInput> | ((input: TInput) => Promise<ActionResult<TData>>)\n): [\n (\n ...args: undefined extends TInput ? [input?: InputHint<TInput>] : [input: InputHint<TInput>]\n ) => Promise<ActionResult<TData>>,\n boolean,\n] {\n const [isPending, startTransition] = useTransition();\n\n const execute = (input?: InputHint<TInput>): Promise<ActionResult<TData>> => {\n return new Promise((resolve) => {\n startTransition(async () => {\n const result = await (action as (input: InputHint<TInput>) => Promise<ActionResult<TData>>)(\n input as InputHint<TInput>\n );\n resolve(result);\n });\n });\n };\n\n return [execute, isPending];\n}\n\n// ─── useFormErrors ──────────────────────────────────────────────────────\n\n/** Return type of useFormErrors(). */\nexport interface FormErrorsResult {\n /** Per-field validation errors keyed by field name. */\n fieldErrors: Record<string, string[]>;\n /** Form-level errors (from `_root` key). */\n formErrors: string[];\n /** Server error if the action threw an ActionError. */\n serverError: { code: string; data?: Record<string, unknown> } | null;\n /** Whether any errors are present. */\n hasErrors: boolean;\n /** Get the first error message for a field, or null. */\n getFieldError: (field: string) => string | null;\n}\n\n/**\n * Extract per-field and form-level errors from an ActionResult.\n *\n * Pure function (no internal hooks) — follows React naming convention\n * since it's used in render. Accepts the result from `useActionState`\n * or flash data from `getFormFlash()`.\n *\n * @example\n * ```tsx\n * const [result, action, isPending] = useActionState(createTodo, null)\n * const errors = useFormErrors(result)\n *\n * return (\n * <form action={action}>\n * <input name=\"title\" />\n * {errors.getFieldError('title') && <p>{errors.getFieldError('title')}</p>}\n * {errors.formErrors.map(e => <p key={e}>{e}</p>)}\n * </form>\n * )\n * ```\n */\nexport function useFormErrors<TData>(\n result:\n | ActionResult<TData>\n | {\n validationErrors?: ValidationErrors;\n serverError?: { code: string; data?: Record<string, unknown> };\n }\n | null\n): FormErrorsResult {\n const empty: FormErrorsResult = {\n fieldErrors: {},\n formErrors: [],\n serverError: null,\n hasErrors: false,\n getFieldError: () => null,\n };\n\n if (!result) return empty;\n\n const validationErrors = result.validationErrors as ValidationErrors | undefined;\n const serverError = result.serverError as\n | { code: string; data?: Record<string, unknown> }\n | undefined;\n\n if (!validationErrors && !serverError) return empty;\n\n // Separate _root (form-level) errors from field errors\n const fieldErrors: Record<string, string[]> = {};\n const formErrors: string[] = [];\n\n if (validationErrors) {\n for (const [key, messages] of Object.entries(validationErrors)) {\n if (key === '_root') {\n formErrors.push(...messages);\n } else {\n fieldErrors[key] = messages;\n }\n }\n }\n\n const hasErrors =\n Object.keys(fieldErrors).length > 0 || formErrors.length > 0 || serverError != null;\n\n return {\n fieldErrors,\n formErrors,\n serverError: serverError ?? null,\n hasErrors,\n getFieldError(field: string): string | null {\n const errs = fieldErrors[field];\n return errs && errs.length > 0 ? errs[0] : null;\n },\n };\n}\n","/**\n * useCookie — reactive client-side cookie hook.\n *\n * Uses useSyncExternalStore for SSR-safe, reactive cookie access.\n * All components reading the same cookie name re-render on change.\n * No cross-tab sync (intentional — see design/29-cookies.md).\n *\n * See design/29-cookies.md §\"useCookie(name) Hook\"\n */\n\nimport { useSyncExternalStore } from 'react';\nimport { getSsrData } from './ssr-data.js';\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\nexport interface ClientCookieOptions {\n /** URL path scope. Default: '/'. */\n path?: string;\n /** Domain scope. Default: omitted (current domain). */\n domain?: string;\n /** Max age in seconds. */\n maxAge?: number;\n /** Expiration date. */\n expires?: Date;\n /** Cross-site policy. Default: 'lax'. */\n sameSite?: 'strict' | 'lax' | 'none';\n /** Only send over HTTPS. Default: true in production. */\n secure?: boolean;\n}\n\nexport type CookieSetter = (value: string, options?: ClientCookieOptions) => void;\n\n// ─── Module-Level Cookie Store ────────────────────────────────────────────\n\ntype Listener = () => void;\n\n/** Per-name subscriber sets. */\nconst listeners = new Map<string, Set<Listener>>();\n\n/** Parse a cookie name from document.cookie. */\nfunction getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n const match = document.cookie.match(\n new RegExp('(?:^|;\\\\s*)' + name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') + '\\\\s*=\\\\s*([^;]*)')\n );\n return match ? decodeURIComponent(match[1]) : undefined;\n}\n\n/** Serialize options into a cookie string suffix. */\nfunction serializeOptions(options?: ClientCookieOptions): string {\n if (!options) return '; Path=/; SameSite=Lax';\n const parts: string[] = [];\n parts.push(`Path=${options.path ?? '/'}`);\n if (options.domain) parts.push(`Domain=${options.domain}`);\n if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);\n if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);\n const sameSite = options.sameSite ?? 'lax';\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);\n if (options.secure) parts.push('Secure');\n return '; ' + parts.join('; ');\n}\n\n/** Notify all subscribers for a given cookie name. */\nfunction notify(name: string): void {\n const subs = listeners.get(name);\n if (subs) {\n for (const fn of subs) fn();\n }\n}\n\n// ─── Hook ─────────────────────────────────────────────────────────────────\n\n/**\n * Reactive hook for reading/writing a client-side cookie.\n *\n * Returns `[value, setCookie, deleteCookie]`:\n * - `value`: current cookie value (string | undefined)\n * - `setCookie`: sets the cookie and triggers re-renders\n * - `deleteCookie`: deletes the cookie and triggers re-renders\n *\n * @param name - Cookie name.\n * @param defaultOptions - Default options for setCookie calls.\n */\nexport function useCookie(\n name: string,\n defaultOptions?: ClientCookieOptions\n): [value: string | undefined, setCookie: CookieSetter, deleteCookie: () => void] {\n const subscribe = (callback: Listener): (() => void) => {\n let subs = listeners.get(name);\n if (!subs) {\n subs = new Set();\n listeners.set(name, subs);\n }\n subs.add(callback);\n return () => {\n subs!.delete(callback);\n if (subs!.size === 0) listeners.delete(name);\n };\n };\n\n const getSnapshot = (): string | undefined => getCookieValue(name);\n const getServerSnapshot = (): string | undefined => getSsrData()?.cookies.get(name);\n\n const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n\n const setCookie: CookieSetter = (newValue: string, options?: ClientCookieOptions) => {\n const merged = { ...defaultOptions, ...options };\n document.cookie = `${name}=${encodeURIComponent(newValue)}${serializeOptions(merged)}`;\n notify(name);\n };\n\n const deleteCookie = (): void => {\n const path = defaultOptions?.path ?? '/';\n const domain = defaultOptions?.domain;\n let cookieStr = `${name}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=${path}`;\n if (domain) cookieStr += `; Domain=${domain}`;\n document.cookie = cookieStr;\n notify(name);\n };\n\n return [value, setCookie, deleteCookie];\n}\n","// @timber-js/app/client — Client-side primitives\n// These are the primary imports for client components.\n//\n// Framework-internal bootstrap, SSR bridge, and segment plumbing is in\n// #client-internal (Node package import).\n// Design doc: design/triage/api-naming-spike.md §8.5\n\n// JsonSerializable moved to @timber-js/app/codec as the single canonical path.\n// Re-export removed per TIM-721.\nexport type { RenderErrorDigest } from './types';\n\n// Navigation\nimport type { JSX } from 'react';\nimport type { SearchParamsDefinition } from '../search-params/define.js';\nimport type { LinkBaseProps } from './link';\nexport { Link, interpolateParams, resolveHref, validateLinkHref, buildLinkProps } from './link';\nexport { mergePreservedSearchParams } from '../shared/merge-search-params.js';\nexport type { LinkProps, LinkPropsWithHref, LinkPropsWithParams, LinkBaseProps } from './link';\nexport type { LinkSegmentParams, OnNavigateHandler, OnNavigateEvent } from './link';\n\n// ─── LinkFunction (originally declared here for module augmentation) ───\n//\n// The codegen emits `declare module '@timber-js/app/client' { interface\n// LinkFunction { ... } }` to add per-route call signatures. TypeScript\n// interface merging via module augmentation only merges with interfaces\n// that are ORIGINALLY DECLARED in the augmented module — a re-exported\n// type binding (`export type { LinkFunction } from './link'`) creates a\n// distinct, unmergeable name. So `LinkFunction` and its supporting\n// `ExternalHref` type must live here, not in `./link.tsx`. The `Link`\n// const in `./link.tsx` imports this interface as a type-only import.\n// See TIM-624.\n\n/**\n * Href types accepted by the catch-all (non-route) call signature.\n *\n * - External protocols: https://, http://, mailto:, tel:, ftp://\n * - Hash-only and query-only links: #section, ?param=value\n * - Computed `string` variables (non-literal)\n *\n * Internal path literals like \"/typo-route\" do NOT match — they must\n * be a known route (from codegen) or stored in a `string` variable.\n * This catches wrong hrefs at the type level.\n */\ntype ExternalHref =\n | `http://${string}`\n | `https://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `ftp://${string}`\n | `//${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * Callable interface for the Link component.\n *\n * Two kinds of call signatures:\n * 1. Per-route (added by codegen via interface merging): DIRECT types\n * for segmentParams — preserves TypeScript excess property checking.\n * 2. Catch-all (below): accepts external hrefs and computed `string`\n * variables. Does NOT accept internal path literals — those must\n * match a known route from the codegen.\n */\nexport interface LinkFunction {\n // External links (literal protocol hrefs)\n (\n props: LinkBaseProps & {\n href: ExternalHref;\n segmentParams?: never;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n }\n ): JSX.Element;\n // Computed/variable href (non-literal string) — e.g. href={myVar}\n // `string extends H` is true only when H is the wide `string` type,\n // not a specific literal. Template literal hrefs like `/blog/${slug}`\n // are handled by resolved-pattern signatures in the codegen.\n <H extends string>(\n props: string extends H\n ? LinkBaseProps & {\n href: H;\n segmentParams?: Record<string, string | number | string[]>;\n searchParams?: {\n definition: SearchParamsDefinition<Record<string, unknown>>;\n values: Record<string, unknown>;\n };\n }\n : never\n ): JSX.Element;\n}\nexport { usePendingNavigation } from './use-pending-navigation';\nexport { useLinkStatus, LinkStatusContext } from './use-link-status';\nexport type { LinkStatus } from './use-link-status';\nexport { useRouter } from './use-router';\nexport type { AppRouterInstance } from './use-router';\nexport { usePathname } from './use-pathname';\nexport { useSearchParams } from './use-search-params';\nexport { useSelectedLayoutSegment, useSelectedLayoutSegments } from './use-selected-layout-segment';\n\n// Forms\nexport { useActionState, useFormAction, useFormErrors } from './form';\nexport type { UseActionStateFn, UseActionStateReturn, FormErrorsResult } from './form';\n\n// Params\nexport { useSegmentParams } from './use-params';\n\n// Query states (URL-synced search params)\nexport { useQueryStates } from './use-query-states';\n\n// Cookies\nexport { useCookie } from './use-cookie';\nexport type { ClientCookieOptions, CookieSetter } from './use-cookie';\n\n// Register the client cookie module with defineCookie's lazy reference.\n// This runs at module load time in the client/SSR environment, wiring up\n// the useCookie hook without a top-level import in define-cookie.ts.\nimport * as _useCookieMod from './use-cookie.js';\nimport { _registerUseCookieModule } from '../cookies/define-cookie.js';\n_registerUseCookieModule(_useCookieMod);\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,IAAa,oBAAoB,cAA0B,EAAE,WAAW,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BhF,SAAgB,gBAA4B;AAC1C,QAAO,WAAW,kBAAkB;;;;;;;ACXtC,SAAgB,mBAAmB,UAAiC;;;;;;;ACJpE,SAAgB,mBAA4B;AAC1C,QACE,OAAO,WAAW,eAClB,gBAAgB,UACf,OAA8C,cAAc;;;;;;;;;ACkBjE,SAAS,mBAA2B;AAClC,KAAI,OAAO,WAAW,YAAa,QAAO,OAAO,SAAS;CAC1D,MAAM,OAAO,YAAY;AACzB,KAAI,CAAC,KAAM,QAAO;CAElB,MAAM,MADK,IAAI,gBAAgB,KAAK,aAAa,CAClC,UAAU;AACzB,QAAO,MAAM,IAAI,QAAQ;;;;;;AA0G3B,IAAM,oBAAoB;AAE1B,SAAgB,iBAAiB,MAAoB;AACnD,KAAI,kBAAkB,KAAK,KAAK,CAC9B,OAAM,IAAI,MACR,sCAAsC,KAAK,4DAE5C;;;AAOL,SAAgB,eAAe,MAAuB;AAEpD,KAAI,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,I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react';
|
|
2
2
|
import type { SearchParamsDefinition } from '../search-params/define.js';
|
|
3
|
+
import type { LinkFunction } from './index.js';
|
|
3
4
|
import { type UrlSegment } from '../routing/segment-classify.js';
|
|
4
5
|
export type OnNavigateEvent = {
|
|
5
6
|
preventDefault: () => void;
|
|
@@ -7,8 +8,12 @@ export type OnNavigateEvent = {
|
|
|
7
8
|
export type OnNavigateHandler = (e: OnNavigateEvent) => void;
|
|
8
9
|
/**
|
|
9
10
|
* Base props shared by all Link variants.
|
|
11
|
+
*
|
|
12
|
+
* Exported so the public `LinkFunction` interface (declared in
|
|
13
|
+
* `./index.ts`, where module augmentation can merge into it) can
|
|
14
|
+
* compose this without duplication.
|
|
10
15
|
*/
|
|
11
|
-
interface LinkBaseProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
|
|
16
|
+
export interface LinkBaseProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
|
|
12
17
|
/** Prefetch the RSC payload on hover */
|
|
13
18
|
prefetch?: boolean;
|
|
14
19
|
/**
|
|
@@ -48,48 +53,6 @@ interface LinkBaseProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'h
|
|
|
48
53
|
export type LinkSegmentParams<T> = {
|
|
49
54
|
[K in keyof T]: [string] extends [T[K]] ? string | number : T[K];
|
|
50
55
|
};
|
|
51
|
-
/**
|
|
52
|
-
* Href types accepted by the catch-all (non-route) call signature.
|
|
53
|
-
*
|
|
54
|
-
* - External protocols: https://, http://, mailto:, tel:, ftp://
|
|
55
|
-
* - Hash-only and query-only links: #section, ?param=value
|
|
56
|
-
* - Computed `string` variables (non-literal)
|
|
57
|
-
*
|
|
58
|
-
* Internal path literals like "/typo-route" do NOT match — they must
|
|
59
|
-
* be a known route (from codegen) or stored in a `string` variable.
|
|
60
|
-
* This catches wrong hrefs at the type level. See TIM-624.
|
|
61
|
-
*/
|
|
62
|
-
type ExternalHref = `http://${string}` | `https://${string}` | `mailto:${string}` | `tel:${string}` | `ftp://${string}` | `//${string}` | `#${string}` | `?${string}`;
|
|
63
|
-
/**
|
|
64
|
-
* Callable interface for the Link component.
|
|
65
|
-
*
|
|
66
|
-
* Two kinds of call signatures:
|
|
67
|
-
* 1. Per-route (added by codegen via interface merging): DIRECT types
|
|
68
|
-
* for segmentParams — preserves TypeScript excess property checking.
|
|
69
|
-
* 2. Catch-all (below): accepts external hrefs and computed `string`
|
|
70
|
-
* variables. Does NOT accept internal path literals — those must
|
|
71
|
-
* match a known route from the codegen.
|
|
72
|
-
*
|
|
73
|
-
* See TIM-624.
|
|
74
|
-
*/
|
|
75
|
-
export interface LinkFunction {
|
|
76
|
-
(props: LinkBaseProps & {
|
|
77
|
-
href: ExternalHref;
|
|
78
|
-
segmentParams?: never;
|
|
79
|
-
searchParams?: {
|
|
80
|
-
definition: SearchParamsDefinition<Record<string, unknown>>;
|
|
81
|
-
values: Record<string, unknown>;
|
|
82
|
-
};
|
|
83
|
-
}): JSX.Element;
|
|
84
|
-
<H extends string>(props: string extends H ? LinkBaseProps & {
|
|
85
|
-
href: H;
|
|
86
|
-
segmentParams?: Record<string, string | number | string[]>;
|
|
87
|
-
searchParams?: {
|
|
88
|
-
definition: SearchParamsDefinition<Record<string, unknown>>;
|
|
89
|
-
values: Record<string, unknown>;
|
|
90
|
-
};
|
|
91
|
-
} : never): JSX.Element;
|
|
92
|
-
}
|
|
93
56
|
/**
|
|
94
57
|
* Runtime-only loose props used internally by the Link implementation.
|
|
95
58
|
* Not exposed to callers — the public API uses LinkFunction.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../../src/client/link.tsx"],"names":[],"mappings":"AAoBA,OAAO,EAIL,KAAK,oBAAoB,EACzB,KAAK,
|
|
1
|
+
{"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../../src/client/link.tsx"],"names":[],"mappings":"AAoBA,OAAO,EAIL,KAAK,oBAAoB,EACzB,KAAK,SAAS,EAEf,MAAM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AAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC,GACA,MAAM,CAyBR;AAID,UAAU,eAAe;IACvB,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,IAAI,CAAC,iBAAiB,EAAE,MAAM,CAAC,GAAG;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;IACpD,YAAY,CAAC,EAAE;QACb,UAAU,EAAE,sBAAsB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;QAC5D,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACjC,CAAC;CACH,GACA,eAAe,CAIjB;AAkCD;;;;;;;;;;;;;;;;GAgBG;AAIH,eAAO,MAAM,IAAI,EAAE,YAoJlB,CAAC"}
|
package/dist/config-types.d.ts
CHANGED
|
@@ -52,6 +52,45 @@ export interface TimberUserConfig {
|
|
|
52
52
|
uploadBodySize?: string;
|
|
53
53
|
maxFields?: number;
|
|
54
54
|
};
|
|
55
|
+
/**
|
|
56
|
+
* Server-action form handling.
|
|
57
|
+
*
|
|
58
|
+
* See design/08-forms-and-actions.md §"Validation errors" and
|
|
59
|
+
* design/13-security.md §"Sensitive field stripping".
|
|
60
|
+
*/
|
|
61
|
+
forms?: {
|
|
62
|
+
/**
|
|
63
|
+
* Strip sensitive fields (passwords, tokens, CVV, SSN, etc.) from the
|
|
64
|
+
* `submittedValues` echoed back on validation failure.
|
|
65
|
+
*
|
|
66
|
+
* Applied to both the with-JS (`createActionClient`) and no-JS (form POST
|
|
67
|
+
* re-render) paths. Safe-by-default: the built-in deny-list is active
|
|
68
|
+
* unless you explicitly opt out.
|
|
69
|
+
*
|
|
70
|
+
* - `true` / omitted — use the built-in deny-list (default, recommended).
|
|
71
|
+
* - `false` — do not strip anything. Dev convenience only; never do this
|
|
72
|
+
* in production — plaintext passwords end up in `defaultValue` attributes,
|
|
73
|
+
* browser history, proxy logs, and the back-forward cache.
|
|
74
|
+
* - `string[]` — additional field names to strip, merged with the built-in list.
|
|
75
|
+
*
|
|
76
|
+
* The built-in list matches (case-insensitive, substring match on
|
|
77
|
+
* normalized names) the following patterns: password / passwd / pwd,
|
|
78
|
+
* secret, apiKey, accessToken, refreshToken, cvv, cvc, cardNumber,
|
|
79
|
+
* cardCvc, ssn, socialSecurityNumber, otp, totp, mfaCode, twoFactorCode,
|
|
80
|
+
* privateKey — plus exact match on `token` (exact-only to avoid
|
|
81
|
+
* false positives on `csrfToken`).
|
|
82
|
+
*
|
|
83
|
+
* **Function predicates are not supported at the global level** because
|
|
84
|
+
* `timber.config.ts` is JSON-serialized into the runtime config and
|
|
85
|
+
* functions cannot cross that boundary. For custom predicates, use
|
|
86
|
+
* the per-action override: `createActionClient({ stripSensitiveFields:
|
|
87
|
+
* (name) => ... })` (functions are supported at the per-action level
|
|
88
|
+
* since `createActionClient` runs in the same module graph as user code).
|
|
89
|
+
*
|
|
90
|
+
* See TIM-816.
|
|
91
|
+
*/
|
|
92
|
+
stripSensitiveFields?: boolean | readonly string[];
|
|
93
|
+
};
|
|
55
94
|
pageExtensions?: string[];
|
|
56
95
|
/**
|
|
57
96
|
* Slow request threshold in milliseconds. Requests exceeding this emit
|