@lolyjs/core 0.2.0-alpha.26 → 0.2.0-alpha.28

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.
@@ -96,6 +96,7 @@ type RouteMiddleware = (ctx: ServerContext & {
96
96
  * @template TProps - Type of props that will be passed to the component (defaults to Record<string, any>)
97
97
  */
98
98
  interface LoaderResult<TProps extends Record<string, any> = Record<string, any>> {
99
+ pathname?: string;
99
100
  props?: TProps;
100
101
  redirect?: {
101
102
  destination: string;
@@ -96,6 +96,7 @@ type RouteMiddleware = (ctx: ServerContext & {
96
96
  * @template TProps - Type of props that will be passed to the component (defaults to Record<string, any>)
97
97
  */
98
98
  interface LoaderResult<TProps extends Record<string, any> = Record<string, any>> {
99
+ pathname?: string;
99
100
  props?: TProps;
100
101
  redirect?: {
101
102
  destination: string;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../modules/react/cache/index.ts","../../modules/react/cache/client-data-cache/index.ts"],"sourcesContent":["export * from \"./client-data-cache\";","import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkCA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,O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D;AAWA,eAAsB,aACpB,KACA,SACoB;AACpB,QAAM,MAAM,aAAa,GAAG;AAI5B,MAAI,SAAS,YAAY;AACvB,qBAAiB,GAAG;AAAA,EACtB;AAEA,QAAM,QAAQ,UAAU,IAAI,GAAG;AAE/B,MAAI,SAAS,CAAC,SAAS,YAAY;AAEjC,QAAI,MAAM,WAAW,aAAa;AAEhC,gBAAU,GAAG;AACb,aAAO,MAAM;AAAA,IACf;AACA,QAAI,MAAM,WAAW,WAAW;AAE9B,aAAO,MAAM;AAAA,IACf;AAAA,EACF;AAIA,QAAM,kBAAkB,CAAC,SAAS;AAGlC,QAAM,eAAe,UAAU,IAAI,GAAG;AACtC,MAAI,gBAAgB,CAAC,SAAS,YAAY;AACxC,QAAI,aAAa,WAAW,aAAa;AACvC,gBAAU,GAAG;AACb,aAAO,aAAa;AAAA,IACtB;AACA,QAAI,aAAa,WAAW,WAAW;AACrC,aAAO,aAAa;AAAA,IACtB;AAAA,EACF;AAGA,QAAM,UAAU,mBAAmB,KAAK,eAAe,EACpD,KAAK,CAAC,UAAU;AAGf,UAAM,kBAAkB,UAAU,IAAI,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,oBAAc,KAAK,EAAE,QAAQ,aAAa,MAAM,CAAC;AAAA,IACnD;AACA,WAAO;AAAA,EACT,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,YAAQ,MAAM,8CAA8C,KAAK;AACjE,UAAM,kBAAkB,UAAU,IAAI,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,gBAAU,IAAI,KAAK,EAAE,QAAQ,YAAY,MAAM,CAAC;AAAA,IAClD;AACA,UAAM;AAAA,EACR,CAAC;AAGH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AAEjD,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../modules/react/cache/index.ts","../../modules/react/cache/client-data-cache/index.ts"],"sourcesContent":["export * from \"./client-data-cache\";","import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n /** Pathname after rewrite (for client-side route matching) */\n pathname?: string;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,OAAe,SAAS,GAAG;AAC/B,MAAC,OAAe,SAAS,IAAI;AAAA,QAC3B,MAAM,oBAAI,IAAwB;AAAA,QAClC,OAAO,oBAAI,IAAyB;AAAA,QACpC,KAAK,CAAC;AAAA,MACR;AAAA,IACF;AACA,WAAQ,OAAe,SAAS;AAAA,EAClC;AAEA,SAAO;AAAA,IACL,MAAM,oBAAI,IAAwB;AAAA,IAClC,OAAO,oBAAI,IAAyB;AAAA,IACpC,KAAK,CAAC;AAAA,EACR;AACF;AAEA,IAAM,aAAa,cAAc;AACjC,IAAM,YAAY,WAAW;AAC7B,IAAM,YAAY,WAAW;AAC7B,IAAM,MAAM,WAAW;AAOvB,SAAS,gBAAgB,KAAqB;AAC5C,SAAO,IAAI,MAAM,GAAG,EAAE,CAAC;AACzB;AAKA,SAAS,WAAW,KAAmB;AACrC,QAAM,WAAW,gBAAgB,GAAG;AACpC,MAAI,CAAC,UAAU,IAAI,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;AAAA,IACtB;AAAA,EACF;AAGA,QAAM,UAAU,mBAAmB,KAAK,eAAe,EACpD,KAAK,CAAC,UAAU;AAGf,UAAM,kBAAkB,UAAU,IAAI,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,oBAAc,KAAK,EAAE,QAAQ,aAAa,MAAM,CAAC;AAAA,IACnD;AACA,WAAO;AAAA,EACT,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,YAAQ,MAAM,8CAA8C,KAAK;AACjE,UAAM,kBAAkB,UAAU,IAAI,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,gBAAU,IAAI,KAAK,EAAE,QAAQ,YAAY,MAAM,CAAC;AAAA,IAClD;AACA,UAAM;AAAA,EACR,CAAC;AAGH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AAEjD,SAAO;AACT;","names":[]}
@@ -1,4 +1,4 @@
1
- import { P as PageMetadata } from '../index.types-DMOO-uvF.mjs';
1
+ import { P as PageMetadata } from '../index.types-B9j4OQft.mjs';
2
2
  import 'express';
3
3
 
4
4
  /**
@@ -21,6 +21,8 @@ type RouteDataResponse = {
21
21
  error?: boolean;
22
22
  message?: string;
23
23
  params?: Record<string, string>;
24
+ /** Pathname after rewrite (for client-side route matching) */
25
+ pathname?: string;
24
26
  };
25
27
  type RouteData = {
26
28
  ok: boolean;
@@ -1,4 +1,4 @@
1
- import { P as PageMetadata } from '../index.types-DMOO-uvF.js';
1
+ import { P as PageMetadata } from '../index.types-B9j4OQft.js';
2
2
  import 'express';
3
3
 
4
4
  /**
@@ -21,6 +21,8 @@ type RouteDataResponse = {
21
21
  error?: boolean;
22
22
  message?: string;
23
23
  params?: Record<string, string>;
24
+ /** Pathname after rewrite (for client-side route matching) */
25
+ pathname?: string;
24
26
  };
25
27
  type RouteData = {
26
28
  ok: boolean;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../modules/react/cache/client-data-cache/index.ts"],"sourcesContent":["import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n"],"mappings":";AAkCA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,OAAe,SAAS,GAAG;AAC/B,MAAC,OAAe,SAAS,IAAI;AAAA,QAC3B,MAAM,oBAAI,IAAwB;AAAA,QAClC,OAAO,oBAAI,IAAyB;AAAA,QACpC,KAAK,CAAC;AAAA,MACR;AAAA,IACF;AACA,WAAQ,OAAe,SAAS;AAAA,EAClC;AAEA,SAAO;AAAA,IACL,MAAM,oBAAI,IAAwB;AAAA,IAClC,OAAO,oBAAI,IAAyB;AAAA,IACpC,KAAK,CAAC;AAAA,EACR;AACF;AAEA,IAAM,aAAa,cAAc;AACjC,IAAM,YAAY,WAAW;AAC7B,IAAM,YAAY,WAAW;AAC7B,IAAM,MAAM,WAAW;AAOvB,SAAS,gBAAgB,KAAqB;AAC5C,SAAO,IAAI,MAAM,GAAG,EAAE,CAAC;AACzB;AAKA,SAAS,WAAW,KAAmB;AACrC,QAAM,WAAW,gBAAgB,GAAG;AACpC,MAAI,CAAC,UAAU,IAAI,QAAQ,GAAG;AAC5B,cAAU,IAAI,UAAU,oBAAI,IAAI,CAAC;AAAA,EACnC;AACA,YAAU,IAAI,QAAQ,EAAG,IAAI,GAAG;AAClC;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,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,oBAAc,KAAK,EAAE,QAAQ,aAAa,MAAM,CAAC;AAAA,IACnD;AACA,WAAO;AAAA,EACT,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,YAAQ,MAAM,8CAA8C,KAAK;AACjE,UAAM,kBAAkB,UAAU,IAAI,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,gBAAU,IAAI,KAAK,EAAE,QAAQ,YAAY,MAAM,CAAC;AAAA,IAClD;AACA,UAAM;AAAA,EACR,CAAC;AAGH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AAEjD,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../modules/react/cache/client-data-cache/index.ts"],"sourcesContent":["import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n /** Pathname after rewrite (for client-side route matching) */\n pathname?: string;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n"],"mappings":";AAoCA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,OAAe,SAAS,GAAG;AAC/B,MAAC,OAAe,SAAS,IAAI;AAAA,QAC3B,MAAM,oBAAI,IAAwB;AAAA,QAClC,OAAO,oBAAI,IAAyB;AAAA,QACpC,KAAK,CAAC;AAAA,MACR;AAAA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AG;AAE/B,MAAI,SAAS,CAAC,SAAS,YAAY;AAEjC,QAAI,MAAM,WAAW,aAAa;AAEhC,gBAAU,GAAG;AACb,aAAO,MAAM;AAAA,IACf;AACA,QAAI,MAAM,WAAW,WAAW;AAE9B,aAAO,MAAM;AAAA,IACf;AAAA,EACF;AAIA,QAAM,kBAAkB,CAAC,SAAS;AAGlC,QAAM,eAAe,UAAU,IAAI,GAAG;AACtC,MAAI,gBAAgB,CAAC,SAAS,YAAY;AACxC,QAAI,aAAa,WAAW,aAAa;AACvC,gBAAU,GAAG;AACb,aAAO,aAAa;AAAA,IACtB;AACA,QAAI,aAAa,WAAW,WAAW;AACrC,aAAO,aAAa;AAAA,IACtB;AAAA,EACF;AAGA,QAAM,UAAU,mBAAmB,KAAK,eAAe,EACpD,KAAK,CAAC,UAAU;AAGf,UAAM,kBAAkB,UAAU,IAAI,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,oBAAc,KAAK,EAAE,QAAQ,aAAa,MAAM,CAAC;AAAA,IACnD;AACA,WAAO;AAAA,EACT,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,YAAQ,MAAM,8CAA8C,KAAK;AACjE,UAAM,kBAAkB,UAAU,IAAI,GAAG;AACzC,QAAI,CAAC,mBAAmB,gBAAgB,WAAW,WAAW;AAC5D,gBAAU,IAAI,KAAK,EAAE,QAAQ,YAAY,MAAM,CAAC;AAAA,IAClD;AACA,UAAM;AAAA,EACR,CAAC;AAGH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AAEjD,SAAO;AACT;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../modules/react/components/index.ts","../../modules/react/components/Image/index.tsx","../../modules/react/cache/client-data-cache/index.ts","../../modules/react/components/Link/index.tsx"],"sourcesContent":["export { Image } from \"./Image\";\r\nexport { Link } from \"./Link\";","import React from 'react';\r\n\r\nconst BASE_DIR = \"/static/assets\";\r\n\r\ninterface ImageProps\r\n extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, \"src\" | \"alt\"> {\r\n src: string;\r\n alt: string;\r\n width?: number;\r\n height?: number;\r\n className?: string;\r\n}\r\n\r\n/**\r\n * Image component that handles static asset paths.\r\n *\r\n * Automatically prefixes relative paths with the static assets directory.\r\n *\r\n * @param props - Image component props\r\n * @returns Image element\r\n */\r\nexport function Image({\r\n src,\r\n alt,\r\n width,\r\n height,\r\n className,\r\n ...rest\r\n}: ImageProps) {\r\n const style: React.CSSProperties = {};\r\n\r\n if (width) style.width = width;\r\n if (height) style.height = height;\r\n\r\n const isRelative = !src.startsWith('http');\r\n const FULL_ROUTE = isRelative ? `${BASE_DIR}/${src}` : src;\r\n\r\n return (\r\n <img\r\n src={FULL_ROUTE}\r\n alt={alt}\r\n width={width}\r\n height={height}\r\n className={className}\r\n style={style}\r\n {...rest}\r\n />\r\n );\r\n}\r\n","import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n","import React from \"react\";\r\nimport { prefetchRouteData } from \"../../cache/index\";\r\n\r\ninterface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {\r\n href: string;\r\n children: React.ReactNode;\r\n prefetch?: boolean;\r\n}\r\n\r\nimport { useEffect, useRef } from \"react\"; \r\n\r\nfunction isExternal(href: string) {\r\n try {\r\n const url = new URL(href, window.location.href);\r\n return url.origin !== window.location.origin;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nexport function Link({\r\n href,\r\n prefetch = true,\r\n children,\r\n ...rest\r\n}: React.PropsWithChildren<{\r\n href: string;\r\n prefetch?: boolean;\r\n}> &\r\n React.AnchorHTMLAttributes<HTMLAnchorElement>) {\r\n const ref = useRef<HTMLAnchorElement | null>(null);\r\n\r\n useEffect(() => {\r\n if (!prefetch || !ref.current || isExternal(href)) return;\r\n\r\n const el = ref.current;\r\n let prefetched = false;\r\n\r\n const io = new IntersectionObserver(([entry]) => {\r\n if (entry.isIntersecting && !prefetched) {\r\n prefetched = true;\r\n prefetchRouteData(href);\r\n }\r\n });\r\n\r\n io.observe(el);\r\n return () => io.disconnect();\r\n }, [href, prefetch]);\r\n\r\n return (\r\n <a ref={ref} href={href} {...rest}>\r\n {children}\r\n </a>\r\n );\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsCI;AApCJ,IAAM,WAAW;AAmBV,SAAS,MAAM;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAe;AACb,QAAM,QAA6B,CAAC;AAEpC,MAAI,MAAO,OAAM,QAAQ;AACzB,MAAI,OAAQ,OAAM,SAAS;AAE3B,QAAM,aAAa,CAAC,IAAI,WAAW,MAAM;AACzC,QAAM,aAAa,aAAa,GAAG,QAAQ,IAAI,GAAG,KAAK;AAEvD,SACE;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACC,GAAG;AAAA;AAAA,EACN;AAEJ;;;ACdA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,OAAe,SAAS,GAAG;AAC/B,MAAC,OAAe,SAAS,IAAI;AAAA,QAC3B,MAAM,oBAAI,IAA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;AAAA,EACT,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,YAAQ,MAAM,iDAAiD,KAAK;AACpE,cAAU,IAAI,KAAK,EAAE,QAAQ,YAAY,MAAM,CAAC;AAChD,UAAM;AAAA,EACR,CAAC;AAEH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AACnD;;;ACpbA,mBAAkC;AAyC9B,IAAAA,sBAAA;AAvCJ,SAAS,WAAW,MAAc;AAChC,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,MAAM,OAAO,SAAS,IAAI;AAC9C,WAAO,IAAI,WAAW,OAAO,SAAS;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,KAAK;AAAA,EACnB;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA,GAAG;AACL,GAIiD;AAC/C,QAAM,UAAM,qBAAiC,IAAI;AAEjD,8BAAU,MAAM;AACd,QAAI,CAAC,YAAY,CAAC,IAAI,WAAW,WAAW,IAAI,EAAG;AAEnD,UAAM,KAAK,IAAI;AACf,QAAI,aAAa;AAEjB,UAAM,KAAK,IAAI,qBAAqB,CAAC,CAAC,KAAK,MAAM;AAC/C,UAAI,MAAM,kBAAkB,CAAC,YAAY;AACvC,qBAAa;AACb,0BAAkB,IAAI;AAAA,MACxB;AAAA,IACF,CAAC;AAED,OAAG,QAAQ,EAAE;AACb,WAAO,MAAM,GAAG,WAAW;AAAA,EAC7B,GAAG,CAAC,MAAM,QAAQ,CAAC;AAEnB,SACE,6CAAC,OAAE,KAAU,MAAa,GAAG,MAC1B,UACH;AAEJ;","names":["import_jsx_runtime"]}
1
+ {"version":3,"sources":["../../modules/react/components/index.ts","../../modules/react/components/Image/index.tsx","../../modules/react/cache/client-data-cache/index.ts","../../modules/react/components/Link/index.tsx"],"sourcesContent":["export { Image } from \"./Image\";\r\nexport { Link } from \"./Link\";","import React from 'react';\r\n\r\nconst BASE_DIR = \"/static/assets\";\r\n\r\ninterface ImageProps\r\n extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, \"src\" | \"alt\"> {\r\n src: string;\r\n alt: string;\r\n width?: number;\r\n height?: number;\r\n className?: string;\r\n}\r\n\r\n/**\r\n * Image component that handles static asset paths.\r\n *\r\n * Automatically prefixes relative paths with the static assets directory.\r\n *\r\n * @param props - Image component props\r\n * @returns Image element\r\n */\r\nexport function Image({\r\n src,\r\n alt,\r\n width,\r\n height,\r\n className,\r\n ...rest\r\n}: ImageProps) {\r\n const style: React.CSSProperties = {};\r\n\r\n if (width) style.width = width;\r\n if (height) style.height = height;\r\n\r\n const isRelative = !src.startsWith('http');\r\n const FULL_ROUTE = isRelative ? `${BASE_DIR}/${src}` : src;\r\n\r\n return (\r\n <img\r\n src={FULL_ROUTE}\r\n alt={alt}\r\n width={width}\r\n height={height}\r\n className={className}\r\n style={style}\r\n {...rest}\r\n />\r\n );\r\n}\r\n","import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n /** Pathname after rewrite (for client-side route matching) */\n pathname?: string;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n","import React from \"react\";\r\nimport { prefetchRouteData } from \"../../cache/index\";\r\n\r\ninterface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {\r\n href: string;\r\n children: React.ReactNode;\r\n prefetch?: boolean;\r\n}\r\n\r\nimport { useEffect, useRef } from \"react\"; \r\n\r\nfunction isExternal(href: string) {\r\n try {\r\n const url = new URL(href, window.location.href);\r\n return url.origin !== window.location.origin;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nexport function Link({\r\n href,\r\n prefetch = true,\r\n children,\r\n ...rest\r\n}: React.PropsWithChildren<{\r\n href: string;\r\n prefetch?: boolean;\r\n}> &\r\n React.AnchorHTMLAttributes<HTMLAnchorElement>) {\r\n const ref = useRef<HTMLAnchorElement | null>(null);\r\n\r\n useEffect(() => {\r\n if (!prefetch || !ref.current || isExternal(href)) return;\r\n\r\n const el = ref.current;\r\n let prefetched = false;\r\n\r\n const io = new IntersectionObserver(([entry]) => {\r\n if (entry.isIntersecting && !prefetched) {\r\n prefetched = true;\r\n prefetchRouteData(href);\r\n }\r\n });\r\n\r\n io.observe(el);\r\n return () => io.disconnect();\r\n }, [href, prefetch]);\r\n\r\n return (\r\n <a ref={ref} href={href} {...rest}>\r\n {children}\r\n </a>\r\n );\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsCI;AApCJ,IAAM,WAAW;AAmBV,SAAS,MAAM;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAe;AACb,QAAM,QAA6B,CAAC;AAEpC,MAAI,MAAO,OAAM,QAAQ;AACzB,MAAI,OAAQ,OAAM,SAAS;AAE3B,QAAM,aAAa,CAAC,IAAI,WAAW,MAAM;AACzC,QAAM,aAAa,aAAa,GAAG,QAAQ,IAAI,GAAG,KAAK;AAEvD,SACE;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACC,GAAG;AAAA;AAAA,EACN;AAEJ;;;ACZA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,OAAe,SAAS,GAAG;AAC/B,MAAC,OAAe,SAAS,I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AAQ,aAAa,MAAM,CAAC;AACjD,WAAO;AAAA,EACT,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,YAAQ,MAAM,iDAAiD,KAAK;AACpE,cAAU,IAAI,KAAK,EAAE,QAAQ,YAAY,MAAM,CAAC;AAChD,UAAM;AAAA,EACR,CAAC;AAEH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AACnD;;;ACtbA,mBAAkC;AAyC9B,IAAAA,sBAAA;AAvCJ,SAAS,WAAW,MAAc;AAChC,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,MAAM,OAAO,SAAS,IAAI;AAC9C,WAAO,IAAI,WAAW,OAAO,SAAS;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,KAAK;AAAA,EACnB;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA,GAAG;AACL,GAIiD;AAC/C,QAAM,UAAM,qBAAiC,IAAI;AAEjD,8BAAU,MAAM;AACd,QAAI,CAAC,YAAY,CAAC,IAAI,WAAW,WAAW,IAAI,EAAG;AAEnD,UAAM,KAAK,IAAI;AACf,QAAI,aAAa;AAEjB,UAAM,KAAK,IAAI,qBAAqB,CAAC,CAAC,KAAK,MAAM;AAC/C,UAAI,MAAM,kBAAkB,CAAC,YAAY;AACvC,qBAAa;AACb,0BAAkB,IAAI;AAAA,MACxB;AAAA,IACF,CAAC;AAED,OAAG,QAAQ,EAAE;AACb,WAAO,MAAM,GAAG,WAAW;AAAA,EAC7B,GAAG,CAAC,MAAM,QAAQ,CAAC;AAEnB,SACE,6CAAC,OAAE,KAAU,MAAa,GAAG,MAC1B,UACH;AAEJ;","names":["import_jsx_runtime"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../modules/react/components/Image/index.tsx","../../modules/react/cache/client-data-cache/index.ts","../../modules/react/components/Link/index.tsx"],"sourcesContent":["import React from 'react';\r\n\r\nconst BASE_DIR = \"/static/assets\";\r\n\r\ninterface ImageProps\r\n extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, \"src\" | \"alt\"> {\r\n src: string;\r\n alt: string;\r\n width?: number;\r\n height?: number;\r\n className?: string;\r\n}\r\n\r\n/**\r\n * Image component that handles static asset paths.\r\n *\r\n * Automatically prefixes relative paths with the static assets directory.\r\n *\r\n * @param props - Image component props\r\n * @returns Image element\r\n */\r\nexport function Image({\r\n src,\r\n alt,\r\n width,\r\n height,\r\n className,\r\n ...rest\r\n}: ImageProps) {\r\n const style: React.CSSProperties = {};\r\n\r\n if (width) style.width = width;\r\n if (height) style.height = height;\r\n\r\n const isRelative = !src.startsWith('http');\r\n const FULL_ROUTE = isRelative ? `${BASE_DIR}/${src}` : src;\r\n\r\n return (\r\n <img\r\n src={FULL_ROUTE}\r\n alt={alt}\r\n width={width}\r\n height={height}\r\n className={className}\r\n style={style}\r\n {...rest}\r\n />\r\n );\r\n}\r\n","import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n","import React from \"react\";\r\nimport { prefetchRouteData } from \"../../cache/index\";\r\n\r\ninterface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {\r\n href: string;\r\n children: React.ReactNode;\r\n prefetch?: boolean;\r\n}\r\n\r\nimport { useEffect, useRef } from \"react\"; \r\n\r\nfunction isExternal(href: string) {\r\n try {\r\n const url = new URL(href, window.location.href);\r\n return url.origin !== window.location.origin;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nexport function Link({\r\n href,\r\n prefetch = true,\r\n children,\r\n ...rest\r\n}: React.PropsWithChildren<{\r\n href: string;\r\n prefetch?: boolean;\r\n}> &\r\n React.AnchorHTMLAttributes<HTMLAnchorElement>) {\r\n const ref = useRef<HTMLAnchorElement | null>(null);\r\n\r\n useEffect(() => {\r\n if (!prefetch || !ref.current || isExternal(href)) return;\r\n\r\n const el = ref.current;\r\n let prefetched = false;\r\n\r\n const io = new IntersectionObserver(([entry]) => {\r\n if (entry.isIntersecting && !prefetched) {\r\n prefetched = true;\r\n prefetchRouteData(href);\r\n }\r\n });\r\n\r\n io.observe(el);\r\n return () => io.disconnect();\r\n }, [href, prefetch]);\r\n\r\n return (\r\n <a ref={ref} href={href} {...rest}>\r\n {children}\r\n </a>\r\n );\r\n}\r\n"],"mappings":";AAsCI;AApCJ,IAAM,WAAW;AAmBV,SAAS,MAAM;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAe;AACb,QAAM,QAA6B,CAAC;AAEpC,MAAI,MAAO,OAAM,QAAQ;AACzB,MAAI,OAAQ,OAAM,SAAS;AAE3B,QAAM,aAAa,CAAC,IAAI,WAAW,MAAM;AACzC,QAAM,aAAa,aAAa,GAAG,QAAQ,IAAI,GAAG,KAAK;AAEvD,SACE;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACC,GAAG;AAAA;AAAA,EACN;AAEJ;;;ACdA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,OAAe,SAAS,GAAG;AAC/B,MAAC,OAAe,SAAS,IAAI;AAAA,QAC3B,MAAM,oBAAI,IAAwB;AAAA,QAClC,OAAO,oBAAI,IAAyB;AAAA,QACpC,KAAK,CAAC;AAAA,MACR;A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K;AACpE,cAAU,IAAI,KAAK,EAAE,QAAQ,YAAY,MAAM,CAAC;AAChD,UAAM;AAAA,EACR,CAAC;AAEH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AACnD;;;ACpbA,SAAS,WAAW,cAAc;AAyC9B,gBAAAA,YAAA;AAvCJ,SAAS,WAAW,MAAc;AAChC,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,MAAM,OAAO,SAAS,IAAI;AAC9C,WAAO,IAAI,WAAW,OAAO,SAAS;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,KAAK;AAAA,EACnB;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA,GAAG;AACL,GAIiD;AAC/C,QAAM,MAAM,OAAiC,IAAI;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC,YAAY,CAAC,IAAI,WAAW,WAAW,IAAI,EAAG;AAEnD,UAAM,KAAK,IAAI;AACf,QAAI,aAAa;AAEjB,UAAM,KAAK,IAAI,qBAAqB,CAAC,CAAC,KAAK,MAAM;AAC/C,UAAI,MAAM,kBAAkB,CAAC,YAAY;AACvC,qBAAa;AACb,0BAAkB,IAAI;AAAA,MACxB;AAAA,IACF,CAAC;AAED,OAAG,QAAQ,EAAE;AACb,WAAO,MAAM,GAAG,WAAW;AAAA,EAC7B,GAAG,CAAC,MAAM,QAAQ,CAAC;AAEnB,SACE,gBAAAA,KAAC,OAAE,KAAU,MAAa,GAAG,MAC1B,UACH;AAEJ;","names":["jsx"]}
1
+ {"version":3,"sources":["../../modules/react/components/Image/index.tsx","../../modules/react/cache/client-data-cache/index.ts","../../modules/react/components/Link/index.tsx"],"sourcesContent":["import React from 'react';\r\n\r\nconst BASE_DIR = \"/static/assets\";\r\n\r\ninterface ImageProps\r\n extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, \"src\" | \"alt\"> {\r\n src: string;\r\n alt: string;\r\n width?: number;\r\n height?: number;\r\n className?: string;\r\n}\r\n\r\n/**\r\n * Image component that handles static asset paths.\r\n *\r\n * Automatically prefixes relative paths with the static assets directory.\r\n *\r\n * @param props - Image component props\r\n * @returns Image element\r\n */\r\nexport function Image({\r\n src,\r\n alt,\r\n width,\r\n height,\r\n className,\r\n ...rest\r\n}: ImageProps) {\r\n const style: React.CSSProperties = {};\r\n\r\n if (width) style.width = width;\r\n if (height) style.height = height;\r\n\r\n const isRelative = !src.startsWith('http');\r\n const FULL_ROUTE = isRelative ? `${BASE_DIR}/${src}` : src;\r\n\r\n return (\r\n <img\r\n src={FULL_ROUTE}\r\n alt={alt}\r\n width={width}\r\n height={height}\r\n className={className}\r\n style={style}\r\n {...rest}\r\n />\r\n );\r\n}\r\n","import type { PageMetadata } from \"@router/index\";\n\n/**\n * Response data structure from server for route data requests\n */\nexport type RouteDataResponse = {\n /** Combined props (layout + page) - kept for backward compatibility */\n props?: Record<string, unknown>;\n /** Layout props (from layout.server.hook.ts) - only present when layout hooks were executed */\n layoutProps?: Record<string, unknown>;\n /** Page props (from page.server.hook.ts) - always present in data requests */\n pageProps?: Record<string, unknown>;\n metadata?: PageMetadata | null;\n theme?: string;\n redirect?: { destination: string; permanent?: boolean };\n notFound?: boolean;\n error?: boolean;\n message?: string;\n params?: Record<string, string>;\n /** Pathname after rewrite (for client-side route matching) */\n pathname?: string;\n};\n\ntype RouteData = {\n ok: boolean;\n status: number;\n json: RouteDataResponse;\n};\n\ntype CacheEntry =\n | { status: \"pending\"; promise: Promise<RouteData> }\n | { status: \"fulfilled\"; value: RouteData }\n | { status: \"rejected\"; error: any };\n\n// Use window to guarantee a single shared cache instance\n// across all bundles/modules\nconst CACHE_KEY = \"__FW_DATA_CACHE__\";\n\n// Maximum number of entries in the cache (LRU)\nconst MAX_CACHE_SIZE = 100;\n\ntype CacheStore = {\n data: Map<string, CacheEntry>;\n index: Map<string, Set<string>>; // pathBase -> Set of keys\n lru: string[]; // Ordered list: most recent at end, oldest at start\n};\n\nfunction getCacheStore(): CacheStore {\n if (typeof window !== \"undefined\") {\n if (!(window as any)[CACHE_KEY]) {\n (window as any)[CACHE_KEY] = {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n }\n return (window as any)[CACHE_KEY];\n }\n // Fallback for SSR (though this shouldn't be used on the client)\n return {\n data: new Map<string, CacheEntry>(),\n index: new Map<string, Set<string>>(),\n lru: [],\n };\n}\n\nconst cacheStore = getCacheStore();\nconst dataCache = cacheStore.data;\nconst pathIndex = cacheStore.index;\nconst lru = cacheStore.lru;\n\n// Helper functions for cache management\n\n/**\n * Extract base path from a cache key (removes query params)\n */\nfunction extractPathBase(key: string): string {\n return key.split(\"?\")[0];\n}\n\n/**\n * Add key to path index\n */\nfunction addToIndex(key: string): void {\n const pathBase = extractPathBase(key);\n if (!pathIndex.has(pathBase)) {\n pathIndex.set(pathBase, new Set());\n }\n pathIndex.get(pathBase)!.add(key);\n}\n\n/**\n * Remove key from path index\n */\nfunction removeFromIndex(key: string): void {\n const pathBase = extractPathBase(key);\n const keys = pathIndex.get(pathBase);\n if (keys) {\n keys.delete(key);\n if (keys.size === 0) {\n pathIndex.delete(pathBase);\n }\n }\n}\n\n/**\n * Update LRU order - move key to end (most recent)\n */\nfunction updateLRU(key: string): void {\n const index = lru.indexOf(key);\n if (index !== -1) {\n lru.splice(index, 1);\n }\n lru.push(key);\n}\n\n/**\n * Remove oldest entries if cache exceeds MAX_CACHE_SIZE\n */\nfunction evictOldest(): void {\n while (lru.length >= MAX_CACHE_SIZE && lru.length > 0) {\n const oldestKey = lru.shift()!;\n dataCache.delete(oldestKey);\n removeFromIndex(oldestKey);\n }\n}\n\n/**\n * Set cache entry and maintain indexes\n */\nfunction setCacheEntry(key: string, entry: CacheEntry): void {\n const existingEntry = dataCache.get(key);\n const wasFulfilled = existingEntry?.status === \"fulfilled\";\n \n dataCache.set(key, entry);\n \n // Only track fulfilled entries in LRU and index (not pending/rejected)\n if (entry.status === \"fulfilled\") {\n // Add to index if it wasn't already fulfilled (new entry or transition from pending/rejected)\n if (!wasFulfilled) {\n addToIndex(key);\n }\n updateLRU(key);\n evictOldest();\n } else if (wasFulfilled) {\n // If entry was fulfilled and now isn't (transitioning to pending/rejected), remove from index\n removeFromIndex(key);\n }\n}\n\n/**\n * Delete cache entry and clean up indexes\n */\nfunction deleteCacheEntry(key: string): void {\n if (dataCache.has(key)) {\n dataCache.delete(key);\n removeFromIndex(key);\n const lruIndex = lru.indexOf(key);\n if (lruIndex !== -1) {\n lru.splice(lruIndex, 1);\n }\n }\n}\n\nfunction buildDataUrl(url: string): string {\n return url + (url.includes(\"?\") ? \"&\" : \"?\") + \"__fw_data=1\";\n}\n\nasync function fetchRouteDataOnce(\n url: string,\n skipLayoutHooks: boolean = true\n): Promise<RouteData> {\n const dataUrl = buildDataUrl(url);\n\n const headers: Record<string, string> = {\n \"x-fw-data\": \"1\",\n Accept: \"application/json\",\n };\n\n // Send header to skip layout hooks execution in SPA navigation\n // Only skip if skipLayoutHooks is true (normal SPA navigation)\n // If false (revalidate), don't send header to force execution of all hooks\n if (skipLayoutHooks) {\n headers[\"x-skip-layout-hooks\"] = \"true\";\n }\n\n const res = await fetch(dataUrl, { headers });\n\n let json: any = {};\n\n try {\n const text = await res.text();\n if (text) {\n json = JSON.parse(text);\n }\n } catch (parseError) {\n console.error(\n \"[client][cache] Failed to parse response as JSON:\",\n parseError\n );\n }\n\n const result: RouteData = {\n ok: res.ok,\n status: res.status,\n json,\n };\n\n return result;\n}\n\n/**\n * Revalidates route data by removing it from the cache.\n * The next time you navigate to this route, fresh data will be fetched from the server.\n * This is a client-side function and does not require a server-side revalidation.\n *\n * @param path - The route path to revalidate (e.g., '/posts/1' or '/posts/1?page=2')\n * If query params are not included, revalidates all variants of that route.\n *\n * @example\n * ```ts\n * // After saving something to the DB, revalidate the route\n * await saveToDatabase(data);\n * revalidatePath('/posts');\n * \n * // Revalidate a specific route with query params\n * revalidatePath('/posts?page=2');\n * ```\n */\nexport function revalidatePath(path: string, skipAutoRevalidate: boolean = false): void {\n // Normalize the base path (without query params)\n const normalizedPath = path.split(\"?\")[0];\n const hasQueryParams = path.includes(\"?\");\n \n // Get all keys for this path base from index (O(1) lookup)\n const keysForPath = pathIndex.get(normalizedPath);\n \n if (!keysForPath || keysForPath.size === 0) {\n return; // No entries to revalidate\n }\n \n // If the path includes specific query params, extract them\n let specificQueryParams: string | undefined;\n if (hasQueryParams) {\n const queryPart = path.split(\"?\")[1];\n // Sort query params for consistent comparison\n specificQueryParams = queryPart\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n }\n \n // Iterate only over keys for this path (much smaller set)\n const keysToDelete: string[] = [];\n for (const key of keysForPath) {\n // If specific query params were specified, check if they match\n if (hasQueryParams && specificQueryParams) {\n const [, keyQuery = \"\"] = key.split(\"?\");\n const keyQueryParams = keyQuery\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (keyQueryParams === specificQueryParams) {\n keysToDelete.push(key);\n }\n } else {\n // If no specific query params, revalidate all variants\n keysToDelete.push(key);\n }\n }\n \n // Delete matching entries\n keysToDelete.forEach((key) => {\n deleteCacheEntry(key);\n });\n \n // If the revalidated path matches the current route, automatically refresh data\n // UNLESS skipAutoRevalidate is true (to prevent recursive calls from revalidate())\n if (!skipAutoRevalidate && typeof window !== \"undefined\") {\n const currentPathname = window.location.pathname;\n const currentSearch = window.location.search;\n const matchesCurrentPath = normalizedPath === currentPathname;\n \n if (matchesCurrentPath) {\n if (hasQueryParams && specificQueryParams) {\n const currentQueryParams = currentSearch\n .replace(\"?\", \"\")\n .split(\"&\")\n .filter((p) => !p.startsWith(\"__fw_data=\"))\n .sort()\n .join(\"&\");\n \n if (currentQueryParams === specificQueryParams) {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n } else {\n revalidate().catch((err) => {\n console.error(\n \"[client][cache] Error revalidating current route:\",\n err\n );\n });\n }\n }\n }\n}\n\n/**\n * Revalidates and refreshes the current page data.\n * Similar to Next.js's `router.refresh()`.\n * \n * This function:\n * 1. Removes the current route from cache\n * 2. Fetches fresh data from the server\n * 3. Updates window.__FW_DATA__ with the new data\n * 4. Dispatches a 'fw-data-refresh' event for components to listen to\n * \n * @returns Promise that resolves with the fresh route data\n * \n * @example\n * ```ts\n * // Refresh current page data after a mutation\n * await revalidate();\n * ```\n */\n// Flag to prevent recursive calls to revalidate()\nlet isRevalidating = false;\n\nexport async function revalidate(): Promise<RouteData> {\n if (typeof window === \"undefined\") {\n throw new Error(\"revalidate() can only be called on the client\");\n }\n\n // Prevent multiple simultaneous revalidations\n if (isRevalidating) {\n // Wait for the current revalidation to complete\n const key = buildDataUrl(window.location.pathname + window.location.search);\n const entry = dataCache.get(key);\n if (entry && entry.status === \"pending\") {\n return entry.promise;\n }\n // If no pending entry, something went wrong, allow the call\n }\n\n isRevalidating = true;\n try {\n const pathname = window.location.pathname + window.location.search;\n \n // Revalidate the path (remove from cache)\n // Pass a flag to prevent revalidatePath from calling revalidate() again (recursive call)\n revalidatePath(pathname, true); // true = skip auto-revalidate\n \n // Fetch fresh data\n const freshData = await getRouteData(pathname, { revalidate: true });\n \n // Update window.__FW_DATA__ if it exists\n if ((window as any).__FW_DATA__ && freshData.ok && freshData.json) {\n const currentData = (window as any).__FW_DATA__;\n \n // Update preserved layout props if new ones were returned\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n (window as any).__FW_LAYOUT_PROPS__ = freshData.json.layoutProps;\n }\n \n // Combine layout props (new or preserved) + page props\n let combinedProps = currentData.props || {};\n if (freshData.json.layoutProps !== undefined && freshData.json.layoutProps !== null) {\n // Use new layout props\n combinedProps = {\n ...freshData.json.layoutProps,\n ...(freshData.json.pageProps ?? freshData.json.props ?? {}),\n };\n } else if (freshData.json.pageProps !== undefined) {\n // Use preserved layout props + new page props\n const preservedLayoutProps = (window as any).__FW_LAYOUT_PROPS__ || {};\n combinedProps = {\n ...preservedLayoutProps,\n ...freshData.json.pageProps,\n };\n } else if (freshData.json.props) {\n // Fallback to combined props\n combinedProps = freshData.json.props;\n }\n \n (window as any).__FW_DATA__ = {\n ...currentData,\n pathname: pathname.split(\"?\")[0],\n params: freshData.json.params || currentData.params || {},\n props: combinedProps,\n metadata: freshData.json.metadata ?? currentData.metadata ?? null,\n notFound: freshData.json.notFound ?? false,\n error: freshData.json.error ?? false,\n };\n \n // Dispatch event for components to listen to\n window.dispatchEvent(new CustomEvent(\"fw-data-refresh\", {\n detail: { data: freshData },\n }));\n }\n \n return freshData;\n } finally {\n isRevalidating = false;\n }\n}\n\n/**\n * @deprecated Use `revalidatePath()` instead. This function is kept for backwards compatibility.\n */\nexport function revalidateRouteData(url: string): void {\n revalidatePath(url);\n}\n\nexport function prefetchRouteData(url: string): void {\n const key = buildDataUrl(url);\n\n const cached = dataCache.get(key);\n\n if (cached && cached.status !== \"rejected\") {\n // Update LRU if it exists and is fulfilled\n if (cached.status === \"fulfilled\") {\n updateLRU(key);\n }\n return;\n }\n\n // Prefetch uses skipLayoutHooks: true (normal navigation behavior)\n const promise = fetchRouteDataOnce(url, true)\n .then((value) => {\n setCacheEntry(key, { status: \"fulfilled\", value });\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error prefetching route data:\", error);\n dataCache.set(key, { status: \"rejected\", error });\n throw error;\n });\n\n dataCache.set(key, { status: \"pending\", promise });\n}\n\nexport type GetRouteDataOptions = {\n /**\n * If true, forces revalidation of route data,\n * ignoring the cache and fetching fresh data from the server.\n * Similar to Next.js's `router.refresh()` behavior.\n */\n revalidate?: boolean;\n};\n\nexport async function getRouteData(\n url: string,\n options?: GetRouteDataOptions\n): Promise<RouteData> {\n const key = buildDataUrl(url);\n\n // If revalidation is requested, remove the entry from cache\n // This ensures we don't reuse pending or fulfilled entries\n if (options?.revalidate) {\n deleteCacheEntry(key);\n }\n\n const entry = dataCache.get(key);\n\n if (entry && !options?.revalidate) {\n // Only use cached entry if not revalidating\n if (entry.status === \"fulfilled\") {\n // Update LRU: mark as recently used\n updateLRU(key);\n return entry.value;\n }\n if (entry.status === \"pending\") {\n // Return existing pending promise to avoid duplicate requests\n return entry.promise;\n }\n }\n\n // No entry in cache (or revalidating), fetch it\n // skipLayoutHooks: true for normal SPA navigation, false when revalidating\n const skipLayoutHooks = !options?.revalidate;\n \n // Check again if an entry was added while we were processing (race condition)\n const currentEntry = dataCache.get(key);\n if (currentEntry && !options?.revalidate) {\n if (currentEntry.status === \"fulfilled\") {\n updateLRU(key);\n return currentEntry.value;\n }\n if (currentEntry.status === \"pending\") {\n return currentEntry.promise;\n }\n }\n \n // Create a new promise for this fetch\n const promise = fetchRouteDataOnce(url, skipLayoutHooks)\n .then((value) => {\n // Only set cache entry if this is still the current fetch for this key\n // This prevents race conditions where multiple revalidations happen simultaneously\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n setCacheEntry(key, { status: \"fulfilled\", value });\n }\n return value;\n })\n .catch((error) => {\n console.error(\"[client][cache] Error fetching route data:\", error);\n const entryAfterFetch = dataCache.get(key);\n if (!entryAfterFetch || entryAfterFetch.status === \"pending\") {\n dataCache.set(key, { status: \"rejected\", error });\n }\n throw error;\n });\n\n // Set pending entry - if revalidating, we already deleted it, so this is safe\n dataCache.set(key, { status: \"pending\", promise });\n \n return promise;\n}\n","import React from \"react\";\r\nimport { prefetchRouteData } from \"../../cache/index\";\r\n\r\ninterface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {\r\n href: string;\r\n children: React.ReactNode;\r\n prefetch?: boolean;\r\n}\r\n\r\nimport { useEffect, useRef } from \"react\"; \r\n\r\nfunction isExternal(href: string) {\r\n try {\r\n const url = new URL(href, window.location.href);\r\n return url.origin !== window.location.origin;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nexport function Link({\r\n href,\r\n prefetch = true,\r\n children,\r\n ...rest\r\n}: React.PropsWithChildren<{\r\n href: string;\r\n prefetch?: boolean;\r\n}> &\r\n React.AnchorHTMLAttributes<HTMLAnchorElement>) {\r\n const ref = useRef<HTMLAnchorElement | null>(null);\r\n\r\n useEffect(() => {\r\n if (!prefetch || !ref.current || isExternal(href)) return;\r\n\r\n const el = ref.current;\r\n let prefetched = false;\r\n\r\n const io = new IntersectionObserver(([entry]) => {\r\n if (entry.isIntersecting && !prefetched) {\r\n prefetched = true;\r\n prefetchRouteData(href);\r\n }\r\n });\r\n\r\n io.observe(el);\r\n return () => io.disconnect();\r\n }, [href, prefetch]);\r\n\r\n return (\r\n <a ref={ref} href={href} {...rest}>\r\n {children}\r\n </a>\r\n );\r\n}\r\n"],"mappings":";AAsCI;AApCJ,IAAM,WAAW;AAmBV,SAAS,MAAM;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAe;AACb,QAAM,QAA6B,CAAC;AAEpC,MAAI,MAAO,OAAM,QAAQ;AACzB,MAAI,OAAQ,OAAM,SAAS;AAE3B,QAAM,aAAa,CAAC,IAAI,WAAW,MAAM;AACzC,QAAM,aAAa,aAAa,GAAG,QAAQ,IAAI,GAAG,KAAK;AAEvD,SACE;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACC,GAAG;AAAA;AAAA,EACN;AAEJ;;;ACZA,IAAM,YAAY;AAGlB,IAAM,iBAAiB;AAQvB,SAAS,gBAA4B;AACnC,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI,CAAE,OAAe,SAAS,GAAG;AAC/B,MAAC,OAAe,SAAS,IAAI;AAAA,QAC3B,MAAM,oBAAI,IAAwB;AAAA,QAClC,OAAO,oBAAI,IAAyB;AAAA,QACpC,KAAK,CAAC;AAAA,MACR;AAAA,IACF;AACA,WAAQ,OAAe,SAAS;AAAA,EAClC;AAEA,SAAO;AAAA,IACL,MAAM,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,EACR,CAAC;AAEH,YAAU,IAAI,KAAK,EAAE,QAAQ,WAAW,QAAQ,CAAC;AACnD;;;ACtbA,SAAS,WAAW,cAAc;AAyC9B,gBAAAA,YAAA;AAvCJ,SAAS,WAAW,MAAc;AAChC,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,MAAM,OAAO,SAAS,IAAI;AAC9C,WAAO,IAAI,WAAW,OAAO,SAAS;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,KAAK;AAAA,EACnB;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA,GAAG;AACL,GAIiD;AAC/C,QAAM,MAAM,OAAiC,IAAI;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC,YAAY,CAAC,IAAI,WAAW,WAAW,IAAI,EAAG;AAEnD,UAAM,KAAK,IAAI;AACf,QAAI,aAAa;AAEjB,UAAM,KAAK,IAAI,qBAAqB,CAAC,CAAC,KAAK,MAAM;AAC/C,UAAI,MAAM,kBAAkB,CAAC,YAAY;AACvC,qBAAa;AACb,0BAAkB,IAAI;AAAA,MACxB;AAAA,IACF,CAAC;AAED,OAAG,QAAQ,EAAE;AACb,WAAO,MAAM,GAAG,WAAW;AAAA,EAC7B,GAAG,CAAC,MAAM,QAAQ,CAAC;AAEnB,SACE,gBAAAA,KAAC,OAAE,KAAU,MAAa,GAAG,MAC1B,UACH;AAEJ;","names":["jsx"]}
package/dist/runtime.cjs CHANGED
@@ -642,13 +642,22 @@ async function handleNormalRoute(nextUrl, json, routes, setState) {
642
642
  theme
643
643
  // Always include theme
644
644
  };
645
- const matched = matchRouteClient(nextUrl, routes);
645
+ const pathnameForMatch = json.pathname || nextUrl;
646
+ let matched = matchRouteClient(pathnameForMatch, routes);
646
647
  if (!matched) {
648
+ matched = matchRouteClient(nextUrl, routes);
649
+ }
650
+ if (!matched) {
651
+ console.warn(
652
+ `[client] Server returned data for ${nextUrl} but no route match found. Available routes:`,
653
+ routes.map((r) => r.pattern)
654
+ );
647
655
  window.location.href = nextUrl;
648
656
  return false;
649
657
  }
658
+ const finalPathname = json.pathname || nextUrl;
650
659
  const windowData = {
651
- pathname: nextUrl,
660
+ pathname: finalPathname,
652
661
  params: matched.params,
653
662
  props: combinedProps,
654
663
  metadata: json.metadata ?? null,
@@ -1047,8 +1056,9 @@ function initializeRouterData(initialUrl, initialData) {
1047
1056
  let routerData = getRouterData();
1048
1057
  if (!routerData) {
1049
1058
  const url = new URL(initialUrl, window.location.origin);
1059
+ const pathname = initialData?.pathname || url.pathname;
1050
1060
  routerData = {
1051
- pathname: url.pathname,
1061
+ pathname,
1052
1062
  params: initialData?.params || {},
1053
1063
  searchParams: Object.fromEntries(url.searchParams.entries())
1054
1064
  };
@@ -1107,11 +1117,12 @@ function bootstrapClient(routes, notFoundRoute, errorRoute = null) {
1107
1117
  return;
1108
1118
  }
1109
1119
  const initialData = getWindowData();
1110
- const initialUrl = window.location.pathname + window.location.search;
1120
+ const initialUrl = (initialData?.pathname || window.location.pathname) + window.location.search;
1111
1121
  if (initialData?.props) {
1112
1122
  setPreservedLayoutProps(initialData.props);
1113
1123
  }
1114
- initializeRouterData(initialUrl, initialData);
1124
+ const routerPathname = initialData?.pathname || window.location.pathname;
1125
+ initializeRouterData(routerPathname + window.location.search, initialData);
1115
1126
  await hydrateInitialRoute(
1116
1127
  container,
1117
1128
  initialUrl,