@flightdev/router 0.4.0

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.
@@ -0,0 +1,373 @@
1
+ /**
2
+ * Type definitions for @flightdev/router
3
+ */
4
+ /**
5
+ * Router context value provided to all components
6
+ */
7
+ interface RouterContextValue {
8
+ /** Current pathname (e.g., '/docs/routing') */
9
+ path: string;
10
+ /** URL search params as object */
11
+ searchParams: URLSearchParams;
12
+ /** Navigate to a new path */
13
+ navigate: (to: string, options?: NavigateOptions) => void;
14
+ /** Go back in history */
15
+ back: () => void;
16
+ /** Go forward in history */
17
+ forward: () => void;
18
+ }
19
+ /**
20
+ * Props for RouterProvider component
21
+ */
22
+ interface RouterProviderProps {
23
+ /** Child components */
24
+ children: unknown;
25
+ /** Initial path for SSR (server passes request URL) */
26
+ initialPath?: string;
27
+ /** Base path for the router (e.g., '/app') */
28
+ basePath?: string;
29
+ }
30
+ /**
31
+ * Prefetch strategy for Link component
32
+ *
33
+ * - 'none': No prefetching (default)
34
+ * - 'intent': Prefetch on hover or focus (recommended for most cases)
35
+ * - 'render': Prefetch immediately when link renders
36
+ * - 'viewport': Prefetch when link enters the viewport (good for mobile)
37
+ */
38
+ type PrefetchStrategy = 'none' | 'intent' | 'render' | 'viewport';
39
+ /**
40
+ * Priority level for prefetch requests
41
+ */
42
+ type PrefetchPriority = 'high' | 'low' | 'auto';
43
+ /**
44
+ * Options for programmatic prefetching
45
+ */
46
+ interface PrefetchOptions {
47
+ /** Priority of the prefetch request */
48
+ priority?: PrefetchPriority;
49
+ /** Include data prefetch (loaders) */
50
+ includeData?: boolean;
51
+ /** Include module prefetch (JS chunks) */
52
+ includeModules?: boolean;
53
+ }
54
+ /**
55
+ * Props for Link component
56
+ */
57
+ interface LinkProps {
58
+ /** Target URL path */
59
+ href: string;
60
+ /** Child content */
61
+ children: unknown;
62
+ /** CSS class name */
63
+ className?: string;
64
+ /** Open in new tab */
65
+ target?: string;
66
+ /** Link relationship */
67
+ rel?: string;
68
+ /**
69
+ * Prefetch strategy for the target page.
70
+ *
71
+ * - `true` or `'intent'`: Prefetch on hover/focus
72
+ * - `'render'`: Prefetch when link renders
73
+ * - `'viewport'`: Prefetch when link enters viewport
74
+ * - `false` or `'none'`: No prefetching (default)
75
+ *
76
+ * @default 'none'
77
+ */
78
+ prefetch?: boolean | PrefetchStrategy;
79
+ /** Replace current history entry instead of pushing */
80
+ replace?: boolean;
81
+ /** Scroll to top after navigation */
82
+ scroll?: boolean;
83
+ /** Aria label for accessibility */
84
+ 'aria-label'?: string;
85
+ /** Click handler */
86
+ onClick?: (event: MouseEvent) => void;
87
+ /**
88
+ * Enable View Transitions API for this navigation.
89
+ * Wraps the navigation in document.startViewTransition() with flushSync.
90
+ *
91
+ * @default false
92
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API
93
+ */
94
+ viewTransition?: boolean;
95
+ }
96
+ /**
97
+ * Options for programmatic navigation
98
+ */
99
+ interface NavigateOptions {
100
+ /** Replace current history entry instead of pushing */
101
+ replace?: boolean;
102
+ /** Scroll to top after navigation */
103
+ scroll?: boolean;
104
+ /** State data to pass to the new route */
105
+ state?: unknown;
106
+ /**
107
+ * Enable View Transitions API for this navigation.
108
+ *
109
+ * @default false
110
+ */
111
+ viewTransition?: boolean;
112
+ }
113
+ /**
114
+ * Dynamic route parameters extracted from URL
115
+ */
116
+ type RouteParams<T extends string = string> = Record<T, string>;
117
+ /**
118
+ * Search params as key-value pairs
119
+ */
120
+ type SearchParams = Record<string, string | string[]>;
121
+ /**
122
+ * Route definition for automatic route generation
123
+ */
124
+ interface RouteDefinition {
125
+ /** Route path pattern (e.g., '/docs/:slug') */
126
+ path: string;
127
+ /** Dynamic import for component */
128
+ component: () => Promise<{
129
+ default: unknown;
130
+ }>;
131
+ /** Dynamic imports for layouts (in order, root first) */
132
+ layouts?: Array<() => Promise<{
133
+ default: unknown;
134
+ }>>;
135
+ /** Dynamic import for loader function */
136
+ loader?: () => Promise<{
137
+ loader: LoaderFunction;
138
+ }>;
139
+ }
140
+ /**
141
+ * Loader function signature
142
+ */
143
+ type LoaderFunction = (context: LoaderContext) => Promise<unknown> | unknown;
144
+ /**
145
+ * Context passed to loader functions
146
+ */
147
+ interface LoaderContext {
148
+ /** Route parameters */
149
+ params: RouteParams;
150
+ /** Request object (available on server) */
151
+ request?: Request;
152
+ /** URL search params */
153
+ searchParams: URLSearchParams;
154
+ }
155
+ /**
156
+ * Route match result
157
+ */
158
+ interface RouteMatch {
159
+ /** Matched route definition */
160
+ route: RouteDefinition;
161
+ /** Extracted parameters */
162
+ params: RouteParams;
163
+ /** Matched path */
164
+ pathname: string;
165
+ }
166
+
167
+ /**
168
+ * Router Context and Provider
169
+ *
170
+ * Provides routing state to the component tree.
171
+ * SSR-safe: works on both server and client.
172
+ */
173
+
174
+ /**
175
+ * Subscribe to router context changes
176
+ */
177
+ declare function subscribe(callback: (ctx: RouterContextValue) => void): () => void;
178
+ /**
179
+ * Get current router context value
180
+ */
181
+ declare function getRouterContext(): RouterContextValue;
182
+ /**
183
+ * Initialize router (call once at app start)
184
+ */
185
+ declare function initRouter(options?: {
186
+ initialPath?: string;
187
+ basePath?: string;
188
+ }): void;
189
+ /**
190
+ * React Context for router
191
+ * Only used if React is available
192
+ */
193
+ declare let RouterContext: unknown;
194
+ declare let RouterProvider: unknown;
195
+ declare let useRouter: () => RouterContextValue;
196
+
197
+ /**
198
+ * @flightdev/router - PrefetchPageLinks Component
199
+ *
200
+ * Renders prefetch link tags for a page. Useful for proactively
201
+ * prefetching pages based on user behavior (e.g., search results).
202
+ *
203
+ * This is the Flight equivalent of React Router's PrefetchPageLinks.
204
+ */
205
+
206
+ declare let PrefetchPageLinks: unknown;
207
+ /**
208
+ * Prefetch multiple pages at once.
209
+ *
210
+ * Useful for prefetching a list of search results or related pages.
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * // Prefetch top 5 search results
215
+ * prefetchPages([
216
+ * '/products/1',
217
+ * '/products/2',
218
+ * '/products/3',
219
+ * ]);
220
+ * ```
221
+ */
222
+ declare function prefetchPages(pages: string[], options?: PrefetchOptions): void;
223
+ /**
224
+ * Prefetch a page when idle.
225
+ *
226
+ * Uses requestIdleCallback if available, otherwise falls back
227
+ * to setTimeout.
228
+ *
229
+ * @example
230
+ * ```typescript
231
+ * // Prefetch after initial render settles
232
+ * prefetchWhenIdle('/dashboard');
233
+ * ```
234
+ */
235
+ declare function prefetchWhenIdle(page: string, options?: PrefetchOptions): void;
236
+
237
+ /**
238
+ * Navigation Utilities
239
+ *
240
+ * Programmatic navigation and route matching utilities.
241
+ */
242
+
243
+ /**
244
+ * Navigate programmatically to a new path
245
+ *
246
+ * @example
247
+ * ```ts
248
+ * navigate('/docs');
249
+ * navigate('/login', { replace: true });
250
+ * navigate('/dashboard', { scroll: false, state: { from: '/home' } });
251
+ * ```
252
+ */
253
+ declare function navigate(to: string, options?: NavigateOptions): void;
254
+ /**
255
+ * Match a pathname against a route pattern
256
+ *
257
+ * @example
258
+ * ```ts
259
+ * matchRoute('/docs/routing', '/docs/:slug');
260
+ * // Returns: { params: { slug: 'routing' }, matched: true }
261
+ * ```
262
+ */
263
+ declare function matchRoute(pathname: string, pattern: string): {
264
+ matched: boolean;
265
+ params: RouteParams;
266
+ };
267
+ /**
268
+ * Parse parameters from a matched route
269
+ *
270
+ * @example
271
+ * ```ts
272
+ * parseParams('/blog/2024/my-post', '/blog/:year/:slug');
273
+ * // Returns: { year: '2024', slug: 'my-post' }
274
+ * ```
275
+ */
276
+ declare function parseParams(pathname: string, pattern: string): RouteParams;
277
+ /**
278
+ * Find the best matching route from a list of route definitions
279
+ */
280
+ declare function findRoute(pathname: string, routes: RouteDefinition[]): RouteMatch | null;
281
+ /**
282
+ * Generate a URL from a route pattern and params
283
+ *
284
+ * @example
285
+ * ```ts
286
+ * generatePath('/docs/:slug', { slug: 'routing' });
287
+ * // Returns: '/docs/routing'
288
+ * ```
289
+ */
290
+ declare function generatePath(pattern: string, params?: RouteParams): string;
291
+ /**
292
+ * Check if current path matches a pattern
293
+ */
294
+ declare function isActive(pattern: string): boolean;
295
+ /**
296
+ * Redirect to a new URL (full page navigation)
297
+ * Use this for external redirects or when you need to break out of SPA
298
+ */
299
+ declare function redirect(url: string): never;
300
+
301
+ /**
302
+ * @flightdev/router - Prefetch Utilities
303
+ *
304
+ * Universal prefetch system for Flight Framework.
305
+ * Works across all UI frameworks and runtimes.
306
+ *
307
+ * Features:
308
+ * - Multiple prefetch strategies (intent, render, viewport)
309
+ * - Priority-based prefetching
310
+ * - Module and data prefetching
311
+ * - IntersectionObserver for viewport detection
312
+ * - SSR-safe implementation
313
+ */
314
+
315
+ /**
316
+ * Prefetch a URL with the specified options.
317
+ *
318
+ * This is the main programmatic prefetch API for Flight Framework.
319
+ * It creates appropriate link elements for prefetching resources.
320
+ *
321
+ * @param href - The URL to prefetch
322
+ * @param options - Prefetch configuration options
323
+ *
324
+ * @example
325
+ * ```typescript
326
+ * // Basic prefetch
327
+ * prefetch('/docs');
328
+ *
329
+ * // High priority prefetch (for critical navigation paths)
330
+ * prefetch('/checkout', { priority: 'high' });
331
+ *
332
+ * // Prefetch with data loaders
333
+ * prefetch('/products', { includeData: true });
334
+ * ```
335
+ */
336
+ declare function prefetch(href: string, options?: PrefetchOptions): void;
337
+ /**
338
+ * Prefetch multiple URLs at once.
339
+ *
340
+ * @param hrefs - Array of URLs to prefetch
341
+ * @param options - Prefetch configuration options
342
+ */
343
+ declare function prefetchAll(hrefs: string[], options?: PrefetchOptions): void;
344
+ /**
345
+ * Check if a URL has been prefetched.
346
+ *
347
+ * @param href - The URL to check
348
+ * @returns True if the URL has been prefetched
349
+ */
350
+ declare function isPrefetched(href: string): boolean;
351
+ /**
352
+ * Clear all prefetch state (useful for testing or memory management).
353
+ */
354
+ declare function clearPrefetchCache(): void;
355
+ /**
356
+ * Observe an element for viewport entry and trigger prefetch.
357
+ *
358
+ * @param element - The link element to observe
359
+ * @param href - The URL to prefetch when visible
360
+ * @returns Cleanup function to stop observing
361
+ */
362
+ declare function observeForPrefetch(element: Element, href: string): () => void;
363
+ /**
364
+ * Setup intent-based prefetching for an element.
365
+ * Prefetches on mouseenter or focus.
366
+ *
367
+ * @param element - The link element
368
+ * @param href - The URL to prefetch
369
+ * @returns Cleanup function to remove listeners
370
+ */
371
+ declare function setupIntentPrefetch(element: HTMLElement, href: string): () => void;
372
+
373
+ export { prefetchWhenIdle as A, getRouterContext as B, subscribe as C, initRouter as D, type LinkProps as L, type NavigateOptions as N, type PrefetchStrategy as P, type RouteParams as R, type SearchParams as S, type RouterContextValue as a, type RouterProviderProps as b, type PrefetchPriority as c, type PrefetchOptions as d, type RouteDefinition as e, type LoaderFunction as f, type LoaderContext as g, type RouteMatch as h, RouterContext as i, RouterProvider as j, PrefetchPageLinks as k, findRoute as l, matchRoute as m, navigate as n, generatePath as o, parseParams as p, isActive as q, redirect as r, prefetch as s, prefetchAll as t, useRouter as u, isPrefetched as v, clearPrefetchCache as w, observeForPrefetch as x, setupIntentPrefetch as y, prefetchPages as z };
@@ -0,0 +1,116 @@
1
+ import { L as LinkProps, b as RouterProviderProps, a as RouterContextValue, R as RouteParams } from '../prefetch-DRp54Q7z.js';
2
+ export { g as LoaderContext, f as LoaderFunction, N as NavigateOptions, d as PrefetchOptions, c as PrefetchPriority, P as PrefetchStrategy, e as RouteDefinition, h as RouteMatch, S as SearchParams, w as clearPrefetchCache, l as findRoute, o as generatePath, B as getRouterContext, D as initRouter, q as isActive, v as isPrefetched, m as matchRoute, n as navigate, x as observeForPrefetch, p as parseParams, s as prefetch, t as prefetchAll, z as prefetchPages, A as prefetchWhenIdle, r as redirect, y as setupIntentPrefetch, C as subscribe } from '../prefetch-DRp54Q7z.js';
3
+ import React from 'react';
4
+
5
+ /**
6
+ * React Link Component
7
+ *
8
+ * Provides client-side navigation with prefetching and View Transitions support.
9
+ * Properly imports React for SSR compatibility.
10
+ */
11
+
12
+ /**
13
+ * Flight Link Component for React
14
+ *
15
+ * A drop-in replacement for `<a>` that enables SPA navigation
16
+ * with optional prefetching strategies and View Transitions.
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * // Basic usage
21
+ * <Link href="/docs">Documentation</Link>
22
+ *
23
+ * // With prefetch on hover/focus (recommended)
24
+ * <Link href="/docs" prefetch="intent">Docs</Link>
25
+ *
26
+ * // With View Transitions (smooth page animations)
27
+ * <Link href="/docs" viewTransition>Docs</Link>
28
+ *
29
+ * // Prefetch immediately when link renders
30
+ * <Link href="/checkout" prefetch="render">Checkout</Link>
31
+ *
32
+ * // Prefetch when link enters viewport (good for mobile)
33
+ * <Link href="/products" prefetch="viewport">Products</Link>
34
+ * ```
35
+ */
36
+ declare function Link({ href, children, className, target, rel, prefetch: prefetchProp, replace, scroll, viewTransition, onClick, 'aria-label': ariaLabel, ...props }: LinkProps): React.ReactElement;
37
+
38
+ /**
39
+ * React Router Provider
40
+ *
41
+ * Provides routing context to React component tree.
42
+ * Properly imports React for SSR compatibility.
43
+ */
44
+
45
+ /**
46
+ * React Context for router
47
+ */
48
+ declare const RouterContext: React.Context<RouterContextValue>;
49
+ /**
50
+ * Hook to access router context
51
+ */
52
+ declare function useRouter(): RouterContextValue;
53
+ /**
54
+ * React Router Provider
55
+ *
56
+ * Wraps your app to provide routing context.
57
+ *
58
+ * @example
59
+ * ```tsx
60
+ * import { RouterProvider } from '@flightdev/router/react';
61
+ *
62
+ * function App() {
63
+ * return (
64
+ * <RouterProvider initialPath="/">
65
+ * <YourApp />
66
+ * </RouterProvider>
67
+ * );
68
+ * }
69
+ * ```
70
+ */
71
+ declare function RouterProvider({ children, initialPath, basePath }: RouterProviderProps): React.ReactElement;
72
+
73
+ /**
74
+ * Hook to get current pathname
75
+ *
76
+ * Uses React 18+ useSyncExternalStore for optimal performance.
77
+ *
78
+ * @example
79
+ * ```tsx
80
+ * function Component() {
81
+ * const pathname = usePathname();
82
+ * return <div>Current path: {pathname}</div>;
83
+ * }
84
+ * ```
85
+ */
86
+ declare function usePathname(): string;
87
+ /**
88
+ * Hook to get current search params
89
+ *
90
+ * @example
91
+ * ```tsx
92
+ * function Component() {
93
+ * const searchParams = useSearchParams();
94
+ * const page = searchParams.get('page') || '1';
95
+ * return <div>Page: {page}</div>;
96
+ * }
97
+ * ```
98
+ */
99
+ declare function useSearchParams(): URLSearchParams;
100
+ /**
101
+ * Hook to get route params
102
+ *
103
+ * Note: For dynamic routes like /blog/[slug], the params
104
+ * must be extracted from the pathname using pattern matching.
105
+ *
106
+ * @example
107
+ * ```tsx
108
+ * function BlogPost() {
109
+ * const params = useParams();
110
+ * return <div>Post: {params.slug}</div>;
111
+ * }
112
+ * ```
113
+ */
114
+ declare function useParams(): RouteParams;
115
+
116
+ export { Link, LinkProps, RouteParams, RouterContext, RouterContextValue, RouterProvider, RouterProviderProps, useParams, usePathname, useRouter, useSearchParams };