rari 0.11.0 → 0.12.1

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.
Files changed (27) hide show
  1. package/dist/ReactFlightClientConfig-BZt6Cjql.d.mts +35 -0
  2. package/dist/client.d.mts +1 -1
  3. package/dist/client.mjs +2 -3
  4. package/dist/get-client-component-BjjGTgmG.mjs +1 -0
  5. package/dist/preload-modules-DcD-Wjko.mjs +2 -0
  6. package/dist/router.mjs +1 -1
  7. package/dist/runtime/AppRouterProvider.d.mts +2 -0
  8. package/dist/runtime/AppRouterProvider.mjs +6 -7
  9. package/dist/runtime/entry-client.mjs +4 -4
  10. package/dist/runtime/rsc-client-runtime.mjs +2 -2
  11. package/dist/runtime/vendor/react-flight-client/ReactFlightClient.d.mts +71 -0
  12. package/dist/runtime/vendor/react-flight-client/ReactFlightClient.mjs +2 -0
  13. package/dist/runtime/vendor/react-flight-client/ReactFlightClientConfig.d.mts +2 -0
  14. package/dist/runtime/vendor/react-flight-client/ReactFlightClientConfig.mjs +1 -0
  15. package/dist/runtime/vendor/react-flight-client/index.d.mts +12 -0
  16. package/dist/runtime/vendor/react-flight-client/index.mjs +1 -0
  17. package/dist/{runtime-client-yoJmu7vX.mjs → runtime-client-D57-4ZUQ.mjs} +2 -2
  18. package/dist/server-build-BbPvWrFq.mjs +175 -0
  19. package/dist/{server-config-Cf6g4PHZ.d.mts → server-config-DXVkrIkP.d.mts} +8 -2
  20. package/dist/vite.d.mts +1 -1
  21. package/dist/vite.mjs +13 -10
  22. package/package.json +14 -14
  23. package/dist/get-client-component-YrjzU6RI.mjs +0 -1
  24. package/dist/preload-components-Bp8OQWGz.mjs +0 -1
  25. package/dist/runtime/react-server-dom-rari-client.d.mts +0 -8
  26. package/dist/runtime/react-server-dom-rari-client.mjs +0 -3
  27. package/dist/server-build-CQUf5NnM.mjs +0 -175
@@ -0,0 +1,35 @@
1
+ //#region src/runtime/vendor/react-flight-client/ReactFlightClientConfig.d.ts
2
+ /**
3
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ *
8
+ * Vendored from: https://github.com/facebook/react
9
+ * Original file: packages/react-client/src/ReactFlightClientConfig.js (shim)
10
+ * Reference impl: packages/react-server-dom-webpack/src/client/ReactFlightClientConfigBundlerWebpack.js
11
+ * Modifications: Adapted for rari's client component registry
12
+ */
13
+ interface ClientReferenceMetadata {
14
+ id: string;
15
+ chunks: Array<string>;
16
+ name: string;
17
+ }
18
+ interface ClientReference<T> {
19
+ specifier: string;
20
+ name: string;
21
+ }
22
+ type ServerConsumerModuleMap = Record<string, any>;
23
+ interface StringDecoder {
24
+ decode: (chunk: Uint8Array, options?: {
25
+ stream?: boolean;
26
+ }) => string;
27
+ }
28
+ declare function resolveClientReference<T>(metadata: ClientReferenceMetadata): ClientReference<T>;
29
+ declare function preloadModule<T>(moduleReference: ClientReference<T>): null | Promise<any>;
30
+ declare function requireModule<T>(moduleReference: ClientReference<T>): T;
31
+ declare function readPartialStringChunk(decoder: StringDecoder, buffer: Uint8Array): string;
32
+ declare function readFinalStringChunk(decoder: StringDecoder, buffer: Uint8Array): string;
33
+ declare function createStringDecoder(): StringDecoder;
34
+ //#endregion
35
+ export { createStringDecoder as a, readPartialStringChunk as c, StringDecoder as i, requireModule as l, ClientReferenceMetadata as n, preloadModule as o, ServerConsumerModuleMap as r, readFinalStringChunk as s, ClientReference as t, resolveClientReference as u };
package/dist/client.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as extractServerPropsWithCache, S as extractServerProps, T as hasServerSideDataFetching, _ as ServerSidePropsResult, a as ServerSpamBlockerConfig, b as clearPropsCacheForComponent, c as ErrorBoundary, d as NotFound, f as RuntimeClient, g as MetadataResult, h as createLoadingBoundary, i as ServerRateLimitConfig, l as HttpRuntimeClient, m as createHttpRuntimeClient, o as DefaultError, p as createErrorBoundary, r as ServerConfig, s as DefaultLoading, t as ServerCSPConfig, u as LoadingSpinner, v as StaticParamsResult, w as extractStaticParams, x as extractMetadata, y as clearPropsCache } from "./server-config-Cf6g4PHZ.mjs";
1
+ import { C as extractServerPropsWithCache, S as extractServerProps, T as hasServerSideDataFetching, _ as ServerSidePropsResult, a as ServerSpamBlockerConfig, b as clearPropsCacheForComponent, c as ErrorBoundary, d as NotFound, f as RuntimeClient, g as MetadataResult, h as createLoadingBoundary, i as ServerRateLimitConfig, l as HttpRuntimeClient, m as createHttpRuntimeClient, o as DefaultError, p as createErrorBoundary, r as ServerConfig, s as DefaultLoading, t as ServerCSPConfig, u as LoadingSpinner, v as StaticParamsResult, w as extractStaticParams, x as extractMetadata, y as clearPropsCache } from "./server-config-DXVkrIkP.mjs";
2
2
  import { a as ErrorProps, c as LayoutEntry, f as NotFoundEntry, h as RouteSegmentType, i as ErrorEntry, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-Cfe0C3JU.mjs";
3
3
  import * as React from "react";
4
4
  import { Component, ErrorInfo, ReactNode } from "react";
package/dist/client.mjs CHANGED
@@ -1,3 +1,2 @@
1
- import{i as e,t}from"./navigate-hfIqe3MK.mjs";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _}from"./runtime-client-yoJmu7vX.mjs";import{Component as v,useEffect as y,useLayoutEffect as b,useRef as x,useState as ee}from"react";import{Fragment as S,jsx as C,jsxs as w}from"react/jsx-runtime";function te(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;return o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e))return h(e);let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0:h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}const T=/fetch|networkerror|load failed/i;function E(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function D(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function O(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function k(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function A(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function j(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function M(e,t){if(e instanceof Error&&e.name===`AbortError`)return E(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return D(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?O(e,n,t):j(e,t)}return e instanceof TypeError&&T.test(e.message)?k(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?A(e,t):j(e,t)}var N=class{options;retryCount;constructor(e={}){this.options={timeout:e.timeout??1e4,maxRetries:e.maxRetries??3,onError:e.onError??(()=>{}),onRetry:e.onRetry??(()=>{})},this.retryCount=new Map}handleError(e,t){let n=M(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};const P=/(^\/+)|(\/+$)/g;function F(e){let t=e.replace(P,``);return t?t.split(`/`):[]}function I(e){try{return decodeURIComponent(e)}catch{return null}}function L(e,t){let n=I(e),r=I(t);return n===null||r===null?!1:n===r}function R(e,t,n){if(!t)return!1;let r=I(e);return r===null?!1:(n[t]=r,!0)}function z(e,t,n,r){if(!n)return{success:!1,newIndex:t};let i=[];for(let n of e.slice(t)){let e=I(n);if(e===null)return{success:!1,newIndex:t};i.push(e)}return r[n]=i,{success:!0,newIndex:e.length}}function B(e,t,n,r){e>=t&&n&&(r[n]=[])}function V(e,t,n,r){if(n>=t.length)return e.type===`optional-catch-all`&&e.param?(B(n,t.length,e.param,r),{success:!0,newIndex:n}):{success:!1,newIndex:n};switch(e.type){case`static`:return L(t[n],e.value)?{success:!0,newIndex:n+1}:{success:!1,newIndex:n};case`dynamic`:return R(t[n],e.param,r)?{success:!0,newIndex:n+1}:{success:!1,newIndex:n};case`catch-all`:case`optional-catch-all`:return z(t,n,e.param,r);default:return{success:!1,newIndex:n}}}function ne(e,t,n){let r=F(n),i={},a=0;for(let e of t){let t=V(e,r,a,i);if(!t.success)return null;a=t.newIndex}return a===r.length?i:null}function H(e){if(!e||e===`/`)return`/`;let t=e;for(;t.endsWith(`/`)&&t.length>1;)t=t.slice(0,-1);return t.startsWith(`/`)||(t=`/${t}`),t}function U(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function W(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}function G({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return C(`div`,{style:{position:`fixed`,top:0,left:0,right:0,bottom:0,background:`rgba(0, 0, 0, 0.5)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:1e4,padding:`20px`},onClick:e=>{e.target===e.currentTarget&&r&&r()},children:w(`div`,{style:{background:`white`,borderRadius:`8px`,padding:`24px`,maxWidth:`500px`,width:`100%`,boxShadow:`0 4px 12px rgba(0, 0, 0, 0.15)`},onClick:e=>e.stopPropagation(),children:[w(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[C(`span`,{style:{fontSize:`32px`},children:(()=>{switch(e.type){case`timeout`:return`⏱️`;case`network-error`:return`📡`;case`not-found`:return`🔍`;case`server-error`:return`⚠️`;case`parse-error`:return`📄`;case`abort`:return`🚫`;default:return`❌`}})()}),C(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),C(`p`,{style:{margin:`0 0 16px 0`,fontSize:`15px`,lineHeight:`1.5`,color:`#4b5563`},children:(()=>{switch(e.type){case`timeout`:return`The page took too long to load. Please try again.`;case`network-error`:return`Unable to connect to the server. Please check your internet connection.`;case`not-found`:return`The page you're looking for doesn't exist.`;case`server-error`:return`The server encountered an error. Please try again in a moment.`;case`parse-error`:return`Unable to load the page content. Please try reloading.`;case`abort`:return`Navigation was cancelled.`;default:return e.message||`An unexpected error occurred.`}})()}),e.url&&w(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[C(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),w(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`Status:`}),` `,e.statusCode]}),w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&w(`div`,{children:[C(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&w(`div`,{style:{marginBottom:`16px`,padding:`8px 12px`,background:`#fef3c7`,border:`1px solid #fbbf24`,borderRadius:`4px`,fontSize:`13px`,color:`#92400e`},children:[`Retry attempt`,` `,i,` `,`of`,` `,a]}),w(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&C(`button`,{onClick:t,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#3b82f6`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#2563eb`},onMouseLeave:e=>{e.currentTarget.style.background=`#3b82f6`},children:`Try Again`}),n&&C(`button`,{onClick:n,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#6b7280`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.background=`#6b7280`},children:`Reload Page`}),r&&C(`button`,{onClick:r,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`transparent`,color:`#6b7280`,border:`1px solid #d1d5db`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`all 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#f9fafb`,e.currentTarget.style.borderColor=`#9ca3af`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`#d1d5db`},children:`Dismiss`})]}),C(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const K=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}async fetchRouteInfo(e){let t={path:e},n=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=null;try{e=await n.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${n.status} ${n.statusText}`)}let r=n.clone();try{return await n.json()}catch(t){try{let e=await r.text();return JSON.parse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=K}var q=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize||50,this.scrollableSelector=e.scrollableSelector||`[data-scrollable], .scrollable, [style*="overflow"]`}captureState(e){let t={scrollPositions:this.captureScrollPositions(),formData:this.captureFormData(),focusedElement:this.captureFocusedElement()};return this.storeState(e,t),t}captureScrollPositions(){let e=new Map;try{e.set(`window`,{x:window.scrollX,y:window.scrollY,element:`window`}),document.querySelectorAll(this.scrollableSelector).forEach((t,n)=>{if(t instanceof HTMLElement){let r=t.id||`scrollable-${n}`;(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)&&e.set(r,{x:t.scrollLeft,y:t.scrollTop,element:r})}})}catch{}return e}captureFormData(){let e=new Map;try{document.querySelectorAll(`form`).forEach((t,n)=>{let r=t.id||t.name||`form-${n}`,i=new FormData(t);i.entries().next().done||e.set(r,i)})}catch{}return e}captureFocusedElement(){try{let e=document.activeElement;if(e&&e!==document.body){if(e.id)return`#${e.id}`;if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.name)return`[name="${e.name}"]`}}catch{}return null}storeState(e,t){let n=this.routeAccessOrder.indexOf(e);for(n!==-1&&this.routeAccessOrder.splice(n,1),this.routeAccessOrder.push(e),this.stateHistory.set(e,t);this.routeAccessOrder.length>this.maxHistorySize;){let e=this.routeAccessOrder.shift();e&&this.stateHistory.delete(e)}}getHistorySize(){return this.stateHistory.size}hasState(e){return this.stateHistory.has(e)}getState(e){return this.stateHistory.get(e)}clearAll(){this.stateHistory.clear(),this.routeAccessOrder=[]}clearState(e){this.stateHistory.delete(e);let t=this.routeAccessOrder.indexOf(e);t!==-1&&this.routeAccessOrder.splice(t,1)}restoreState(e){let t=this.stateHistory.get(e);if(!t)return!1;let n=!0;return this.restoreScrollPositions(t.scrollPositions)||(n=!1),this.restoreFormData(t.formData)||(n=!1),t.focusedElement&&this.restoreFocus(t.focusedElement),n}restoreScrollPositions(e){let t=!0;try{e.forEach((e,n)=>{try{if(n===`window`)window.scrollTo(e.x,e.y);else{let r=document.getElementById(n)||document.querySelector(`[data-scrollable-id="${n}"]`);r instanceof HTMLElement?(r.scrollLeft=e.x,r.scrollTop=e.y):t=!1}}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore scroll positions:`,e),t=!1}return t}restoreFormData(e){let t=!0;try{e.forEach((e,n)=>{try{let r=document.getElementById(n)||document.querySelector(`form[name="${n}"]`)||document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];r instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=r.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e:t.value=e)}):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t instanceof HTMLInputElement&&(t.type===`checkbox`||t.type===`radio`)?t.checked=t.value===e:t.value=e)}catch{t=!1}}):t=!1}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore form data:`,e),t=!1}return t}restoreFocus(e){try{let t=document.querySelector(e);t instanceof HTMLElement&&requestAnimationFrame(()=>{try{t.focus()}catch{}})}catch{}}};function J(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function Y(e){let t=document.querySelector(e);t&&t.remove()}function X(e){e.title&&(document.title=e.title),e.description?J(`meta[name="description"]`,{name:`description`,content:e.description}):Y(`meta[name="description"]`),e.keywords&&e.keywords.length>0?J(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):Y(`meta[name="keywords"]`),e.viewport&&J(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function Z(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function Q(e){if(e===void 0){Y(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?J(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):Y(`meta[name="robots"]`)}function $(e){if(e===void 0){Y(`meta[property="og:title"]`),Y(`meta[property="og:description"]`),Y(`meta[property="og:url"]`),Y(`meta[property="og:site_name"]`),Y(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?J(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):Y(`meta[property="og:title"]`),e.description?J(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):Y(`meta[property="og:description"]`),e.url?J(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):Y(`meta[property="og:url"]`),e.siteName?J(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):Y(`meta[property="og:site_name"]`),e.type?J(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):Y(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove())}function re(e){if(e===void 0){Y(`meta[name="twitter:card"]`),Y(`meta[name="twitter:site"]`),Y(`meta[name="twitter:creator"]`),Y(`meta[name="twitter:title"]`),Y(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?J(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):Y(`meta[name="twitter:card"]`),e.site?J(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):Y(`meta[name="twitter:site"]`),e.creator?J(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):Y(`meta[name="twitter:creator"]`),e.title?J(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):Y(`meta[name="twitter:title"]`),e.description?J(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):Y(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove())}function ie(e){X(e),Z(e.canonical),Q(e.robots),$(e.openGraph),re(e.twitter)}function ae({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=ee(()=>({currentRoute:H(r),navigationId:0,error:null})),s=x(null),c=x(!0),l=x(H(r)),u=x(0),d=x(new N({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),f=x(new Map),p=x([]),m=x(new q({maxHistorySize:50})),h=x(null),g=x(i),_=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,v=()=>{s.current&&=(s.current.abort(),null)},T=()=>{for(let[,e]of f.current.entries())e.abortController.abort();f.current.clear()},E=(e,t)=>{f.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},D=async e=>K.get(e),O=x(null),k=(e,t)=>{if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))},A=e=>{try{let t=e.headers.get(`x-rari-metadata`);t&&ie(JSON.parse(decodeURIComponent(t)))}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},j=async(e,t,n,r,i,a,o,s,c)=>{if(!e.body)return;let l=e.body.getReader(),u=new TextDecoder,d=``;try{for(;;){let{done:e,value:r}=await l.read();if(e)break;if(t.signal.aborted){await l.cancel(),E(n,i);return}d+=u.decode(r,{stream:!0});let a=d.split(`
2
- `);d=a.pop()||``;for(let e of a)e.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:e,navigationId:i}}))}d+=u.decode(),d.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:d,navigationId:i}})),window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:a,to:r,navigationId:i,options:o,routeInfo:{...s,extractedParams:c},abortSignal:t.signal,isStreaming:!0}}))}catch(e){throw console.error(`[rari] Router: Streaming error:`,e),e}},M=async(e,t,n,r,i,a,o,s)=>{let c=await e.text();window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,routeInfo:{...a,extractedParams:o},abortSignal:s.signal,rscWireFormat:c}}))},P=(e,t,n)=>{n.historyKey?requestAnimationFrame(()=>{m.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=(n=0)=>{let r=document.getElementById(t);r?r.scrollIntoView({behavior:`smooth`,block:`start`}):n<10&&setTimeout(e,50,n+1)};e()})},F=(e,t,n,r)=>{c.current&&(l.current=e,o(t=>({...t,currentRoute:e,navigationId:r,error:null})),d.current.resetRetry(e),P(e,t,n))},I=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){E(t,n);return}let i=d.current.handleError(e,t);c.current&&o(e=>({...e,error:i})),f.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),O.current?.()},L=async(e,t={})=>{if(!e||typeof e!=`string`){console.error(`[rari] Router: Invalid navigation target:`,e);return}let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=H(n);if(i===l.current&&!t.replace){k(i,r);return}let a=f.current.get(i);if(a)return a.promise;let o=await D(i);T(),v();let c=new AbortController;s.current=c,u.current+=1;let d=u.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:d,targetPath:i}}));let p=(async()=>{let e=l.current;try{t.historyKey||m.current.captureState(e);let n=t.historyKey||_(),a=window.location.origin+i,s=await fetch(a,{headers:{Accept:`text/x-component`},signal:c.signal});if(!s.ok&&s.status!==404)throw Error(`Failed to fetch: ${s.status}`);let l=new URL(s.url).pathname;if(c.signal.aborted){E(i,d);return}let u=r?`${l}#${r}`:l,p={route:l,navigationId:d,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(p,``,u):window.history.pushState(p,``,u),A(s);let h=s.headers.get(`x-render-mode`)===`streaming`,g=o?.segments&&ne(``,o.segments,l)||{};if(h&&s.body?await j(s,c,i,l,d,e,t,o,g):await M(s,e,l,d,t,o,g,c),c.signal.aborted){E(i,d);return}F(l,r,t,d),f.current.delete(i),O.current?.()}catch(t){I(t,i,d,e)}})();return f.current.set(i,{targetPath:i,navigationId:d,promise:p,abortController:c}),p},R=async()=>{if(p.current.length===0)return;let e=p.current.at(-1);e&&(p.current=[],await L(e.path,e.options))},z=x(L);b(()=>(O.current=R,z.current=L,()=>{O.current=null,z.current=null}));let B=x(null);B.current||=te((e,t)=>{z.current?.(e,t)},50,{leading:!1,trailing:!0,maxWait:200});let V=e=>{if(e.button!==0||e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)return;let t=e.target;for(;t&&t.tagName!==`A`;)t=t.parentElement;if(!t||t.tagName!==`A`)return;let n=t;if(n.target&&n.target!==`_self`||n.hasAttribute(`download`))return;let r=n.getAttribute(`href`);if(!r||U(r))return;if(r.startsWith(`#`)){e.preventDefault();let t=r.slice(1),n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,r));return}e.preventDefault();let i=W(r);B.current&&B.current(i,{replace:!1})},J=e=>{let t=window.location.pathname,n=e.state;z.current&&z.current(t,{replace:!0,scroll:!1,historyKey:n?.key})},Y=()=>{if(a.error&&a.error.url){let e=a.error.url;d.current.incrementRetry(e),L(e,{replace:!1})}},X=()=>{window.location.reload()},Z=()=>{o(e=>({...e,error:null}))};y(()=>{let e=window.history.state;if(!e||!e.key){let e={route:H(r),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:_()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[r]);let Q=e=>{if(e.persisted){let e=window.location.pathname;m.current.captureState(e)}},$=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{m.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return y(()=>(document.addEventListener(`click`,V),window.addEventListener(`popstate`,J),window.addEventListener(`pagehide`,Q),window.addEventListener(`pageshow`,$),()=>{document.removeEventListener(`click`,V),window.removeEventListener(`popstate`,J),window.removeEventListener(`pagehide`,Q),window.removeEventListener(`pageshow`,$)}),[]),y(()=>{g.current=i;let e=()=>{document.hidden?h.current=Date.now():h.current!==null&&Date.now()-h.current>g.current&&K.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[i]),y(()=>(c.current=!0,e((e,t)=>z.current?.(e,t)??Promise.resolve()),()=>{c.current=!1,t(),v(),T(),B.current?.cancel&&B.current.cancel()}),[]),w(S,{children:[n,a.error&&C(G,{error:a.error,onRetry:Y,onReload:X,onDismiss:Z,retryCount:d.current.getRetryCount(a.error.url||``),maxRetries:3})]})}var oe=class extends v{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`[rari] Layout: Error in layout "${this.props.layoutPath}":`,e,t),this.props.onError&&this.props.onError(e,t),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:layout-error`,{detail:{layoutPath:this.props.layoutPath,error:e,errorInfo:t,timestamp:Date.now()}}))}reset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError&&this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):w(`div`,{style:{padding:`16px`,margin:`16px 0`,background:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`},children:[C(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`},children:`Layout Error`}),w(`p`,{style:{margin:`0 0 8px 0`,fontSize:`14px`},children:[`An error occurred in layout:`,` `,C(`code`,{children:this.props.layoutPath})]}),w(`details`,{style:{fontSize:`12px`,marginBottom:`8px`},children:[C(`summary`,{style:{cursor:`pointer`},children:`Error details`}),w(`pre`,{style:{marginTop:`8px`,padding:`8px`,background:`#fff`,border:`1px solid #ddd`,borderRadius:`2px`,overflow:`auto`},children:[this.state.error.message,`
3
- `,this.state.error.stack]})]}),C(`button`,{onClick:this.reset,type:`button`,style:{padding:`6px 12px`,background:`#c00`,color:`white`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},children:`Try Again`})]}):this.props.children}};export{ae as ClientRouter,_ as DefaultError,f as DefaultLoading,h as ErrorBoundary,l as HttpRuntimeClient,oe as LayoutErrorBoundary,r as LoadingSpinner,N as NavigationErrorHandler,G as NavigationErrorOverlay,p as NotFound,q as StatePreserver,a as clearPropsCache,o as clearPropsCacheForComponent,g as createErrorBoundary,i as createHttpRuntimeClient,u as createLoadingBoundary,m as extractMetadata,d as extractServerProps,c as extractServerPropsWithCache,s as extractStaticParams,n as hasServerSideDataFetching};
1
+ import{i as e,t}from"./navigate-hfIqe3MK.mjs";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _}from"./runtime-client-D57-4ZUQ.mjs";import{Component as v,useEffect as y,useLayoutEffect as b,useRef as x,useState as S}from"react";import{Fragment as C,jsx as w,jsxs as T}from"react/jsx-runtime";function E(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;return o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e))return h(e);let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0:h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}const D=/fetch|networkerror|load failed/i;function O(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function k(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function A(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function j(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function M(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function N(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function P(e,t){if(e instanceof Error&&e.name===`AbortError`)return O(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return k(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?A(e,n,t):N(e,t)}return e instanceof TypeError&&D.test(e.message)?j(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?M(e,t):N(e,t)}var F=class{options;retryCount;constructor(e={}){this.options={timeout:e.timeout??1e4,maxRetries:e.maxRetries??3,onError:e.onError??(()=>{}),onRetry:e.onRetry??(()=>{})},this.retryCount=new Map}handleError(e,t){let n=P(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};function I(e){if(!e||e===`/`)return`/`;let t=e;for(;t.endsWith(`/`)&&t.length>1;)t=t.slice(0,-1);return t.startsWith(`/`)||(t=`/${t}`),t}function L(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function R(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}function z({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return w(`div`,{style:{position:`fixed`,top:0,left:0,right:0,bottom:0,background:`rgba(0, 0, 0, 0.5)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:1e4,padding:`20px`},onClick:e=>{e.target===e.currentTarget&&r&&r()},children:T(`div`,{style:{background:`white`,borderRadius:`8px`,padding:`24px`,maxWidth:`500px`,width:`100%`,boxShadow:`0 4px 12px rgba(0, 0, 0, 0.15)`},onClick:e=>e.stopPropagation(),children:[T(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[w(`span`,{style:{fontSize:`32px`},children:(()=>{switch(e.type){case`timeout`:return`⏱️`;case`network-error`:return`📡`;case`not-found`:return`🔍`;case`server-error`:return`⚠️`;case`parse-error`:return`📄`;case`abort`:return`🚫`;default:return`❌`}})()}),w(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),w(`p`,{style:{margin:`0 0 16px 0`,fontSize:`15px`,lineHeight:`1.5`,color:`#4b5563`},children:(()=>{switch(e.type){case`timeout`:return`The page took too long to load. Please try again.`;case`network-error`:return`Unable to connect to the server. Please check your internet connection.`;case`not-found`:return`The page you're looking for doesn't exist.`;case`server-error`:return`The server encountered an error. Please try again in a moment.`;case`parse-error`:return`Unable to load the page content. Please try reloading.`;case`abort`:return`Navigation was cancelled.`;default:return e.message||`An unexpected error occurred.`}})()}),e.url&&T(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[w(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),T(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`Status:`}),` `,e.statusCode]}),T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&T(`div`,{children:[w(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&T(`div`,{style:{marginBottom:`16px`,padding:`8px 12px`,background:`#fef3c7`,border:`1px solid #fbbf24`,borderRadius:`4px`,fontSize:`13px`,color:`#92400e`},children:[`Retry attempt`,` `,i,` `,`of`,` `,a]}),T(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&w(`button`,{onClick:t,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#3b82f6`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#2563eb`},onMouseLeave:e=>{e.currentTarget.style.background=`#3b82f6`},children:`Try Again`}),n&&w(`button`,{onClick:n,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#6b7280`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.background=`#6b7280`},children:`Reload Page`}),r&&w(`button`,{onClick:r,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`transparent`,color:`#6b7280`,border:`1px solid #d1d5db`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`all 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#f9fafb`,e.currentTarget.style.borderColor=`#9ca3af`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`#d1d5db`},children:`Dismiss`})]}),w(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const B=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}async fetchRouteInfo(e){let t=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})});if(!t.ok){let e=null;try{e=await t.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${t.status} ${t.statusText}`)}let n=t.clone();try{return await t.json()}catch(t){try{let e=await n.text();return JSON.parse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=B}var V=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize||50,this.scrollableSelector=e.scrollableSelector||`[data-scrollable], .scrollable, [style*="overflow"]`}captureState(e){let t={scrollPositions:this.captureScrollPositions(),formData:this.captureFormData(),focusedElement:this.captureFocusedElement()};return this.storeState(e,t),t}captureScrollPositions(){let e=new Map;try{e.set(`window`,{x:window.scrollX,y:window.scrollY,element:`window`}),document.querySelectorAll(this.scrollableSelector).forEach((t,n)=>{if(t instanceof HTMLElement){let r=t.id||`scrollable-${n}`;(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)&&e.set(r,{x:t.scrollLeft,y:t.scrollTop,element:r})}})}catch{}return e}captureFormData(){let e=new Map;try{document.querySelectorAll(`form`).forEach((t,n)=>{let r=t.id||t.name||`form-${n}`,i=new FormData(t);i.entries().next().done||e.set(r,i)})}catch{}return e}captureFocusedElement(){try{let e=document.activeElement;if(e&&e!==document.body){if(e.id)return`#${e.id}`;if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.name)return`[name="${e.name}"]`}}catch{}return null}storeState(e,t){let n=this.routeAccessOrder.indexOf(e);for(n!==-1&&this.routeAccessOrder.splice(n,1),this.routeAccessOrder.push(e),this.stateHistory.set(e,t);this.routeAccessOrder.length>this.maxHistorySize;){let e=this.routeAccessOrder.shift();e&&this.stateHistory.delete(e)}}getHistorySize(){return this.stateHistory.size}hasState(e){return this.stateHistory.has(e)}getState(e){return this.stateHistory.get(e)}clearAll(){this.stateHistory.clear(),this.routeAccessOrder=[]}clearState(e){this.stateHistory.delete(e);let t=this.routeAccessOrder.indexOf(e);t!==-1&&this.routeAccessOrder.splice(t,1)}restoreState(e){let t=this.stateHistory.get(e);if(!t)return!1;let n=!0;return this.restoreScrollPositions(t.scrollPositions)||(n=!1),this.restoreFormData(t.formData)||(n=!1),t.focusedElement&&this.restoreFocus(t.focusedElement),n}restoreScrollPositions(e){let t=!0;try{e.forEach((e,n)=>{try{if(n===`window`)window.scrollTo(e.x,e.y);else{let r=document.getElementById(n)||document.querySelector(`[data-scrollable-id="${n}"]`);r instanceof HTMLElement?(r.scrollLeft=e.x,r.scrollTop=e.y):t=!1}}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore scroll positions:`,e),t=!1}return t}restoreFormData(e){let t=!0;try{e.forEach((e,n)=>{try{let r=document.getElementById(n)||document.querySelector(`form[name="${n}"]`)||document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];r instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=r.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e:t.value=e)}):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t instanceof HTMLInputElement&&(t.type===`checkbox`||t.type===`radio`)?t.checked=t.value===e:t.value=e)}catch{t=!1}}):t=!1}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore form data:`,e),t=!1}return t}restoreFocus(e){try{let t=document.querySelector(e);t instanceof HTMLElement&&requestAnimationFrame(()=>{try{t.focus()}catch{}})}catch{}}};function H(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function U(e){let t=document.querySelector(e);t&&t.remove()}function W(e){e.title&&(document.title=e.title),e.description?H(`meta[name="description"]`,{name:`description`,content:e.description}):U(`meta[name="description"]`),e.keywords&&e.keywords.length>0?H(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):U(`meta[name="keywords"]`),e.viewport&&H(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function G(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function K(e){if(e===void 0){U(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?H(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):U(`meta[name="robots"]`)}function q(e){if(e===void 0){U(`meta[property="og:title"]`),U(`meta[property="og:description"]`),U(`meta[property="og:url"]`),U(`meta[property="og:site_name"]`),U(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?H(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):U(`meta[property="og:title"]`),e.description?H(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):U(`meta[property="og:description"]`),e.url?H(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):U(`meta[property="og:url"]`),e.siteName?H(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):U(`meta[property="og:site_name"]`),e.type?H(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):U(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove())}function J(e){if(e===void 0){U(`meta[name="twitter:card"]`),U(`meta[name="twitter:site"]`),U(`meta[name="twitter:creator"]`),U(`meta[name="twitter:title"]`),U(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?H(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):U(`meta[name="twitter:card"]`),e.site?H(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):U(`meta[name="twitter:site"]`),e.creator?H(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):U(`meta[name="twitter:creator"]`),e.title?H(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):U(`meta[name="twitter:title"]`),e.description?H(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):U(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove())}function Y(e){W(e),G(e.canonical),K(e.robots),q(e.openGraph),J(e.twitter)}function X({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=S(()=>({currentRoute:I(r),navigationId:0,error:null})),s=x(null),c=x(!0),l=x(I(r)),u=x(0),d=x(new F({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),f=x(new Map),p=x([]),m=x(new V({maxHistorySize:50})),h=x(null),g=x(i),_=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,v=()=>{s.current&&=(s.current.abort(),null)},D=()=>{for(let[,e]of f.current.entries())e.abortController.abort();f.current.clear()},O=(e,t)=>{f.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},k=x(null),A=(e,t)=>{if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))},j=e=>{try{let t=e.headers.get(`x-rari-metadata`);t&&Y(JSON.parse(decodeURIComponent(t)))}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},M=(e,t,n,r,i,a)=>{u.current===r&&window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,abortSignal:a.signal,rscResponsePromise:e}}))},N=(e,t,n)=>{n.historyKey?requestAnimationFrame(()=>{m.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=(n=0)=>{let r=document.getElementById(t);r?r.scrollIntoView({behavior:`smooth`,block:`start`}):n<10&&setTimeout(e,50,n+1)};e()})},P=(e,t,n,r)=>{c.current&&(l.current=e,o(t=>({...t,currentRoute:e,navigationId:r,error:null})),d.current.resetRetry(e),N(e,t,n))},H=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){O(t,n);return}let i=d.current.handleError(e,t);c.current&&(o(e=>({...e,error:i})),window.history.replaceState(window.history.state,``,r)),f.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),k.current?.()},U=async(e,t={})=>{if(!e||typeof e!=`string`)return;let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=I(n);if(i===l.current&&!t.replace){A(i,r);return}let a=f.current.get(i);if(a)return a.promise;D(),v();let o=new AbortController;s.current=o,u.current+=1;let c=u.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:c,targetPath:i}}));let d=(async()=>{let e=l.current;try{t.historyKey||m.current.captureState(e);let n=t.historyKey||_(),a=window.location.origin+i,s=r?`${i}#${r}`:i,l={route:i,navigationId:c,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(l,``,s):window.history.pushState(l,``,s);let u=await fetch(a,{headers:{Accept:`text/x-component`},signal:o.signal}).then(e=>{if(!e.ok&&e.status!==404)throw Error(`Failed to fetch: ${e.status}`);return e});if(o.signal.aborted){O(i,c);return}let d=new URL(u.url).pathname;if(o.signal.aborted){O(i,c);return}if(d!==i){let e=r?`${d}#${r}`:d;window.history.replaceState({...l,route:d},``,e)}if(M(Promise.resolve(u),e,d,c,t,o),j(u),o.signal.aborted){O(i,c);return}P(d,r,t,c),f.current.delete(i),k.current?.()}catch(t){H(t,i,c,e)}})();return f.current.set(i,{targetPath:i,navigationId:c,promise:d,abortController:o}),d},W=async()=>{if(p.current.length===0)return;let e=p.current.at(-1);e&&(p.current=[],await U(e.path,e.options))},G=x(U);b(()=>(k.current=W,G.current=U,()=>{k.current=null,G.current=null}));let K=x(null);K.current||=E((e,t)=>{G.current?.(e,t)},50,{leading:!0,trailing:!0,maxWait:200});let q=e=>{if(e.button!==0||e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)return;let t=e.target;for(;t&&t.tagName!==`A`;)t=t.parentElement;if(!t||t.tagName!==`A`)return;let n=t;if(n.target&&n.target!==`_self`||n.hasAttribute(`download`))return;let r=n.getAttribute(`href`);if(!r||L(r))return;if(r.startsWith(`#`)){e.preventDefault();let t=r.slice(1),n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,r));return}e.preventDefault();let i=R(r);K.current&&K.current(i,{replace:!1})},J=e=>{let t=window.location.pathname,n=e.state;G.current&&G.current(t,{replace:!0,scroll:!1,historyKey:n?.key})},X=()=>{if(a.error&&a.error.url){let e=a.error.url;d.current.incrementRetry(e),U(e,{replace:!1})}},Z=()=>{window.location.reload()},ee=()=>{o(e=>({...e,error:null}))};y(()=>{let e=window.history.state;if(!e||!e.key){let e={route:I(r),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:_()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[r]);let Q=e=>{if(e.persisted){let e=window.location.pathname;m.current.captureState(e)}},$=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{m.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return y(()=>(document.addEventListener(`click`,q),window.addEventListener(`popstate`,J),window.addEventListener(`pagehide`,Q),window.addEventListener(`pageshow`,$),()=>{document.removeEventListener(`click`,q),window.removeEventListener(`popstate`,J),window.removeEventListener(`pagehide`,Q),window.removeEventListener(`pageshow`,$)}),[]),y(()=>{g.current=i;let e=()=>{document.hidden?h.current=Date.now():h.current!==null&&Date.now()-h.current>g.current&&B.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[i]),y(()=>(c.current=!0,e((e,t)=>G.current?.(e,t)??Promise.resolve()),()=>{c.current=!1,t(),v(),D(),K.current?.cancel&&K.current.cancel()}),[]),T(C,{children:[n,a.error&&w(z,{error:a.error,onRetry:X,onReload:Z,onDismiss:ee,retryCount:d.current.getRetryCount(a.error.url||``),maxRetries:3})]})}var Z=class extends v{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`[rari] Layout: Error in layout "${this.props.layoutPath}":`,e,t),this.props.onError&&this.props.onError(e,t),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:layout-error`,{detail:{layoutPath:this.props.layoutPath,error:e,errorInfo:t,timestamp:Date.now()}}))}reset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError&&this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):T(`div`,{style:{padding:`16px`,margin:`16px 0`,background:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`},children:[w(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`},children:`Layout Error`}),T(`p`,{style:{margin:`0 0 8px 0`,fontSize:`14px`},children:[`An error occurred in layout:`,` `,w(`code`,{children:this.props.layoutPath})]}),T(`details`,{style:{fontSize:`12px`,marginBottom:`8px`},children:[w(`summary`,{style:{cursor:`pointer`},children:`Error details`}),T(`pre`,{style:{marginTop:`8px`,padding:`8px`,background:`#fff`,border:`1px solid #ddd`,borderRadius:`2px`,overflow:`auto`},children:[this.state.error.message,`
2
+ `,this.state.error.stack]})]}),w(`button`,{onClick:this.reset,type:`button`,style:{padding:`6px 12px`,background:`#c00`,color:`white`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},children:`Try Again`})]}):this.props.children}};export{X as ClientRouter,_ as DefaultError,f as DefaultLoading,h as ErrorBoundary,l as HttpRuntimeClient,Z as LayoutErrorBoundary,r as LoadingSpinner,F as NavigationErrorHandler,z as NavigationErrorOverlay,p as NotFound,V as StatePreserver,a as clearPropsCache,o as clearPropsCacheForComponent,g as createErrorBoundary,i as createHttpRuntimeClient,u as createLoadingBoundary,m as extractMetadata,d as extractServerProps,c as extractServerPropsWithCache,s as extractStaticParams,n as hasServerSideDataFetching};
@@ -0,0 +1 @@
1
+ function e(e){return e.loading=!0,e.loadPromise=e.loader().then(t=>(e.component=t,e.registered=!0,e.loading=!1,t)).catch(t=>{throw console.error(`[rari] Failed to load component ${e.id}:`,t),e.loading=!1,e.loadPromise=void 0,t}),e.loadPromise}async function t(t,n){return t.component==null?t.loadPromise?(await t.loadPromise,r(t,n)):t.loader?await e(t)==null?null:r(t,n):null:r(t,n)}function n(t){return!t.loader||t.loading||t.component!=null||t.loadPromise?Promise.resolve(null):e(t)}function r(e,t){if(e.component==null)return null;let n=e.component;return!t||t===`default`?n.default??n:n[t]===void 0?n.default?.[t]===void 0?null:n.default[t]:n[t]}function i(e){e.loader&&!e.loading&&!e.loadPromise&&n(e).catch(()=>{})}function a(e,t){let n=e.indexOf(`#`),a=n===-1?e:e.slice(0,n),o=n===-1?void 0:e.slice(n+1),s=t[a];return s?s.component==null?(i(s),null):r(s,o):null}function o(e,t,n,a){let o=a[e];if(!o||!n[o])return null;let s=n[o];return r(s,t)??(i(s),null)}function s(e,t,n){let r=e.indexOf(`#`),i=r===-1?e:e.slice(0,r),a=r===-1?``:e.slice(r+1),s=f(i);for(let e of s){let r=o(e,a,t,n);if(r!==null)return r}return null}function c(e,t,n){let a=e.indexOf(`#`),o=a===-1?e:e.slice(0,a),s=a===-1?void 0:e.slice(a+1),c=n[o];if(!c||!t[c])return null;let l=t[c];return r(l,s)??(i(l),null)}function l(e,t){let n=t[e];if(!n)return null;let a=e.indexOf(`#`);return r(n,a===-1?void 0:e.slice(a+1))??(a===-1?null:r(n))??(i(n),null)}function u(e,t){let n=t[`~clientComponents`]||{},r=t[`~clientComponentPaths`]||{},i=t[`~clientComponentNames`]||{},o=e.replace(/\\/g,`/`),u=l(o,n)||(o===e?null:l(e,n));if(u!==null)return u;let d=a(o,n)||(o===e?null:a(e,n));if(d!==null)return d;let f=s(o,n,r)||(o===e?null:s(e,n,r));return f===null?c(o,n,i)||(o===e?null:c(e,n,i)):f}function d(e){return u(e,globalThis)}function f(e){return e.startsWith(`./`)?[e,e.slice(2)]:[e,`./${e}`]}async function p(e){let n=globalThis[`~clientComponents`]||{},r=globalThis[`~clientComponentPaths`]||{},i=globalThis[`~clientComponentNames`]||{},a=e.replace(/\\/g,`/`),o=n[a];if(o){let e=a.indexOf(`#`),n=e===-1?void 0:a.slice(e+1);return await t(o,n)}if(a!==e&&(o=n[e],o)){let n=e.indexOf(`#`),r=n===-1?void 0:e.slice(n+1);return await t(o,r)}let s=a.indexOf(`#`),c=s===-1?a:a.slice(0,s),l=s===-1?void 0:a.slice(s+1);if(o=n[c],o)return await t(o,l);if(a!==e){let r=e.indexOf(`#`);if(o=n[r===-1?e:e.slice(0,r)],o)return await t(o,l)}let u=a===e?[c]:[c,e.includes(`#`)?e.slice(0,e.indexOf(`#`)):e];for(let e of u){for(let i of f(e)){let e=r[i];if(e&&(o=n[e],o))return await t(o,l)}let a=i[e];if(a&&(o=n[a],o))return await t(o,l)}return null}export{p as n,r,d as t};
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./get-client-component-BjjGTgmG.mjs";async function t(t,n){let r=t.split(`
2
+ `),i=new Set;for(let e of r){let t=e.trim();if(!t)continue;let r=t.indexOf(`:`);if(r===-1)continue;let a=t.substring(r+1);if(a.startsWith(`I{`))try{let e=a.substring(1),t=JSON.parse(e);if(typeof t==`object`&&!Array.isArray(t)&&t.id){let e=t.id.replace(/\\/g,`/`),r=t.name&&t.name!==`default`?`${e}#${t.name}`:e;(!n||!n.has(r))&&i.add(r)}}catch{}}i.size>0&&await Promise.all(Array.from(i,async t=>{try{if(!await e(t)){console.warn(`[rari] Failed to preload component: ${t}`);return}n?.add(t)}catch(e){console.error(`[rari] Error preloading component ${t}:`,e)}}))}export{t};
package/dist/router.mjs CHANGED
@@ -1 +1 @@
1
- import{n as e,r as t}from"./navigate-hfIqe3MK.mjs";import{createContext as n,use as r,useEffect as i,useMemo as a,useRef as o,useState as s}from"react";import{jsx as c}from"react/jsx-runtime";const l=n(null);function u({children:t,initialPathname:n}){let[r,u]=s(n),[d,f]=s(()=>typeof window<`u`?new URLSearchParams(window.location.search):new URLSearchParams),[p,m]=s({}),h=o(null);return i(()=>{let e=e=>{let t=e.detail;t?.to&&(u(t.to),f(new URLSearchParams(window.location.search)),t?.routeInfo?.extractedParams?m(t.routeInfo.extractedParams):m({}))};return window.addEventListener(`rari:navigate`,e),()=>{window.removeEventListener(`rari:navigate`,e)}},[]),i(()=>{let t=e();t&&(h.current=t);let n=e=>{h.current=e.detail.navigate},r=()=>{h.current=null};return window.addEventListener(`rari:register-navigate`,n),window.addEventListener(`rari:deregister-navigate`,r),()=>{window.removeEventListener(`rari:register-navigate`,n),window.removeEventListener(`rari:deregister-navigate`,r)}},[]),c(l,{value:a(()=>({pathname:r,params:p,searchParams:d,push:async(e,t)=>{h.current?await h.current(e,t):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.href=e)},replace:async(e,t)=>{h.current?await h.current(e,{...t,replace:!0}):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.replace(e))},back:()=>{window.history.back()},forward:()=>{window.history.forward()},refresh:()=>{window.dispatchEvent(new CustomEvent(`rari:app-router-rerender`))},prefetch:async e=>{try{let t=new URL(e,window.location.origin);await fetch(t.pathname+t.search,{headers:{Accept:`text/x-component`},priority:`low`})}catch(e){console.warn(`[rari] Prefetch failed:`,e)}}}),[r,p,d]),children:t})}function d(){let e=r(l);if(!e)throw Error(`useRouter must be used within a RouterProvider`);return e}function f(){return d().pathname}function p(){return d().params}function m(){return d().searchParams}export{u as RouterProvider,t as navigate,p as useParams,f as usePathname,d as useRouter,m as useSearchParams};
1
+ import{n as e,r as t}from"./navigate-hfIqe3MK.mjs";import{createContext as n,use as r,useEffect as i,useMemo as a,useRef as o,useState as s}from"react";import{jsx as c}from"react/jsx-runtime";const l=n(null);function u({children:t,initialPathname:n}){let[r,u]=s(n),[d,f]=s(()=>typeof window<`u`?new URLSearchParams(window.location.search):new URLSearchParams),[p,m]=s({}),h=o(null);return i(()=>{let e=e=>{let t=e.detail;t?.to&&(u(t.to),f(new URLSearchParams(window.location.search)),m({}))};return window.addEventListener(`rari:navigate`,e),()=>{window.removeEventListener(`rari:navigate`,e)}},[]),i(()=>{let t=e();t&&(h.current=t);let n=e=>{h.current=e.detail.navigate},r=()=>{h.current=null};return window.addEventListener(`rari:register-navigate`,n),window.addEventListener(`rari:deregister-navigate`,r),()=>{window.removeEventListener(`rari:register-navigate`,n),window.removeEventListener(`rari:deregister-navigate`,r)}},[]),c(l,{value:a(()=>({pathname:r,params:p,searchParams:d,push:async(e,t)=>{h.current?await h.current(e,t):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.href=e)},replace:async(e,t)=>{h.current?await h.current(e,{...t,replace:!0}):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.replace(e))},back:()=>{window.history.back()},forward:()=>{window.history.forward()},refresh:()=>{window.dispatchEvent(new CustomEvent(`rari:app-router-rerender`))},prefetch:async e=>{try{let t=new URL(e,window.location.origin);await fetch(t.pathname+t.search,{headers:{Accept:`text/x-component`},priority:`low`})}catch(e){console.warn(`[rari] Prefetch failed:`,e)}}}),[r,p,d]),children:t})}function d(){let e=r(l);if(!e)throw Error(`useRouter must be used within a RouterProvider`);return e}function f(){return d().pathname}function p(){return d().params}function m(){return d().searchParams}export{u as RouterProvider,t as navigate,p as useParams,f as usePathname,d as useRouter,m as useSearchParams};
@@ -15,6 +15,8 @@ interface NavigationDetail {
15
15
  routeInfo?: any;
16
16
  abortSignal?: AbortSignal;
17
17
  rscWireFormat?: string;
18
+ rscResponse?: Response;
19
+ rscResponsePromise?: Promise<Response>;
18
20
  isStreaming?: boolean;
19
21
  }
20
22
  declare function AppRouterProvider({
@@ -1,10 +1,9 @@
1
- "use client";import{x as e,y as t}from"../regex-constants-CmOAY1_W.mjs";import{t as n}from"../preload-components-Bp8OQWGz.mjs";import*as r from"react";import{Suspense as i,useEffect as a,useRef as o,useState as s,useTransition as c}from"react";import{Fragment as l,jsx as u,jsxs as d}from"react/jsx-runtime";const f=/"timestamp":(\d+)/,p=/^[;\s]*$/,ee=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)$/;function m(e){return new Promise(t=>{setTimeout(t,e)})}function h(e){if(!e||e.length===0)return!1;let t=e.charAt(0),n=e.charCodeAt(0);return e.startsWith(`I[`)||e.startsWith(`"$S`)?!1:!!(n===84||t===`[`||t===`{`||e.startsWith(`E{`)||t===`"`||ee.test(e))}function te(){return d(`div`,{style:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:9999},children:[u(`div`,{style:{width:`40px`,height:`40px`,border:`4px solid rgba(0, 0, 0, 0.1)`,borderTopColor:`#3b82f6`,borderRadius:`50%`,animation:`spin 1s linear infinite`}}),u(`style`,{children:`
1
+ "use client";import{x as e,y as t}from"../regex-constants-CmOAY1_W.mjs";import{t as n}from"../preload-modules-DcD-Wjko.mjs";import*as r from"react";import{Suspense as i,useEffect as a,useRef as o,useState as s}from"react";import{Fragment as c,jsx as l,jsxs as u}from"react/jsx-runtime";import{createFromFetch as d,createFromReadableStream as f}from"virtual:react-flight-client";const ee=/"timestamp":(\d+)/,p=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)$/,m=/^[0-9a-f]+$/i,te=/^\$L?[0-9a-f]+$/i;function ne(e){return new Promise(t=>{setTimeout(t,e)})}function h(e){if(!e||e.length===0)return!1;let t=e.charAt(0),n=e.charCodeAt(0);return e.startsWith(`I[`)||e.startsWith(`I{`)||e.startsWith(`"$S`)?!1:!!(n===84||t===`[`||t===`{`||e.startsWith(`E{`)||t===`"`||p.test(e))}function re(e){return!e||e.length===0?!1:!!(e.includes(`"fallback"`)||e.includes(`$Lfallback`)||e.startsWith(`E{`))}function ie(){return u(`div`,{style:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:9999},children:[l(`div`,{style:{width:`40px`,height:`40px`,border:`4px solid rgba(0, 0, 0, 0.1)`,borderTopColor:`#3b82f6`,borderRadius:`50%`,animation:`spin 1s linear infinite`}}),l(`style`,{children:`
2
2
  @keyframes spin {
3
3
  to { transform: rotate(360deg); }
4
4
  }
5
- `})]})}function ne({contentRef:e,rowsDataRef:t,modulesDataRef:n,symbolsDataRef:i,suspendingPromisesRef:a,getSuspendingPromise:o,rscToReact:s}){let c=t.current,l=n.current,u=i.current,d=a.current,f=c.has(e);if(r.useEffect(()=>{f&&d.has(e)&&d.delete(e)},[e,f,d]),f)return s(c.get(e),l,void 0,u,c);throw o(e)}function g({children:g,initialPayload:_,onNavigate:v}){let[y,b]=s(_),[,x]=s(0),S=o({x:0,y:0}),C=o(new Map),w=o(null),[,re]=c(),T=o(v),E=o(0),D=o(new Map),O=o([]),k=o(null),A=o(0),[j,M]=s(null),N=o(typeof window<`u`&&window.location.hash.length>0),ie=o(0),P=o(!1),F=o(!1),I=o(!1),L=o(Promise.resolve()),ae=o(!1),oe=o(!!_),R=o(null);a(()=>{T.current=v},[v]);let z=()=>{if(typeof document>`u`)return;let e=document.querySelectorAll(`form`);C.current.clear(),e.forEach((e,t)=>{let n=new FormData(e);C.current.set(`form-${t}`,n)})},se=()=>{typeof document>`u`||document.querySelectorAll(`form`).forEach((e,t)=>{let n=C.current.get(`form-${t}`);n&&n.forEach((t,n)=>{let r=e.elements.namedItem(n);r&&(r.type===`checkbox`||r.type===`radio`?r.checked=t===`on`:r.value=t)})})},B=(e,t,n,r)=>{let i={timestamp:Date.now(),error:e,type:t,details:n,filePath:r};O.current.push(i),A.current+=1,O.current.length>10&&O.current.shift(),console.error(`[rari] HMR: Failure detected`,{type:t,details:n,filePath:r,consecutiveFailures:A.current,error:e.message,stack:e.stack,timestamp:new Date(i.timestamp).toISOString()}),A.current>=2&&M(i),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:hmr-failure`,{detail:i}))},V=()=>{setTimeout(()=>{window.location.reload()},1e3)},H=()=>{A.current>0&&(A.current=0)},ce=e=>{if(!k.current)return!1;if(e===k.current)return!0;let t=e.match(f);if(t){let e=Number.parseInt(t[1],10);if(Date.now()-e>5e3)return!0}return!1};function le(e){let t;try{t=JSON.stringify(e)}catch{try{let n=new WeakSet;t=JSON.stringify(e,(e,t)=>{if(typeof t==`object`&&t){if(n.has(t))return`[Circular]`;n.add(t)}return t})}catch{t=`[Unstringifiable:${typeof e}:${String(e).substring(0,50)}]`}}let n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return Math.abs(n).toString(36)}function U(e,n,i,a,o,s){if(e==null)return null;if(typeof e==`string`&&e.startsWith(`$L`)&&o&&o.has(e)){let t=s??new Set;return t.has(e)?(console.warn(`[rari] AppRouter: Circular $L reference detected:`,e),null):(t.add(e),U(o.get(e),n,i,a,o,t))}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,s,c,l]=e,u=s;if(typeof s==`string`&&s.startsWith(`$`)&&a){let e=s.substring(1);if(t.test(e)){let e=a.get(s);e&&(e===`$Sreact.suspense`||e===`react.suspense`?u=`Suspense`:console.warn(`[rari] AppRouter: Unknown symbol:`,e))}}if(u===`Suspense`||s===`Suspense`){let e=Y(l,n,i,a,o);return r.createElement(r.Suspense,c?{...e,key:c}:e)}if(typeof u==`string`&&u.startsWith(`$L`)){let e=n.get(u);if(!e)return null;let t=globalThis[`~clientComponents`]?.[e.id]?.component;if(!t||typeof t!=`function`)return null;let s=c||`fallback-${u}-${ie.current++}`,d={...l,children:l.children===void 0?void 0:U(l.children,n,i,a,o)};return r.createElement(t,{key:s,...d})}if(!u||typeof u!=`string`&&typeof u!=`function`)return console.error(`[rari] AppRouter: Invalid component type:`,{type:u,typeOf:typeof u,serverKey:c,props:l,rscData:e}),null;let d=Y(l,n,i,a,o);return r.createElement(u,c?{...d,key:c}:d)}return e.map((e,t)=>{let s=U(e,n,i,a,o);if(s==null)return null;if(typeof s==`object`&&r.isValidElement(s)&&!s.key){let n=typeof e==`object`&&e?le(e):`primitive`,i=`rsc-${Array.isArray(e)&&e[0]===`$`&&e[1]?String(e[1]):`unknown`}-${n}-${t}`;return r.createElement(r.Fragment,{key:i},s)}return s}).filter(e=>e!=null)}return e}let W=o(new Set),G=o(new Map),K=o(new Map),q=o(new Map),J=o(new Map);function ue(e){if(!J.current.has(e)){let t=new Promise(()=>{});J.current.set(e,{promise:t,timestamp:Date.now()})}return J.current.get(e).promise}function de(){J.current.clear(),W.current.clear()}function fe(){let e=Date.now(),t=[];J.current.forEach((n,r)=>{e-n.timestamp>3e4&&t.push(r)}),t.forEach(e=>{J.current.delete(e),W.current.delete(e)})}function Y(e,t,n,i,a){if(!e||typeof e!=`object`)return e;a&&(G.current=a),t&&(K.current=t),i&&(q.current=i);let o={};for(let s in e)if(Object.hasOwn(e,s))if(s===`children`){let c=e.children;if(typeof c==`string`&&c.startsWith(`$L`))if(a&&a.has(c)){let e=a.get(c);W.current.delete(c),o[s]=U(e,t,n,i,a)}else W.current.add(c),o[s]=r.createElement(ne,{key:`lazy-${c}`,contentRef:c,rowsDataRef:G,modulesDataRef:K,symbolsDataRef:q,suspendingPromisesRef:J,getSuspendingPromise:ue,rscToReact:U});else o[s]=c===void 0?void 0:U(c,t,n,i,a)}else s===`dangerouslySetInnerHTML`?o[s]=e[s]:o[s]=U(e[s],t,n,i,a);return o}let pe=(e,t)=>{try{let n=t===`array`?`[`:`{`,r=t===`array`?`]`:`}`,i=0,a=-1,o=!1,s=!1;for(let t=0;t<e.length;t++){let c=e[t];if(s){s=!1;continue}if(c===`\\`){s=!0;continue}if(c===`"`&&!s){o=!o;continue}if(!o){if(c===n)i++;else if(c===r&&(i--,i===0)){a=t+1;break}}}if(a===-1)return null;let c=e.substring(0,a),l=e.substring(a).trim();return l.length>0&&!p.test(l)&&console.warn(`[rari] Sanitized corrupted JSON (possible userscript injection):`,{extracted:c.substring(0,100),discarded:l.substring(0,50)}),c}catch(e){return console.error(`[rari] Failed to sanitize JSON:`,e),null}},me=e=>{let t=new Set;if(!e?.modules||!e?.rawElement||!e?.rows)return t;let n=new Set,r=i=>{if(i){if(typeof i==`string`&&i.startsWith(`$L`)){let a=e.modules.get(i);a?.id&&(t.add(a.id),a.name&&a.name!==`default`&&t.add(`${a.id}#${a.name}`)),e.rows?.has(i)&&!n.has(i)&&(n.add(i),r(e.rows.get(i)));return}if(Array.isArray(i)){for(let e of i)r(e);return}if(typeof i==`object`&&i)for(let e of Object.values(i))r(e)}};return r(e.rawElement),t},X=async(e,r=!1,i=!0)=>{try{let a=e.split(`
6
- `),o=new Map,s=new Map,c=new Map,l=null,u=[],d=null,f=null;for(let e=0;e<a.length;e++){let n=a[e];if(!n.trim())continue;let i=n.indexOf(`:`);if(i===-1)continue;let p=n.substring(0,i).trim();if(!t.test(p)){console.warn(`[rari] AppRouter: Invalid row ID (non-numeric), skipping line:`,n.substring(0,50));continue}let m=n.substring(i+1);try{if(m.startsWith(`"$S`)){let e=m.slice(1,-1);s.set(`$${p}`,e);continue}if(m.startsWith(`I[`)){let t=pe(m.substring(1),`array`);if(!t){console.warn(`[rari] AppRouter: Could not sanitize import line, skipping:`,n.substring(0,80));continue}let i=JSON.parse(t);if(Array.isArray(i)&&i.length>=3){let[t,n,a]=i;o.set(`$L${p}`,{id:t,chunks:Array.isArray(n)?n:[n],name:a||`default`}),r&&t.includes(`layout`)&&(d!==null&&f!==null&&u.push({layoutPath:d,startLine:f,endLine:e-1,props:{}}),d=t,f=e)}}else if(m.startsWith(`[`)){let e=JSON.parse(m);if(c.set(`$L${p}`,e),r&&Array.isArray(e)&&e.length>=4&&typeof e[1]==`string`&&e[1].startsWith(`$L`)){let t=e[1],n=o.get(t);if(n&&n.id.includes(`layout`)){let t=e[3]||{};if(d&&f!==null){let e=u.find(e=>e.layoutPath===d&&e.startLine===f);e&&(e.props=t)}}}l===null&&Array.isArray(e)&&(e[0]===`$`?l=e:Array.isArray(e[0])&&e[0][0]===`$`&&(l=e.length===1?e[0]:e))}else if(m.startsWith(`{`)||m.startsWith(`E{`)){let e=m.startsWith(`E{`)?m.substring(1):m,t=JSON.parse(e);c.set(`$L${p}`,t),l===null&&(l=t)}else if(m.charCodeAt(0)===84){let e=m.slice(1);c.set(`$L${p}`,e),l===null&&(l=e)}else if(m.startsWith(`"`)&&!m.startsWith(`"$S`)){let e=JSON.parse(m);c.set(`$L${p}`,e),l===null&&(l=e)}else if(ee.test(m)){let e=JSON.parse(m);c.set(`$L${p}`,e),l===null&&(l=e)}}catch(e){console.error(`[rari] AppRouter: Failed to parse RSC line:`,n,e)}}i&&await n(o),r&&d!==null&&f!==null&&u.push({layoutPath:d,startLine:f,endLine:a.length-1,props:{}});let p=l;return l!=null&&(ie.current=0,l=U(l,o,void 0,s,c)),{element:l,rawElement:p,rows:c,modules:o,symbols:s,wireFormat:e,layoutBoundaries:r?u:void 0}}catch(e){throw console.error(`[rari] AppRouter: Failed to parse RSC wire format:`,e),e}},he=async(t,n)=>{let r=t||window.location.pathname,i=E.current,a=`${i}:${r}${window.location.search}`,o=D.current.get(a);if(o)return o;let s=(async()=>{try{let t=(import.meta.env.RARI_SERVER_URL||window.location.origin).replace(e,``)+r+window.location.search,a=await fetch(t,{headers:{Accept:`text/x-component`},cache:`no-store`,signal:n});if(!a.ok){let e=Error(`Failed to fetch RSC data: ${a.status} ${a.statusText}`);throw B(e,`fetch`,`HTTP ${a.status} when fetching ${t}`,window.location.pathname),e}let o=await a.text();if(ce(o)&&y)return y;let s;try{s=await X(o,!1)}catch(e){let t=e instanceof Error?e:Error(String(e));throw B(t,`parse`,`Failed to parse RSC wire format: ${t.message}`,window.location.pathname),t}return E.current===i&&(b(s),k.current=o,H()),s}catch(e){throw e instanceof Error&&!e.message.includes(`Failed to fetch RSC data`)&&!e.message.includes(`Failed to parse`)&&B(e,`network`,`Network error: ${e.message}`,window.location.pathname),console.error(`[rari] AppRouter: Error fetching RSC payload:`,e),e}finally{D.current.delete(a)}})();return D.current.set(a,s),s},Z=o(X),Q=o(he),ge=o(Y),_e=o(U);a(()=>{Z.current=X,Q.current=he,ge.current=Y,_e.current=U}),a(()=>{if(typeof window>`u`)return;let e=setInterval(()=>{fe()},3e4),n=async e=>{let t=e.detail;t.navigationId===E.current&&(N.current=!0,t.isStreaming||(w.current=null),de(),S.current={x:window.scrollX,y:window.scrollY},z(),re(async()=>{try{if(t.rscWireFormat){let e=await Z.current(t.rscWireFormat,!1,!0);E.current===t.navigationId&&(b(e),k.current=t.rscWireFormat,H())}else if(t.isStreaming){E.current===t.navigationId&&(M(null),R.current=t),ae.current=!1;return}else await Q.current(t.to,t.abortSignal);E.current===t.navigationId&&(x(e=>e+1),M(null),T.current&&T.current(t))}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;console.error(`[rari] AppRouter: Navigation failed:`,e),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:t.from,to:t.to,error:e,navigationId:t.navigationId}})),A.current>=3&&V()}finally{let e=typeof window<`u`&&window.location.hash.length>0;!t.options?.historyKey&&!e&&requestAnimationFrame(()=>{t.options?.scroll!==!1&&window.scrollTo(0,0)})}}))},r=async()=>{S.current={x:window.scrollX,y:window.scrollY},z();try{await Q.current(),x(e=>e+1),M(null)}catch(e){console.error(`[rari] AppRouter: HMR update failed:`,e),A.current>=3&&V()}finally{requestAnimationFrame(()=>{window.scrollTo(S.current.x,S.current.y),se()})}},i=async()=>{try{await Q.current(),x(e=>e+1),M(null)}catch(e){console.error(`[rari] AppRouter: RSC invalidation failed:`,e),A.current>=3&&V()}},a=e=>{let t=e;w.current=[],E.current=t.detail.navigationId,P.current=!1,F.current=!1,I.current=!1,L.current=Promise.resolve(),ae.current=!0,oe.current=!1,R.current=null},o=async()=>{try{await Q.current(),M(null)}catch(e){console.error(`[rari] AppRouter: Manifest update failed:`,e),A.current>=3&&V()}},s=async()=>{if(!w.current||w.current.length===0||oe.current)return;let e=E.current,n=[...w.current],r=n.some(e=>{let n=e.indexOf(`:`),r=n>0?e.substring(0,n).trim():``,i=n>0?e.substring(n+1):``;return t.test(r)&&h(i)}),i=n.some(e=>{let r=e.indexOf(`:`),i=r>0?e.substring(0,r).trim():``,a=r>0?e.substring(r+1):``;return!t.test(i)||!h(a)?!1:n.some(e=>{let t=e.indexOf(`:`),n=t>0?e.substring(t+1):``;return RegExp(`"?\\$L${i}"?(?![0-9a-fA-F])`).test(n)})});if(!r&&!i)return;if(!P.current&&r&&!i&&(P.current=!0,n.some(e=>e.includes(`"$Sreact.suspense"`)||e.includes(`react.suspense`)))){let t=n.filter(e=>{let t=e.indexOf(`:`),r=t>0?e.substring(0,t).trim():``,a=RegExp(`"\\$L${r}"(?![0-9a-fA-F])`);return!i||!n.some(e=>a.test(e))});try{let n=await Z.current(t.join(`
7
- `),!1,!1);E.current===e&&(b(n),x(e=>e+1))}catch(e){console.error(`[rari] AppRouter: Failed to parse shell:`,e)}return}let a=n.some(e=>e.includes(`"$Sreact.suspense"`)||e.includes(`react.suspense`));if(!(!i&&a&&!I.current)&&!F.current){P.current=!0;try{let t=await Z.current(n.join(`
8
- `),!1,!0);if(a||i){let r=me(t);(async()=>{let t=0,i=!1;for(;t<20;){let e=globalThis[`~clientComponents`]||{},n=Object.entries(e).filter(([e,t])=>r.has(e)&&t.loading&&t.loadPromise).map(([e,t])=>t.loadPromise);if(n.length===0){i=!0;break}try{await Promise.race([Promise.all(n),m(50)])}catch{}await m(10),t++}if(i||console.warn(`[rari] AppRouter: Module load timeout, rendering anyway`),E.current===e&&!F.current){F.current=!0;try{let t=w.current?[...w.current]:n,r=await Z.current(t.join(`
9
- `),!1,!1);E.current===e&&(b(r),x(e=>e+1),R.current&&T.current&&(T.current(R.current),R.current=null),I.current&&(w.current=null))}catch(e){console.error(`[rari] AppRouter: Failed to re-parse after client load:`,e)}}})().catch(e=>{console.error(`[rari] AppRouter: Client component loading failed:`,e)})}if(E.current!==e||F.current)return;let r=w.current?[...w.current]:n;if(t=await Z.current(r.join(`
10
- `),!1,!1),E.current!==e||F.current)return;b(t),x(e=>e+1),R.current&&T.current&&(T.current(R.current),R.current=null),I.current&&(F.current=!0,w.current=null)}catch(e){console.error(`[rari] AppRouter: Failed to parse streaming RSC row:`,e)}}},c=e=>{let t=e,n=t.detail.rscRow,r=t.detail.navigationId;if(!n||!n.trim()||!w.current)return;let i=E.current;if(!(r==null||r!==i)){if(n.trim()===`STREAM_COMPLETE`){I.current=!0,L.current=L.current.then(()=>{if(E.current===i)return s()});return}w.current.push(n),L.current=L.current.then(()=>{if(E.current===i)return s()})}};return window.addEventListener(`rari:navigation-start`,a),window.addEventListener(`rari:navigate`,n),window.addEventListener(`rari:app-router-rerender`,r),window.addEventListener(`rari:rsc-invalidate`,i),window.addEventListener(`rari:app-router-manifest-updated`,o),window.addEventListener(`rari:rsc-row`,c),()=>{clearInterval(e),de(),window.removeEventListener(`rari:navigation-start`,a),window.removeEventListener(`rari:navigate`,n),window.removeEventListener(`rari:app-router-rerender`,r),window.removeEventListener(`rari:rsc-invalidate`,i),window.removeEventListener(`rari:app-router-manifest-updated`,o),window.removeEventListener(`rari:rsc-row`,c)}},[]),a(()=>{if(!(typeof window>`u`)&&window.location.hash&&y&&N.current){let e=window.location.hash.slice(1);requestAnimationFrame(()=>{requestAnimationFrame(()=>{let t=document.getElementById(e);t&&(t.scrollIntoView({behavior:`instant`,block:`start`}),N.current=!1)})})}},[y]);let ve=()=>{window.location.reload()},ye=()=>{M(null)},be=e=>{if(!e||typeof e!=`object`)return null;if(e.type===`html`&&e.props?.children){let t=Array.isArray(e.props.children)?e.props.children:[e.props.children];for(let e of t)if(e&&typeof e==`object`&&e.type===`body`)return e.props?.children??null}return e},$=g;return y?.element!=null&&($=be(y.element)??y.element),Array.isArray($)&&$.length===1&&r.isValidElement($[0])?$=$[0]:Array.isArray($)&&$.length>0&&$.every(e=>r.isValidElement(e)||e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)&&($=r.createElement(r.Fragment,null,...$)),$&&typeof $==`object`&&!r.isValidElement($)&&(console.error(`[rari] AppRouter: Invalid content to render:`,$),$=g),d(l,{children:[j&&d(`div`,{style:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,padding:`24px`,background:`rgba(220, 38, 38, 0.95)`,color:`white`,borderRadius:`8px`,fontSize:`14px`,zIndex:1e4,maxWidth:`500px`,boxShadow:`0 4px 6px rgba(0, 0, 0, 0.3)`},children:[u(`div`,{style:{marginBottom:`16px`,fontWeight:`bold`,fontSize:`16px`},children:`⚠️ HMR Update Failed`}),d(`div`,{style:{marginBottom:`12px`,opacity:.9},children:[j.type===`fetch`&&`Failed to fetch updated content from server.`,j.type===`parse`&&`Failed to parse server response.`,j.type===`stale`&&`Server returned stale content.`,j.type===`network`&&`Network error occurred.`]}),u(`div`,{style:{marginBottom:`16px`,fontSize:`12px`,opacity:.8,fontFamily:`monospace`},children:j.details}),d(`div`,{style:{marginBottom:`12px`,fontSize:`12px`,opacity:.7},children:[`Consecutive failures:`,` `,A.current,` `,`/`,` `,3]}),d(`div`,{style:{display:`flex`,gap:`8px`},children:[u(`button`,{onClick:ve,type:`button`,style:{padding:`8px 16px`,background:`white`,color:`#dc2626`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontWeight:`bold`,fontSize:`14px`},children:`Refresh Page`}),u(`button`,{onClick:ye,type:`button`,style:{padding:`8px 16px`,background:`rgba(255, 255, 255, 0.2)`,color:`white`,border:`1px solid rgba(255, 255, 255, 0.3)`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},children:`Dismiss`})]}),u(`div`,{style:{marginTop:`12px`,fontSize:`11px`,opacity:.6},children:`Check the console for detailed error logs.`})]}),u(i,{fallback:u(te,{}),children:$})]})}export{g as AppRouterProvider};
5
+ `})]})}function ae({contentRef:e,rowsDataRef:t,modulesDataRef:n,symbolsDataRef:i,suspendingPromisesRef:a,getSuspendingPromise:o,rscToReact:s}){let c=t.current,l=n.current,u=i.current,d=a.current,f=c.has(e);if(r.useEffect(()=>{f&&d.has(e)&&d.delete(e)},[e,f,d]),f)return s(c.get(e),l,void 0,u,c);throw o(e)}function g({children:p,initialPayload:g,onNavigate:_}){let[v,y]=s(g),b=s(0)[1],x=o({x:0,y:0}),S=o(new Map),C=o(null),oe=o(new Set),w=o(_),T=o(0),E=o(new Map),D=o([]),O=o(null),k=o(0),[A,j]=s(null),M=o(typeof window<`u`&&window.location.hash.length>0),se=o(0),N=o(!1),P=o(!1),F=o(!1),I=o(Promise.resolve()),ce=o(!1),le=o(!!g),L=o(null);a(()=>{w.current=_},[_]),a(()=>{if(v?.element!=null&&v.element&&typeof v.element==`object`&&`status`in v.element&&v.element.status===`rejected`){let e=v.element.reason;e&&console.error(`[rari] AppRouter: Flight payload rejected:`,e)}},[v]);let R=()=>{if(typeof document>`u`)return;let e=document.querySelectorAll(`form`);S.current.clear(),e.forEach((e,t)=>{let n=new FormData(e);S.current.set(`form-${t}`,n)})},ue=()=>{typeof document>`u`||document.querySelectorAll(`form`).forEach((e,t)=>{let n=S.current.get(`form-${t}`);n&&n.forEach((t,n)=>{let r=e.elements.namedItem(n);r&&(r.type===`checkbox`||r.type===`radio`?r.checked=t===`on`:r.value=t)})})},z=(e,t,n,r)=>{let i={timestamp:Date.now(),error:e,type:t,details:n,filePath:r};D.current.push(i),k.current+=1,D.current.length>10&&D.current.shift(),k.current>=2&&j(i),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:hmr-failure`,{detail:i}))},B=()=>{setTimeout(()=>{window.location.reload()},1e3)},V=()=>{k.current>0&&(k.current=0)},de=e=>{if(!O.current)return!1;if(e===O.current)return!0;let t=e.match(ee);if(t){let e=Number.parseInt(t[1],10);if(Date.now()-e>5e3)return!0}return!1};function fe(e){let t;try{t=JSON.stringify(e)}catch{try{let n=new WeakSet;t=JSON.stringify(e,(e,t)=>{if(typeof t==`object`&&t){if(n.has(t))return`[Circular]`;n.add(t)}return t})}catch{t=`[Unstringifiable:${typeof e}:${String(e).substring(0,50)}]`}}let n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return Math.abs(n).toString(36)}function H(e,n,i,a,o,s){if(e==null)return null;if(typeof e==`string`&&e.startsWith(`$`)&&e.length>1&&m.test(e.substring(1))&&o&&o.has(e)){let t=s??new Set;return t.has(e)?(console.warn(`[rari] AppRouter: Circular $ reference detected:`,e),null):(t.add(e),H(o.get(e),n,i,a,o,t))}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,s,c,l]=e,u=s;if(typeof s==`string`&&s.startsWith(`$`)&&a){let e=s.substring(1);if(t.test(e)){let e=a.get(s);e&&(e===`$Sreact.suspense`||e===`react.suspense`?u=`Suspense`:console.warn(`[rari] AppRouter: Unknown symbol:`,e))}}if(u===`Suspense`||s===`Suspense`){let e=he(l,n,i,a,o);return r.createElement(r.Suspense,c?{...e,key:c}:e)}if(typeof u==`string`&&u.startsWith(`$`)&&te.test(u)){let e=n.get(u);if(!e)return console.warn(`[rari] AppRouter: Module not found for reference:`,u,`Available modules:`,Array.from(n.keys())),null;let t=globalThis[`~clientComponents`]?.[e.id]?.component;if(!t)return console.warn(`[rari] AppRouter: Component not loaded:`,e.id),null;if(typeof t!=`function`)return null;let s=c||`fallback-${u}-${se.current++}`,d={...l,children:l.children===void 0?void 0:H(l.children,n,i,a,o)};return r.createElement(t,{key:s,...d})}if(!u||typeof u!=`string`&&typeof u!=`function`||typeof u==`string`&&u.startsWith(`$`))return null;let d=he(l,n,i,a,o);return r.createElement(u,c?{...d,key:c}:d)}return e.map((e,t)=>{let s=H(e,n,i,a,o);if(s==null)return null;if(typeof s==`object`&&r.isValidElement(s)&&!s.key){let n=typeof e==`object`&&e?fe(e):`primitive`,i=`rsc-${Array.isArray(e)&&e[0]===`$`&&e[1]?String(e[1]):`unknown`}-${n}-${t}`;return r.createElement(r.Fragment,{key:i},s)}return s}).filter(e=>e!=null)}return e}let U=o(new Set),W=o(new Map),G=o(new Map),K=o(new Map),q=o(new Map);function pe(e){if(!q.current.has(e)){let t=new Promise(()=>{});q.current.set(e,{promise:t,timestamp:Date.now()})}return q.current.get(e).promise}function J(){q.current.clear(),U.current.clear()}function me(){let e=Date.now(),t=[];q.current.forEach((n,r)=>{e-n.timestamp>3e4&&t.push(r)}),t.forEach(e=>{q.current.delete(e),U.current.delete(e)})}function he(e,t,n,i,a){if(!e||typeof e!=`object`)return e;a&&(W.current=a),t&&(G.current=t),i&&(K.current=i);let o={};for(let s in e)if(Object.hasOwn(e,s))if(s===`children`){let c=e.children;if(typeof c==`string`&&c.startsWith(`$`)&&c.length>1&&m.test(c.substring(1)))if(a&&a.has(c)){let e=a.get(c);U.current.delete(c),o[s]=H(e,t,n,i,a)}else U.current.add(c),o[s]=r.createElement(ae,{key:`lazy-${c}`,contentRef:c,rowsDataRef:W,modulesDataRef:G,symbolsDataRef:K,suspendingPromisesRef:q,getSuspendingPromise:pe,rscToReact:H});else o[s]=c===void 0?void 0:H(c,t,n,i,a)}else s===`dangerouslySetInnerHTML`?o[s]=e[s]:o[s]=H(e[s],t,n,i,a);return o}let Y=async e=>{await n(e,oe.current);let t=await f(new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e)),t.close()}}));return{element:t,rawElement:t,wireFormat:e}},ge=e=>({element:d(e)}),_e=async(t,n)=>{let r=t||window.location.pathname,i=T.current,a=`${i}:${r}${window.location.search}`,o=E.current.get(a);if(o)return o;let s=(async()=>{try{let t=(import.meta.env.RARI_SERVER_URL||window.location.origin).replace(e,``)+r+window.location.search,a=await fetch(t,{headers:{Accept:`text/x-component`},cache:`no-store`,signal:n});if(!a.ok){let e=Error(`Failed to fetch RSC data: ${a.status} ${a.statusText}`);throw z(e,`fetch`,`HTTP ${a.status} when fetching ${t}`,window.location.pathname),e}let o=await a.text();if(de(o)&&v)return v;let s;try{s=await Y(o)}catch(e){let t=e instanceof Error?e:Error(String(e));throw z(t,`parse`,`Failed to parse RSC wire format: ${t.message}`,window.location.pathname),t}return T.current===i&&(y(s),O.current=o,V()),s}catch(e){throw e instanceof Error&&!e.message.includes(`Failed to fetch RSC data`)&&!e.message.includes(`Failed to parse`)&&z(e,`network`,`Network error: ${e.message}`,window.location.pathname),e}finally{E.current.delete(a)}})();return E.current.set(a,s),s},X=o(Y),Z=o(ge),Q=o(_e);a(()=>{X.current=Y,Z.current=ge,Q.current=_e}),a(()=>{if(typeof window>`u`)return;let e=setInterval(()=>{me()},3e4),t=async e=>{let t=e.detail;if(t.navigationId!==T.current)return;M.current=!0,t.isStreaming||(C.current=null),J(),x.current={x:window.scrollX,y:window.scrollY},R();let n=null,r=null;try{t.rscResponsePromise?n=Z.current(t.rscResponsePromise):t.rscResponse?n=Z.current(Promise.resolve(t.rscResponse)):t.rscWireFormat?n=await X.current(t.rscWireFormat):t.isStreaming||(n=await Q.current(t.to,t.abortSignal))}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;r=e}if(r){console.error(`[rari] AppRouter: Navigation failed:`,r),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:t.from,to:t.to,error:r,navigationId:t.navigationId}})),k.current>=3&&B();return}if(!n&&t.isStreaming&&T.current===t.navigationId){L.current=t;return}n&&T.current===t.navigationId&&(y(n),t.rscWireFormat&&(O.current=t.rscWireFormat),V(),b(e=>e+1),j(null),w.current&&w.current(t));let i=typeof window<`u`&&window.location.hash.length>0;!t.options?.historyKey&&!i&&requestAnimationFrame(()=>{t.options?.scroll!==!1&&window.scrollTo(0,0)})},n=async()=>{x.current={x:window.scrollX,y:window.scrollY},R();try{await Q.current(),b(e=>e+1),j(null)}catch(e){console.error(`HMR refetch error:`,e instanceof Error?e.message:String(e)),k.current>=3&&B()}finally{requestAnimationFrame(()=>{window.scrollTo(x.current.x,x.current.y),ue()})}},r=async()=>{try{await Q.current(),b(e=>e+1),j(null)}catch(e){console.error(`RSC invalidate error:`,e instanceof Error?e.message:String(e)),k.current>=3&&B()}},i=e=>{let t=e;if(C.current=[],oe.current.clear(),T.current=t.detail.navigationId,typeof window<`u`){let e=window;e[`~rari`]||={},e[`~rari`].navigationId=t.detail.navigationId}N.current=!1,P.current=!1,F.current=!1,I.current=Promise.resolve(),ce.current=!0,le.current=!1,L.current=null},a=async()=>{try{await Q.current(),j(null)}catch(e){console.error(`Manifest update error:`,e instanceof Error?e.message:String(e)),k.current>=3&&B()}},o=async()=>{if(!C.current||C.current.length===0||le.current)return;let e=T.current,t=[...C.current],n=t.some(e=>{let t=e.indexOf(`:`),n=t>0?e.substring(0,t).trim():``,r=t>0?e.substring(t+1):``;return m.test(n)&&h(r)}),r=t.some(e=>{let n=e.indexOf(`:`),r=n>0?e.substring(0,n).trim():``,i=n>0?e.substring(n+1):``;return!m.test(r)||!h(i)?!1:t.some(e=>{let t=e.indexOf(`:`),n=t>0?e.substring(0,t).trim():``,i=t>0?e.substring(t+1):``;return!m.test(n)||!h(i)||re(i)?!1:RegExp(`"?\\$L?${r}"?(?![0-9a-fA-F])`).test(i)})});if(!n&&!r)return;if(!N.current&&n&&!r&&(N.current=!0,t.some(e=>e.includes(`"$Sreact.suspense"`)||e.includes(`react.suspense`)))){try{let n=t.filter(e=>{let n=e.indexOf(`:`),i=n>0?e.substring(0,n).trim():``,a=RegExp(`"\\$L?${i}"(?![0-9a-fA-F])`);return!r||!t.some(e=>a.test(e))}),i=await X.current(n.join(`
6
+ `));T.current===e&&(y(i),b(e=>e+1))}catch(e){console.error(`[rari] Failed to parse shell payload:`,e),N.current=!1,I.current=Promise.resolve()}return}let i=t.some(e=>e.includes(`"$Sreact.suspense"`)||e.includes(`react.suspense`));if(!(!r&&i&&!F.current)&&!P.current){N.current=!0;try{let n=await X.current(t.join(`
7
+ `));if((i||r)&&(await ne(50),T.current===e&&!P.current)){let n=C.current?[...C.current]:t,r=await X.current(n.join(`
8
+ `));T.current===e&&(P.current=!0,y(r),b(e=>e+1),L.current&&w.current&&(w.current(L.current),L.current=null),F.current&&(C.current=null))}if(T.current!==e||P.current)return;let a=C.current?[...C.current]:t;if(n=await X.current(a.join(`
9
+ `)),T.current!==e||P.current)return;y(n),b(e=>e+1),L.current&&w.current&&(w.current(L.current),L.current=null),F.current&&(P.current=!0,C.current=null)}catch(e){console.error(`Process rows error:`,e instanceof Error?e.message:String(e))}}},s=e=>{let t=e,n=t.detail.rscRow,r=t.detail.navigationId;if(!n||!n.trim()||!C.current)return;let i=T.current;if(!(r==null||r!==i)){if(n.trim()===`STREAM_COMPLETE`){F.current=!0,I.current=I.current.then(()=>{if(T.current===i)return o()});return}C.current.push(n),I.current=I.current.then(()=>{if(T.current===i)return o()})}};return window.addEventListener(`rari:navigation-start`,i),window.addEventListener(`rari:navigate`,t),window.addEventListener(`rari:app-router-rerender`,n),window.addEventListener(`rari:rsc-invalidate`,r),window.addEventListener(`rari:app-router-manifest-updated`,a),window.addEventListener(`rari:rsc-row`,s),()=>{clearInterval(e),J(),window.removeEventListener(`rari:navigation-start`,i),window.removeEventListener(`rari:navigate`,t),window.removeEventListener(`rari:app-router-rerender`,n),window.removeEventListener(`rari:rsc-invalidate`,r),window.removeEventListener(`rari:app-router-manifest-updated`,a),window.removeEventListener(`rari:rsc-row`,s)}},[]),a(()=>{if(!(typeof window>`u`)&&window.location.hash&&v&&M.current){let e=window.location.hash.slice(1);requestAnimationFrame(()=>{requestAnimationFrame(()=>{let t=document.getElementById(e);t&&(t.scrollIntoView({behavior:`instant`,block:`start`}),M.current=!1)})})}},[v]);let ve=()=>{window.location.reload()},ye=()=>{j(null)},be=e=>{if(!e||typeof e!=`object`)return null;if(e.type===`html`&&e.props?.children){let t=Array.isArray(e.props.children)?e.props.children:[e.props.children];for(let e of t)if(e&&typeof e==`object`&&e.type===`body`)return e.props?.children??null}return e},$=p;if(v?.element!=null)if(v.element&&typeof v.element==`object`&&`status`in v.element){let e=v.element.status;$=e===`fulfilled`?v.element.value:e===`rejected`?p:r.use(v.element)}else $=be(v.element)??v.element;return Array.isArray($)&&$.length===1&&r.isValidElement($[0])?$=$[0]:Array.isArray($)&&$.length>0&&$.every(e=>r.isValidElement(e)||e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)&&($=r.createElement(r.Fragment,null,...$)),u(c,{children:[A&&u(`div`,{style:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,padding:`24px`,background:`rgba(220, 38, 38, 0.95)`,color:`white`,borderRadius:`8px`,fontSize:`14px`,zIndex:1e4,maxWidth:`500px`,boxShadow:`0 4px 6px rgba(0, 0, 0, 0.3)`},children:[l(`div`,{style:{marginBottom:`16px`,fontWeight:`bold`,fontSize:`16px`},children:`⚠️ HMR Update Failed`}),u(`div`,{style:{marginBottom:`12px`,opacity:.9},children:[A.type===`fetch`&&`Failed to fetch updated content from server.`,A.type===`parse`&&`Failed to parse server response.`,A.type===`stale`&&`Server returned stale content.`,A.type===`network`&&`Network error occurred.`]}),l(`div`,{style:{marginBottom:`16px`,fontSize:`12px`,opacity:.8,fontFamily:`monospace`},children:A.details}),u(`div`,{style:{marginBottom:`12px`,fontSize:`12px`,opacity:.7},children:[`Consecutive failures:`,` `,k.current,` `,`/`,` `,3]}),u(`div`,{style:{display:`flex`,gap:`8px`},children:[l(`button`,{onClick:ve,type:`button`,style:{padding:`8px 16px`,background:`white`,color:`#dc2626`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontWeight:`bold`,fontSize:`14px`},children:`Refresh Page`}),l(`button`,{onClick:ye,type:`button`,style:{padding:`8px 16px`,background:`rgba(255, 255, 255, 0.2)`,color:`white`,border:`1px solid rgba(255, 255, 255, 0.3)`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},children:`Dismiss`})]}),l(`div`,{style:{marginTop:`12px`,fontSize:`11px`,opacity:.6},children:`Check the console for detailed error logs.`})]}),l(i,{fallback:l(ie,{}),children:$})]})}export{g as AppRouterProvider};
@@ -1,10 +1,10 @@
1
- import"../regex-constants-CmOAY1_W.mjs";import{n as e,t}from"../get-client-component-YrjzU6RI.mjs";import*as n from"react";import"react";import{ClientRouter as r}from"rari/client";import{RouterProvider as i}from"rari/router";import{createRoot as a}from"react-dom/client";import{AppRouterProvider as o}from"virtual:app-router-provider";import{createFromReadableStream as s}from"virtual:react-server-dom-rari-client.ts";import"virtual:rsc-integration.ts";function c(){return globalThis[`~rari`]}function l(){return globalThis}function u(){return window}function d(){return{moduleMap:new Proxy({},{get(e,t){return new Proxy({},{get(e,n){return{id:`${String(t)}#${String(n)}`,chunks:[],name:String(n)}}})}}),moduleLoading:new Proxy({},{get(e,t){return new Proxy({},{get(e,n){return async()=>{try{let e=String(t),r=String(n),i=`${e}#${r}`;if(l()[`~clientComponents`]?.[i]?.component)return l()[`~clientComponents`][i].component;if(l()[`~clientComponents`]?.[e]?.component){let t=l()[`~clientComponents`][e].component;return r===`default`?t:t?.[r]}let a=l()[`~clientComponents`]?.[i]||l()[`~clientComponents`]?.[e];if(a?.loader){a.loadPromise||=(a.loading=!0,a.loader().then(e=>(a.component=e.default||e,a.registered=!0,a.loading=!1,e)).catch(t=>{throw a.loading=!1,a.loadPromise=void 0,console.error(`[rari] Failed to lazy load ${e}#${r}:`,t),t}));let t=await a.loadPromise,n=t.default||t;return r===`default`?n:n?.[r]??n}return console.warn(`[rari] Module ${e}#${r} not found in client components registry`),null}catch(e){return console.error(`[rari] Failed to load ${String(t)}#${String(n)}:`,e),null}}}})}})}}c()===void 0&&(globalThis[`~rari`]={}),c().AppRouterProvider=o,c().ClientRouter=r,c().getClientComponent=t;async function f(t){try{await e(t)}catch(e){console.error(`[rari] Failed to preload component ${t}:`,e)}}
1
+ import"../regex-constants-CmOAY1_W.mjs";import{n as e,r as t,t as n}from"../get-client-component-BjjGTgmG.mjs";import{t as r}from"../preload-modules-DcD-Wjko.mjs";import*as i from"react";import"react";import{ClientRouter as a}from"rari/client";import{RouterProvider as o}from"rari/router";import{createRoot as s}from"react-dom/client";import{AppRouterProvider as c}from"virtual:app-router-provider";import{createFromReadableStream as l}from"virtual:react-flight-client";import"virtual:rsc-integration.ts";const u=/^\$L?[0-9a-f]+$/i;function d(e,t){let n=e.get(t);if(n)return n;let r=t.startsWith(`$L`)?`$${t.slice(2)}`:`$L${t.slice(1)}`;return e.get(r)}function f(){return globalThis[`~rari`]}function p(){return globalThis}function m(){return window}f()===void 0&&(globalThis[`~rari`]={}),f().AppRouterProvider=c,f().ClientRouter=a,f().getClientComponent=n;async function h(t){try{await e(t)}catch(e){console.error(`[rari] Failed to preload component ${t}:`,e)}}
2
2
  /*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */
3
- c().preloadClientComponent=f,l()[`~clientComponents`]===void 0&&(globalThis[`~clientComponents`]={}),l()[`~clientComponentPaths`]===void 0&&(globalThis[`~clientComponentPaths`]={});
3
+ f().preloadClientComponent=h,p()[`~clientComponents`]===void 0&&(globalThis[`~clientComponents`]={}),p()[`~clientComponentPaths`]===void 0&&(globalThis[`~clientComponentPaths`]={});
4
4
  /*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */
5
- function p(){c().hydrateClientComponents||(c().hydrateClientComponents=function(e,t,r){let i=u()[`~rari`].boundaryModules||new Map;function o(e){if(!e)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t,r,a]=e,s=a?{...a}:{};if(a?.children&&(s.children=o(a.children)),s[`~boundaryId`]&&delete s[`~boundaryId`],typeof t==`string`){if(t.startsWith(`$L`)){let e=i.get(t);if(e){let t=`${e.id}#${e.name||`default`}`,i=null,a=l()[`~clientComponents`][t]||l()[`~clientComponents`][e.id];return a&&(a.component?i=a.component:a.loader&&!a.loading&&(a.loading=!0,a.loadPromise=a.loader().then(e=>(a.component=e.default||e,a.registered=!0,a.loading=!1,a.component)).catch(t=>{throw a.loading=!1,a.loadPromise=void 0,console.error(`[rari] Failed to load component ${e.id}:`,t),t})),a.loadPromise&&!a.component)?n.createElement(n.Suspense,{fallback:null},n.createElement(_,{key:r,componentInfo:a,childProps:s})):i?n.createElement(i,r?{...s,key:r}:s):s.children||null}return s.children||null}return n.createElement(t,r?{...s,key:r}:s)}return null}return e.map((e,t)=>{let r=null;if(Array.isArray(e)&&e.length>=4&&e[0]===`$`){let t=e[2];(typeof t==`string`||typeof t==`number`)&&(r=String(t))}r||=`rsc-${t}-${typeof e==`string`?e:JSON.stringify(e).slice(0,20)}`;let i=o(e);return n.isValidElement(i)&&!i.key?n.createElement(n.Fragment,{key:r},i):i})}return e}try{let e=o(t);e&&(a(r).render(e),r.classList.add(`rari-boundary-hydrated`))}catch(e){console.error(`[rari] Failed to hydrate client components:`,e),console.error(`[rari] Error stack:`,e.stack)}})}function m(){let e=u()[`~rari`].pendingBoundaryHydrations;if(!(!e||e.size===0)){for(let[t,n]of e.entries())c().hydrateClientComponents&&c().hydrateClientComponents(t,n.content,n.element);e.clear()}}p();async function h(t){let n=[];for(let r of t){let t=e(r).catch(e=>{console.error(`[rari] Failed to preload component ${r}:`,e)});n.push(t)}n.length>0&&await Promise.all(n)}async function g(){let e=document.getElementById(`root`);if(!e){console.error(`[rari] Root element not found`);return}let c=document.getElementById(`__RARI_RSC_PAYLOAD__`),l=e.children.length>0,f=u()[`~rari`]?.streaming?.bufferedRows&&u()[`~rari`].streaming.bufferedRows.length>0;if(p(),l&&!c&&!f){let e=document.querySelectorAll(`[data-client-component]`);if(e.length>0){let r=new Set;e.forEach(e=>{let t=e.getAttribute(`data-client-component`);t&&r.add(t)}),await h(r),e.forEach(e=>{let r=e.getAttribute(`data-client-component`),i=e.getAttribute(`data-props`);if(r)try{let o=t(r);if(!o)return;let s=i?JSON.parse(i):{};requestAnimationFrame(()=>{try{document.contains(e)&&(e.replaceChildren(),a(e).render(n.createElement(o,s)))}catch(e){console.error(`[rari] Failed to hydrate client component ${r}:`,e)}})}catch(e){console.error(`[rari] Failed to hydrate client component ${r}:`,e)}})}return}if(l&&f&&!c&&document.querySelectorAll(`[data-boundary-id]`).length>0){u()[`~rari`].pendingBoundaryHydrations&&u()[`~rari`].pendingBoundaryHydrations.size>0&&m();return}try{let t;if(!c&&!f&&!l)try{let e=window.location.pathname+window.location.search,n=(import.meta.env.DEV?import.meta.env.RARI_SERVER_URL||`http://localhost:${import.meta.env.VITE_RSC_PORT||`3000`}`:window.location.origin)+e,r=await fetch(n,{headers:{Accept:`text/x-component`},cache:`no-store`});if(!r.ok&&r.status!==404)throw Error(`Failed to fetch RSC data: ${r.status}`);let i=r.body;t=await s(i,d())}catch(e){if(e instanceof Promise)throw e;if(console.error(`[rari] Failed to fetch initial RSC data:`,e),e instanceof Error)console.error(`[rari] Error name:`,e.name),console.error(`[rari] Error message:`,e.message),e.stack&&console.error(`[rari] Error stack:`,e.stack);else if(typeof e==`string`)console.error(`[rari] Error details:`,e);else if(e&&typeof e==`object`)try{let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=e[n];console.error(`[rari] Error details:`,JSON.stringify(t,null,2))}catch{console.error(`[rari] Error details:`,String(e))}else console.error(`[rari] Error details:`,String(e));t=null}else if(c&&c.textContent)try{let e=c.textContent,n=u()[`~rari`]?.streaming?.bufferedRows&&u()[`~rari`].streaming.bufferedRows.length>0;t=u()[`~rari`]?.streaming?.complete===void 0||n?await s(new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e));let n=e=>{let n=e;n.detail?.rscRow&&t.enqueue(new TextEncoder().encode(`\n${n.detail.rscRow}`))},r=()=>{t.close(),window.removeEventListener(`rari:html-stream-row`,n),window.removeEventListener(`rari:stream-complete`,r)};if(window.addEventListener(`rari:html-stream-row`,n),window.addEventListener(`rari:stream-complete`,r),u()[`~rari`]?.streaming?.bufferedRows){let e=[...u()[`~rari`].streaming.bufferedRows];for(let n of e)t.enqueue(new TextEncoder().encode(`\n${n}`));u()[`~rari`].streaming.bufferedRows=[]}u()[`~rari`]?.streaming?.complete&&r()}}),d()):await s(new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e)),t.close()}}),d())}catch(e){console.error(`[rari] Failed to parse embedded RSC payload:`,e),t=null}else if(f)try{t=await s(new ReadableStream({start(e){let t=t=>{let n=t;n.detail?.rscRow&&e.enqueue(new TextEncoder().encode(`${n.detail.rscRow}\n`))},n=()=>{e.close(),window.removeEventListener(`rari:html-stream-row`,t),window.removeEventListener(`rari:stream-complete`,n)};if(window.addEventListener(`rari:html-stream-row`,t),window.addEventListener(`rari:stream-complete`,n),u()[`~rari`]?.streaming?.bufferedRows){let t=[...u()[`~rari`].streaming.bufferedRows];u()[`~rari`].streaming.bufferedRows=[];for(let n of t)e.enqueue(new TextEncoder().encode(`${n}\n`))}u()[`~rari`]?.streaming?.complete&&n()}}),d())}catch(e){console.error(`[rari] Failed to process streaming RSC payload:`,e),t=null}if(!t)throw Error(`No RSC data available for hydration`);let p;p=t;let m;m=n.createElement(o,{initialPayload:{element:t}},p),m=n.createElement(r,{initialRoute:window.location.pathname,children:m}),m=n.createElement(i,{initialPathname:window.location.pathname,children:m}),a(e).render(m)}catch(t){console.error(`[rari] Error rendering app:`,t),e.innerHTML=`
5
+ function g(){f().hydrateClientComponents||(f().hydrateClientComponents=function(e,n,r){let a=m()[`~rari`].boundaryModules||new Map;function o(e){if(!e)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,n,r,s]=e,c=s?{...s}:{};if(s?.children&&(c.children=o(s.children)),c[`~boundaryId`]&&delete c[`~boundaryId`],typeof n==`string`){if(n.startsWith(`$`)&&u.test(n)){let e=d(a,n);if(e){let n=`${e.id}#${e.name||`default`}`,a=n.replace(/\\/g,`/`),o=e.id.replace(/\\/g,`/`),s=null,l=!e.name||e.name===`default`,u=p()[`~clientComponents`][a]||p()[`~clientComponents`][n]||l&&(p()[`~clientComponents`][o]||p()[`~clientComponents`][e.id]);return u&&(u.component?s=t(u,e.name):u.loader&&!u.loading&&(u.loading=!0,u.loadPromise=u.loader().then(e=>(u.component=e,u.registered=!0,u.loading=!1,e)).catch(t=>{throw u.loading=!1,u.loadPromise=void 0,console.error(`[rari] Failed to load component ${e.id}:`,t),t})),u.loadPromise&&!u.component)?i.createElement(i.Suspense,{fallback:null},i.createElement(b,{key:r,componentInfo:u,exportName:e.name,childProps:c})):s?i.createElement(s,r?{...c,key:r}:c):c.children||null}return c.children||null}return i.createElement(n,r?{...c,key:r}:c)}return null}return e.map((e,t)=>{let n=null;if(Array.isArray(e)&&e.length>=4&&e[0]===`$`){let t=e[2];(typeof t==`string`||typeof t==`number`)&&(n=String(t))}n||=`rsc-${t}-${typeof e==`string`?e:JSON.stringify(e).slice(0,20)}`;let r=o(e);return i.isValidElement(r)&&!r.key?i.createElement(i.Fragment,{key:n},r):r})}return e}try{let e=o(n);e&&(s(r).render(e),r.classList.add(`rari-boundary-hydrated`))}catch(e){console.error(`[rari] Failed to hydrate client components:`,e),console.error(`[rari] Error stack:`,e.stack)}})}function _(){let e=m()[`~rari`].pendingBoundaryHydrations;if(!(!e||e.size===0)){for(let[t,n]of e.entries())f().hydrateClientComponents&&f().hydrateClientComponents(t,n.content,n.element);e.clear()}}g();async function v(t){let n=[];for(let r of t){let t=e(r).catch(e=>{console.error(`[rari] Failed to preload component ${r}:`,e)});n.push(t)}n.length>0&&await Promise.all(n)}async function y(){let e=document.getElementById(`root`);if(!e){console.error(`[rari] Root element not found`);return}let t=document.getElementById(`__RARI_RSC_PAYLOAD__`),u=e.children.length>0,d=m()[`~rari`]?.streaming?.bufferedRows&&m()[`~rari`].streaming.bufferedRows.length>0;if(g(),u&&!t&&!d){let e=document.querySelectorAll(`[data-client-component]`);if(e.length>0){let t=new Set;e.forEach(e=>{let n=e.getAttribute(`data-client-component`);n&&t.add(n)}),await v(t),e.forEach(e=>{let t=e.getAttribute(`data-client-component`),r=e.getAttribute(`data-props`);if(t)try{let a=n(t);if(!a)return;let o=r?JSON.parse(r):{};requestAnimationFrame(()=>{try{document.contains(e)&&(e.replaceChildren(),s(e).render(i.createElement(a,o)))}catch(e){console.error(`[rari] Failed to hydrate client component ${t}:`,e)}})}catch(e){console.error(`[rari] Failed to hydrate client component ${t}:`,e)}})}return}if(u&&d&&!t&&document.querySelectorAll(`[data-boundary-id]`).length>0){m()[`~rari`].pendingBoundaryHydrations&&m()[`~rari`].pendingBoundaryHydrations.size>0&&_();return}try{let n;if(!t&&!d&&!u)try{let e=window.location.pathname+window.location.search,t=(import.meta.env.DEV?import.meta.env.RARI_SERVER_URL||`http://localhost:${import.meta.env.VITE_RSC_PORT||`3000`}`:window.location.origin)+e,r=await fetch(t,{headers:{Accept:`text/x-component`},cache:`no-store`});if(!r.ok&&r.status!==404)throw Error(`Failed to fetch RSC data: ${r.status}`);if(!r.body)throw Error(`RSC response has no body`);n=await l(r.body)}catch(e){if(e instanceof Promise)throw e;if(console.error(`[rari] Failed to fetch initial RSC data:`,e),e instanceof Error)console.error(`[rari] Error name:`,e.name),console.error(`[rari] Error message:`,e.message),e.stack&&console.error(`[rari] Error stack:`,e.stack);else if(typeof e==`string`)console.error(`[rari] Error details:`,e);else if(e&&typeof e==`object`)try{let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=e[n];console.error(`[rari] Error details:`,JSON.stringify(t,null,2))}catch{console.error(`[rari] Error details:`,String(e))}else console.error(`[rari] Error details:`,String(e));n=null}else if(t&&t.textContent)try{let e=t.textContent;await r(e);let i=m()[`~rari`]?.streaming?.bufferedRows&&m()[`~rari`].streaming.bufferedRows.length>0;n=m()[`~rari`]?.streaming?.complete===void 0||i?await l(new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e));let n=e=>{let n=e;n.detail?.rscRow&&t.enqueue(new TextEncoder().encode(`\n${n.detail.rscRow}`))},r=()=>{t.close(),window.removeEventListener(`rari:html-stream-row`,n),window.removeEventListener(`rari:stream-complete`,r)};if(window.addEventListener(`rari:html-stream-row`,n),window.addEventListener(`rari:stream-complete`,r),m()[`~rari`]?.streaming?.bufferedRows){let e=[...m()[`~rari`].streaming.bufferedRows];for(let n of e)t.enqueue(new TextEncoder().encode(`\n${n}`));m()[`~rari`].streaming.bufferedRows=[]}m()[`~rari`]?.streaming?.complete&&r()}})):await l(new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e)),t.close()}}))}catch(e){console.error(`[rari] Failed to parse embedded RSC payload:`,e),console.error(`[rari] Error stack:`,e instanceof Error?e.stack:`no stack`),n=null}else if(d)try{n=await l(new ReadableStream({start(e){let t=t=>{let n=t;n.detail?.rscRow&&e.enqueue(new TextEncoder().encode(`${n.detail.rscRow}\n`))},n=()=>{e.close(),window.removeEventListener(`rari:html-stream-row`,t),window.removeEventListener(`rari:stream-complete`,n)};if(window.addEventListener(`rari:html-stream-row`,t),window.addEventListener(`rari:stream-complete`,n),m()[`~rari`]?.streaming?.bufferedRows){let t=[...m()[`~rari`].streaming.bufferedRows];m()[`~rari`].streaming.bufferedRows=[];for(let n of t)e.enqueue(new TextEncoder().encode(`${n}\n`))}m()[`~rari`]?.streaming?.complete&&n()}}))}catch(e){console.error(`[rari] Failed to process streaming RSC payload:`,e),n=null}if(!n)throw Error(`No RSC data available for hydration`);let f;f=n;let p;p=i.createElement(c,{initialPayload:{element:n}},f),p=i.createElement(a,{initialRoute:window.location.pathname,children:p}),p=i.createElement(o,{initialPathname:window.location.pathname,children:p}),s(e).render(p)}catch(t){console.error(`[rari] Error rendering app:`,t),e.innerHTML=`
6
6
  <div style="padding: 20px; background: #fee; border: 2px solid #f00; margin: 20px;">
7
7
  <h2>Error Loading App</h2>
8
8
  <p></p>
9
9
  </div>
10
- `;let n=e.querySelector(`p`);n&&(n.textContent=t instanceof Error?t.message:String(t))}}function _({componentInfo:e,childProps:t}){if(!e.loadPromise)return null;if(n.use(e.loadPromise),e.component){let r=e.component;return n.createElement(r,t)}return null}import.meta.hot&&import.meta.hot.data.hasRendered||(g().catch(e=>{console.error(`[rari] Fatal error:`,e)}),import.meta.hot&&(import.meta.hot.data.hasRendered=!0));export{f as preloadClientComponent,g as renderApp};
10
+ `;let n=e.querySelector(`p`);n&&(n.textContent=t instanceof Error?t.message:String(t))}}function b({componentInfo:e,exportName:n,childProps:r}){if(!e.loadPromise)return null;if(i.use(e.loadPromise),e.component){let a=t(e,n);return a?i.createElement(a,r):null}return null}import.meta.hot&&import.meta.hot.data.hasRendered||(y().catch(e=>{console.error(`[rari] Fatal error:`,e)}),import.meta.hot&&(import.meta.hot.data.hasRendered=!0));export{h as preloadClientComponent,y as renderApp};
@@ -1,2 +1,2 @@
1
- import{f as e,g as t,h as n,m as r,n as i,p as a,u as o,v as s}from"../regex-constants-CmOAY1_W.mjs";import{t as c}from"../get-client-component-YrjzU6RI.mjs";import{createFromFetch as l,createFromReadableStream as u}from"./react-server-dom-rari-client.mjs";import*as d from"react";import{Suspense as f,cloneElement as p,createElement as m,isValidElement as h,use as g,useEffect as _,useState as v}from"react";import*as y from"react-dom/client";function b(){return import.meta.env?.RARI_SERVER_URL?import.meta.env.RARI_SERVER_URL:typeof window<`u`?window.location.origin:`http://localhost:3000`}if(globalThis[`~rari`]===void 0&&(globalThis[`~rari`]={}),globalThis[`~rari`].isDevelopment=process.env.NODE_ENV!==`production`,globalThis[`~clientComponents`]===void 0&&(globalThis[`~clientComponents`]={}),globalThis[`~clientComponentNames`]===void 0&&(globalThis[`~clientComponentNames`]={}),globalThis[`~clientComponentPaths`]===void 0&&(globalThis[`~clientComponentPaths`]={}),typeof window<`u`){window[`~rari`]||(window[`~rari`]=globalThis[`~rari`]),window[`~rari`].streaming||(window[`~rari`].streaming={bufferedRows:[],bufferedEvents:[]}),window[`~rari`].streaming.bufferedEvents||(window[`~rari`].streaming.bufferedEvents=[]),window[`~rari`].boundaryModules||(window[`~rari`].boundaryModules=new Map),window[`~rari`].pendingBoundaryHydrations||(window[`~rari`].pendingBoundaryHydrations=new Map),globalThis[`~rari`].processBoundaryUpdate=function(o,s,c){let l=document.querySelector(`[data-boundary-id="${o}"]`);if(l)try{let u=s.indexOf(`:`);if(u===-1){console.warn(`[rari] Invalid RSC row format (no colon):`,s);return}let d=s.substring(0,u),f=s.substring(u+1);if(f.startsWith(`I[`)){try{let e=JSON.parse(f.substring(1));if(Array.isArray(e)&&e.length>=3){let[t,n,r]=e,i=`$L${d}`;window[`~rari`].boundaryModules?.set(i,{id:t,chunks:Array.isArray(n)?n:[n],name:r||`default`})}}catch(e){console.error(`[rari] Failed to parse import row:`,f,e)}return}let p;try{p=JSON.parse(f)}catch(e){console.error(`[rari] Failed to parse RSC content:`,f,e);return}function m(e){if(!e)return!1;if(typeof e==`string`)return e.startsWith(`$L`);if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t]=e;if(typeof t==`string`&&t.startsWith(`$L`))return!0;let n=e[3];if(n&&n.children)return m(n.children)}return e.some(e=>m(e))}return!1}if(m(p)){if(window[`~rari`].pendingBoundaryHydrations?.set(o,{content:p,element:l,rowId:c}),globalThis[`~rari`].hydrateClientComponents){let e=globalThis[`~rari`].hydrateClientComponents;e(o,p,l)}return}function h(o){let s=i=>i.replace(e,`&amp;`).replace(n,`&lt;`).replace(r,`&gt;`).replace(t,`&quot;`).replace(a,`&#39;`),c=new Set(`div.span.p.ul.ol.li.a.img.section.article.header.footer.nav.main.aside.strong.em.b.i.button.input.label.form.select.option.textarea.h1.h2.h3.h4.h5.h6.table.thead.tbody.tr.td.th.code.pre.blockquote.hr.br.small.mark.del.ins.sub.sup.abbr.time.figure.figcaption.details.summary.dialog.menu.menuitem.canvas.svg.path.circle.rect.line.polygon.polyline.ellipse.text.g.defs.use.symbol.clippath.mask.pattern.lineargradient.radialgradient.stop.image.video.audio.source.track.picture.dl.dt.dd.fieldset.legend`.split(`.`));if(!o)return``;if(typeof o==`string`||typeof o==`number`)return s(String(o));if(Array.isArray(o)){if(o.length>=4&&o[0]===`$`){let[,e,,t]=o,n=typeof e==`string`&&c.has(e.toLowerCase())?e.toLowerCase():`div`,r=null,a=``,l=``;if(t){for(let[e,n]of Object.entries(t))if(e===`dangerouslySetInnerHTML`&&n&&typeof n==`object`&&`__html`in n)r=n.__html;else if(e!==`children`&&e!==`~boundaryId`){let t=e===`className`?`class`:e;if(e===`style`&&typeof n==`object`&&n){let e=Object.entries(n).map(([e,t])=>`${e.replace(i,`$1-$2`).toLowerCase()}:${String(t)}`).join(`;`);l+=` style="${s(e)}"`}else typeof n==`string`||typeof n==`number`?l+=` ${t}="${s(String(n))}"`:typeof n==`boolean`&&n&&(l+=` ${t}`)}r===null&&t.children&&(a=h(t.children))}return`<${n}${l}>${r===null?a:r}</${n}>`}return o.map(h).join(``)}return``}let g=h(p);if(g){let e=document.contains(l);e&&(l.innerHTML=g,l.classList.add(`rari-boundary-resolved`)),window.dispatchEvent(new CustomEvent(`rari:boundary-resolved`,{detail:{boundaryId:o,rscRow:s,rowId:c,element:l,wasAttached:e}}))}}catch(e){console.error(`[rari] Error processing boundary update:`,e)}};let o=window,s=globalThis;o[`~rari`].streaming?.bufferedEvents&&o[`~rari`].streaming.bufferedEvents.length>0&&(o[`~rari`].streaming.bufferedEvents.forEach(e=>{let{boundaryId:t,rscRow:n,rowId:r}=e;s[`~rari`].processBoundaryUpdate?.(t,n,r)}),o[`~rari`].streaming.bufferedEvents=[]),window.addEventListener(`rari:boundary-update`,e=>{let{boundaryId:t,rscRow:n,rowId:r}=e.detail;s[`~rari`].processBoundaryUpdate&&s[`~rari`].processBoundaryUpdate(t,n,r)})}function x(e,t,n){let r=n===`default`?e.name||t.split(`/`).pop()?.replace(o,``)||`DefaultComponent`:n,i=r,a={id:i,path:t,type:`client`,component:e,registered:!0};globalThis[`~clientComponents`][i]=a,globalThis[`~clientComponents`][t]=a,globalThis[`~clientComponentPaths`][t]=i,globalThis[`~clientComponentNames`][r]=i,e&&(e[`~isClientComponent`]=!0,e[`~clientComponentId`]=i),typeof window<`u`&&fetch(`/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:i,file_path:t,export_name:n})}).catch(e=>{console.error(`[rari] Failed to register client component with server:`,e)})}function S(e){return c(e)}function C(){let e={};for(let[t,n]of Object.entries(globalThis[`~clientComponents`]))e[t]={id:t,chunks:[n.path],name:t,async:!1,default:n.component};return e}let w=l,T=u,E=null;async function D(){return E||(E=(async()=>{try{return w=l,T=u,typeof T!=`function`&&(T=null),typeof w!=`function`&&(w=null),y}catch(e){return console.error(`Failed to load react-dom/client RSC functions:`,e),w=null,T=null,null}})(),E)}const O=new Map,k=new class{componentCache;moduleCache;inflightRequests;config;constructor(){this.componentCache=new Map,this.moduleCache=new Map,this.inflightRequests=new Map,this.config={maxRetries:5,retryDelay:500,timeout:1e4}}configure(e){this.config={...this.config,...e}}clearCache(){this.componentCache.clear(),this.moduleCache.clear(),O.clear()}async fetchServerComponent(e,t={}){let n=typeof window<`u`&&window[`~rari`]?.hmr?.refreshCounters?.[e]||0,r=`${e}:${JSON.stringify(t)}:hmr:${n}`;if(this.componentCache.has(r))return this.componentCache.get(r);if(this.inflightRequests.has(r))return this.inflightRequests.get(r);let i=this.fetchServerComponentStream(e,t);this.inflightRequests.set(r,i);try{let e=await i;return this.componentCache.set(r,e),e}finally{this.inflightRequests.delete(r)}}async fetchServerComponentStream(e,t={}){await D();let n=(()=>{let e=[`/_rari/stream`];try{if(typeof window<`u`&&(window.location.hostname===`localhost`||window.location.hostname===`127.0.0.1`)){let t=b();t&&e.push(`${t}/_rari/stream`)}}catch{}return e})(),r=null,i=null,a=async()=>{for(let r of n)try{let n=await this.fetchWithTimeout(r,{method:`POST`,headers:{"Content-Type":`application/json`,...this.buildRequestHeaders()},body:JSON.stringify({component_id:e,props:t})});if(n.ok)return n;i=Error(`HTTP ${n.status}: ${await n.text()}`)}catch(e){i=e}return null};if(r=await a(),r||=(await new Promise(e=>setTimeout(e,this.config.retryDelay)),await a()),!r)throw i||Error(`Failed to reach stream endpoint`);if(!r.ok){let e=await r.text();throw Error(`Server responded with ${r.status}: ${e}`)}let o=r.body;if(!o)throw Error(`No ReadableStream from stream response`);let s=o.getReader(),c=new TextDecoder,l=new Map,u=new Map,d=e=>{if(!m)return console.error(`React not available for RSC conversion`),null;if(!e)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t,n,r]=e;if(t===`react.suspense`||t===`suspense`)return m(f,{fallback:d(r?.fallback)||null},r?.children?d(r.children):null);let i=r?{...r}:{};if(r?.children){let e=d(r.children);Array.isArray(e)?i.children=e.map((e,t)=>h(e)&&e.key==null?p(e,{key:t}):e):i.children=e}if(typeof t==`string`){if(t.startsWith(`$L`)){let e=l.get(t);if(e){let t=S(`${e.id}#${e.name||`default`}`);if(t)return m(t,n?{...i,key:n}:i)}return i&&i.children?i.children:null}if(t.includes(`.tsx#`)||t.includes(`.jsx#`)){let e=S(t);return e?m(e,n?{...i,key:n}:i):(console.error(`Failed to resolve client component:`,t),null)}else return i&&Object.hasOwn(i,`~boundaryId`)&&(i={...i},delete i[`~boundaryId`]),m(t,n?{...i,key:n}:i)}else console.error(`Unknown RSC element type:`,t)}return e.map(e=>d(e))}return typeof e==`object`?(console.error(`Unexpected object in RSC conversion:`,e),null):e},g=null,y=new Map,x=``,C=null,w=async()=>{try{for(;;){let{value:e,done:t}=await s.read();if(t)break;let n=c.decode(e,{stream:!0});x+=n;let r=x.split(`
2
- `),i=r.slice(0,-1);x=r.at(-1)||``;for(let e of i)if(e.trim())try{let t=e.indexOf(`:`);if(t===-1)continue;let n=e.substring(0,t),r=e.substring(t+1);if(r.startsWith(`I[`))try{let e=JSON.parse(r.substring(1));if(Array.isArray(e)&&e.length>=3){let[t,r,i]=e;l.set(`$L${n}`,{id:t,chunks:Array.isArray(r)?r:[r],name:i||`default`})}}catch(e){console.error(`Failed to parse import row:`,r,e)}else if(r.startsWith(`E{`))try{let e=JSON.parse(r.substring(1));console.error(`RSC stream error:`,e)}catch(e){console.error(`Failed to parse error row:`,r,e)}else if(r.startsWith(`Symbol.for(`))continue;else if(r.startsWith(`[`)){let e=JSON.parse(r);if(Array.isArray(e)&&e.length>=4){let[t,r,i]=e,a=i?.[`~boundaryId`];if(t===`$`&&(r===`react.suspense`||r===`suspense`)&&i&&a&&u.set(`$L${n}`,a),t===`$`&&i&&Object.hasOwn(i,`children`)&&typeof r==`string`&&r.startsWith(`$L`)){let e=u.get(r)||null;if(e){let t=d(i.children);y.set(e,t),C&&C.updateBoundary(e,t);continue}}}if(!g){let t=!0;if(Array.isArray(e)&&e.length>=4&&e[0]===`$`){let n=e[1],r=e[3],i=r?.[`~boundaryId`];typeof n==`string`&&(n===`react.suspense`||n===`suspense`)&&r&&i&&(t=!1)}t&&(g=d(e),C&&typeof C.updateRoot==`function`&&C.updateRoot())}}}catch(t){console.error(`Failed to parse stream line:`,e,t)}}}catch(e){console.error(`Error processing stream:`,e)}},T=()=>{let[,e]=v(0);_(()=>(C={updateBoundary:(t,n)=>{y.set(t,n),e(e=>e+1)},updateRoot:()=>{e(e=>e+1)}},()=>{C=null}),[]);let t=e=>{if(!e)return null;if(h(e)){let n=e.props,r=n?.[`~boundaryId`];if(n&&r){let e=y.get(r);if(e)return e}if(n&&n.children){let r=t(n.children);if(r!==n.children){let t={...n};return e.key!==null&&e.key!==void 0&&(t.key=e.key),m(e.type,t,r)}}return e}return Array.isArray(e)?e.map(e=>t(e)):e};return t(g)};w();let E=Promise.resolve(m(T));return{"~isRscResponse":!0,"~rscPromise":E,readRoot(){return E}}}buildRequestHeaders(){return{Accept:`text/x-component`,"Cache-Control":`no-cache, no-transform`}}async fetchWithTimeout(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{let i=await fetch(e,{...t,signal:n.signal});return clearTimeout(r),i}catch(e){throw clearTimeout(r),e}}async processRscResponse(e){if(await D(),w)try{let t=w(Promise.resolve(e));return{"~isRscResponse":!0,"~rscPromise":t,readRoot(){return t}}}catch{throw Error(`React Server DOM client not available`)}else throw Error(`React Server DOM client not available`)}async processRscResponseManually(e){let t=await e.text();return this.parseRscResponse(t)}parseRscResponse(e){let t=e.trim().split(s),n=new Map,r=new Map,i=[];for(let e of t){let t=e.indexOf(`:`);if(t===-1)continue;let a=e.substring(0,t),o=e.substring(t+1);if(o)try{if(o.startsWith(`I[`)){let e=o.substring(1),t=JSON.parse(e);if(Array.isArray(t)&&t.length>=3){let[e,r,i]=t;n.set(`$L${a}`,{id:e,chunks:Array.isArray(r)?r:[r],name:i||`default`})}}else if(o.startsWith(`E{`)){let e=o.substring(1),t=JSON.parse(e);i.push(t),console.error(`RSC: Server error`,t)}else if(o.startsWith(`[`)){let e=JSON.parse(o);r.set(a,e)}else if(o.startsWith(`Symbol.for(`))continue;else console.error(`Unknown RSC row format:`,e)}catch(t){console.error(`Failed to parse RSC row:`,e,t)}}if(i.length>0)throw Error(`RSC Server Error: ${i.map(e=>e.message||e).join(`, `)}`);let a=null,o=r.keys().toSorted((e,t)=>Number.parseInt(e)-Number.parseInt(t));for(let e of o){let t=r.get(e);if(Array.isArray(t)&&t.length>=2&&t[0]===`$`){let[,e,,n]=t,r=n?.[`~boundaryId`];if(e===`react.suspense`&&n&&r)continue;a=t;break}}return a?this.reconstructElementFromRscData(a,n):(console.error(`No valid root element found in RSC payload`,{elements:r,modules:n}),null)}reconstructElementFromRscData(e,t){if(e==null)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))if(e.length>=4&&e[0]===`$`){let[,n,r,i]=e,a=n;if(typeof n==`string`&&n.includes(`#`))a=S(n)||(({children:e,...t})=>m(`div`,{...t,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},m(`small`,{style:{color:`#c00`}},`Missing Client Component: ${n}`),e));else if(typeof n==`string`&&n.startsWith(`$L`)&&t.has(n)){let e=t.get(n);e&&(a=S(`${e.id}#${e.name}`)||(({children:t,...r})=>m(`div`,{...r,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},m(`small`,{style:{color:`#c00`}},`Missing Client Component: ${e.name} (${e.id})`),t)))}let o=i?this.processPropsRecursively(i,t):{};return m(a,{key:r,...o})}else return e.map(e=>this.reconstructElementFromRscData(e,t));return typeof e==`object`?null:e}processPropsRecursively(e,t){if(!e||typeof e!=`object`)return e;let n={};for(let[r,i]of Object.entries(e))if(r===`children`)if(Array.isArray(i))if(i.length>=2&&i[0]===`$`)n[r]=this.reconstructElementFromRscData(i,t);else{let e=i.map(e=>this.reconstructElementFromRscData(e,t)).filter(e=>e!=null);e.length===0?n[r]=null:e.length===1?n[r]=e[0]:n[r]=e}else n[r]=this.reconstructElementFromRscData(i,t);else r===`dangerouslySetInnerHTML`?n[r]=i:n[r]=this.reconstructElementFromRscData(i,t);return n}};function A({error:e,details:t}){return m(`div`,{className:`rsc-error`,style:{padding:`16px`,backgroundColor:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`,margin:`8px 0`,fontFamily:`monospace`}},m(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`}},`RSC Error`),m(`p`,{style:{margin:`0 0 8px 0`}},e),t&&m(`details`,{style:{marginTop:`8px`}},m(`summary`,{style:{cursor:`pointer`}},`Error Details`),m(`pre`,{style:{fontSize:`12px`,overflow:`auto`,backgroundColor:`#f5f5f5`,padding:`8px`}},JSON.stringify(t,null,2))))}function j({rootPromise:e}){return g(e)}function M({componentId:e,props:t,fallback:n}){let r=typeof window<`u`&&window[`~rari`]?.hmr?.refreshCounters?.[e]||0,i=`${e}:${JSON.stringify(t)}:hmr:${r}`;if(!O.has(i)){let n=k.fetchServerComponent(e,t).catch(e=>{throw O.delete(i),e});O.set(i,n)}let a=g(O.get(i));if(a?.[`~isRscResponse`]){let e=a.readRoot();return m(f,{fallback:n??null},m(j,{rootPromise:e}))}return a??null}var N=class extends d.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidUpdate(e){e.mountKey!==this.props.mountKey&&this.state.hasError&&this.setState({hasError:!1,error:null})}componentDidCatch(e,t){console.error(`[rari] ServerComponentErrorBoundary: Error in component ${this.props.componentId}:`,e,t)}render(){return this.state.hasError?m(A,{error:this.state.error?.message||`Unknown error`,details:{componentId:this.props.componentId}}):this.props.children}};function P(e){let t=0;if(typeof window<`u`){let n=window;n[`~rari`].hmr||(n[`~rari`].hmr={refreshCounters:{}}),n[`~rari`].hmr.refreshCounters[e]===void 0&&(n[`~rari`].hmr.refreshCounters[e]=0),t=n[`~rari`].hmr.refreshCounters[e]}let n=n=>{let[r,i]=v(t);return _(()=>{let t=t=>{let n=t.detail;if(n&&n.filePath&&I(n.filePath)&&(k.clearCache(),typeof window<`u`)){let t=window;t[`~rari`].hmr||(t[`~rari`].hmr={refreshCounters:{}}),t[`~rari`].hmr.refreshCounters[e]=(t[`~rari`].hmr.refreshCounters[e]||0)+1,i(t[`~rari`].hmr.refreshCounters[e])}};return typeof window<`u`&&window.addEventListener(`rari:rsc-invalidate`,t),()=>{typeof window<`u`&&window.removeEventListener(`rari:rsc-invalidate`,t)}},[]),m(f,{fallback:null},m(N,{componentId:e,mountKey:r},m(M,{key:`${e}-${r}`,componentId:e,props:n,fallback:null})))};return n.displayName=`ServerComponent(${e})`,function(e){return m(n,e)}}function F(e,t){return k.fetchServerComponent(e,t)}function I(e){if(!e)return!1;try{return typeof globalThis<`u`&&globalThis[`~rari`].serverComponents?globalThis[`~rari`].serverComponents.has(e):!1}catch(e){return console.error(`Error checking if file is server component:`,e),!1}}if(import.meta.hot){let e=!1,t=[],n=new Map;function r(r,i){n.set(r,i),import.meta.hot.on(r,async n=>{if(!e){t.push({event:r,data:n});return}try{await i(n)}catch(e){console.error(`[rari] HMR: Error in handler for '${r}':`,e)}})}r(`rari:register-server-component`,e=>{e?.filePath&&typeof globalThis<`u`&&(globalThis[`~rari`].serverComponents=globalThis[`~rari`].serverComponents||new Set,globalThis[`~rari`].serverComponents.add(e.filePath))}),r(`rari:server-components-registry`,e=>{e?.serverComponents&&Array.isArray(e.serverComponents)&&typeof globalThis<`u`&&(globalThis[`~rari`].serverComponents=globalThis[`~rari`].serverComponents||new Set,e.serverComponents.forEach(e=>{globalThis[`~rari`].serverComponents?.add(e)}))}),r(`vite:beforeFullReload`,async e=>{e?.path&&I(e.path)&&await u({filePath:e.path,forceReload:!0})}),r(`rari:server-component-updated`,async e=>{let t=e?.id||e?.componentId,n=e?.t||e?.timestamp;if(t){if(typeof window<`u`){let r=new CustomEvent(`rari:rsc-invalidate`,{detail:{componentId:t,filePath:e.filePath||e.file,type:`server-component`,timestamp:n}});window.dispatchEvent(r)}}else e?.path&&I(e.path)&&await u({filePath:e.path,forceReload:!1})}),r(`rari:app-router-updated`,async e=>{try{if(!e||!e.routePath&&(!e.affectedRoutes||e.affectedRoutes.length===0))return;await i(e)}catch(e){console.error(`[rari] HMR: App router update failed:`,e)}}),r(`rari:server-action-updated`,async e=>{if(e?.filePath&&(k.clearCache(),typeof window<`u`)){let t=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:e.filePath,type:`server-action`}});window.dispatchEvent(t)}});async function i(e){let t=e.fileType,n=e.filePath,r=e.routePath,i=e.affectedRoutes,o=e.manifestUpdated,u=e.metadata;e.metadataChanged&&u&&a(u);try{let e=`${b()}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`register`,file_path:n})});if(!t.ok){let e=await t.text(),n=`Component reload failed with status ${t.status}: ${e}`;throw console.error(`[rari] HMR:`,n),Error(n)}let r=await t.json();if(typeof r!=`object`||!r){let e=`Invalid reload response: null or non-object`;throw console.error(`[rari] HMR:`,e,r),Error(e)}if(r.success!==!0&&r.reloaded!==!0){let e=`Component reload unsuccessful: ${r.error||`unknown error`}`;throw console.error(`[rari] HMR:`,e,r),Error(e)}}catch(e){console.error(`[rari] HMR: Failed to reload component:`,e);return}let d=[r];switch(t){case`page`:d=[r];break;case`layout`:case`loading`:case`error`:case`not-found`:d=i;break;default:break}await s({routes:d,fileType:t,filePath:n,componentId:r}),o&&await l(),await c({routePath:r,affectedRoutes:i})}function a(e){if(!(typeof document>`u`)&&(e.title&&(document.title=e.title),e.description)){let t=document.querySelector(`meta[name="description"]`);t||(t=document.createElement(`meta`),t.setAttribute(`name`,`description`),document.head.appendChild(t)),t.setAttribute(`content`,e.description)}}function o(e){if(!e||e.length===0){k.clearCache();return}let t=[];for(let n of k.componentCache.keys())for(let r of e){if(n.includes(`route:${r}:`)||n.startsWith(`${r}:`)){t.push(n);break}if(r!==`/`&&n.includes(`route:${r}/`)){t.push(n);break}}for(let e of t)k.componentCache.delete(e),O.delete(e);let n=[];for(let t of O.keys())for(let r of e){if(t.includes(`route:${r}:`)||t.startsWith(`${r}:`)){n.push(t);break}if(r!==`/`&&t.includes(`route:${r}/`)){n.push(t);break}}for(let e of n)O.delete(e)}async function s(e){let t=e.routes||[],n=e.fileType,r=e.filePath,i=e.componentId;if(i||r)try{let e=`${b()}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate`,componentId:i||r,filePath:r})}),n=await t.text();t.ok||console.error(`[rari] HMR: Server cache invalidation failed:`,t.status,n)}catch(e){console.error(`[rari] HMR: Failed to call server invalidation endpoint:`,e)}if(o(t),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{routes:t,fileType:n}});window.dispatchEvent(e)}}async function c(e){let t=e.routePath,n=e.affectedRoutes||[t];if(!(typeof window>`u`))try{let e=window.location.pathname,r=new CustomEvent(`rari:app-router-rerender`,{detail:{routePath:t,affectedRoutes:n,currentPath:e,preserveParams:!0}});window.dispatchEvent(r)}catch(e){throw console.error(`[rari] HMR: Failed to trigger re-render:`,e),e}}async function l(){typeof window<`u`&&window[`~rari`]?.routeInfoCache&&window[`~rari`].routeInfoCache.clear()}async function u(e){let t=e?.filePath||e;if(k.clearCache(),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:t}});window.dispatchEvent(e)}}t.length>0?(async()=>{try{for(;t.length>0;){let e=[...t];t.length=0;for(let{event:t,data:r}of e){let e=n.get(t);if(e)try{await e(r)}catch(e){console.error(`[rari] HMR: Error replaying buffered event '${t}':`,e)}}}}catch(e){console.error(`[rari] HMR: Error during event replay:`,e)}finally{e=!0}})():e=!0}var L=class{overlay;currentError;escapeKeyHandler;constructor(){this.overlay=null,this.currentError=null,this.escapeKeyHandler=null}show(e){this.currentError=e,this.overlay?this.updateOverlay(e):this.createOverlay(e)}hide(){this.overlay&&(this.overlay.remove(),this.overlay=null,this.currentError=null),this.escapeKeyHandler&&=(document.removeEventListener(`keydown`,this.escapeKeyHandler),null)}isVisible(){return this.overlay!==null}createOverlay(e){this.overlay=document.createElement(`div`),this.overlay.id=`rari-hmr-error-overlay`,this.updateOverlay(e),document.body.appendChild(this.overlay),this.escapeKeyHandler=e=>{e.key===`Escape`&&this.hide()},document.addEventListener(`keydown`,this.escapeKeyHandler)}updateOverlay(e){if(!this.overlay)return;this.overlay.replaceChildren();let t=document.createElement(`div`);t.style.cssText=`position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.85); z-index: 999999; display: flex; align-items: center; justify-content: center; padding: 2rem; backdrop-filter: blur(4px);`;let n=document.createElement(`div`);n.style.cssText=`background: #1e1e1e; color: #e0e0e0; border-radius: 0.5rem; padding: 2rem; max-width: 50rem; width: 100%; max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.4); border: 1px solid #ef4444;`;let r=document.createElement(`div`);r.style.cssText=`display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem;`;let i=document.createElement(`div`);i.style.cssText=`display: flex; align-items: center; gap: 0.75rem;`;let a=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);a.style.cssText=`width: 2rem; height: 2rem; color: #ef4444;`,a.setAttribute(`fill`,`none`),a.setAttribute(`stroke`,`currentColor`),a.setAttribute(`viewBox`,`0 0 24 24`);let o=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);o.setAttribute(`stroke-linecap`,`round`),o.setAttribute(`stroke-linejoin`,`round`),o.setAttribute(`stroke-width`,`2`),o.setAttribute(`d`,`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z`),a.appendChild(o);let s=document.createElement(`h1`);s.style.cssText=`margin: 0; font-size: 1.5rem; font-weight: 700; color: #ef4444;`,s.textContent=`Build Error`,i.appendChild(a),i.appendChild(s);let c=document.createElement(`button`);if(c.style.cssText=`background: transparent; border: none; color: #9ca3af; cursor: pointer; padding: 0.5rem; border-radius: 0.25rem; transition: all 0.2s; font-size: 1.5rem; line-height: 1; width: 2rem; height: 2rem; display: flex; align-items: center; justify-content: center;`,c.textContent=`×`,c.setAttribute(`aria-label`,`Close overlay`),c.onclick=()=>this.hide(),c.onmouseover=()=>{c.style.background=`rgba(255,255,255,0.1)`,c.style.color=`#e0e0e0`},c.onmouseout=()=>{c.style.background=`transparent`,c.style.color=`#9ca3af`},c.onfocus=()=>{c.style.background=`rgba(255,255,255,0.1)`,c.style.color=`#e0e0e0`},c.onblur=()=>{c.style.background=`transparent`,c.style.color=`#9ca3af`},r.appendChild(i),r.appendChild(c),n.appendChild(r),e.filePath){let t=document.createElement(`div`);t.style.cssText=`margin-bottom: 1rem; padding: 0.75rem; background: rgba(0, 0, 0, 0.2); border-radius: 0.375rem; font-family: monospace; font-size: 0.875rem;`;let r=document.createElement(`strong`);r.textContent=`File: `,t.appendChild(r),t.appendChild(document.createTextNode(e.filePath)),n.appendChild(t)}let l=document.createElement(`div`);l.style.cssText=`margin-bottom: 1.5rem;`;let u=document.createElement(`h2`);u.style.cssText=`margin: 0 0 0.75rem 0; font-size: 1rem; font-weight: 600; color: #fca5a5;`,u.textContent=`Error Message:`;let d=document.createElement(`pre`);if(d.style.cssText=`margin: 0; padding: 1rem; background: rgba(239, 68, 68, 0.1); border-left: 4px solid #ef4444; border-radius: 0.375rem; overflow-x: auto; font-family: monospace; font-size: 0.875rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word; color: #fca5a5;`,d.textContent=e.message??`An error occurred`,l.appendChild(u),l.appendChild(d),n.appendChild(l),e.stack){let t=document.createElement(`details`);t.style.cssText=`margin-top: 1rem; cursor: pointer;`;let r=document.createElement(`summary`);r.style.cssText=`font-weight: 600; margin-bottom: 0.5rem; user-select: none;`,r.textContent=`Stack Trace`;let i=document.createElement(`pre`);i.style.cssText=`margin: 0; padding: 0.75rem; background: rgba(0, 0, 0, 0.2); border-radius: 0.375rem; overflow-x: auto; font-size: 0.875rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word;`,i.textContent=e.stack,t.appendChild(r),t.appendChild(i),n.appendChild(t)}let f=document.createElement(`div`);f.style.cssText=`margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #374151; display: flex; gap: 0.75rem; align-items: center;`;let p=document.createElement(`button`);p.style.cssText=`padding: 0.625rem 1.25rem; background: #ef4444; color: white; border: none; border-radius: 0.375rem; cursor: pointer; font-weight: 600; font-size: 0.875rem; transition: all 0.2s;`,p.textContent=`Reload Page`,p.onclick=()=>window.location.reload(),p.onmouseover=()=>{p.style.background=`#dc2626`},p.onmouseout=()=>{p.style.background=`#ef4444`},p.onfocus=()=>{p.style.background=`#dc2626`},p.onblur=()=>{p.style.background=`#ef4444`};let m=document.createElement(`button`);m.style.cssText=`padding: 0.625rem 1.25rem; background: #374151; color: #e0e0e0; border: none; border-radius: 0.375rem; cursor: pointer; font-weight: 600; font-size: 0.875rem; transition: all 0.2s;`,m.textContent=`Dismiss`,m.onclick=()=>this.hide(),m.onmouseover=()=>{m.style.background=`#4b5563`},m.onmouseout=()=>{m.style.background=`#374151`},m.onfocus=()=>{m.style.background=`#4b5563`},m.onblur=()=>{m.style.background=`#374151`};let h=document.createElement(`span`);h.style.cssText=`margin-left: auto; font-size: 0.75rem; color: #9ca3af;`;let g=new Date(e.timestamp);h.textContent=Number.isNaN(g.valueOf())?``:g.toLocaleTimeString(),f.appendChild(p),f.appendChild(m),f.appendChild(h),n.appendChild(f),t.appendChild(n),this.overlay.appendChild(t)}};let R=null;function z(){return R||=new L,R}if(import.meta.hot){let e=z();import.meta.hot.on(`rari:hmr-error`,t=>{let n=t.msg||t.message,r=t.file||t.filePath,i=t.t||t.timestamp,a=t.count||t.errorCount,o=t.max||t.maxErrors;console.error(`[rari] HMR: Build error:`,n),r&&console.error(`[rari] HMR: File:`,r),t.stack&&console.error(`[rari] HMR: Stack:`,t.stack),e.show({message:n,stack:t.stack,filePath:r,timestamp:i}),a&&o&&(a>=o?console.error(`[rari] HMR: Maximum error count (${o}) reached. Consider restarting the dev server if issues persist.`):a>=o-2&&console.warn(`[rari] HMR: Error count: ${a}/${o}. Approaching maximum error threshold.`))}),import.meta.hot.on(`rari:hmr-error-cleared`,()=>{e.hide()}),import.meta.hot.on(`vite:error`,t=>{e.show({message:t.err?.message||`Unknown Vite error`,stack:t.err?.stack,filePath:t.err?.file,timestamp:Date.now()})})}export{A as RscErrorComponent,C as createClientModuleMap,P as createServerComponentWrapper,F as fetchServerComponent,S as getClientComponent,x as registerClientComponent,k as rscClient};
1
+ import{f as e,g as t,h as n,m as r,n as i,p as a,u as o,v as s}from"../regex-constants-CmOAY1_W.mjs";import{t as c}from"../get-client-component-BjjGTgmG.mjs";import{createFromFetch as l,createFromReadableStream as u}from"./vendor/react-flight-client/index.mjs";import*as d from"react";import{Suspense as f,cloneElement as p,createElement as m,isValidElement as h,use as g,useEffect as _,useState as v}from"react";import*as y from"react-dom/client";function b(){return import.meta.env?.RARI_SERVER_URL?import.meta.env.RARI_SERVER_URL:typeof window<`u`?window.location.origin:`http://localhost:3000`}globalThis[`~rari`]===void 0&&(globalThis[`~rari`]={}),globalThis[`~rari`].isDevelopment=process.env.NODE_ENV!==`production`,globalThis[`~clientComponents`]===void 0&&(globalThis[`~clientComponents`]={}),globalThis[`~clientComponentNames`]===void 0&&(globalThis[`~clientComponentNames`]={}),globalThis[`~clientComponentPaths`]===void 0&&(globalThis[`~clientComponentPaths`]={}),typeof window<`u`&&(window[`~rari`]||(window[`~rari`]=globalThis[`~rari`]),window[`~rari`].streaming||(window[`~rari`].streaming={bufferedRows:[],bufferedEvents:[]}),window[`~rari`].streaming.bufferedEvents||(window[`~rari`].streaming.bufferedEvents=[]),window[`~rari`].boundaryModules||(window[`~rari`].boundaryModules=new Map),window[`~rari`].pendingBoundaryHydrations||(window[`~rari`].pendingBoundaryHydrations=new Map));function x(e){if(!e.startsWith(`I{`))return null;try{let t=JSON.parse(e.substring(1));if(typeof t==`object`&&t&&!Array.isArray(t)){if(typeof t.id!=`string`)return console.error(`[rari] Invalid import data: id must be a string:`,t),null;let e;if(typeof t.chunks==`string`)e=[t.chunks];else if(Array.isArray(t.chunks))e=t.chunks.filter(e=>typeof e==`string`);else return console.error(`[rari] Invalid import data: chunks must be a string or array:`,t),null;return e.length===0?(console.error(`[rari] Invalid import data: chunks array is empty:`,t),null):{id:t.id,chunks:e,name:t.name||`default`}}console.error(`[rari] Invalid import data format, expected object:`,t)}catch(t){console.error(`[rari] Failed to parse import row:`,e,t)}return null}if(typeof window<`u`){globalThis[`~rari`].processBoundaryUpdate=function(o,s,c){let l=document.querySelector(`[data-boundary-id="${o}"]`);if(l)try{let u=s.indexOf(`:`);if(u===-1){console.warn(`[rari] Invalid RSC row format (no colon):`,s);return}let d=s.substring(0,u),f=s.substring(u+1),p=x(f);if(p){let e=`$L${d}`;window[`~rari`].boundaryModules?.set(e,p);return}let m;try{m=JSON.parse(f)}catch(e){console.error(`[rari] Failed to parse RSC content:`,f,e);return}function h(e){if(!e)return!1;if(typeof e==`string`)return e.startsWith(`$L`);if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t]=e;if(typeof t==`string`&&t.startsWith(`$L`))return!0;let n=e[3];if(n&&n.children)return h(n.children)}return e.some(e=>h(e))}return!1}if(h(m)){if(window[`~rari`].pendingBoundaryHydrations?.set(o,{content:m,element:l,rowId:c}),globalThis[`~rari`].hydrateClientComponents){let e=globalThis[`~rari`].hydrateClientComponents;e(o,m,l)}return}function g(o){let s=i=>i.replace(e,`&amp;`).replace(n,`&lt;`).replace(r,`&gt;`).replace(t,`&quot;`).replace(a,`&#39;`),c=new Set(`div.span.p.ul.ol.li.a.img.section.article.header.footer.nav.main.aside.strong.em.b.i.button.input.label.form.select.option.textarea.h1.h2.h3.h4.h5.h6.table.thead.tbody.tr.td.th.code.pre.blockquote.hr.br.small.mark.del.ins.sub.sup.abbr.time.figure.figcaption.details.summary.dialog.menu.menuitem.canvas.svg.path.circle.rect.line.polygon.polyline.ellipse.text.g.defs.use.symbol.clippath.mask.pattern.lineargradient.radialgradient.stop.image.video.audio.source.track.picture.dl.dt.dd.fieldset.legend`.split(`.`));if(!o)return``;if(typeof o==`string`||typeof o==`number`)return s(String(o));if(Array.isArray(o)){if(o.length>=4&&o[0]===`$`){let[,e,,t]=o,n=typeof e==`string`&&c.has(e.toLowerCase())?e.toLowerCase():`div`,r=null,a=``,l=``;if(t){for(let[e,n]of Object.entries(t))if(e===`dangerouslySetInnerHTML`&&n&&typeof n==`object`&&`__html`in n)r=n.__html;else if(e!==`children`&&e!==`~boundaryId`){let t=e===`className`?`class`:e;if(e===`style`&&typeof n==`object`&&n){let e=Object.entries(n).map(([e,t])=>`${e.replace(i,`$1-$2`).toLowerCase()}:${String(t)}`).join(`;`);l+=` style="${s(e)}"`}else typeof n==`string`||typeof n==`number`?l+=` ${t}="${s(String(n))}"`:typeof n==`boolean`&&n&&(l+=` ${t}`)}r===null&&t.children&&(a=g(t.children))}return`<${n}${l}>${r===null?a:r}</${n}>`}return o.map(g).join(``)}return``}let _=g(m);if(_){let e=document.contains(l);e&&(l.innerHTML=_,l.classList.add(`rari-boundary-resolved`)),window.dispatchEvent(new CustomEvent(`rari:boundary-resolved`,{detail:{boundaryId:o,rscRow:s,rowId:c,element:l,wasAttached:e}}))}}catch(e){console.error(`[rari] Error processing boundary update:`,e)}};let o=window,s=globalThis;o[`~rari`].streaming?.bufferedEvents&&o[`~rari`].streaming.bufferedEvents.length>0&&(o[`~rari`].streaming.bufferedEvents.forEach(e=>{let{boundaryId:t,rscRow:n,rowId:r}=e;s[`~rari`].processBoundaryUpdate?.(t,n,r)}),o[`~rari`].streaming.bufferedEvents=[]),window.addEventListener(`rari:boundary-update`,e=>{let{boundaryId:t,rscRow:n,rowId:r}=e.detail;s[`~rari`].processBoundaryUpdate&&s[`~rari`].processBoundaryUpdate(t,n,r)})}function S(e,t,n){let r=n===`default`?e.name||t.split(`/`).pop()?.replace(o,``)||`DefaultComponent`:n,i=r,a={id:i,path:t,type:`client`,component:e,registered:!0};globalThis[`~clientComponents`]===void 0&&(globalThis[`~clientComponents`]={});let s=`${t}#${n}`;globalThis[`~clientComponents`][i]=a,globalThis[`~clientComponents`][t]=a,globalThis[`~clientComponents`][s]=a,globalThis[`~clientComponentPaths`][t]=i,globalThis[`~clientComponentNames`][r]=i,e&&(e[`~isClientComponent`]=!0,e[`~clientComponentId`]=i),typeof window<`u`&&fetch(`/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:i,file_path:t,export_name:n})}).catch(e=>{console.error(`[rari] Failed to register client component with server:`,e)})}function C(e){return c(e)}function w(){let e={};for(let[t,n]of Object.entries(globalThis[`~clientComponents`]))e[t]={id:t,chunks:[n.path],name:t,async:!1,default:n.component};return e}let T=l,E=u,D=null;async function O(){return D||(D=(async()=>{try{return T=l,E=u,typeof E!=`function`&&(E=null),typeof T!=`function`&&(T=null),y}catch(e){return console.error(`Failed to load react-dom/client RSC functions:`,e),T=null,E=null,null}})(),D)}const k=new Map,A=new class{componentCache;moduleCache;inflightRequests;config;constructor(){this.componentCache=new Map,this.moduleCache=new Map,this.inflightRequests=new Map,this.config={maxRetries:5,retryDelay:500,timeout:1e4}}configure(e){this.config={...this.config,...e}}clearCache(){this.componentCache.clear(),this.moduleCache.clear(),k.clear()}async fetchServerComponent(e,t={}){let n=typeof window<`u`&&window[`~rari`]?.hmr?.refreshCounters?.[e]||0,r=`${e}:${JSON.stringify(t)}:hmr:${n}`;if(this.componentCache.has(r))return this.componentCache.get(r);if(this.inflightRequests.has(r))return this.inflightRequests.get(r);let i=this.fetchServerComponentStream(e,t);this.inflightRequests.set(r,i);try{let e=await i;return this.componentCache.set(r,e),e}finally{this.inflightRequests.delete(r)}}async fetchServerComponentStream(e,t={}){await O();let n=(()=>{let e=[`/_rari/stream`];try{if(typeof window<`u`&&(window.location.hostname===`localhost`||window.location.hostname===`127.0.0.1`)){let t=b();t&&e.push(`${t}/_rari/stream`)}}catch{}return e})(),r=null,i=null,a=async()=>{for(let r of n)try{let n=await this.fetchWithTimeout(r,{method:`POST`,headers:{"Content-Type":`application/json`,...this.buildRequestHeaders()},body:JSON.stringify({component_id:e,props:t})});if(n.ok)return n;i=Error(`HTTP ${n.status}: ${await n.text()}`)}catch(e){i=e}return null};if(r=await a(),r||=(await new Promise(e=>setTimeout(e,this.config.retryDelay)),await a()),!r)throw i||Error(`Failed to reach stream endpoint`);if(!r.ok){let e=await r.text();throw Error(`Server responded with ${r.status}: ${e}`)}let o=r.body;if(!o)throw Error(`No ReadableStream from stream response`);let s=o.getReader(),c=new TextDecoder,l=new Map,u=new Map,d=e=>{if(!m)return console.error(`React not available for RSC conversion`),null;if(!e)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t,n,r]=e;if(t===`react.suspense`||t===`suspense`)return m(f,{fallback:d(r?.fallback)||null},r?.children?d(r.children):null);let i=r?{...r}:{};if(r?.children){let e=d(r.children);Array.isArray(e)?i.children=e.map((e,t)=>h(e)&&e.key==null?p(e,{key:t}):e):i.children=e}if(typeof t==`string`){if(t.startsWith(`$L`)){let e=l.get(t);if(e){let t=C(`${e.id}#${e.name||`default`}`);if(t)return m(t,n?{...i,key:n}:i)}return i&&i.children?i.children:null}if(t.includes(`.tsx#`)||t.includes(`.jsx#`)){let e=C(t);return e?m(e,n?{...i,key:n}:i):(console.error(`Failed to resolve client component:`,t),null)}else return i&&Object.hasOwn(i,`~boundaryId`)&&(i={...i},delete i[`~boundaryId`]),m(t,n?{...i,key:n}:i)}else console.error(`Unknown RSC element type:`,t)}return e.map(e=>d(e))}return typeof e==`object`?(console.error(`Unexpected object in RSC conversion:`,e),null):e},g=null,y=new Map,S=``,w=null,T=async()=>{try{for(;;){let{value:e,done:t}=await s.read();if(t)break;let n=c.decode(e,{stream:!0});S+=n;let r=S.split(`
2
+ `),i=r.slice(0,-1);S=r.at(-1)||``;for(let e of i)if(e.trim())try{let t=e.indexOf(`:`);if(t===-1)continue;let n=e.substring(0,t),r=e.substring(t+1),i=x(r);if(i)l.set(`$L${n}`,i);else if(r.startsWith(`E{`))try{let e=JSON.parse(r.substring(1));console.error(`RSC stream error:`,e)}catch(e){console.error(`Failed to parse error row:`,r,e)}else if(r.startsWith(`Symbol.for(`))continue;else if(r.startsWith(`[`)){let e=JSON.parse(r);if(Array.isArray(e)&&e.length>=4){let[t,r,i]=e,a=i?.[`~boundaryId`];if(t===`$`&&(r===`react.suspense`||r===`suspense`)&&i&&a&&u.set(`$L${n}`,a),t===`$`&&i&&Object.hasOwn(i,`children`)&&typeof r==`string`&&r.startsWith(`$L`)){let e=u.get(r)||null;if(e){let t=d(i.children);y.set(e,t),w&&w.updateBoundary(e,t);continue}}}if(!g){let t=!0;if(Array.isArray(e)&&e.length>=4&&e[0]===`$`){let n=e[1],r=e[3],i=r?.[`~boundaryId`];typeof n==`string`&&(n===`react.suspense`||n===`suspense`)&&r&&i&&(t=!1)}t&&(g=d(e),w&&typeof w.updateRoot==`function`&&w.updateRoot())}}}catch(t){console.error(`Failed to parse stream line:`,e,t)}}}catch(e){console.error(`Error processing stream:`,e)}},E=()=>{let[,e]=v(0);_(()=>(w={updateBoundary:(t,n)=>{y.set(t,n),e(e=>e+1)},updateRoot:()=>{e(e=>e+1)}},()=>{w=null}),[e]);let t=e=>{if(!e)return null;if(h(e)){let n=e.props,r=n?.[`~boundaryId`];if(n&&r){let e=y.get(r);if(e)return e}if(n&&n.children){let r=t(n.children);if(r!==n.children){let t={...n};return e.key!==null&&e.key!==void 0&&(t.key=e.key),m(e.type,t,r)}}return e}return Array.isArray(e)?e.map(e=>t(e)):e};return t(g)};T();let D=Promise.resolve(m(E));return{"~isRscResponse":!0,"~rscPromise":D,readRoot(){return D}}}buildRequestHeaders(){return{Accept:`text/x-component`,"Cache-Control":`no-cache, no-transform`}}async fetchWithTimeout(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{let i=await fetch(e,{...t,signal:n.signal});return clearTimeout(r),i}catch(e){throw clearTimeout(r),e}}async processRscResponse(e){if(await O(),T)try{let t=T(Promise.resolve(e));return{"~isRscResponse":!0,"~rscPromise":t,readRoot(){return t}}}catch{throw Error(`React Server DOM client not available`)}else throw Error(`React Server DOM client not available`)}async processRscResponseManually(e){let t=await e.text();return this.parseRscResponse(t)}parseRscResponse(e){let t=e.trim().split(s),n=new Map,r=new Map,i=[];for(let e of t){let t=e.indexOf(`:`);if(t===-1)continue;let a=e.substring(0,t),o=e.substring(t+1);if(o)try{let t=x(o);if(t)n.set(`$L${a}`,t);else if(o.startsWith(`E{`)){let e=o.substring(1),t=JSON.parse(e);i.push(t),console.error(`RSC: Server error`,t)}else if(o.startsWith(`[`)){let e=JSON.parse(o);r.set(a,e)}else if(o.startsWith(`Symbol.for(`))continue;else console.error(`Unknown RSC row format:`,e)}catch(t){console.error(`Failed to parse RSC row:`,e,t)}}if(i.length>0)throw Error(`RSC Server Error: ${i.map(e=>e.message||e).join(`, `)}`);let a=null,o=Array.from(r.keys()).sort((e,t)=>Number.parseInt(e,16)-Number.parseInt(t,16));for(let e of o){let t=r.get(e);if(Array.isArray(t)&&t.length>=2&&t[0]===`$`){let[,e,,n]=t,r=n?.[`~boundaryId`];if(e===`react.suspense`&&n&&r)continue;a=t;break}}return a?this.reconstructElementFromRscData(a,n):(console.error(`No valid root element found in RSC payload`,{elements:r,modules:n}),null)}reconstructElementFromRscData(e,t){if(e==null)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))if(e.length>=4&&e[0]===`$`){let[,n,r,i]=e,a=n;if(typeof n==`string`&&n.includes(`#`))a=C(n)||(({children:e,...t})=>m(`div`,{...t,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},m(`small`,{style:{color:`#c00`}},`Missing Client Component: ${n}`),e));else if(typeof n==`string`&&n.startsWith(`$L`)&&t.has(n)){let e=t.get(n);e&&(a=C(`${e.id}#${e.name}`)||(({children:t,...r})=>m(`div`,{...r,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},m(`small`,{style:{color:`#c00`}},`Missing Client Component: ${e.name} (${e.id})`),t)))}let o=i?this.processPropsRecursively(i,t):{};return m(a,{key:r,...o})}else return e.map(e=>this.reconstructElementFromRscData(e,t));return typeof e==`object`?null:e}processPropsRecursively(e,t){if(!e||typeof e!=`object`)return e;let n={};for(let[r,i]of Object.entries(e))if(r===`children`)if(Array.isArray(i))if(i.length>=2&&i[0]===`$`)n[r]=this.reconstructElementFromRscData(i,t);else{let e=i.map(e=>this.reconstructElementFromRscData(e,t)).filter(e=>e!=null);e.length===0?n[r]=null:e.length===1?n[r]=e[0]:n[r]=e}else n[r]=this.reconstructElementFromRscData(i,t);else r===`dangerouslySetInnerHTML`?n[r]=i:n[r]=this.reconstructElementFromRscData(i,t);return n}};function j({error:e,details:t}){return m(`div`,{className:`rsc-error`,style:{padding:`16px`,backgroundColor:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`,margin:`8px 0`,fontFamily:`monospace`}},m(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`}},`RSC Error`),m(`p`,{style:{margin:`0 0 8px 0`}},e),t&&m(`details`,{style:{marginTop:`8px`}},m(`summary`,{style:{cursor:`pointer`}},`Error Details`),m(`pre`,{style:{fontSize:`12px`,overflow:`auto`,backgroundColor:`#f5f5f5`,padding:`8px`}},JSON.stringify(t,null,2))))}function M({rootPromise:e}){return g(e)}function N({componentId:e,props:t,fallback:n}){let r=typeof window<`u`&&window[`~rari`]?.hmr?.refreshCounters?.[e]||0,i=`${e}:${JSON.stringify(t)}:hmr:${r}`;if(!k.has(i)){let n=A.fetchServerComponent(e,t).catch(e=>{throw k.delete(i),e});k.set(i,n)}let a=g(k.get(i));if(a?.[`~isRscResponse`]){let e=a.readRoot();return m(f,{fallback:n??null},m(M,{rootPromise:e}))}return a??null}var P=class extends d.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidUpdate(e){e.mountKey!==this.props.mountKey&&this.state.hasError&&this.setState({hasError:!1,error:null})}componentDidCatch(e,t){console.error(`[rari] ServerComponentErrorBoundary: Error in component ${this.props.componentId}:`,e,t)}render(){return this.state.hasError?m(j,{error:this.state.error?.message||`Unknown error`,details:{componentId:this.props.componentId}}):this.props.children}};function F(e){let t=0;if(typeof window<`u`){let n=window;n[`~rari`].hmr||(n[`~rari`].hmr={refreshCounters:{}}),n[`~rari`].hmr.refreshCounters[e]===void 0&&(n[`~rari`].hmr.refreshCounters[e]=0),t=n[`~rari`].hmr.refreshCounters[e]}let n=n=>{let[r,i]=v(t);return _(()=>{let t=t=>{let n=t.detail;if(n&&n.filePath&&L(n.filePath)&&(A.clearCache(),typeof window<`u`)){let t=window;t[`~rari`].hmr||(t[`~rari`].hmr={refreshCounters:{}}),t[`~rari`].hmr.refreshCounters[e]=(t[`~rari`].hmr.refreshCounters[e]||0)+1,i(t[`~rari`].hmr.refreshCounters[e])}};return typeof window<`u`&&window.addEventListener(`rari:rsc-invalidate`,t),()=>{typeof window<`u`&&window.removeEventListener(`rari:rsc-invalidate`,t)}},[]),m(f,{fallback:null},m(P,{componentId:e,mountKey:r},m(N,{key:`${e}-${r}`,componentId:e,props:n,fallback:null})))};return n.displayName=`ServerComponent(${e})`,function(e){return m(n,e)}}function I(e,t){return A.fetchServerComponent(e,t)}function L(e){if(!e)return!1;try{return typeof globalThis<`u`&&globalThis[`~rari`].serverComponents?globalThis[`~rari`].serverComponents.has(e):!1}catch(e){return console.error(`Error checking if file is server component:`,e),!1}}if(import.meta.hot){let e=!1,t=[],n=new Map;function r(r,i){n.set(r,i),import.meta.hot.on(r,async n=>{if(!e){t.push({event:r,data:n});return}try{await i(n)}catch(e){console.error(`[rari] HMR: Error in handler for '${r}':`,e)}})}r(`rari:register-server-component`,e=>{e?.filePath&&typeof globalThis<`u`&&(globalThis[`~rari`].serverComponents=globalThis[`~rari`].serverComponents||new Set,globalThis[`~rari`].serverComponents.add(e.filePath))}),r(`rari:server-components-registry`,e=>{e?.serverComponents&&Array.isArray(e.serverComponents)&&typeof globalThis<`u`&&(globalThis[`~rari`].serverComponents=globalThis[`~rari`].serverComponents||new Set,e.serverComponents.forEach(e=>{globalThis[`~rari`].serverComponents?.add(e)}))}),r(`vite:beforeFullReload`,async e=>{e?.path&&L(e.path)&&await u({filePath:e.path,forceReload:!0})}),r(`rari:server-component-updated`,async e=>{let t=e?.id||e?.componentId,n=e?.t||e?.timestamp;if(t){if(typeof window<`u`){let r=new CustomEvent(`rari:rsc-invalidate`,{detail:{componentId:t,filePath:e.filePath||e.file,type:`server-component`,timestamp:n}});window.dispatchEvent(r)}}else e?.path&&L(e.path)&&await u({filePath:e.path,forceReload:!1})}),r(`rari:app-router-updated`,async e=>{try{if(!e||!e.routePath&&(!e.affectedRoutes||e.affectedRoutes.length===0))return;await i(e)}catch(e){console.error(`[rari] HMR: App router update failed:`,e)}}),r(`rari:server-action-updated`,async e=>{if(e?.filePath&&(A.clearCache(),typeof window<`u`)){let t=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:e.filePath,type:`server-action`}});window.dispatchEvent(t)}});async function i(e){let t=e.fileType,n=e.filePath,r=e.routePath,i=e.affectedRoutes,o=e.manifestUpdated,u=e.metadata;e.metadataChanged&&u&&a(u);try{let e=`${b()}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`register`,file_path:n})});if(!t.ok){let e=await t.text(),n=`Component reload failed with status ${t.status}: ${e}`;throw console.error(`[rari] HMR:`,n),Error(n)}let r=await t.json();if(typeof r!=`object`||!r){let e=`Invalid reload response: null or non-object`;throw console.error(`[rari] HMR:`,e,r),Error(e)}if(r.success!==!0&&r.reloaded!==!0){let e=`Component reload unsuccessful: ${r.error||`unknown error`}`;throw console.error(`[rari] HMR:`,e,r),Error(e)}}catch(e){console.error(`[rari] HMR: Failed to reload component:`,e);return}let d=[r];switch(t){case`page`:d=[r];break;case`layout`:case`loading`:case`error`:case`not-found`:d=i;break;default:break}await s({routes:d,fileType:t,filePath:n,componentId:r}),o&&await l(),await c({routePath:r,affectedRoutes:i})}function a(e){if(!(typeof document>`u`)&&(e.title&&(document.title=e.title),e.description)){let t=document.querySelector(`meta[name="description"]`);t||(t=document.createElement(`meta`),t.setAttribute(`name`,`description`),document.head.appendChild(t)),t.setAttribute(`content`,e.description)}}function o(e){if(!e||e.length===0){A.clearCache();return}let t=[];for(let n of A.componentCache.keys())for(let r of e){if(n.includes(`route:${r}:`)||n.startsWith(`${r}:`)){t.push(n);break}if(r!==`/`&&n.includes(`route:${r}/`)){t.push(n);break}}for(let e of t)A.componentCache.delete(e),k.delete(e);let n=[];for(let t of k.keys())for(let r of e){if(t.includes(`route:${r}:`)||t.startsWith(`${r}:`)){n.push(t);break}if(r!==`/`&&t.includes(`route:${r}/`)){n.push(t);break}}for(let e of n)k.delete(e)}async function s(e){let t=e.routes||[],n=e.fileType,r=e.filePath,i=e.componentId;if(i||r)try{let e=`${b()}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate`,componentId:i||r,filePath:r})}),n=await t.text();t.ok||console.error(`[rari] HMR: Server cache invalidation failed:`,t.status,n)}catch(e){console.error(`[rari] HMR: Failed to call server invalidation endpoint:`,e)}if(o(t),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{routes:t,fileType:n}});window.dispatchEvent(e)}}async function c(e){let t=e.routePath,n=e.affectedRoutes||[t];if(!(typeof window>`u`))try{let e=window.location.pathname,r=new CustomEvent(`rari:app-router-rerender`,{detail:{routePath:t,affectedRoutes:n,currentPath:e,preserveParams:!0}});window.dispatchEvent(r)}catch(e){throw console.error(`[rari] HMR: Failed to trigger re-render:`,e),e}}async function l(){typeof window<`u`&&window[`~rari`]?.routeInfoCache&&window[`~rari`].routeInfoCache.clear()}async function u(e){let t=e?.filePath||e;if(A.clearCache(),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:t}});window.dispatchEvent(e)}}t.length>0?(async()=>{try{for(;t.length>0;){let e=[...t];t.length=0;for(let{event:t,data:r}of e){let e=n.get(t);if(e)try{await e(r)}catch(e){console.error(`[rari] HMR: Error replaying buffered event '${t}':`,e)}}}}catch(e){console.error(`[rari] HMR: Error during event replay:`,e)}finally{e=!0}})():e=!0}var R=class{overlay;currentError;escapeKeyHandler;constructor(){this.overlay=null,this.currentError=null,this.escapeKeyHandler=null}show(e){this.currentError=e,this.overlay?this.updateOverlay(e):this.createOverlay(e)}hide(){this.overlay&&(this.overlay.remove(),this.overlay=null,this.currentError=null),this.escapeKeyHandler&&=(document.removeEventListener(`keydown`,this.escapeKeyHandler),null)}isVisible(){return this.overlay!==null}createOverlay(e){this.overlay=document.createElement(`div`),this.overlay.id=`rari-hmr-error-overlay`,this.updateOverlay(e),document.body.appendChild(this.overlay),this.escapeKeyHandler=e=>{e.key===`Escape`&&this.hide()},document.addEventListener(`keydown`,this.escapeKeyHandler)}updateOverlay(e){if(!this.overlay)return;this.overlay.replaceChildren();let t=document.createElement(`div`);t.style.cssText=`position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.85); z-index: 999999; display: flex; align-items: center; justify-content: center; padding: 2rem; backdrop-filter: blur(4px);`;let n=document.createElement(`div`);n.style.cssText=`background: #1e1e1e; color: #e0e0e0; border-radius: 0.5rem; padding: 2rem; max-width: 50rem; width: 100%; max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.4); border: 1px solid #ef4444;`;let r=document.createElement(`div`);r.style.cssText=`display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem;`;let i=document.createElement(`div`);i.style.cssText=`display: flex; align-items: center; gap: 0.75rem;`;let a=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);a.style.cssText=`width: 2rem; height: 2rem; color: #ef4444;`,a.setAttribute(`fill`,`none`),a.setAttribute(`stroke`,`currentColor`),a.setAttribute(`viewBox`,`0 0 24 24`);let o=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);o.setAttribute(`stroke-linecap`,`round`),o.setAttribute(`stroke-linejoin`,`round`),o.setAttribute(`stroke-width`,`2`),o.setAttribute(`d`,`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z`),a.appendChild(o);let s=document.createElement(`h1`);s.style.cssText=`margin: 0; font-size: 1.5rem; font-weight: 700; color: #ef4444;`,s.textContent=`Build Error`,i.appendChild(a),i.appendChild(s);let c=document.createElement(`button`);if(c.style.cssText=`background: transparent; border: none; color: #9ca3af; cursor: pointer; padding: 0.5rem; border-radius: 0.25rem; transition: all 0.2s; font-size: 1.5rem; line-height: 1; width: 2rem; height: 2rem; display: flex; align-items: center; justify-content: center;`,c.textContent=`×`,c.setAttribute(`aria-label`,`Close overlay`),c.onclick=()=>this.hide(),c.onmouseover=()=>{c.style.background=`rgba(255,255,255,0.1)`,c.style.color=`#e0e0e0`},c.onmouseout=()=>{c.style.background=`transparent`,c.style.color=`#9ca3af`},c.onfocus=()=>{c.style.background=`rgba(255,255,255,0.1)`,c.style.color=`#e0e0e0`},c.onblur=()=>{c.style.background=`transparent`,c.style.color=`#9ca3af`},r.appendChild(i),r.appendChild(c),n.appendChild(r),e.filePath){let t=document.createElement(`div`);t.style.cssText=`margin-bottom: 1rem; padding: 0.75rem; background: rgba(0, 0, 0, 0.2); border-radius: 0.375rem; font-family: monospace; font-size: 0.875rem;`;let r=document.createElement(`strong`);r.textContent=`File: `,t.appendChild(r),t.appendChild(document.createTextNode(e.filePath)),n.appendChild(t)}let l=document.createElement(`div`);l.style.cssText=`margin-bottom: 1.5rem;`;let u=document.createElement(`h2`);u.style.cssText=`margin: 0 0 0.75rem 0; font-size: 1rem; font-weight: 600; color: #fca5a5;`,u.textContent=`Error Message:`;let d=document.createElement(`pre`);if(d.style.cssText=`margin: 0; padding: 1rem; background: rgba(239, 68, 68, 0.1); border-left: 4px solid #ef4444; border-radius: 0.375rem; overflow-x: auto; font-family: monospace; font-size: 0.875rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word; color: #fca5a5;`,d.textContent=e.message??`An error occurred`,l.appendChild(u),l.appendChild(d),n.appendChild(l),e.stack){let t=document.createElement(`details`);t.style.cssText=`margin-top: 1rem; cursor: pointer;`;let r=document.createElement(`summary`);r.style.cssText=`font-weight: 600; margin-bottom: 0.5rem; user-select: none;`,r.textContent=`Stack Trace`;let i=document.createElement(`pre`);i.style.cssText=`margin: 0; padding: 0.75rem; background: rgba(0, 0, 0, 0.2); border-radius: 0.375rem; overflow-x: auto; font-size: 0.875rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word;`,i.textContent=e.stack,t.appendChild(r),t.appendChild(i),n.appendChild(t)}let f=document.createElement(`div`);f.style.cssText=`margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #374151; display: flex; gap: 0.75rem; align-items: center;`;let p=document.createElement(`button`);p.style.cssText=`padding: 0.625rem 1.25rem; background: #ef4444; color: white; border: none; border-radius: 0.375rem; cursor: pointer; font-weight: 600; font-size: 0.875rem; transition: all 0.2s;`,p.textContent=`Reload Page`,p.onclick=()=>window.location.reload(),p.onmouseover=()=>{p.style.background=`#dc2626`},p.onmouseout=()=>{p.style.background=`#ef4444`},p.onfocus=()=>{p.style.background=`#dc2626`},p.onblur=()=>{p.style.background=`#ef4444`};let m=document.createElement(`button`);m.style.cssText=`padding: 0.625rem 1.25rem; background: #374151; color: #e0e0e0; border: none; border-radius: 0.375rem; cursor: pointer; font-weight: 600; font-size: 0.875rem; transition: all 0.2s;`,m.textContent=`Dismiss`,m.onclick=()=>this.hide(),m.onmouseover=()=>{m.style.background=`#4b5563`},m.onmouseout=()=>{m.style.background=`#374151`},m.onfocus=()=>{m.style.background=`#4b5563`},m.onblur=()=>{m.style.background=`#374151`};let h=document.createElement(`span`);h.style.cssText=`margin-left: auto; font-size: 0.75rem; color: #9ca3af;`;let g=new Date(e.timestamp);h.textContent=Number.isNaN(g.valueOf())?``:g.toLocaleTimeString(),f.appendChild(p),f.appendChild(m),f.appendChild(h),n.appendChild(f),t.appendChild(n),this.overlay.appendChild(t)}};let z=null;function B(){return z||=new R,z}if(import.meta.hot){let e=B();import.meta.hot.on(`rari:hmr-error`,t=>{let n=t.msg||t.message,r=t.file||t.filePath,i=t.t||t.timestamp,a=t.count||t.errorCount,o=t.max||t.maxErrors;console.error(`[rari] HMR: Build error:`,n),r&&console.error(`[rari] HMR: File:`,r),t.stack&&console.error(`[rari] HMR: Stack:`,t.stack),e.show({message:n,stack:t.stack,filePath:r,timestamp:i}),a&&o&&(a>=o?console.error(`[rari] HMR: Maximum error count (${o}) reached. Consider restarting the dev server if issues persist.`):a>=o-2&&console.warn(`[rari] HMR: Error count: ${a}/${o}. Approaching maximum error threshold.`))}),import.meta.hot.on(`rari:hmr-error-cleared`,()=>{e.hide()}),import.meta.hot.on(`vite:error`,t=>{e.show({message:t.err?.message||`Unknown Vite error`,stack:t.err?.stack,filePath:t.err?.file,timestamp:Date.now()})})}export{j as RscErrorComponent,w as createClientModuleMap,F as createServerComponentWrapper,I as fetchServerComponent,C as getClientComponent,S as registerClientComponent,A as rscClient};