rari 0.10.0 → 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 +4 -2
- package/dist/client.mjs +2 -2
- package/dist/{index-DuCX6G_W.d.mts → index-Dc4oQSkA.d.mts} +5 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/mdx.mjs +1 -1
- package/dist/preload-components-5Y8ZOaFG.mjs +1 -0
- package/dist/regex-constants-DMuIAFub.mjs +1 -0
- package/dist/routes-DXBE0bwy.mjs +1 -0
- package/dist/runtime/AppRouterProvider.mjs +4 -4
- package/dist/runtime/entry-client.mjs +2 -2
- package/dist/runtime/react-server-dom-rari-client.mjs +2 -2
- package/dist/runtime/rsc-client-runtime.mjs +2 -2
- package/dist/{server-build-emJwCUjS.mjs → server-build-BaEm53O_.mjs} +9 -9
- package/dist/{server-config-BLpfK714.d.mts → server-config-Bi4AvErE.d.mts} +5 -1
- package/dist/{sitemap-generator-Di-7pmiz.mjs → sitemap-generator-D_gTjklw.mjs} +1 -1
- package/dist/vite-Dm2UZbFt.mjs +79 -0
- package/dist/vite.d.mts +2 -2
- package/dist/vite.mjs +1 -1
- package/package.json +9 -9
- package/dist/preload-components-TyCxVZPF.mjs +0 -1
- package/dist/regex-constants-BM4Vd-_c.mjs +0 -1
- package/dist/routes-DEvXO96u.mjs +0 -1
- package/dist/vite-BTJjUXqs.mjs +0 -79
package/dist/client.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as RouteSegmentType, B as hasServerSideDataFetching, C as LayoutEntry, D as NotFoundEntry, F as clearPropsCacheForComponent, I as extractMetadata, L as extractServerProps, M as ServerSidePropsResult, N as StaticParamsResult, P as clearPropsCache, R as extractServerPropsWithCache, S as GenerateStaticParams, T as LoadingEntry, _ as AppRouteManifest, a as ServerSpamBlockerConfig, b as ErrorProps, c as ErrorBoundary, d as NotFound, f as RuntimeClient, g as AppRouteEntry, h as createLoadingBoundary, i as ServerRateLimitConfig, j as MetadataResult, k as RouteSegment, l as HttpRuntimeClient, m as createHttpRuntimeClient, o as DefaultError, p as createErrorBoundary, r as ServerConfig, s as DefaultLoading, t as ServerCSPConfig, u as LoadingSpinner, v as AppRouteMatch, x as GenerateMetadata, y as ErrorEntry, z as extractStaticParams } from "./server-config-Bi4AvErE.mjs";
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
import { Component, ErrorInfo, ReactNode } from "react";
|
|
4
4
|
import * as react_jsx_runtime0 from "react/jsx-runtime";
|
|
@@ -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,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as AppRouteManifest, a as ServerSpamBlockerConfig, i as ServerRateLimitConfig, n as ServerCacheControlConfig, t as ServerCSPConfig } from "./server-config-Bi4AvErE.mjs";
|
|
2
2
|
import { Plugin, UserConfig } from "rolldown-vite";
|
|
3
3
|
|
|
4
4
|
//#region src/fetch-cache.d.ts
|
|
@@ -129,6 +129,7 @@ interface ServerBuildOptions {
|
|
|
129
129
|
csp?: ServerCSPConfig;
|
|
130
130
|
rateLimit?: ServerRateLimitConfig;
|
|
131
131
|
spamBlocker?: ServerSpamBlockerConfig;
|
|
132
|
+
cacheControl?: ServerCacheControlConfig;
|
|
132
133
|
}
|
|
133
134
|
//#endregion
|
|
134
135
|
//#region src/vite/index.d.ts
|
|
@@ -179,6 +180,9 @@ interface RariOptions {
|
|
|
179
180
|
spamBlocker?: {
|
|
180
181
|
enabled?: boolean;
|
|
181
182
|
};
|
|
183
|
+
cacheControl?: {
|
|
184
|
+
routes: Record<string, string>;
|
|
185
|
+
};
|
|
182
186
|
}
|
|
183
187
|
declare function defineRariOptions(config: RariOptions): RariOptions;
|
|
184
188
|
declare function rari(options?: RariOptions): Plugin[];
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { _ as SitemapVideo, a as generateAppRouteManifest, c as ApiResponse, d as RouteHandler, f as Robots, g as SitemapImage, h as SitemapEntry, i as rariRouter, l as ApiRouteHandlers, m as Sitemap, n as defineRariOptions, o as ProxyPluginOptions, p as RobotsRule, r as rari, s as rariProxy, t as defineRariConfig, u as RouteContext } from "./index-
|
|
1
|
+
import { A as RouteSegmentType, B as hasServerSideDataFetching, C as LayoutEntry, D as NotFoundEntry, E as Metadata, F as clearPropsCacheForComponent, I as extractMetadata, L as extractServerProps, M as ServerSidePropsResult, N as StaticParamsResult, O as PageProps, P as clearPropsCache, R as extractServerPropsWithCache, S as GenerateStaticParams, T as LoadingEntry, _ as AppRouteManifest, a as ServerSpamBlockerConfig, b as ErrorProps, f as RuntimeClient, g as AppRouteEntry, i as ServerRateLimitConfig, j as MetadataResult, k as RouteSegment, l as HttpRuntimeClient, m as createHttpRuntimeClient, r as ServerConfig, t as ServerCSPConfig, v as AppRouteMatch, w as LayoutProps, x as GenerateMetadata, y as ErrorEntry, z as extractStaticParams } from "./server-config-Bi4AvErE.mjs";
|
|
2
|
+
import { _ as SitemapVideo, a as generateAppRouteManifest, c as ApiResponse, d as RouteHandler, f as Robots, g as SitemapImage, h as SitemapEntry, i as rariRouter, l as ApiRouteHandlers, m as Sitemap, n as defineRariOptions, o as ProxyPluginOptions, p as RobotsRule, r as rari, s as rariProxy, t as defineRariConfig, u as RouteContext } from "./index-Dc4oQSkA.mjs";
|
|
3
3
|
import { a as ProxyModule, c as RariURL, i as ProxyMatcher, l as RequestCookies, n as ProxyConfig, o as ProxyResult, r as ProxyFunction, s as RariFetchEvent, t as CookieOptions, u as ResponseCookies } from "./types-BQ-op_Tc.mjs";
|
|
4
4
|
import { RariRequest } from "./proxy/RariRequest.mjs";
|
|
5
5
|
import { RariResponse } from "./proxy/RariResponse.mjs";
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"./vite-
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./vite-Dm2UZbFt.mjs";import{RariRequest as o}from"./proxy/RariRequest.mjs";import{RariResponse as s}from"./proxy/RariResponse.mjs";import{c,d as l,f as u,g as d,h as f,i as p,m,p as h,u as g}from"./runtime-client-Bg4V1Ksp.mjs";import"./regex-constants-DMuIAFub.mjs";import{t as _}from"./routes-DXBE0bwy.mjs";import"./constants-DZAg-dr0.mjs";import"./server-build-BaEm53O_.mjs";import"./vite.mjs";export{r as ApiResponse,p as HttpRuntimeClient,o as RariRequest,s as RariResponse,g as clearPropsCache,l as clearPropsCacheForComponent,c as createHttpRuntimeClient,a as defineRariConfig,n as defineRariOptions,u as extractMetadata,h as extractServerProps,m as extractServerPropsWithCache,f as extractStaticParams,_ as generateAppRouteManifest,d as hasServerSideDataFetching,i as rari,e as rariProxy,t as rariRouter};
|
package/dist/mdx.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as e}from"./regex-constants-
|
|
1
|
+
import{d as e}from"./regex-constants-DMuIAFub.mjs";import{registerClientComponent as t,registerClientReference as n}from"./runtime/react-server-dom-shim.mjs";function r(r,i,a=`default`){let o=`${i}#${a}`;if(t(r,i,a),typeof globalThis<`u`){let t=globalThis;t[`~clientComponents`]||={};let n=i.replace(e,``).split(`/`).pop()||a,s={id:a===`default`?n:a,path:i,type:`client`,component:r,registered:!0};t[`~clientComponents`][o]=s,t[`~clientComponents`][n]=s,t[`~clientComponents`][i]=s}function s(){throw Error(`Attempted to call ${a}() from the server but ${a} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`)}return n(s,i,a)}function i(e){let t={};for(let[n,{component:i,id:a,exportName:o=`default`}]of Object.entries(e))t[n]=r(i,a,o);return t}export{r as createMDXClientReference,i as createMDXClientReferences};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e,w as t}from"./regex-constants-DMuIAFub.mjs";async function n(n){let r=globalThis[`~clientComponents`]||{},i=[];for(let[,a]of n){let n=[a.id,`${a.id}#${a.name||`default`}`,a.id.replace(t,``),a.id.replace(e,`/`)];for(let e of n){let t=r[e];if(t?.loader&&!t.component&&!t.loading){t.loading=!0,t.loadPromise=t.loader().then(e=>{t.component=e.default||e,t.registered=!0,t.loading=!1}).catch(n=>{t.loading=!1,t.loadPromise=void 0,console.error(`[rari] Failed to preload component ${e}:`,n)}),i.push(t.loadPromise);break}}}i.length>0&&await Promise.all(i)}export{n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=/\.(?:tsx?|jsx?)$/,t=/^[A-Z]:\\/i,n=/\\/g,r=/[/\\]/,i=/\/$/,a=/^src\//,o=/^file:\/\//,s=/^https?:\/\//,c={AMPERSAND:/&/g,LT:/</g,GT:/>/g,QUOTE:/"/g,APOS:/'/g},l=c.AMPERSAND,u=c.LT,d=c.GT,f=c.QUOTE,p=c.APOS,m=l,h=u,g=d,_=f,v=p,y=l,b=u,x=d,S=f,C=p,w=/[^\w/-]/g,T=/^\d+$/,E=/([a-z])([A-Z])/g,D=/export\s+default\s+/,O=/^export\s+default\s+function\s+(\w+)/gm,k=/^export\s+default\s+async\s+function\s+(\w+)/gm,A=/^export\s+default\s+(\w+);?\s*$/gm,j=/^export\s*\{\s*(\w+)\s+as\s+default\s*\};?\s*$/gm,M=/^export\s+(?:async\s+)?function\s+(\w+)/gm,N=/export\s+(?:function|const|class)\s+(\w+)/,P=/\.[^.]*$/,F=/\r?\n/,I=/['"]/g;export{b as A,I as C,y as D,t as E,C as O,i as S,e as T,_,j as a,T as b,D as c,P as d,o as f,h as g,g as h,k as i,S as j,x as k,M as l,v as m,E as n,O as o,m as p,w as r,A as s,n as t,N as u,s as v,a as w,r as x,F as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{t,x as n}from"./regex-constants-DMuIAFub.mjs";import{promises as r}from"node:fs";import i from"node:path";var a=e({generateAppRouteManifest:()=>f});const o={PAGE:`page`,LAYOUT:`layout`,LOADING:`loading`,ERROR:`error`,NOT_FOUND:`not-found`,TEMPLATE:`template`,DEFAULT:`default`,ROUTE:`route`,OG_IMAGE:`opengraph-image`,TWITTER_IMAGE:`twitter-image`,ICON:`icon`,APPLE_ICON:`apple-icon`},s={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},c=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,l=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,u=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var d=class{appDir;extensions;verbose;constructor(e){this.appDir=i.resolve(e.appDir),this.extensions=e.extensions||[`.tsx`,`.jsx`,`.ts`,`.js`],this.verbose=e.verbose||!1}async generateManifest(){this.verbose&&console.warn(`[rari] Router: Scanning app directory: ${this.appDir}`);let e=[],t=[],n=[],r=[],i=[],a=[],o=[];return await this.scanDirectory(``,e,t,n,r,i,a,o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} API routes`),console.warn(`[rari] Router: Found ${o.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,apiRoutes:this.sortApiRoutes(a),ogImages:o,generated:new Date().toISOString()}}async scanDirectory(e,t,n,a,o,s,c,l){let u=i.join(this.appDir,e),d;try{d=await r.readdir(u)}catch{return}let f=[],p=[];for(let e of d){let t=i.join(u,e),n=await r.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&p.push(e):n.isFile()&&f.push(e)}await this.processSpecialFiles(e,f,t,n,a,o,s,c,l);for(let r of p){let u=e?i.join(e,r):r;await this.scanDirectory(u,t,n,a,o,s,c,l)}}async processSpecialFiles(e,t,n,a,s,u,d,f,p){let m=this.pathToRoute(e),h=this.findFile(t,o.PAGE);if(h){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:m,filePath:i.join(e,h),segments:t,params:r,isDynamic:r.length>0})}let g=this.findFile(t,o.LAYOUT);if(g){let t=this.getParentPath(e);a.push({path:m,filePath:i.join(e,g),parentPath:t?this.pathToRoute(t):void 0})}let _=this.findFile(t,o.LOADING);if(_){let t=this.generateComponentId(m,`loading`);s.push({path:m,filePath:i.join(e,_),componentId:t})}let v=this.findFile(t,o.ERROR);v&&u.push({path:m,filePath:i.join(e,v)});let y=this.findFile(t,o.NOT_FOUND);y&&d.push({path:m,filePath:i.join(e,y)});let b=this.findFile(t,o.OG_IMAGE);if(b){let t=i.join(e,b),n=i.join(this.appDir,t),a,o,s;try{let e=await r.readFile(n,`utf-8`),t=e.match(c);t&&(a=Number.parseInt(t[1],10),o=Number.parseInt(t[2],10));let i=e.match(l);i&&(s=i[1])}catch{}p.push({path:m,filePath:t,width:a,height:o,contentType:s})}let x=this.findFile(t,o.ROUTE);if(x){let t=await this.processApiRouteFile(e,x);f.push(t)}}findFile(e,t){for(let n of this.extensions){let r=`${t}${n}`;if(e.includes(r))return r}}pathToRoute(e){return e?`/${e.replace(t,`/`).split(`/`).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?`[[...${e.match(s.OPTIONAL_CATCH_ALL)[1]}]]`:s.CATCH_ALL.test(e)?`[...${e.match(s.CATCH_ALL)[1]}]`:s.DYNAMIC.test(e)?`[${e.match(s.DYNAMIC)[1]}]`:e).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(n).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?{type:`optional-catch-all`,value:e,param:e.match(s.OPTIONAL_CATCH_ALL)[1]}:s.CATCH_ALL.test(e)?{type:`catch-all`,value:e,param:e.match(s.CATCH_ALL)[1]}:s.DYNAMIC.test(e)?{type:`dynamic`,value:e,param:e.match(s.DYNAMIC)[1]}:{type:`static`,value:e}):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(n).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=i.join(this.appDir,e),n=await r.readFile(t,`utf-8`),a=[];for(let e of u){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),r=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||r.test(n))&&a.push(e)}return a}async processApiRouteFile(e,t){let n=i.join(e,t),r=this.pathToRoute(e),a=this.parseRouteSegments(e),o=this.extractParams(a),s=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:a,params:o,isDynamic:o.length>0,methods:s}}};async function f(e,t={}){return new d({appDir:e,...t}).generateManifest()}export{a as n,f as t};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use client";import{
|
|
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,8 +1,8 @@
|
|
|
1
|
-
import"../regex-constants-
|
|
1
|
+
import"../regex-constants-DMuIAFub.mjs";import{n as e,t}from"../get-client-component-CpMI09nb.mjs";import*as n from"react";import{Suspense as r}from"react";import{ClientRouter as i}from"rari/client";import{createRoot as a}from"react-dom/client";import{AppRouterProvider as o}from"virtual:app-router-provider";import{createFromReadableStream as s}from"virtual:react-server-dom-rari-client.ts";import"virtual:rsc-integration.ts";function c(){return globalThis[`~rari`]}function l(){return globalThis}function u(){return window}function d(){return{moduleMap:new Proxy({},{get(e,t){return new Proxy({},{get(e,n){return{id:`${String(t)}#${String(n)}`,chunks:[],name:String(n)}}})}}),moduleLoading:new Proxy({},{get(e,t){return new Proxy({},{get(e,n){return async()=>{try{let e=String(t),r=String(n),i=`${e}#${r}`;if(l()[`~clientComponents`]?.[i]?.component)return l()[`~clientComponents`][i].component;if(l()[`~clientComponents`]?.[e]?.component){let t=l()[`~clientComponents`][e].component;return r===`default`?t:t?.[r]}let a=l()[`~clientComponents`]?.[i]||l()[`~clientComponents`]?.[e];if(a?.loader){a.loadPromise||=(a.loading=!0,a.loader().then(e=>(a.component=e.default||e,a.registered=!0,a.loading=!1,e)).catch(t=>{throw a.loading=!1,a.loadPromise=void 0,console.error(`[rari] Failed to lazy load ${e}#${r}:`,t),t}));let t=await a.loadPromise,n=t.default||t;return r===`default`?n:n?.[r]??n}return console.warn(`[rari] Module ${e}#${r} not found in client components registry`),null}catch(e){return console.error(`[rari] Failed to load ${String(t)}#${String(n)}:`,e),null}}}})}})}}c()===void 0&&(globalThis[`~rari`]={}),c().AppRouterProvider=o,c().ClientRouter=i,c().getClientComponent=t;async function f(t){try{await e(t)}catch(e){console.error(`[rari] Failed to preload component ${t}:`,e)}}
|
|
2
2
|
/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */
|
|
3
3
|
c().preloadClientComponent=f,l()[`~clientComponents`]===void 0&&(globalThis[`~clientComponents`]={}),l()[`~clientComponentPaths`]===void 0&&(globalThis[`~clientComponentPaths`]={});
|
|
4
4
|
/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */
|
|
5
|
-
function p(){c().hydrateClientComponents||(c().hydrateClientComponents=function(e,t,r){let i=u()[`~rari`].boundaryModules||new Map;function o(e){if(!e)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t,r,a]=e,s=a?{...a}:{};if(a?.children&&(s.children=o(a.children)),s[`~boundaryId`]&&delete s[`~boundaryId`],typeof t==`string`){if(t.startsWith(`$L`)){let e=i.get(t);if(e){let t=`${e.id}#${e.name||`default`}`,i=null,a=l()[`~clientComponents`][t]||l()[`~clientComponents`][e.id];return a&&(a.component?i=a.component:a.loader&&!a.loading&&(a.loading=!0,a.loadPromise=a.loader().then(e=>(a.component=e.default||e,a.registered=!0,a.loading=!1,a.component)).catch(t=>{throw a.loading=!1,a.loadPromise=void 0,console.error(`[rari] Failed to load component ${e.id}:`,t),t})),a.loadPromise&&!a.component&&n.use(a.loadPromise)),i?n.createElement(i,r?{...s,key:r}:s):s.children||null}return s.children||null}return n.createElement(t,r?{...s,key:r}:s)}return null}return e.map((e,t)=>{let r=o(e);return n.isValidElement(r)&&!r.key?n.cloneElement(r,{key:t}):r})}return e}try{let e=o(t);e&&(a(r).render(e),r.classList.add(`rari-boundary-hydrated`))}catch(e){console.error(`[rari] Failed to hydrate client components:`,e),console.error(`[rari] Error stack:`,e.stack)}})}function m(){let e=u()[`~rari`].pendingBoundaryHydrations;if(!(!e||e.size===0)){for(let[t,n]of e.entries())c().hydrateClientComponents&&c().hydrateClientComponents(t,n.content,n.element);e.clear()}}p();async function h(t){let n=[];for(let r of t){let t=e(r).catch(e=>{console.error(`[rari] Failed to preload component ${r}:`,e)});n.push(t)}n.length>0&&await Promise.all(n)}async function g(){let e=document.getElementById(`root`);if(!e){console.error(`[rari] Root element not found`);return}let r=document.getElementById(`__RARI_RSC_PAYLOAD__`),c=e.children.length>0,l=u()[`~rari`]?.bufferedRows&&u()[`~rari`].bufferedRows.length>0;if(p(),c&&!r&&!l){let e=document.querySelectorAll(`[data-client-component]`);if(e.length>0){let r=new Set;e.forEach(e=>{let t=e.getAttribute(`data-client-component`);t&&r.add(t)}),await h(r),e.forEach(e=>{let r=e.getAttribute(`data-client-component`),i=e.getAttribute(`data-props`);if(r)try{let o=t(r);if(!o)return;let s=i?JSON.parse(i):{};e.innerHTML=``,a(e).render(n.createElement(o,s))}catch(e){console.error(`[rari] Failed to hydrate client component ${r}:`,e)}})}return}if(c&&l&&!r&&document.querySelectorAll(`[data-boundary-id]`).length>0){u()[`~rari`].pendingBoundaryHydrations&&u()[`~rari`].pendingBoundaryHydrations.size>0&&m();return}try{let t;if(!r&&!l&&!c)try{let e=window.location.pathname+window.location.search,n=await fetch(
|
|
5
|
+
function p(){c().hydrateClientComponents||(c().hydrateClientComponents=function(e,t,r){let i=u()[`~rari`].boundaryModules||new Map;function o(e){if(!e)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t,r,a]=e,s=a?{...a}:{};if(a?.children&&(s.children=o(a.children)),s[`~boundaryId`]&&delete s[`~boundaryId`],typeof t==`string`){if(t.startsWith(`$L`)){let e=i.get(t);if(e){let t=`${e.id}#${e.name||`default`}`,i=null,a=l()[`~clientComponents`][t]||l()[`~clientComponents`][e.id];return a&&(a.component?i=a.component:a.loader&&!a.loading&&(a.loading=!0,a.loadPromise=a.loader().then(e=>(a.component=e.default||e,a.registered=!0,a.loading=!1,a.component)).catch(t=>{throw a.loading=!1,a.loadPromise=void 0,console.error(`[rari] Failed to load component ${e.id}:`,t),t})),a.loadPromise&&!a.component&&n.use(a.loadPromise)),i?n.createElement(i,r?{...s,key:r}:s):s.children||null}return s.children||null}return n.createElement(t,r?{...s,key:r}:s)}return null}return e.map((e,t)=>{let r=o(e);return n.isValidElement(r)&&!r.key?n.cloneElement(r,{key:t}):r})}return e}try{let e=o(t);e&&(a(r).render(e),r.classList.add(`rari-boundary-hydrated`))}catch(e){console.error(`[rari] Failed to hydrate client components:`,e),console.error(`[rari] Error stack:`,e.stack)}})}function m(){let e=u()[`~rari`].pendingBoundaryHydrations;if(!(!e||e.size===0)){for(let[t,n]of e.entries())c().hydrateClientComponents&&c().hydrateClientComponents(t,n.content,n.element);e.clear()}}p();async function h(t){let n=[];for(let r of t){let t=e(r).catch(e=>{console.error(`[rari] Failed to preload component ${r}:`,e)});n.push(t)}n.length>0&&await Promise.all(n)}async function g(){let e=document.getElementById(`root`);if(!e){console.error(`[rari] Root element not found`);return}let r=document.getElementById(`__RARI_RSC_PAYLOAD__`),c=e.children.length>0,l=u()[`~rari`]?.bufferedRows&&u()[`~rari`].bufferedRows.length>0;if(p(),c&&!r&&!l){let e=document.querySelectorAll(`[data-client-component]`);if(e.length>0){let r=new Set;e.forEach(e=>{let t=e.getAttribute(`data-client-component`);t&&r.add(t)}),await h(r),e.forEach(e=>{let r=e.getAttribute(`data-client-component`),i=e.getAttribute(`data-props`);if(r)try{let o=t(r);if(!o)return;let s=i?JSON.parse(i):{};e.innerHTML=``,a(e).render(n.createElement(o,s))}catch(e){console.error(`[rari] Failed to hydrate client component ${r}:`,e)}})}return}if(c&&l&&!r&&document.querySelectorAll(`[data-boundary-id]`).length>0){u()[`~rari`].pendingBoundaryHydrations&&u()[`~rari`].pendingBoundaryHydrations.size>0&&m();return}try{let t;if(!r&&!l&&!c)try{let e=window.location.pathname+window.location.search,n=(import.meta.env.DEV?import.meta.env.RARI_SERVER_URL||`http://localhost:${import.meta.env.VITE_RSC_PORT||`3000`}`:window.location.origin)+e,r=await fetch(n,{headers:{Accept:`text/x-component`},cache:`no-store`});if(!r.ok&&r.status!==404)throw Error(`Failed to fetch RSC data: ${r.status}`);let i=r.body;t=await s(i,d())}catch(e){if(e instanceof Promise)throw e;if(console.error(`[rari] Failed to fetch initial RSC data:`,e),e instanceof Error)console.error(`[rari] Error name:`,e.name),console.error(`[rari] Error message:`,e.message),e.stack&&console.error(`[rari] Error stack:`,e.stack);else if(typeof e==`string`)console.error(`[rari] Error details:`,e);else if(e&&typeof e==`object`)try{let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=e[n];console.error(`[rari] Error details:`,JSON.stringify(t,null,2))}catch{console.error(`[rari] Error details:`,String(e))}else console.error(`[rari] Error details:`,String(e));t=null}else if(r&&r.textContent)try{let e=r.textContent,n=u()[`~rari`]?.bufferedRows&&u()[`~rari`].bufferedRows.length>0;t=u()[`~rari`]?.streamComplete===void 0||n?await s(new ReadableStream({start(t){if(t.enqueue(new TextEncoder().encode(e)),u()[`~rari`]?.bufferedRows){for(let e of u()[`~rari`].bufferedRows)t.enqueue(new TextEncoder().encode(`\n${e}`));u()[`~rari`].bufferedRows=[]}let n=e=>{let n=e;n.detail?.rscRow&&t.enqueue(new TextEncoder().encode(`\n${n.detail.rscRow}`))},r=()=>{t.close(),window.removeEventListener(`rari:rsc-row`,n),window.removeEventListener(`rari:stream-complete`,r)};window.addEventListener(`rari:rsc-row`,n),window.addEventListener(`rari:stream-complete`,r),u()[`~rari`]?.streamComplete&&r()}}),d()):await s(new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e)),t.close()}}),d())}catch(e){console.error(`[rari] Failed to parse embedded RSC payload:`,e),t=null}else if(l)try{t=await s(new ReadableStream({start(e){if(u()[`~rari`]?.bufferedRows){for(let t of u()[`~rari`].bufferedRows)e.enqueue(new TextEncoder().encode(`${t}\n`));u()[`~rari`].bufferedRows=[]}let t=t=>{let n=t;n.detail?.rscRow&&e.enqueue(new TextEncoder().encode(`${n.detail.rscRow}\n`))},n=()=>{e.close(),window.removeEventListener(`rari:rsc-row`,t),window.removeEventListener(`rari:stream-complete`,n)};window.addEventListener(`rari:rsc-row`,t),window.addEventListener(`rari:stream-complete`,n),u()[`~rari`]?.streamComplete&&n()}}),d())}catch(e){console.error(`[rari] Failed to process streaming RSC payload:`,e),t=null}if(!t)throw Error(`No RSC data available for hydration`);let f;f=t;let p;p=n.createElement(o,{initialPayload:{element:t}},f),p=n.createElement(i,{initialRoute:window.location.pathname},p),a(e).render(p)}catch(t){console.error(`[rari] Error rendering app:`,t),e.innerHTML=`
|
|
6
6
|
<div style="padding: 20px; background: #fee; border: 2px solid #f00; margin: 20px;">
|
|
7
7
|
<h2>Error Loading App</h2>
|
|
8
8
|
<p></p>
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`?(l(o,s,c,t,n,r),u===null&&s!==73&&c.trim()&&!(c.startsWith(`"$S`)&&c.endsWith(`"`))&&n.has(o.toString())&&(u=o.toString()),a=0,o=0,s=0,c=``):c+=d,i++;break}}return c.trim()&&(l(o,s,c,t,n,r),u===null&&s!==73&&!(c.startsWith(`"$S`)&&c.endsWith(`"`))&&n.has(o.toString())&&(u=o.toString())),{modules:t,chunks:n,symbols:r,rootElement:u===null?null:n.get(u)}}function l(e,t,n,r,i,a){let o=e.toString();try{switch(t){case 73:{let e=JSON.parse(n);Array.isArray(e)&&e.length>=3&&r.set(`$L${o}`,{id:e[0],chunks:e[1]||[],name:e[2]||`default`});break}case 69:{console.error(`[rari] RSC: Error chunk:`,n);let e=JSON.parse(n);i.set(o,{error:e});break}case 84:i.set(o,n);break;case 72:case 68:case 87:break;case 67:break;default:{if(!n.trim())break;if(n.startsWith(`"$S`)&&n.endsWith(`"`)){let e=n.slice(1,-1);a.set(o,e);break}let e=JSON.parse(n);i.set(o,e);break}}}catch(e){console.error(`[rari] RSC: Failed to parse row:`,{id:o,tag:t,data:n},e)}}function u(
|
|
1
|
+
import{b as e,t,w as n}from"../regex-constants-DMuIAFub.mjs";import{r}from"../get-client-component-CpMI09nb.mjs";import{t as i}from"../preload-components-5Y8ZOaFG.mjs";import*as a from"react";async function o(e,t={}){let{moduleMap:n={}}=t,r=e.getReader(),a=[];for(;;){let{done:e,value:t}=await r.read();if(e)break;a.push(t)}let o=new Uint8Array(a.reduce((e,t)=>e+t.length,0)),s=0;for(let e of a)o.set(e,s),s+=e.length;let l=c(new TextDecoder().decode(o));return await i(l.modules),u(l.rootElement,l.modules,n,l.symbols,l.chunks)}async function s(e,t={}){let n=c(await(await e).text());return await i(n.modules),u(n.rootElement,n.modules,t.moduleMap||{},n.symbols,n.chunks)}function c(e){let t=new Map,n=new Map,r=new Map,i=0,a=0,o=0,s=0,c=``,u=null;for(;i<e.length;){let d=e[i],f=e.charCodeAt(i);switch(a){case 0:d===`:`?(a=1,i++):(f>=48&&f<=57?o=o<<4|f-48:f>=97&&f<=102?o=o<<4|f-87:f>=65&&f<=70&&(o=o<<4|f-55),i++);break;case 1:f===73||f===69||f===84||f===72||f===68||f===87||f===67?(s=f,a=2,i++):(s=0,a=2);break;case 2:d===`
|
|
2
|
+
`?(l(o,s,c,t,n,r),u===null&&s!==73&&c.trim()&&!(c.startsWith(`"$S`)&&c.endsWith(`"`))&&n.has(o.toString())&&(u=o.toString()),a=0,o=0,s=0,c=``):c+=d,i++;break}}return c.trim()&&(l(o,s,c,t,n,r),u===null&&s!==73&&!(c.startsWith(`"$S`)&&c.endsWith(`"`))&&n.has(o.toString())&&(u=o.toString())),{modules:t,chunks:n,symbols:r,rootElement:u===null?null:n.get(u)}}function l(e,t,n,r,i,a){let o=e.toString();try{switch(t){case 73:{let e=JSON.parse(n);Array.isArray(e)&&e.length>=3&&r.set(`$L${o}`,{id:e[0],chunks:e[1]||[],name:e[2]||`default`});break}case 69:{console.error(`[rari] RSC: Error chunk:`,n);let e=JSON.parse(n);i.set(o,{error:e});break}case 84:i.set(o,n);break;case 72:case 68:case 87:break;case 67:break;default:{if(!n.trim())break;if(n.startsWith(`"$S`)&&n.endsWith(`"`)){let e=n.slice(1,-1);a.set(o,e);break}let e=JSON.parse(n);i.set(o,e);break}}}catch(e){console.error(`[rari] RSC: Failed to parse row:`,{id:o,tag:t,data:n},e)}}function u(t,n,r,i,o){if(!t)return null;if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`){if(typeof t==`string`&&t.startsWith(`$`)&&t.length>1){if(t[1]===`L`){let e=t.slice(2),a=o?.get(e);if(!a){let e=new Promise(()=>{});throw e._rscLazyRef=t,e}return u(a,n,r,i,o)}let e=t.slice(1),a=o?.get(e);return a?u(a,n,r,i,o):null}return t}if(Array.isArray(t)){if(t.length>=4&&t[0]===`$`){let[,s,c,l]=t;if(typeof s==`string`&&s.startsWith(`$`)&&s.length>1&&e.test(s.slice(1))){let e=s.slice(1),t=i?.get(e);if(t&&t.startsWith(`$S`)&&t.slice(2)===`react.suspense`){let e=f(l,n,r,i,o);return a.createElement(a.Suspense,c?{...e,key:c}:e)}}if(typeof s==`string`&&s.startsWith(`$S`)){if(s.slice(2)===`react.suspense`){let e=f(l,n,r,i,o);return a.createElement(a.Suspense,c?{...e,key:c}:e)}return null}if(typeof s==`string`&&s.startsWith(`$L`)){let e=s.substring(2);if(e===`ClientRouter`&&(!l||!l.manifest))return l&&l.children?u(l.children,n,r,i,o):null;let t=d(e,n,r);if(t){let e=f(l,n,r,i,o);return a.createElement(t,c?{...e,key:c}:e)}return null}let p=f(l,n,r,i,o);return a.createElement(s,c?{...p,key:c}:p)}return t.map(e=>u(e,n,r,i,o))}return t}function d(e,i,a){if(e===`AppRouterProvider`){let e=globalThis[`~rari`]?.AppRouterProvider;if(e)return e}if(e===`ClientRouter`){let e=globalThis[`~rari`]?.ClientRouter;if(e)return e}if(i&&i.size>0){let a=`$L${e}`,o=i.get(a);if(o){let e=globalThis[`~clientComponents`]||{},i=[o.id,`${o.id}#${o.name||`default`}`,o.id.replace(n,``),o.id.replace(t,`/`)];for(let t of i){let n=e[t];if(n){if(n.component)return n.component;if(n.loader&&!n.loading)return r(n,o.id);if(n.loading)return null}}console.warn(`[rari] Component not found in registry:`,{moduleId:o.id,moduleName:o.name,triedKeys:i,availableKeys:Object.keys(e).slice(0,10)})}}if(a[e])return a[e];let o=globalThis[`~clientComponents`]||{};for(let[t,n]of Object.entries(o)){let i=t===e,a=t.endsWith(`/${e}`)||t.endsWith(`\\${e}`),o=t.endsWith(`#${e}`),s=n.name===e;if(i||a||o||s){if(n.component)return n.component;if(n.loader&&!n.loading)return r(n,t)}}return null}function f(e,t,n,r,i){if(!e||typeof e!=`object`)return e;let a={};for(let o in e)if(Object.hasOwn(e,o)){if(o.startsWith(`~`)||o===`ref`)continue;o===`children`?a[o]=e.children?u(e.children,t,n,r,i):void 0:a[o]=e[o]}return a}function p(e){return JSON.stringify(e)}function m(e){return JSON.parse(e)}export{s as createFromFetch,o as createFromReadableStream,m as decodeReply,p as encodeReply};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{_ as e,d as t,g as n,h as r,m as i,n as a,p as o,
|
|
2
|
-
`),i=r.slice(0,-1);x=r.at(-1)||``;for(let e of i)if(e.trim())try{let t=e.indexOf(`:`);if(t===-1)continue;let n=e.substring(0,t),r=e.substring(t+1);if(r.startsWith(`I[`))try{let e=JSON.parse(r.substring(1));if(Array.isArray(e)&&e.length>=3){let[t,r,i]=e;l.set(`$L${n}`,{id:t,chunks:Array.isArray(r)?r:[r],name:i||`default`})}}catch(e){console.error(`Failed to parse import row:`,r,e)}else if(r.startsWith(`E{`))try{let e=JSON.parse(r.substring(1));console.error(`RSC stream error:`,e)}catch(e){console.error(`Failed to parse error row:`,r,e)}else if(r.startsWith(`Symbol.for(`))continue;else if(r.startsWith(`[`)){let e=JSON.parse(r);if(Array.isArray(e)&&e.length>=4){let[t,r,i]=e,a=i?.[`~boundaryId`];if(t===`$`&&(r===`react.suspense`||r===`suspense`)&&i&&a&&u.set(`$L${n}`,a),t===`$`&&i&&Object.hasOwn(i,`children`)&&typeof r==`string`&&r.startsWith(`$L`)){let e=u.get(r)||null;if(e){let t=g(i.children);y.set(e,t),S&&S.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),S&&typeof S.updateRoot==`function`&&S.updateRoot())}}}catch(t){console.error(`Failed to parse stream line:`,e,t)}}}catch(e){console.error(`Error processing stream:`,e)}},w=()=>{let[,e]=_(0);h(()=>(S={updateBoundary:(t,n)=>{y.set(t,n),e(e=>e+1)},updateRoot:()=>{e(e=>e+1)}},()=>{S=null}),[]);let t=e=>{if(!e)return null;if(m(e)){let n=e.props,r=n?.[`~boundaryId`];if(n&&r){let e=y.get(r);if(e)return e}if(n&&n.children){let r=t(n.children);if(r!==n.children)return f(e,{...n,children:r})}return e}return Array.isArray(e)?e.map(e=>t(e)):e};return t(v)};return C(),{"~isRscResponse":!0,"~rscPromise":Promise.resolve(p(w)),readRoot(){return Promise.resolve(p(w))}}}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 T(),S)try{let t=S(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=b(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=b(`${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 D({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 O({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),E.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(D,{error:`Error loading component`,details:{message:l.message,componentId:e}}):s?s[`~isRscResponse`]?p(d,{fallback:n||null},s.readRoot()):s:p(D,{error:`No data received for component: ${e}`,details:{componentId:e,dataType:typeof s,hasData:!!s}})}function k(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&&j(n.filePath)&&(E.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(O,{key:`${e}-${r}`,componentId:e,props:n,fallback:null}))};return n.displayName=`ServerComponent(${e})`,function(e){return p(n,e)}}function A(e,t){return E.fetchServerComponent(e,t)}function j(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){import.meta.hot.on(`rari:register-server-component`,e=>{e?.filePath&&typeof globalThis<`u`&&(globalThis[`~rari`].serverComponents=globalThis[`~rari`].serverComponents||new Set,globalThis[`~rari`].serverComponents.add(e.filePath))}),import.meta.hot.on(`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)}))}),import.meta.hot.on(`vite:beforeFullReload`,async e=>{e?.path&&j(e.path)&&await o({filePath:e.path,forceReload:!0})}),import.meta.hot.on(`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&&j(e.path)&&await o({filePath:e.path,forceReload:!1})}),import.meta.hot.on(`rari:app-router-updated`,async t=>{try{if(!t)return;await e(t)}catch(e){console.error(`[rari] HMR: App router update failed:`,e)}}),import.meta.hot.on(`rari:server-action-updated`,async e=>{if(e?.filePath&&(E.clearCache(),typeof window<`u`)){let t=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:e.filePath,type:`server-action`}});window.dispatchEvent(t)}});async function e(e){let n=e.fileType,o=e.filePath,s=e.routePath,c=e.affectedRoutes,l=e.manifestUpdated,u=e.metadata;e.metadataChanged&&u&&t(u);try{let e=`${window.location.origin}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`register`,file_path:o})});t.ok||console.error(`[rari] HMR: Component reload failed:`,t.status),await new Promise(e=>setTimeout(e,100))}catch(e){console.error(`[rari] HMR: Failed to reload component:`,e)}let d=[s];switch(n){case`page`:d=[s];break;case`layout`:case`loading`:case`error`:case`not-found`:d=c;break;default:break}await r({routes:d,fileType:n,filePath:o,componentId:s}),l&&await a(),await i({routePath:s,affectedRoutes:c})}function t(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 n(e){if(!e||e.length===0){E.clearCache();return}let t=[];for(let n of E.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)E.componentCache.delete(e)}async function r(e){let t=e.routes||[],r=e.fileType,i=e.filePath,a=e.componentId;if(a||i)try{let e=`${window.location.origin.includes(`:5173`)?`http://localhost:3000`:window.location.origin}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate`,componentId:a||i,filePath:i})});t.ok||console.error(`[rari] HMR: Server cache invalidation failed:`,t.status)}catch(e){console.error(`[rari] HMR: Failed to call server invalidation endpoint:`,e)}if(n(t),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{routes:t,fileType:r}});window.dispatchEvent(e);let n=window.location.pathname;if(t.includes(n)||t.includes(`/`))try{let e=(window.location.origin.includes(`:5173`)?`http://localhost:3000`:window.location.origin)+n+window.location.search,t=await fetch(e,{headers:{Accept:`text/x-component`},cache:`no-cache`});t.ok||console.error(`[rari] HMR: Failed to re-fetch route:`,t.status)}catch(e){console.error(`[rari] HMR: Failed to re-fetch route:`,e)}}}async function i(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 a(){typeof window<`u`&&window[`~rari`]?.routeInfoCache&&window[`~rari`].routeInfoCache.clear()}async function o(e){let t=e?.filePath||e;if(E.clearCache(),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:t}});window.dispatchEvent(e)}}}var M=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 N=null;function P(){return N||=new M,N}if(import.meta.hot){let e=P();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{D as RscErrorComponent,x as createClientModuleMap,k as createServerComponentWrapper,A as fetchServerComponent,b as getClientComponent,y as registerClientComponent,E as rscClient};
|
|
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;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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{T as t,a as n,f as r,i,l as a,o,r as s,s as c,w as l}from"./regex-constants-DMuIAFub.mjs";import u from"node:fs";import d from"node:path";import f from"node:process";import{build as p}from"rolldown";var m=e({ServerComponentBuilder:()=>O,createServerBuildPlugin:()=>A,scanDirectory:()=>k});const h=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,g=/from\s+['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s+['"]([^'"]+)['"]/g,_=/import(?:\s+(?:\w+|\{[^}]*\}|\*\s+as\s+\w+)(?:\s*,\s*(?:\w+|\{[^}]*\}|\*\s+as\s+\w+))*\s+from\s+)?['"]([^'"]+)['"]/g,v=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,y=/import\s+(?:(\w+)|\{([^}]+)\})\s+from\s+['"]([^'"]+)['"];?\s*$/gm,b=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,x=/\\/g,S=/\.(tsx?|jsx?)$/,C=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,w=/[/\\]components[/\\](\w+)(?:\.tsx?|\.jsx?)?$/,T=/^export\s*\{([^}]+)\};?\s*$/gm,E=/^export\s+(const|let|var)\s+(\w+)/gm,D=/^(?:robots|sitemap)\.(?:tsx?|jsx?)$/;var O=class{serverComponents=new Map;serverActions=new Map;options;projectRoot;buildCache=new Map;htmlOnlyImports=new Set;fileImporters=new Map;getComponentCount(){return this.serverComponents.size+this.serverActions.size}constructor(e,t={}){this.projectRoot=e;let n=t.rscDir||`server`;this.options={outDir:t.outDir||d.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath||d.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath||d.join(n,`config.json`),minify:t.minify??f.env.NODE_ENV===`production`,alias:t.alias||{},define:t.define,csp:t.csp,rateLimit:t.rateLimit,spamBlocker:t.spamBlocker,cacheControl:t.cacheControl},this.parseHtmlImports()}parseHtmlImports(){let e=d.join(this.projectRoot,`index.html`);if(u.existsSync(e))try{let t=u.readFileSync(e,`utf-8`);for(let e of t.matchAll(h)){let t=e[1]||e[2];if(t.startsWith(`/src/`)){let e=d.join(this.projectRoot,t.slice(1));this.htmlOnlyImports.add(e)}}}catch(e){console.warn(`[server-build] Error parsing index.html:`,e)}}isHtmlOnlyImport(e){return this.htmlOnlyImports.has(e)}isServerComponent(e){if(e.includes(`node_modules`)||this.isHtmlOnlyImport(e))return!1;try{if(!u.existsSync(e))return!1;let t=u.readFileSync(e,`utf-8`).split(`
|
|
2
2
|
`),n=!1,r=!1;for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use client'`||t===`"use client"`||t===`'use client';`||t===`"use client";`){n=!0;break}if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`){r=!0;break}if(t)break}}return!n&&!r}catch{return!1}}isClientComponent(e){try{if(!u.existsSync(e))return!1;let t=u.readFileSync(e,`utf-8`),n=[`'use client'`,`"use client"`,`/* @client */`,`// @client`],r=t.trim();return n.some(e=>r.startsWith(e)||t.includes(e))}catch{return!1}}buildImportGraph(e){this.fileImporters.clear();let n=e=>{if(!u.existsSync(e))return;let r=u.readdirSync(e,{withFileTypes:!0});for(let i of r){let r=d.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;n(r)}else if(i.isFile()&&t.test(i.name))try{let e=u.readFileSync(r,`utf-8`),t;for(g.lastIndex=0,t=g.exec(e);t!==null;){let n=t[1]||t[2]||t[3],i=null;if(n.startsWith(`./`)||n.startsWith(`../`)){let e=d.dirname(r);i=d.resolve(e,n)}else if(n.startsWith(`@/`)){let e=n.slice(2);i=d.join(this.projectRoot,`src`,e)}if(i){let e=[``,`.ts`,`.tsx`,`.js`,`.jsx`],t=null;for(let n of e){let e=i+n;if(u.existsSync(e)&&u.statSync(e).isFile()){t=e;break}}t&&(this.fileImporters.has(t)||this.fileImporters.set(t,new Set),this.fileImporters.get(t).add(r))}t=g.exec(e)}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error building import graph:`,r,e)}}};n(e)}isOnlyImportedByClientComponents(e){let t=this.fileImporters.get(e);if(!t||t.size===0)return!1;for(let e of t)if(!this.isClientComponent(e)&&!this.isOnlyImportedByClientComponents(e))return!1;return!0}addServerComponent(e){let t=u.readFileSync(e,`utf-8`);if(this.isServerAction(t)){let n=this.extractDependencies(t),r=this.hasNodeImports(t);this.serverActions.set(e,{filePath:e,originalCode:t,dependencies:n,hasNodeImports:r});return}if(!this.isServerComponent(e))return;let n=this.extractDependencies(t),r=this.hasNodeImports(t);this.serverComponents.set(e,{filePath:e,originalCode:t,dependencies:n,hasNodeImports:r})}isServerAction(e){let t=e.split(`
|
|
3
3
|
`);for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`)return!0;if(t)break}}return!1}extractDependencies(e){let t=[],n;for(_.lastIndex=0;n=_.exec(e),n!==null;){let e=n[1];!e.startsWith(`.`)&&!e.startsWith(`/`)&&!e.startsWith(`node:`)&&!this.isNodeBuiltin(e)&&t.push(e)}return[...new Set(t)]}isNodeBuiltin(e){return[`fs`,`path`,`os`,`crypto`,`util`,`stream`,`events`,`process`,`buffer`,`url`,`querystring`,`zlib`,`http`,`https`,`net`,`tls`,`child_process`,`cluster`,`worker_threads`].includes(e)}hasNodeImports(e){return e.includes(`from 'node:`)||e.includes(`from "node:`)||e.includes(`from 'fs'`)||e.includes(`from "fs"`)||e.includes(`from 'path'`)||e.includes(`from "path"`)||e.includes(`from 'os'`)||e.includes(`from "os"`)||e.includes(`from 'crypto'`)||e.includes(`from "crypto"`)||e.includes(`from 'util'`)||e.includes(`from "util"`)||e.includes(`from 'stream'`)||e.includes(`from "stream"`)||e.includes(`from 'events'`)||e.includes(`from "events"`)}async getTransformedComponentsForDevelopment(){let e=[];for(let[t]of this.serverComponents){let n=d.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i})}for(let[t]of this.serverActions){let n=d.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i})}return e}transformComponentImportsToGlobal(e){let t=[];for(let n of e.matchAll(v)){let[e,r,i]=n;if(!i.startsWith(`.`)&&!i.startsWith(`@`)&&!i.startsWith(`~`)&&!i.startsWith(`#`))continue;let a=null;if(i.startsWith(`.`)){if(i.includes(`/components/`)){let n=i.match(C);if(n){let i=n[1],a=[d.resolve(this.projectRoot,`src`,`components`,`${i}.tsx`),d.resolve(this.projectRoot,`src`,`components`,`${i}.ts`),d.resolve(this.projectRoot,`src`,`components`,`${i}.jsx`),d.resolve(this.projectRoot,`src`,`components`,`${i}.js`)],o=!1;for(let e of a)if(u.existsSync(e)&&this.isClientComponent(e)){o=!0;break}if(!o)continue;let s=`// Component reference: ${i}
|
|
4
4
|
const ${r} = (props) => {
|
|
@@ -38,7 +38,7 @@ const ${r} = (props) => {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
return Component(props);
|
|
41
|
-
}`;t.push({original:e,replacement:m})}}}let n=e;for(let{original:e,replacement:r}of t)n=n.replace(e,r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createBuildPlugins(e,t,n,
|
|
41
|
+
}`;t.push({original:e,replacement:m})}}}let n=e;for(let{original:e,replacement:r}of t)n=n.replace(e,r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createBuildPlugins(e,t,n,i,a=!1){let o=d.dirname(i),s=b.test(d.basename(i)),c=this,l=new Map,f=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){let e=d.resolve(o,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(u.existsSync(n)&&u.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=d.join(e,`index${t}`);if(u.existsSync(n))return n}return e}return null},load(r){return r===e?{code:t,moduleType:n}:null}},{name:`resolve-client-server-boundaries`,resolveId:(t,n)=>{if(!n||n.includes(`node_modules`)||n.includes(`/packages/rari/dist`)||t.startsWith(`node:`)||c.isNodeBuiltin(t)||t===`react`||t===`react-dom`||t===`react/jsx-runtime`||t===`react/jsx-dev-runtime`)return null;let r=null,i=c.options.alias||{};for(let[e,n]of Object.entries(i))if(t.startsWith(`${e}/`)||t===e){let i=t.slice(e.length),a=d.join(n,i);r=d.isAbsolute(a)?a:d.resolve(c.projectRoot,a);break}if(!r&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?o:d.dirname(n);r=d.resolve(i,t)}if(r)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(u.existsSync(t)&&u.statSync(t).isFile()){if(c.isClientComponent(t)){let e=d.relative(c.projectRoot,t),n=e.startsWith(`..`)?t:e;return l.set(t,n),{id:`\0client-ref:${t}`}}try{let e=u.readFileSync(t,`utf-8`).split(`
|
|
42
42
|
`);for(let n of e){let e=n.trim();if(!(e.startsWith(`//`)||e.startsWith(`/*`)||!e)){if(e===`'use server'`||e===`"use server"`||e===`'use server';`||e===`"use server";`){let e=d.relative(c.projectRoot,t),n=e.startsWith(`..`)?t:e;return f.set(t,n),{id:`\0server-action:${t}`}}if(e)break}}}catch(e){console.error(`[rari] Failed to read file for server action detection: ${t}`,e)}break}}return null},load(e){if(e.startsWith(`\0client-ref:`)){let t=e.slice(12),n=d.relative(c.projectRoot,t),r=l.get(t)||(n.startsWith(`..`)?t:n);return{code:`
|
|
43
43
|
function registerClientReference(clientReference, id, exportName) {
|
|
44
44
|
const key = id + '#' + exportName;
|
|
@@ -67,10 +67,10 @@ function registerClientReference(clientReference, id, exportName) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
export default registerClientReference(null, ${JSON.stringify(r)}, "default");
|
|
70
|
-
`,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15);return{code:`export * from ${JSON.stringify(t)};`,moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!a)return null;if(e.startsWith(`file://`)){let t=e.replace(
|
|
70
|
+
`,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15);return{code:`export * from ${JSON.stringify(t)};`,moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!a)return null;if(e.startsWith(`file://`)){let t=e.replace(r,``);return u.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null,i=c.options.alias||{};for(let[t,r]of Object.entries(i))if(e.startsWith(`${t}/`)||e===t){let i=e.slice(t.length),a=d.join(r,i);n=d.isAbsolute(a)?a:d.resolve(c.projectRoot,a);break}let s=t?.startsWith(`\0`)?o:t?d.dirname(t):o;if(!n&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=d.resolve(s,e)),!n||s.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(u.existsSync(t)&&u.statSync(t).isFile()){if(c.isClientComponent(t))return null;let e=d.join(c.projectRoot,`src`);if(!t.startsWith(e))return null;let n=d.relative(e,t),r=d.join(c.options.outDir,c.options.rscDir,n.replace(S,`.js`));if(u.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:u.readFileSync(t,`utf-8`),moduleType:`js`}}return null}},{name:`resolve-aliases`,resolveId:e=>{if(e.startsWith(`\0`))return null;let t=c.options.alias||{};for(let[n,r]of Object.entries(t))if(e.startsWith(`${n}/`)||e===n){let t=e.slice(n.length),i=d.join(r,t),a=d.isAbsolute(i)?i:d.resolve(c.projectRoot,i);for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=a+e;if(u.existsSync(t)&&u.statSync(t).isFile())return t}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let t=d.join(a,`index${e}`);if(u.existsSync(t))return t}return a}return null}},{name:`resolve-rari-proxy`,resolveId:e=>{if(s&&e===`rari`){let e=d.resolve(c.projectRoot,`node_modules/rari/dist/proxy/RariResponse.mjs`);if(u.existsSync(e))return e;let t=d.resolve(c.projectRoot,`node_modules/rari/src/proxy/RariResponse.ts`);if(u.existsSync(t))return t}return null}},{name:`externalize-deps`,resolveId:e=>e.startsWith(`\0`)?null:e.startsWith(`node:`)||c.isNodeBuiltin(e)||[`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`rari/image`].includes(e)?{id:e,external:!0}:e===`rari`||e===`rari/client`?null:!e.startsWith(`.`)&&!e.startsWith(`/`)?{id:e,external:!0}:null}]}async buildComponentCodeOnly(e){let t=await u.promises.readFile(e,`utf-8`),n=this.transformClientImports(t,e),r=this.isPageComponent(e),i=r?this.transformComponentImportsToGlobal(n):n,a=d.extname(e),o;o=a===`.tsx`?`tsx`:a===`.ts`?`ts`:a===`.jsx`?`jsx`:`js`;let s=`\0virtual:${e}`,c=await p({input:s,platform:`node`,write:!1,output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${o}`]:o},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(f.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(s,i,o,e,r)});if(!c.output||c.output.length===0)throw Error(`No output generated from Rolldown`);let l=c.output.find(e=>e.type===`chunk`&&e.isEntry);if(!l||l.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let m=l.code;return m=`// Built: ${new Date().toISOString()}\n${m}`,m}async buildServerComponents(){let e=d.join(this.options.outDir,this.options.rscDir);await u.promises.mkdir(e,{recursive:!0});let t={react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`},n=this.options.alias||{};for(let[e,r]of Object.entries(n)){let n=d.isAbsolute(r)?r:d.resolve(this.projectRoot,r);t[`${e}/`]=`file://${n}/`}let r={components:{},importMap:{imports:t},version:`1.0.0`,buildTime:new Date().toISOString()};for(let[e,t]of this.serverComponents){if(this.isPageComponent(e))continue;let n=d.relative(this.projectRoot,e),i=this.getComponentId(n),a=d.join(this.options.rscDir,`${i}.js`),o=d.join(this.options.outDir,a),s=d.dirname(o);await u.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=`file://${d.resolve(this.projectRoot,o)}`;r.components[i]={id:i,filePath:e,relativePath:n,bundlePath:a,moduleSpecifier:c,dependencies:t.dependencies,hasNodeImports:t.hasNodeImports}}for(let[e,t]of this.serverComponents){if(!this.isPageComponent(e))continue;let n=d.relative(this.projectRoot,e),i=this.getComponentId(n),a=d.join(this.options.rscDir,`${i}.js`),o=d.join(this.options.outDir,a),s=d.dirname(o);await u.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=`file://${d.resolve(this.projectRoot,o)}`;r.components[i]={id:i,filePath:e,relativePath:n,bundlePath:a,moduleSpecifier:c,dependencies:t.dependencies,hasNodeImports:t.hasNodeImports}}for(let[e,t]of this.serverActions){let n=d.relative(this.projectRoot,e),i=this.getComponentId(n),a=d.join(this.options.rscDir,`${i}.js`),o=d.join(this.options.outDir,a),s=d.dirname(o);await u.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=`file://${d.resolve(this.projectRoot,o)}`;r.components[i]={id:i,filePath:e,relativePath:n,bundlePath:a,moduleSpecifier:c,dependencies:t.dependencies,hasNodeImports:t.hasNodeImports}}let i=d.join(this.options.outDir,this.options.manifestPath);await u.promises.writeFile(i,JSON.stringify(r,null,2),`utf-8`);let a={};this.options.csp&&(a.csp=this.options.csp),this.options.rateLimit&&(a.rateLimit=this.options.rateLimit),this.options.spamBlocker&&(a.spamBlocker=this.options.spamBlocker),this.options.cacheControl&&(a.cacheControl=this.options.cacheControl);let o=d.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(a).length===0)try{await u.promises.unlink(o)}catch(e){e.code!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await u.promises.writeFile(o,JSON.stringify(a,null,2),`utf-8`);return r}async buildSingleComponent(e,t,n=!1){let r=await u.promises.readFile(e,`utf-8`),i=this.transformClientImports(r,e),a=this.isPageComponent(e),o=a?this.transformComponentImportsToGlobal(i):i,s=d.extname(e),c;c=s===`.tsx`?`tsx`:s===`.ts`?`ts`:s===`.jsx`?`jsx`:`js`;let l=`\0virtual:${e}`,m=await p({input:l,platform:`node`,write:!1,output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${c}`]:c},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(f.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(l,o,c,e,a)});if(!m.output||m.output.length===0)throw Error(`No output generated from Rolldown`);let h=m.output.find(e=>e.type===`chunk`&&e.isEntry);if(!h||h.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let g=h.code;g=`// Built: ${new Date().toISOString()}\n${g}`,await u.promises.writeFile(t,g,`utf-8`);let _=await u.promises.open(t,`r+`);if(await _.sync(),await _.close(),n)return g}createSelfRegisteringModule(e,t){if(e.includes(`Self-registering Production Component`))return e;let r=e,s=null,l=[];if(r=r.replace(o,(e,t)=>(s=t,`function ${t}`)),r=r.replace(i,(e,t)=>(s=t,`async function ${t}`)),r=r.replace(c,(e,t)=>(s=t,`// Default export: ${t}`)),r=r.replace(n,(e,t)=>(s=t,`// Default export: ${t}`)),r=r.replace(T,(e,n)=>{let i=n.split(`,`).map(e=>e.trim()),a=[];return i.forEach(e=>{if(e.includes(`as default`)){let t=e.replace(`as default`,``).trim();s=t,a.push(`${t} (default)`)}else if(e===`default`){let e=`${t}_default`;r.includes(`var ${e}`)&&(s=e),a.push(`default`)}else l.push(e),a.push(e)}),`// Exports: ${a.join(`, `)}`}),r=r.replace(a,(e,t)=>(l.push(t),e.replace(`export `,``))),r=r.replace(E,(e,t,n)=>(l.push(n),`${t} ${n}`)),!s){let e=`${t}_default`;r.includes(`var ${e}`)&&(s=e)}return`// Self-registering Production Component: ${t}
|
|
71
71
|
|
|
72
72
|
if (!globalThis["${t}"]) {
|
|
73
|
-
${
|
|
73
|
+
${r}
|
|
74
74
|
|
|
75
75
|
try {
|
|
76
76
|
const moduleKey = "${t}";
|
|
@@ -80,15 +80,15 @@ if (!globalThis["${t}"]) {
|
|
|
80
80
|
if (!globalThis['~serverFunctions']) globalThis['~serverFunctions'] = {};
|
|
81
81
|
if (!globalThis['~serverFunctions'].all) globalThis['~serverFunctions'].all = {};
|
|
82
82
|
|
|
83
|
-
${
|
|
83
|
+
${l.map(e=>`if (typeof ${e} !== 'undefined') {
|
|
84
84
|
globalThis.${e} = ${e};
|
|
85
85
|
globalThis['~serverFunctions'].all['${e}'] = ${e};
|
|
86
86
|
exportedFunctions['${e}'] = ${e};
|
|
87
87
|
}`).join(`
|
|
88
88
|
`)}
|
|
89
89
|
|
|
90
|
-
${
|
|
91
|
-
mainExport = ${
|
|
90
|
+
${s?`if (typeof ${s} !== 'undefined') {
|
|
91
|
+
mainExport = ${s};
|
|
92
92
|
}`:``}
|
|
93
93
|
|
|
94
94
|
if (mainExport === null && Object.keys(exportedFunctions).length > 0) {
|
|
@@ -173,5 +173,5 @@ function registerClientReference(clientReference, id, exportName) {
|
|
|
173
173
|
return clientProxy;
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
-
`+n);for(let{original:e,replacement:t}of i)n=n.replace(e,t);return n}resolveImportPath(e,t){let n=e,r=this.options.alias||{};for(let[t,i]of Object.entries(r))if(e.startsWith(`${t}/`)||e===t){let r=e.slice(t.length);n=d.join(i,r);break}d.isAbsolute(n)||(n=d.resolve(d.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];for(let e of i){let t=`${n}${e}`;if(u.existsSync(t))return t}if(u.existsSync(n))for(let e of i){let t=d.join(n,`index${e}`);if(u.existsSync(t))return t}return`${n}.tsx`}getComponentId(e){return e.replace(x,`/`).replace(S,``).replace(
|
|
177
|
-
`),t=!1;for(let n of e){let e=n.trim();if(!(e.startsWith(`//`)||e.startsWith(`/*`)||!e)){if(e===`'use server'`||e===`"use server"`||e===`'use server';`||e===`"use server";`){t=!0;break}if(e)break}}t&&n.addServerComponent(i)}}catch(e){console.warn(`[server-build] Error checking ${i}:`,e instanceof Error?e.message:e)}}}}function A(e={}){let n=null,r,i=!1;return{name:`rari-server-build`,configResolved(t){r=t.root,i=t.command===`serve`;let a={};if(t.resolve?.alias){let e=t.resolve.alias;Array.isArray(e)?e.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&(a[e.find]=e.replacement)}):typeof e==`object`&&Object.entries(e).forEach(([e,t])=>{typeof t==`string`&&(a[e]=t)})}n=new O(r,{...e,alias:a})},buildStart(){if(!n)return;let e=f.env.NODE_ENV===`production`,t=[d.join(r,`dist`,`cache`,`og`),d.join(r,`dist`,`cache`,`images`)];e&&t.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of t)try{u.existsSync(e)&&u.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let i=d.join(r,`src`);u.existsSync(i)&&k(i,n)},async closeBundle(){if(n){await n.buildServerComponents();try{let{generateRobotsFile:e}=await import(`./robots-generator-Bo5MHa-v.mjs`);await e({appDir:d.join(r,`src`,`app`),outDir:d.join(r,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-generator-
|
|
176
|
+
`+n);for(let{original:e,replacement:t}of i)n=n.replace(e,t);return n}resolveImportPath(e,t){let n=e,r=this.options.alias||{};for(let[t,i]of Object.entries(r))if(e.startsWith(`${t}/`)||e===t){let r=e.slice(t.length);n=d.join(i,r);break}d.isAbsolute(n)||(n=d.resolve(d.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];for(let e of i){let t=`${n}${e}`;if(u.existsSync(t))return t}if(u.existsSync(n))for(let e of i){let t=d.join(n,`index${e}`);if(u.existsSync(t))return t}return`${n}.tsx`}getComponentId(e){return e.replace(x,`/`).replace(S,``).replace(s,`_`).replace(l,``)}async rebuildComponent(e){let t=this.getComponentId(d.relative(this.projectRoot,e)),n=await u.promises.readFile(e,`utf-8`),r=this.extractDependencies(n),i={filePath:e,originalCode:n,dependencies:r,hasNodeImports:this.hasNodeImports(n)};this.isServerAction(n)?this.serverActions.set(e,i):this.serverComponents.set(e,i);let a=d.join(this.options.rscDir,`${t}.js`),o=d.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await u.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.dependencies)===JSON.stringify(r))return await u.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a),{componentId:t,bundlePath:d.join(this.options.outDir,a),success:!0};let l=d.dirname(o);await u.promises.mkdir(l,{recursive:!0});let f=await this.buildSingleComponent(e,o,!0);return this.buildCache.set(e,{code:f,timestamp:Date.now(),dependencies:r}),await this.updateManifestForComponent(t,e,a),{componentId:t,bundlePath:d.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,t,n){let r=d.join(this.options.outDir,this.options.manifestPath),i;if(this.manifestCache)i=this.manifestCache;else if(u.existsSync(r)){let e=await u.promises.readFile(r,`utf-8`);i=JSON.parse(e),this.manifestCache=i}else i={components:{},importMap:{imports:{react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`}},version:`1.0.0`,buildTime:new Date().toISOString()},this.manifestCache=i;let a=this.serverComponents.get(t)||this.serverActions.get(t),o=d.join(this.options.outDir,n),s=`file://${d.resolve(this.projectRoot,o)}`;if(a)i.components[e]={id:e,filePath:t,relativePath:d.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:s,dependencies:a.dependencies,hasNodeImports:a.hasNodeImports};else{let r=await u.promises.readFile(t,`utf-8`);i.components[e]={id:e,filePath:t,relativePath:d.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:s,dependencies:this.extractDependencies(r),hasNodeImports:this.hasNodeImports(r)}}i.importMap||={imports:{react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`}},i.buildTime=new Date().toISOString(),await u.promises.writeFile(r,JSON.stringify(i,null,2),`utf-8`),this.manifestCache=i}clearCache(){this.buildCache.clear(),this.manifestCache=null}async getTransformedComponentCode(e){return await this.buildComponentCodeOnly(e)}};function k(e,n,r=!0){r&&n.buildImportGraph(e);let i=u.readdirSync(e,{withFileTypes:!0});for(let r of i){let i=d.join(e,r.name);if(r.isDirectory())k(i,n,!1);else if(r.isFile()&&t.test(r.name)){if(D.test(r.name)||r.name.endsWith(`.d.ts`)||n.isOnlyImportedByClientComponents(i))continue;try{if(n.isServerComponent(i))n.addServerComponent(i);else{let e=u.readFileSync(i,`utf-8`).split(`
|
|
177
|
+
`),t=!1;for(let n of e){let e=n.trim();if(!(e.startsWith(`//`)||e.startsWith(`/*`)||!e)){if(e===`'use server'`||e===`"use server"`||e===`'use server';`||e===`"use server";`){t=!0;break}if(e)break}}t&&n.addServerComponent(i)}}catch(e){console.warn(`[server-build] Error checking ${i}:`,e instanceof Error?e.message:e)}}}}function A(e={}){let n=null,r,i=!1;return{name:`rari-server-build`,configResolved(t){r=t.root,i=t.command===`serve`;let a={};if(t.resolve?.alias){let e=t.resolve.alias;Array.isArray(e)?e.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&(a[e.find]=e.replacement)}):typeof e==`object`&&Object.entries(e).forEach(([e,t])=>{typeof t==`string`&&(a[e]=t)})}n=new O(r,{...e,alias:a})},buildStart(){if(!n)return;let e=f.env.NODE_ENV===`production`,t=[d.join(r,`dist`,`cache`,`og`),d.join(r,`dist`,`cache`,`images`)];e&&t.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of t)try{u.existsSync(e)&&u.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let i=d.join(r,`src`);u.existsSync(i)&&k(i,n)},async closeBundle(){if(n){await n.buildServerComponents();try{let{generateRobotsFile:e}=await import(`./robots-generator-Bo5MHa-v.mjs`);await e({appDir:d.join(r,`src`,`app`),outDir:d.join(r,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-generator-D_gTjklw.mjs`);await e({appDir:d.join(r,`src`,`app`),outDir:d.join(r,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}}},async handleHotUpdate({file:e}){if(!n||!i)return;let a=d.relative(r,e).replace(x,`/`);if(!(!a.startsWith(`src/`)||!t.test(a)))try{if((await u.promises.readFile(e,`utf-8`)).includes(`use client`))return;await n.buildServerComponents()}catch(e){console.error(`[rari] Build: Error rebuilding ${a}:`,e)}}}}export{m as n,A as t};
|
|
@@ -391,10 +391,14 @@ interface ServerRateLimitConfig {
|
|
|
391
391
|
interface ServerSpamBlockerConfig {
|
|
392
392
|
enabled?: boolean;
|
|
393
393
|
}
|
|
394
|
+
interface ServerCacheControlConfig {
|
|
395
|
+
routes: Record<string, string>;
|
|
396
|
+
}
|
|
394
397
|
interface ServerConfig {
|
|
395
398
|
csp?: ServerCSPConfig;
|
|
396
399
|
rateLimit?: ServerRateLimitConfig;
|
|
397
400
|
spamBlocker?: ServerSpamBlockerConfig;
|
|
401
|
+
cacheControl?: ServerCacheControlConfig;
|
|
398
402
|
}
|
|
399
403
|
//#endregion
|
|
400
|
-
export {
|
|
404
|
+
export { RouteSegmentType as A, hasServerSideDataFetching as B, LayoutEntry as C, NotFoundEntry as D, Metadata as E, clearPropsCacheForComponent as F, extractMetadata as I, extractServerProps as L, ServerSidePropsResult as M, StaticParamsResult as N, PageProps as O, clearPropsCache as P, extractServerPropsWithCache as R, GenerateStaticParams as S, LoadingEntry as T, AppRouteManifest as _, ServerSpamBlockerConfig as a, ErrorProps as b, ErrorBoundary as c, NotFound as d, RuntimeClient as f, AppRouteEntry as g, createLoadingBoundary as h, ServerRateLimitConfig as i, MetadataResult as j, RouteSegment as k, HttpRuntimeClient as l, createHttpRuntimeClient as m, ServerCacheControlConfig as n, DefaultError as o, createErrorBoundary as p, ServerConfig as r, DefaultLoading as s, ServerCSPConfig as t, LoadingSpinner as u, AppRouteMatch as v, LayoutProps as w, GenerateMetadata as x, ErrorEntry as y, extractStaticParams as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as e,D as t,O as n,j as r,k as i}from"./regex-constants-DMuIAFub.mjs";import{promises as a}from"node:fs";import o from"node:path";import{Buffer as s}from"node:buffer";function c(a){return a.replace(t,`&`).replace(e,`<`).replace(i,`>`).replace(r,`"`).replace(n,`'`)}function l(e){return(typeof e==`string`?new Date(e):e).toISOString()}function u(e){let t=[];for(let n of e)typeof n==`string`?(t.push(` <image:image>`),t.push(` <image:loc>${c(n)}</image:loc>`),t.push(` </image:image>`)):(t.push(` <image:image>`),t.push(` <image:loc>${c(n.loc)}</image:loc>`),n.title&&t.push(` <image:title>${c(n.title)}</image:title>`),n.caption&&t.push(` <image:caption>${c(n.caption)}</image:caption>`),n.geoLocation&&t.push(` <image:geo_location>${c(n.geoLocation)}</image:geo_location>`),n.license&&t.push(` <image:license>${c(n.license)}</image:license>`),t.push(` </image:image>`));return t.join(`
|
|
2
2
|
`)}function d(e){let t=[];for(let n of e){if(t.push(` <video:video>`),t.push(` <video:title>${c(n.title)}</video:title>`),t.push(` <video:thumbnail_loc>${c(n.thumbnail_loc)}</video:thumbnail_loc>`),t.push(` <video:description>${c(n.description)}</video:description>`),n.content_loc&&t.push(` <video:content_loc>${c(n.content_loc)}</video:content_loc>`),n.player_loc&&t.push(` <video:player_loc>${c(n.player_loc)}</video:player_loc>`),n.duration!==void 0&&t.push(` <video:duration>${n.duration}</video:duration>`),n.expiration_date&&t.push(` <video:expiration_date>${c(n.expiration_date)}</video:expiration_date>`),n.rating!==void 0&&t.push(` <video:rating>${n.rating}</video:rating>`),n.view_count!==void 0&&t.push(` <video:view_count>${n.view_count}</video:view_count>`),n.publication_date&&t.push(` <video:publication_date>${c(n.publication_date)}</video:publication_date>`),n.family_friendly!==void 0&&t.push(` <video:family_friendly>${n.family_friendly?`yes`:`no`}</video:family_friendly>`),n.restriction&&t.push(` <video:restriction relationship="${n.restriction.relationship}">${c(n.restriction.content)}</video:restriction>`),n.platform&&t.push(` <video:platform relationship="${n.platform.relationship}">${c(n.platform.content)}</video:platform>`),n.requires_subscription!==void 0&&t.push(` <video:requires_subscription>${n.requires_subscription?`yes`:`no`}</video:requires_subscription>`),n.uploader){let e=n.uploader.info?` info="${c(n.uploader.info)}"`:``;t.push(` <video:uploader${e}>${c(n.uploader.name)}</video:uploader>`)}if(n.live!==void 0&&t.push(` <video:live>${n.live?`yes`:`no`}</video:live>`),n.tag)for(let e of n.tag)t.push(` <video:tag>${c(e)}</video:tag>`);t.push(` </video:video>`)}return t.join(`
|
|
3
3
|
`)}function f(e){let t=e.some(e=>e.images&&e.images.length>0),n=e.some(e=>e.videos&&e.videos.length>0),r=e.some(e=>e.alternates?.languages),i=[`xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"`];t&&i.push(`xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`),n&&i.push(`xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"`),r&&i.push(`xmlns:xhtml="http://www.w3.org/1999/xhtml"`);let a=[`<?xml version="1.0" encoding="UTF-8"?>`,`<urlset ${i.join(` `)}>`];for(let t of e){if(a.push(` <url>`),a.push(` <loc>${c(t.url)}</loc>`),t.lastModified&&a.push(` <lastmod>${l(t.lastModified)}</lastmod>`),t.changeFrequency&&a.push(` <changefreq>${t.changeFrequency}</changefreq>`),t.priority!==void 0&&a.push(` <priority>${t.priority}</priority>`),t.alternates?.languages)for(let[e,n]of Object.entries(t.alternates.languages))a.push(` <xhtml:link rel="alternate" hreflang="${c(e)}" href="${c(n)}" />`);t.images&&t.images.length>0&&a.push(u(t.images)),t.videos&&t.videos.length>0&&a.push(d(t.videos)),a.push(` </url>`)}return a.push(`</urlset>`),a.join(`
|
|
4
4
|
`)}async function p(e,t=[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=[],r=o.join(e,`sitemap.xml`);try{return await a.access(r),n.push({type:`static`,path:r}),n}catch{}for(let r of t){let t=o.join(e,`sitemap${r}`);try{return await a.access(t),n.push({type:`dynamic`,path:t}),n}catch{}}return n}async function m(e){let{appDir:t,extensions:n}=e,r=await p(t,n);if(r.length===0)return!1;await a.mkdir(e.outDir,{recursive:!0});let i=r[0];if(i.type===`static`){let t=o.join(e.outDir,`sitemap.xml`);return await a.copyFile(i.path,t),!0}try{let{build:t}=await import(`rolldown`),n=await a.readFile(i.path,`utf-8`),r=`\0virtual:sitemap`,c=await t({input:r,external:[`rari`],platform:`node`,write:!1,output:{format:`esm`,codeSplitting:!1},plugins:[{name:`virtual-sitemap`,resolveId(e){return e===r?e:e.startsWith(`.`)?o.resolve(o.dirname(i.path),e):null},load(e){if(e===r){let e=o.extname(i.path).slice(1),t;switch(e){case`ts`:t=`ts`;break;case`tsx`:t=`tsx`;break;case`js`:case`mjs`:case`cjs`:t=`js`;break;case`jsx`:t=`jsx`;break;case`json`:t=`json`;break;default:throw Error(`Unsupported sitemap file extension: ".${e}". Allowed extensions are: .ts, .tsx, .js, .jsx, .mjs, .cjs, .json`)}return{code:n,moduleType:t}}return null}}]});if(!c.output||c.output.length===0)throw Error(`Failed to build sitemap module`);let l=c.output.find(e=>e.type===`chunk`&&e.isEntry)||c.output.find(e=>e.type===`chunk`);if(!l||l.type!==`chunk`)throw Error(`No chunk output found in sitemap build result`);let u=l.code,d=await import(`data:text/javascript;base64,${s.from(u).toString(`base64`)}`);if(typeof d.generateSitemaps==`function`){let t=await d.generateSitemaps(),n=o.join(e.outDir,`sitemap`);await a.mkdir(n,{recursive:!0});for(let{id:n}of t){let t;t=typeof d.default==`function`?await d.default({id:String(n)}):d.default;let r=f(t),i=o.join(e.outDir,`sitemap/${n}.xml`);await a.writeFile(i,r)}}else{let t=f(typeof d.default==`function`?await d.default():d.default),n=o.join(e.outDir,`sitemap.xml`);await a.writeFile(n,t)}return!0}catch(e){return console.error(`[rari] Failed to build/execute sitemap file:`,e),!1}}export{m as generateSitemapFiles};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import{C as e,E as t,T as n,c as r,d as i,r as a,t as o,u as s,v as c,w as l}from"./regex-constants-DMuIAFub.mjs";import{a as u,i as d,n as f,o as p,r as m,t as h}from"./constants-DZAg-dr0.mjs";import{t as g}from"./server-build-BaEm53O_.mjs";import _,{promises as v}from"node:fs";import y from"node:path";import b from"node:process";import{Buffer as ee}from"node:buffer";import{spawn as te}from"node:child_process";import{fileURLToPath as x}from"node:url";import{build as S}from"rolldown";var C=class extends Response{static json(e,t){let n=new Headers(t?.headers);return n.has(`content-type`)||n.set(`content-type`,`application/json`),new Response(JSON.stringify(e),{...t,headers:n})}static redirect(e,t=307){return new Response(null,{status:t,headers:{location:e}})}static noContent(e){return new Response(null,{...e,status:204})}};function w(e={}){let{root:t=b.cwd(),srcDir:n=`src`,proxyFileName:r=`proxy`,extensions:i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`],verbose:a=!1}=e,o=null,s=e=>{a&&console.warn(`[rari] Proxy: ${e}`)};async function c(){for(let e of i){let n=`${r}${e}`,i=y.join(t,n);try{return await v.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=y.join(t,n);try{await v.access(e);for(let t of i){let i=`${r}${t}`,a=y.join(e,i);try{return await v.access(a),s(`Found proxy file: ${y.join(n,i)}`),{filePath:a,exists:!0,relativePath:y.join(n,i)}}catch{}}}catch{}return null}return{name:`rari:proxy`,async buildStart(){o=await c(),s(o?`Proxy enabled: ${o.relativePath}`:`No proxy file found`)},configureServer(e){o&&(e.watcher.add(o.filePath),e.watcher.on(`change`,t=>{t===o?.filePath&&(s(`Proxy file changed, reloading...`),e.ws.send({type:`custom`,event:`rari:proxy-reload`}))}))},async handleHotUpdate({file:e,server:t}){if(o&&e===o.filePath)return s(`Hot reloading proxy...`),t.ws.send({type:`custom`,event:`rari:proxy-reload`,data:{file:o.relativePath}}),[]}}}const T=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,E=/title\s*:\s*['"]([^'"]+)['"]/,D=/description\s*:\s*['"]([^'"]+)['"]/,O=/keywords\s*:\s*\[([\s\S]*?)\]/,k={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function A(e){switch(y.basename(e).replace(n,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function j(e,t){let n=y.relative(t,y.dirname(e));return!n||n===`.`?`/`:`/${n.replace(o,`/`).split(`/`).filter(Boolean).join(`/`)}`}function M(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function N(t){try{let n=t.match(T);if(!n)return null;let r=n[1],i={},a=r.match(E);a&&(i.title=a[1]);let o=r.match(D);o&&(i.description=o[1]);let s=r.match(O);s&&(i.keywords=s[1].split(`,`).map(t=>t.trim().replace(e,``)).filter(Boolean));for(let e of[`author`,`viewport`,`themeColor`,`robots`,`openGraph`,`twitter`]){let t=RegExp(`${e}\\s*:\\s*['"]([^'"]+)['"]`,`m`),n=r.match(t);n&&(i[e]=n[1])}return Object.keys(i).length>0?i:null}catch(e){return console.error(`[rari] Router: Failed to extract metadata:`,e),null}}function ne(e){let t=[];for(let n of[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]){let r=RegExp(`export\\s+(?:async\\s+)?function\\s+${n}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${n}\\s*=`);(r.test(e)||i.test(e))&&t.push(n)}return t}async function re(e){try{let t=await fetch(`http://localhost:3000/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate-api-route`,filePath:e})});if(!t.ok){console.error(`[rari] Router: Failed to invalidate API route cache: ${t.statusText}`);return}let n=await t.json();n.success||console.error(`[rari] HMR: Failed to invalidate API route cache: ${n.error||`Unknown error`}`)}catch(e){console.error(`[rari] Router: Failed to notify API route invalidation:`,e)}}function P(e={}){let t={...k,...e},n=null,r=new Map,i=null,a=new Set,o=e=>[...e].toSorted().join(`|`),s=async e=>{let n=new Set,r=async e=>{try{let i=await v.readdir(e,{withFileTypes:!0});for(let a of i){let i=y.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&A(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=y.resolve(e,t.appDir);try{await v.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let{generateAppRouteManifest:d}=await import(`./routes-DXBE0bwy.mjs`).then(e=>e.n),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=y.resolve(e,t.outDir);await v.mkdir(m,{recursive:!0});let h=y.join(m,`server`);return await v.mkdir(h,{recursive:!0}),await v.writeFile(y.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=y.resolve(e.config.root,t.appDir);e.watcher.on(`all`,async(r,i)=>{if(i.startsWith(n)&&t.extensions.some(e=>i.endsWith(e)))try{let n=A(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||b.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=y.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=A(i);if(e){let t=r.get(i);t&&clearTimeout(t);let l=setTimeout(async()=>{r.delete(i);let t=!a.has(i),l=n;n=await c(o.config.root,t);let u=l!==n,d=j(i,s),f=[d];if(n)try{f=JSON.parse(n).routes.map(e=>e.path)}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let p=M(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=N(await v.readFile(i,`utf-8`));e&&(m=e,h=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{g=ne(await v.readFile(i,`utf-8`)),await re(y.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:y.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var ie=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer&&=(clearTimeout(this.resetTimer),null)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.resetTimer&&=(clearTimeout(this.resetTimer),null),this.reset()}},ae=class{serverComponentBuilder;rustServerUrl;pendingUpdates=new Map;pendingFiles=new Set;batchTimer=null;DEBOUNCE_DELAY=200;errorHandler;logBatch=[];logBatchTimer=null;LOG_BATCH_DELAY=500;constructor(e,t=3e3){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new ie({maxErrors:5,resetTimeout:3e4})}async handleClientComponentUpdate(e,t){let n=y.relative(b.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=await Promise.allSettled(e.map(async e=>{let t=y.relative(b.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),r=[],i=[];if(n.forEach(e=>{e.status===`fulfilled`&&e.value.success?r.push(e.value):e.status===`fulfilled`&&!e.value.success?i.push(e.value):e.status===`rejected`&&i.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),r.length>0){let e=Date.now();r.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(i.length>0){let e=Date.now();i.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});if(!n.ok){let e=await n.text();throw Error(`HTTP ${n.status}: ${e}`)}let r=await n.text(),i;try{i=JSON.parse(r)}catch(e){throw Error(`Failed to parse server response (status ${n.status}): ${e instanceof Error?e.message:String(e)}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`)}if(!i||typeof i!=`object`)throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);let a=i;if(!a.success)throw Error(a.message||a.error||`Component reload failed`)}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}detectComponentType(e){try{let t=_.readFileSync(e,`utf-8`).split(`
|
|
2
|
+
`);for(let e of t){let t=e.trim();if(!(!t||t.startsWith(`//`)||t.startsWith(`/*`))){if(t===`'use client'`||t===`"use client"`)return`client`;break}}return`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
|
|
3
|
+
• `);this.outputLog(t,`${n.length} updates:\n • ${e}`)}this.logBatch=[],this.logBatchTimer=null}outputLog(e,t){let n=`[rari] HMR:`;switch(e){case`success`:console.warn(`\x1B[32m${n}\x1B[0m ${t}`);break;case`warning`:console.warn(`\x1B[33m${n}\x1B[0m ${t}`);break;case`error`:console.error(`\x1B[31m${n}\x1B[0m ${t}`);break;default:console.warn(`${n} ${t}`);break}}dispose(){this.logBatchTimer&&(clearTimeout(this.logBatchTimer),this.flushLogs()),this.batchTimer&&=(clearTimeout(this.batchTimer),null);for(let e of this.pendingUpdates.values())clearTimeout(e);this.pendingUpdates.clear(),this.pendingFiles.clear(),this.errorHandler.dispose()}};const oe=/import\s+(\w+)\s+from\s+['"]rari\/image['"]/g,se=/import\s+\{[^}]*\b(?:Image\s+as\s+(\w+)|Image)\b[^}]*\}\s+from\s+['"]rari\/image['"]/g,ce=/src:\s*["']([^"']+)["']/,F=/[.*+?^${}()|[\]\\]/g,I=/width:\s*(\d+)/,L=/quality:\s*(\d+)/,R=/preload:\s*(true|!0)/,z=/preload:\s*(false|!1)/,B=/<Image\s([^/>]+)\/>/g,V=/<Image\s([^>]+)>/g,H=/src=\{?["']([^"']+)["']\}?|src=\{([^}]+)\}/,U=/width=\{?(\d+)\}?/,W=/quality=\{?(\d+)\}?/,G=/preload(?:=\{?true\}?)?/,le=/preload=\{?false\}?/;async function ue(e,t=[]){let r=new Map;async function i(e){if(!_.existsSync(e))return;let t=_.readdirSync(e,{withFileTypes:!0});for(let a of t){let t=y.join(e,a.name);if(a.isDirectory()){if(a.name===`node_modules`||a.name===`dist`)continue;await i(t)}else if(a.isFile()&&n.test(a.name))try{let e=_.readFileSync(t,`utf8`);if(!e.includes(`from 'rari/image'`)&&!e.includes(`from "rari/image"`))continue;await de(e,t,r)}catch(e){console.warn(`Failed to read or process file ${t}:`,e)}}}await i(e);for(let e of t)_.existsSync(e)&&await i(e);return{images:[...r.values()]}}async function de(e,t,n){try{let r;r=t.endsWith(`.tsx`)?`tsx`:t.endsWith(`.jsx`)?`jsx`:t.endsWith(`.ts`)?`ts`:`js`;let i=`\0virtual:${t}`,a=await S({input:i,platform:`browser`,write:!1,output:{format:`esm`},moduleTypes:{[`.${r}`]:r},transform:{jsx:`react`},plugins:[{name:`virtual-module`,resolveId(e){return e===i?e:null},load(t){return t===i?{code:e,moduleType:r}:null}}]});if(!a.output||a.output.length===0)throw Error(`Transform produced no output`);let o=a.output[0].code,s=new Set;for(let e of o.matchAll(oe))s.add(e[1]);for(let e of o.matchAll(se))e[1]?s.add(e[1]):s.add(`Image`);if(s.size===0)return;for(let e of s){let t=e.replace(F,`\\$&`),r=RegExp(`React\\.createElement\\(\\s*${t}\\s*,\\s*\\{([^}]+)\\}`,`g`);for(let e of o.matchAll(r)){let t=e[1],r=t.match(ce);if(!r)continue;let i=r[1];if(!i.startsWith(`/`)&&!i.startsWith(`http`))continue;let a=t.match(I),o=a?Number.parseInt(a[1],10):void 0,s=t.match(L),c=s?Number.parseInt(s[1],10):void 0,l=t.match(R),u=t.match(z),d=!!l&&!u,f=`${i}:${o||`auto`}:${c||75}`;(!n.has(f)||d)&&n.set(f,{src:i,width:o,quality:c,preload:d})}}}catch{fe(e,n)}}function fe(e,t){for(let n of e.matchAll(B))K(n[1],t);for(let n of e.matchAll(V))K(n[1],t)}function K(e,t){let n=e.match(H);if(!n)return;let r=n[1]||n[2];if(!r||r.includes(`{`)||!r.startsWith(`/`)&&!r.startsWith(`http`))return;let i=e.match(U),a=i?Number.parseInt(i[1],10):void 0,o=e.match(W),s=o?Number.parseInt(o[1],10):void 0,c=G.test(e)&&!le.test(e),l=`${r}:${a||`auto`}:${s||75}`;(!t.has(l)||c)&&t.set(l,{src:r,width:a,quality:s,preload:c})}const pe=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,me=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,he=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ge=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,_e=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ve=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ye=/import\s+["']\.\.?\/([^"']+)["'];?/g,be=/import\s*(?:\(\s*)?["']([^"']+)["']\)?/g,xe=/export\s*\{([^}]+)\}/g,Se=/\s+as\s+/,Ce=/export\s+default\s+(?:function|class)\s+\w+/,we=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,q=/export\s+default\s+([^;]+)/,Te=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,Ee=/^['"]use client['"];?\s*$/gm,De=/import\s+["']([^"']+)["']/g,J=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,Oe=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,ke=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,Ae=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,je=/import\s+["']([^"']+)["']/g,Y=/from(\s*)(['"])(?:\.\/|rari\/)react-server-dom-rari-client\.mjs\2/g,Me=/\bJSX\b/,Ne=/^components\//,Pe=/\{([^}]*)\}/,Fe={remotePatterns:[],localPatterns:[],deviceSizes:h,imageSizes:m,formats:f,qualityAllowlist:p,minimumCacheTTL:u,maxCacheSize:d};async function X(e){let t=import.meta.url,n=x(t),r=y.dirname(n),i=[y.join(r,`runtime`,e),y.join(r,`../runtime`,e)];for(let e of i)try{let t=await _.promises.readFile(e,`utf-8`);return e.endsWith(`.ts`)&&(t=t.replace(pe,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(me,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(he,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(ge,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(_e,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(ve,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(ye,(e,t)=>`import "rari/${t}";`)),t}catch(t){t.code!==`ENOENT`&&t.code!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${e}:`,t)}throw Error(`Could not find ${e}. Tried: ${i.join(`, `)}`)}async function Ie(){return X(`rsc-client-runtime.mjs`)}async function Le(e,t){return(await X(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function Re(){return X(`react-server-dom-shim.mjs`)}async function Z(e,t){let n=await ue(y.join(e,`src`)),r={...Fe,...t.images,preoptimizeManifest:n.images},i=y.join(e,`dist`),a=y.join(i,`server`);_.existsSync(a)||_.mkdirSync(a,{recursive:!0});let o=y.join(a,`image.json`);_.writeFileSync(o,JSON.stringify(r,null,2))}function Q(e,t=[]){let r=new Set;function i(e){if(!_.existsSync(e))return;let t=_.readdirSync(e,{withFileTypes:!0});for(let a of t){let t=y.join(e,a.name);if(a.isDirectory()){if(a.name===`node_modules`)continue;i(t)}else if(a.isFile()&&n.test(a.name))try{let e=_.readFileSync(t,`utf8`);(e.includes(`'use client'`)||e.includes(`"use client"`))&&r.add(t)}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error during file scan:`,t,e)}}}i(e);for(let e of t)_.existsSync(e)&&i(e);return r}function ze(e){return e}function $(e={}){let u=new Map,d=new Set,f=new Map,p=null,m=null,h={};function v(e){if(f.has(e))return f.get(e);let t={hasUseServer:!1,hasUseClient:!1},r=e.replace(o,`/`);if(!n.test(r)||!r.includes(`/src/`))return f.set(e,t),t;try{let n=_.readFileSync(e,`utf-8`);t.hasUseServer=n.includes(`'use server'`)||n.includes(`"use server"`),t.hasUseClient=n.includes(`'use client'`)||n.includes(`"use client"`),f.set(e,t)}catch{f.set(e,t)}return t}function S(t){if(t.includes(`node_modules`)||t.includes(`/rari/dist/`)||t.includes(`\\rari\\dist\\`))return!1;let n=e.projectRoot||b.cwd(),r=y.join(n,`index.html`);if(_.existsSync(r))try{let e=_.readFileSync(r,`utf-8`);for(let r of e.matchAll(be)){let e=r[1];if(e.startsWith(`/src/`)&&y.join(n,e.slice(1))===t)return!1}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading index.html:`,e)}let i;try{i=_.realpathSync(t)}catch{return!1}try{if(!_.existsSync(i))return!1;let e=_.readFileSync(i,`utf-8`),t=T(e,`use client`);return T(e,`use server`)?!1:!t}catch{return!1}}function C(e){try{let t=[],n=e.matchAll(xe);for(let e of n){let n=e[1].split(`,`);for(let e of n){let n=e.trim().split(Se).at(-1)?.trim();n&&t.push(n)}}(Ce.test(e)||r.test(e))&&t.push(`default`);let i=e.matchAll(Te);for(let e of i)e[1]&&t.push(e[1]);return[...new Set(t)]}catch{return[]}}function T(e,t){try{let n=e.split(`
|
|
4
|
+
`);for(let e of n){let n=e.trim();if(!(!n||n.startsWith(`//`)||n.startsWith(`/*`))){if(n===`'${t}'`||n===`"${t}"`||n===`'${t}';`||n===`"${t}";`)return!0;break}}return!1}catch{return!1}}function E(e,t){if(!T(e,`use server`))return e;let n=C(e);if(n.length===0)return e;let r=e;r+=`
|
|
5
|
+
|
|
6
|
+
import {registerServerReference} from "react-server-dom-rari/server";
|
|
7
|
+
`;for(let i of n)if(i===`default`){let n=e.match(we);if(n){let e=n[1];r+=`
|
|
8
|
+
// Register server reference for default export
|
|
9
|
+
`,r+=`registerServerReference(${e}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`}else{let n=e.match(q);if(n){let e=n[1].trim(),a=`__default_export__`;r=r.replace(q,`const ${a} = ${e};\nexport default ${a}`),r+=`
|
|
10
|
+
// Register server reference for default export
|
|
11
|
+
`,r+=`if (typeof ${a} === "function") {\n`,r+=` registerServerReference(${a}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`,r+=`}
|
|
12
|
+
`}}}else r+=`\n// Register server reference for ${i}\n`,r+=`if (typeof ${i} === "function") {\n`,r+=` registerServerReference(${i}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`,r+=`}
|
|
13
|
+
`;return r+=`
|
|
14
|
+
|
|
15
|
+
if (import.meta.hot) {
|
|
16
|
+
import.meta.hot.accept(() => {
|
|
17
|
+
});
|
|
18
|
+
}`,r}function D(e,t){let r=T(e,`use server`),i=S(t);if(r){let r=C(e);if(r.length===0)return``;let i=y.relative(b.cwd(),t).replace(o,`/`).replace(n,``).replace(a,`_`).replace(l,``),s=`import { createServerReference } from "rari/runtime/actions";
|
|
19
|
+
`;for(let e of r)e===`default`?s+=`export default createServerReference("default", ${JSON.stringify(i)}, "default");\n`:s+=`export const ${e} = createServerReference("${e}", ${JSON.stringify(i)}, "${e}");\n`;return s}if(i){let r=C(e);if(r.length===0)return``;let i=y.relative(b.cwd(),t).replace(o,`/`).replace(n,``).replace(a,`_`).replace(l,``).replace(Ne,``),s=`import { createServerComponentWrapper } from "virtual:rsc-integration.ts";
|
|
20
|
+
`;for(let e of r)e===`default`?s+=`export default createServerComponentWrapper("${i}", ${JSON.stringify(t)});\n`:s+=`export const ${e} = createServerComponentWrapper("${i}_${e}", ${JSON.stringify(t)});\n`;return s}if(!T(e,`use client`))return e;let s=C(e);if(s.length===0)return``;let c=`import {registerClientReference} from "react-server-dom-rari/server";
|
|
21
|
+
`;for(let e of s){if(e===`default`){let e=`Attempted to call the default export of ${t} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export default `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(e)});`}else{let t=`Attempted to call ${e}() from the server but ${e} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export const ${e} = `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(t)});`}c+=`},`,c+=`${JSON.stringify(t)},`,c+=`${JSON.stringify(e)});\n`}return c}function O(e,t){return!T(e,`use client`)||C(e).length===0?e:e.replace(Ee,``)}function k(e,t){let n=e;for(let[t,r]of Object.entries(h))if(e.startsWith(`${t}/`)){n=e.replace(t,r);break}else if(e===t){n=r;break}let r=y.resolve(y.dirname(t),n),i=[`.tsx`,`.jsx`,`.ts`,`.js`];for(let e of i){let t=`${r}${e}`;if(_.existsSync(t))return t}if(_.existsSync(r))for(let e of i){let t=y.join(r,`index${e}`);if(_.existsSync(t))return t}return`${r}.tsx`}function A(e){return(e.split(`/`).pop()||e).replace(i,``)}let j=!1;async function M(){let e=`http://localhost:${b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3)}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return j=t,t}catch{return j=!1,!1}}let N=[{name:`rari`,config(t,{command:r}){if(t.define=t.define||{},r===`serve`||b.env.RARI_SERVER_URL||b.env.RARI_HOST){let e=b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3),n;if(b.env.RARI_SERVER_URL)n=b.env.RARI_SERVER_URL;else if(b.env.RARI_HOST){let t=b.env.RARI_HOST.startsWith(`http`)?b.env.RARI_HOST:`http://${b.env.RARI_HOST}`;n=t.replace(c,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}if(r===`build`){let r=e.projectRoot||b.cwd(),i=y.join(r,`index.html`);if(_.existsSync(i))try{let e=_.readFileSync(i,`utf-8`),r=[];for(let t of e.matchAll(De)){let e=t[1];if(e.startsWith(`/src/`)&&n.test(e)){let t=e.slice(1),n=y.basename(t,y.extname(t));r.push({path:t,name:n})}}if(r.length>0){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{};let e=t.build.rolldownOptions.input||{main:`./index.html`},n;n=typeof e==`string`?{main:e}:Array.isArray(e)?{main:e[0]||`./index.html`}:{...e},r.forEach(({path:e,name:t})=>{n[t]=`./${e}`}),t.build.rolldownOptions.input=n}}catch(e){console.warn(`[rari] Error parsing index.html for build inputs:`,e)}}t.resolve=t.resolve||{};let i=Array.isArray(t.resolve.dedupe)?t.resolve.dedupe:[],a=[`react`,`react-dom`];t.resolve.dedupe=[...new Set([...i||[],...a])];let o=[];Array.isArray(t.resolve.alias)?o=t.resolve.alias:t.resolve.alias&&typeof t.resolve.alias==`object`&&(o=Object.entries(t.resolve.alias).map(([e,t])=>({find:e,replacement:t})));let s=new Set(o.map(e=>String(e.find)));try{let e=x(import.meta.resolve(`react`)),n=x(import.meta.resolve(`react-dom/client`)),r=x(import.meta.resolve(`react/jsx-runtime`)),i=[];s.has(`react/jsx-runtime`)||i.push({find:`react/jsx-runtime`,replacement:r});try{let e=x(import.meta.resolve(`react/jsx-dev-runtime`));s.has(`react/jsx-dev-runtime`)||i.push({find:`react/jsx-dev-runtime`,replacement:e})}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving react/jsx-dev-runtime:`,e)}s.has(`react`)||i.push({find:`react`,replacement:e}),s.has(`react-dom/client`)||i.push({find:`react-dom/client`,replacement:n}),i.length>0&&(t.resolve.alias=[...o,...i])}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error configuring React aliases:`,e)}t.environments=t.environments||{},t.environments.rsc={resolve:{conditions:[`react-server`,`node`,`import`]},...t.environments.rsc},t.environments.ssr={resolve:{conditions:[`node`,`import`]},...t.environments.ssr},t.environments.client={resolve:{conditions:[`browser`,`import`]},...t.environments.client},t.optimizeDeps=t.optimizeDeps||{},t.optimizeDeps.include=t.optimizeDeps.include||[];for(let e of[`react`,`react-dom`,`react-dom/client`,`react-dom/server`,`react/jsx-runtime`,`react/jsx-dev-runtime`])t.optimizeDeps.include.includes(e)||t.optimizeDeps.include.push(e);if(t.optimizeDeps.exclude=t.optimizeDeps.exclude||[],t.optimizeDeps.exclude.includes(`rari`)||t.optimizeDeps.exclude.push(`rari`),r===`build`)for(let e of[`rsc`,`ssr`,`client`]){let n=t.environments[e];n&&n.build&&(n.build.rolldownOptions=n.build.rolldownOptions||{})}t.server=t.server||{},t.server.proxy=t.server.proxy||{};let l=b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3);if(t.server.proxy[`/api`]={target:`http://localhost:${l}`,changeOrigin:!0,secure:!1,ws:!0},t.server.proxy[`/_rari`]={target:`http://localhost:${l}`,changeOrigin:!0,secure:!1,ws:!0},r===`build`){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{},t.build.rolldownOptions.input||(t.build.rolldownOptions.input={main:`./index.html`}),t.build.rolldownOptions.output=t.build.rolldownOptions.output||{};let e=Array.isArray(t.build.rolldownOptions.output)?t.build.rolldownOptions.output:[t.build.rolldownOptions.output];for(let t of e)t.advancedChunks=t.advancedChunks||{},t.advancedChunks.groups=t.advancedChunks.groups||[],t.advancedChunks.groups.push({name(e){return e.includes(`node_modules`)?e.includes(`node_modules/react-dom`)?`react-dom`:e.includes(`node_modules/react`)?`react`:`vendor`:null}}),t.chunkFileNames||=e=>e.moduleIds?.some(e=>v(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds?.some(e=>v(e).hasUseClient)?`client/components/[name]-[hash].js`:`assets/[name]-[hash].js`}return t.environments&&t.environments.client&&(t.environments.client.build||(t.environments.client.build={}),t.environments.client.build.rolldownOptions||(t.environments.client.build.rolldownOptions={}),t.environments.client.build.rolldownOptions.input||(t.environments.client.build.rolldownOptions.input={})),t},configResolved(e){let t=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react-dom/client`]);if(e.resolve?.alias){let n=e.resolve.alias;Array.isArray(n)?n.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!t.has(e.find)&&(h[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(h[e]=n)})}},transform(e,t){if(!n.test(t))return null;let r=this.environment;if(T(e,`use client`)){u.set(t,`client`),d.add(t);let n=e.split(`
|
|
22
|
+
`);for(let e of n){let n=e.match(J);if(!n)continue;let r=n[4];if(!r)continue;let i=k(r,t);_.existsSync(i)&&(u.set(i,`client`),d.add(i))}return O(e,t)}if(u.get(t)===`client`||d.has(t))return O(e,t);if(S(t)){if(u.set(t,`server`),r&&(r.name===`rsc`||r.name===`ssr`))return E(e,t);{let n=D(e,t);return n=`// HMR acceptance for server component
|
|
23
|
+
if (import.meta.hot) {
|
|
24
|
+
import.meta.hot.accept();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (typeof globalThis !== 'undefined') {
|
|
28
|
+
if (!globalThis['~rari']) globalThis['~rari'] = {};
|
|
29
|
+
globalThis['~rari'].serverComponents = globalThis['~rari'].serverComponents || new Set();
|
|
30
|
+
globalThis['~rari'].serverComponents.add(${JSON.stringify(t)});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
${n}`,n}}if(T(e,`use server`))return u.set(t,`server`),r&&(r.name===`rsc`||r.name===`ssr`)?E(e,t):D(e,t);let i=u.get(t);if(i===`server`)return r&&(r.name===`rsc`||r.name===`ssr`)?E(e,t):D(e,t);if(i===`client`)return O(e,t);u.set(t,`unknown`);let a=e.split(`
|
|
34
|
+
`),o=e,s=!1,c=!1,l=!1,f=[];for(let n of a){let i=n.match(J);if(!i)continue;let a=i[1],p=i[4],m=A(p),h=k(p,t),g=T(e,`use client`)||u.get(t)===`client`||t.includes(`entry-client`),v=u.get(h)===`client`||_.existsSync(h)&&_.readFileSync(h,`utf-8`).includes(`'use client'`);if(v&&(u.set(h,`client`),d.add(h)),v&&r&&(r.name===`rsc`||r.name===`ssr`)){if(!g){let e=n,t=a||`default`,r=`
|
|
35
|
+
import { registerClientReference } from "react-server-dom-rari/server";
|
|
36
|
+
const ${t} = registerClientReference(
|
|
37
|
+
function() {
|
|
38
|
+
throw new Error("Attempted to call ${t} from the server but it's on the client. It can only be rendered as a Component or passed to props of a Client Component.");
|
|
39
|
+
},
|
|
40
|
+
${JSON.stringify(h)},
|
|
41
|
+
${JSON.stringify(a||`default`)}
|
|
42
|
+
);`;o=o.replace(e,r),s=!0,c=!0}}else if(!g&&S(h)){s=!0,c=!0,l=!0;let e=n;a&&a!==`_`&&f.push(`const ${a} = createServerComponentWrapper('${m}', '${p}');`),o=o.replace(e,``)}}if(s){let e=o.includes(`import React`)||o.match(Oe)||o.match(ke),n=o.includes(`createServerComponentWrapper`),r=``;if(c&&!e&&(r+=`import React from 'react';
|
|
43
|
+
`),l&&!n&&(r+=`import { createServerComponentWrapper } from 'virtual:rsc-integration.ts';
|
|
44
|
+
`),f.length>0&&(r+=`${f.join(`
|
|
45
|
+
`)}\n`),r&&(o=r+o),!o.includes(`Suspense`)){let e=o.match(Ae);e&&(e[1]&&!e[2].includes(`Suspense`)?o=o.replace(e[0],e[0].replace(Pe,`{ Suspense, $1 }`)):e[1]||(o=o.replace(e[0],`import React, { Suspense } from 'react';`)))}let i=b.env.NODE_ENV!==`production`,a=o.includes(`</`)||o.includes(`/>`)||Me.test(o);return!o.includes(`'use client'`)&&!o.includes(`"use client"`)&&a&&i&&(o=`'use client';\n\n${o}`,u.set(t,`client`)),o}return null},async configureServer(t){let r=e.projectRoot||b.cwd(),a=y.join(r,`src`);await Z(r,e);let o=null,s=async()=>{try{let{ServerComponentBuilder:i,scanDirectory:a}=await import(`./server-build-BaEm53O_.mjs`).then(e=>e.n),s=new i(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:h,csp:e.csp,rateLimit:e.rateLimit,spamBlocker:e.spamBlocker,cacheControl:e.cacheControl});if(o=s,!m&&o){let e=b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3);m=new ae(o,e)}let c=y.join(r,`src`),l=[];if(_.existsSync(c)){let e=t=>{let r=_.readdirSync(t,{withFileTypes:!0});for(let i of r){let r=y.join(t,i.name);if(i.isDirectory())e(r);else if(i.isFile()&&n.test(i.name))try{S(r)&&l.push(r)}catch(e){console.error(`[rari] Error checking ${r}:`,e)}}};e(c),a(c,s)}l.length>0&&t.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:l}});let u=await s.getTransformedComponentsForDevelopment(),d=`http://localhost:${b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3)}`;for(let e of u)try{if(e.id.startsWith(`app/`)||e.code.includes(`"use server"`)||e.code.includes(`'use server'`))continue;let t=await fetch(`${d}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Runtime: Failed to register component ${e.id}:`,t instanceof Error?t.message:String(t))}}catch(e){console.error(`[rari] Runtime: Component discovery failed:`,e instanceof Error?e.message:String(e))}},c=async()=>{try{let e=`http://localhost:${b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3)}`,t=Q(a,Object.values(h));for(let n of t){let t=y.relative(b.cwd(),n),r=y.basename(n).replace(i,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:t,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${r}:`,e)}}}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},l=async()=>{if(p)return;let{getBinaryPath:e,getInstallationInstructions:n}=await import(`./platform.mjs`),r;try{r=e()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(n());return}let i=b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3),a=b.env.NODE_ENV===`production`?`production`:`development`,o=t.config.server.port||5173,l=[`--mode`,a,`--port`,i.toString(),`--host`,`127.0.0.1`];p=te(r,l,{stdio:[`ignore`,`pipe`,`pipe`],cwd:b.cwd(),env:{...b.env,RUST_LOG:b.env.RUST_LOG||`error`,RARI_VITE_PORT:o.toString()}}),p.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),p.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),p.on(`error`,e=>{j=!1,console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),p.on(`exit`,(e,t)=>{p=null,j=!1,t?console.error(`rari server stopped by signal ${t}`):e===0?console.error(`rari server stopped successfully`):e&&console.error(`rari server exited with code ${e}`)});let u=!1;for(let e=0;e<20&&(u=await M(),!u);e++)await new Promise(e=>setTimeout(e,500));u?(await c(),await s()):console.error(`Server failed to become ready for component registration`)},d=async t=>{try{if(!S(t))return;let{ServerComponentBuilder:n}=await import(`./server-build-BaEm53O_.mjs`).then(e=>e.n),i=new n(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:h,csp:e.csp,rateLimit:e.rateLimit,spamBlocker:e.spamBlocker,cacheControl:e.cacheControl});i.addServerComponent(t);let a=await i.getTransformedComponentsForDevelopment();if(a.length===0)return;let o=`http://localhost:${b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3)}`;for(let e of a)try{let t=await fetch(`${o}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}catch(e){console.error(`[rari] Targeted HMR failed for`,`${t}:`,e instanceof Error?e.message:String(e)),setTimeout(s,1e3)}};l().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),t.middlewares.use(async(e,t,n)=>{let r=e.headers.accept;if(r&&r.includes(`text/x-component`)&&e.url&&!e.url.startsWith(`/api`)&&!e.url.startsWith(`/rsc`)&&!e.url.includes(`.`)){if(!j&&!await M()){let e=Date.now();for(;Date.now()-e<1e4&&!await M();)await new Promise(e=>setTimeout(e,100));if(!j){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}}let n=b.env.SERVER_PORT?Number(b.env.SERVER_PORT):Number(b.env.PORT||b.env.RSC_PORT||3e3),r=`http://localhost:${n}${e.url}`;try{let i={};for(let[t,n]of Object.entries(e.headers))typeof n==`string`?i[t]=n:Array.isArray(n)&&(i[t]=n.join(`,`));i.host=`localhost:${n}`,i[`accept-encoding`]=`identity`;let a=await fetch(r,{method:e.method,headers:i});if(t.statusCode=a.status,a.headers.forEach((e,n)=>{n.toLowerCase()!==`content-encoding`&&t.setHeader(n,e)}),a.body){let e=a.body.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)break;t.write(ee.from(r))}t.end()}catch(e){console.error(`[rari] Stream error:`,e),t.headersSent||(t.statusCode=500),t.end()}}else t.end();return}catch(e){console.error(`[rari] Failed to proxy RSC request:`,e),t.headersSent||(t.statusCode=500,t.end(`Internal Server Error`));return}}n()}),t.watcher.on(`change`,async e=>{n.test(e)&&u.delete(e),n.test(e)&&e.includes(a)&&(S(e)?(t.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await d(e)):setTimeout(s,1e3))}),t.middlewares.use(`/api/vite/hmr-transform`,async(e,t)=>{if(e.method!==`POST`){t.statusCode=405,t.end(`Method Not Allowed`);return}let n=``;e.on(`data`,e=>{n+=e.toString()}),e.on(`end`,async()=>{try{let{filePath:e}=JSON.parse(n);if(!e){t.statusCode=400,t.end(JSON.stringify({error:`filePath is required`}));return}await d(e),t.statusCode=200,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!0,filePath:e,message:`Component transformation completed`}))}catch(e){t.statusCode=500,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)}))}})}),t.httpServer?.on(`close`,()=>{m&&=(m.dispose(),null),p&&=(p.kill(`SIGTERM`),null),j=!1})},resolveId(e,t){if(e===`virtual:rsc-integration`||e===`virtual:rsc-integration.ts`)return`virtual:rsc-integration.ts`;if(e===`virtual:rari-entry-client`||e===`virtual:rari-entry-client.ts`)return`virtual:rari-entry-client.ts`;if(e===`virtual:react-server-dom-rari-client`||e===`virtual:react-server-dom-rari-client.ts`)return`virtual:react-server-dom-rari-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`./DefaultLoadingIndicator`||e===`./DefaultLoadingIndicator.tsx`)return`virtual:default-loading-indicator.tsx`;if(e===`./LoadingErrorBoundary`||e===`./LoadingErrorBoundary.tsx`)return`virtual:loading-error-boundary.tsx`;if(e===`react-server-dom-rari/server`)return e;if(t&&t.startsWith(`virtual:`)&&e.startsWith(`../`)){let n=import.meta.url,r=x(n),i=y.dirname(r),a=null,o=[y.join(i,`runtime`),y.join(i,`../runtime`)];for(let e of o)if(_.existsSync(e)){a=e;break}if(a){let t=y.join(a,e);if(_.existsSync(t))return t;let n=y.join(a,`../dist`,y.basename(e));if(_.existsSync(n))return n}else console.warn(`[rari] Runtime directory not found, attempting fallback resolution for virtual import.\n Importer: ${t}\n ID: ${e}\n Current Dir: ${i}\n Hint: Runtime lookup failed, trying currentDir as fallback`);let s=y.join(i,e);if(_.existsSync(s))return s;let c=y.join(i,`../dist`,y.basename(e));if(_.existsSync(c))return c}if(b.env.NODE_ENV===`production`)try{let t=y.resolve(e);if(_.existsSync(t)&&S(t))return{id:e,external:!0}}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving server component:`,e,t)}return null},async load(i){if(n.test(i)){let e=this.environment;if(e&&e.name===`client`)try{let e=_.readFileSync(i,`utf-8`);if(T(e,`use server`))return D(e,i)}catch{}}if(i===`virtual:rari-entry-client.ts`){let e=Q(y.join(b.cwd(),`src`),Object.values(h)),i=new Set([...d,...e]),a=[{path:`rari/image`,exports:[`Image`]}],c=[...i].filter(e=>{try{return T(_.readFileSync(e,`utf-8`),`use client`)}catch{return!1}}).map(e=>{let i=y.relative(b.cwd(),e).replace(o,`/`),a=i.replace(n,``),c=i.startsWith(`..`)?e.replace(o,`/`):i,l=!1,u=``;try{let t=_.readFileSync(e,`utf-8`),n=r.test(t),i=t.match(s);!n&&i&&(l=!0,u=i[1])}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let d=c.replace(o,`/`),f=d.startsWith(`/`)||t.test(d)?d:`/${d}`;return` "${c}": {
|
|
46
|
+
id: "${a}",
|
|
47
|
+
path: "${c}",
|
|
48
|
+
type: "client",
|
|
49
|
+
loader: () => ${l?`import(${JSON.stringify(f)}).then(m => m.${u} || m.default || m)`:`import(${JSON.stringify(f)}).then(m => m.default || m)`},
|
|
50
|
+
component: null,
|
|
51
|
+
loading: false,
|
|
52
|
+
registered: false
|
|
53
|
+
}`}).join(`,
|
|
54
|
+
`),l=a.map((e,t)=>`import { ${e.exports.map(e=>`${e} as External${t}_${e}`).join(`, `)} } from '${e.path}';`).join(`
|
|
55
|
+
`),u=a.flatMap((e,t)=>e.exports.map(n=>{let r=`External${t}_${n}`;return`
|
|
56
|
+
globalThis['~clientComponents'] = globalThis['~clientComponents'] || {};
|
|
57
|
+
globalThis['~clientComponents']["${`${e.path}#${n}`}"] = {
|
|
58
|
+
id: "${n}",
|
|
59
|
+
path: "${e.path}",
|
|
60
|
+
type: "client",
|
|
61
|
+
component: ${r},
|
|
62
|
+
registered: true
|
|
63
|
+
};
|
|
64
|
+
globalThis['~clientComponents']["${e.path}"] = globalThis['~clientComponents']["${e.path}"] || {};
|
|
65
|
+
globalThis['~clientComponents']["${e.path}"].component = ${r};
|
|
66
|
+
globalThis['~clientComponentPaths'] = globalThis['~clientComponentPaths'] || {};
|
|
67
|
+
globalThis['~clientComponentPaths']["${e.path}"] = "${n}";`})).join(`
|
|
68
|
+
`);return await Le(l,[`
|
|
69
|
+
const lazyComponentRegistry = {
|
|
70
|
+
${c}
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
for (const [path, config] of Object.entries(lazyComponentRegistry)) {
|
|
74
|
+
globalThis['~clientComponents'][path] = config;
|
|
75
|
+
globalThis['~clientComponents'][config.id] = config;
|
|
76
|
+
globalThis['~clientComponentPaths'][path] = config.id;
|
|
77
|
+
}
|
|
78
|
+
`,u].filter(Boolean).join(`
|
|
79
|
+
`))}if(i===`react-server-dom-rari/server`)return await Re();if(i===`virtual:app-router-provider.tsx`){let e=[y.join(b.cwd(),`packages/rari/dist/runtime/AppRouterProvider.mjs`),y.join(b.cwd(),`node_modules/rari/dist/runtime/AppRouterProvider.mjs`)];for(let t of e)if(_.existsSync(t))return _.readFileSync(t,`utf-8`);return`export function AppRouterProvider({ children }) { return children; }`}if(i===`virtual:default-loading-indicator.tsx`){let e=[y.join(b.cwd(),`packages/rari/dist/runtime/DefaultLoadingIndicator.mjs`),y.join(b.cwd(),`node_modules/rari/dist/runtime/DefaultLoadingIndicator.mjs`)];for(let t of e)if(_.existsSync(t))return _.readFileSync(t,`utf-8`);return`export function DefaultLoadingIndicator() { return null; }`}if(i===`virtual:loading-error-boundary.tsx`){let e=[y.join(b.cwd(),`packages/rari/dist/runtime/LoadingErrorBoundary.mjs`),y.join(b.cwd(),`node_modules/rari/dist/runtime/LoadingErrorBoundary.mjs`)];for(let t of e)if(_.existsSync(t))return _.readFileSync(t,`utf-8`);return`export class LoadingErrorBoundary extends React.Component { render() { return this.props.children; } }`}if(i===`virtual:rsc-integration.ts`)return(await Ie()).replace(Y,(e,t,n)=>`from${t}${n}virtual:react-server-dom-rari-client.ts${n}`);if(i===`virtual:react-server-dom-rari-client.ts`)return await X(`react-server-dom-rari-client.mjs`);if(i.endsWith(`.mjs`)&&_.existsSync(i))try{let t=e.projectRoot||b.cwd(),n=_.realpathSync(i),r=y.relative(t,n),a=!r.startsWith(`..`)&&!y.isAbsolute(r),o=n.includes(`${y.sep}node_modules${y.sep}`),s=n.includes(`${y.sep}packages${y.sep}rari${y.sep}`)||n.includes(`${y.sep}node_modules${y.sep}rari${y.sep}`);return a||o||s?_.readFileSync(i,`utf-8`):(console.warn(`[rari] Refusing to load .mjs file outside project root and node_modules: ${i}`),null)}catch(e){return console.warn(`[rari] Error validating .mjs file path: ${i}`,e),null}},async handleHotUpdate({file:e,server:t}){if(!n.test(e))return;if(e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let r=m?.detectComponentType(e)||`unknown`,i=e.includes(`/app/`)||e.includes(`\\app\\`),a=e.endsWith(`page.tsx`)||e.endsWith(`page.jsx`),o=e.endsWith(`layout.tsx`)||e.endsWith(`layout.jsx`),s=e.endsWith(`loading.tsx`)||e.endsWith(`loading.jsx`),c=e.endsWith(`error.tsx`)||e.endsWith(`error.jsx`),l=e.endsWith(`not-found.tsx`)||e.endsWith(`not-found.jsx`);if(!(i&&(a||o||s||c||l))&&r!==`client`&&r===`server`)return m&&await m.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(je)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}return t.length>0?{html:e,tags:t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`}))}:e}},async writeBundle(){await Z(e.projectRoot||b.cwd(),e)}},g({...e.serverBuild,csp:e.csp,rateLimit:e.rateLimit,spamBlocker:e.spamBlocker,cacheControl:e.cacheControl})];return e.proxy!==!1&&N.push(w(e.proxy||{})),e.router!==!1&&N.push(P(e.router||{})),N}function Be(e){return{plugins:[$(),...e.plugins||[]],...e}}export{w as a,P as i,ze as n,C as o,$ as r,Be as t};
|
package/dist/vite.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { _ as SitemapVideo, a as generateAppRouteManifest, c as ApiResponse, d as RouteHandler, f as Robots, g as SitemapImage, h as SitemapEntry, i as rariRouter, l as ApiRouteHandlers, m as Sitemap, n as defineRariOptions, o as ProxyPluginOptions, p as RobotsRule, r as rari, s as rariProxy, t as defineRariConfig, u as RouteContext } from "./index-
|
|
1
|
+
import { A as RouteSegmentType, B as hasServerSideDataFetching, C as LayoutEntry, D as NotFoundEntry, E as Metadata, F as clearPropsCacheForComponent, I as extractMetadata, L as extractServerProps, M as ServerSidePropsResult, N as StaticParamsResult, O as PageProps, P as clearPropsCache, R as extractServerPropsWithCache, S as GenerateStaticParams, T as LoadingEntry, _ as AppRouteManifest, a as ServerSpamBlockerConfig, b as ErrorProps, f as RuntimeClient, g as AppRouteEntry, i as ServerRateLimitConfig, j as MetadataResult, k as RouteSegment, l as HttpRuntimeClient, m as createHttpRuntimeClient, r as ServerConfig, t as ServerCSPConfig, v as AppRouteMatch, w as LayoutProps, x as GenerateMetadata, y as ErrorEntry, z as extractStaticParams } from "./server-config-Bi4AvErE.mjs";
|
|
2
|
+
import { _ as SitemapVideo, a as generateAppRouteManifest, c as ApiResponse, d as RouteHandler, f as Robots, g as SitemapImage, h as SitemapEntry, i as rariRouter, l as ApiRouteHandlers, m as Sitemap, n as defineRariOptions, o as ProxyPluginOptions, p as RobotsRule, r as rari, s as rariProxy, t as defineRariConfig, u as RouteContext } from "./index-Dc4oQSkA.mjs";
|
|
3
3
|
import { a as ProxyModule, c as RariURL, i as ProxyMatcher, l as RequestCookies, n as ProxyConfig, o as ProxyResult, r as ProxyFunction, s as RariFetchEvent, t as CookieOptions, u as ResponseCookies } from "./types-BQ-op_Tc.mjs";
|
|
4
4
|
import { RariRequest } from "./proxy/RariRequest.mjs";
|
|
5
5
|
import { RariResponse } from "./proxy/RariResponse.mjs";
|
package/dist/vite.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"./vite-
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./vite-Dm2UZbFt.mjs";import{RariRequest as o}from"./proxy/RariRequest.mjs";import{RariResponse as s}from"./proxy/RariResponse.mjs";import{c,d as l,f as u,g as d,h as f,i as p,m,p as h,u as g}from"./runtime-client-Bg4V1Ksp.mjs";import"./regex-constants-DMuIAFub.mjs";import{t as _}from"./routes-DXBE0bwy.mjs";import"./constants-DZAg-dr0.mjs";import"./server-build-BaEm53O_.mjs";export{r as ApiResponse,p as HttpRuntimeClient,o as RariRequest,s as RariResponse,g as clearPropsCache,l as clearPropsCacheForComponent,c as createHttpRuntimeClient,a as defineRariConfig,n as defineRariOptions,u as extractMetadata,h as extractServerProps,m as extractServerPropsWithCache,f as extractStaticParams,_ as generateAppRouteManifest,d as hasServerSideDataFetching,i as rari,e as rariProxy,t as rariRouter};
|
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,18 +102,18 @@
|
|
|
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
|
-
"@types/node": "^25.
|
|
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.
|
|
116
|
-
"oxlint": "^1.
|
|
115
|
+
"@typescript/native-preview": "^7.0.0-dev.20260221.1",
|
|
116
|
+
"oxlint": "^1.49.0",
|
|
117
117
|
"rolldown-vite": "^7.3.1",
|
|
118
118
|
"tsdown": "^0.20.3",
|
|
119
119
|
"@rari/deploy": "0.1.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{S as e,t}from"./regex-constants-BM4Vd-_c.mjs";async function n(n){let r=globalThis[`~clientComponents`]||{},i=[];for(let[,a]of n){let n=[a.id,`${a.id}#${a.name||`default`}`,a.id.replace(e,``),a.id.replace(t,`/`)];for(let e of n){let t=r[e];if(t?.loader&&!t.component&&!t.loading){t.loading=!0,t.loadPromise=t.loader().then(e=>{t.component=e.default||e,t.registered=!0,t.loading=!1}).catch(n=>{t.loading=!1,t.loadPromise=void 0,console.error(`[rari] Failed to preload component ${e}:`,n)}),i.push(t.loadPromise);break}}}i.length>0&&await Promise.all(i)}export{n as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=/\.(?:tsx?|jsx?)$/,t=/^[A-Z]:\\/i,n=/\\/g,r=/[/\\]/,i=/^src\//,a=/^file:\/\//,o={AMPERSAND:/&/g,LT:/</g,GT:/>/g,QUOTE:/"/g,APOS:/'/g},s=o.AMPERSAND,c=o.LT,l=o.GT,u=o.QUOTE,d=o.APOS,f=s,p=c,m=l,h=u,g=d,_=s,v=c,y=l,b=u,x=d,S=/[^\w/-]/g,C=/^\d+$/,w=/([a-z])([A-Z])/g,T=/export\s+default\s+/,E=/^export\s+default\s+function\s+(\w+)/gm,D=/^export\s+default\s+async\s+function\s+(\w+)/gm,O=/^export\s+default\s+(\w+);?\s*$/gm,k=/^export\s*\{\s*(\w+)\s+as\s+default\s*\};?\s*$/gm,A=/^export\s+(?:async\s+)?function\s+(\w+)/gm,j=/export\s+(?:function|const|class)\s+(\w+)/,M=/\.[^.]*$/,N=/\r?\n/,P=/['"]/g;export{e as C,y as D,x as E,v as O,i as S,_ as T,h as _,k as a,r as b,T as c,M as d,a as f,p as g,m as h,D as i,b as k,A as l,g as m,w as n,E as o,f as p,S as r,O as s,n as t,j as u,N as v,t as w,P as x,C as y};
|
package/dist/routes-DEvXO96u.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{b as t,t as n}from"./regex-constants-BM4Vd-_c.mjs";import{promises as r}from"node:fs";import i from"node:path";var a=e({generateAppRouteManifest:()=>f});const o={PAGE:`page`,LAYOUT:`layout`,LOADING:`loading`,ERROR:`error`,NOT_FOUND:`not-found`,TEMPLATE:`template`,DEFAULT:`default`,ROUTE:`route`,OG_IMAGE:`opengraph-image`,TWITTER_IMAGE:`twitter-image`,ICON:`icon`,APPLE_ICON:`apple-icon`},s={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},c=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,l=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,u=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var d=class{appDir;extensions;verbose;constructor(e){this.appDir=i.resolve(e.appDir),this.extensions=e.extensions||[`.tsx`,`.jsx`,`.ts`,`.js`],this.verbose=e.verbose||!1}async generateManifest(){this.verbose&&console.warn(`[rari] Router: Scanning app directory: ${this.appDir}`);let e=[],t=[],n=[],r=[],i=[],a=[],o=[];return await this.scanDirectory(``,e,t,n,r,i,a,o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} API routes`),console.warn(`[rari] Router: Found ${o.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,apiRoutes:this.sortApiRoutes(a),ogImages:o,generated:new Date().toISOString()}}async scanDirectory(e,t,n,a,o,s,c,l){let u=i.join(this.appDir,e),d;try{d=await r.readdir(u)}catch{return}let f=[],p=[];for(let e of d){let t=i.join(u,e),n=await r.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&p.push(e):n.isFile()&&f.push(e)}await this.processSpecialFiles(e,f,t,n,a,o,s,c,l);for(let r of p){let u=e?i.join(e,r):r;await this.scanDirectory(u,t,n,a,o,s,c,l)}}async processSpecialFiles(e,t,n,a,s,u,d,f,p){let m=this.pathToRoute(e),h=this.findFile(t,o.PAGE);if(h){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:m,filePath:i.join(e,h),segments:t,params:r,isDynamic:r.length>0})}let g=this.findFile(t,o.LAYOUT);if(g){let t=this.getParentPath(e);a.push({path:m,filePath:i.join(e,g),parentPath:t?this.pathToRoute(t):void 0})}let _=this.findFile(t,o.LOADING);if(_){let t=this.generateComponentId(m,`loading`);s.push({path:m,filePath:i.join(e,_),componentId:t})}let v=this.findFile(t,o.ERROR);v&&u.push({path:m,filePath:i.join(e,v)});let y=this.findFile(t,o.NOT_FOUND);y&&d.push({path:m,filePath:i.join(e,y)});let b=this.findFile(t,o.OG_IMAGE);if(b){let t=i.join(e,b),n=i.join(this.appDir,t),a,o,s;try{let e=await r.readFile(n,`utf-8`),t=e.match(c);t&&(a=Number.parseInt(t[1],10),o=Number.parseInt(t[2],10));let i=e.match(l);i&&(s=i[1])}catch{}p.push({path:m,filePath:t,width:a,height:o,contentType:s})}let x=this.findFile(t,o.ROUTE);if(x){let t=await this.processApiRouteFile(e,x);f.push(t)}}findFile(e,t){for(let n of this.extensions){let r=`${t}${n}`;if(e.includes(r))return r}}pathToRoute(e){return e?`/${e.replace(n,`/`).split(`/`).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?`[[...${e.match(s.OPTIONAL_CATCH_ALL)[1]}]]`:s.CATCH_ALL.test(e)?`[...${e.match(s.CATCH_ALL)[1]}]`:s.DYNAMIC.test(e)?`[${e.match(s.DYNAMIC)[1]}]`:e).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(t).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?{type:`optional-catch-all`,value:e,param:e.match(s.OPTIONAL_CATCH_ALL)[1]}:s.CATCH_ALL.test(e)?{type:`catch-all`,value:e,param:e.match(s.CATCH_ALL)[1]}:s.DYNAMIC.test(e)?{type:`dynamic`,value:e,param:e.match(s.DYNAMIC)[1]}:{type:`static`,value:e}):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let n=e.split(t).filter(Boolean);return n.length===0?null:n.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=i.join(this.appDir,e),n=await r.readFile(t,`utf-8`),a=[];for(let e of u){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),r=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||r.test(n))&&a.push(e)}return a}async processApiRouteFile(e,t){let n=i.join(e,t),r=this.pathToRoute(e),a=this.parseRouteSegments(e),o=this.extractParams(a),s=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:a,params:o,isDynamic:o.length>0,methods:s}}};async function f(e,t={}){return new d({appDir:e,...t}).generateManifest()}export{a as n,f as t};
|
package/dist/vite-BTJjUXqs.mjs
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import{C as e,S as t,c as n,d as r,r as i,t as a,u as o,w as s,x as c}from"./regex-constants-BM4Vd-_c.mjs";import{a as l,i as u,n as d,o as f,r as p,t as m}from"./constants-DZAg-dr0.mjs";import{t as h}from"./server-build-emJwCUjS.mjs";import g,{promises as _}from"node:fs";import v from"node:path";import y from"node:process";import{Buffer as ee}from"node:buffer";import{spawn as te}from"node:child_process";import{fileURLToPath as b}from"node:url";import{build as x}from"rolldown";var S=class extends Response{static json(e,t){let n=new Headers(t?.headers);return n.has(`content-type`)||n.set(`content-type`,`application/json`),new Response(JSON.stringify(e),{...t,headers:n})}static redirect(e,t=307){return new Response(null,{status:t,headers:{location:e}})}static noContent(e){return new Response(null,{...e,status:204})}};function C(e={}){let{root:t=y.cwd(),srcDir:n=`src`,proxyFileName:r=`proxy`,extensions:i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`],verbose:a=!1}=e,o=null,s=e=>{a&&console.warn(`[rari] Proxy: ${e}`)};async function c(){for(let e of i){let n=`${r}${e}`,i=v.join(t,n);try{return await _.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=v.join(t,n);try{await _.access(e);for(let t of i){let i=`${r}${t}`,a=v.join(e,i);try{return await _.access(a),s(`Found proxy file: ${v.join(n,i)}`),{filePath:a,exists:!0,relativePath:v.join(n,i)}}catch{}}}catch{}return null}return{name:`rari:proxy`,async buildStart(){o=await c(),s(o?`Proxy enabled: ${o.relativePath}`:`No proxy file found`)},configureServer(e){o&&(e.watcher.add(o.filePath),e.watcher.on(`change`,t=>{t===o?.filePath&&(s(`Proxy file changed, reloading...`),e.ws.send({type:`custom`,event:`rari:proxy-reload`}))}))},async handleHotUpdate({file:e,server:t}){if(o&&e===o.filePath)return s(`Hot reloading proxy...`),t.ws.send({type:`custom`,event:`rari:proxy-reload`,data:{file:o.relativePath}}),[]}}}const w=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,T=/title\s*:\s*['"]([^'"]+)['"]/,E=/description\s*:\s*['"]([^'"]+)['"]/,D=/keywords\s*:\s*\[([\s\S]*?)\]/,O={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function k(t){switch(v.basename(t).replace(e,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function A(e,t){let n=v.relative(t,v.dirname(e));return!n||n===`.`?`/`:`/${n.replace(a,`/`).split(`/`).filter(Boolean).join(`/`)}`}function j(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function M(e){try{let t=e.match(w);if(!t)return null;let n=t[1],r={},i=n.match(T);i&&(r.title=i[1]);let a=n.match(E);a&&(r.description=a[1]);let o=n.match(D);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(c,``)).filter(Boolean));for(let e of[`author`,`viewport`,`themeColor`,`robots`,`openGraph`,`twitter`]){let t=RegExp(`${e}\\s*:\\s*['"]([^'"]+)['"]`,`m`),i=n.match(t);i&&(r[e]=i[1])}return Object.keys(r).length>0?r:null}catch(e){return console.error(`[rari] Router: Failed to extract metadata:`,e),null}}function ne(e){let t=[];for(let n of[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]){let r=RegExp(`export\\s+(?:async\\s+)?function\\s+${n}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${n}\\s*=`);(r.test(e)||i.test(e))&&t.push(n)}return t}async function re(e){try{let t=await fetch(`http://localhost:3000/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate-api-route`,filePath:e})});if(!t.ok){console.error(`[rari] Router: Failed to invalidate API route cache: ${t.statusText}`);return}let n=await t.json();n.success||console.error(`[rari] HMR: Failed to invalidate API route cache: ${n.error||`Unknown error`}`)}catch(e){console.error(`[rari] Router: Failed to notify API route invalidation:`,e)}}function N(e={}){let t={...O,...e},n=null,r=new Map,i=null,a=new Set,o=e=>[...e].toSorted().join(`|`),s=async e=>{let n=new Set,r=async e=>{try{let i=await _.readdir(e,{withFileTypes:!0});for(let a of i){let i=v.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&k(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=v.resolve(e,t.appDir);try{await _.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let{generateAppRouteManifest:d}=await import(`./routes-DEvXO96u.mjs`).then(e=>e.n),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=v.resolve(e,t.outDir);await _.mkdir(m,{recursive:!0});let h=v.join(m,`server`);return await _.mkdir(h,{recursive:!0}),await _.writeFile(v.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=v.resolve(e.config.root,t.appDir);e.watcher.on(`all`,async(r,i)=>{if(i.startsWith(n)&&t.extensions.some(e=>i.endsWith(e)))try{let n=k(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||y.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=v.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=k(i);if(e){let t=r.get(i);t&&clearTimeout(t);let l=setTimeout(async()=>{r.delete(i);let t=!a.has(i),l=n;n=await c(o.config.root,t);let u=l!==n,d=A(i,s),f=[d];if(n)try{f=JSON.parse(n).routes.map(e=>e.path)}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let p=j(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=M(await _.readFile(i,`utf-8`));e&&(m=e,h=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{g=ne(await _.readFile(i,`utf-8`)),await re(v.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let y={fileType:e,filePath:v.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:y})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var ie=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer&&=(clearTimeout(this.resetTimer),null)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.resetTimer&&=(clearTimeout(this.resetTimer),null),this.reset()}},ae=class{serverComponentBuilder;rustServerUrl;pendingUpdates=new Map;pendingFiles=new Set;batchTimer=null;DEBOUNCE_DELAY=200;errorHandler;logBatch=[];logBatchTimer=null;LOG_BATCH_DELAY=500;constructor(e,t=3e3){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new ie({maxErrors:5,resetTimeout:3e4})}async handleClientComponentUpdate(e,t){let n=v.relative(y.cwd(),e),r=Date.now();this.queueLog(`info`,`Client component changed: ${n}`);try{let i=t.moduleGraph.getModuleById(e);if(i){t.moduleGraph.invalidateModule(i);let e=Date.now()-r;this.queueLog(`success`,`Client component updated: ${n} (${e}ms)`),this.errorHandler.reset()}else this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=Date.now();if(e.length===1){let t=v.relative(y.cwd(),e[0]);this.queueLog(`info`,`Rebuilding server component: ${t}`)}else this.queueLog(`info`,`Rebuilding ${e.length} server components in batch`);let r=await Promise.allSettled(e.map(async e=>{let t=v.relative(y.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),i=[],a=[];r.forEach(e=>{e.status===`fulfilled`&&e.value.success?i.push(e.value):e.status===`fulfilled`&&!e.value.success?a.push(e.value):e.status===`rejected`&&a.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})});let o=Date.now()-n;if(i.length>0){let e=Date.now();i.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),i.length===1?this.queueLog(`success`,`Server component updated: ${i[0].relativePath} (${o}ms)`):this.queueLog(`success`,`${i.length} server components updated (${o}ms)`),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(a.length>0){let e=Date.now();a.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});if(!n.ok){let e=await n.text();throw Error(`HTTP ${n.status}: ${e}`)}}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}detectComponentType(e){try{let t=g.readFileSync(e,`utf-8`).split(`
|
|
2
|
-
`);for(let e of t){let t=e.trim();if(!(!t||t.startsWith(`//`)||t.startsWith(`/*`))){if(t===`'use client'`||t===`"use client"`)return`client`;break}}return`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
|
|
3
|
-
• `);this.outputLog(t,`${n.length} updates:\n • ${e}`)}this.logBatch=[],this.logBatchTimer=null}outputLog(e,t){let n=`[rari] HMR:`;switch(e){case`success`:console.warn(`\x1B[32m${n}\x1B[0m ${t}`);break;case`warning`:console.warn(`\x1B[33m${n}\x1B[0m ${t}`);break;case`error`:console.error(`\x1B[31m${n}\x1B[0m ${t}`);break;default:console.warn(`${n} ${t}`);break}}dispose(){this.logBatchTimer&&(clearTimeout(this.logBatchTimer),this.flushLogs()),this.batchTimer&&=(clearTimeout(this.batchTimer),null);for(let e of this.pendingUpdates.values())clearTimeout(e);this.pendingUpdates.clear(),this.pendingFiles.clear(),this.errorHandler.dispose()}};const oe=/import\s+(\w+)\s+from\s+['"]rari\/image['"]/g,se=/import\s+\{[^}]*\b(?:Image\s+as\s+(\w+)|Image)\b[^}]*\}\s+from\s+['"]rari\/image['"]/g,ce=/src:\s*["']([^"']+)["']/,P=/[.*+?^${}()|[\]\\]/g,F=/width:\s*(\d+)/,I=/quality:\s*(\d+)/,L=/preload:\s*(true|!0)/,R=/preload:\s*(false|!1)/,z=/<Image\s([^/>]+)\/>/g,B=/<Image\s([^>]+)>/g,V=/src=\{?["']([^"']+)["']\}?|src=\{([^}]+)\}/,H=/width=\{?(\d+)\}?/,U=/quality=\{?(\d+)\}?/,W=/preload(?:=\{?true\}?)?/,G=/preload=\{?false\}?/;async function le(t,n=[]){let r=new Map;async function i(t){if(!g.existsSync(t))return;let n=g.readdirSync(t,{withFileTypes:!0});for(let a of n){let n=v.join(t,a.name);if(a.isDirectory()){if(a.name===`node_modules`||a.name===`dist`)continue;await i(n)}else if(a.isFile()&&e.test(a.name))try{let e=g.readFileSync(n,`utf8`);if(!e.includes(`from 'rari/image'`)&&!e.includes(`from "rari/image"`))continue;await ue(e,n,r)}catch(e){console.warn(`Failed to read or process file ${n}:`,e)}}}await i(t);for(let e of n)g.existsSync(e)&&await i(e);return{images:[...r.values()]}}async function ue(e,t,n){try{let r;r=t.endsWith(`.tsx`)?`tsx`:t.endsWith(`.jsx`)?`jsx`:t.endsWith(`.ts`)?`ts`:`js`;let i=`\0virtual:${t}`,a=await x({input:i,platform:`browser`,write:!1,output:{format:`esm`},moduleTypes:{[`.${r}`]:r},transform:{jsx:`react`},plugins:[{name:`virtual-module`,resolveId(e){return e===i?e:null},load(t){return t===i?{code:e,moduleType:r}:null}}]});if(!a.output||a.output.length===0)throw Error(`Transform produced no output`);let o=a.output[0].code,s=new Set;for(let e of o.matchAll(oe))s.add(e[1]);for(let e of o.matchAll(se))e[1]?s.add(e[1]):s.add(`Image`);if(s.size===0)return;for(let e of s){let t=e.replace(P,`\\$&`),r=RegExp(`React\\.createElement\\(\\s*${t}\\s*,\\s*\\{([^}]+)\\}`,`g`);for(let e of o.matchAll(r)){let t=e[1],r=t.match(ce);if(!r)continue;let i=r[1];if(!i.startsWith(`/`)&&!i.startsWith(`http`))continue;let a=t.match(F),o=a?Number.parseInt(a[1],10):void 0,s=t.match(I),c=s?Number.parseInt(s[1],10):void 0,l=t.match(L),u=t.match(R),d=!!l&&!u,f=`${i}:${o||`auto`}:${c||75}`;(!n.has(f)||d)&&n.set(f,{src:i,width:o,quality:c,preload:d})}}}catch{de(e,n)}}function de(e,t){for(let n of e.matchAll(z))K(n[1],t);for(let n of e.matchAll(B))K(n[1],t)}function K(e,t){let n=e.match(V);if(!n)return;let r=n[1]||n[2];if(!r||r.includes(`{`)||!r.startsWith(`/`)&&!r.startsWith(`http`))return;let i=e.match(H),a=i?Number.parseInt(i[1],10):void 0,o=e.match(U),s=o?Number.parseInt(o[1],10):void 0,c=W.test(e)&&!G.test(e),l=`${r}:${a||`auto`}:${s||75}`;(!t.has(l)||c)&&t.set(l,{src:r,width:a,quality:s,preload:c})}const fe=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,pe=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,me=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,he=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ge=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,_e=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ve=/import\s+["']\.\.?\/([^"']+)["'];?/g,ye=/import\s*(?:\(\s*)?["']([^"']+)["']\)?/g,be=/export\s*\{([^}]+)\}/g,xe=/\s+as\s+/,Se=/export\s+default\s+(?:function|class)\s+\w+/,Ce=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,q=/export\s+default\s+([^;]+)/,we=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,Te=/^['"]use client['"];?\s*$/gm,Ee=/import\s+["']([^"']+)["']/g,J=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,De=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,Oe=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,ke=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,Ae=/import\s+["']([^"']+)["']/g,je=/from(\s*)(['"])(?:\.\/|rari\/)react-server-dom-rari-client\.mjs\2/g,Y=/\bJSX\b/,Me=/^components\//,Ne=/\{([^}]*)\}/,Pe={remotePatterns:[],localPatterns:[],deviceSizes:m,imageSizes:p,formats:d,qualityAllowlist:f,minimumCacheTTL:l,maxCacheSize:u};async function X(e){let t=import.meta.url,n=b(t),r=v.dirname(n),i=[v.join(r,`runtime`,e),v.join(r,`../runtime`,e)];for(let e of i)try{let t=await g.promises.readFile(e,`utf-8`);return e.endsWith(`.ts`)&&(t=t.replace(fe,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(pe,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(me,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(he,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(ge,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(_e,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(ve,(e,t)=>`import "rari/${t}";`)),t}catch(t){t.code!==`ENOENT`&&t.code!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${e}:`,t)}throw Error(`Could not find ${e}. Tried: ${i.join(`, `)}`)}async function Fe(){return X(`rsc-client-runtime.mjs`)}async function Ie(e,t){return(await X(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function Le(){return X(`react-server-dom-shim.mjs`)}async function Z(e,t){let n=await le(v.join(e,`src`)),r={...Pe,...t.images,preoptimizeManifest:n.images},i=v.join(e,`dist`),a=v.join(i,`server`);g.existsSync(a)||g.mkdirSync(a,{recursive:!0});let o=v.join(a,`image.json`);g.writeFileSync(o,JSON.stringify(r,null,2))}function Q(t,n=[]){let r=new Set;function i(t){if(!g.existsSync(t))return;let n=g.readdirSync(t,{withFileTypes:!0});for(let a of n){let n=v.join(t,a.name);if(a.isDirectory()){if(a.name===`node_modules`)continue;i(n)}else if(a.isFile()&&e.test(a.name))try{let e=g.readFileSync(n,`utf8`);(e.includes(`'use client'`)||e.includes(`"use client"`))&&r.add(n)}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error during file scan:`,n,e)}}}i(t);for(let e of n)g.existsSync(e)&&i(e);return r}function Re(e){return e}function $(c={}){let l=new Map,u=new Set,d=new Map,f=null,p=null,m={};function _(t){if(d.has(t))return d.get(t);let n={hasUseServer:!1,hasUseClient:!1},r=t.replace(a,`/`);if(!e.test(r)||!r.includes(`/src/`))return d.set(t,n),n;try{let e=g.readFileSync(t,`utf-8`);n.hasUseServer=e.includes(`'use server'`)||e.includes(`"use server"`),n.hasUseClient=e.includes(`'use client'`)||e.includes(`"use client"`),d.set(t,n)}catch{d.set(t,n)}return n}function x(e){if(e.includes(`node_modules`)||e.includes(`/rari/dist/`)||e.includes(`\\rari\\dist\\`))return!1;let t=c.projectRoot||y.cwd(),n=v.join(t,`index.html`);if(g.existsSync(n))try{let r=g.readFileSync(n,`utf-8`);for(let n of r.matchAll(ye)){let r=n[1];if(r.startsWith(`/src/`)&&v.join(t,r.slice(1))===e)return!1}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading index.html:`,e)}let r;try{r=g.realpathSync(e)}catch{return!1}try{if(!g.existsSync(r))return!1;let e=g.readFileSync(r,`utf-8`),t=w(e,`use client`);return w(e,`use server`)?!1:!t}catch{return!1}}function S(e){try{let t=[],r=e.matchAll(be);for(let e of r){let n=e[1].split(`,`);for(let e of n){let n=e.trim().split(xe).at(-1)?.trim();n&&t.push(n)}}(Se.test(e)||n.test(e))&&t.push(`default`);let i=e.matchAll(we);for(let e of i)e[1]&&t.push(e[1]);return[...new Set(t)]}catch{return[]}}function w(e,t){try{let n=e.split(`
|
|
4
|
-
`);for(let e of n){let n=e.trim();if(!(!n||n.startsWith(`//`)||n.startsWith(`/*`))){if(n===`'${t}'`||n===`"${t}"`||n===`'${t}';`||n===`"${t}";`)return!0;break}}return!1}catch{return!1}}function T(e,t){if(!w(e,`use server`))return e;let n=S(e);if(n.length===0)return e;let r=e;r+=`
|
|
5
|
-
|
|
6
|
-
import {registerServerReference} from "react-server-dom-rari/server";
|
|
7
|
-
`;for(let i of n)if(i===`default`){let n=e.match(Ce);if(n){let e=n[1];r+=`
|
|
8
|
-
// Register server reference for default export
|
|
9
|
-
`,r+=`registerServerReference(${e}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`}else{let n=e.match(q);if(n){let e=n[1].trim(),a=`__default_export__`;r=r.replace(q,`const ${a} = ${e};\nexport default ${a}`),r+=`
|
|
10
|
-
// Register server reference for default export
|
|
11
|
-
`,r+=`if (typeof ${a} === "function") {\n`,r+=` registerServerReference(${a}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`,r+=`}
|
|
12
|
-
`}}}else r+=`\n// Register server reference for ${i}\n`,r+=`if (typeof ${i} === "function") {\n`,r+=` registerServerReference(${i}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`,r+=`}
|
|
13
|
-
`;return r+=`
|
|
14
|
-
|
|
15
|
-
if (import.meta.hot) {
|
|
16
|
-
import.meta.hot.accept(() => {
|
|
17
|
-
});
|
|
18
|
-
}`,r}function E(n,r){let o=w(n,`use server`),s=x(r);if(o){let o=S(n);if(o.length===0)return``;let s=v.relative(y.cwd(),r).replace(a,`/`).replace(e,``).replace(i,`_`).replace(t,``),c=`import { createServerReference } from "rari/runtime/actions";
|
|
19
|
-
`;for(let e of o)e===`default`?c+=`export default createServerReference("default", ${JSON.stringify(s)}, "default");\n`:c+=`export const ${e} = createServerReference("${e}", ${JSON.stringify(s)}, "${e}");\n`;return c}if(s){let o=S(n);if(o.length===0)return``;let s=v.relative(y.cwd(),r).replace(a,`/`).replace(e,``).replace(i,`_`).replace(t,``).replace(Me,``),c=`import { createServerComponentWrapper } from "virtual:rsc-integration.ts";
|
|
20
|
-
`;for(let e of o)e===`default`?c+=`export default createServerComponentWrapper("${s}", ${JSON.stringify(r)});\n`:c+=`export const ${e} = createServerComponentWrapper("${s}_${e}", ${JSON.stringify(r)});\n`;return c}if(!w(n,`use client`))return n;let c=S(n);if(c.length===0)return``;let l=`import {registerClientReference} from "react-server-dom-rari/server";
|
|
21
|
-
`;for(let e of c){if(e===`default`){let e=`Attempted to call the default export of ${r} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;l+=`export default `,l+=`registerClientReference(function() {`,l+=`throw new Error(${JSON.stringify(e)});`}else{let t=`Attempted to call ${e}() from the server but ${e} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;l+=`export const ${e} = `,l+=`registerClientReference(function() {`,l+=`throw new Error(${JSON.stringify(t)});`}l+=`},`,l+=`${JSON.stringify(r)},`,l+=`${JSON.stringify(e)});\n`}return l}function D(e,t){return!w(e,`use client`)||S(e).length===0?e:e.replace(Te,``)}function O(e,t){let n=e;for(let[t,r]of Object.entries(m))if(e.startsWith(`${t}/`)){n=e.replace(t,r);break}else if(e===t){n=r;break}let r=v.resolve(v.dirname(t),n),i=[`.tsx`,`.jsx`,`.ts`,`.js`];for(let e of i){let t=`${r}${e}`;if(g.existsSync(t))return t}if(g.existsSync(r))for(let e of i){let t=v.join(r,`index${e}`);if(g.existsSync(t))return t}return`${r}.tsx`}function k(e){return(e.split(`/`).pop()||e).replace(r,``)}let A=!1;async function j(){let e=`http://localhost:${y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3)}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return A=t,t}catch{return A=!1,!1}}let M=[{name:`rari`,config(t,{command:n}){if(n===`build`){let n=c.projectRoot||y.cwd(),r=v.join(n,`index.html`);if(g.existsSync(r))try{let n=g.readFileSync(r,`utf-8`),i=[];for(let t of n.matchAll(Ee)){let n=t[1];if(n.startsWith(`/src/`)&&e.test(n)){let e=n.slice(1),t=v.basename(e,v.extname(e));i.push({path:e,name:t})}}if(i.length>0){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{};let e=t.build.rolldownOptions.input||{main:`./index.html`},n;n=typeof e==`string`?{main:e}:Array.isArray(e)?{main:e[0]||`./index.html`}:{...e},i.forEach(({path:e,name:t})=>{n[t]=`./${e}`}),t.build.rolldownOptions.input=n}}catch(e){console.warn(`[rari] Error parsing index.html for build inputs:`,e)}}t.resolve=t.resolve||{};let r=Array.isArray(t.resolve.dedupe)?t.resolve.dedupe:[],i=[`react`,`react-dom`];t.resolve.dedupe=[...new Set([...r||[],...i])];let a=[];Array.isArray(t.resolve.alias)?a=t.resolve.alias:t.resolve.alias&&typeof t.resolve.alias==`object`&&(a=Object.entries(t.resolve.alias).map(([e,t])=>({find:e,replacement:t})));let o=new Set(a.map(e=>String(e.find)));try{let e=b(import.meta.resolve(`react`)),n=b(import.meta.resolve(`react-dom/client`)),r=b(import.meta.resolve(`react/jsx-runtime`)),i=[];o.has(`react/jsx-runtime`)||i.push({find:`react/jsx-runtime`,replacement:r});try{let e=b(import.meta.resolve(`react/jsx-dev-runtime`));o.has(`react/jsx-dev-runtime`)||i.push({find:`react/jsx-dev-runtime`,replacement:e})}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving react/jsx-dev-runtime:`,e)}o.has(`react`)||i.push({find:`react`,replacement:e}),o.has(`react-dom/client`)||i.push({find:`react-dom/client`,replacement:n}),i.length>0&&(t.resolve.alias=[...a,...i])}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error configuring React aliases:`,e)}t.environments=t.environments||{},t.environments.rsc={resolve:{conditions:[`react-server`,`node`,`import`]},...t.environments.rsc},t.environments.ssr={resolve:{conditions:[`node`,`import`]},...t.environments.ssr},t.environments.client={resolve:{conditions:[`browser`,`import`]},...t.environments.client},t.optimizeDeps=t.optimizeDeps||{},t.optimizeDeps.include=t.optimizeDeps.include||[];for(let e of[`react`,`react-dom`,`react-dom/client`,`react-dom/server`,`react/jsx-runtime`,`react/jsx-dev-runtime`])t.optimizeDeps.include.includes(e)||t.optimizeDeps.include.push(e);if(t.optimizeDeps.exclude=t.optimizeDeps.exclude||[],t.optimizeDeps.exclude.includes(`rari`)||t.optimizeDeps.exclude.push(`rari`),n===`build`)for(let e of[`rsc`,`ssr`,`client`]){let n=t.environments[e];n&&n.build&&(n.build.rolldownOptions=n.build.rolldownOptions||{})}t.server=t.server||{},t.server.proxy=t.server.proxy||{};let s=y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3);if(t.server.proxy[`/api`]={target:`http://localhost:${s}`,changeOrigin:!0,secure:!1,ws:!0},t.server.proxy[`/_rari`]={target:`http://localhost:${s}`,changeOrigin:!0,secure:!1,ws:!0},n===`build`){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{},t.build.rolldownOptions.input||(t.build.rolldownOptions.input={main:`./index.html`}),t.build.rolldownOptions.output=t.build.rolldownOptions.output||{};let e=Array.isArray(t.build.rolldownOptions.output)?t.build.rolldownOptions.output:[t.build.rolldownOptions.output];for(let t of e)t.advancedChunks=t.advancedChunks||{},t.advancedChunks.groups=t.advancedChunks.groups||[],t.advancedChunks.groups.push({name(e){return e.includes(`node_modules`)?e.includes(`node_modules/react-dom`)?`react-dom`:e.includes(`node_modules/react`)?`react`:`vendor`:null}}),t.chunkFileNames||=e=>e.moduleIds?.some(e=>_(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds?.some(e=>_(e).hasUseClient)?`client/components/[name]-[hash].js`:`assets/[name]-[hash].js`}return t.environments&&t.environments.client&&(t.environments.client.build||(t.environments.client.build={}),t.environments.client.build.rolldownOptions||(t.environments.client.build.rolldownOptions={}),t.environments.client.build.rolldownOptions.input||(t.environments.client.build.rolldownOptions.input={})),t},configResolved(e){let t=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react-dom/client`]);if(e.resolve?.alias){let n=e.resolve.alias;Array.isArray(n)?n.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!t.has(e.find)&&(m[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(m[e]=n)})}},transform(t,n){if(!e.test(n))return null;let r=this.environment;if(w(t,`use client`)){l.set(n,`client`),u.add(n);let e=t.split(`
|
|
22
|
-
`);for(let t of e){let e=t.match(J);if(!e)continue;let r=e[4];if(!r)continue;let i=O(r,n);g.existsSync(i)&&(l.set(i,`client`),u.add(i))}return D(t,n)}if(l.get(n)===`client`||u.has(n))return D(t,n);if(x(n)){if(l.set(n,`server`),r&&(r.name===`rsc`||r.name===`ssr`))return T(t,n);{let e=E(t,n);return e=`// HMR acceptance for server component
|
|
23
|
-
if (import.meta.hot) {
|
|
24
|
-
import.meta.hot.accept();
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (typeof globalThis !== 'undefined') {
|
|
28
|
-
if (!globalThis['~rari']) globalThis['~rari'] = {};
|
|
29
|
-
globalThis['~rari'].serverComponents = globalThis['~rari'].serverComponents || new Set();
|
|
30
|
-
globalThis['~rari'].serverComponents.add(${JSON.stringify(n)});
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
${e}`,e}}if(w(t,`use server`))return l.set(n,`server`),r&&(r.name===`rsc`||r.name===`ssr`)?T(t,n):E(t,n);let i=l.get(n);if(i===`server`)return r&&(r.name===`rsc`||r.name===`ssr`)?T(t,n):E(t,n);if(i===`client`)return D(t,n);l.set(n,`unknown`);let a=t.split(`
|
|
34
|
-
`),o=t,s=!1,c=!1,d=!1,f=[];for(let e of a){let i=e.match(J);if(!i)continue;let a=i[1],p=i[4],m=k(p),h=O(p,n),_=w(t,`use client`)||l.get(n)===`client`||n.includes(`entry-client`),v=l.get(h)===`client`||g.existsSync(h)&&g.readFileSync(h,`utf-8`).includes(`'use client'`);if(v&&(l.set(h,`client`),u.add(h)),v&&r&&(r.name===`rsc`||r.name===`ssr`)){if(!_){let t=e,n=a||`default`,r=`
|
|
35
|
-
import { registerClientReference } from "react-server-dom-rari/server";
|
|
36
|
-
const ${n} = registerClientReference(
|
|
37
|
-
function() {
|
|
38
|
-
throw new Error("Attempted to call ${n} from the server but it's on the client. It can only be rendered as a Component or passed to props of a Client Component.");
|
|
39
|
-
},
|
|
40
|
-
${JSON.stringify(h)},
|
|
41
|
-
${JSON.stringify(a||`default`)}
|
|
42
|
-
);`;o=o.replace(t,r),s=!0,c=!0}}else if(!_&&x(h)){s=!0,c=!0,d=!0;let t=e;a&&a!==`_`&&f.push(`const ${a} = createServerComponentWrapper('${m}', '${p}');`),o=o.replace(t,``)}}if(s){let e=o.includes(`import React`)||o.match(De)||o.match(Oe),t=o.includes(`createServerComponentWrapper`),r=``;if(c&&!e&&(r+=`import React from 'react';
|
|
43
|
-
`),d&&!t&&(r+=`import { createServerComponentWrapper } from 'virtual:rsc-integration.ts';
|
|
44
|
-
`),f.length>0&&(r+=`${f.join(`
|
|
45
|
-
`)}\n`),r&&(o=r+o),!o.includes(`Suspense`)){let e=o.match(ke);e&&(e[1]&&!e[2].includes(`Suspense`)?o=o.replace(e[0],e[0].replace(Ne,`{ Suspense, $1 }`)):e[1]||(o=o.replace(e[0],`import React, { Suspense } from 'react';`)))}let i=y.env.NODE_ENV!==`production`,a=o.includes(`</`)||o.includes(`/>`)||Y.test(o);return!o.includes(`'use client'`)&&!o.includes(`"use client"`)&&a&&i&&(o=`'use client';\n\n${o}`,l.set(n,`client`)),o}return null},async configureServer(t){let n=c.projectRoot||y.cwd(),i=v.join(n,`src`);await Z(n,c);let a=null,o=async()=>{try{let{ServerComponentBuilder:r,scanDirectory:i}=await import(`./server-build-emJwCUjS.mjs`).then(e=>e.n),o=new r(n,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:m,csp:c.csp,rateLimit:c.rateLimit,spamBlocker:c.spamBlocker});if(a=o,!p&&a){let e=y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3);p=new ae(a,e)}let s=v.join(n,`src`),l=[];if(g.existsSync(s)){let t=n=>{let r=g.readdirSync(n,{withFileTypes:!0});for(let i of r){let r=v.join(n,i.name);if(i.isDirectory())t(r);else if(i.isFile()&&e.test(i.name))try{x(r)&&l.push(r)}catch(e){console.error(`[rari] Error checking ${r}:`,e)}}};t(s),i(s,o)}l.length>0&&t.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:l}});let u=await o.getTransformedComponentsForDevelopment(),d=`http://localhost:${y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3)}`;for(let e of u)try{if(e.id.startsWith(`app/`)||e.code.includes(`"use server"`)||e.code.includes(`'use server'`))continue;let t=await fetch(`${d}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Runtime: Failed to register component ${e.id}:`,t instanceof Error?t.message:String(t))}}catch(e){console.error(`[rari] Runtime: Component discovery failed:`,e instanceof Error?e.message:String(e))}},s=async()=>{try{let e=`http://localhost:${y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3)}`,t=Q(i,Object.values(m));for(let n of t){let t=v.relative(y.cwd(),n),i=v.basename(n).replace(r,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:i,file_path:t,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${i}:`,e)}}}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},u=async()=>{if(f)return;let{getBinaryPath:e,getInstallationInstructions:n}=await import(`./platform.mjs`),r;try{r=e()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(n());return}let i=y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3),a=y.env.NODE_ENV===`production`?`production`:`development`,c=t.config.server.port||5173,l=[`--mode`,a,`--port`,i.toString(),`--host`,`127.0.0.1`];f=te(r,l,{stdio:[`ignore`,`pipe`,`pipe`],cwd:y.cwd(),env:{...y.env,RUST_LOG:y.env.RUST_LOG||`error`,RARI_VITE_PORT:c.toString()}}),f.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),f.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),f.on(`error`,e=>{A=!1,console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),f.on(`exit`,(e,t)=>{f=null,A=!1,t?console.error(`rari server stopped by signal ${t}`):e===0?console.error(`rari server stopped successfully`):e&&console.error(`rari server exited with code ${e}`)});let u=!1;for(let e=0;e<20&&(u=await j(),!u);e++)await new Promise(e=>setTimeout(e,500));u?(await s(),await o()):console.error(`Server failed to become ready for component registration`)},d=async e=>{try{if(!x(e))return;let{ServerComponentBuilder:t}=await import(`./server-build-emJwCUjS.mjs`).then(e=>e.n),r=new t(n,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:m,csp:c.csp,rateLimit:c.rateLimit,spamBlocker:c.spamBlocker});r.addServerComponent(e);let i=await r.getTransformedComponentsForDevelopment();if(i.length===0)return;let a=`http://localhost:${y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3)}`;for(let e of i)try{let t=await fetch(`${a}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}catch(t){console.error(`[rari] Targeted HMR failed for`,`${e}:`,t instanceof Error?t.message:String(t)),setTimeout(o,1e3)}};u().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),t.middlewares.use(async(e,t,n)=>{let r=e.headers.accept;if(r&&r.includes(`text/x-component`)&&e.url&&!e.url.startsWith(`/api`)&&!e.url.startsWith(`/rsc`)&&!e.url.includes(`.`)){if(!A&&!await j()){let e=Date.now();for(;Date.now()-e<1e4&&!await j();)await new Promise(e=>setTimeout(e,100));if(!A){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}}let n=y.env.SERVER_PORT?Number(y.env.SERVER_PORT):Number(y.env.PORT||y.env.RSC_PORT||3e3),r=`http://localhost:${n}${e.url}`;try{let i={};for(let[t,n]of Object.entries(e.headers))typeof n==`string`?i[t]=n:Array.isArray(n)&&(i[t]=n.join(`,`));i.host=`localhost:${n}`,i[`accept-encoding`]=`identity`;let a=await fetch(r,{method:e.method,headers:i});if(t.statusCode=a.status,a.headers.forEach((e,n)=>{n.toLowerCase()!==`content-encoding`&&t.setHeader(n,e)}),a.body){let e=a.body.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)break;t.write(ee.from(r))}t.end()}catch(e){console.error(`[rari] Stream error:`,e),t.headersSent||(t.statusCode=500),t.end()}}else t.end();return}catch(e){console.error(`[rari] Failed to proxy RSC request:`,e),t.headersSent||(t.statusCode=500,t.end(`Internal Server Error`));return}}n()}),t.watcher.on(`change`,async n=>{e.test(n)&&l.delete(n),e.test(n)&&n.includes(i)&&(x(n)?(t.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:n}}),await d(n)):setTimeout(o,1e3))}),t.middlewares.use(`/api/vite/hmr-transform`,async(e,t)=>{if(e.method!==`POST`){t.statusCode=405,t.end(`Method Not Allowed`);return}let n=``;e.on(`data`,e=>{n+=e.toString()}),e.on(`end`,async()=>{try{let{filePath:e}=JSON.parse(n);if(!e){t.statusCode=400,t.end(JSON.stringify({error:`filePath is required`}));return}await d(e),t.statusCode=200,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!0,filePath:e,message:`Component transformation completed`}))}catch(e){t.statusCode=500,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)}))}})}),t.httpServer?.on(`close`,()=>{p&&=(p.dispose(),null),f&&=(f.kill(`SIGTERM`),null),A=!1})},resolveId(e,t){if(e===`virtual:rsc-integration`||e===`virtual:rsc-integration.ts`)return`virtual:rsc-integration.ts`;if(e===`virtual:rari-entry-client`||e===`virtual:rari-entry-client.ts`)return`virtual:rari-entry-client.ts`;if(e===`virtual:react-server-dom-rari-client`||e===`virtual:react-server-dom-rari-client.ts`)return`virtual:react-server-dom-rari-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`./DefaultLoadingIndicator`||e===`./DefaultLoadingIndicator.tsx`)return`virtual:default-loading-indicator.tsx`;if(e===`./LoadingErrorBoundary`||e===`./LoadingErrorBoundary.tsx`)return`virtual:loading-error-boundary.tsx`;if(e===`react-server-dom-rari/server`)return e;if(t&&t.startsWith(`virtual:`)&&e.startsWith(`../`)){let n=import.meta.url,r=b(n),i=v.dirname(r),a=null,o=[v.join(i,`runtime`),v.join(i,`../runtime`)];for(let e of o)if(g.existsSync(e)){a=e;break}if(a){let t=v.join(a,e);if(g.existsSync(t))return t;let n=v.join(a,`../dist`,v.basename(e));if(g.existsSync(n))return n}else console.warn(`[rari] Runtime directory not found, attempting fallback resolution for virtual import.\n Importer: ${t}\n ID: ${e}\n Current Dir: ${i}\n Hint: Runtime lookup failed, trying currentDir as fallback`);let s=v.join(i,e);if(g.existsSync(s))return s;let c=v.join(i,`../dist`,v.basename(e));if(g.existsSync(c))return c}if(y.env.NODE_ENV===`production`)try{let t=v.resolve(e);if(g.existsSync(t)&&x(t))return{id:e,external:!0}}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving server component:`,e,t)}return null},async load(t){if(e.test(t)){let e=this.environment;if(e&&e.name===`client`)try{let e=g.readFileSync(t,`utf-8`);if(w(e,`use server`))return E(e,t)}catch{}}if(t===`virtual:rari-entry-client.ts`){let t=Q(v.join(y.cwd(),`src`),Object.values(m)),r=new Set([...u,...t]),i=[{path:`rari/image`,exports:[`Image`]}],c=[...r].filter(e=>{try{return w(g.readFileSync(e,`utf-8`),`use client`)}catch{return!1}}).map(t=>{let r=v.relative(y.cwd(),t).replace(a,`/`),i=r.replace(e,``),c=r.startsWith(`..`)?t.replace(a,`/`):r,l=!1,u=``;try{let e=g.readFileSync(t,`utf-8`),r=n.test(e),i=e.match(o);!r&&i&&(l=!0,u=i[1])}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,t,e)}let d=c.replace(a,`/`),f=d.startsWith(`/`)||s.test(d)?d:`/${d}`;return` "${c}": {
|
|
46
|
-
id: "${i}",
|
|
47
|
-
path: "${c}",
|
|
48
|
-
type: "client",
|
|
49
|
-
loader: () => ${l?`import(${JSON.stringify(f)}).then(m => m.${u} || m.default || m)`:`import(${JSON.stringify(f)}).then(m => m.default || m)`},
|
|
50
|
-
component: null,
|
|
51
|
-
loading: false,
|
|
52
|
-
registered: false
|
|
53
|
-
}`}).join(`,
|
|
54
|
-
`),l=i.map((e,t)=>`import { ${e.exports.map(e=>`${e} as External${t}_${e}`).join(`, `)} } from '${e.path}';`).join(`
|
|
55
|
-
`),d=i.flatMap((e,t)=>e.exports.map(n=>{let r=`External${t}_${n}`;return`
|
|
56
|
-
globalThis['~clientComponents'] = globalThis['~clientComponents'] || {};
|
|
57
|
-
globalThis['~clientComponents']["${`${e.path}#${n}`}"] = {
|
|
58
|
-
id: "${n}",
|
|
59
|
-
path: "${e.path}",
|
|
60
|
-
type: "client",
|
|
61
|
-
component: ${r},
|
|
62
|
-
registered: true
|
|
63
|
-
};
|
|
64
|
-
globalThis['~clientComponents']["${e.path}"] = globalThis['~clientComponents']["${e.path}"] || {};
|
|
65
|
-
globalThis['~clientComponents']["${e.path}"].component = ${r};
|
|
66
|
-
globalThis['~clientComponentPaths'] = globalThis['~clientComponentPaths'] || {};
|
|
67
|
-
globalThis['~clientComponentPaths']["${e.path}"] = "${n}";`})).join(`
|
|
68
|
-
`);return await Ie(l,[`
|
|
69
|
-
const lazyComponentRegistry = {
|
|
70
|
-
${c}
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
for (const [path, config] of Object.entries(lazyComponentRegistry)) {
|
|
74
|
-
globalThis['~clientComponents'][path] = config;
|
|
75
|
-
globalThis['~clientComponents'][config.id] = config;
|
|
76
|
-
globalThis['~clientComponentPaths'][path] = config.id;
|
|
77
|
-
}
|
|
78
|
-
`,d].filter(Boolean).join(`
|
|
79
|
-
`))}if(t===`react-server-dom-rari/server`)return await Le();if(t===`virtual:app-router-provider.tsx`){let e=[v.join(y.cwd(),`packages/rari/dist/runtime/AppRouterProvider.mjs`),v.join(y.cwd(),`node_modules/rari/dist/runtime/AppRouterProvider.mjs`)];for(let t of e)if(g.existsSync(t))return g.readFileSync(t,`utf-8`);return`export function AppRouterProvider({ children }) { return children; }`}if(t===`virtual:default-loading-indicator.tsx`){let e=[v.join(y.cwd(),`packages/rari/dist/runtime/DefaultLoadingIndicator.mjs`),v.join(y.cwd(),`node_modules/rari/dist/runtime/DefaultLoadingIndicator.mjs`)];for(let t of e)if(g.existsSync(t))return g.readFileSync(t,`utf-8`);return`export function DefaultLoadingIndicator() { return null; }`}if(t===`virtual:loading-error-boundary.tsx`){let e=[v.join(y.cwd(),`packages/rari/dist/runtime/LoadingErrorBoundary.mjs`),v.join(y.cwd(),`node_modules/rari/dist/runtime/LoadingErrorBoundary.mjs`)];for(let t of e)if(g.existsSync(t))return g.readFileSync(t,`utf-8`);return`export class LoadingErrorBoundary extends React.Component { render() { return this.props.children; } }`}if(t===`virtual:rsc-integration.ts`)return(await Fe()).replace(je,(e,t,n)=>`from${t}${n}virtual:react-server-dom-rari-client.ts${n}`);if(t===`virtual:react-server-dom-rari-client.ts`)return await X(`react-server-dom-rari-client.mjs`);if(t.endsWith(`.mjs`)&&g.existsSync(t))try{let e=c.projectRoot||y.cwd(),n=g.realpathSync(t),r=v.relative(e,n),i=!r.startsWith(`..`)&&!v.isAbsolute(r),a=n.includes(`${v.sep}node_modules${v.sep}`),o=n.includes(`${v.sep}packages${v.sep}rari${v.sep}`)||n.includes(`${v.sep}node_modules${v.sep}rari${v.sep}`);return i||a||o?g.readFileSync(t,`utf-8`):(console.warn(`[rari] Refusing to load .mjs file outside project root and node_modules: ${t}`),null)}catch(e){return console.warn(`[rari] Error validating .mjs file path: ${t}`,e),null}},async handleHotUpdate({file:t,server:n}){if(!e.test(t))return;if(t.includes(`/dist/`)||t.includes(`\\dist\\`))return[];let r=p?.detectComponentType(t)||`unknown`,i=t.includes(`/app/`)||t.includes(`\\app\\`),a=t.endsWith(`page.tsx`)||t.endsWith(`page.jsx`),o=t.endsWith(`layout.tsx`)||t.endsWith(`layout.jsx`),s=t.endsWith(`loading.tsx`)||t.endsWith(`loading.jsx`),c=t.endsWith(`error.tsx`)||t.endsWith(`error.jsx`),l=t.endsWith(`not-found.tsx`)||t.endsWith(`not-found.jsx`);if(i&&(a||o||s||c||l)){let e=`page`;o?e=`layout`:s?e=`loading`:c?e=`error`:l&&(e=`not-found`),n.hot.send(`rari:app-router-updated`,{type:`rari-hmr`,filePath:t,fileType:e});return}if(r!==`client`&&r===`server`)return p&&await p.handleServerComponentUpdate(t,n),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(Ae)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}return t.length>0?{html:e,tags:t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`}))}:e}},async writeBundle(){await Z(c.projectRoot||y.cwd(),c)}},h({...c.serverBuild,csp:c.csp,rateLimit:c.rateLimit,spamBlocker:c.spamBlocker})];return c.proxy!==!1&&M.push(C(c.proxy||{})),c.router!==!1&&M.push(N(c.router||{})),M}function ze(e){return{plugins:[$(),...e.plugins||[]],...e}}export{C as a,N as i,Re as n,S as o,$ as r,ze as t};
|