rari 0.10.1 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.mts
CHANGED
|
@@ -7,10 +7,12 @@ import * as react_jsx_runtime0 from "react/jsx-runtime";
|
|
|
7
7
|
interface ClientRouterProps {
|
|
8
8
|
children: React.ReactNode;
|
|
9
9
|
initialRoute: string;
|
|
10
|
+
staleWindowMs?: number;
|
|
10
11
|
}
|
|
11
12
|
declare function ClientRouter({
|
|
12
13
|
children,
|
|
13
|
-
initialRoute
|
|
14
|
+
initialRoute,
|
|
15
|
+
staleWindowMs
|
|
14
16
|
}: ClientRouterProps): react_jsx_runtime0.JSX.Element;
|
|
15
17
|
//#endregion
|
|
16
18
|
//#region src/router/LayoutErrorBoundary.d.ts
|
package/dist/client.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h}from"./runtime-client-Bg4V1Ksp.mjs";import{Component as g,useEffect as _,useRef as v,useState as y}from"react";import{Fragment as b,jsx as x,jsxs as S}from"react/jsx-runtime";function C(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,l=Math.min(s,c);r=setTimeout(p,l)}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}function w(e,t){if(e instanceof Error&&e.name===`AbortError`)return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1};if(e instanceof Error&&e.message.includes(`timeout`))return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0};if(e instanceof Error&&`status`in e){let n=e.status;return n===404?{type:`not-found`,message:`Page not found`,originalError:e,statusCode:n,url:t,timestamp:Date.now(),retryable:!1}:n>=500?{type:`server-error`,message:`Server error: ${n}`,originalError:e,statusCode:n,url:t,timestamp:Date.now(),retryable:!0}:{type:`fetch-error`,message:`HTTP error: ${n}`,originalError:e,statusCode:n,url:t,timestamp:Date.now(),retryable:n>=500}}return e instanceof TypeError&&e.message.includes(`fetch`)?{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}:e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}:{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}}var T=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=w(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:navigation-error`,{detail:n})),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 E(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 D(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function O(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}function k({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return x(`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:S(`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:[S(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[x(`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`❌`}})()}),x(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),x(`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&&S(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[x(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),S(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[S(`div`,{style:{marginBottom:`4px`},children:[x(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&S(`div`,{style:{marginBottom:`4px`},children:[x(`strong`,{children:`Status:`}),` `,e.statusCode]}),S(`div`,{style:{marginBottom:`4px`},children:[x(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&S(`div`,{children:[x(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&S(`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]}),S(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&x(`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&&x(`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&&x(`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`})]}),x(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const A=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=await n.json();throw Error(e.error||`Failed to fetch route info`)}return n.json()}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=A}var j=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 M(e){e.title&&(document.title=e.title);let t=(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)}};if(e.description&&t(`meta[name="description"]`,{name:`description`,content:e.description}),e.keywords&&e.keywords.length>0&&t(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}),e.viewport&&t(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport}),e.canonical){let t=document.querySelector(`link[rel="canonical"]`);t||(t=document.createElement(`link`),t.setAttribute(`rel`,`canonical`),document.head.appendChild(t)),t.setAttribute(`href`,e.canonical)}if(e.robots){let n=[];e.robots.index!==void 0&&n.push(e.robots.index?`index`:`noindex`),e.robots.follow!==void 0&&n.push(e.robots.follow?`follow`:`nofollow`),e.robots.nocache&&n.push(`nocache`),n.length>0&&t(`meta[name="robots"]`,{name:`robots`,content:n.join(`, `)})}if(e.openGraph){let n=e.openGraph;if(n.title&&t(`meta[property="og:title"]`,{property:`og:title`,content:n.title}),n.description&&t(`meta[property="og:description"]`,{property:`og:description`,content:n.description}),n.url&&t(`meta[property="og:url"]`,{property:`og:url`,content:n.url}),n.siteName&&t(`meta[property="og:site_name"]`,{property:`og:site_name`,content:n.siteName}),n.type&&t(`meta[property="og:type"]`,{property:`og:type`,content:n.type}),n.images&&n.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let e of n.images){let t=document.createElement(`meta`);t.setAttribute(`property`,`og:image`),t.setAttribute(`content`,e),document.head.appendChild(t)}}}if(e.twitter){let n=e.twitter;if(n.card&&t(`meta[name="twitter:card"]`,{name:`twitter:card`,content:n.card}),n.site&&t(`meta[name="twitter:site"]`,{name:`twitter:site`,content:n.site}),n.creator&&t(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:n.creator}),n.title&&t(`meta[name="twitter:title"]`,{name:`twitter:title`,content:n.title}),n.description&&t(`meta[name="twitter:description"]`,{name:`twitter:description`,content:n.description}),n.images&&n.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let e of n.images){let t=document.createElement(`meta`);t.setAttribute(`name`,`twitter:image`),t.setAttribute(`content`,e),document.head.appendChild(t)}}}}function N({children:e,initialRoute:t}){let[n,r]=y(()=>({currentRoute:E(t),navigationId:0,error:null})),i=v(null),a=v(!0),o=v(E(t)),s=v(new T({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),c=v(new Map),l=v([]),u=v(new j({maxHistorySize:50})),d=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,f=()=>{i.current&&=(i.current.abort(),null)},p=()=>{for(let[,e]of c.current.entries())e.abortController.abort();c.current.clear()},m=(e,t)=>{c.current.delete(e),a.current&&n.navigationId===t&&r(e=>({...e}))},h=async e=>A.get(e),g=v(null),w=async(e,t={})=>{if(!e||typeof e!=`string`){console.error(`[rari] Router: Invalid navigation target:`,e);return}let[l,_]=e.includes(`#`)?e.split(`#`):[e,``],v=E(l);if(v===o.current&&!t.replace){if(_){let e=document.getElementById(_);e&&(e.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${v}#${_}`))}return}let y=c.current.get(v);if(y)return y.promise;let b=await h(v);p(),f();let x=new AbortController;i.current=x;let S=n.navigationId+1,C=(async()=>{let e=o.current;try{t.historyKey||u.current.captureState(e);let n=t.historyKey||d(),i={route:v,navigationId:S,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n},l=_?`${v}#${_}`:v;t.replace?window.history.replaceState(i,``,l):window.history.pushState(i,``,l);let f=window.location.origin+v,p=await fetch(f,{headers:{Accept:`text/x-component`},signal:x.signal});if(!p.ok&&p.status!==404)throw Error(`Failed to fetch: ${p.status}`);let h=new URL(p.url).pathname,y=h===v?v:h;if(h!==v){let e=_?`${h}#${_}`:h;window.history.replaceState({route:h,navigationId:S,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:t.historyKey||d()},``,e)}if(x.signal.aborted){m(y,S);return}try{let e=p.headers.get(`x-rari-metadata`);if(e){let t=decodeURIComponent(e);M(JSON.parse(t))}}catch{}if(p.headers.get(`x-render-mode`)===`streaming`&&p.body){let n=p.body.getReader(),r=new TextDecoder,i=``;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(x.signal.aborted){await n.cancel(),m(y,S);return}i+=r.decode(t,{stream:!0});let a=i.split(`
|
|
2
|
-
`);i=a.pop()||``;for(let e of a)e.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:e}}))}i.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:i}})),window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:e,to:
|
|
1
|
+
import{a as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h}from"./runtime-client-Bg4V1Ksp.mjs";import{Component as g,useEffect as _,useRef as v,useState as y}from"react";import{Fragment as b,jsx as x,jsxs as S}from"react/jsx-runtime";function C(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,l=Math.min(s,c);r=setTimeout(p,l)}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}function w(e,t){if(e instanceof Error&&e.name===`AbortError`)return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1};if(e instanceof Error&&e.message.includes(`timeout`))return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0};if(e instanceof Error&&`status`in e){let n=e.status;return n===404?{type:`not-found`,message:`Page not found`,originalError:e,statusCode:n,url:t,timestamp:Date.now(),retryable:!1}:n>=500?{type:`server-error`,message:`Server error: ${n}`,originalError:e,statusCode:n,url:t,timestamp:Date.now(),retryable:!0}:{type:`fetch-error`,message:`HTTP error: ${n}`,originalError:e,statusCode:n,url:t,timestamp:Date.now(),retryable:n>=500}}return e instanceof TypeError&&e.message.includes(`fetch`)?{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}:e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}:{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}}var T=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=w(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:navigation-error`,{detail:n})),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 E(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 D(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function O(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}function k({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return x(`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:S(`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:[S(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[x(`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`❌`}})()}),x(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),x(`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&&S(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[x(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),S(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[S(`div`,{style:{marginBottom:`4px`},children:[x(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&S(`div`,{style:{marginBottom:`4px`},children:[x(`strong`,{children:`Status:`}),` `,e.statusCode]}),S(`div`,{style:{marginBottom:`4px`},children:[x(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&S(`div`,{children:[x(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&S(`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]}),S(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&x(`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&&x(`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&&x(`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`})]}),x(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const A=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=A}var j=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 M(e){e.title&&(document.title=e.title);let t=(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)}};if(e.description&&t(`meta[name="description"]`,{name:`description`,content:e.description}),e.keywords&&e.keywords.length>0&&t(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}),e.viewport&&t(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport}),e.canonical){let t=document.querySelector(`link[rel="canonical"]`);t||(t=document.createElement(`link`),t.setAttribute(`rel`,`canonical`),document.head.appendChild(t)),t.setAttribute(`href`,e.canonical)}if(e.robots){let n=[];e.robots.index!==void 0&&n.push(e.robots.index?`index`:`noindex`),e.robots.follow!==void 0&&n.push(e.robots.follow?`follow`:`nofollow`),e.robots.nocache&&n.push(`nocache`),n.length>0&&t(`meta[name="robots"]`,{name:`robots`,content:n.join(`, `)})}if(e.openGraph){let n=e.openGraph;if(n.title&&t(`meta[property="og:title"]`,{property:`og:title`,content:n.title}),n.description&&t(`meta[property="og:description"]`,{property:`og:description`,content:n.description}),n.url&&t(`meta[property="og:url"]`,{property:`og:url`,content:n.url}),n.siteName&&t(`meta[property="og:site_name"]`,{property:`og:site_name`,content:n.siteName}),n.type&&t(`meta[property="og:type"]`,{property:`og:type`,content:n.type}),n.images&&n.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let e of n.images){let t=document.createElement(`meta`);t.setAttribute(`property`,`og:image`),t.setAttribute(`content`,e),document.head.appendChild(t)}}}if(e.twitter){let n=e.twitter;if(n.card&&t(`meta[name="twitter:card"]`,{name:`twitter:card`,content:n.card}),n.site&&t(`meta[name="twitter:site"]`,{name:`twitter:site`,content:n.site}),n.creator&&t(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:n.creator}),n.title&&t(`meta[name="twitter:title"]`,{name:`twitter:title`,content:n.title}),n.description&&t(`meta[name="twitter:description"]`,{name:`twitter:description`,content:n.description}),n.images&&n.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let e of n.images){let t=document.createElement(`meta`);t.setAttribute(`name`,`twitter:image`),t.setAttribute(`content`,e),document.head.appendChild(t)}}}}function N({children:e,initialRoute:t,staleWindowMs:n=3e4}){let[r,i]=y(()=>({currentRoute:E(t),navigationId:0,error:null})),a=v(null),o=v(!0),s=v(E(t)),c=v(new T({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),l=v(new Map),u=v([]),d=v(new j({maxHistorySize:50})),f=v(null),p=v(n),m=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,h=()=>{a.current&&=(a.current.abort(),null)},g=()=>{for(let[,e]of l.current.entries())e.abortController.abort();l.current.clear()},w=(e,t)=>{l.current.delete(e),o.current&&r.navigationId===t&&i(e=>({...e}))},N=async e=>A.get(e),P=v(null),F=async(e,t={})=>{if(!e||typeof e!=`string`){console.error(`[rari] Router: Invalid navigation target:`,e);return}let[n,u]=e.includes(`#`)?e.split(`#`):[e,``],f=E(n);if(f===s.current&&!t.replace){if(u){let e=document.getElementById(u);e&&(e.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${f}#${u}`))}return}let p=l.current.get(f);if(p)return p.promise;let _=await N(f);g(),h();let v=new AbortController;a.current=v;let y=r.navigationId+1,b=(async()=>{let e=s.current;try{t.historyKey||d.current.captureState(e);let n=t.historyKey||m(),r={route:f,navigationId:y,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n},a=u?`${f}#${u}`:f;t.replace?window.history.replaceState(r,``,a):window.history.pushState(r,``,a);let p=window.location.origin+f,h=await fetch(p,{headers:{Accept:`text/x-component`},signal:v.signal});if(!h.ok&&h.status!==404)throw Error(`Failed to fetch: ${h.status}`);let g=new URL(h.url).pathname,b=g===f?f:g;if(g!==f){let e=u?`${g}#${u}`:g;window.history.replaceState({route:g,navigationId:y,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:t.historyKey||m()},``,e)}if(v.signal.aborted){w(b,y);return}try{let e=h.headers.get(`x-rari-metadata`);if(e){let t=decodeURIComponent(e);M(JSON.parse(t))}}catch{}if(h.headers.get(`x-render-mode`)===`streaming`&&h.body){let n=h.body.getReader(),r=new TextDecoder,i=``;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(v.signal.aborted){await n.cancel(),w(b,y);return}i+=r.decode(t,{stream:!0});let a=i.split(`
|
|
2
|
+
`);i=a.pop()||``;for(let e of a)e.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:e}}))}i.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:i}})),window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:e,to:b,navigationId:y,options:t,routeInfo:_,abortSignal:v.signal,isStreaming:!0}}))}catch(e){throw console.error(`[rari] Router: Streaming error:`,e),e}}else{let n=await h.text();window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:e,to:b,navigationId:y,options:t,routeInfo:_,abortSignal:v.signal,rscWireFormat:n}}))}if(v.signal.aborted){w(b,y);return}o.current&&(s.current=b,i(e=>({...e,currentRoute:b,error:null})),c.current.resetRetry(b),t.historyKey?requestAnimationFrame(()=>{d.current.restoreState(b)}):u&&requestAnimationFrame(()=>{let e=(t=0)=>{let n=document.getElementById(u);n?n.scrollIntoView({behavior:`smooth`,block:`start`}):t<10&&setTimeout(e,50,t+1)};e()})),l.current.delete(f),P.current?.()}catch(t){if(t instanceof Error&&t.name===`AbortError`){w(f,y);return}let n=c.current.handleError(t,f);o.current&&i(e=>({...e,error:n})),l.current.delete(f),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:e,to:f,error:n,navigationId:y}})),P.current?.()}})();return l.current.set(f,{targetPath:f,navigationId:y,promise:b,abortController:v}),b};P.current=async()=>{if(u.current.length===0)return;let e=u.current.at(-1);e&&(u.current=[],await F(e.path,e.options))};let I=v(F);I.current=F;let L=v(null);L.current||=C((e,t)=>{I.current(e,t)},50,{leading:!1,trailing:!0,maxWait:200});let R=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||D(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=O(r);L.current&&L.current(i,{replace:!1})},z=e=>{let t=window.location.pathname,n=e.state;I.current&&I.current(t,{replace:!0,scroll:!1,historyKey:n?.key})},B=()=>{if(r.error&&r.error.url){let e=r.error.url;c.current.incrementRetry(e),F(e,{replace:!1})}},V=()=>{window.location.reload()},H=()=>{i(e=>({...e,error:null}))};_(()=>{let e=window.history.state;if(!e||!e.key){let e={route:r.currentRoute,navigationId:r.navigationId,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:m()};window.history.replaceState(e,``,window.location.pathname+window.location.search)}},[]);let U=e=>{if(e.persisted){let e=window.location.pathname;d.current.captureState(e)}},W=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{d.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return _(()=>(document.addEventListener(`click`,R),window.addEventListener(`popstate`,z),window.addEventListener(`pagehide`,U),window.addEventListener(`pageshow`,W),()=>{document.removeEventListener(`click`,R),window.removeEventListener(`popstate`,z),window.removeEventListener(`pagehide`,U),window.removeEventListener(`pageshow`,W)}),[]),_(()=>{p.current=n;let e=()=>{document.hidden?f.current=Date.now():f.current!==null&&Date.now()-f.current>p.current&&A.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[n]),_(()=>(o.current=!0,()=>{o.current=!1,h(),g(),L.current?.cancel&&L.current.cancel()}),[]),S(b,{children:[e,r.error&&x(k,{error:r.error,onRetry:B,onReload:V,onDismiss:H,retryCount:c.current.getRetryCount(r.error.url||``),maxRetries:3})]})}var P=class extends g{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):S(`div`,{style:{padding:`16px`,margin:`16px 0`,background:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`},children:[x(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`},children:`Layout Error`}),S(`p`,{style:{margin:`0 0 8px 0`,fontSize:`14px`},children:[`An error occurred in layout:`,` `,x(`code`,{children:this.props.layoutPath})]}),S(`details`,{style:{fontSize:`12px`,marginBottom:`8px`},children:[x(`summary`,{style:{cursor:`pointer`},children:`Error details`}),S(`pre`,{style:{marginTop:`8px`,padding:`8px`,background:`#fff`,border:`1px solid #ddd`,borderRadius:`2px`,overflow:`auto`},children:[this.state.error.message,`
|
|
3
3
|
`,this.state.error.stack]})]}),x(`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{N as ClientRouter,m as DefaultError,l as DefaultLoading,f as ErrorBoundary,o as HttpRuntimeClient,P as LayoutErrorBoundary,e as LoadingSpinner,T as NavigationErrorHandler,k as NavigationErrorOverlay,u as NotFound,j as StatePreserver,h as clearPropsCache,n as clearPropsCacheForComponent,p as createErrorBoundary,t as createHttpRuntimeClient,s as createLoadingBoundary,r as extractMetadata,d as extractServerProps,c as extractServerPropsWithCache,a as extractStaticParams,i as hasServerSideDataFetching};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use client";import{S as e,b as t}from"../regex-constants-DMuIAFub.mjs";import{t as n}from"../preload-components-5Y8ZOaFG.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+)
|
|
1
|
+
"use client";import{S as e,b as t}from"../regex-constants-DMuIAFub.mjs";import{t as n}from"../preload-components-5Y8ZOaFG.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]*$/;function m(){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:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
to { transform: rotate(360deg); }
|
|
4
4
|
}
|
|
5
|
-
`})]})}function
|
|
6
|
-
`),
|
|
7
|
-
`),t=await
|
|
5
|
+
`})]})}function h({children:h,initialPayload:g,onNavigate:_}){let[v,y]=s(g),[,b]=s(0),x=o({x:0,y:0}),S=o(new Map),C=o(null),[,w]=c(),T=o(0),E=o(new Map),D=o([]),O=o(null),k=o(0),[A,j]=s(null),M=()=>{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)})},N=()=>{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)})})},P=(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(),console.error(`[rari] HMR: Failure detected`,{type:t,details:n,filePath:r,consecutiveFailures:k.current,error:e.message,stack:e.stack,timestamp:new Date(i.timestamp).toISOString()}),k.current>=2&&j(i),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:hmr-failure`,{detail:i}))},F=()=>{setTimeout(()=>{window.location.reload()},1e3)},I=()=>{k.current>0&&(k.current=0)},L=e=>{if(!O.current)return!1;if(e===O.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 R(e,n,i,a,o){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[,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=K(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-${Math.random()}`,d={...l,children:l.children?R(l.children,n,i,a,o):void 0};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=K(l,n,i,a,o);return r.createElement(u,c?{...d,key:c}:d)}return e.map((e,t)=>{let s=R(e,n,i,a,o);return s?typeof s==`object`&&r.isValidElement(s)&&!s.key?r.cloneElement(s,{key:t}):s:null}).filter(Boolean)}return e}let z=o(new Set),B=o(new Map),V=o(new Map),H=o(new Map),U=o(new Map);function W(e){if(!U.current.has(e)){let t=new Promise(()=>{});U.current.set(e,t)}return U.current.get(e)}function G({contentRef:e}){let t=B.current,n=V.current,r=H.current;if(t.has(e))return U.current.delete(e),R(t.get(e),n,void 0,r,t);throw W(e)}function K(e,t,n,i,a){if(!e||typeof e!=`object`)return e;a&&(B.current=a),t&&(V.current=t),i&&(H.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);z.current.delete(c),o[s]=R(e,t,n,i,a)}else z.current.add(c),o[s]=r.createElement(G,{key:`lazy-${c}`,contentRef:c});else o[s]=c?R(c,t,n,i,a):void 0}else s===`dangerouslySetInnerHTML`?o[s]=e[s]:o[s]=R(e[s],t,n,i,a);return o}let q=(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}},J=async(e,i=!1)=>{try{let a=e.trim().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].trim();if(!n)continue;let r=n.indexOf(`:`);if(r===-1)continue;let p=n.substring(0,r);if(!t.test(p)){console.warn(`[rari] AppRouter: Invalid row ID (non-numeric), skipping line:`,n.substring(0,50));continue}let m=n.substring(r+1);try{if(m.startsWith(`"$S`)){let e=m.slice(1,-1);s.set(`$${p}`,e);continue}if(m.startsWith(`I[`)){let t=q(m.substring(1),`array`);if(!t){console.warn(`[rari] AppRouter: Could not sanitize import line, skipping:`,n.substring(0,80));continue}let r=JSON.parse(t);if(Array.isArray(r)&&r.length>=3){let[t,n,a]=r;o.set(`$L${p}`,{id:t,chunks:Array.isArray(n)?n:[n],name:a||`default`}),i&&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),i&&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&&Array.isArray(e)&&(e[0]===`$`?l=e:Array.isArray(e[0])&&e[0][0]===`$`&&(l=e.length===1?e[0]:e))}}catch(e){console.error(`[rari] AppRouter: Failed to parse RSC line:`,n,e)}}if(await n(o),i&&d!==null&&f!==null&&u.push({layoutPath:d,startLine:f,endLine:a.length-1,props:{}}),l&&Array.isArray(l)){if(l[0]===`$`)l=R(l,o,void 0,s,c);else if(Array.isArray(l[0])){let e=l.map(e=>Array.isArray(e)&&e[0]===`$`?R(e,o,void 0,s,c):e).filter(e=>e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||r.isValidElement(e));l=e.length===1?e[0]:e}}return{element:l,modules:o,symbols:s,wireFormat:e,layoutBoundaries:i?u:void 0}}catch(e){throw console.error(`[rari] AppRouter: Failed to parse RSC wire format:`,e),e}},Y=async(t,n)=>{let r=t||window.location.pathname,i=E.current.get(r);if(i)return i;let a=(async()=>{try{let t=(import.meta.env.RARI_SERVER_URL||window.location.origin).replace(e,``)+r+window.location.search,i=await fetch(t,{headers:{Accept:`text/x-component`,"Cache-Control":`no-cache`,Pragma:`no-cache`},cache:`no-store`,signal:n});if(!i.ok){let e=Error(`Failed to fetch RSC data: ${i.status} ${i.statusText}`);throw P(e,`fetch`,`HTTP ${i.status} when fetching ${t}`,window.location.pathname),e}let a=await i.text();if(L(a)&&v)return v;let o;try{o=await J(a,!1)}catch(e){let t=e instanceof Error?e:Error(String(e));throw P(t,`parse`,`Failed to parse RSC wire format: ${t.message}`,window.location.pathname),t}return y(o),O.current=a,I(),o}catch(e){throw e instanceof Error&&!e.message.includes(`Failed to fetch RSC data`)&&!e.message.includes(`Failed to parse`)&&P(e,`network`,`Network error: ${e.message}`,window.location.pathname),console.error(`[rari] AppRouter: Error fetching RSC payload:`,e),e}finally{E.current.delete(r)}})();return E.current.set(r,a),a};a(()=>{if(typeof window>`u`)return;let e=async e=>{let t=e.detail;T.current=t.navigationId,C.current=null,x.current={x:window.scrollX,y:window.scrollY},M(),w(async()=>{try{t.rscWireFormat?(y(await J(t.rscWireFormat,!1)),O.current=t.rscWireFormat,I()):t.isStreaming?C.current=[]:await Y(t.to,t.abortSignal),T.current===t.navigationId&&(b(e=>e+1),j(null),_&&_(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}})),k.current>=3&&F()}finally{t.options?.historyKey||requestAnimationFrame(()=>{t.options?.scroll!==!1&&window.scrollTo(0,0)})}})},t=async()=>{x.current={x:window.scrollX,y:window.scrollY},M();try{await Y(),b(e=>e+1),j(null)}catch(e){console.error(`[rari] AppRouter: HMR update failed:`,e),k.current>=3&&F()}finally{requestAnimationFrame(()=>{window.scrollTo(x.current.x,x.current.y),N()})}},n=async()=>{try{await Y(),b(e=>e+1),j(null)}catch(e){console.error(`[rari] AppRouter: RSC invalidation failed:`,e),k.current>=3&&F()}},r=async()=>{try{await Y(),j(null)}catch(e){console.error(`[rari] AppRouter: Manifest update failed:`,e),k.current>=3&&F()}},i=async e=>{let t=e.detail.rscRow;if(!(!t||!t.trim())){C.current||=[],C.current.push(t);try{let e=C.current.join(`
|
|
7
|
+
`),t=await J(e,!1);C.current.length<=2&&e.includes(`~boundaryId`)?(y(t),b(e=>e+1)):w(()=>{y(t),b(e=>e+1)})}catch(e){console.error(`[rari] AppRouter: Failed to parse streaming RSC row:`,e)}}};return window.addEventListener(`rari:navigate`,e),window.addEventListener(`rari:app-router-rerender`,t),window.addEventListener(`rari:rsc-invalidate`,n),window.addEventListener(`rari:app-router-manifest-updated`,r),window.addEventListener(`rari:rsc-row`,i),()=>{window.removeEventListener(`rari:navigate`,e),window.removeEventListener(`rari:app-router-rerender`,t),window.removeEventListener(`rari:rsc-invalidate`,n),window.removeEventListener(`rari:app-router-manifest-updated`,r),window.removeEventListener(`rari:rsc-row`,i)}},[_]);let X=()=>{window.location.reload()},Z=()=>{j(null)},Q=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},$=h;return v?.element&&($=Q(v.element)||v.element),Array.isArray($)&&$.length===1&&r.isValidElement($[0])&&($=$[0]),$&&typeof $==`object`&&!r.isValidElement($)&&(console.error(`[rari] AppRouter: Invalid content to render:`,$),$=h),d(l,{children:[A&&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:[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.`]}),u(`div`,{style:{marginBottom:`16px`,fontSize:`12px`,opacity:.8,fontFamily:`monospace`},children:A.details}),d(`div`,{style:{marginBottom:`12px`,fontSize:`12px`,opacity:.7},children:[`Consecutive failures:`,` `,k.current,` `,`/`,` `,3]}),d(`div`,{style:{display:`flex`,gap:`8px`},children:[u(`button`,{onClick:X,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:Z,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(m,{}),children:$})]})}export{h as AppRouterProvider};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{_ as e,d as t,g as n,h as r,m as i,n as a,p as o,y as s}from"../regex-constants-DMuIAFub.mjs";import{t as c}from"../get-client-component-CpMI09nb.mjs";import"../preload-components-5Y8ZOaFG.mjs";import{createFromFetch as l,createFromReadableStream as u}from"./react-server-dom-rari-client.mjs";import{Suspense as d,cloneElement as f,createElement as p,isValidElement as m,useEffect as h,useRef as g,useState as _}from"react";import*as v from"react-dom/client";function y(){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`].bufferedEvents||(window[`~rari`].bufferedEvents=[]),window[`~rari`].boundaryModules||(window[`~rari`].boundaryModules=new Map),window[`~rari`].pendingBoundaryHydrations||(window[`~rari`].pendingBoundaryHydrations=new Map),globalThis[`~rari`].processBoundaryUpdate=function(t,s,c){let l=document.querySelector(`[data-boundary-id="${t}"]`);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(t,{content:p,element:l,rowId:c}),globalThis[`~rari`].hydrateClientComponents){let e=globalThis[`~rari`].hydrateClientComponents;e(t,p,l)}return}function h(t){let s=t=>t.replace(o,`&`).replace(n,`<`).replace(r,`>`).replace(e,`"`).replace(i,`'`);if(!t)return``;if(typeof t==`string`||typeof t==`number`)return s(String(t));if(Array.isArray(t)){if(t.length>=4&&t[0]===`$`){let[,e,,n]=t,r=null,i=``,o=``;if(n){for(let[e,t]of Object.entries(n))if(e===`dangerouslySetInnerHTML`&&t&&typeof t==`object`&&`__html`in t)r=t.__html;else if(e!==`children`&&e!==`~boundaryId`){let n=e===`className`?`class`:e;if(e===`style`&&typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${e.replace(a,`$1-$2`).toLowerCase()}:${String(t)}`).join(`;`);o+=` style="${s(e)}"`}else typeof t==`string`||typeof t==`number`?o+=` ${n}="${s(String(t))}"`:typeof t==`boolean`&&t&&(o+=` ${n}`)}r===null&&n.children&&(i=h(n.children))}return`<${e}${o}>${r===null?i:r}</${e}>`}return t.map(h).join(``)}return``}let g=h(p);g&&(l.innerHTML=g,l.classList.add(`rari-boundary-resolved`))}catch(e){console.error(`[rari] Error processing boundary update:`,e)}window.dispatchEvent(new CustomEvent(`rari:boundary-resolved`,{detail:{boundaryId:t,rscRow:s,rowId:c,element:l}}))}};let t=window,s=globalThis;t[`~rari`].bufferedEvents&&t[`~rari`].bufferedEvents.length>0&&(t[`~rari`].bufferedEvents.forEach(e=>{let{boundaryId:t,rscRow:n,rowId:r}=e;s[`~rari`].processBoundaryUpdate?.(t,n,r)}),t[`~rari`].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 b(e,n,r){let i=r===`default`?e.name||n.split(`/`).pop()?.replace(t,``)||`DefaultComponent`:r,a=i,o={id:a,path:n,type:`client`,component:e,registered:!0};globalThis[`~clientComponents`][a]=o,globalThis[`~clientComponents`][n]=o,globalThis[`~clientComponentPaths`][n]=a,globalThis[`~clientComponentNames`][i]=a,e&&(e[`~isClientComponent`]=!0,e[`~clientComponentId`]=a),typeof window<`u`&&fetch(`/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:a,file_path:n,export_name:r})}).catch(e=>{console.error(`[rari] Failed to register client component with server:`,e)})}function x(e){return c(e)}function S(){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 C=l,w=u,T=null;async function E(){return T||(T=(async()=>{try{return C=l,w=u,typeof w!=`function`&&(w=null),typeof C!=`function`&&(C=null),v}catch(e){return console.error(`Failed to load react-dom/client RSC functions:`,e),C=null,w=null,null}})(),T)}const D=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()}async fetchServerComponent(e,t={}){let n=typeof window<`u`&&window[`~rscRefreshCounters`]&&window[`~rscRefreshCounters`][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 E();let n=(()=>{let e=[`/_rari/stream`];try{if(typeof window<`u`&&(window.location.hostname===`localhost`||window.location.hostname===`127.0.0.1`)){let t=y();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,g=e=>{if(!p)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>=3&&e[0]===`$`){let[,t,n,r]=e;if(t===`react.suspense`||t===`suspense`)return p(d,{fallback:g(r?.fallback)||null},r?.children?g(r.children):null);let i=r?{...r}:{};if(r?.children){let e=g(r.children);Array.isArray(e)?i.children=e.map((e,t)=>m(e)?f(e,{key:e.key??t}):e):i.children=e}if(typeof t==`string`){if(t.startsWith(`$L`)){let e=l.get(t);if(e){let t=x(`${e.id}#${e.name||`default`}`);if(t)return p(t,n?{...i,key:n}:i)}return i&&i.children?i.children:null}if(t.includes(`.tsx#`)||t.includes(`.jsx#`)){let e=x(t);return e?p(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`]),p(t,n?{...i,key:n}:i)}else console.error(`Unknown RSC element type:`,t)}return e.map(e=>g(e))}return typeof e==`object`?(console.error(`Unexpected object in RSC conversion:`,e),null):e},v=null,b=new Map,S=``,C=null,w=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);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=g(i.children);b.set(e,t),C&&C.updateBoundary(e,t);continue}}}if(!v){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&&(v=g(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]=_(0);h(()=>(C={updateBoundary:(t,n)=>{b.set(t,n),e(e=>e+1)},updateRoot:()=>{e(e=>e+1)}},()=>{C=null}),[]);let t=e=>{if(!e)return null;if(m(e)){let n=e.props,r=n?.[`~boundaryId`];if(n&&r){let e=b.get(r);if(e)return e}if(n&&n.children){let r=t(n.children);if(r!==n.children)return f(e,{...n,children:r})}return e}return Array.isArray(e)?e.map(e=>t(e)):e};return t(v)};return w(),{"~isRscResponse":!0,"~rscPromise":Promise.resolve(p(T)),readRoot(){return Promise.resolve(p(T))}}}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 E(),C)try{let t=C(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=x(n)||(({children:e,...t})=>p(`div`,{...t,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},p(`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=x(`${e.id}#${e.name}`)||(({children:t,...r})=>p(`div`,{...r,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},p(`small`,{style:{color:`#c00`}},`Missing Client Component: ${e.name} (${e.id})`),t)))}let o=i?this.processPropsRecursively(i,t):{};return p(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 O({error:e,details:t}){return p(`div`,{className:`rsc-error`,style:{padding:`16px`,backgroundColor:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`,margin:`8px 0`,fontFamily:`monospace`}},p(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`}},`RSC Error`),p(`p`,{style:{margin:`0 0 8px 0`}},e),t&&p(`details`,{style:{marginTop:`8px`}},p(`summary`,{style:{cursor:`pointer`}},`Error Details`),p(`pre`,{style:{fontSize:`12px`,overflow:`auto`,backgroundColor:`#f5f5f5`,padding:`8px`}},JSON.stringify(t,null,2))))}function k({componentId:e,props:t,fallback:n}){let[r,i]=_({data:null,loading:!0,error:null}),a=JSON.stringify(t),o=g(a);h(()=>{let n=!0;return o.current!==a&&(i({data:null,loading:!0,error:null}),o.current=a),D.fetchServerComponent(e,t).then(e=>{n&&i({data:e,loading:!1,error:null})}).catch(e=>{n&&i({data:null,loading:!1,error:e})}),()=>{n=!1}},[e,a]);let{data:s,loading:c,error:l}=r;return c?n||null:l?p(O,{error:`Error loading component`,details:{message:l.message,componentId:e}}):s?s[`~isRscResponse`]?p(d,{fallback:n||null},s.readRoot()):s:p(O,{error:`No data received for component: ${e}`,details:{componentId:e,dataType:typeof s,hasData:!!s}})}function A(e){let t=0;if(typeof window<`u`){let n=window;n[`~rscRefreshCounters`]=n[`~rscRefreshCounters`]||{},n[`~rscRefreshCounters`][e]===void 0&&(n[`~rscRefreshCounters`][e]=0),t=n[`~rscRefreshCounters`][e]}let n=n=>{let[r,i]=_(t);return h(()=>{let t=t=>{let n=t.detail;if(n&&n.filePath&&M(n.filePath)&&(D.clearCache(),typeof window<`u`)){let t=window;t[`~rscRefreshCounters`]||={},t[`~rscRefreshCounters`][e]=(t[`~rscRefreshCounters`][e]||0)+1,i(t[`~rscRefreshCounters`][e])}};return typeof window<`u`&&window.addEventListener(`rari:rsc-invalidate`,t),()=>{typeof window<`u`&&window.removeEventListener(`rari:rsc-invalidate`,t)}},[]),p(d,{fallback:null},p(k,{key:`${e}-${r}`,componentId:e,props:n,fallback:null}))};return n.displayName=`ServerComponent(${e})`,function(e){return p(n,e)}}function j(e,t){return D.fetchServerComponent(e,t)}function M(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&&M(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&&M(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&&(D.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=`${y()}/_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){D.clearCache();return}let t=[];for(let n of D.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)D.componentCache.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=`${y()}/_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(D.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 N=class{overlay;currentError;constructor(){this.overlay=null,this.currentError=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)}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)}updateOverlay(e){if(!this.overlay)return;let t=e.filePath?`<div style="margin-bottom: 1rem; padding: 0.75rem; background: rgba(0, 0, 0, 0.2); border-radius: 0.375rem; font-family: monospace; font-size: 0.875rem;"><strong>File:</strong> ${this.escapeHtml(e.filePath)}</div>`:``,n=e.stack?`<details style="margin-top: 1rem; cursor: pointer;"><summary style="font-weight: 600; margin-bottom: 0.5rem; user-select: none;">Stack Trace</summary><pre style="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;">${this.escapeHtml(e.stack)}</pre></details>`:``;this.overlay.innerHTML=`<div style="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);"><div style="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;"><div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem;"><div style="display: flex; align-items: center; gap: 0.75rem;"><svg style="width: 2rem; height: 2rem; color: #ef4444;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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"></path></svg><h1 style="margin: 0; font-size: 1.5rem; font-weight: 700; color: #ef4444;">Build Error</h1></div><button onclick="document.getElementById('rari-hmr-error-overlay').remove()" style="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;" onmouseover="this.style.background='rgba(255,255,255,0.1)'; this.style.color='#e0e0e0'" onmouseout="this.style.background='transparent'; this.style.color='#9ca3af'">×</button></div>${t}<div style="margin-bottom: 1.5rem;"><h2 style="margin: 0 0 0.75rem 0; font-size: 1rem; font-weight: 600; color: #fca5a5;">Error Message:</h2><pre style="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;">${this.escapeHtml(e.message)}</pre></div>${n}<div style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #374151; display: flex; gap: 0.75rem; align-items: center;"><button onclick="window.location.reload()" style="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;" onmouseover="this.style.background='#dc2626'" onmouseout="this.style.background='#ef4444'">Reload Page</button><button onclick="document.getElementById('rari-hmr-error-overlay').remove()" style="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;" onmouseover="this.style.background='#4b5563'" onmouseout="this.style.background='#374151'">Dismiss</button><span style="margin-left: auto; font-size: 0.75rem; color: #9ca3af;">${new Date(e.timestamp).toLocaleTimeString()}</span></div></div></div>`}escapeHtml(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}};let P=null;function F(){return P||=new N,P}if(import.meta.hot){let e=F();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{O as RscErrorComponent,S as createClientModuleMap,A as createServerComponentWrapper,j as fetchServerComponent,x as getClientComponent,b as registerClientComponent,D as rscClient};
|
|
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);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=g(i.children);b.set(e,t),C&&C.updateBoundary(e,t);continue}}}if(!v){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&&(v=g(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]=_(0);h(()=>(C={updateBoundary:(t,n)=>{b.set(t,n),e(e=>e+1)},updateRoot:()=>{e(e=>e+1)}},()=>{C=null}),[]);let t=e=>{if(!e)return null;if(m(e)){let n=e.props,r=n?.[`~boundaryId`];if(n&&r){let e=b.get(r);if(e)return e}if(n&&n.children){let r=t(n.children);if(r!==n.children)return f(e,{...n,children:r})}return e}return Array.isArray(e)?e.map(e=>t(e)):e};return t(v)};return w(),{"~isRscResponse":!0,"~rscPromise":Promise.resolve(p(T)),readRoot(){return Promise.resolve(p(T))}}}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 E(),C)try{let t=C(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=x(n)||(({children:e,...t})=>p(`div`,{...t,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},p(`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=x(`${e.id}#${e.name}`)||(({children:t,...r})=>p(`div`,{...r,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},p(`small`,{style:{color:`#c00`}},`Missing Client Component: ${e.name} (${e.id})`),t)))}let o=i?this.processPropsRecursively(i,t):{};return p(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 O({error:e,details:t}){return p(`div`,{className:`rsc-error`,style:{padding:`16px`,backgroundColor:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`,margin:`8px 0`,fontFamily:`monospace`}},p(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`}},`RSC Error`),p(`p`,{style:{margin:`0 0 8px 0`}},e),t&&p(`details`,{style:{marginTop:`8px`}},p(`summary`,{style:{cursor:`pointer`}},`Error Details`),p(`pre`,{style:{fontSize:`12px`,overflow:`auto`,backgroundColor:`#f5f5f5`,padding:`8px`}},JSON.stringify(t,null,2))))}function k({componentId:e,props:t,fallback:n}){let[r,i]=_({data:null,loading:!0,error:null}),a=JSON.stringify(t),o=g(a);h(()=>{let n=!0;return o.current!==a&&(i({data:null,loading:!0,error:null}),o.current=a),D.fetchServerComponent(e,t).then(e=>{n&&i({data:e,loading:!1,error:null})}).catch(e=>{n&&i({data:null,loading:!1,error:e})}),()=>{n=!1}},[e,a]);let{data:s,loading:c,error:l}=r;return c?n||null:l?p(O,{error:`Error loading component`,details:{message:l.message,componentId:e}}):s?s[`~isRscResponse`]?p(d,{fallback:n||null},s.readRoot()):s:p(O,{error:`No data received for component: ${e}`,details:{componentId:e,dataType:typeof s,hasData:!!s}})}function A(e){let t=0;if(typeof window<`u`){let n=window;n[`~rscRefreshCounters`]=n[`~rscRefreshCounters`]||{},n[`~rscRefreshCounters`][e]===void 0&&(n[`~rscRefreshCounters`][e]=0),t=n[`~rscRefreshCounters`][e]}let n=n=>{let[r,i]=_(t);return h(()=>{let t=t=>{let n=t.detail;if(n&&n.filePath&&M(n.filePath)&&(D.clearCache(),typeof window<`u`)){let t=window;t[`~rscRefreshCounters`]||={},t[`~rscRefreshCounters`][e]=(t[`~rscRefreshCounters`][e]||0)+1,i(t[`~rscRefreshCounters`][e])}};return typeof window<`u`&&window.addEventListener(`rari:rsc-invalidate`,t),()=>{typeof window<`u`&&window.removeEventListener(`rari:rsc-invalidate`,t)}},[]),p(d,{fallback:null},p(k,{key:`${e}-${r}`,componentId:e,props:n,fallback:null}))};return n.displayName=`ServerComponent(${e})`,function(e){return p(n,e)}}function j(e,t){return D.fetchServerComponent(e,t)}function M(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&&M(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&&M(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&&(D.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=`${y()}/_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){D.clearCache();return}let t=[];for(let n of D.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)D.componentCache.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=`${y()}/_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(D.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 N=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;for(;this.overlay.firstChild;)this.overlay.removeChild(this.overlay.firstChild);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 P=null;function F(){return P||=new N,P}if(import.meta.hot){let e=F();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{O as RscErrorComponent,S as createClientModuleMap,A as createServerComponentWrapper,j as fetchServerComponent,x as getClientComponent,b as registerClientComponent,D as rscClient};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rari",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.10.
|
|
4
|
+
"version": "0.10.2",
|
|
5
5
|
"description": "Runtime Accelerated Rendering Infrastructure (rari)",
|
|
6
6
|
"author": "Ryan Skinner",
|
|
7
7
|
"license": "MIT",
|
|
@@ -102,17 +102,17 @@
|
|
|
102
102
|
"rolldown": "1.0.0-rc.2"
|
|
103
103
|
},
|
|
104
104
|
"optionalDependencies": {
|
|
105
|
-
"rari-darwin-arm64": "0.10.
|
|
106
|
-
"rari-darwin-x64": "0.10.
|
|
107
|
-
"rari-linux-arm64": "0.10.
|
|
108
|
-
"rari-linux-x64": "0.10.
|
|
109
|
-
"rari-win32-x64": "0.10.
|
|
105
|
+
"rari-darwin-arm64": "0.10.2",
|
|
106
|
+
"rari-darwin-x64": "0.10.2",
|
|
107
|
+
"rari-linux-arm64": "0.10.2",
|
|
108
|
+
"rari-linux-x64": "0.10.2",
|
|
109
|
+
"rari-win32-x64": "0.10.2"
|
|
110
110
|
},
|
|
111
111
|
"devDependencies": {
|
|
112
112
|
"@types/node": "^25.3.0",
|
|
113
113
|
"@types/react": "^19.2.14",
|
|
114
114
|
"@types/react-dom": "^19.2.3",
|
|
115
|
-
"@typescript/native-preview": "^7.0.0-dev.
|
|
115
|
+
"@typescript/native-preview": "^7.0.0-dev.20260221.1",
|
|
116
116
|
"oxlint": "^1.49.0",
|
|
117
117
|
"rolldown-vite": "^7.3.1",
|
|
118
118
|
"tsdown": "^0.20.3",
|