rari 0.14.8 → 0.14.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import e from"node:path";const t=new WeakMap;function n(e){let n=t.get(e);return n||(n=Object.entries(e).sort((e,t)=>t[0].length-e[0].length),t.set(e,n),n)}function r(t,r,i){if(typeof t!=`string`)throw TypeError(`Expected source to be a string, but received ${typeof t}`);if(r==null)throw TypeError(`Expected aliases to be an object, but received ${r}`);if(typeof r!=`object`||Array.isArray(r))throw TypeError(`Expected aliases to be a plain object, but received ${Array.isArray(r)?`array`:typeof r}`);if(Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null)throw TypeError(`Expected aliases to be a plain object, but received ${r.constructor?.name||`object with custom prototype`}`);if(typeof i!=`string`)throw TypeError(`Expected projectRoot to be a string, but received ${typeof i}`);let a=n(r);for(let[n,r]of a)if(t.startsWith(`${n}/`)||t===n){let a=t.slice(n.length),o=e.join(r,a);return e.isAbsolute(o)?o:e.resolve(i,o)}return null}export{r as t};
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import{getBinaryPath as e,getInstallationInstructions as t}from"./platform.mjs";import{spawn as n}from"node:child_process";import{existsSync as r,readFileSync as i,realpathSync as a}from"node:fs";import{resolve as o}from"node:path";import s from"node:process";import{fileURLToPath as c}from"node:url";import{styleText as l}from"node:util";function u(e){console.warn(`${l(`blue`,`info`)} ${e}`)}function d(e){console.warn(`${l(`green`,`✓`)} ${e}`)}function f(e){console.error(`${l(`red`,`✗`)} ${e}`)}function p(e){console.warn(`${l(`yellow`,`⚠`)} ${e}`)}const m=/^([^=]+)=(.*)$/;function h(e){let t=e.trim();if(!t||t.startsWith(`#`))return null;let n=t.match(m);if(!n)return null;let[,r,i]=n,a=r.trim(),o=i.trim();return(o.startsWith(`"`)&&o.endsWith(`"`)||o.startsWith(`'`)&&o.endsWith(`'`))&&(o=o.slice(1,-1)),{key:a,value:o}}function g(){let e=o(s.cwd(),`.env`);if(!r(e))return;let t=i(e,`utf-8`);for(let e of t.split(`
3
- `)){let t=h(e);t&&!s.env[t.key]&&(s.env[t.key]=t.value)}}g();const[,,_,...v]=s.argv;function y(e){let t=s.cwd();for(;;){let n=e(t);if(n!==null)return n;let r=o(t,`..`);if(r===t)break;t=r}return null}function b(e){return r(o(e,`pnpm-lock.yaml`))?`pnpm`:r(o(e,`yarn.lock`))?`yarn`:r(o(e,`bun.lockb`))?`bun`:r(o(e,`package-lock.json`))?`npm`:null}function x(e){try{let t=o(e,`package.json`);if(!r(t))return null;let n=JSON.parse(i(t,`utf-8`));if(n.packageManager?.startsWith(`pnpm`))return`pnpm`;if(n.packageManager?.startsWith(`yarn`))return`yarn`;if(n.packageManager?.startsWith(`bun`))return`bun`;if(n.packageManager?.startsWith(`npm`))return`npm`}catch{}return null}function S(){return y(e=>b(e)??x(e))??`npm`}function C(){let e=S(),t=s.platform===`win32`;switch(e){case`bun`:return t?`bun.cmd`:`bun`;case`pnpm`:return t?`pnpm.cmd`:`pnpm`;case`yarn`:return t?`yarn.cmd`:`yarn`;default:return t?`npx.cmd`:`npx`}}function w(){return y(e=>{try{let t=o(e,`package.json`);if(r(t)){let e=JSON.parse(i(t,`utf-8`)),n={...e.dependencies,...e.devDependencies};if(n[`vite-plus`])return`vp`;if(n.vite)return`vite`}}catch{}return null})??`vite`}function T(e,t,r={}){let i=s.platform===`win32`;if(e===`npx`){let e=C();if(e.includes(`bun`))return n(i?`bunx.cmd`:`bunx`,t,{...r,shell:i});if(e.includes(`pnpm`))return n(e,[`exec`,...t],{...r,shell:i});if(e.includes(`yarn`)){let[a,...o]=t;return n(e,a===`vp`?[`dlx`,`-p`,`vite-plus`,`vp`,...o]:[`dlx`,...t],{...r,shell:i})}}return i&&e===`npx`?n(`npx.cmd`,t,{...r,shell:!0}):n(e,t,r)}function E(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function D(){return!!(s.env.RAILWAY_ENVIRONMENT||s.env.RAILWAY_PROJECT_ID||s.env.RAILWAY_SERVICE_ID)}function O(){return!!(s.env.RENDER||s.env.RENDER_SERVICE_ID||s.env.RENDER_SERVICE_NAME)}function k(){return D()||O()}function A(){return D()?`Railway`:O()?`Render`:`local`}function j(){return{port:s.env.PORT||s.env.RSC_PORT||`3000`,mode:s.env.NODE_ENV||`production`,host:k()?`0.0.0.0`:`127.0.0.1`}}async function M(){let{existsSync:e,rmSync:t}=await import(`node:fs`),{resolve:n}=await import(`node:path`),r=n(s.cwd(),`dist`);e(r)&&(u(`Cleaning dist folder...`),t(r,{recursive:!0,force:!0})),u(`Type checking...`);let i=T(`npx`,[`tsgo`],{stdio:`inherit`,cwd:s.cwd()});await new Promise((e,t)=>{i.on(`exit`,n=>{n===0?(d(`Type check passed`),e()):(f(`Type check failed with code ${n}`),t(Error(`Type check failed with code ${n}`)))}),i.on(`error`,t)}),u(`Building for production...`);let a=T(`npx`,[w(),`build`],{stdio:`inherit`,cwd:s.cwd()});await new Promise((e,t)=>{a.on(`exit`,n=>{n===0?(d(`Build complete`),e()):(f(`Build failed with code ${n}`),t(Error(`Build failed with code ${n}`)))}),a.on(`error`,t)}),await N()}async function N(){if(r(o(s.cwd(),`dist`,`server`,`image.json`))&&r(o(s.cwd(),`public`)))try{let t=n(e(),[`optimize-images`],{stdio:`inherit`,cwd:s.cwd(),shell:!1});await new Promise(e=>{t.on(`exit`,t=>{t===0||p(`Image pre-optimization exited with code ${t}`),e()}),t.on(`error`,t=>{p(`Image pre-optimization error: ${E(t)}`),e()})})}catch(e){p(`Could not pre-optimize images: ${E(e)}`)}}async function P(){let{existsSync:e}=await import(`node:fs`),{resolve:t}=await import(`node:path`),n=w();if(!e(t(s.cwd(),`dist`))){u(`First run detected - building project...`);let e=T(`npx`,[n,`build`,`--mode`,`development`],{stdio:`inherit`,cwd:s.cwd()});await new Promise((t,n)=>{e.on(`exit`,e=>{e===0?(d(`Initial build complete`),t()):(f(`Build failed with code ${e}`),n(Error(`Build failed with code ${e}`)))}),e.on(`error`,n)})}u(`Starting Vite${n===`vp`?`+`:``} dev server...`);let r=T(`npx`,[n,`dev`],{stdio:`inherit`,cwd:s.cwd()}),i=()=>{u(`Shutting down dev server...`),r.kill(`SIGTERM`)};return s.on(`SIGINT`,i),s.on(`SIGTERM`,i),r.on(`error`,e=>{f(`Failed to start Vite: ${e.message}`),s.exit(1)}),r.on(`exit`,e=>{e!==0&&e!==null&&(f(`Vite exited with code ${e}`),s.exit(e))}),new Promise(()=>{})}async function F(){let r;try{r=e()}catch{f(`Failed to obtain rari binary`),f(t()),s.exit(1)}let{port:i,mode:a,host:o}=j();if(k()){let e=A();u(`${e} environment detected`),u(`Starting rari server for ${e} deployment...`),u(`Mode: ${a}, Host: ${o}, Port: ${i}`),u(`using binary: ${r}`)}let c=n(r,[`--mode`,a,`--port`,i,`--host`,o],{stdio:`inherit`,cwd:s.cwd(),env:{...s.env,RUST_LOG:s.env.RUST_LOG||`error`}}),l=()=>{u(`shutting down...`),c.kill(`SIGTERM`)};return s.on(`SIGINT`,l),s.on(`SIGTERM`,l),c.on(`error`,e=>{f(`Failed to start rari server: ${e.message}`),e.message.includes(`ENOENT`)&&f(`Binary not found. Please ensure rari is properly installed.`),s.exit(1)}),c.on(`exit`,(e,t)=>{t?u(`server stopped by signal ${t}`):e===0?d(`server stopped successfully`):(f(`server exited with code ${e}`),s.exit(e||1))}),new Promise(()=>{})}async function I(){u(`Setting up Railway deployment...`),k()&&(f(`Already running in ${A()} environment. Use "rari start" instead.`),s.exit(1));let{createRailwayDeployment:e}=await import(`./railway-s8_vD6IQ.mjs`);await e()}async function L(){u(`Setting up Render deployment...`),k()&&(f(`Already running in ${A()} environment. Use "rari start" instead.`),s.exit(1));let{createRenderDeployment:e}=await import(`./render--U1cY-wT.mjs`);await e()}async function R(){switch(_){case void 0:case`help`:case`--help`:case`-h`:console.warn(`${l(`bold`,`rari CLI`)}
3
+ `)){let t=h(e);t&&!s.env[t.key]&&(s.env[t.key]=t.value)}}g();const[,,_,...v]=s.argv;function y(e){let t=s.cwd();for(;;){let n=e(t);if(n!==null)return n;let r=o(t,`..`);if(r===t)break;t=r}return null}function b(e){return r(o(e,`pnpm-lock.yaml`))?`pnpm`:r(o(e,`yarn.lock`))?`yarn`:r(o(e,`bun.lockb`))?`bun`:r(o(e,`package-lock.json`))?`npm`:null}function x(e){try{let t=o(e,`package.json`);if(!r(t))return null;let n=JSON.parse(i(t,`utf-8`));if(n.packageManager?.startsWith(`pnpm`))return`pnpm`;if(n.packageManager?.startsWith(`yarn`))return`yarn`;if(n.packageManager?.startsWith(`bun`))return`bun`;if(n.packageManager?.startsWith(`npm`))return`npm`}catch{}return null}function S(){return y(e=>b(e)??x(e))??`npm`}function C(){let e=S(),t=s.platform===`win32`;switch(e){case`bun`:return t?`bun.cmd`:`bun`;case`pnpm`:return t?`pnpm.cmd`:`pnpm`;case`yarn`:return t?`yarn.cmd`:`yarn`;default:return t?`npx.cmd`:`npx`}}function w(){return y(e=>{try{let t=o(e,`package.json`);if(r(t)){let e=JSON.parse(i(t,`utf-8`)),n={...e.dependencies,...e.devDependencies};if(n[`vite-plus`])return`vp`;if(n.vite)return`vite`}}catch{}return null})??`vite`}function T(e,t,r={}){let i=s.platform===`win32`;if(e===`npx`){let e=C();if(e.includes(`bun`))return n(i?`bunx.cmd`:`bunx`,t,{...r,shell:i});if(e.includes(`pnpm`))return n(e,[`exec`,...t],{...r,shell:i});if(e.includes(`yarn`)){let[a,...o]=t;return n(e,a===`vp`?[`dlx`,`-p`,`vite-plus`,`vp`,...o]:[`dlx`,...t],{...r,shell:i})}}return i&&e===`npx`?n(`npx.cmd`,t,{...r,shell:!0}):n(e,t,r)}function E(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function D(){return!!(s.env.RAILWAY_ENVIRONMENT||s.env.RAILWAY_PROJECT_ID||s.env.RAILWAY_SERVICE_ID)}function O(){return!!(s.env.RENDER||s.env.RENDER_SERVICE_ID||s.env.RENDER_SERVICE_NAME)}function k(){return D()||O()}function A(){return D()?`Railway`:O()?`Render`:`local`}function j(){return{port:s.env.PORT||s.env.RSC_PORT||`3000`,mode:s.env.NODE_ENV||`production`,host:k()?`0.0.0.0`:`127.0.0.1`}}async function M(){let{existsSync:e,rmSync:t}=await import(`node:fs`),{resolve:n}=await import(`node:path`),r=n(s.cwd(),`dist`);e(r)&&(u(`Cleaning dist folder...`),t(r,{recursive:!0,force:!0})),u(`Type checking...`);let i=T(`npx`,[`tsgo`],{stdio:`inherit`,cwd:s.cwd()});await new Promise((e,t)=>{i.on(`exit`,n=>{n===0?(d(`Type check passed`),e()):(f(`Type check failed with code ${n}`),t(Error(`Type check failed with code ${n}`)))}),i.on(`error`,t)}),u(`Building for production...`);let a=T(`npx`,[w(),`build`],{stdio:`inherit`,cwd:s.cwd()});await new Promise((e,t)=>{a.on(`exit`,n=>{n===0?(d(`Build complete`),e()):(f(`Build failed with code ${n}`),t(Error(`Build failed with code ${n}`)))}),a.on(`error`,t)}),await N()}async function N(){if(r(o(s.cwd(),`dist`,`server`,`image.json`))&&r(o(s.cwd(),`public`)))try{let t=n(e(),[`optimize-images`],{stdio:`inherit`,cwd:s.cwd(),shell:!1});await new Promise(e=>{t.on(`exit`,t=>{t===0||p(`Image pre-optimization exited with code ${t}`),e()}),t.on(`error`,t=>{p(`Image pre-optimization error: ${E(t)}`),e()})})}catch(e){p(`Could not pre-optimize images: ${E(e)}`)}}async function P(){let{existsSync:e}=await import(`node:fs`),{resolve:t}=await import(`node:path`),n=w();if(!e(t(s.cwd(),`dist`))){u(`First run detected - building project...`);let e=T(`npx`,[n,`build`,`--mode`,`development`],{stdio:`inherit`,cwd:s.cwd()});await new Promise((t,n)=>{e.on(`exit`,e=>{e===0?(d(`Initial build complete`),t()):(f(`Build failed with code ${e}`),n(Error(`Build failed with code ${e}`)))}),e.on(`error`,n)})}u(`Starting Vite${n===`vp`?`+`:``} dev server...`);let r=T(`npx`,[n,`dev`],{stdio:`inherit`,cwd:s.cwd()}),i=()=>{u(`Shutting down dev server...`),r.kill(`SIGTERM`)};return s.on(`SIGINT`,i),s.on(`SIGTERM`,i),r.on(`error`,e=>{f(`Failed to start Vite: ${e.message}`),s.exit(1)}),r.on(`exit`,e=>{e!==0&&e!==null&&(f(`Vite exited with code ${e}`),s.exit(e))}),new Promise(()=>{})}async function F(){let r;try{r=e()}catch{f(`Failed to obtain rari binary`),f(t()),s.exit(1)}let{port:i,mode:a,host:o}=j();if(k()){let e=A();u(`${e} environment detected`),u(`Starting rari server for ${e} deployment...`),u(`Mode: ${a}, Host: ${o}, Port: ${i}`),u(`using binary: ${r}`)}let c=n(r,[`--mode`,a,`--port`,i,`--host`,o],{stdio:`inherit`,cwd:s.cwd(),env:{...s.env,RUST_LOG:s.env.RUST_LOG||`error`}}),l=()=>{u(`shutting down...`),c.kill(`SIGTERM`)};return s.on(`SIGINT`,l),s.on(`SIGTERM`,l),c.on(`error`,e=>{f(`Failed to start rari server: ${e.message}`),e.message.includes(`ENOENT`)&&f(`Binary not found. Please ensure rari is properly installed.`),s.exit(1)}),c.on(`exit`,(e,t)=>{t?u(`server stopped by signal ${t}`):e===0?d(`server stopped successfully`):(f(`server exited with code ${e}`),s.exit(e||1))}),new Promise(()=>{})}async function I(){u(`Setting up Railway deployment...`),k()&&(f(`Already running in ${A()} environment. Use "rari start" instead.`),s.exit(1));let{createRailwayDeployment:e}=await import(`./railway--nFNI3h8.mjs`);await e()}async function L(){u(`Setting up Render deployment...`),k()&&(f(`Already running in ${A()} environment. Use "rari start" instead.`),s.exit(1));let{createRenderDeployment:e}=await import(`./render-EieI0V5b.mjs`);await e()}async function R(){switch(_){case void 0:case`help`:case`--help`:case`-h`:console.warn(`${l(`bold`,`rari CLI`)}
4
4
 
5
5
  ${l(`bold`,`Usage:`)}
6
6
  ${l(`cyan`,`rari dev`)} Start the development server with Vite
package/dist/client.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as ServerSidePropsResult, c as clearPropsCacheForComponent, d as extractServerPropsWithCache, f as extractStaticParams, i as MetadataResult, l as extractMetadata, o as StaticParamsResult, p as hasServerSideDataFetching, r as ServerConfig, s as clearPropsCache, t as ServerCSPConfig, u as extractServerProps } from "./server-config-D_oeQzpc.mjs";
2
- import { a as ErrorProps, c as LayoutEntry, f as NotFoundEntry, g as TemplateEntry, h as RouteSegmentType, i as ErrorEntry, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-K8DF80Bq.mjs";
1
+ import { a as ServerSidePropsResult, c as clearPropsCacheForComponent, d as extractServerPropsWithCache, f as extractStaticParams, i as MetadataResult, l as extractMetadata, o as StaticParamsResult, p as hasServerSideDataFetching, r as ServerConfig, s as clearPropsCache, t as ServerCSPConfig, u as extractServerProps } from "./server-config-D7_4Hk9w.mjs";
2
+ import { a as ErrorProps, c as LayoutEntry, f as NotFoundEntry, g as TemplateEntry, h as RouteSegmentType, i as ErrorEntry, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-BwhW3M72.mjs";
3
3
  import * as React from "react";
4
4
 
5
5
  //#region src/router/ClientRouter.d.ts
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- import{i as e,t}from"./navigate-DuyUa6qD.mjs";import{a as n,i as r,n as i,o as a,r as o,s,t as c}from"./props-extractor-C8FRV5vW.mjs";import{useEffect as l,useLayoutEffect as u,useRef as d,useState as f}from"react";function p(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;return o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e))return h(e);let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0:h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}const m=/fetch|networkerror|load failed/i;function h(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function g(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function _(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function v(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function y(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function b(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function x(e,t){if(e instanceof Error&&e.name===`AbortError`)return h(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return g(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?_(e,n,t):b(e,t)}return e instanceof TypeError&&m.test(e.message)?v(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?y(e,t):b(e,t)}var S=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=x(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};function C(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 w(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function T(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}const E=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}async fetchRouteInfo(e){let t=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})});if(!t.ok){let e=null;try{e=await t.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${t.status} ${t.statusText}`)}let n=t.clone();try{return await t.json()}catch(t){try{let e=await n.text();return JSON.parse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=E}var D=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 O(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function k(e){let t=document.querySelector(e);t&&t.remove()}function A(e){e.title&&(document.title=e.title),e.description?O(`meta[name="description"]`,{name:`description`,content:e.description}):k(`meta[name="description"]`),e.keywords&&e.keywords.length>0?O(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):k(`meta[name="keywords"]`),e.viewport&&O(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function j(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function M(e){if(e===void 0){k(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?O(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):k(`meta[name="robots"]`)}function N(e){if(e===void 0){k(`meta[property="og:title"]`),k(`meta[property="og:description"]`),k(`meta[property="og:url"]`),k(`meta[property="og:site_name"]`),k(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?O(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):k(`meta[property="og:title"]`),e.description?O(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):k(`meta[property="og:description"]`),e.url?O(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):k(`meta[property="og:url"]`),e.siteName?O(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):k(`meta[property="og:site_name"]`),e.type?O(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):k(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove())}function P(e){if(e===void 0){k(`meta[name="twitter:card"]`),k(`meta[name="twitter:site"]`),k(`meta[name="twitter:creator"]`),k(`meta[name="twitter:title"]`),k(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?O(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):k(`meta[name="twitter:card"]`),e.site?O(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):k(`meta[name="twitter:site"]`),e.creator?O(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):k(`meta[name="twitter:creator"]`),e.title?O(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):k(`meta[name="twitter:title"]`),e.description?O(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):k(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove())}function F(e){A(e),j(e.canonical),M(e.robots),N(e.openGraph),P(e.twitter)}function I({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=f(()=>({currentRoute:C(r),navigationId:0,error:null})),s=d(null),c=d(!0),m=d(C(r)),h=d(0),g=d(new S({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),_=d(new Map),v=d([]),y=d(new D({maxHistorySize:50})),b=d(null),x=d(i),O=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,k=()=>{s.current&&=(s.current.abort(),null)},A=()=>{for(let[,e]of _.current.entries())e.abortController.abort();_.current.clear()},j=(e,t)=>{_.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},M=d(null),N=(e,t)=>{if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))},P=e=>{try{let t=e.headers.get(`x-rari-metadata`);t&&F(JSON.parse(decodeURIComponent(t)))}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},I=(e,t,n,r,i,a)=>{h.current===r&&window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,abortSignal:a.signal,rscResponsePromise:e}}))},L=(e,t,n)=>{n.historyKey?requestAnimationFrame(()=>{y.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=(n=0)=>{let r=document.getElementById(t);r?r.scrollIntoView({behavior:`smooth`,block:`start`}):n<10&&setTimeout(e,50,n+1)};e()})},R=(e,t,n,r)=>{c.current&&(m.current=e,o(t=>({...t,currentRoute:e,navigationId:r,error:null})),g.current.resetRetry(e),L(e,t,n))},z=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){j(t,n);return}let i=g.current.handleError(e,t);c.current&&(o(e=>({...e,error:i})),window.history.replaceState(window.history.state,``,r)),_.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),M.current?.()},B=async(e,t={})=>{if(!e||typeof e!=`string`)return;let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=C(n);if(i===m.current&&!t.replace){N(i,r);return}let a=_.current.get(i);if(a)return a.promise;A(),k();let o=new AbortController;s.current=o,h.current+=1;let c=h.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:c,targetPath:i}}));let l=(async()=>{let e=m.current;try{t.historyKey||y.current.captureState(e);let n=t.historyKey||O(),a=window.location.origin+i,s=r?`${i}#${r}`:i,l={route:i,navigationId:c,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(l,``,s):window.history.pushState(l,``,s);let u=await fetch(a,{headers:{Accept:`text/x-component`},signal:o.signal}).then(e=>{if(!e.ok&&e.status!==404)throw Error(`Failed to fetch: ${e.status}`);return e});if(o.signal.aborted){j(i,c);return}let d=new URL(u.url).pathname;if(o.signal.aborted){j(i,c);return}if(d!==i){let e=r?`${d}#${r}`:d;window.history.replaceState({...l,route:d},``,e)}if(I(Promise.resolve(u),e,d,c,t,o),P(u),o.signal.aborted){j(i,c);return}R(d,r,t,c),_.current.delete(i),M.current?.()}catch(t){z(t,i,c,e)}})();return _.current.set(i,{targetPath:i,navigationId:c,promise:l,abortController:o}),l},V=async()=>{if(v.current.length===0)return;let e=v.current.at(-1);e&&(v.current=[],await B(e.path,e.options))},H=d(B);u(()=>(M.current=V,H.current=B,()=>{M.current=null,H.current=null}));let U=d(null);U.current||=p((e,t)=>{H.current?.(e,t)},50,{leading:!0,trailing:!0,maxWait:200});let W=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||w(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=T(r);U.current&&U.current(i,{replace:!1})},G=e=>{let t=window.location.pathname,n=e.state;H.current&&H.current(t,{replace:!0,scroll:!1,historyKey:n?.key})};l(()=>{let e=window.history.state;if(!e||!e.key){let e={route:C(r),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:O()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[r]);let K=e=>{if(e.persisted){let e=window.location.pathname;y.current.captureState(e)}},q=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{y.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return l(()=>(document.addEventListener(`click`,W),window.addEventListener(`popstate`,G),window.addEventListener(`pagehide`,K),window.addEventListener(`pageshow`,q),()=>{document.removeEventListener(`click`,W),window.removeEventListener(`popstate`,G),window.removeEventListener(`pagehide`,K),window.removeEventListener(`pageshow`,q)}),[]),l(()=>{x.current=i;let e=()=>{document.hidden?b.current=Date.now():b.current!==null&&Date.now()-b.current>x.current&&E.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[i]),l(()=>(c.current=!0,e((e,t)=>H.current?.(e,t)??Promise.resolve()),()=>{c.current=!1,t(),k(),A(),U.current?.cancel&&U.current.cancel()}),[]),n}export{I as ClientRouter,S as NavigationErrorHandler,D as StatePreserver,c as clearPropsCache,i as clearPropsCacheForComponent,o as extractMetadata,r as extractServerProps,n as extractServerPropsWithCache,a as extractStaticParams,s as hasServerSideDataFetching};
1
+ import{i as e,t}from"./navigate-DuyUa6qD.mjs";import{a as n,i as r,n as i,o as a,r as o,s,t as c}from"./props-extractor-C8FRV5vW.mjs";import{useEffect as l,useLayoutEffect as u,useRef as d,useState as f}from"react";function p(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;return o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e))return h(e);let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0:h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}function m(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 h(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function g(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}const _=/fetch|networkerror|load failed/i;function v(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function y(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function b(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function x(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function S(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function C(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function w(e,t){if(e instanceof Error&&e.name===`AbortError`)return v(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return y(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?b(e,n,t):C(e,t)}return e instanceof TypeError&&_.test(e.message)?x(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?S(e,t):C(e,t)}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}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};const E=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}async fetchRouteInfo(e){let t=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})});if(!t.ok){let e=null;try{e=await t.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${t.status} ${t.statusText}`)}let n=t.clone();try{return await t.json()}catch(t){try{let e=await n.text();return JSON.parse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=E}var D=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 O(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function k(e){let t=document.querySelector(e);t&&t.remove()}function A(e){e.title&&(document.title=e.title),e.description?O(`meta[name="description"]`,{name:`description`,content:e.description}):k(`meta[name="description"]`),e.keywords&&e.keywords.length>0?O(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):k(`meta[name="keywords"]`),e.viewport&&O(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function j(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function M(e){if(e===void 0){k(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?O(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):k(`meta[name="robots"]`)}function N(e){if(e===void 0){k(`meta[property="og:title"]`),k(`meta[property="og:description"]`),k(`meta[property="og:url"]`),k(`meta[property="og:site_name"]`),k(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?O(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):k(`meta[property="og:title"]`),e.description?O(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):k(`meta[property="og:description"]`),e.url?O(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):k(`meta[property="og:url"]`),e.siteName?O(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):k(`meta[property="og:site_name"]`),e.type?O(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):k(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove())}function P(e){if(e===void 0){k(`meta[name="twitter:card"]`),k(`meta[name="twitter:site"]`),k(`meta[name="twitter:creator"]`),k(`meta[name="twitter:title"]`),k(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?O(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):k(`meta[name="twitter:card"]`),e.site?O(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):k(`meta[name="twitter:site"]`),e.creator?O(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):k(`meta[name="twitter:creator"]`),e.title?O(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):k(`meta[name="twitter:title"]`),e.description?O(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):k(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove())}function F(e){A(e),j(e.canonical),M(e.robots),N(e.openGraph),P(e.twitter)}function I({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=f(()=>({currentRoute:m(r),navigationId:0,error:null})),s=d(null),c=d(!0),_=d(m(r)),v=d(0),y=d(new T({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),b=d(new Map),x=d([]),S=d(new D({maxHistorySize:50})),C=d(null),w=d(i),O=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,k=()=>{s.current&&=(s.current.abort(),null)},A=()=>{for(let[,e]of b.current.entries())e.abortController.abort();b.current.clear()},j=(e,t)=>{b.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},M=d(null),N=(e,t)=>{if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))},P=e=>{try{let t=e.headers.get(`x-rari-metadata`);t&&F(JSON.parse(decodeURIComponent(t)))}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},I=(e,t,n,r,i,a)=>{v.current===r&&window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,abortSignal:a.signal,rscResponsePromise:e}}))},L=(e,t,n)=>{n.historyKey?requestAnimationFrame(()=>{S.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=(n=0)=>{let r=document.getElementById(t);r?r.scrollIntoView({behavior:`smooth`,block:`start`}):n<10&&setTimeout(e,50,n+1)};e()})},R=(e,t,n,r)=>{c.current&&(_.current=e,o(t=>({...t,currentRoute:e,navigationId:r,error:null})),y.current.resetRetry(e),L(e,t,n))},z=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){j(t,n);return}let i=y.current.handleError(e,t);c.current&&(o(e=>({...e,error:i})),window.history.replaceState(window.history.state,``,r)),b.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),M.current?.()},B=async(e,t={})=>{if(!e||typeof e!=`string`)return;let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=m(n);if(i===_.current&&!t.replace){N(i,r);return}let a=b.current.get(i);if(a)return a.promise;A(),k();let o=new AbortController;s.current=o,v.current+=1;let c=v.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:c,targetPath:i}}));let l=(async()=>{let e=_.current;try{t.historyKey||S.current.captureState(e);let n=t.historyKey||O(),a=window.location.origin+i,s=r?`${i}#${r}`:i,l={route:i,navigationId:c,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(l,``,s):window.history.pushState(l,``,s);let u=await fetch(a,{headers:{Accept:`text/x-component`},signal:o.signal}).then(e=>{if(!e.ok&&e.status!==404)throw Error(`Failed to fetch: ${e.status}`);return e});if(o.signal.aborted){j(i,c);return}let d=new URL(u.url).pathname;if(o.signal.aborted){j(i,c);return}if(d!==i){let e=r?`${d}#${r}`:d;window.history.replaceState({...l,route:d},``,e)}if(I(Promise.resolve(u),e,d,c,t,o),P(u),o.signal.aborted){j(i,c);return}R(d,r,t,c),b.current.delete(i),M.current?.()}catch(t){z(t,i,c,e)}})();return b.current.set(i,{targetPath:i,navigationId:c,promise:l,abortController:o}),l},V=async()=>{if(x.current.length===0)return;let e=x.current.at(-1);e&&(x.current=[],await B(e.path,e.options))},H=d(B);u(()=>(M.current=V,H.current=B,()=>{M.current=null,H.current=null}));let U=d(null);U.current||=p((e,t)=>{H.current?.(e,t)},50,{leading:!0,trailing:!0,maxWait:200});let W=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||h(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=g(r);U.current&&U.current(i,{replace:!1})},G=e=>{let t=window.location.pathname,n=e.state;H.current&&H.current(t,{replace:!0,scroll:!1,historyKey:n?.key})};l(()=>{let e=window.history.state;if(!e||!e.key){let e={route:m(r),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:O()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[r]);let K=e=>{if(e.persisted){let e=window.location.pathname;S.current.captureState(e)}},q=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{S.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return l(()=>(document.addEventListener(`click`,W),window.addEventListener(`popstate`,G),window.addEventListener(`pagehide`,K),window.addEventListener(`pageshow`,q),()=>{document.removeEventListener(`click`,W),window.removeEventListener(`popstate`,G),window.removeEventListener(`pagehide`,K),window.removeEventListener(`pageshow`,q)}),[]),l(()=>{w.current=i;let e=()=>{document.hidden?C.current=Date.now():C.current!==null&&Date.now()-C.current>w.current&&E.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[i]),l(()=>(c.current=!0,e((e,t)=>H.current?.(e,t)??Promise.resolve()),()=>{c.current=!1,t(),k(),A(),U.current?.cancel&&U.current.cancel()}),[]),n}export{I as ClientRouter,T as NavigationErrorHandler,D as StatePreserver,c as clearPropsCache,i as clearPropsCacheForComponent,o as extractMetadata,r as extractServerProps,n as extractServerPropsWithCache,a as extractStaticParams,s as hasServerSideDataFetching};
@@ -0,0 +1,3 @@
1
+ import{C as e,E as t,S as n,T as r,w as i}from"./regex-constants-DQ2vkSU5.mjs";import{t as a}from"./alias-resolver-BIWqeQml.mjs";import{t as o}from"./resolve-R6nLL3qq.mjs";import{Buffer as s}from"node:buffer";import{promises as c}from"node:fs";import l from"node:path";const u=`\0virtual:feed`;function d(a){return a.replace(n,`&amp;`).replace(r,`&lt;`).replace(i,`&gt;`).replace(t,`&quot;`).replace(e,`&apos;`)}function f(e){return(typeof e==`string`?new Date(e):e).toUTCString()}function p(e){return e?typeof e==`string`?` <dc:creator>${d(e)}</dc:creator>`:e.email?` <author>${d(`${e.email} (${e.name})`)}</author>`:` <dc:creator>${d(e.name)}</dc:creator>`:``}function m(e){let t=[` <item>`];t.push(` <title>${d(e.title)}</title>`),t.push(` <link>${d(e.url)}</link>`),e.description&&t.push(` <description>${d(e.description)}</description>`),e.content&&t.push(` <content:encoded><![CDATA[${e.content.replace(/\]\]>/g,`]]]]><![CDATA[>`)}]]></content:encoded>`);let n=p(e.author);if(n&&t.push(n),e.pubDate&&t.push(` <pubDate>${f(e.pubDate)}</pubDate>`),t.push(` <guid isPermaLink="${e.guid?`false`:`true`}">${d(e.guid||e.url)}</guid>`),e.categories)for(let n of e.categories)t.push(` <category>${d(n)}</category>`);if(e.enclosure){let n=[`url="${d(e.enclosure.url)}"`];e.enclosure.length!==void 0&&n.push(`length="${e.enclosure.length}"`),n.push(`type="${d(e.enclosure.type||`application/octet-stream`)}"`),t.push(` <enclosure ${n.join(` `)} />`)}return t.push(` </item>`),t.join(`
2
+ `)}function h(e){let t=e.items.some(e=>e.content),n=e.items.some(e=>typeof e.author==`string`||typeof e.author==`object`&&e.author!==null&&!e.author.email),r=[];t&&r.push(`xmlns:content="http://purl.org/rss/1.0/modules/content/"`),n&&r.push(`xmlns:dc="http://purl.org/dc/elements/1.1/"`),r.push(`xmlns:atom="http://www.w3.org/2005/Atom"`);let i=[`<?xml version="1.0" encoding="UTF-8"?>`,`<rss version="2.0"${r.length>0?` ${r.join(` `)}`:``}>`,` <channel>`,` <title>${d(e.title)}</title>`,` <link>${d(e.link)}</link>`,` <description>${d(e.description)}</description>`,` <atom:link href="${d(`${e.link.replace(/\/+$/,``)}/feed.xml`)}" rel="self" type="application/rss+xml" />`];e.language&&i.push(` <language>${d(e.language)}</language>`),e.copyright&&i.push(` <copyright>${d(e.copyright)}</copyright>`),e.lastBuildDate&&i.push(` <lastBuildDate>${f(e.lastBuildDate)}</lastBuildDate>`),e.ttl!==void 0&&i.push(` <ttl>${e.ttl}</ttl>`),e.image&&(i.push(` <image>`),i.push(` <url>${d(e.image.url)}</url>`),i.push(` <title>${d(e.image.title)}</title>`),i.push(` <link>${d(e.image.link)}</link>`),e.image.width!==void 0&&i.push(` <width>${e.image.width}</width>`),e.image.height!==void 0&&i.push(` <height>${e.image.height}</height>`),i.push(` </image>`));for(let t of e.items)i.push(m(t));return i.push(` </channel>`),i.push(`</rss>`),i.join(`
3
+ `)}function g(e){switch(e){case`ts`:return`ts`;case`tsx`:return`tsx`;case`js`:case`mjs`:return`js`;case`jsx`:return`jsx`;default:throw Error(`Unsupported feed file extension: ".${e}". Allowed extensions are: .ts, .tsx, .js, .jsx, .mjs`)}}async function _(e,t=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`]){let n=l.join(e,`feed.xml`);try{return await c.access(n),{type:`static`,path:n}}catch{}for(let n of t){let t=l.join(e,`feed${n}`);try{return await c.access(t),{type:`dynamic`,path:t}}catch{}}return null}function v(e,t,n={},r){return{name:`virtual-feed`,resolveId(t,i){if(t===u)return t;if(Object.keys(n).length>0){let e=a(t,n,r);if(e)return o(e)||e}if(t.startsWith(`.`)){let n=!i||i.startsWith(`\0`)?e.path:i,r=l.resolve(l.dirname(n),t);return o(r)||r}return null},async load(n){if(n===u)return{code:t,moduleType:g(l.extname(e.path).slice(1))};if(n&&!n.startsWith(`\0`))try{return{code:await c.readFile(n,`utf-8`),moduleType:g(l.extname(n).slice(1))}}catch{return null}return null}}}async function y(e){let{appDir:t,outDir:n,extensions:r,aliases:i={}}=e,a=await _(t,r);if(!a)return!1;await c.mkdir(n,{recursive:!0});let o=l.join(n,`feed.xml`);if(a.type===`static`)return await c.copyFile(a.path,o),!0;try{let{build:e}=await import(`rolldown`),n=await e({input:u,external:[`rari`],platform:`node`,write:!1,output:{format:`esm`,codeSplitting:!1},plugins:[v(a,await c.readFile(a.path,`utf-8`),i,l.dirname(l.dirname(t)))]});if(!n.output||n.output.length===0)throw Error(`Failed to build feed module`);let r=n.output.find(e=>e.type===`chunk`&&e.isEntry)||n.output.find(e=>e.type===`chunk`);if(!r||r.type!==`chunk`)throw Error(`No chunk output found in feed build result`);let d=r.code,f=await import(`data:text/javascript;base64,${s.from(d).toString(`base64`)}`);if(!f||f.default==null)throw Error(`Feed file must export a default export (either an object or a function)`);let p;if(typeof f.default==`function`){let e=f.default();p=e instanceof Promise?await e:e}else p=f.default;let m=h(p);return await c.writeFile(o,m),!0}catch(e){return console.error(`[rari] Failed to build/execute feed file:`,e),!1}}export{y as generateFeedFile};
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { d as Metadata, l as LayoutProps, p as PageProps } from "./types-K8DF80Bq.mjs";
2
- import { a as SitemapImage, i as SitemapEntry, n as RobotsRule, o as SitemapVideo, r as Sitemap, t as Robots } from "./metadata-route-85WvBQcW.mjs";
1
+ import { d as Metadata, l as LayoutProps, p as PageProps } from "./types-BwhW3M72.mjs";
2
+ import { a as Sitemap, c as SitemapVideo, i as RobotsRule, n as FeedEntry, o as SitemapEntry, r as Robots, s as SitemapImage, t as Feed } from "./metadata-route-_d5FkjlL.mjs";
3
3
  import { c as RariURL, n as ProxyConfig, r as ProxyFunction, s as RariFetchEvent } from "./types-3dq9RGI5.mjs";
4
4
  import { RariRequest } from "./proxy/RariRequest.mjs";
5
5
  import { RariResponse } from "./proxy/RariResponse.mjs";
6
- export { type LayoutProps, type Metadata, type PageProps, type ProxyConfig, type ProxyFunction, type RariFetchEvent, RariRequest, RariResponse, type RariURL, type Robots, type RobotsRule, type Sitemap, type SitemapEntry, type SitemapImage, type SitemapVideo };
6
+ export { type Feed, type FeedEntry, type LayoutProps, type Metadata, type PageProps, type ProxyConfig, type ProxyFunction, type RariFetchEvent, RariRequest, RariResponse, type RariURL, type Robots, type RobotsRule, type Sitemap, type SitemapEntry, type SitemapImage, type SitemapVideo };
@@ -68,5 +68,41 @@ interface SitemapEntry {
68
68
  videos?: SitemapVideo[];
69
69
  }
70
70
  type Sitemap = SitemapEntry[];
71
+ interface FeedEntry {
72
+ title: string;
73
+ url: string;
74
+ description?: string;
75
+ content?: string;
76
+ author?: string | {
77
+ name: string;
78
+ email?: string;
79
+ url?: string;
80
+ };
81
+ pubDate?: string | Date;
82
+ guid?: string;
83
+ categories?: string[];
84
+ enclosure?: {
85
+ url: string;
86
+ length?: number;
87
+ type?: string;
88
+ };
89
+ }
90
+ interface Feed {
91
+ title: string;
92
+ description: string;
93
+ link: string;
94
+ language?: string;
95
+ copyright?: string;
96
+ lastBuildDate?: string | Date;
97
+ ttl?: number;
98
+ image?: {
99
+ url: string;
100
+ title: string;
101
+ link: string;
102
+ width?: number;
103
+ height?: number;
104
+ };
105
+ items: FeedEntry[];
106
+ }
71
107
  //#endregion
72
- export { SitemapImage as a, SitemapEntry as i, RobotsRule as n, SitemapVideo as o, Sitemap as r, Robots as t };
108
+ export { Sitemap as a, SitemapVideo as c, RobotsRule as i, FeedEntry as n, SitemapEntry as o, Robots as r, SitemapImage as s, Feed as t };
@@ -1,4 +1,4 @@
1
- //#region src/proxy/shared/utils.d.ts
1
+ //#region src/proxy/shared/types.d.ts
2
2
  interface SimpleRequest {
3
3
  url: string;
4
4
  method: string;
@@ -1 +1 @@
1
- function e(e){if(!e)return null;let t=e.headers?.get?.(`x-rari-proxy-rewrite`);return t?{continue:!1,rewrite:t}:null}function t(e){if(!e||e.status==null)return null;let t=e.headers?.get?.(`location`);return t&&e.status>=300&&e.status<400?{continue:!1,redirect:{destination:t,permanent:e.status===301||e.status===308}}:null}function n(e,t,n){if(Object.hasOwn(e,t)){let r=e[t];e[t]=Array.isArray(r)?[...r,n]:[r,n]}else e[t]=n}function r(e){let t={},r={};return e?.forEach&&e.forEach((e,i)=>{let a=i.toLowerCase();a.startsWith(`x-rari-proxy-request-`)?n(t,a.replace(`x-rari-proxy-request-`,``),e):a.startsWith(`x-rari-proxy-`)||n(r,a,e)}),{requestHeaders:Object.keys(t).length>0?t:void 0,responseHeaders:Object.keys(r).length>0?r:void 0}}function i(e){let{requestHeaders:t,responseHeaders:n}=r(e.headers);return{continue:!0,requestHeaders:t,responseHeaders:n}}async function a(e){let t={};e.headers?.forEach&&e.headers.forEach((e,r)=>{n(t,r.toLowerCase(),e)});let r;try{e.text&&typeof e.text==`function`?r=await e.text():e.body!=null&&typeof e.body==`string`?r=e.body:e.body!=null&&console.warn(`[rari] Proxy: Response body is not extractable as text`)}catch(e){console.error(`[rari] Proxy: Failed to extract response body:`,e)}return{continue:!1,response:{status:e.status??200,headers:t,body:r}}}async function o(n){return n?e(n)||t(n)||(n.headers?.get?.(`x-rari-proxy-continue`)===`true`?i(n):n.status==null?{continue:!0}:await a(n)):{continue:!0}}async function s(e,t){try{let n=await import(e);if(!n||!n.proxy)return console.error(`[rari] Proxy: proxy function not found in module`),!1;let{RariRequest:r}=await import(t);return globalThis[`~rariExecuteProxy`]=async function(e){try{let t=new r(e.url,{method:e.method,headers:new Headers(e.headers)}),i=[],a=await n.proxy(t,{waitUntil:e=>{e.catch(()=>{}),i.push(e)}});return i.length>0&&Promise.allSettled(i).then(e=>{e.forEach((e,t)=>{e.status===`rejected`&&console.error(`[rari] Proxy: waitUntil promise ${t} failed:`,e.reason)})}),await o(a)}catch(e){return console.error(`[rari] Proxy: Proxy execution error:`,e),{continue:!0}}},!0}catch(e){return console.error(`[rari] Proxy: Failed to initialize proxy executor:`,e),!1}}export{s as initializeProxyExecutor};
1
+ function e(e,t,n){if(Object.hasOwn(e,t)){let r=e[t];e[t]=Array.isArray(r)?[...r,n]:[r,n]}else e[t]=n}function t(t){let n={},r={};return t?.forEach&&t.forEach((t,i)=>{let a=i.toLowerCase();a.startsWith(`x-rari-proxy-request-`)?e(n,a.replace(`x-rari-proxy-request-`,``),t):a.startsWith(`x-rari-proxy-`)||e(r,a,t)}),{requestHeaders:Object.keys(n).length>0?n:void 0,responseHeaders:Object.keys(r).length>0?r:void 0}}function n(t){let n={};return t?.forEach&&t.forEach((t,r)=>{e(n,r.toLowerCase(),t)}),n}function r(e){if(!e)return null;let t=e.headers?.get?.(`x-rari-proxy-rewrite`);return t?{continue:!1,rewrite:t}:null}function i(e){if(!e||e.status==null)return null;let t=e.headers?.get?.(`location`);return t&&e.status>=300&&e.status<400?{continue:!1,redirect:{destination:t,permanent:e.status===301||e.status===308}}:null}function a(e){let{requestHeaders:n,responseHeaders:r}=t(e.headers);return{continue:!0,requestHeaders:n,responseHeaders:r}}async function o(e){let t=n(e.headers),r;try{e.text&&typeof e.text==`function`?r=await e.text():e.body!=null&&typeof e.body==`string`?r=e.body:e.body!=null&&console.warn(`[rari] Proxy: Response body is not extractable as text`)}catch(e){console.error(`[rari] Proxy: Failed to extract response body:`,e)}return{continue:!1,response:{status:e.status??200,headers:t,body:r}}}async function s(e){return e?r(e)||i(e)||(e.headers?.get?.(`x-rari-proxy-continue`)===`true`?a(e):e.status==null?{continue:!0}:await o(e)):{continue:!0}}async function c(e,t){try{let n=await import(e);if(!n||!n.proxy)return console.error(`[rari] Proxy: proxy function not found in module`),!1;let{RariRequest:r}=await import(t);return globalThis[`~rariExecuteProxy`]=async function(e){try{let t=new r(e.url,{method:e.method,headers:new Headers(e.headers)}),i=[],a=await n.proxy(t,{waitUntil:e=>{e.catch(()=>{}),i.push(e)}});return i.length>0&&Promise.allSettled(i).then(e=>{e.forEach((e,t)=>{e.status===`rejected`&&console.error(`[rari] Proxy: waitUntil promise ${t} failed:`,e.reason)})}),await s(a)}catch(e){return console.error(`[rari] Proxy: Proxy execution error:`,e),{continue:!0}}},!0}catch(e){return console.error(`[rari] Proxy: Failed to initialize proxy executor:`,e),!1}}export{c as initializeProxyExecutor};
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./utils-BdLqcjvq-QFbF96eD.mjs";import{existsSync as o,readFileSync as s,writeFileSync as c}from"node:fs";import{join as l}from"node:path";import u from"node:process";import{styleText as d}from"node:util";function f(){let r=u.cwd();e(`Creating Railway deployment configuration...`),t(r,{providerName:`Railway`,deployScript:`echo "Push to GitHub and connect to Railway to deploy"`,startScript:`rari start`,dependency:n()}),p(r),a(r,`Railway`,`.railway`),m(r),h()}function p(e){i(e,`railway.toml`,`[build]
1
+ import{a as e,i as t,n,o as r,r as i,t as a}from"./utils-DtilLmFs-CiitZqwE.mjs";import{existsSync as o,readFileSync as s,writeFileSync as c}from"node:fs";import{join as l}from"node:path";import u from"node:process";import{styleText as d}from"node:util";function f(){let r=u.cwd();e(`Creating Railway deployment configuration...`),t(r,{providerName:`Railway`,deployScript:`echo "Push to GitHub and connect to Railway to deploy"`,startScript:`rari start`,dependency:n()}),p(r),a(r,`Railway`,`.railway`),m(r),h()}function p(e){i(e,`railway.toml`,`[build]
2
2
  builder = "RAILPACK"
3
3
 
4
4
  [deploy]
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./utils-BdLqcjvq-QFbF96eD.mjs";import{existsSync as o,readFileSync as s,writeFileSync as c}from"node:fs";import{join as l}from"node:path";import u from"node:process";import{styleText as d}from"node:util";function f(){let r=u.cwd();e(`Creating Render deployment configuration...`),t(r,{providerName:`Render`,deployScript:`echo "Push to GitHub and connect to Render to deploy"`,startScript:`rari start`,dependency:n()}),p(r),a(r,`Render`,`.render`),m(r),h()}function p(e){i(e,`render.yaml`,`services:
1
+ import{a as e,i as t,n,o as r,r as i,t as a}from"./utils-DtilLmFs-CiitZqwE.mjs";import{existsSync as o,readFileSync as s,writeFileSync as c}from"node:fs";import{join as l}from"node:path";import u from"node:process";import{styleText as d}from"node:util";function f(){let r=u.cwd();e(`Creating Render deployment configuration...`),t(r,{providerName:`Render`,deployScript:`echo "Push to GitHub and connect to Render to deploy"`,startScript:`rari start`,dependency:n()}),p(r),a(r,`Render`,`.render`),m(r),h()}function p(e){i(e,`render.yaml`,`services:
2
2
  - type: web
3
3
  name: rari-app
4
4
  runtime: node
@@ -0,0 +1 @@
1
+ import{existsSync as e}from"node:fs";import t from"node:path";const n=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`];function r(r){for(let t of n){let n=r+t;if(e(n))return n}for(let i of n){let n=t.join(r,`index${i}`);if(e(n))return n}return null}export{r as t};
@@ -0,0 +1,2 @@
1
+ import{Buffer as e}from"node:buffer";import{promises as t}from"node:fs";import n from"node:path";function r(e){return Array.isArray(e)?e:e?[e]:[`*`]}function i(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``)}function a(e){let t=[],n=r(e.userAgent);for(let r of n){t.push(`User-Agent: ${r}`);let n=i(e.allow);for(let e of n)t.push(`Allow: ${e}`);let a=i(e.disallow);for(let e of a)t.push(`Disallow: ${e}`);e.crawlDelay!==void 0&&t.push(`Crawl-delay: ${e.crawlDelay}`),t.push(``)}return t}function o(e){return e?[`Host: ${e}`,``]:[]}function s(e){return i(e).map(e=>`Sitemap: ${e}`)}function c(e){let t=[],n=Array.isArray(e.rules)?e.rules:[e.rules];for(let e of n)t.push(...a(e));return t.push(...o(e.host)),t.push(...s(e.sitemap)),t.join(`
2
+ `)}async function l(e,r=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`]){let i=n.join(e,`robots.txt`);try{return await t.access(i),{type:`static`,path:i}}catch(e){if(e?.code!==`ENOENT`)throw e}for(let i of r){let r=n.join(e,`robots${i}`);try{return await t.access(r),{type:`dynamic`,path:r}}catch(e){if(e?.code!==`ENOENT`)throw e}}return null}async function u(r){let{appDir:i,outDir:a,extensions:o}=r,s=await l(i,o);if(!s)return!1;let u=n.join(a,`robots.txt`);if(await t.mkdir(n.dirname(u),{recursive:!0}),s.type===`static`)return await t.copyFile(s.path,u),!0;try{let{build:r}=await import(`rolldown`),i=await t.readFile(s.path,`utf-8`),a=`\0virtual:robots`,o=await r({input:a,external:[`rari`],platform:`node`,write:!1,output:{format:`esm`,codeSplitting:!1},plugins:[{name:`virtual-robots`,resolveId(e){return e===a?e:e.startsWith(`.`)?n.resolve(n.dirname(s.path),e):null},load(e){if(e===a){let e=n.extname(s.path).slice(1),t;switch(e){case`ts`:t=`ts`;break;case`tsx`:t=`tsx`;break;case`js`:case`mjs`:t=`js`;break;case`jsx`:t=`jsx`;break;default:throw Error(`Unsupported robots file extension: .${e}. Supported extensions are: .ts, .tsx, .js, .jsx, .mjs`)}return{code:i,moduleType:t}}return null}}]});if(!o.output||o.output.length===0)throw Error(`Failed to build robots module`);let l=o.output.find(e=>e.type===`chunk`&&e.isEntry)||o.output.find(e=>e.type===`chunk`);if(!l||l.type!==`chunk`)throw Error(`No chunk output found in robots build result`);let d=l.code,f=await import(`data:text/javascript;base64,${e.from(d).toString(`base64`)}`);if(!f||f.default==null)throw Error(`Robots file must export a default export (either an object or a function)`);let p;if(typeof f.default==`function`){let e=f.default();p=e instanceof Promise?await e:e}else p=f.default;let m=c(p);return await t.writeFile(u,m),!0}catch(e){return console.error(`[rari] Failed to build/execute robots file:`,e),!1}}export{u as generateRobotsFile};
@@ -1 +1 @@
1
- "use client";import{t as e}from"../timer-utils-Duul5JHq.mjs";import{Component as t}from"react";import{jsx as n}from"react/jsx-runtime";var r=class extends t{_isMounted=!1;_pendingTimer=null;constructor(e){super(e),this.state={hasError:!1,error:null,ErrorComponent:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidMount(){this._isMounted=!0}componentWillUnmount(){this._isMounted=!1,this._pendingTimer=e(this._pendingTimer)}componentDidCatch(e,t){console.error(`[rari] Error boundary caught error:`,e,t);let n=this.props.errorComponentId;if(n&&typeof window<`u`){let e=window[`~clientComponents`]?.[n];e&&(e.component&&typeof e.component==`function`?this.setState({ErrorComponent:e.component}):e.loader&&!e.loading&&(e.loading=!0,e.loader().then(t=>{let n=t.default||t;e.component=n,e.registered=!0,e.loading=!1,this.setState({ErrorComponent:n})}).catch(t=>{e.loading=!1,console.error(`[rari] Failed to load error component ${n}:`,t)})))}}reset=()=>{this._pendingTimer=e(this._pendingTimer),this._pendingTimer=setTimeout(()=>{this._isMounted&&this.setState({hasError:!1,error:null,ErrorComponent:null}),this._pendingTimer=null},50)};render(){if(this.state.hasError&&this.state.error){let{ErrorComponent:e}=this.state;return e?n(e,{error:this.state.error,reset:this.reset}):null}return this.props.children}};export{r as ErrorBoundaryWrapper};
1
+ "use client";import{t as e}from"../timer-Duul5JHq.mjs";import{Component as t}from"react";import{jsx as n}from"react/jsx-runtime";var r=class extends t{_isMounted=!1;_pendingTimer=null;constructor(e){super(e),this.state={hasError:!1,error:null,ErrorComponent:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidMount(){this._isMounted=!0}componentWillUnmount(){this._isMounted=!1,this._pendingTimer=e(this._pendingTimer)}componentDidCatch(e,t){console.error(`[rari] Error boundary caught error:`,e,t);let n=this.props.errorComponentId;if(n&&typeof window<`u`){let e=window[`~clientComponents`]?.[n];e&&(e.component&&typeof e.component==`function`?this.setState({ErrorComponent:e.component}):e.loader&&!e.loading&&(e.loading=!0,e.loader().then(t=>{let n=t.default||t;e.component=n,e.registered=!0,e.loading=!1,this.setState({ErrorComponent:n})}).catch(t=>{e.loading=!1,console.error(`[rari] Failed to load error component ${n}:`,t)})))}}reset=()=>{this._pendingTimer=e(this._pendingTimer),this._pendingTimer=setTimeout(()=>{this._isMounted&&this.setState({hasError:!1,error:null,ErrorComponent:null}),this._pendingTimer=null},50)};render(){if(this.state.hasError&&this.state.error){let{ErrorComponent:e}=this.state;return e?n(e,{error:this.state.error,reset:this.reset}):null}return this.props.children}};export{r as ErrorBoundaryWrapper};
@@ -71,6 +71,11 @@ interface MetadataResult {
71
71
  };
72
72
  viewport?: string;
73
73
  canonical?: string;
74
+ alternates?: {
75
+ canonical?: string;
76
+ languages?: Record<string, string>;
77
+ types?: Record<string, string>;
78
+ };
74
79
  }
75
80
  type StaticParamsResult = Array<Record<string, string | string[]>>;
76
81
  declare function extractServerProps(componentPath: string, params: Record<string, string>, searchParams: Record<string, string>): Promise<ServerSidePropsResult>;
@@ -1,7 +1,7 @@
1
- import{C as e,E as t,S as n,T as r,w as i}from"./regex-constants-DQ2vkSU5.mjs";import{t as a}from"./alias-resolver-BintHkb_.mjs";import{Buffer as o}from"node:buffer";import{existsSync as s,promises as c}from"node:fs";import l from"node:path";const u=/[^\w-]/g,d=`\0virtual:sitemap`;function f(a){return a.replace(n,`&amp;`).replace(r,`&lt;`).replace(i,`&gt;`).replace(t,`&quot;`).replace(e,`&apos;`)}function p(e){return(typeof e==`string`?new Date(e):e).toISOString()}function m(e){return[` <image:image>`,` <image:loc>${f(e)}</image:loc>`,` </image:image>`].join(`
1
+ import{C as e,E as t,S as n,T as r,w as i}from"./regex-constants-DQ2vkSU5.mjs";import{t as a}from"./alias-resolver-BIWqeQml.mjs";import{t as o}from"./resolve-R6nLL3qq.mjs";import{Buffer as s}from"node:buffer";import{promises as c}from"node:fs";import l from"node:path";const u=/[^\w-]/g,d=`\0virtual:sitemap`;function f(a){return a.replace(n,`&amp;`).replace(r,`&lt;`).replace(i,`&gt;`).replace(t,`&quot;`).replace(e,`&apos;`)}function p(e){return(typeof e==`string`?new Date(e):e).toISOString()}function m(e){return[` <image:image>`,` <image:loc>${f(e)}</image:loc>`,` </image:image>`].join(`
2
2
  `)}function h(e){let t=[` <image:image>`,` <image:loc>${f(e.loc)}</image:loc>`];return e.title&&t.push(` <image:title>${f(e.title)}</image:title>`),e.caption&&t.push(` <image:caption>${f(e.caption)}</image:caption>`),e.geoLocation&&t.push(` <image:geo_location>${f(e.geoLocation)}</image:geo_location>`),e.license&&t.push(` <image:license>${f(e.license)}</image:license>`),t.push(` </image:image>`),t.join(`
3
3
  `)}function g(e){let t=[];for(let n of e)typeof n==`string`?t.push(m(n)):t.push(h(n));return t.join(`
4
4
  `)}function _(e){let t=[];if(t.push(` <video:video>`),t.push(` <video:title>${f(e.title)}</video:title>`),t.push(` <video:thumbnail_loc>${f(e.thumbnail_loc)}</video:thumbnail_loc>`),t.push(` <video:description>${f(e.description)}</video:description>`),e.content_loc&&t.push(` <video:content_loc>${f(e.content_loc)}</video:content_loc>`),e.player_loc&&t.push(` <video:player_loc>${f(e.player_loc)}</video:player_loc>`),e.duration!==void 0&&t.push(` <video:duration>${e.duration}</video:duration>`),e.expiration_date&&t.push(` <video:expiration_date>${f(e.expiration_date)}</video:expiration_date>`),e.rating!==void 0&&t.push(` <video:rating>${e.rating}</video:rating>`),e.view_count!==void 0&&t.push(` <video:view_count>${e.view_count}</video:view_count>`),e.publication_date&&t.push(` <video:publication_date>${f(e.publication_date)}</video:publication_date>`),e.family_friendly!==void 0&&t.push(` <video:family_friendly>${e.family_friendly?`yes`:`no`}</video:family_friendly>`),e.requires_subscription!==void 0&&t.push(` <video:requires_subscription>${e.requires_subscription?`yes`:`no`}</video:requires_subscription>`),e.live!==void 0&&t.push(` <video:live>${e.live?`yes`:`no`}</video:live>`),e.restriction&&t.push(` <video:restriction relationship="${f(e.restriction.relationship)}">${f(e.restriction.content)}</video:restriction>`),e.platform&&t.push(` <video:platform relationship="${f(e.platform.relationship)}">${f(e.platform.content)}</video:platform>`),e.uploader){let n=e.uploader.info?` info="${f(e.uploader.info)}"`:``;t.push(` <video:uploader${n}>${f(e.uploader.name)}</video:uploader>`)}if(e.tag)for(let n of e.tag)t.push(` <video:tag>${f(n)}</video:tag>`);return t.push(` </video:video>`),t.join(`
5
5
  `)}function v(e){return e.map(e=>_(e)).join(`
6
6
  `)}function y(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"`];return 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"`),i}function b(e,t){e.push(` <url>`),e.push(` <loc>${f(t.url)}</loc>`),t.lastModified&&e.push(` <lastmod>${p(t.lastModified)}</lastmod>`),t.changeFrequency&&e.push(` <changefreq>${t.changeFrequency}</changefreq>`),t.priority!==void 0&&e.push(` <priority>${t.priority}</priority>`)}function x(e,t){if(t.alternates?.languages)for(let[n,r]of Object.entries(t.alternates.languages))e.push(` <xhtml:link rel="alternate" hreflang="${f(n)}" href="${f(String(r))}" />`)}function S(e,t){t.images&&t.images.length>0&&e.push(g(t.images)),t.videos&&t.videos.length>0&&e.push(v(t.videos))}function C(e){let t=[`<?xml version="1.0" encoding="UTF-8"?>`,`<urlset ${y(e).join(` `)}>`];for(let n of e)b(t,n),x(t,n),S(t,n),t.push(` </url>`);return t.push(`</urlset>`),t.join(`
7
- `)}async function w(e,t=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`]){let n=[],r=l.join(e,`sitemap.xml`);try{return await c.access(r),n.push({type:`static`,path:r}),n}catch{}for(let r of t){let t=l.join(e,`sitemap${r}`);try{return await c.access(t),n.push({type:`dynamic`,path:t}),n}catch{}}return n}function T(e){switch(e){case`ts`:return`ts`;case`tsx`:return`tsx`;case`js`:case`mjs`:case`cjs`:return`js`;case`jsx`:return`jsx`;case`json`:return`json`;default:throw Error(`Unsupported sitemap file extension: ".${e}". Allowed extensions are: .ts, .tsx, .js, .jsx, .mjs, .cjs, .json`)}}function E(e,t,n={},r){return{name:`virtual-sitemap`,resolveId(t,i){if(t===d)return t;if(Object.keys(n).length>0){let e=a(t,n,r);if(e){for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`]){let n=e+t;try{if(s(n))return n}catch{}}return e}}if(t.startsWith(`.`)){let n=l.resolve(l.dirname(i??e.path),t);for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`]){let t=n+e;try{if(s(t))return t}catch{}}return n}return null},async load(n){if(n===d)return{code:t,moduleType:T(l.extname(e.path).slice(1))};if(n&&!n.startsWith(`\0`))try{return{code:await c.readFile(n,`utf-8`),moduleType:T(l.extname(n).slice(1))}}catch{return null}return null}}}function D(e){if(!e.output||e.output.length===0)throw Error(`Failed to build sitemap module`);let t=e.output.find(e=>e.type===`chunk`&&e.isEntry)||e.output.find(e=>e.type===`chunk`);if(!t||t.type!==`chunk`)throw Error(`No chunk output found in sitemap build result`);return t.code}async function O(e,t,n={},r){let{build:i}=await import(`rolldown`),a=D(await i({input:d,external:[`rari`],platform:`node`,write:!1,output:{format:`esm`,codeSplitting:!1},plugins:[E(e,t,n,r)]}));return await import(`data:text/javascript;base64,${o.from(a).toString(`base64`)}`)}async function k(e,t){let n=await e.generateSitemaps(),r=l.join(t,`sitemap`);await c.mkdir(r,{recursive:!0});let i=new Map;for(let{id:t}of n)try{let n=String(t).replace(u,`_`);(!n||n.length===0)&&(n=`_`);let a=i.get(n);if(a!==void 0)throw Error(`Duplicate sanitized sitemap ID "${n}": original IDs "${a}" and "${t}" collide`);i.set(n,String(t));let o=C(typeof e.default==`function`?await e.default({id:t}):e.default),s=l.join(r,`${n}.xml`);await c.writeFile(s,o)}catch(e){throw Error(`Failed to generate sitemap for id "${t}"`,{cause:e})}}async function A(e,t){let n=C(typeof e.default==`function`?await e.default():e.default),r=l.join(t,`sitemap.xml`);await c.writeFile(r,n)}async function j(e){let{appDir:t,extensions:n,outDir:r,aliases:i={}}=e,a=await w(t,n);if(a.length===0)return!1;await c.mkdir(r,{recursive:!0});let o=a[0];if(o.type===`static`){let e=l.join(r,`sitemap.xml`);return await c.copyFile(o.path,e),!0}try{let e=await O(o,await c.readFile(o.path,`utf-8`),i,l.dirname(l.dirname(t)));return typeof e.generateSitemaps==`function`?await k(e,r):await A(e,r),!0}catch(e){return console.error(`[rari] Failed to build/execute sitemap file:`,e),!1}}export{j as generateSitemapFiles};
7
+ `)}async function w(e,t=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.json`]){let n=[],r=l.join(e,`sitemap.xml`);try{return await c.access(r),n.push({type:`static`,path:r}),n}catch{}for(let r of t){let t=l.join(e,`sitemap${r}`);try{return await c.access(t),n.push({type:`dynamic`,path:t}),n}catch{}}return n}function T(e){switch(e){case`ts`:return`ts`;case`tsx`:return`tsx`;case`js`:case`mjs`:return`js`;case`jsx`:return`jsx`;case`json`:return`json`;default:throw Error(`Unsupported sitemap file extension: ".${e}". Allowed extensions are: .ts, .tsx, .js, .jsx, .mjs, .json`)}}function E(e,t,n={},r){return{name:`virtual-sitemap`,resolveId(t,i){if(t===d)return t;if(Object.keys(n).length>0){let e=a(t,n,r);if(e)return o(e)||e}if(t.startsWith(`.`)){let n=!i||i.startsWith(`\0`)?e.path:i,r=l.resolve(l.dirname(n),t);return o(r)||r}return null},async load(n){if(n===d)return{code:t,moduleType:T(l.extname(e.path).slice(1))};if(n&&!n.startsWith(`\0`))try{return{code:await c.readFile(n,`utf-8`),moduleType:T(l.extname(n).slice(1))}}catch{return null}return null}}}function D(e){if(!e.output||e.output.length===0)throw Error(`Failed to build sitemap module`);let t=e.output.find(e=>e.type===`chunk`&&e.isEntry)||e.output.find(e=>e.type===`chunk`);if(!t||t.type!==`chunk`)throw Error(`No chunk output found in sitemap build result`);return t.code}async function O(e,t,n={},r){let{build:i}=await import(`rolldown`),a=D(await i({input:d,external:[`rari`],platform:`node`,write:!1,output:{format:`esm`,codeSplitting:!1},plugins:[E(e,t,n,r)]}));return await import(`data:text/javascript;base64,${s.from(a).toString(`base64`)}`)}async function k(e,t){let n=await e.generateSitemaps(),r=l.join(t,`sitemap`);await c.mkdir(r,{recursive:!0});let i=new Map;for(let{id:t}of n)try{let n=String(t).replace(u,`_`);(!n||n.length===0)&&(n=`_`);let a=i.get(n);if(a!==void 0)throw Error(`Duplicate sanitized sitemap ID "${n}": original IDs "${a}" and "${t}" collide`);i.set(n,String(t));let o=C(typeof e.default==`function`?await e.default({id:t}):e.default),s=l.join(r,`${n}.xml`);await c.writeFile(s,o)}catch(e){throw Error(`Failed to generate sitemap for id "${t}"`,{cause:e})}}async function A(e,t){let n=C(typeof e.default==`function`?await e.default():e.default),r=l.join(t,`sitemap.xml`);await c.writeFile(r,n)}async function j(e){let{appDir:t,extensions:n,outDir:r,aliases:i={}}=e,a=await w(t,n);if(a.length===0)return!1;await c.mkdir(r,{recursive:!0});let o=a[0];if(o.type===`static`){let e=l.join(r,`sitemap.xml`);return await c.copyFile(o.path,e),!0}try{let e=await O(o,await c.readFile(o.path,`utf-8`),i,l.dirname(l.dirname(t)));return typeof e.generateSitemaps==`function`?await k(e,r):await A(e,r),!0}catch(e){return console.error(`[rari] Failed to build/execute sitemap file:`,e),!1}}export{j as generateSitemapFiles};
@@ -155,6 +155,11 @@ interface RouteMetadata {
155
155
  statusBarStyle?: 'default' | 'black' | 'black-translucent';
156
156
  };
157
157
  canonical?: string;
158
+ alternates?: {
159
+ canonical?: string;
160
+ languages?: Record<string, string>;
161
+ types?: Record<string, string>;
162
+ };
158
163
  }
159
164
  type Metadata = RouteMetadata;
160
165
  type RouteParams = Record<string, string | string[]>;
@@ -2,6 +2,7 @@ import{existsSync as e,readFileSync as t,writeFileSync as n}from"node:fs";import
2
2
  `);if(e(c)){let e=t(c,`utf-8`),r=e.split(`
3
3
  `).map(e=>e.trim());r.includes(`${o}/`)||r.includes(o)||(n(c,e+l),s(`Updated .gitignore with ${a} entries`))}else n(c,`# Dependencies
4
4
  node_modules
5
+ .pnpm-store
5
6
 
6
7
  # Build outputs
7
8
  dist
package/dist/vite.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { a as ServerSidePropsResult, c as clearPropsCacheForComponent, d as extractServerPropsWithCache, f as extractStaticParams, i as MetadataResult, l as extractMetadata, n as ServerCacheControlConfig, o as StaticParamsResult, p as hasServerSideDataFetching, r as ServerConfig, s as clearPropsCache, t as ServerCSPConfig, u as extractServerProps } from "./server-config-D_oeQzpc.mjs";
2
- import { a as ErrorProps, c as LayoutEntry, d as Metadata, f as NotFoundEntry, g as TemplateEntry, h as RouteSegmentType, i as ErrorEntry, l as LayoutProps, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, p as PageProps, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-K8DF80Bq.mjs";
3
- import { a as SitemapImage, i as SitemapEntry, n as RobotsRule, o as SitemapVideo, r as Sitemap, t as Robots } from "./metadata-route-85WvBQcW.mjs";
1
+ import { a as ServerSidePropsResult, c as clearPropsCacheForComponent, d as extractServerPropsWithCache, f as extractStaticParams, i as MetadataResult, l as extractMetadata, n as ServerCacheControlConfig, o as StaticParamsResult, p as hasServerSideDataFetching, r as ServerConfig, s as clearPropsCache, t as ServerCSPConfig, u as extractServerProps } from "./server-config-D7_4Hk9w.mjs";
2
+ import { a as ErrorProps, c as LayoutEntry, d as Metadata, f as NotFoundEntry, g as TemplateEntry, h as RouteSegmentType, i as ErrorEntry, l as LayoutProps, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, p as PageProps, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-BwhW3M72.mjs";
3
+ import { a as Sitemap, c as SitemapVideo, i as RobotsRule, o as SitemapEntry, r as Robots, s as SitemapImage } from "./metadata-route-_d5FkjlL.mjs";
4
4
  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-3dq9RGI5.mjs";
5
5
  import { RariRequest } from "./proxy/RariRequest.mjs";
6
6
  import { RariResponse } from "./proxy/RariResponse.mjs";
package/dist/vite.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{a as n,i as r,n as i,o as a,r as o,s,t as c}from"./props-extractor-C8FRV5vW.mjs";import{i as l,n as u,o as d,r as f,t as p}from"./constants-De7aSsCq.mjs";import{_ as m,a as h,b as g,c as _,i as v,m as y,o as ee,r as b,s as te,t as x,x as ne,y as S}from"./regex-constants-DQ2vkSU5.mjs";import{t as C}from"./timer-utils-Duul5JHq.mjs";import{t as re}from"./alias-resolver-BintHkb_.mjs";import{Buffer as ie}from"node:buffer";import{spawn as ae}from"node:child_process";import w,{promises as T}from"node:fs";import E from"node:path";import D from"node:process";import{fileURLToPath as O,pathToFileURL as k}from"node:url";import oe from"node:crypto";import A from"node:fs/promises";import{build as j}from"rolldown";function se(e={}){let{root:t=D.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=E.join(t,n);try{return await T.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=E.join(t,n);try{await T.access(e);for(let t of i){let i=`${r}${t}`,a=E.join(e,i);try{return await T.access(a),s(`Found proxy file: ${E.join(n,i)}`),{filePath:a,exists:!0,relativePath:E.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 M={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`},N={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},ce=[{pattern:N.OPTIONAL_CATCH_ALL,type:`optional-catch-all`,format:e=>`[[...${e}]]`},{pattern:N.CATCH_ALL,type:`catch-all`,format:e=>`[...${e}]`},{pattern:N.DYNAMIC,type:`dynamic`,format:e=>`[${e}]`}],le=/^\([^/]+\)$/;function P(e){return le.test(e)}function ue(e){return e?e.replace(x,`/`).split(`/`).filter(Boolean).some(P):!1}function de(e){for(let t of ce){let n=e.match(t.pattern);if(n)return{type:t.type,param:n[1],format:t.format}}}function fe(e){let t=de(e);return t?t.format(t.param):e}function pe(e){let t=de(e);return t?{type:t.type,value:e,param:t.param}:{type:`static`,value:e}}const me=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,he=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,ge=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var _e=class{appDir;extensions;verbose;constructor(e){this.appDir=E.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=[],s=[];await this.scanDirectory(``,e,t,n,r,i,a,o,s);for(let o of[t,n,r,i,a,s])this.finalizeGroupEntries(e,o);return this.assertNoDuplicateRoutes(e),this.assertNoDuplicateRoutes(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} templates`),console.warn(`[rari] Router: Found ${o.length} API routes`),console.warn(`[rari] Router: Found ${s.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,templates:this.sortTemplates(a),apiRoutes:this.sortApiRoutes(o),ogImages:s,generated:new Date().toISOString()}}finalizeGroupEntries(e,t){for(let n=t.length-1;n>=0;n--){let r=t[n],i=E.dirname(r.filePath).replace(x,`/`);if(!ue(i))continue;let a=e.filter(e=>{let t=E.dirname(e.filePath).replace(x,`/`);return t===i||t.startsWith(`${i}/`)}).map(e=>e.path);if(a.length===0){t.splice(n,1);continue}let o=Array.from(new Set(a)).sort();r.path=o[0],o.length>1&&(r.additionalPaths=o.slice(1))}}assertNoDuplicateRoutes(e){let t=new Map;for(let n of e){let e=t.get(n.path);if(e)throw Error(`[rari] Route conflict: path '${n.path}' is defined by both '${e}' and '${n.filePath}'.`);t.set(n.path,n.filePath)}}async scanDirectory(e,t,n,r,i,a,o,s,c){let l=E.join(this.appDir,e),u;try{u=await T.readdir(l)}catch{return}let d=[],f=[];for(let e of u){let t=E.join(l,e),n=await T.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&f.push(e):n.isFile()&&d.push(e)}await this.processSpecialFiles(e,d,t,n,r,i,a,o,s,c);for(let l of f){let u=e?E.join(e,l):l;await this.scanDirectory(u,t,n,r,i,a,o,s,c)}}async processSpecialFiles(e,t,n,r,i,a,o,s,c,l){let u=this.pathToRoute(e),d=this.findFile(t,M.PAGE);if(d){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:u,filePath:E.join(e,d).replace(x,`/`),segments:t,params:r,isDynamic:r.length>0})}let f=this.findFile(t,M.LAYOUT);if(f){let t=this.getParentPath(e);r.push({path:u,filePath:E.join(e,f).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let p=this.findFile(t,M.LOADING);if(p){let t=this.generateComponentId(u,`loading`);i.push({path:u,filePath:E.join(e,p).replace(x,`/`),componentId:t})}let m=this.findFile(t,M.ERROR);m&&a.push({path:u,filePath:E.join(e,m).replace(x,`/`)});let h=this.findFile(t,M.NOT_FOUND);h&&o.push({path:u,filePath:E.join(e,h).replace(x,`/`)});let g=this.findFile(t,M.TEMPLATE);if(g){let t=this.getParentPath(e);s.push({path:u,filePath:E.join(e,g).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let _=this.findFile(t,M.OG_IMAGE);if(_){let t=E.join(e,_).replace(x,`/`),n=E.join(this.appDir,t),r,i,a;try{let e=await T.readFile(n,`utf-8`),t=e.match(me);t&&(r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10));let o=e.match(he);o&&(a=o[1])}catch{}l.push({path:u,filePath:t,width:r,height:i,contentType:a})}let v=this.findFile(t,M.ROUTE);if(v){let t=await this.processApiRouteFile(e,v);c.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(x,`/`).split(`/`).filter(Boolean).filter(e=>!P(e)).map(fe).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(m).filter(Boolean).filter(e=>!P(e)).map(pe):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(m).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(`_`)&&!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)}sortTemplates(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=E.join(this.appDir,e),n=await T.readFile(t,`utf-8`),r=[];for(let e of ge){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||i.test(n))&&r.push(e)}return r}async processApiRouteFile(e,t){let n=E.join(e,t).replace(x,`/`),r=this.pathToRoute(e),i=this.parseRouteSegments(e),a=this.extractParams(i),o=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:i,params:a,isDynamic:a.length>0,methods:o}}};async function ve(e,t={}){return new _e({appDir:e,...t}).generateManifest()}const ye=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,be=/title\s*:\s*['"]([^'"]+)['"]/,xe=/description\s*:\s*['"]([^'"]+)['"]/,Se=/keywords\s*:\s*\[([\s\S]*?)\]/,Ce={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function F(e){switch(E.basename(e).replace(g,``)){case`page`:return`page`;case`layout`:return`layout`;case`template`:return`template`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function we(e){return/^\([^/]+\)$/.test(e)}function Te(e){if(!e||e===`/`)return`/`;let t=e.replace(x,`/`).split(`/`).filter(e=>!!e&&!we(e));return t.length>0?`/${t.join(`/`)}`:`/`}function Ee(e,t){let n=E.relative(t,E.dirname(e));return!n||n===`.`?`/`:Te(`/${n.replace(x,`/`).split(`/`).filter(Boolean).join(`/`)}`)}function De(e,t,n){if(t===`page`)return[e];let r=`${e}${e===`/`?``:`/`}`,i=n.filter(t=>t===e||t.startsWith(r));return i.length>0?i:[e]}function Oe(e){try{let t=e.match(ye);if(!t)return null;let n=t[1],r={},i=n.match(be);i&&(r.title=i[1]);let a=n.match(xe);a&&(r.description=a[1]);let o=n.match(Se);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(S,``)).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 ke(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 Ae(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 je(e={}){let t={...Ce,...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 T.readdir(e,{withFileTypes:!0});for(let a of i){let i=E.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&F(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=E.resolve(e,t.appDir);try{await T.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let d=await ve(c,{extensions:t.extensions}),f=JSON.stringify(d,null,2),p=E.resolve(e,t.outDir);await T.mkdir(p,{recursive:!0});let m=E.join(p,`server`);return await T.mkdir(m,{recursive:!0}),await T.writeFile(E.join(m,`routes.json`),f,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),f}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=E.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=F(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(`The above dynamic import cannot be analyzed`)&&e.includes(`packages/rari/dist/`)||t(e,n)}},async writeBundle(){n=await c(u||D.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=E.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=F(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=Ee(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=De(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=Oe(await T.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=ke(await T.readFile(i,`utf-8`)),await Ae(E.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:E.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();let e=u||D.cwd(),n=E.resolve(e,t.outDir,`server`),i=E.join(n,`routes.json`);try{let e=await T.readFile(i,`utf-8`),t=JSON.parse(e),r=!1;for(let e of t.routes){if(!e.isDynamic)continue;let t=e.componentId;if(!t)continue;let i=t.startsWith(`app/`)?t.slice(4):t,a=E.resolve(n,`app`,`${i}.js`);try{let t=await import(a);if(typeof t.generateStaticParams==`function`){let n=await t.generateStaticParams();Array.isArray(n)&&n.length>0&&(e.staticParams=n,r=!0)}}catch{}}r&&await T.writeFile(i,JSON.stringify(t,null,2),`utf-8`)}catch{}}}}const Me=/\\/g,Ne=/[^\w/-]/g,Pe=/^src\//,Fe=/\.(tsx?|jsx?)$/,Ie=/^\.\.(?:[/\\]|$)/;function Le(e,t=8){return oe.createHash(`sha256`).update(e).digest(`hex`).slice(0,t)}function Re(e,t=D.cwd()){let n=E.isAbsolute(e)?e:E.resolve(t,e),r=E.relative(t,n);return(Ie.test(r)||E.isAbsolute(r)?e:r).replace(Me,`/`)}function ze(e){return e.replace(Fe,``).replace(Ne,`_`).replace(Pe,``)}function I(e,t=D.cwd()){let n=Re(e,t);return`${ze(n)}_${Le(n)}`}const Be=new Set([`return`,`throw`,`case`,`typeof`,`instanceof`,`new`,`delete`,`void`,`in`,`of`]),Ve=8232,He=8233;function L(e){return e===32||e===9||e===13||e===10||e===Ve||e===He||e===65279}function R(e){return e===13||e===10||e===Ve||e===He}function z(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Ue(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function We(e,t,n){for(;t<n&&L(e.charCodeAt(t));)t++;return t}function B(e,t,n){for(;t<n;){let r=We(e,t,n);if(r!==t){t=r;continue}let i=e.charCodeAt(t);if(i===47&&e.charCodeAt(t+1)===47){t=V(e,t,n);continue}if(i===47&&e.charCodeAt(t+1)===42){t=H(e,t,n);continue}break}return t}function V(e,t,n){for(;t<n&&!R(e.charCodeAt(t));)t++;return t}function H(e,t,n){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;return t+2}function U(e,t,n,r){for(t++;t<n;){let n=e.charCodeAt(t);if(n===92){t+=2;continue}if(n===r)return t+1;t++}return t}function Ge(e,t,n){t++;let r=e.charCodeAt(t)===47;for(r&&t++;t<n;){let n=e.charCodeAt(t);if(z(n)||n===46||n===45)t++;else break}let i=+!r;for(;t<n&&i>0;){let a=e.charCodeAt(t);if(a===39||a===34||a===96){t=U(e,t,n,a);continue}if(a===123){t++;let r=1;for(;t<n&&r>0;){let i=e.charCodeAt(t);if(i===39||i===34||i===96){t=U(e,t,n,i);continue}i===123&&r++,i===125&&r--,t++}continue}if(a===47&&e.charCodeAt(t+1)===62){i--,t+=2;continue}if(a===62){t++,r&&i--;continue}if(a===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||Ue(r)){for(r===47?(i--,t++):r!==33&&i++,t++;t<n;){let n=e.charCodeAt(t);if(z(n)||n===46||n===45)t++;else break}continue}t++;continue}t++}return t}function W(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function G(e){let t={hasUseClient:!1,hasUseServer:!1},n=0,r=e.length;for(;n<r;){let i=e.charCodeAt(n);if(L(i)){n++;continue}if(i===47&&e.charCodeAt(n+1)===47){n=V(e,n,r);continue}if(i===47&&e.charCodeAt(n+1)===42){n=H(e,n,r);continue}if(i!==39&&i!==34)return t;let a=n+1,o=U(e,n,r,i);if(o<=a)return t;let s=o-1-a,c=o;for(;c<r;){let i=e.charCodeAt(c);if(L(i)&&!R(i)){c++;continue}if(R(i)||i===59){s===10&&W(e,a,`use client`)?t.hasUseClient=!0:s===10&&W(e,a,`use server`)&&(t.hasUseServer=!0),n=c+1;break}if(i===47&&e.charCodeAt(c+1)===47){c=V(e,c,r);continue}if(i===47&&e.charCodeAt(c+1)===42){c=H(e,c,r);continue}return t}if(c>=r)return s===10&&W(e,a,`use client`)?t.hasUseClient=!0:s===10&&W(e,a,`use server`)&&(t.hasUseServer=!0),t}return t}function K(e){let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(L(r)){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){t=V(e,t,n);continue}if(r===47&&e.charCodeAt(t+1)===42){t=H(e,t,n);continue}if(r!==39&&r!==34)return!1;let i=t+1,a=U(e,t,n,r);if(a<=i||a-1-i!=10||!W(e,i,`use server`))return!1;let o=a;for(;o<n;){let t=e.charCodeAt(o);if(L(t)&&!R(t)){o++;continue}if(R(t)||t===59)return!0;if(t===47&&e.charCodeAt(o+1)===47){o=V(e,o,n);continue}if(t===47&&e.charCodeAt(o+1)===42){o=H(e,o,n);continue}return!1}return!0}return!1}function q(e){let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(L(r)){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){t=V(e,t,n);continue}if(r===47&&e.charCodeAt(t+1)===42){t=H(e,t,n);continue}if(r!==39&&r!==34)return!1;let i=t+1,a=U(e,t,n,r);if(a<=i||a-1-i!=10||!W(e,i,`use client`))return!1;let o=a;for(;o<n;){let t=e.charCodeAt(o);if(L(t)&&!R(t)){o++;continue}if(R(t)||t===59)return!0;if(t===47&&e.charCodeAt(o+1)===47){o=V(e,o,n);continue}if(t===47&&e.charCodeAt(o+1)===42){o=H(e,o,n);continue}return!1}return!0}return!1}function Ke(e){return e===40||e===91||e===123||e===44||e===59||e===61||e===58||e===63||e===33||e===43||e===45||e===42||e===37||e===38||e===124||e===94||e===126||e===60||e===62}function qe(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(L(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}break}if(n<0||!z(e.charCodeAt(n)))return;let r=n;for(;n>=0&&z(e.charCodeAt(n));)n--;return e.slice(n+1,r+1)}function Je(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(L(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return-1;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}return t}return-1}function Ye(e,t){let n=Je(e,t);if(n===-1||Ke(n))return!0;let r=qe(e,t);return r?Be.has(r):!1}function Xe(e,t,n){t++;let r=!1;for(;t<n;){let i=e.charCodeAt(t);if(i===92){t+=2;continue}if(r){i===93&&(r=!1),t++;continue}if(i===91){r=!0,t++;continue}if(i===47){for(t++;t<n&&z(e.charCodeAt(t));)t++;return t}if(R(i))return t;t++}return t}function Ze(e,t){return e.charCodeAt(t)===101&&e.charCodeAt(t+1)===120&&e.charCodeAt(t+2)===112&&e.charCodeAt(t+3)===111&&e.charCodeAt(t+4)===114&&e.charCodeAt(t+5)===116}function J(e,t){return e.charCodeAt(t)===100&&e.charCodeAt(t+1)===101&&e.charCodeAt(t+2)===102&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===117&&e.charCodeAt(t+5)===108&&e.charCodeAt(t+6)===116}function Y(e){let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(L(r)){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){t=V(e,t,n);continue}if(r===47&&e.charCodeAt(t+1)===42){t=H(e,t,n);continue}if(r===39||r===34||r===96){t=U(e,t,n,r);continue}if(r===47&&e.charCodeAt(t+1)!==47&&e.charCodeAt(t+1)!==42&&Ye(e,t)){t=Xe(e,t,n);continue}if(r===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||Ue(r)){t=Ge(e,t,n);continue}t++;continue}if(Ze(e,t)){let r=t+6;if(r<n){let t=e.charCodeAt(r);if(L(t)||t===123||t===47&&(e.charCodeAt(r+1)===47||e.charCodeAt(r+1)===42)){let t=B(e,r,n);if(J(e,t)){let r=t+7;if(r>=n||!z(e.charCodeAt(r)))return!0}if(e.charCodeAt(t)===123){let r=t+1;for(;r<n&&(r=B(e,r,n),e.charCodeAt(r)!==125);){let t=r;for(;r<n&&z(e.charCodeAt(r));)r++;let i=r-t;if(i===0)break;r=B(e,r,n);let a=!1;if(e.charCodeAt(r)===97&&e.charCodeAt(r+1)===115){a=!0;let t=r+2;if(t<n&&!z(e.charCodeAt(t))){r=B(e,t,n);let i=r;for(;r<n&&z(e.charCodeAt(r));)r++;if(r-i===7&&J(e,i))return!0}}if(!a&&i===7&&J(e,t))return!0;if(e.charCodeAt(r)===44){r++;continue}if(e.charCodeAt(r)===125)break;r++}}}}}t++}return!1}function Qe(e,t){let n=null;for(let r of t)if(e.endsWith(r)&&(n??=w.existsSync(e),n))return e;for(let n of t){let t=`${e}${n}`;if(w.existsSync(t))return t}return null}function $e(e,t){if(w.existsSync(e)){if(!w.statSync(e).isDirectory())return null;for(let n of t){let t=E.join(e,`index${n}`);if(w.existsSync(t))return t}}return null}async function X(e){if(!e.ok){let t;try{t=await e.text()}catch{t=`<unable to read response body>`}let n=t.length>200?`${t.slice(0,200)}...`:t,r=Error(`HTTP ${e.status}: ${e.statusText}`);throw r.status=e.status,r.statusText=e.statusText,r.bodyPreview=n,r}}var et=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=C(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=C(this.resetTimer)}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.reset()}},tt=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 et({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=E.relative(D.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=this.collectDependentPageComponents(e);for(let e of n)this.serverComponentBuilder.invalidateBuildCacheFor(e);let r=[...e,...n],i=await Promise.allSettled(r.map(async e=>{let t=E.relative(D.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))}}})),a=[],o=[];if(i.forEach(e=>{e.status===`fulfilled`&&e.value.success?a.push(e.value):e.status===`fulfilled`&&!e.value.success?o.push(e.value):e.status===`rejected`&&o.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),a.length>0){let e=Date.now();a.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(o.length>0){let e=Date.now();o.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})});await X(n);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}}collectDependentPageComponents(e){let t=this.serverComponentBuilder.getImportGraph(),n=new Set,r=new Set,i=a=>{if(r.has(a))return;r.add(a);let o=t.get(a);if(o)for(let t of o)(t.includes(`/app/`)||t.includes(`\\app\\`))&&!e.includes(t)&&n.add(t),i(t)};for(let t of e)i(t);return[...n]}detectComponentType(e){try{return q(w.readFileSync(e,`utf-8`))?`client`:`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(`
2
- • `);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 nt=/import\s+(\w+)\s+from\s+['"]rari\/image['"]/g,rt=/import\s+\{[^}]*\b(?:Image\s+as\s+(\w+)|Image)\b[^}]*\}\s+from\s+['"]rari\/image['"]/g,it=/src:\s*["']([^"']+)["']/,at=/[.*+?^${}()|[\]\\]/g,ot=/^[A-Z_$][\w$]*$/i,st=/width:\s*(\d+)/,ct=/quality:\s*(\d+)/,lt=/preload:\s*(true|!0)/,ut=/preload:\s*(false|!1)/,dt=/src=\{?["']([^"']+)["']\}?|src=\{([^}]+)\}/,ft=/width=\{?(\d+)\}?/,pt=/quality=\{?(\d+)\}?/,mt=/preload(?:=\{?true\}?)?/,ht=/preload=\{?false\}?/;async function gt(e,t){try{await Ot(await A.readFile(e,`utf8`),e,t)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to process ${e}:`,t)}}const _t=new class{permits;queue=[];constructor(e){this.permits=e}async acquire(){if(this.permits>0){this.permits--;return}return new Promise(e=>{this.queue.push(e)})}release(){this.permits++;let e=this.queue.shift();e&&(this.permits--,e())}async run(e){await this.acquire();try{return await e()}finally{this.release()}}}(50);async function Z(e,t){try{await A.access(e)}catch{return}let n=await A.readdir(e,{withFileTypes:!0}),r=[];for(let i of n){let n=E.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`dist`)continue;r.push(Z(n,t))}else i.isFile()&&g.test(i.name)&&r.push(_t.run(()=>gt(n,t)))}await Promise.all(r)}async function vt(e,t=[]){let n=new Map;try{await A.access(e),await Z(e,n)}catch(t){throw t.code===`ENOENT`?Error(`Required source directory does not exist: ${e}`):t}for(let e of t)try{await A.access(e),await Z(e,n)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to scan directory ${e}:`,t)}return{images:[...n.values()]}}function yt(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:e.endsWith(`.ts`)?`ts`:`js`}async function bt(e,t,n){let r=`\0virtual:${t}`,i=await j({input:r,external:[`rari/image`],platform:`browser`,write:!1,output:{format:`esm`},moduleTypes:{[`.${n}`]:n},transform:{jsx:`react`},plugins:[{name:`virtual-module`,resolveId(e){return e===r?e:null},load(t){return t===r?{code:e,moduleType:n}:null}}]});if(!i.output||i.output.length===0)throw Error(`Transform produced no output`);return i.output[0].code}function xt(e){let t=new Set;for(let n of e.matchAll(nt))t.add(n[1]);for(let n of e.matchAll(rt))n[1]?t.add(n[1]):t.add(`Image`);return t}function St(e){return xt(e)}function Ct(e){let t=e.match(it);if(!t)return null;let n=t[1];if(!n.startsWith(`/`)&&!n.startsWith(`http`))return null;let r=e.match(st),i=r?Number.parseInt(r[1],10):void 0,a=e.match(ct),o=a?Number.parseInt(a[1],10):void 0,s=e.match(lt),c=e.match(ut);return{src:n,width:i,quality:o,preload:!!s&&!c}}function wt(e,t){let n=`${e.src}:${e.width??`auto`}:${e.quality??75}`;(!t.has(n)||e.preload)&&t.set(n,e)}function Tt(e,t){let n=0,r=!1,i=``,a=!1,o=0;for(let s=t;s<e.length;s++){let c=e[s];if(a){a=!1;continue}if(c===`\\`){a=!0;continue}if(!r&&(c===`"`||c===`'`||c==="`")){r=!0,i=c,c==="`"&&(o=1);continue}if(r&&c===i){i==="`"?(o--,o===0&&(r=!1,i=``)):(r=!1,i=``);continue}if(r&&i==="`"&&c===`$`&&s+1<e.length&&e[s+1]===`{`){n++,s++;continue}if(r&&i==="`"&&n>0&&c==="`"){o++;continue}if(r&&i==="`"&&c===`}`&&n>0){n--;continue}if(!r){if(c===`{`)n++;else if(c===`}`&&(n--,n===0))return e.substring(t+1,s)}}return null}function Et(e,t,n){for(let r of t){if(!ot.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe identifier: ${r}`);continue}let t=r.replace(at,`\\$&`),i=RegExp(`React\\.createElement\\(\\s*${t}\\s*,\\s*\\{`,`g`);for(let t of e.matchAll(i)){let r=Tt(e,t.index+t[0].length-1);if(r){let e=Ct(r);e&&wt(e,n)}}}}function Dt(e){return xt(e)}async function Ot(e,t,n){let r=Dt(e);if(r.size!==0)try{let r=await bt(e,t,yt(t)),i=St(r);if(i.size===0)return;Et(r,i,n)}catch{kt(e,r,n)}}function kt(e,t,n){for(let r of t){if(!ot.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe alias: ${r}`);continue}let t=r.replace(at,`\\$&`),i=RegExp(`<${t}\\s([^/>]+)\\/>`,`g`),a=RegExp(`<${t}\\s([^>]+)>`,`g`);for(let t of e.matchAll(i))At(t[1],n);for(let t of e.matchAll(a))At(t[1],n)}}function At(e,t){let n=e.match(dt);if(!n)return;let r=n[1]||n[2];if(!r||r.includes(`{`)||!r.startsWith(`/`)&&!r.startsWith(`http`))return;let i=e.match(ft),a=i?Number.parseInt(i[1],10):void 0,o=e.match(pt),s=o?Number.parseInt(o[1],10):void 0,c=mt.test(e)&&!ht.test(e),l=`${r}:${a??`auto`}:${s??75}`;(!t.has(l)||c)&&t.set(l,{src:r,width:a,quality:s,preload:c})}const jt=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,Q=/from\s+['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s+['"]([^'"]+)['"]/g,Mt=/import(?:\s+(?:\w+|\{[^}]*\}|\*\s+as\s+\w+)(?:\s*,\s*(?:\w+|\{[^}]*\}|\*\s+as\s+\w+))*\s+from\s+)?['"]([^'"]+)['"]/g,Nt=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,Pt=/import\s+(?:(\w+)|\{([^}]+)\})\s+from\s+['"]([^'"]+)['"];?\s*$/gm,Ft=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,It=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,Lt=/[/\\]components[/\\](\w+)(?:\.tsx?|\.jsx?)?$/,Rt=/^(?:robots|sitemap)\.(?:tsx?|jsx?)$/,zt=/^node:/,Bt=new Set([`fs`,`path`,`os`,`crypto`,`util`,`stream`,`events`,`process`,`buffer`,`url`,`querystring`,`zlib`,`http`,`https`,`net`,`tls`,`child_process`,`cluster`,`worker_threads`]),Vt=`[hash]_[local]`,Ht=E.dirname(O(import.meta.url)),Ut=E.dirname(Ht);function Wt(e){return e.startsWith(Ut)}var $=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}getImportGraph(){let e=new Map;for(let[t,n]of this.fileImporters)e.set(t,new Set(n));return e}getHtmlOnlyImports(){return new Set(this.htmlOnlyImports)}hashString(e,t=8){return Le(e,t)}async writeComponentCssAsset(e,t){if(t.length===0)return[];let n=E.join(this.options.outDir,`assets`,`server`);await w.promises.mkdir(n,{recursive:!0});let r=`${t.join(`
3
- `)}\n`,i=`${this.hashString(e+r,12)}.css`,a=E.join(n,i);return await w.promises.writeFile(a,r,`utf-8`),[`/assets/server/${i}`]}getComponentIdFromRouteManifestPath(e){return this.getComponentId(E.join(this.projectRoot,`src`,`app`,e))}getLegacyComponentReferenceId(e){return this.getReadableComponentId(this.getProjectRelativePath(e))}async writeRouteCssEntries(e){let t=E.join(this.options.outDir,this.options.rscDir,`routes.json`);if(!w.existsSync(t))return;let n=await w.promises.readFile(t,`utf-8`),r=JSON.parse(n),i=t=>{if(t)for(let n of t){if(!n.filePath)continue;let t=this.getComponentIdFromRouteManifestPath(n.filePath);n.componentId=t;let r=e.components[t]?.css??[];r.length?n.css=r:delete n.css}};if(i(r.routes),i(r.layouts),i(r.loading),i(r.errors),i(r.notFound),r.apiRoutes)for(let e of r.apiRoutes)e.filePath&&(e.componentId=this.getComponentIdFromRouteManifestPath(e.filePath));await w.promises.writeFile(t,JSON.stringify(r,null,2),`utf-8`)}constructor(e,t={}){this.projectRoot=e;let n=t.rscDir||`server`;this.options={outDir:t.outDir||E.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath||E.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath||E.join(n,`config.json`),minify:t.minify??D.env.NODE_ENV===`production`,alias:t.alias||{},define:t.define,csp:t.csp,cacheControl:t.cacheControl},this.parseHtmlImports()}parseHtmlImports(){let e=E.join(this.projectRoot,`index.html`);if(w.existsSync(e))try{let t=w.readFileSync(e,`utf-8`);for(let e of t.matchAll(jt)){let t=e[1]||e[2];if(t.startsWith(`/src/`)){let e=E.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,t){if(e.includes(`node_modules`)||this.isHtmlOnlyImport(e))return!1;try{let n=G(t??w.readFileSync(e,`utf-8`));return!n.hasUseClient&&!n.hasUseServer}catch{return!1}}isClientComponent(e,t){try{return G(t??w.readFileSync(e,`utf-8`)).hasUseClient}catch{return!1}}buildImportGraph(e){this.fileImporters.clear();let t=e=>{if(!w.existsSync(e))return;let n=w.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=E.join(e,r.name);if(r.isDirectory()){if(r.name===`node_modules`)continue;t(n)}else if(r.isFile()&&g.test(r.name))try{let e=w.readFileSync(n,`utf-8`),t;for(Q.lastIndex=0,t=Q.exec(e);t!==null;){let r=t[1]||t[2]||t[3],i=null;if(r.startsWith(`./`)||r.startsWith(`../`)){let e=E.dirname(n);i=E.resolve(e,r)}else if(r.startsWith(`@/`)){let e=r.slice(2);i=E.join(this.projectRoot,`src`,e)}if(i){let e=[``,`.ts`,`.tsx`,`.js`,`.jsx`],t=null;for(let n of e){let e=i+n;try{if(w.statSync(e).isFile()){t=e;break}}catch{}}t&&(this.fileImporters.has(t)||this.fileImporters.set(t,new Set),this.fileImporters.get(t).add(n))}t=Q.exec(e)}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error building import graph:`,n,e)}}};t(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,t){let n=t??w.readFileSync(e,`utf-8`);if(this.isServerAction(n)){let t=this.extractDependencies(n),r=this.hasNodeImports(n);this.serverActions.set(e,{filePath:e,originalCode:n,dependencies:t,hasNodeImports:r});return}if(!this.isServerComponent(e,n))return;let r=this.extractDependencies(n),i=this.hasNodeImports(n);this.serverComponents.set(e,{filePath:e,originalCode:n,dependencies:r,hasNodeImports:i})}isServerAction(e){return G(e).hasUseServer}extractDependencies(e){let t=[],n;for(Mt.lastIndex=0;n=Mt.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 Bt.has(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=E.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=E.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(Nt)){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(It);if(n){let i=n[1],a=[E.resolve(this.projectRoot,`src`,`components`,`${i}.tsx`),E.resolve(this.projectRoot,`src`,`components`,`${i}.ts`),E.resolve(this.projectRoot,`src`,`components`,`${i}.jsx`),E.resolve(this.projectRoot,`src`,`components`,`${i}.js`)],o=!1;for(let e of a)if(w.existsSync(e)&&this.isClientComponent(e)){o=!0;break}if(!o)continue;let s=`// Component reference: ${i}
1
+ import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{a as n,i as r,n as i,o as a,r as o,s,t as c}from"./props-extractor-C8FRV5vW.mjs";import{i as l,n as u,o as d,r as f,t as p}from"./constants-De7aSsCq.mjs";import{_ as m,a as h,b as g,c as _,i as v,m as y,o as ee,r as b,s as te,t as x,x as ne,y as S}from"./regex-constants-DQ2vkSU5.mjs";import{t as C}from"./timer-Duul5JHq.mjs";import{t as re}from"./alias-resolver-BIWqeQml.mjs";import{Buffer as ie}from"node:buffer";import{spawn as ae}from"node:child_process";import w,{promises as T}from"node:fs";import E from"node:path";import D from"node:process";import{fileURLToPath as O,pathToFileURL as k}from"node:url";import oe from"node:crypto";import A from"node:fs/promises";import{build as j}from"rolldown";function se(e={}){let{root:t=D.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=E.join(t,n);try{return await T.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=E.join(t,n);try{await T.access(e);for(let t of i){let i=`${r}${t}`,a=E.join(e,i);try{return await T.access(a),s(`Found proxy file: ${E.join(n,i)}`),{filePath:a,exists:!0,relativePath:E.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 M={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`},N={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},ce=[{pattern:N.OPTIONAL_CATCH_ALL,type:`optional-catch-all`,format:e=>`[[...${e}]]`},{pattern:N.CATCH_ALL,type:`catch-all`,format:e=>`[...${e}]`},{pattern:N.DYNAMIC,type:`dynamic`,format:e=>`[${e}]`}],le=/^\([^/]+\)$/;function P(e){return le.test(e)}function ue(e){return e?e.replace(x,`/`).split(`/`).filter(Boolean).some(P):!1}function de(e){for(let t of ce){let n=e.match(t.pattern);if(n)return{type:t.type,param:n[1],format:t.format}}}function fe(e){let t=de(e);return t?t.format(t.param):e}function pe(e){let t=de(e);return t?{type:t.type,value:e,param:t.param}:{type:`static`,value:e}}const me=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,he=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,ge=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var _e=class{appDir;extensions;verbose;constructor(e){this.appDir=E.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=[],s=[];await this.scanDirectory(``,e,t,n,r,i,a,o,s);for(let o of[t,n,r,i,a,s])this.finalizeGroupEntries(e,o);return this.assertNoDuplicateRoutes(e),this.assertNoDuplicateRoutes(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} templates`),console.warn(`[rari] Router: Found ${o.length} API routes`),console.warn(`[rari] Router: Found ${s.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,templates:this.sortTemplates(a),apiRoutes:this.sortApiRoutes(o),ogImages:s,generated:new Date().toISOString()}}finalizeGroupEntries(e,t){for(let n=t.length-1;n>=0;n--){let r=t[n],i=E.dirname(r.filePath).replace(x,`/`);if(!ue(i))continue;let a=e.filter(e=>{let t=E.dirname(e.filePath).replace(x,`/`);return t===i||t.startsWith(`${i}/`)}).map(e=>e.path);if(a.length===0){t.splice(n,1);continue}let o=Array.from(new Set(a)).sort();r.path=o[0],o.length>1&&(r.additionalPaths=o.slice(1))}}assertNoDuplicateRoutes(e){let t=new Map;for(let n of e){let e=t.get(n.path);if(e)throw Error(`[rari] Route conflict: path '${n.path}' is defined by both '${e}' and '${n.filePath}'.`);t.set(n.path,n.filePath)}}async scanDirectory(e,t,n,r,i,a,o,s,c){let l=E.join(this.appDir,e),u;try{u=await T.readdir(l)}catch{return}let d=[],f=[];for(let e of u){let t=E.join(l,e),n=await T.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&f.push(e):n.isFile()&&d.push(e)}await this.processSpecialFiles(e,d,t,n,r,i,a,o,s,c);for(let l of f){let u=e?E.join(e,l):l;await this.scanDirectory(u,t,n,r,i,a,o,s,c)}}async processSpecialFiles(e,t,n,r,i,a,o,s,c,l){let u=this.pathToRoute(e),d=this.findFile(t,M.PAGE);if(d){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:u,filePath:E.join(e,d).replace(x,`/`),segments:t,params:r,isDynamic:r.length>0})}let f=this.findFile(t,M.LAYOUT);if(f){let t=this.getParentPath(e);r.push({path:u,filePath:E.join(e,f).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let p=this.findFile(t,M.LOADING);if(p){let t=this.generateComponentId(u,`loading`);i.push({path:u,filePath:E.join(e,p).replace(x,`/`),componentId:t})}let m=this.findFile(t,M.ERROR);m&&a.push({path:u,filePath:E.join(e,m).replace(x,`/`)});let h=this.findFile(t,M.NOT_FOUND);h&&o.push({path:u,filePath:E.join(e,h).replace(x,`/`)});let g=this.findFile(t,M.TEMPLATE);if(g){let t=this.getParentPath(e);s.push({path:u,filePath:E.join(e,g).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let _=this.findFile(t,M.OG_IMAGE);if(_){let t=E.join(e,_).replace(x,`/`),n=E.join(this.appDir,t),r,i,a;try{let e=await T.readFile(n,`utf-8`),t=e.match(me);t&&(r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10));let o=e.match(he);o&&(a=o[1])}catch{}l.push({path:u,filePath:t,width:r,height:i,contentType:a})}let v=this.findFile(t,M.ROUTE);if(v){let t=await this.processApiRouteFile(e,v);c.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(x,`/`).split(`/`).filter(Boolean).filter(e=>!P(e)).map(fe).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(m).filter(Boolean).filter(e=>!P(e)).map(pe):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(m).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(`_`)&&!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)}sortTemplates(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=E.join(this.appDir,e),n=await T.readFile(t,`utf-8`),r=[];for(let e of ge){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||i.test(n))&&r.push(e)}return r}async processApiRouteFile(e,t){let n=E.join(e,t).replace(x,`/`),r=this.pathToRoute(e),i=this.parseRouteSegments(e),a=this.extractParams(i),o=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:i,params:a,isDynamic:a.length>0,methods:o}}};async function ve(e,t={}){return new _e({appDir:e,...t}).generateManifest()}const ye=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,be=/title\s*:\s*['"]([^'"]+)['"]/,xe=/description\s*:\s*['"]([^'"]+)['"]/,Se=/keywords\s*:\s*\[([\s\S]*?)\]/,Ce={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function we(e){switch(E.basename(e).replace(g,``)){case`page`:return`page`;case`layout`:return`layout`;case`template`:return`template`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function Te(e){return/^\([^/]+\)$/.test(e)}function Ee(e){if(!e||e===`/`)return`/`;let t=e.replace(x,`/`).split(`/`).filter(e=>!!e&&!Te(e));return t.length>0?`/${t.join(`/`)}`:`/`}function De(e,t){let n=E.relative(t,E.dirname(e));return!n||n===`.`?`/`:Ee(`/${n.replace(x,`/`).split(`/`).filter(Boolean).join(`/`)}`)}function Oe(e,t,n){if(t===`page`)return[e];let r=`${e}${e===`/`?``:`/`}`,i=n.filter(t=>t===e||t.startsWith(r));return i.length>0?i:[e]}function ke(e){try{let t=e.match(ye);if(!t)return null;let n=t[1],r={},i=n.match(be);i&&(r.title=i[1]);let a=n.match(xe);a&&(r.description=a[1]);let o=n.match(Se);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(S,``)).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 Ae(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 je(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 Me(e={}){let t={...Ce,...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 T.readdir(e,{withFileTypes:!0});for(let a of i){let i=E.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&we(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=E.resolve(e,t.appDir);try{await T.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let d=await ve(c,{extensions:t.extensions}),f=JSON.stringify(d,null,2),p=E.resolve(e,t.outDir);await T.mkdir(p,{recursive:!0});let m=E.join(p,`server`);return await T.mkdir(m,{recursive:!0}),await T.writeFile(E.join(m,`routes.json`),f,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),f}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=E.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=we(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(`The above dynamic import cannot be analyzed`)&&e.includes(`packages/rari/dist/`)||t(e,n)}},async writeBundle(){n=await c(u||D.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=E.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=we(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=De(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=Oe(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=ke(await T.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=Ae(await T.readFile(i,`utf-8`)),await je(E.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:E.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();let e=u||D.cwd(),n=E.resolve(e,t.outDir,`server`),i=E.join(n,`routes.json`);try{let e=await T.readFile(i,`utf-8`),t=JSON.parse(e),r=!1;for(let e of t.routes){if(!e.isDynamic)continue;let t=e.componentId;if(!t)continue;let i=t.startsWith(`app/`)?t.slice(4):t,a=E.resolve(n,`app`,`${i}.js`);try{let t=await import(a);if(typeof t.generateStaticParams==`function`){let n=await t.generateStaticParams();Array.isArray(n)&&n.length>0&&(e.staticParams=n,r=!0)}}catch{}}r&&await T.writeFile(i,JSON.stringify(t,null,2),`utf-8`)}catch{}}}}const Ne=/\\/g,Pe=/[^\w/-]/g,Fe=/^src\//,Ie=/\.(tsx?|jsx?)$/,Le=/^\.\.(?:[/\\]|$)/;function Re(e,t=8){return oe.createHash(`sha256`).update(e).digest(`hex`).slice(0,t)}function ze(e,t=D.cwd()){let n=E.isAbsolute(e)?e:E.resolve(t,e),r=E.relative(t,n);return(Le.test(r)||E.isAbsolute(r)?e:r).replace(Ne,`/`)}function Be(e){return e.replace(Ie,``).replace(Pe,`_`).replace(Fe,``)}function F(e,t=D.cwd()){let n=ze(e,t);return`${Be(n)}_${Re(n)}`}const Ve=new Set([`return`,`throw`,`case`,`typeof`,`instanceof`,`new`,`delete`,`void`,`in`,`of`]),He=8232,Ue=8233;function I(e){return e===32||e===9||e===13||e===10||e===He||e===Ue||e===65279}function L(e){return e===13||e===10||e===He||e===Ue}function R(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function We(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function Ge(e,t,n){for(;t<n&&I(e.charCodeAt(t));)t++;return t}function z(e,t,n){for(;t<n;){let r=Ge(e,t,n);if(r!==t){t=r;continue}let i=e.charCodeAt(t);if(i===47&&e.charCodeAt(t+1)===47){t=B(e,t,n);continue}if(i===47&&e.charCodeAt(t+1)===42){t=V(e,t,n);continue}break}return t}function B(e,t,n){for(;t<n&&!L(e.charCodeAt(t));)t++;return t}function V(e,t,n){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;return t+2}function H(e,t,n,r){for(t++;t<n;){let n=e.charCodeAt(t);if(n===92){t+=2;continue}if(n===r)return t+1;t++}return t}function Ke(e,t,n){t++;let r=e.charCodeAt(t)===47;for(r&&t++;t<n;){let n=e.charCodeAt(t);if(R(n)||n===46||n===45)t++;else break}let i=+!r;for(;t<n&&i>0;){let a=e.charCodeAt(t);if(a===39||a===34||a===96){t=H(e,t,n,a);continue}if(a===123){t++;let r=1;for(;t<n&&r>0;){let i=e.charCodeAt(t);if(i===39||i===34||i===96){t=H(e,t,n,i);continue}i===123&&r++,i===125&&r--,t++}continue}if(a===47&&e.charCodeAt(t+1)===62){i--,t+=2;continue}if(a===62){t++,r&&i--;continue}if(a===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||We(r)){for(r===47?(i--,t++):r!==33&&i++,t++;t<n;){let n=e.charCodeAt(t);if(R(n)||n===46||n===45)t++;else break}continue}t++;continue}t++}return t}function U(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function W(e){let t={hasUseClient:!1,hasUseServer:!1},n=0,r=e.length;for(;n<r;){let i=e.charCodeAt(n);if(I(i)){n++;continue}if(i===47&&e.charCodeAt(n+1)===47){n=B(e,n,r);continue}if(i===47&&e.charCodeAt(n+1)===42){n=V(e,n,r);continue}if(i!==39&&i!==34)return t;let a=n+1,o=H(e,n,r,i);if(o<=a)return t;let s=o-1-a,c=o;for(;c<r;){let i=e.charCodeAt(c);if(I(i)&&!L(i)){c++;continue}if(L(i)||i===59){s===10&&U(e,a,`use client`)?t.hasUseClient=!0:s===10&&U(e,a,`use server`)&&(t.hasUseServer=!0),n=c+1;break}if(i===47&&e.charCodeAt(c+1)===47){c=B(e,c,r);continue}if(i===47&&e.charCodeAt(c+1)===42){c=V(e,c,r);continue}return t}if(c>=r)return s===10&&U(e,a,`use client`)?t.hasUseClient=!0:s===10&&U(e,a,`use server`)&&(t.hasUseServer=!0),t}return t}function G(e){let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(I(r)){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){t=B(e,t,n);continue}if(r===47&&e.charCodeAt(t+1)===42){t=V(e,t,n);continue}if(r!==39&&r!==34)return!1;let i=t+1,a=H(e,t,n,r);if(a<=i||a-1-i!=10||!U(e,i,`use server`))return!1;let o=a;for(;o<n;){let t=e.charCodeAt(o);if(I(t)&&!L(t)){o++;continue}if(L(t)||t===59)return!0;if(t===47&&e.charCodeAt(o+1)===47){o=B(e,o,n);continue}if(t===47&&e.charCodeAt(o+1)===42){o=V(e,o,n);continue}return!1}return!0}return!1}function K(e){let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(I(r)){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){t=B(e,t,n);continue}if(r===47&&e.charCodeAt(t+1)===42){t=V(e,t,n);continue}if(r!==39&&r!==34)return!1;let i=t+1,a=H(e,t,n,r);if(a<=i||a-1-i!=10||!U(e,i,`use client`))return!1;let o=a;for(;o<n;){let t=e.charCodeAt(o);if(I(t)&&!L(t)){o++;continue}if(L(t)||t===59)return!0;if(t===47&&e.charCodeAt(o+1)===47){o=B(e,o,n);continue}if(t===47&&e.charCodeAt(o+1)===42){o=V(e,o,n);continue}return!1}return!0}return!1}function qe(e){return e===40||e===91||e===123||e===44||e===59||e===61||e===58||e===63||e===33||e===43||e===45||e===42||e===37||e===38||e===124||e===94||e===126||e===60||e===62}function Je(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(I(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}break}if(n<0||!R(e.charCodeAt(n)))return;let r=n;for(;n>=0&&R(e.charCodeAt(n));)n--;return e.slice(n+1,r+1)}function Ye(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(I(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return-1;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}return t}return-1}function Xe(e,t){let n=Ye(e,t);if(n===-1||qe(n))return!0;let r=Je(e,t);return r?Ve.has(r):!1}function Ze(e,t,n){t++;let r=!1;for(;t<n;){let i=e.charCodeAt(t);if(i===92){t+=2;continue}if(r){i===93&&(r=!1),t++;continue}if(i===91){r=!0,t++;continue}if(i===47){for(t++;t<n&&R(e.charCodeAt(t));)t++;return t}if(L(i))return t;t++}return t}function Qe(e,t){return e.charCodeAt(t)===101&&e.charCodeAt(t+1)===120&&e.charCodeAt(t+2)===112&&e.charCodeAt(t+3)===111&&e.charCodeAt(t+4)===114&&e.charCodeAt(t+5)===116}function q(e,t){return e.charCodeAt(t)===100&&e.charCodeAt(t+1)===101&&e.charCodeAt(t+2)===102&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===117&&e.charCodeAt(t+5)===108&&e.charCodeAt(t+6)===116}function J(e){let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(I(r)){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){t=B(e,t,n);continue}if(r===47&&e.charCodeAt(t+1)===42){t=V(e,t,n);continue}if(r===39||r===34||r===96){t=H(e,t,n,r);continue}if(r===47&&e.charCodeAt(t+1)!==47&&e.charCodeAt(t+1)!==42&&Xe(e,t)){t=Ze(e,t,n);continue}if(r===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||We(r)){t=Ke(e,t,n);continue}t++;continue}if(Qe(e,t)){let r=t+6;if(r<n){let t=e.charCodeAt(r);if(I(t)||t===123||t===47&&(e.charCodeAt(r+1)===47||e.charCodeAt(r+1)===42)){let t=z(e,r,n);if(q(e,t)){let r=t+7;if(r>=n||!R(e.charCodeAt(r)))return!0}if(e.charCodeAt(t)===123){let r=t+1;for(;r<n&&(r=z(e,r,n),e.charCodeAt(r)!==125);){let t=r;for(;r<n&&R(e.charCodeAt(r));)r++;let i=r-t;if(i===0)break;r=z(e,r,n);let a=!1;if(e.charCodeAt(r)===97&&e.charCodeAt(r+1)===115){a=!0;let t=r+2;if(t<n&&!R(e.charCodeAt(t))){r=z(e,t,n);let i=r;for(;r<n&&R(e.charCodeAt(r));)r++;if(r-i===7&&q(e,i))return!0}}if(!a&&i===7&&q(e,t))return!0;if(e.charCodeAt(r)===44){r++;continue}if(e.charCodeAt(r)===125)break;r++}}}}}t++}return!1}const $e=new Map,et=new Map;function Y(e){let t=$e.get(e);return t===void 0?(t=w.existsSync(e),$e.set(e,t),t):t}function tt(e){let t=et.get(e);if(t!==void 0)return t;try{t=w.statSync(e).isDirectory()}catch{t=!1}return et.set(e,t),t}function X(e,t){let n=null;for(let r of t)if(e.endsWith(r)&&(n??=Y(e),n))return e;for(let n of t){let t=`${e}${n}`;if(Y(t))return t}return null}function Z(e,t){if(Y(e)){if(!tt(e))return null;for(let n of t){let t=E.join(e,`index${n}`);if(Y(t))return t}}return null}async function Q(e){if(!e.ok){let t;try{t=await e.text()}catch{t=`<unable to read response body>`}let n=t.length>200?`${t.slice(0,200)}...`:t,r=Error(`HTTP ${e.status}: ${e.statusText}`);throw r.status=e.status,r.statusText=e.statusText,r.bodyPreview=n,r}}var nt=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=C(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=C(this.resetTimer)}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.reset()}},rt=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 nt({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=E.relative(D.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=this.collectDependentPageComponents(e);for(let e of n)this.serverComponentBuilder.invalidateBuildCacheFor(e);let r=[...e,...n],i=await Promise.allSettled(r.map(async e=>{let t=E.relative(D.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))}}})),a=[],o=[];if(i.forEach(e=>{e.status===`fulfilled`&&e.value.success?a.push(e.value):e.status===`fulfilled`&&!e.value.success?o.push(e.value):e.status===`rejected`&&o.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),a.length>0){let e=Date.now();a.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(o.length>0){let e=Date.now();o.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})});await Q(n);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}}collectDependentPageComponents(e){let t=this.serverComponentBuilder.getImportGraph(),n=new Set,r=new Set,i=a=>{if(r.has(a))return;r.add(a);let o=t.get(a);if(o)for(let t of o)(t.includes(`/app/`)||t.includes(`\\app\\`))&&!e.includes(t)&&n.add(t),i(t)};for(let t of e)i(t);return[...n]}detectComponentType(e){try{return K(w.readFileSync(e,`utf-8`))?`client`:`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(`
2
+ • `);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 it=/import\s+(\w+)\s+from\s+['"]rari\/image['"]/g,at=/import\s+\{[^}]*\b(?:Image\s+as\s+(\w+)|Image)\b[^}]*\}\s+from\s+['"]rari\/image['"]/g,ot=/src:\s*["']([^"']+)["']/,st=/[.*+?^${}()|[\]\\]/g,ct=/^[A-Z_$][\w$]*$/i,lt=/width:\s*(\d+)/,ut=/quality:\s*(\d+)/,dt=/preload:\s*(true|!0)/,ft=/preload:\s*(false|!1)/,pt=/src=\{?["']([^"']+)["']\}?|src=\{([^}]+)\}/,mt=/width=\{?(\d+)\}?/,ht=/quality=\{?(\d+)\}?/,gt=/preload(?:=\{?true\}?)?/,_t=/preload=\{?false\}?/;async function vt(e,t){try{await jt(await A.readFile(e,`utf8`),e,t)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to process ${e}:`,t)}}const yt=new class{permits;queue=[];constructor(e){this.permits=e}async acquire(){if(this.permits>0){this.permits--;return}return new Promise(e=>{this.queue.push(e)})}release(){this.permits++;let e=this.queue.shift();e&&(this.permits--,e())}async run(e){await this.acquire();try{return await e()}finally{this.release()}}}(50);async function bt(e,t){try{await A.access(e)}catch{return}let n=await A.readdir(e,{withFileTypes:!0}),r=[];for(let i of n){let n=E.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`dist`)continue;r.push(bt(n,t))}else i.isFile()&&g.test(i.name)&&r.push(yt.run(()=>vt(n,t)))}await Promise.all(r)}async function xt(e,t=[]){let n=new Map;try{await A.access(e),await bt(e,n)}catch(t){throw t.code===`ENOENT`?Error(`Required source directory does not exist: ${e}`):t}for(let e of t)try{await A.access(e),await bt(e,n)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to scan directory ${e}:`,t)}return{images:[...n.values()]}}function St(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:e.endsWith(`.ts`)?`ts`:`js`}async function Ct(e,t,n){let r=`\0virtual:${t}`,i=await j({input:r,external:[`rari/image`],platform:`browser`,write:!1,output:{format:`esm`},moduleTypes:{[`.${n}`]:n},transform:{jsx:`react`},plugins:[{name:`virtual-module`,resolveId(e){return e===r?e:null},load(t){return t===r?{code:e,moduleType:n}:null}}]});if(!i.output||i.output.length===0)throw Error(`Transform produced no output`);return i.output[0].code}function wt(e){let t=new Set;for(let n of e.matchAll(it))t.add(n[1]);for(let n of e.matchAll(at))n[1]?t.add(n[1]):t.add(`Image`);return t}function Tt(e){return wt(e)}function Et(e){let t=e.match(ot);if(!t)return null;let n=t[1];if(!n.startsWith(`/`)&&!n.startsWith(`http`))return null;let r=e.match(lt),i=r?Number.parseInt(r[1],10):void 0,a=e.match(ut),o=a?Number.parseInt(a[1],10):void 0,s=e.match(dt),c=e.match(ft);return{src:n,width:i,quality:o,preload:!!s&&!c}}function Dt(e,t){let n=`${e.src}:${e.width??`auto`}:${e.quality??75}`;(!t.has(n)||e.preload)&&t.set(n,e)}function Ot(e,t){let n=0,r=!1,i=``,a=!1,o=0;for(let s=t;s<e.length;s++){let c=e[s];if(a){a=!1;continue}if(c===`\\`){a=!0;continue}if(!r&&(c===`"`||c===`'`||c==="`")){r=!0,i=c,c==="`"&&(o=1);continue}if(r&&c===i){i==="`"?(o--,o===0&&(r=!1,i=``)):(r=!1,i=``);continue}if(r&&i==="`"&&c===`$`&&s+1<e.length&&e[s+1]===`{`){n++,s++;continue}if(r&&i==="`"&&n>0&&c==="`"){o++;continue}if(r&&i==="`"&&c===`}`&&n>0){n--;continue}if(!r){if(c===`{`)n++;else if(c===`}`&&(n--,n===0))return e.substring(t+1,s)}}return null}function kt(e,t,n){for(let r of t){if(!ct.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe identifier: ${r}`);continue}let t=r.replace(st,`\\$&`),i=RegExp(`React\\.createElement\\(\\s*${t}\\s*,\\s*\\{`,`g`);for(let t of e.matchAll(i)){let r=Ot(e,t.index+t[0].length-1);if(r){let e=Et(r);e&&Dt(e,n)}}}}function At(e){return wt(e)}async function jt(e,t,n){let r=At(e);if(r.size!==0)try{let r=await Ct(e,t,St(t)),i=Tt(r);if(i.size===0)return;kt(r,i,n)}catch{Mt(e,r,n)}}function Mt(e,t,n){for(let r of t){if(!ct.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe alias: ${r}`);continue}let t=r.replace(st,`\\$&`),i=RegExp(`<${t}\\s([^/>]+)\\/>`,`g`),a=RegExp(`<${t}\\s([^>]+)>`,`g`);for(let t of e.matchAll(i))Nt(t[1],n);for(let t of e.matchAll(a))Nt(t[1],n)}}function Nt(e,t){let n=e.match(pt);if(!n)return;let r=n[1]||n[2];if(!r||r.includes(`{`)||!r.startsWith(`/`)&&!r.startsWith(`http`))return;let i=e.match(mt),a=i?Number.parseInt(i[1],10):void 0,o=e.match(ht),s=o?Number.parseInt(o[1],10):void 0,c=gt.test(e)&&!_t.test(e),l=`${r}:${a??`auto`}:${s??75}`;(!t.has(l)||c)&&t.set(l,{src:r,width:a,quality:s,preload:c})}const Pt=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,Ft=/from\s+['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s+['"]([^'"]+)['"]/g,It=/import(?:\s+(?:\w+|\{[^}]*\}|\*\s+as\s+\w+)(?:\s*,\s*(?:\w+|\{[^}]*\}|\*\s+as\s+\w+))*\s+from\s+)?['"]([^'"]+)['"]/g,Lt=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,Rt=/import\s+(?:(\w+)|\{([^}]+)\})\s+from\s+['"]([^'"]+)['"];?\s*$/gm,zt=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,Bt=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,Vt=/[/\\]components[/\\](\w+)(?:\.tsx?|\.jsx?)?$/,Ht=/^(?:robots|sitemap|feed)\.(?:tsx?|jsx?)$/,Ut=/^node:/,Wt=new Set([`fs`,`path`,`os`,`crypto`,`util`,`stream`,`events`,`process`,`buffer`,`url`,`querystring`,`zlib`,`http`,`https`,`net`,`tls`,`child_process`,`cluster`,`worker_threads`]),Gt=`[hash]_[local]`,Kt=E.dirname(O(import.meta.url)),qt=E.dirname(Kt);function Jt(e){return e.startsWith(qt)}let Yt=null;async function Xt(){return Yt||=(await import(`lightningcss`)).transform,Yt}var Zt=class{serverComponents=new Map;serverActions=new Map;options;projectRoot;buildCache=new Map;htmlOnlyImports=new Set;fileImporters=new Map;directiveResultCache=new Map;getComponentCount(){return this.serverComponents.size+this.serverActions.size}hasComponent(e){return this.serverComponents.has(e)||this.serverActions.has(e)}removeComponent(e){this.serverComponents.delete(e),this.serverActions.delete(e),this.directiveResultCache.delete(e)}getImportGraph(){let e=new Map;for(let[t,n]of this.fileImporters)e.set(t,new Set(n));return e}getHtmlOnlyImports(){return new Set(this.htmlOnlyImports)}hashString(e,t=8){return Re(e,t)}async writeComponentCssAsset(e,t){if(t.length===0)return[];let n=E.join(this.options.outDir,`assets`,`server`);await w.promises.mkdir(n,{recursive:!0});let r=`${t.join(`
3
+ `)}\n`,i=`${this.hashString(e+r,12)}.css`,a=E.join(n,i);return await w.promises.writeFile(a,r,`utf-8`),[`/assets/server/${i}`]}getComponentIdFromRouteManifestPath(e){return this.getComponentId(E.join(this.projectRoot,`src`,`app`,e))}getLegacyComponentReferenceId(e){return this.getReadableComponentId(this.getProjectRelativePath(e))}async writeRouteCssEntries(e){let t=E.join(this.options.outDir,this.options.rscDir,`routes.json`);if(!w.existsSync(t))return;let n=await w.promises.readFile(t,`utf-8`),r=JSON.parse(n),i=t=>{if(t)for(let n of t){if(!n.filePath)continue;let t=this.getComponentIdFromRouteManifestPath(n.filePath);n.componentId=t;let r=e.components[t]?.css??[];r.length?n.css=r:delete n.css}};if(i(r.routes),i(r.layouts),i(r.loading),i(r.errors),i(r.notFound),r.apiRoutes)for(let e of r.apiRoutes)e.filePath&&(e.componentId=this.getComponentIdFromRouteManifestPath(e.filePath));await w.promises.writeFile(t,JSON.stringify(r,null,2),`utf-8`)}constructor(e,t={}){this.projectRoot=e;let n=t.rscDir||`server`;this.options={outDir:t.outDir||E.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath||E.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath||E.join(n,`config.json`),minify:t.minify??D.env.NODE_ENV===`production`,alias:t.alias||{},define:t.define,csp:t.csp,cacheControl:t.cacheControl},this.parseHtmlImports()}parseHtmlImports(){let e=E.join(this.projectRoot,`index.html`);if(w.existsSync(e))try{let t=w.readFileSync(e,`utf-8`);for(let e of t.matchAll(Pt)){let t=e[1]||e[2];if(t.startsWith(`/src/`)){let e=E.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)}getDirectivesCached(e,t){if(!t){let t=this.directiveResultCache.get(e);if(t)return t}try{let n=W(t??w.readFileSync(e,`utf-8`)),r={hasUseClient:n.hasUseClient,hasUseServer:n.hasUseServer,error:!1};return this.directiveResultCache.set(e,r),r}catch{return{hasUseClient:!1,hasUseServer:!1,error:!0}}}isServerComponent(e,t){if(e.includes(`node_modules`)||this.isHtmlOnlyImport(e))return!1;let n=this.getDirectivesCached(e,t);return n.error?!1:!n.hasUseClient&&!n.hasUseServer}isClientComponent(e,t){return this.getDirectivesCached(e,t).hasUseClient}buildImportGraph(e){this.fileImporters.clear();let t=e=>{if(!w.existsSync(e))return;let n=w.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=E.join(e,r.name);if(r.isDirectory()){if(r.name===`node_modules`)continue;t(n)}else if(r.isFile()&&g.test(r.name))try{let e=w.readFileSync(n,`utf-8`),t;for(Ft.lastIndex=0,t=Ft.exec(e);t!==null;){let r=t[1]||t[2]||t[3],i=null;if(r.startsWith(`./`)||r.startsWith(`../`)){let e=E.dirname(n);i=E.resolve(e,r)}else if(r.startsWith(`@/`)){let e=r.slice(2);i=E.join(this.projectRoot,`src`,e)}if(i){let e=[``,`.ts`,`.tsx`,`.js`,`.jsx`],t=null;for(let n of e){let e=i+n;try{if(w.statSync(e).isFile()){t=e;break}}catch{}}t&&(this.fileImporters.has(t)||this.fileImporters.set(t,new Set),this.fileImporters.get(t).add(n))}t=Ft.exec(e)}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error building import graph:`,n,e)}}};t(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,t){let n=t??w.readFileSync(e,`utf-8`);if(this.isServerAction(n)){let t=this.extractDependencies(n),r=this.hasNodeImports(n);this.serverActions.set(e,{filePath:e,originalCode:n,dependencies:t,hasNodeImports:r});return}if(!this.isServerComponent(e,n))return;let r=this.extractDependencies(n),i=this.hasNodeImports(n);this.serverComponents.set(e,{filePath:e,originalCode:n,dependencies:r,hasNodeImports:i})}isServerAction(e){return W(e).hasUseServer}extractDependencies(e){let t=[],n;for(It.lastIndex=0;n=It.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 Wt.has(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=E.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=E.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(Lt)){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(Bt);if(n){let i=n[1],a=[E.resolve(this.projectRoot,`src`,`components`,`${i}.tsx`),E.resolve(this.projectRoot,`src`,`components`,`${i}.ts`),E.resolve(this.projectRoot,`src`,`components`,`${i}.jsx`),E.resolve(this.projectRoot,`src`,`components`,`${i}.js`)],o=!1;for(let e of a)if(w.existsSync(e)&&this.isClientComponent(e)){o=!0;break}if(!o)continue;let s=`// Component reference: ${i}
4
4
  const ${r} = (props) => {
5
5
  let Component = globalThis['~clientComponents']?.['components/${i}']?.component
6
6
  || globalThis['components/${i}'];
@@ -18,7 +18,7 @@ const ${r} = (props) => {
18
18
  }
19
19
 
20
20
  return Component(props);
21
- }`;t.push({original:e,replacement:s})}}continue}let o=this.options.alias||{};for(let[e,t]of Object.entries(o))if(i.startsWith(`${e}/`)||i===e){let n=i.slice(e.length);a=E.join(t,n);break}if(a){let n=a.match(Lt);if(n){let i=n[1],o=E.isAbsolute(a)?a:E.resolve(this.projectRoot,a),s=[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`],c=!1,l=o;for(let e of s)if(w.existsSync(e)){l=e,this.isClientComponent(e)&&(c=!0);break}if(!c)continue;let u=this.getLegacyComponentReferenceId(l),d=`// Component reference: ${i}
21
+ }`;t.push({original:e,replacement:s})}}continue}let o=this.options.alias||{};for(let[e,t]of Object.entries(o))if(i.startsWith(`${e}/`)||i===e){let n=i.slice(e.length);a=E.join(t,n);break}if(a){let n=a.match(Vt);if(n){let i=n[1],o=E.isAbsolute(a)?a:E.resolve(this.projectRoot,a),s=[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`],c=!1,l=o;for(let e of s)if(w.existsSync(e)){l=e,this.isClientComponent(e)&&(c=!0);break}if(!c)continue;let u=this.getLegacyComponentReferenceId(l),d=`// Component reference: ${i}
22
22
  const ${r} = (props) => {
23
23
  let Component = globalThis['~clientComponents']?.['${u}']?.component
24
24
  || globalThis['${u}'];
@@ -36,7 +36,7 @@ const ${r} = (props) => {
36
36
  }
37
37
 
38
38
  return Component(props);
39
- }`;t.push({original:e,replacement:d})}}}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,r,i=!1,a){let o=E.dirname(r),s=Ft.test(E.basename(r)),c=this,l=new Map,u=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){if(t.endsWith(`.module.css`))return null;let e=E.resolve(o,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(w.existsSync(n)&&w.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=E.join(e,`index${t}`);if(w.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`)||Wt(n)||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;if(r=re(t,c.options.alias||{},c.projectRoot),!r&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?o:E.dirname(n);r=E.resolve(i,t)}if(r)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(w.existsSync(t)&&w.statSync(t).isFile()){if(c.isClientComponent(t)){let e=E.relative(c.projectRoot,t),n=(e.startsWith(`..`)?t:e).replace(x,`/`);return l.set(t,n),{id:`\0client-ref:${t}`}}try{let e=w.readFileSync(t,`utf-8`);if(K(e)){let n=c.getComponentId(t),r=Y(e);return u.set(t,{actionId:n,hasDefaultExport:r}),{id:`\0server-action:${t}`}}}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=E.relative(c.projectRoot,t),r=(l.get(t)||(n.startsWith(`..`)?t:n)).replace(x,`/`);return{code:`
39
+ }`;t.push({original:e,replacement:d})}}}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,r,i=!1,a){let o=E.dirname(r),s=zt.test(E.basename(r)),c=this,l=new Map,u=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){if(t.endsWith(`.module.css`))return null;let e=E.resolve(o,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(w.existsSync(n)&&w.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=E.join(e,`index${t}`);if(w.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`)||Jt(n)||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;if(r=re(t,c.options.alias||{},c.projectRoot),!r&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?o:E.dirname(n);r=E.resolve(i,t)}if(r)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(w.existsSync(t)&&w.statSync(t).isFile()){if(c.isClientComponent(t)){let e=E.relative(c.projectRoot,t),n=(e.startsWith(`..`)?t:e).replace(x,`/`);return l.set(t,n),{id:`\0client-ref:${t}`}}try{let e=w.readFileSync(t,`utf-8`);if(G(e)){let n=c.getComponentId(t),r=J(e);return u.set(t,{actionId:n,hasDefaultExport:r}),{id:`\0server-action:${t}`}}}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=E.relative(c.projectRoot,t),r=(l.get(t)||(n.startsWith(`..`)?t:n)).replace(x,`/`);return{code:`
40
40
  function registerClientReference(clientReference, id, exportName) {
41
41
  const key = id + '#' + exportName;
42
42
  const clientProxy = {};
@@ -56,7 +56,7 @@ function registerClientReference(clientReference, id, exportName) {
56
56
  }
57
57
 
58
58
  export default registerClientReference(null, ${JSON.stringify(r)}, "default");
59
- `,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=u.get(t)?.actionId??c.getComponentId(t),r=E.join(c.options.outDir,c.options.rscDir,`${n}.js`),i=k(E.resolve(c.projectRoot,r)).href;return{code:u.get(t)?.hasDefaultExport??!1?`export * from ${JSON.stringify(i)};\nexport { default } from ${JSON.stringify(i)};`:`export * from ${JSON.stringify(i)};`,moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!i)return null;if(e.startsWith(`file://`)){let t=e.replace(_,``);return w.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null;n=re(e,c.options.alias||{},c.projectRoot);let r=t?.startsWith(`\0`)?o:t?E.dirname(t):o;if(!n&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=E.resolve(r,e)),!n||r.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(w.existsSync(t)&&w.statSync(t).isFile()){if(c.isClientComponent(t))return null;let e=E.join(c.projectRoot,`src`);if(!t.startsWith(e))return null;let n=c.getComponentId(t),r=E.join(c.options.outDir,c.options.rscDir,`${n}.js`);if(w.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:w.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=E.join(r,t),a=E.isAbsolute(i)?i:E.resolve(c.projectRoot,i);for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=a+e;if(w.existsSync(t)&&w.statSync(t).isFile())return t}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let t=E.join(a,`index${e}`);if(w.existsSync(t))return t}return a}return null}},{name:`resolve-rari-proxy`,resolveId:e=>{if(s&&e===`rari`){let e=E.join(Ht,`proxy/RariResponse.mjs`);if(w.existsSync(e))return e;let t=E.join(Ut,`src/proxy/RariResponse.ts`);if(w.existsSync(t))return t}return null}},{name:`css-modules`,resolveId:(e,t)=>{if(e.endsWith(`.module.css`)){let n=!t?.startsWith(`\0`)&&t?E.dirname(t):o,r=E.resolve(n,e);if(w.existsSync(r))return{id:`\0css-module:${r}`}}return null},load:async e=>{if(!e.startsWith(`\0css-module:`))return null;let t=e.slice(12);try{let{transform:e}=await import(`lightningcss`),n=w.readFileSync(t),r=e({filename:E.relative(this.projectRoot,t),code:n,cssModules:{pattern:Vt}});a&&a.push(new TextDecoder().decode(r.code));let i={};if(r.exports)for(let[e,t]of Object.entries(r.exports))i[e]=t.name;return{code:`export default ${JSON.stringify(i)}`,moduleType:`js`}}catch(t){throw Error(`[rari] Failed to process CSS module ${e}: ${t instanceof Error?t.message:String(t)}`)}}},{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 w.promises.readFile(e,`utf-8`),n=this.transformClientImports(t,e),r=this.isPageComponent(e),i=r?this.transformComponentImportsToGlobal(n):n,a=E.extname(e),o;o=a===`.tsx`?`tsx`:a===`.ts`?`ts`:a===`.jsx`?`jsx`:`js`;let s=`\0virtual:${e}`,c=await j({input:s,platform:`node`,write:!1,external:[zt,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],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(D.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 u=l.code;return u=`// Built: ${new Date().toISOString()}\n${u}`,u}async buildServerComponents(){let e=E.join(this.options.outDir,this.options.rscDir);await w.promises.mkdir(e,{recursive:!0});let t={components:{},buildTime:new Date().toISOString()};for(let[e,n]of this.serverComponents){if(this.isPageComponent(e))continue;let r=E.relative(this.projectRoot,e),i=this.getComponentId(e),a=E.join(this.options.rscDir,`${i}.js`),o=E.join(this.options.outDir,a),s=E.dirname(o);await w.promises.mkdir(s,{recursive:!0});let c=await this.buildSingleComponent(e,o),l=await this.writeComponentCssAsset(i,c.css),u=k(E.resolve(this.projectRoot,o)).href;t.components[i]={id:i,filePath:e,relativePath:r,bundlePath:a,moduleSpecifier:u,dependencies:n.dependencies,hasNodeImports:n.hasNodeImports,css:l}}for(let[e,n]of this.serverComponents){if(!this.isPageComponent(e))continue;let r=E.relative(this.projectRoot,e),i=this.getComponentId(e),a=E.join(this.options.rscDir,`${i}.js`),o=E.join(this.options.outDir,a),s=E.dirname(o);await w.promises.mkdir(s,{recursive:!0});let c=await this.buildSingleComponent(e,o),l=await this.writeComponentCssAsset(i,c.css),u=k(E.resolve(this.projectRoot,o)).href;t.components[i]={id:i,filePath:e,relativePath:r,bundlePath:a,moduleSpecifier:u,dependencies:n.dependencies,hasNodeImports:n.hasNodeImports,css:l}}for(let[e,n]of this.serverActions){let r=E.relative(this.projectRoot,e),i=this.getComponentId(e),a=E.join(this.options.rscDir,`${i}.js`),o=E.join(this.options.outDir,a),s=E.dirname(o);await w.promises.mkdir(s,{recursive:!0});let c=await this.buildSingleComponent(e,o),l=await this.writeComponentCssAsset(i,c.css),u=k(E.resolve(this.projectRoot,o)).href;t.components[i]={id:i,filePath:e,relativePath:r,bundlePath:a,moduleSpecifier:u,dependencies:n.dependencies,hasNodeImports:n.hasNodeImports,css:l}}let n=E.join(this.options.outDir,this.options.manifestPath);await w.promises.writeFile(n,JSON.stringify(t,null,2),`utf-8`),await this.writeRouteCssEntries(t);let r={};this.options.csp&&(r.csp=this.options.csp),this.options.cacheControl&&(r.cacheControl=this.options.cacheControl);let i=E.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(r).length===0)try{await w.promises.unlink(i)}catch(e){e.code!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await w.promises.writeFile(i,JSON.stringify(r,null,2),`utf-8`);return t}async buildSingleComponent(e,t){let n=await w.promises.readFile(e,`utf-8`),r=this.transformClientImports(n,e),i=this.isPageComponent(e),a=i?this.transformComponentImportsToGlobal(r):r,o=E.extname(e),s;s=o===`.tsx`?`tsx`:o===`.ts`?`ts`:o===`.jsx`?`jsx`:`js`;let c=`\0virtual:${e}`,l=[],u=await j({input:c,platform:`node`,write:!1,external:[zt,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${s}`]:s},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(D.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(c,a,s,e,i,l)});if(!u.output||u.output.length===0)throw Error(`No output generated from Rolldown`);let d=u.output.find(e=>e.type===`chunk`&&e.isEntry);if(!d||d.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let f=d.code;f=`// Built: ${new Date().toISOString()}\n${f}`,await w.promises.writeFile(t,f,`utf-8`);let p=await w.promises.open(t,`r+`);return await p.sync(),await p.close(),{code:f,css:l}}transformClientImports(e,t){let n=e,r,i=[],a=!1,o=[`rari/image`];for(Pt.lastIndex=0;r=Pt.exec(e),r!==null;){let[e,n,s,c]=r,l=!1,u=c;if(o.includes(c))l=!0;else{let e=this.resolveImportPath(c,t);this.isClientComponent(e)&&(l=!0,u=E.relative(this.projectRoot,e).replace(x,`/`))}if(l){a=!0;let t=``;n?t=`const ${n} = registerClientReference(
59
+ `,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=u.get(t)?.actionId??c.getComponentId(t),r=E.join(c.options.outDir,c.options.rscDir,`${n}.js`),i=k(E.resolve(c.projectRoot,r)).href;return{code:u.get(t)?.hasDefaultExport??!1?`export * from ${JSON.stringify(i)};\nexport { default } from ${JSON.stringify(i)};`:`export * from ${JSON.stringify(i)};`,moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!i)return null;if(e.startsWith(`file://`)){let t=e.replace(_,``);return w.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null;n=re(e,c.options.alias||{},c.projectRoot);let r=t?.startsWith(`\0`)?o:t?E.dirname(t):o;if(!n&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=E.resolve(r,e)),!n||r.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(w.existsSync(t)&&w.statSync(t).isFile()){if(c.isClientComponent(t))return null;let e=E.join(c.projectRoot,`src`);if(!t.startsWith(e))return null;let n=c.getComponentId(t),r=E.join(c.options.outDir,c.options.rscDir,`${n}.js`);if(w.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:w.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=E.join(r,t),a=E.isAbsolute(i)?i:E.resolve(c.projectRoot,i);for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=a+e;if(w.existsSync(t)&&w.statSync(t).isFile())return t}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let t=E.join(a,`index${e}`);if(w.existsSync(t))return t}return a}return null}},{name:`resolve-rari-proxy`,resolveId:e=>{if(s&&e===`rari`){let e=E.join(Kt,`proxy/RariResponse.mjs`);if(w.existsSync(e))return e;let t=E.join(qt,`src/proxy/RariResponse.ts`);if(w.existsSync(t))return t}return null}},{name:`css-modules`,resolveId:(e,t)=>{if(e.endsWith(`.module.css`)){let n=!t?.startsWith(`\0`)&&t?E.dirname(t):o,r=E.resolve(n,e);if(w.existsSync(r))return{id:`\0css-module:${r}`}}return null},load:async e=>{if(!e.startsWith(`\0css-module:`))return null;let t=e.slice(12);try{let e=await Xt(),n=w.readFileSync(t),r=e({filename:E.relative(this.projectRoot,t),code:n,cssModules:{pattern:Gt}});a&&a.push(new TextDecoder().decode(r.code));let i={};if(r.exports)for(let[e,t]of Object.entries(r.exports))i[e]=t.name;return{code:`export default ${JSON.stringify(i)}`,moduleType:`js`}}catch(t){throw Error(`[rari] Failed to process CSS module ${e}: ${t instanceof Error?t.message:String(t)}`)}}},{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 w.promises.readFile(e,`utf-8`),n=this.transformClientImports(t,e),r=this.isPageComponent(e),i=r?this.transformComponentImportsToGlobal(n):n,a=E.extname(e),o;o=a===`.tsx`?`tsx`:a===`.ts`?`ts`:a===`.jsx`?`jsx`:`js`;let s=`\0virtual:${e}`,c=await j({input:s,platform:`node`,write:!1,external:[Ut,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],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(D.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 u=l.code;return u=`// Built: ${new Date().toISOString()}\n${u}`,u}async buildComponentBatch(e,t,n){let r=0,i=0,a=[];if(await new Promise(o=>{let s=()=>{for(;r<n&&i<e.length;){let[n,c]=e[i++],l=E.relative(this.projectRoot,n),u=this.getComponentId(n),d=E.join(this.options.rscDir,`${u}.js`),f=E.join(this.options.outDir,d);r++,(async()=>{try{let e=E.dirname(f);await w.promises.mkdir(e,{recursive:!0});let r=await this.buildSingleComponent(n,f),i=await this.writeComponentCssAsset(u,r.css),a=k(E.resolve(this.projectRoot,f)).href;t.components[u]={id:u,filePath:n,relativePath:l,bundlePath:d,moduleSpecifier:a,dependencies:c.dependencies,hasNodeImports:c.hasNodeImports,css:i}}catch(e){a.push(e instanceof Error?e:Error(String(e)))}finally{r--,i>=e.length&&r===0?o():s()}})()}e.length===0&&o()};s()}),a.length>0)throw a[0]}async buildServerComponents(){let e=E.join(this.options.outDir,this.options.rscDir);await w.promises.mkdir(e,{recursive:!0});let t={components:{},buildTime:new Date().toISOString()},n=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),r=[...this.serverComponents.entries()].filter(([e])=>!this.isPageComponent(e)),i=[...this.serverComponents.entries()].filter(([e])=>this.isPageComponent(e)),a=[...this.serverActions.entries()];await Promise.all([this.buildComponentBatch(r,t,n),this.buildComponentBatch(a,t,n)]),await this.buildComponentBatch(i,t,n);let o=E.join(this.options.outDir,this.options.manifestPath);await w.promises.writeFile(o,JSON.stringify(t,null,2),`utf-8`),await this.writeRouteCssEntries(t);let s={};this.options.csp&&(s.csp=this.options.csp),this.options.cacheControl&&(s.cacheControl=this.options.cacheControl);let c=E.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(s).length===0)try{await w.promises.unlink(c)}catch(e){e.code!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await w.promises.writeFile(c,JSON.stringify(s,null,2),`utf-8`);return t}async buildSSRClientComponents(){let e=E.join(this.options.outDir,`ssr`);await w.promises.mkdir(e,{recursive:!0});let t=[],n=E.join(this.projectRoot,`src`),r=e=>{if(!w.existsSync(e))return;let n=w.readdirSync(e,{withFileTypes:!0});for(let i of n){let n=E.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;r(n)}else if(i.isFile()&&g.test(i.name))try{let e=w.readFileSync(n,`utf-8`);K(e)&&t.push({filePath:n,code:e})}catch{}}};if(r(n),t.length===0){let t=E.join(e,`manifest.json`);await w.promises.writeFile(t,`{}`,`utf-8`);return}let i={},a=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),o=0,s=0;await new Promise(e=>{let n=()=>{for(;o<a&&s<t.length;){let{filePath:r,code:a}=t[s++],c=E.relative(this.projectRoot,r).replace(x,`/`),l=`ssr/${this.getComponentId(r)}.js`,u=E.join(this.options.outDir,l);o++,(async()=>{try{let e=E.dirname(u);await w.promises.mkdir(e,{recursive:!0}),await this.buildSSRSingleClient(r,u),i[c]={id:c,filePath:r,bundlePath:l,exports:this.extractExportNames(a)}}catch(e){console.warn(`[rari] SSR build failed for ${c}:`,e instanceof Error?e.message:e)}finally{o--,s>=t.length&&o===0?e():n()}})()}t.length===0&&e()};n()});let c=E.join(e,`manifest.json`);await w.promises.writeFile(c,JSON.stringify(i,null,2),`utf-8`)}extractExportNames(e){let t=[];/export\s+default\b/.test(e)&&t.push(`default`);for(let n of e.matchAll(/export\s+(?:function|const|let|var|class)\s+(\w+)/g))t.push(n[1]);return t.length>0?t:[`default`]}async buildSSRSingleClient(e,t){let n=(await w.promises.readFile(e,`utf-8`)).replace(/^['"]use client['"];?\s*/m,``),r=E.extname(e),i;i=r===`.tsx`?`tsx`:r===`.ts`?`ts`:r===`.jsx`?`jsx`:`js`;let a=`\0ssr-virtual:${e}`,o=this.projectRoot,s=(await j({input:a,platform:`node`,write:!1,external:[Ut,`react`,`react-dom`,/^react\//,/^rari/],output:{format:`esm`,minify:!1},moduleTypes:{[`.${i}`]:i},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react-jsx`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(D.env.NODE_ENV||`production`)}},plugins:[{name:`ssr-client-virtual`,resolveId(e){return e===a?e:null},load(e){return e===a?{code:n,moduleType:i}:null}},{name:`ssr-client-resolve`,resolveId(t,n){if(t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`@/`)){let r=t;return t.startsWith(`@/`)?r=E.join(o,`src`,t.slice(2)):n===a?r=E.resolve(E.dirname(e),t):n&&(r=E.resolve(E.dirname(n.replace(`\0ssr-virtual:`,``)),t)),X(r,[`.ts`,`.tsx`,`.js`,`.jsx`])||Z(r,[`.ts`,`.tsx`,`.js`,`.jsx`])||null}return null}}]})).output[0],c=typeof s==`object`&&`code`in s?s.code:``;return await w.promises.writeFile(t,c,`utf-8`),{code:c}}async buildSingleComponent(e,t){let n=await w.promises.readFile(e,`utf-8`),r=this.transformClientImports(n,e),i=this.isPageComponent(e),a=i?this.transformComponentImportsToGlobal(r):r,o=E.extname(e),s;s=o===`.tsx`?`tsx`:o===`.ts`?`ts`:o===`.jsx`?`jsx`:`js`;let c=`\0virtual:${e}`,l=[],u=await j({input:c,platform:`node`,write:!1,external:[Ut,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${s}`]:s},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(D.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(c,a,s,e,i,l)});if(!u.output||u.output.length===0)throw Error(`No output generated from Rolldown`);let d=u.output.find(e=>e.type===`chunk`&&e.isEntry);if(!d||d.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let f=d.code;f=`// Built: ${new Date().toISOString()}\n${f}`,await w.promises.writeFile(t,f,`utf-8`);let p=await w.promises.open(t,`r+`);return await p.sync(),await p.close(),{code:f,css:l}}transformClientImports(e,t){let n=e,r,i=[],a=!1,o=[`rari/image`];for(Rt.lastIndex=0;r=Rt.exec(e),r!==null;){let[e,n,s,c]=r,l=!1,u=c;if(o.includes(c))l=!0;else{let e=this.resolveImportPath(c,t);this.isClientComponent(e)&&(l=!0,u=E.relative(this.projectRoot,e).replace(x,`/`))}if(l){a=!0;let t=``;n?t=`const ${n} = registerClientReference(
60
60
  null,
61
61
  ${JSON.stringify(u)},
62
62
  "default"
@@ -97,12 +97,12 @@ function registerClientReference(clientReference, id, exportName) {
97
97
  return clientProxy;
98
98
  }
99
99
 
100
- `+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=E.join(i,r);break}E.isAbsolute(n)||(n=E.resolve(E.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];return Qe(n,i)||$e(n,i)||`${n}.tsx`}getProjectRelativePath(e){return Re(e,this.projectRoot)}getReadableComponentId(e){return ze(e)}getComponentId(e){return I(e,this.projectRoot)}async rebuildComponent(e){let t=this.getComponentId(e),n=await w.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=E.join(this.options.rscDir,`${t}.js`),o=E.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await w.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.dependencies)===JSON.stringify(r))return await w.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a,s.css),{componentId:t,bundlePath:E.join(this.options.outDir,a),success:!0};let l=E.dirname(o);await w.promises.mkdir(l,{recursive:!0});let u=await this.buildSingleComponent(e,o),d=await this.writeComponentCssAsset(t,u.css);return this.buildCache.set(e,{code:u.code,css:d,timestamp:Date.now(),dependencies:r}),await this.updateManifestForComponent(t,e,a,d),{componentId:t,bundlePath:E.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,t,n,r=[]){let i=E.join(this.options.outDir,this.options.manifestPath),a;if(this.manifestCache)a=this.manifestCache;else if(w.existsSync(i)){let e=await w.promises.readFile(i,`utf-8`);a=JSON.parse(e),this.manifestCache=a}else a={components:{},buildTime:new Date().toISOString()},this.manifestCache=a;let o=this.serverComponents.get(t)||this.serverActions.get(t),s=E.join(this.options.outDir,n),c=k(E.resolve(this.projectRoot,s)).href;if(o)a.components[e]={id:e,filePath:t,relativePath:E.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:c,dependencies:o.dependencies,hasNodeImports:o.hasNodeImports,css:r};else{let i=await w.promises.readFile(t,`utf-8`);a.components[e]={id:e,filePath:t,relativePath:E.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:c,dependencies:this.extractDependencies(i),hasNodeImports:this.hasNodeImports(i),css:r}}a.buildTime=new Date().toISOString(),await w.promises.writeFile(i,JSON.stringify(a,null,2),`utf-8`),await this.writeRouteCssEntries(a),this.manifestCache=a}clearCache(){this.buildCache.clear(),this.manifestCache=null}invalidateBuildCacheFor(e){this.buildCache.delete(e)}async getTransformedComponentCode(e){return await this.buildComponentCodeOnly(e)}};function Gt(e){return Y(e)||h.test(e)||v.test(e)||b.test(e)}function Kt(e,t,n=!0){n&&t.buildImportGraph(e);let r=w.readdirSync(e,{withFileTypes:!0});for(let n of r){let r=E.join(e,n.name);if(n.isDirectory())Kt(r,t,!1);else if(n.isFile()&&g.test(n.name)){if(Rt.test(n.name)||n.name.endsWith(`.d.ts`))continue;try{let e=w.readFileSync(r,`utf-8`);if(K(e)){t.addServerComponent(r,e);continue}if(t.isOnlyImportedByClientComponents(r))continue;if(t.isServerComponent(r,e)){if(!Gt(e))continue;t.addServerComponent(r,e)}}catch(e){console.warn(`[server-build] Error checking ${r}:`,e instanceof Error?e.message:e)}}}}function qt(e={}){let t=null,n,r=!1,i={};return{name:`rari-server-build`,configResolved(a){n=a.root,r=a.command===`serve`;let o={};if(a.resolve?.alias){let e=a.resolve.alias;Array.isArray(e)?e.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&(o[e.find]=e.replacement)}):typeof e==`object`&&Object.entries(e).forEach(([e,t])=>{typeof t==`string`&&(o[e]=t)})}i=o,t=new $(n,{...e,alias:o})},buildStart(){if(!t)return;let e=D.env.NODE_ENV===`production`,r=[E.join(n,`dist`,`cache`,`og`),E.join(n,`dist`,`cache`,`images`)];e&&r.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of r)try{w.existsSync(e)&&w.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let i=E.join(n,`src`);w.existsSync(i)&&Kt(i,t)},async closeBundle(){if(t){await t.buildServerComponents();try{let{generateRobotsFile:e}=await import(`./robots-generator-l2O5neuR.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`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-BGu4N9qc.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`],aliases:i})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}}},async handleHotUpdate({file:e}){if(!t||!r)return;let i=E.relative(n,e).replace(x,`/`);if(!(!i.startsWith(`src/`)||!g.test(i)))try{if(q(await w.promises.readFile(e,`utf-8`)))return;await t.buildServerComponents()}catch(e){console.error(`[rari] Build: Error rebuilding ${i}:`,e)}}}}const Jt="[rari] Runtime dist not built. Run `pnpm build` in the rari package first.",Yt=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Xt=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Zt=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Qt=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,$t=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,en=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,tn=/import\s+["']\.\.?\/([^"']+)["'];?/g,nn=/import\s*(?:\(\s*)?["']([^"']+)["']\)?/g,rn=/export\s*\{([^}]+)\}/g,an=/\s+as\s+/,on=/export\s+default\s+(?:function|class)\s+\w+/,sn=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,cn=/export\s+default\s+([^;]+)/,ln=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,un=/^['"]use client['"];?\s*$/gm,dn=/import\s+["']([^"']+)["']/g,fn=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,pn=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,mn=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,hn=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,gn=/import\s+["']([^"']+)["']/g,_n=/from(\s*)(['"])(?:\.\/vendor\/react-flight-client\/index|rari\/runtime\/vendor\/react-flight-client\/index)\.mjs\2/g,vn=/\bJSX\b/,yn=/\{([^}]*)\}/,bn=/^['"]use client['"];?\s*\n/,xn={remotePatterns:[],localPatterns:[],deviceSizes:p,imageSizes:f,formats:u,qualityAllowlist:d,minimumCacheTTL:60,maxCacheSize:l};async function Sn(e){let t=import.meta.url,n=O(t),r=E.dirname(n),i=[E.join(r,`runtime`,e),E.join(r,`../runtime`,e)];for(let e of i)try{let t=await w.promises.readFile(e,`utf-8`);return e.endsWith(`.ts`)&&(t=t.replace(Yt,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Xt,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Zt,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Qt,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace($t,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(en,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(tn,(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(`, `)}`)}const Cn=E.dirname(O(import.meta.url)),wn=E.dirname(Cn);function Tn(e){let t=[E.join(Cn,`runtime`,e),E.join(Cn,`../runtime`,e)];for(let e of t)if(w.existsSync(e))return e;return null}function En(e){return e.startsWith(wn)}async function Dn(){return Sn(`rsc-client-runtime.mjs`)}async function On(e,t){return(await Sn(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function kn(){return Sn(`react-server-dom-shim.mjs`)}async function An(e,t){let n=await vt(E.join(e,`src`)),r={...xn,...t.images,preoptimizeManifest:n.images},i=E.join(e,`dist`),a=E.join(i,`server`);w.existsSync(a)||w.mkdirSync(a,{recursive:!0});let o=E.join(a,`image.json`);w.writeFileSync(o,JSON.stringify(r,null,2))}function jn(e,t=[]){let n=new Set;function r(e){if(!w.existsSync(e))return;let t=w.readdirSync(e,{withFileTypes:!0});for(let i of t){let t=E.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;r(t)}else if(i.isFile()&&g.test(i.name))try{q(w.readFileSync(t,`utf8`))&&n.add(t)}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error during file scan:`,t,e)}}}r(e);for(let e of t)w.existsSync(e)&&r(e);return n}function Mn(e){return e}function Nn(e={}){let t=new Map,n=new Set,r=new Map,i=null,a=null,o={};function s(e){if(r.has(e))return r.get(e);let t={hasUseServer:!1,hasUseClient:!1},n=e.replace(x,`/`);if(!g.test(n)||!n.includes(`/src/`))return r.set(e,t),t;try{let n=G(w.readFileSync(e,`utf-8`));t.hasUseServer=n.hasUseServer,t.hasUseClient=n.hasUseClient,r.set(e,t)}catch{r.set(e,t)}return t}let c=null,l=null;function u(){let t=e.projectRoot||D.cwd(),n=E.join(t,`index.html`);try{let e=w.statSync(n).mtimeMs;if(c!==null&&e===l)return c;l=e}catch{return c===null&&(c=new Set),c}c=new Set;try{let e=w.readFileSync(n,`utf-8`);for(let n of e.matchAll(nn)){let e=n[1];e.startsWith(`/src/`)&&c.add(E.join(t,e.slice(1)))}}catch{}return c}function d(e){if(e.includes(`node_modules`)||En(e)||u().has(e))return!1;let t;try{t=w.realpathSync(e)}catch{return!1}try{let e=G(w.readFileSync(t,`utf-8`));return e.hasUseServer?!1:!e.hasUseClient}catch{return!1}}function f(e){try{let t=[],n=e.matchAll(rn);for(let e of n){let n=e[1].split(`,`);for(let e of n){let n=e.trim().split(an).at(-1)?.trim();n&&t.push(n)}}(on.test(e)||Y(e))&&t.push(`default`);let r=e.matchAll(ln);for(let e of r)e[1]&&t.push(e[1]);return[...new Set(t)]}catch{return[]}}function p(e,t){if(!K(e))return e;let n=f(e);if(n.length===0)return e;let r=JSON.stringify(t),i=e;i+=`
100
+ `+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=E.join(i,r);break}E.isAbsolute(n)||(n=E.resolve(E.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];return X(n,i)||Z(n,i)||`${n}.tsx`}getProjectRelativePath(e){return ze(e,this.projectRoot)}getReadableComponentId(e){return Be(e)}getComponentId(e){return F(e,this.projectRoot)}async rebuildComponent(e){let t=this.getComponentId(e),n=await w.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.delete(e)):(this.serverComponents.set(e,i),this.serverActions.delete(e));let a=E.join(this.options.rscDir,`${t}.js`),o=E.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await w.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.dependencies)===JSON.stringify(r))return await w.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a,s.css),{componentId:t,bundlePath:E.join(this.options.outDir,a),success:!0};let l=E.dirname(o);await w.promises.mkdir(l,{recursive:!0});let u=await this.buildSingleComponent(e,o),d=await this.writeComponentCssAsset(t,u.css);return this.buildCache.set(e,{code:u.code,css:d,timestamp:Date.now(),dependencies:r}),await this.updateManifestForComponent(t,e,a,d),{componentId:t,bundlePath:E.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,t,n,r=[]){let i=E.join(this.options.outDir,this.options.manifestPath),a;if(this.manifestCache)a=this.manifestCache;else if(w.existsSync(i)){let e=await w.promises.readFile(i,`utf-8`);a=JSON.parse(e),this.manifestCache=a}else a={components:{},buildTime:new Date().toISOString()},this.manifestCache=a;let o=this.serverComponents.get(t)||this.serverActions.get(t),s=E.join(this.options.outDir,n),c=k(E.resolve(this.projectRoot,s)).href;if(o)a.components[e]={id:e,filePath:t,relativePath:E.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:c,dependencies:o.dependencies,hasNodeImports:o.hasNodeImports,css:r};else{let i=await w.promises.readFile(t,`utf-8`);a.components[e]={id:e,filePath:t,relativePath:E.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:c,dependencies:this.extractDependencies(i),hasNodeImports:this.hasNodeImports(i),css:r}}a.buildTime=new Date().toISOString(),await w.promises.writeFile(i,JSON.stringify(a,null,2),`utf-8`),await this.writeRouteCssEntries(a),this.manifestCache=a}clearCache(){this.buildCache.clear(),this.manifestCache=null}invalidateBuildCacheFor(e){this.buildCache.delete(e)}async getTransformedComponentCode(e){return await this.buildComponentCodeOnly(e)}};function Qt(e){return J(e)||h.test(e)||v.test(e)||b.test(e)}function $t(e,t,n){let r=E.basename(e);return Ht.test(r)||r.endsWith(`.d.ts`)||K(t)?!1:G(t)?!0:n.isOnlyImportedByClientComponents(e)?!1:n.isServerComponent(e,t)&&Qt(t)}function en(e,t,n=!0){n&&t.buildImportGraph(e);let r=w.readdirSync(e,{withFileTypes:!0});for(let n of r){let r=E.join(e,n.name);if(n.isDirectory())en(r,t,!1);else if(n.isFile()&&g.test(n.name))try{let e=w.readFileSync(r,`utf-8`);$t(r,e,t)&&t.addServerComponent(r,e)}catch(e){console.warn(`[server-build] Error checking ${r}:`,e instanceof Error?e.message:e)}}}function tn(e={}){let t=null,n,r=!1,i={};return{name:`rari-server-build`,configResolved(a){n=a.root,r=a.command===`serve`;let o={};if(a.resolve?.alias){let e=a.resolve.alias;Array.isArray(e)?e.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&(o[e.find]=e.replacement)}):typeof e==`object`&&Object.entries(e).forEach(([e,t])=>{typeof t==`string`&&(o[e]=t)})}i=o,t=new Zt(n,{...e,alias:o})},buildStart(){if(!t)return;let e=D.env.NODE_ENV===`production`,r=[E.join(n,`dist`,`cache`,`og`),E.join(n,`dist`,`cache`,`images`)];e&&r.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of r)try{w.existsSync(e)&&w.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let i=E.join(n,`src`);w.existsSync(i)&&en(i,t)},async closeBundle(){if(t){await t.buildServerComponents(),await t.buildSSRClientComponents();try{let{generateRobotsFile:e}=await import(`./robots-generator-CsTVq3Jp.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`dist`)})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-generator-DWgqfKQu.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}try{let{generateFeedFile:e}=await import(`./feed-generator-CM9mK131.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate feed:`,e)}}},async handleHotUpdate({file:e}){if(!t||!r)return;let i=E.relative(n,e).replace(x,`/`);if(!(!i.startsWith(`src/`)||!g.test(i)))try{let n=await w.promises.readFile(e,`utf-8`),r=t.hasComponent(e);if(!$t(e,n,t)){r&&t.removeComponent(e);return}r||t.addServerComponent(e,n),await t.rebuildComponent(e)}catch(e){console.error(`[rari] Build: Error rebuilding ${i}:`,e)}}}}const nn="[rari] Runtime dist not built. Run `pnpm build` in the rari package first.",rn=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,an=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,on=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,sn=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,cn=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ln=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,un=/import\s+["']\.\.?\/([^"']+)["'];?/g,dn=/import\s*(?:\(\s*)?["']([^"']+)["']\)?/g,fn=/export\s*\{([^}]+)\}/g,pn=/\s+as\s+/,mn=/export\s+default\s+(?:function|class)\s+\w+/,hn=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,gn=/export\s+default\s+([^;]+)/,_n=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,vn=/^['"]use client['"];?\s*$/gm,yn=/import\s+["']([^"']+)["']/g,bn=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,xn=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,Sn=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,Cn=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,wn=/import\s+["']([^"']+)["']/g,Tn=/from(\s*)(['"])(?:\.\/vendor\/react-flight-client\/index|rari\/runtime\/vendor\/react-flight-client\/index)\.mjs\2/g,En=/\bJSX\b/,Dn=/\{([^}]*)\}/,On=/^['"]use client['"];?\s*\n/,kn={remotePatterns:[],localPatterns:[],deviceSizes:p,imageSizes:f,formats:u,qualityAllowlist:d,minimumCacheTTL:60,maxCacheSize:l},An=new Map;async function jn(e){let t=An.get(e);if(t)return t;let n=import.meta.url,r=O(n),i=E.dirname(r),a=[E.join(i,`runtime`,e),E.join(i,`../runtime`,e)];for(let t of a)try{let n=await w.promises.readFile(t,`utf-8`);return t.endsWith(`.ts`)&&(n=n.replace(rn,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(an,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(on,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(sn,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(cn,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(ln,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(un,(e,t)=>`import "rari/${t}";`)),An.set(e,n),n}catch(e){e.code!==`ENOENT`&&e.code!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${t}:`,e)}throw Error(`Could not find ${e}. Tried: ${a.join(`, `)}`)}const Mn=E.dirname(O(import.meta.url)),Nn=E.dirname(Mn);function $(e){let t=[E.join(Mn,`runtime`,e),E.join(Mn,`../runtime`,e)];for(let e of t)if(w.existsSync(e))return e;return null}function Pn(e){return e.startsWith(Nn)}async function Fn(){return jn(`rsc-client-runtime.mjs`)}async function In(e,t){return(await jn(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function Ln(){return jn(`react-server-dom-shim.mjs`)}async function Rn(e,t){let n=await xt(E.join(e,`src`)),r={...kn,...t.images,preoptimizeManifest:n.images},i=E.join(e,`dist`),a=E.join(i,`server`);w.existsSync(a)||w.mkdirSync(a,{recursive:!0});let o=E.join(a,`image.json`);w.writeFileSync(o,JSON.stringify(r,null,2))}function zn(e,t=[]){let n=new Set;function r(e){if(!w.existsSync(e))return;let t=w.readdirSync(e,{withFileTypes:!0});for(let i of t){let t=E.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;r(t)}else if(i.isFile()&&g.test(i.name))try{K(w.readFileSync(t,`utf8`))&&n.add(t)}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error during file scan:`,t,e)}}}r(e);for(let e of t)w.existsSync(e)&&r(e);return n}function Bn(e){return e}function Vn(e={}){let t=new Map,n=new Set,r=new Map,i=null,a=null,o={};function s(e){if(r.has(e))return r.get(e);let t={hasUseServer:!1,hasUseClient:!1},n=e.replace(x,`/`);if(!g.test(n)||!n.includes(`/src/`))return r.set(e,t),t;try{let n=W(w.readFileSync(e,`utf-8`));t.hasUseServer=n.hasUseServer,t.hasUseClient=n.hasUseClient,r.set(e,t)}catch{r.set(e,t)}return t}let c=null,l=null;function u(){let t=e.projectRoot||D.cwd(),n=E.join(t,`index.html`);try{let e=w.statSync(n).mtimeMs;if(c!==null&&e===l)return c;l=e}catch{return c===null&&(c=new Set),c}c=new Set;try{let e=w.readFileSync(n,`utf-8`);for(let n of e.matchAll(dn)){let e=n[1];e.startsWith(`/src/`)&&c.add(E.join(t,e.slice(1)))}}catch{}return c}function d(e){if(e.includes(`node_modules`)||Pn(e)||u().has(e))return!1;let t;try{t=w.realpathSync(e)}catch{return!1}try{let e=W(w.readFileSync(t,`utf-8`));return e.hasUseServer?!1:!e.hasUseClient}catch{return!1}}function f(e){try{let t=[],n=e.matchAll(fn);for(let e of n){let n=e[1].split(`,`);for(let e of n){let n=e.trim().split(pn).at(-1)?.trim();n&&t.push(n)}}(mn.test(e)||J(e))&&t.push(`default`);let r=e.matchAll(_n);for(let e of r)e[1]&&t.push(e[1]);return[...new Set(t)]}catch{return[]}}function p(e,t){if(!G(e))return e;let n=f(e);if(n.length===0)return e;let r=JSON.stringify(t),i=e;i+=`
101
101
 
102
102
  import {registerServerReference} from "react-server-dom-rari/server";
103
- `;for(let t of n)if(t==="default"){let n=e.match(sn);if(n){let e=n[1];i+=`
103
+ `;for(let t of n)if(t==="default"){let n=e.match(hn);if(n){let e=n[1];i+=`
104
104
  // Register server reference for default export
105
- `,i+=`registerServerReference(${e}, ${r}, ${JSON.stringify(t)});\n`}else{let n=e.match(cn);if(n){let e=n[1].trim(),a=`__default_export__`;i=i.replace(cn,`const ${a} = ${e};\nexport default ${a}`),i+=`
105
+ `,i+=`registerServerReference(${e}, ${r}, ${JSON.stringify(t)});\n`}else{let n=e.match(gn);if(n){let e=n[1].trim(),a=`__default_export__`;i=i.replace(gn,`const ${a} = ${e};\nexport default ${a}`),i+=`
106
106
  // Register server reference for default export
107
107
  `,i+=`if (typeof ${a} === "function") {\n`,i+=` registerServerReference(${a}, ${r}, ${JSON.stringify(t)});\n`,i+=`}
108
108
  `}}}else i+=`\n// Register server reference for ${t}\n`,i+=`if (typeof ${t} === "function") {\n`,i+=` registerServerReference(${t}, ${r}, ${JSON.stringify(t)});\n`,i+=`}
@@ -111,11 +111,11 @@ import {registerServerReference} from "react-server-dom-rari/server";
111
111
  if (import.meta.hot) {
112
112
  import.meta.hot.accept(() => {
113
113
  });
114
- }`,i}function m(t,n){let r=e.projectRoot||D.cwd(),i=K(t),a=d(n);if(i){let e=f(t);if(e.length===0)return``;let i=I(n,r),a=JSON.stringify(i),o=`import { createServerReference } from "rari/runtime/actions";
115
- `;for(let t of e)t==="default"?o+=`export default createServerReference("default", ${a}, "default");\n`:o+=`export const ${t} = createServerReference("${t}", ${a}, "${t}");\n`;return o}if(a){let e=f(t);if(e.length===0)return``;let i=I(n,r),a=JSON.stringify(n),o=`import { createServerComponentWrapper } from "virtual:rsc-integration.ts";
116
- `;for(let t of e)t==="default"?o+=`export default createServerComponentWrapper("${i}", ${a});\n`:o+=`export const ${t} = createServerComponentWrapper("${i}_${t}", ${a});\n`;return o}if(!q(t))return t;let o=f(t);if(o.length===0)return``;let s=JSON.stringify(n),c=`import {registerClientReference} from "react-server-dom-rari/server";
117
- `;for(let e of o){if(e==="default"){let e=`Attempted to call the default export of ${n} 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+=`${s},`,c+=`${JSON.stringify(e)});\n`}return c}function h(e,t){return!q(e)||f(e).length===0?e:e.replace(un,``)}function _(e,t){let n=e;for(let[t,r]of Object.entries(o))if(e.startsWith(`${t}/`)){n=e.replace(t,r);break}else if(e===t){n=r;break}let r=E.resolve(E.dirname(t),n),i=[`.tsx`,`.jsx`,`.ts`,`.js`];return Qe(r,i)||$e(r,i)||`${r}.tsx`}function v(e){return(e.split(`/`).pop()||e).replace(te,``)}let b=!1;async function S(){let e=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3)}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return b=t,t}catch{return b=!1,!1}}let C=[{name:`rari`,config(t,{command:n}){if(t.define=t.define||{},n===`serve`||D.env.RARI_SERVER_URL||D.env.RARI_HOST){let e=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3),n;if(D.env.RARI_SERVER_URL)n=D.env.RARI_SERVER_URL;else if(D.env.RARI_HOST){let t=D.env.RARI_HOST.startsWith(`http`)?D.env.RARI_HOST:`http://${D.env.RARI_HOST}`;n=t.replace(y,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}let r=typeof t.css?.modules==`object`?t.css.modules:{};if(t.css={...t.css,transformer:t.css?.transformer??`lightningcss`,modules:{...r,pattern:Vt}},n===`build`){let n=e.projectRoot||D.cwd(),r=E.join(n,`index.html`);if(w.existsSync(r))try{let e=w.readFileSync(r,`utf-8`),n=[];for(let t of e.matchAll(dn)){let e=t[1];if(e.startsWith(`/src/`)&&g.test(e)){let t=e.slice(1),r=E.basename(t,E.extname(t));n.push({path:t,name:r})}}if(n.length>0){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{};let e=t.build.rolldownOptions.input||{main:`./index.html`},r;r=typeof e==`string`?{main:e}:Array.isArray(e)?{main:e[0]||`./index.html`}:{...e},n.forEach(({path:e,name:t})=>{r[t]=`./${e}`}),t.build.rolldownOptions.input=r}}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 c=new Set(o.map(e=>String(e.find)));try{let e=O(import.meta.resolve(`react`)),n=O(import.meta.resolve(`react-dom/client`)),r=O(import.meta.resolve(`react/jsx-runtime`)),i=[];c.has(`react/jsx-runtime`)||i.push({find:`react/jsx-runtime`,replacement:r});try{let e=O(import.meta.resolve(`react/jsx-dev-runtime`));c.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)}c.has(`react`)||i.push({find:`react`,replacement:e}),c.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`),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 l=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.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},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){if(t.codeSplitting!==!1&&typeof t.codeSplitting!=`object`&&(t.codeSplitting={}),typeof t.codeSplitting==`object`){t.codeSplitting.groups=t.codeSplitting.groups||[];let e=t.codeSplitting.groups;t.codeSplitting.groups.push({name(t){if(t.includes(`node_modules`)){for(let n of e)if(n.test){let e=!1;if(typeof n.test==`function`?e=!!n.test(t):n.test instanceof RegExp?e=n.test.test(t):typeof n.test==`string`&&(e=t.includes(n.test)),e)return null}return t.includes(`node_modules/react-dom`)?`react-dom`:t.includes(`node_modules/react`)?`react`:`vendor`}return null}})}t.chunkFileNames||=e=>e.moduleIds?.some(e=>s(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds?.some(e=>s(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)&&(o[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(o[e]=n)})}},transform(e,r){if(!g.test(r))return null;let i=this.environment;if(q(e)){t.set(r,`client`),n.add(r);let i=e.split(`
118
- `);for(let e of i){let i=e.match(fn);if(!i)continue;let a=i[4];if(!a)continue;let o=_(a,r);w.existsSync(o)&&(t.set(o,`client`),n.add(o))}return h(e,r)}if(t.get(r)===`client`||n.has(r))return h(e,r);if(d(r)){if(t.set(r,`server`),i&&(i.name===`rsc`||i.name===`ssr`))return p(e,r);{let t=m(e,r);return t=`// HMR acceptance for server component
114
+ }`,i}function m(t,n){let r=e.projectRoot||D.cwd(),i=G(t),a=d(n);if(i){let e=f(t);if(e.length===0)return``;let i=F(n,r),a=JSON.stringify(i),o=`import { createServerReference } from "rari/runtime/actions";
115
+ `;for(let t of e)t==="default"?o+=`export default createServerReference("default", ${a}, "default");\n`:o+=`export const ${t} = createServerReference("${t}", ${a}, "${t}");\n`;return o}if(a){let e=f(t);if(e.length===0)return``;let i=F(n,r),a=JSON.stringify(n),o=`import { createServerComponentWrapper } from "virtual:rsc-integration.ts";
116
+ `;for(let t of e)t==="default"?o+=`export default createServerComponentWrapper("${i}", ${a});\n`:o+=`export const ${t} = createServerComponentWrapper("${i}_${t}", ${a});\n`;return o}if(!K(t))return t;let o=f(t);if(o.length===0)return``;let s=JSON.stringify(n),c=`import {registerClientReference} from "react-server-dom-rari/server";
117
+ `;for(let e of o){if(e==="default"){let e=`Attempted to call the default export of ${n} 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+=`${s},`,c+=`${JSON.stringify(e)});\n`}return c}function h(e,t){return!K(e)||f(e).length===0?e:e.replace(vn,``)}function _(e,t){let n=e;for(let[t,r]of Object.entries(o))if(e.startsWith(`${t}/`)){n=e.replace(t,r);break}else if(e===t){n=r;break}let r=E.resolve(E.dirname(t),n),i=[`.tsx`,`.jsx`,`.ts`,`.js`];return X(r,i)||Z(r,i)||`${r}.tsx`}function v(e){return(e.split(`/`).pop()||e).replace(te,``)}let b=!1;async function S(){let e=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3)}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return b=t,t}catch{return b=!1,!1}}let C=[{name:`rari`,config(t,{command:n}){if(t.define=t.define||{},n===`serve`||D.env.RARI_SERVER_URL||D.env.RARI_HOST){let e=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3),n;if(D.env.RARI_SERVER_URL)n=D.env.RARI_SERVER_URL;else if(D.env.RARI_HOST){let t=D.env.RARI_HOST.startsWith(`http`)?D.env.RARI_HOST:`http://${D.env.RARI_HOST}`;n=t.replace(y,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}let r=typeof t.css?.modules==`object`?t.css.modules:{};if(t.css={...t.css,transformer:t.css?.transformer??`lightningcss`,modules:{...r,pattern:Gt}},n===`build`){let n=e.projectRoot||D.cwd(),r=E.join(n,`index.html`);if(w.existsSync(r))try{let e=w.readFileSync(r,`utf-8`),n=[];for(let t of e.matchAll(yn)){let e=t[1];if(e.startsWith(`/src/`)&&g.test(e)){let t=e.slice(1),r=E.basename(t,E.extname(t));n.push({path:t,name:r})}}if(n.length>0){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{};let e=t.build.rolldownOptions.input||{main:`./index.html`},r;r=typeof e==`string`?{main:e}:Array.isArray(e)?{main:e[0]||`./index.html`}:{...e},n.forEach(({path:e,name:t})=>{r[t]=`./${e}`}),t.build.rolldownOptions.input=r}}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 c=new Set(o.map(e=>String(e.find)));try{let e=O(import.meta.resolve(`react`)),n=O(import.meta.resolve(`react-dom/client`)),r=O(import.meta.resolve(`react/jsx-runtime`)),i=[];c.has(`react/jsx-runtime`)||i.push({find:`react/jsx-runtime`,replacement:r});try{let e=O(import.meta.resolve(`react/jsx-dev-runtime`));c.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)}c.has(`react`)||i.push({find:`react`,replacement:e}),c.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`),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 l=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.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},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){if(t.codeSplitting!==!1&&typeof t.codeSplitting!=`object`&&(t.codeSplitting={}),typeof t.codeSplitting==`object`){t.codeSplitting.groups=t.codeSplitting.groups||[];let e=t.codeSplitting.groups;t.codeSplitting.groups.push({name(t){if(t.includes(`node_modules`)){for(let n of e)if(n.test){let e=!1;if(typeof n.test==`function`?e=!!n.test(t):n.test instanceof RegExp?e=n.test.test(t):typeof n.test==`string`&&(e=t.includes(n.test)),e)return null}return t.includes(`node_modules/react-dom`)?`react-dom`:t.includes(`node_modules/react`)?`react`:`vendor`}return null}})}t.chunkFileNames||=e=>e.moduleIds?.some(e=>s(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds?.some(e=>s(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)&&(o[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(o[e]=n)})}},transform(e,r){if(!g.test(r))return null;let i=this.environment;if(K(e)){t.set(r,`client`),n.add(r);let i=e.split(`
118
+ `);for(let e of i){let i=e.match(bn);if(!i)continue;let a=i[4];if(!a)continue;let o=_(a,r);w.existsSync(o)&&(t.set(o,`client`),n.add(o))}return h(e,r)}if(t.get(r)===`client`||n.has(r))return h(e,r);if(d(r)){if(t.set(r,`server`),i&&(i.name===`rsc`||i.name===`ssr`))return p(e,r);{let t=m(e,r);return t=`// HMR acceptance for server component
119
119
  if (import.meta.hot) {
120
120
  import.meta.hot.accept();
121
121
  }
@@ -126,8 +126,8 @@ if (typeof globalThis !== 'undefined') {
126
126
  globalThis['~rari'].serverComponents.add(${JSON.stringify(r)});
127
127
  }
128
128
 
129
- ${t}`,t}}if(K(e))return t.set(r,`server`),i&&(i.name===`rsc`||i.name===`ssr`)?p(e,r):m(e,r);let a=t.get(r);if(a===`server`)return i&&(i.name===`rsc`||i.name===`ssr`)?p(e,r):m(e,r);if(a===`client`)return h(e,r);t.set(r,`unknown`);let o=e.split(`
130
- `),s=e,c=!1,l=!1,u=!1,f=[],y=q(e)||t.get(r)===`client`||r.includes(`entry-client`);for(let e of o){let a=e.match(fn);if(!a)continue;let o=a[1],p=a[4],m=v(p),h=_(p,r),g=t.get(h)===`client`||w.existsSync(h)&&q(w.readFileSync(h,`utf-8`));if(g&&(t.set(h,`client`),n.add(h)),g&&i&&(i.name===`rsc`||i.name===`ssr`)){if(!y){let t=e,n=o||`default`,r=`
129
+ ${t}`,t}}if(G(e))return t.set(r,`server`),i&&(i.name===`rsc`||i.name===`ssr`)?p(e,r):m(e,r);let a=t.get(r);if(a===`server`)return i&&(i.name===`rsc`||i.name===`ssr`)?p(e,r):m(e,r);if(a===`client`)return h(e,r);t.set(r,`unknown`);let o=e.split(`
130
+ `),s=e,c=!1,l=!1,u=!1,f=[],y=K(e)||t.get(r)===`client`||r.includes(`entry-client`);for(let e of o){let a=e.match(bn);if(!a)continue;let o=a[1],p=a[4],m=v(p),h=_(p,r),g=t.get(h)===`client`||w.existsSync(h)&&K(w.readFileSync(h,`utf-8`));if(g&&(t.set(h,`client`),n.add(h)),g&&i&&(i.name===`rsc`||i.name===`ssr`)){if(!y){let t=e,n=o||`default`,r=`
131
131
  import { registerClientReference } from "react-server-dom-rari/server";
132
132
  const ${n} = registerClientReference(
133
133
  function() {
@@ -135,10 +135,10 @@ const ${n} = registerClientReference(
135
135
  },
136
136
  ${JSON.stringify(h)},
137
137
  ${JSON.stringify(o||`default`)}
138
- );`;s=s.replace(t,r),c=!0,l=!0}}else if(!y&&d(h)){c=!0,l=!0,u=!0;let t=e;o&&o!==`_`&&f.push(`const ${o} = createServerComponentWrapper('${m}', '${p}');`),s=s.replace(t,``)}}if(c){let e=s.includes(`import React`)||s.match(pn)||s.match(mn),n=s.includes(`createServerComponentWrapper`),i=``;if(l&&!e&&(i+=`import React from 'react';
138
+ );`;s=s.replace(t,r),c=!0,l=!0}}else if(!y&&d(h)){c=!0,l=!0,u=!0;let t=e;o&&o!==`_`&&f.push(`const ${o} = createServerComponentWrapper('${m}', '${p}');`),s=s.replace(t,``)}}if(c){let e=s.includes(`import React`)||s.match(xn)||s.match(Sn),n=s.includes(`createServerComponentWrapper`),i=``;if(l&&!e&&(i+=`import React from 'react';
139
139
  `),u&&!n&&(i+=`import { createServerComponentWrapper } from 'virtual:rsc-integration.ts';
140
140
  `),f.length>0&&(i+=`${f.join(`
141
- `)}\n`),i&&(s=i+s),!s.includes(`Suspense`)){let e=s.match(hn);e&&(e[1]&&!e[2].includes(`Suspense`)?s=s.replace(e[0],e[0].replace(yn,`{ Suspense, $1 }`)):e[1]||(s=s.replace(e[0],`import React, { Suspense } from 'react';`)))}let a=D.env.NODE_ENV!==`production`,o=s.includes(`</`)||s.includes(`/>`)||vn.test(s);return!q(s)&&o&&a&&(s=`'use client';\n\n${s}`,t.set(r,`client`)),s}return null},async configureServer(n){let r=e.projectRoot||D.cwd(),s=E.join(r,`src`);await An(r,e);let c=null,l=async()=>{try{let t=new $(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,cacheControl:e.cacheControl});if(c=t,!a&&c){let e=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3);a=new tt(c,e)}let i=E.join(r,`src`),s=[];if(w.existsSync(i)){let e=t=>{let n=w.readdirSync(t,{withFileTypes:!0});for(let r of n){let n=E.join(t,r.name);if(r.isDirectory())e(n);else if(r.isFile()&&g.test(r.name))try{d(n)&&s.push(n)}catch(e){console.error(`[rari] Error checking ${n}:`,e)}}};e(i),Kt(i,t)}s.length>0&&n.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:s}});let l=await t.getTransformedComponentsForDevelopment(),u=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3)}`;for(let e of l)try{if(e.id.startsWith(`app/`)||K(e.code))continue;let t=await fetch(`${u}/_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))}},u=async()=>{try{let e=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3)}`,t=jn(s,Object.values(o));for(let n of t){let t=E.relative(D.cwd(),n),r=E.basename(n).replace(te,``);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)}},f=async()=>{if(i)return;let{getBinaryPath:e,getInstallationInstructions:t}=await import(`./platform.mjs`),r;try{r=e()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(t());return}let a=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3),o=D.env.NODE_ENV===`production`?`production`:`development`,s=n.config.server.port||5173,c=[`--mode`,o,`--port`,a.toString(),`--host`,`127.0.0.1`];i=ae(r,c,{stdio:[`ignore`,`pipe`,`pipe`],cwd:D.cwd(),env:{...D.env,RUST_LOG:D.env.RUST_LOG||`error`,RARI_VITE_PORT:s.toString()}}),i.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),i.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),i.on(`error`,e=>{b=!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.`)}),i.on(`exit`,(e,t)=>{i=null,b=!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 d=!1;for(let e=0;e<20&&(d=await S(),!d);e++)await new Promise(e=>setTimeout(e,500));d?(await u(),await l()):console.error(`Server failed to become ready for component registration`)},p=async t=>{try{if(!d(t))return;let n=new $(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,cacheControl:e.cacheControl});n.addServerComponent(t);let i=await n.getTransformedComponentsForDevelopment();if(i.length===0)return;let a=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.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(e){console.error(`[rari] Targeted HMR failed for`,`${t}:`,e instanceof Error?e.message:String(e)),setTimeout(l,1e3)}};f().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),n.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(!b&&!await S()){let e=Date.now();for(;Date.now()-e<1e4&&!await S();)await new Promise(e=>setTimeout(e,100));if(!b){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}}let n=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.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(ie.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()}),n.watcher.on(`change`,async e=>{g.test(e)&&t.delete(e),g.test(e)&&e.includes(s)&&(d(e)?(n.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await p(e)):setTimeout(l,1e3))}),n.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 p(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)}))}})}),n.httpServer?.on(`close`,()=>{a&&=(a.dispose(),null),i&&=(i.kill(`SIGTERM`),null),b=!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-flight-client`||e===`virtual:react-flight-client.ts`)return`virtual:react-flight-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`virtual:error-boundary-wrapper`||e===`virtual:error-boundary-wrapper.tsx`)return`virtual:error-boundary-wrapper.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=O(n),i=E.dirname(r),a=null,o=[E.join(i,`runtime`),E.join(i,`../runtime`)];for(let e of o)if(w.existsSync(e)){a=e;break}if(a){let t=E.join(a,e);if(w.existsSync(t))return t;let n=E.join(a,`../dist`,E.basename(e));if(w.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=E.join(i,e);if(w.existsSync(s))return s;let c=E.join(i,`../dist`,E.basename(e));if(w.existsSync(c))return c}if(D.env.NODE_ENV===`production`)try{let t=E.resolve(e);if(w.existsSync(t)&&d(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(g.test(t)){let e=this.environment;if(e&&e.name===`client`)try{let e=w.readFileSync(t,`utf-8`);if(K(e))return m(e,t)}catch{}}if(t===`virtual:rari-entry-client.ts`){let e=jn(E.join(D.cwd(),`src`),Object.values(o)),t=new Set([...n,...e]),r=[{path:`rari/image`,exports:[`Image`]},{path:`virtual:error-boundary-wrapper.tsx`,exports:[`ErrorBoundaryWrapper`]}],i=[...t].filter(e=>{try{return q(w.readFileSync(e,`utf-8`))}catch{return!1}}).map(e=>{let t=E.relative(D.cwd(),e).replace(x,`/`),n=t.replace(g,``),r=t.startsWith(`..`)?e.replace(x,`/`):t,i=!1,a=``;try{let t=w.readFileSync(e,`utf-8`),n=Y(t),r=t.match(ee);!n&&r&&(i=!0,a=r[1])}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let o=i?a:E.basename(e,E.extname(e)),s=r.replace(x,`/`),c=s.startsWith(`/`)||ne.test(s)?s:`/${s}`;return` "${r}": {
141
+ `)}\n`),i&&(s=i+s),!s.includes(`Suspense`)){let e=s.match(Cn);e&&(e[1]&&!e[2].includes(`Suspense`)?s=s.replace(e[0],e[0].replace(Dn,`{ Suspense, $1 }`)):e[1]||(s=s.replace(e[0],`import React, { Suspense } from 'react';`)))}let a=D.env.NODE_ENV!==`production`,o=s.includes(`</`)||s.includes(`/>`)||En.test(s);return!K(s)&&o&&a&&(s=`'use client';\n\n${s}`,t.set(r,`client`)),s}return null},async configureServer(n){let r=e.projectRoot||D.cwd(),s=E.join(r,`src`);await Rn(r,e);let c=null,l=async()=>{try{let t=new Zt(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,cacheControl:e.cacheControl});if(c=t,!a&&c){let e=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3);a=new rt(c,e)}let i=E.join(r,`src`),s=[];if(w.existsSync(i)){let e=t=>{let n=w.readdirSync(t,{withFileTypes:!0});for(let r of n){let n=E.join(t,r.name);if(r.isDirectory())e(n);else if(r.isFile()&&g.test(r.name))try{d(n)&&s.push(n)}catch(e){console.error(`[rari] Error checking ${n}:`,e)}}};e(i),en(i,t)}s.length>0&&n.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:s}});let l=await t.getTransformedComponentsForDevelopment(),u=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3)}`;for(let e of l)try{if(e.id.startsWith(`app/`)||G(e.code))continue;let t=await fetch(`${u}/_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))}},u=async()=>{try{let e=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3)}`,t=zn(s,Object.values(o));for(let n of t){let t=E.relative(D.cwd(),n),r=E.basename(n).replace(te,``);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)}},f=async()=>{if(i)return;let{getBinaryPath:e,getInstallationInstructions:t}=await import(`./platform.mjs`),r;try{r=e()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(t());return}let a=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.env.RSC_PORT||3e3),o=D.env.NODE_ENV===`production`?`production`:`development`,s=n.config.server.port||5173,c=[`--mode`,o,`--port`,a.toString(),`--host`,`127.0.0.1`];i=ae(r,c,{stdio:[`ignore`,`pipe`,`pipe`],cwd:D.cwd(),env:{...D.env,RUST_LOG:D.env.RUST_LOG||`error`,RARI_VITE_PORT:s.toString()}}),i.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),i.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),i.on(`error`,e=>{b=!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.`)}),i.on(`exit`,(e,t)=>{i=null,b=!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 d=!1;for(let e=0;e<20&&(d=await S(),!d);e++)await new Promise(e=>setTimeout(e,500));d?(await u(),await l()):console.error(`Server failed to become ready for component registration`)},p=async t=>{try{if(!d(t))return;let n=new Zt(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,cacheControl:e.cacheControl});n.addServerComponent(t);let i=await n.getTransformedComponentsForDevelopment();if(i.length===0)return;let a=`http://localhost:${D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.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(e){console.error(`[rari] Targeted HMR failed for`,`${t}:`,e instanceof Error?e.message:String(e)),setTimeout(l,1e3)}};f().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),n.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(!b&&!await S()){let e=Date.now();for(;Date.now()-e<1e4&&!await S();)await new Promise(e=>setTimeout(e,100));if(!b){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}}let n=D.env.SERVER_PORT?Number(D.env.SERVER_PORT):Number(D.env.PORT||D.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(ie.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()}),n.watcher.on(`change`,async e=>{g.test(e)&&t.delete(e),g.test(e)&&e.includes(s)&&(d(e)?(n.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await p(e)):setTimeout(l,1e3))}),n.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 p(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)}))}})}),n.httpServer?.on(`close`,()=>{a&&=(a.dispose(),null),i&&=(i.kill(`SIGTERM`),null),b=!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-flight-client`||e===`virtual:react-flight-client.ts`)return`virtual:react-flight-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`virtual:error-boundary-wrapper`||e===`virtual:error-boundary-wrapper.tsx`)return`virtual:error-boundary-wrapper.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=O(n),i=E.dirname(r),a=null,o=[E.join(i,`runtime`),E.join(i,`../runtime`)];for(let e of o)if(w.existsSync(e)){a=e;break}if(a){let t=E.join(a,e);if(w.existsSync(t))return t;let n=E.join(a,`../dist`,E.basename(e));if(w.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=E.join(i,e);if(w.existsSync(s))return s;let c=E.join(i,`../dist`,E.basename(e));if(w.existsSync(c))return c}if(D.env.NODE_ENV===`production`)try{let t=E.resolve(e);if(w.existsSync(t)&&d(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(g.test(t)){let e=this.environment;if(e&&e.name===`client`)try{let e=w.readFileSync(t,`utf-8`);if(G(e))return m(e,t)}catch{}}if(t===`virtual:rari-entry-client.ts`){let e=zn(E.join(D.cwd(),`src`),Object.values(o)),t=new Set([...n,...e]),r=[{path:`rari/image`,exports:[`Image`]},{path:`virtual:error-boundary-wrapper.tsx`,exports:[`ErrorBoundaryWrapper`]}],i=[...t].filter(e=>{try{return K(w.readFileSync(e,`utf-8`))}catch{return!1}}).map(e=>{let t=E.relative(D.cwd(),e).replace(x,`/`),n=t.replace(g,``),r=t.startsWith(`..`)?e.replace(x,`/`):t,i=!1,a=``;try{let t=w.readFileSync(e,`utf-8`),n=J(t),r=t.match(ee);!n&&r&&(i=!0,a=r[1])}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let o=i?a:E.basename(e,E.extname(e)),s=r.replace(x,`/`),c=s.startsWith(`/`)||ne.test(s)?s:`/${s}`;return` "${r}": {
142
142
  id: "${n}",
143
143
  path: "${r}",
144
144
  exportName: "${o}",
@@ -162,7 +162,7 @@ globalThis['~clientComponents']["${e.path}"] = globalThis['~clientComponents']["
162
162
  globalThis['~clientComponents']["${e.path}"].component = ExternalModule${t};
163
163
  globalThis['~clientComponentPaths'] = globalThis['~clientComponentPaths'] || {};
164
164
  globalThis['~clientComponentPaths']["${e.path}"] = "${n}";`)).join(`
165
- `);return await On(a,[`
165
+ `);return await In(a,[`
166
166
  const lazyComponentRegistry = {
167
167
  ${i}
168
168
  };
@@ -175,6 +175,6 @@ for (const [path, config] of Object.entries(lazyComponentRegistry)) {
175
175
  globalThis['~clientComponentPaths'][path] = config.id;
176
176
  }
177
177
  `,s].filter(Boolean).join(`
178
- `))}if(t===`react-server-dom-rari/server`)return await kn();if(t===`virtual:app-router-provider.tsx`){let e=Tn(`AppRouterProvider.mjs`);if(e)return w.readFileSync(e,`utf-8`);throw Error(Jt)}if(t===`virtual:loading-error-boundary.tsx`){let e=Tn(`LoadingErrorBoundary.mjs`);if(e)return w.readFileSync(e,`utf-8`);throw Error(Jt)}if(t===`virtual:error-boundary-wrapper.tsx`){let e=Tn(`ErrorBoundaryWrapper.mjs`);if(e){let t=w.readFileSync(e,`utf-8`);if(!t.includes(`import React`)&&!t.includes(`from "react"`)&&!t.includes(`from 'react'`)){let e=t.match(bn);if(e){let n=e[0];return`
178
+ `))}if(t===`react-server-dom-rari/server`)return await Ln();if(t===`virtual:app-router-provider.tsx`){let e=$(`AppRouterProvider.mjs`);if(e)return w.readFileSync(e,`utf-8`);throw Error(nn)}if(t===`virtual:loading-error-boundary.tsx`){let e=$(`LoadingErrorBoundary.mjs`);if(e)return w.readFileSync(e,`utf-8`);throw Error(nn)}if(t===`virtual:error-boundary-wrapper.tsx`){let e=$(`ErrorBoundaryWrapper.mjs`);if(e){let t=w.readFileSync(e,`utf-8`);if(!t.includes(`import React`)&&!t.includes(`from "react"`)&&!t.includes(`from 'react'`)){let e=t.match(On);if(e){let n=e[0];return`
179
179
  ${n}import * as React from 'react';\n${t.slice(n.length)}`}return`
180
- import * as React from 'react';\n${t}`}return t}throw Error(Jt)}if(t===`virtual:rsc-integration.ts`)return(await Dn()).replace(_n,(e,t,n)=>`from${t}${n}virtual:react-flight-client.ts${n}`);if(t===`virtual:react-flight-client.ts`)return{code:`export * from 'rari/runtime/vendor/react-flight-client'`};if(t.endsWith(`.mjs`)&&w.existsSync(t))try{let n=e.projectRoot||D.cwd(),r=w.realpathSync(t),i=E.relative(n,r),a=!i.startsWith(`..`)&&!E.isAbsolute(i),o=r.includes(`${E.sep}node_modules${E.sep}`),s=r.includes(`${E.sep}packages${E.sep}rari${E.sep}`)||r.includes(`${E.sep}node_modules${E.sep}rari${E.sep}`);return a||o||s?w.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:e,server:t}){if(!g.test(e))return;if(e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let n=a?.detectComponentType(e)||`unknown`,r=e.includes(`/app/`)||e.includes(`\\app\\`),i=(e,t)=>e.endsWith(`${t}.tsx`)||e.endsWith(`${t}.jsx`)||e.endsWith(`${t}.ts`)||e.endsWith(`${t}.js`),o=[`page`,`layout`,`template`,`loading`,`error`,`not-found`].some(t=>i(e,t));if(!(r&&o)&&n!==`client`&&n===`server`)return a&&await a.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(gn)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}let n=[];n.push({tag:`script`,attrs:{type:`module`},children:`import 'virtual:rari-entry-client';`,injectTo:`head-prepend`}),t.length>0&&n.push(...t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`})));let r=e;r=r.replace(/^\s*import\s+["']\/src\/[^"']+["'];?\s*$/gm,``),r=r.replace(/^\s*import\s+["']virtual:rari-entry-client["'];?\s*$/gm,``);let i;do i=r,r=r.replace(/<script\s+type=["']module["'][^>]*>\s*<\/script>/gi,``);while(r!==i);return{html:r,tags:n}}},async writeBundle(){await An(e.projectRoot||D.cwd(),e)}},qt({...e.serverBuild,csp:e.csp,cacheControl:e.cacheControl})];return e.proxy!==!1&&C.push(se(e.proxy||{})),e.router!==!1&&C.push(je(e.router||{})),C}function Pn(e){return{plugins:[Nn(),...e.plugins||[]],...e}}var Fn=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})}},In=class{baseUrl;timeout;components=[];initialized=!1;constructor(e={}){let{host:t=`127.0.0.1`,port:n=3e3,timeout:r=3e4,ssl:i=!1}=e,a=i?`https`:`http`;this.baseUrl=`${a}://${t}:${n}`,this.timeout=r}assertInitialized(){if(!this.initialized)throw Error(`Runtime client not initialized. Call initialize() first.`)}async request(e,t={}){let{method:n=`GET`,body:r,headers:i={}}=t,a=`${this.baseUrl}${e}`,o={method:n,headers:{"Content-Type":`application/json`,...i},signal:AbortSignal.timeout(this.timeout)};r&&(n===`POST`||n===`PUT`)&&(o.body=JSON.stringify(r));try{let e=await fetch(a,o);return await X(e),e.headers.get(`content-type`)?.includes(`application/json`)?await e.json():await e.text()}catch(e){if(e instanceof Error){if(e.name===`AbortError`)throw Error(`Request timeout after ${this.timeout}ms`);if(e.message.includes(`ECONNREFUSED`))throw Error(`Failed to connect to rari server at ${this.baseUrl}. Make sure the server is running.`)}throw e}}async initialize(){try{let e=await this.request(`/_rari/health`);if(e.status!==`healthy`)throw Error(`Server is not healthy: ${e.status}`);this.initialized=!0}catch(e){throw Error(`Failed to initialize runtime client: ${e}`)}}async registerComponent(e,t){this.assertInitialized();let n={component_id:e,component_code:t};try{let t=await this.request(`/_rari/register`,{method:`POST`,body:n});if(!t.success)throw Error(`Failed to register component: ${t.error||`Unknown error`}`);this.components.includes(e)||this.components.push(e)}catch(t){throw Error(`Failed to register component ${e}: ${t}`)}}async renderToStreamCallbacks(e,t){this.assertInitialized();let n={component_id:e,props:t?JSON.parse(t):void 0};try{let e=await fetch(`${this.baseUrl}/_rari/stream`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout)});return await X(e),e.body}catch(t){throw Error(`Failed to stream component ${e}: ${t}`)}}registerClientComponent(e,t,n){this.queueClientComponentRegistration(e,t,n)}async queueClientComponentRegistration(e,t,n){if(!this.initialized){console.error(`[rari] Runtime: Client not initialized. Registration for "${e}" dropped.`);return}let r={component_id:e,file_path:t,export_name:n};try{let e=await this.request(`/_rari/register-client`,{method:`POST`,body:r});if(!e.success)throw Error(`Failed to register client component: ${e.error||`Unknown error`}`)}catch(t){console.error(`[rari] Runtime: Failed to register client component ${e}:`,t)}}registerClientReference(e,t,n){this.queueClientComponentRegistration(e,t,n)}listComponents(){return[...this.components]}async shutdown(){this.initialized=!1,this.components=[]}async checkHealth(){return this.assertInitialized(),await this.request(`/_rari/health`)}isInitialized(){return this.initialized}getBaseUrl(){return this.baseUrl}};function Ln(e){return new In(e)}function Rn(e){return Nn(e)}export{Fn as ApiResponse,In as HttpRuntimeClient,e as RariRequest,t as RariResponse,c as clearPropsCache,i as clearPropsCacheForComponent,Ln as createHttpRuntimeClient,Pn as defineRariConfig,Mn as defineRariOptions,o as extractMetadata,r as extractServerProps,n as extractServerPropsWithCache,a as extractStaticParams,ve as generateAppRouteManifest,s as hasServerSideDataFetching,Rn as rari,se as rariProxy,je as rariRouter};
180
+ import * as React from 'react';\n${t}`}return t}throw Error(nn)}if(t===`virtual:rsc-integration.ts`)return(await Fn()).replace(Tn,(e,t,n)=>`from${t}${n}virtual:react-flight-client.ts${n}`);if(t===`virtual:react-flight-client.ts`)return{code:`export * from 'rari/runtime/vendor/react-flight-client'`};if(t.endsWith(`.mjs`)&&w.existsSync(t))try{let n=e.projectRoot||D.cwd(),r=w.realpathSync(t),i=E.relative(n,r),a=!i.startsWith(`..`)&&!E.isAbsolute(i),o=r.includes(`${E.sep}node_modules${E.sep}`),s=r.includes(`${E.sep}packages${E.sep}rari${E.sep}`)||r.includes(`${E.sep}node_modules${E.sep}rari${E.sep}`);return a||o||s?w.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:e,server:t}){if(!g.test(e))return;if(e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let n=a?.detectComponentType(e)||`unknown`,r=e.includes(`/app/`)||e.includes(`\\app\\`),i=(e,t)=>e.endsWith(`${t}.tsx`)||e.endsWith(`${t}.jsx`)||e.endsWith(`${t}.ts`)||e.endsWith(`${t}.js`),o=[`page`,`layout`,`template`,`loading`,`error`,`not-found`].some(t=>i(e,t));if(!(r&&o)&&n!==`client`&&n===`server`)return a&&await a.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(wn)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}let n=[];n.push({tag:`script`,attrs:{type:`module`},children:`import 'virtual:rari-entry-client';`,injectTo:`head-prepend`}),t.length>0&&n.push(...t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`})));let r=e;r=r.replace(/^\s*import\s+["']\/src\/[^"']+["'];?\s*$/gm,``),r=r.replace(/^\s*import\s+["']virtual:rari-entry-client["'];?\s*$/gm,``);let i;do i=r,r=r.replace(/<script\s+type=["']module["'][^>]*>\s*<\/script>/gi,``);while(r!==i);return{html:r,tags:n}}},async writeBundle(){await Rn(e.projectRoot||D.cwd(),e)}},tn({...e.serverBuild,csp:e.csp,cacheControl:e.cacheControl})];return e.proxy!==!1&&C.push(se(e.proxy||{})),e.router!==!1&&C.push(Me(e.router||{})),C}function Hn(e){return{plugins:[Vn(),...e.plugins||[]],...e}}var Un=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})}},Wn=class{baseUrl;timeout;components=[];initialized=!1;constructor(e={}){let{host:t=`127.0.0.1`,port:n=3e3,timeout:r=3e4,ssl:i=!1}=e,a=i?`https`:`http`;this.baseUrl=`${a}://${t}:${n}`,this.timeout=r}assertInitialized(){if(!this.initialized)throw Error(`Runtime client not initialized. Call initialize() first.`)}async request(e,t={}){let{method:n=`GET`,body:r,headers:i={}}=t,a=`${this.baseUrl}${e}`,o={method:n,headers:{"Content-Type":`application/json`,...i},signal:AbortSignal.timeout(this.timeout)};r&&(n===`POST`||n===`PUT`)&&(o.body=JSON.stringify(r));try{let e=await fetch(a,o);return await Q(e),e.headers.get(`content-type`)?.includes(`application/json`)?await e.json():await e.text()}catch(e){if(e instanceof Error){if(e.name===`AbortError`)throw Error(`Request timeout after ${this.timeout}ms`);if(e.message.includes(`ECONNREFUSED`))throw Error(`Failed to connect to rari server at ${this.baseUrl}. Make sure the server is running.`)}throw e}}async initialize(){try{let e=await this.request(`/_rari/health`);if(e.status!==`healthy`)throw Error(`Server is not healthy: ${e.status}`);this.initialized=!0}catch(e){throw Error(`Failed to initialize runtime client: ${e}`)}}async registerComponent(e,t){this.assertInitialized();let n={component_id:e,component_code:t};try{let t=await this.request(`/_rari/register`,{method:`POST`,body:n});if(!t.success)throw Error(`Failed to register component: ${t.error||`Unknown error`}`);this.components.includes(e)||this.components.push(e)}catch(t){throw Error(`Failed to register component ${e}: ${t}`)}}async renderToStreamCallbacks(e,t){this.assertInitialized();let n={component_id:e,props:t?JSON.parse(t):void 0};try{let e=await fetch(`${this.baseUrl}/_rari/stream`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout)});return await Q(e),e.body}catch(t){throw Error(`Failed to stream component ${e}: ${t}`)}}registerClientComponent(e,t,n){this.queueClientComponentRegistration(e,t,n)}async queueClientComponentRegistration(e,t,n){if(!this.initialized){console.error(`[rari] Runtime: Client not initialized. Registration for "${e}" dropped.`);return}let r={component_id:e,file_path:t,export_name:n};try{let e=await this.request(`/_rari/register-client`,{method:`POST`,body:r});if(!e.success)throw Error(`Failed to register client component: ${e.error||`Unknown error`}`)}catch(t){console.error(`[rari] Runtime: Failed to register client component ${e}:`,t)}}registerClientReference(e,t,n){this.queueClientComponentRegistration(e,t,n)}listComponents(){return[...this.components]}async shutdown(){this.initialized=!1,this.components=[]}async checkHealth(){return this.assertInitialized(),await this.request(`/_rari/health`)}isInitialized(){return this.initialized}getBaseUrl(){return this.baseUrl}};function Gn(e){return new Wn(e)}function Kn(e){return Vn(e)}export{Un as ApiResponse,Wn as HttpRuntimeClient,e as RariRequest,t as RariResponse,c as clearPropsCache,i as clearPropsCacheForComponent,Gn as createHttpRuntimeClient,Hn as defineRariConfig,Bn as defineRariOptions,o as extractMetadata,r as extractServerProps,n as extractServerPropsWithCache,a as extractStaticParams,ve as generateAppRouteManifest,s as hasServerSideDataFetching,Kn as rari,se as rariProxy,Me as rariRouter};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rari",
3
3
  "type": "module",
4
- "version": "0.14.8",
4
+ "version": "0.14.11",
5
5
  "description": "Runtime Accelerated Rendering Infrastructure (rari)",
6
6
  "author": "Ryan Skinner",
7
7
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "repository": {
10
10
  "directory": "packages/rari",
11
11
  "type": "git",
12
- "url": "https://github.com/rari-build/rari.git"
12
+ "url": "git+https://github.com/rari-build/rari.git"
13
13
  },
14
14
  "bugs": {
15
15
  "url": "https://github.com/rari-build/rari/issues"
@@ -115,21 +115,21 @@
115
115
  "rolldown": "^1.1.0"
116
116
  },
117
117
  "optionalDependencies": {
118
- "rari-darwin-arm64": "0.14.8",
119
- "rari-darwin-x64": "0.14.8",
120
- "rari-linux-arm64": "0.14.8",
121
- "rari-linux-x64": "0.14.8",
122
- "rari-win32-arm64": "0.14.8",
123
- "rari-win32-x64": "0.14.8"
118
+ "rari-darwin-arm64": "0.14.11",
119
+ "rari-darwin-x64": "0.14.11",
120
+ "rari-linux-arm64": "0.14.11",
121
+ "rari-linux-x64": "0.14.11",
122
+ "rari-win32-arm64": "0.14.11",
123
+ "rari-win32-x64": "0.14.11"
124
124
  },
125
125
  "devDependencies": {
126
- "@types/node": "^25.9.2",
126
+ "@types/node": "^25.9.3",
127
127
  "@types/react": "^19.2.17",
128
128
  "@types/react-dom": "^19.2.3",
129
- "@typescript/native-preview": "^7.0.0-dev.20260606.1",
129
+ "@typescript/native-preview": "^7.0.0-dev.20260610.1",
130
130
  "vite-plus": "^0.1.24",
131
- "@rari/deploy": "0.1.0",
132
- "@rari/logger": "0.1.0"
131
+ "@rari/deploy": "0.0.0",
132
+ "@rari/logger": "0.0.0"
133
133
  },
134
134
  "scripts": {
135
135
  "build": "pnpm clean && pnpm typecheck && vp pack",
@@ -1 +0,0 @@
1
- import e from"node:path";function t(t,n,r){if(typeof t!=`string`)throw TypeError(`Expected source to be a string, but received ${typeof t}`);if(n==null)throw TypeError(`Expected aliases to be an object, but received ${n}`);if(typeof n!=`object`||Array.isArray(n))throw TypeError(`Expected aliases to be a plain object, but received ${Array.isArray(n)?`array`:typeof n}`);if(Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw TypeError(`Expected aliases to be a plain object, but received ${n.constructor?.name||`object with custom prototype`}`);if(typeof r!=`string`)throw TypeError(`Expected projectRoot to be a string, but received ${typeof r}`);let i=Object.entries(n).sort((e,t)=>t[0].length-e[0].length);for(let[n,a]of i)if(t.startsWith(`${n}/`)||t===n){let i=t.slice(n.length),o=e.join(a,i);return e.isAbsolute(o)?o:e.resolve(r,o)}return null}export{t};
@@ -1,2 +0,0 @@
1
- import{Buffer as e}from"node:buffer";import{promises as t}from"node:fs";import n from"node:path";function r(e){return Array.isArray(e)?e:e?[e]:[`*`]}function i(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``)}function a(e){let t=[],n=r(e.userAgent);for(let r of n){t.push(`User-Agent: ${r}`);let n=i(e.allow);for(let e of n)t.push(`Allow: ${e}`);let a=i(e.disallow);for(let e of a)t.push(`Disallow: ${e}`);e.crawlDelay!==void 0&&t.push(`Crawl-delay: ${e.crawlDelay}`),t.push(``)}return t}function o(e){return e?[`Host: ${e}`,``]:[]}function s(e){return i(e).map(e=>`Sitemap: ${e}`)}function c(e){let t=[],n=Array.isArray(e.rules)?e.rules:[e.rules];for(let e of n)t.push(...a(e));return t.push(...o(e.host)),t.push(...s(e.sitemap)),t.join(`
2
- `)}async function l(e,r=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`]){let i=n.join(e,`robots.txt`);try{return await t.access(i),{type:`static`,path:i}}catch(e){if(e?.code!==`ENOENT`)throw e}for(let i of r){let r=n.join(e,`robots${i}`);try{return await t.access(r),{type:`dynamic`,path:r}}catch(e){if(e?.code!==`ENOENT`)throw e}}return null}async function u(r){let{appDir:i,outDir:a,extensions:o}=r,s=await l(i,o);if(!s)return!1;let u=n.join(a,`robots.txt`);if(await t.mkdir(n.dirname(u),{recursive:!0}),s.type===`static`)return await t.copyFile(s.path,u),!0;try{let{build:r}=await import(`rolldown`),i=await t.readFile(s.path,`utf-8`),a=`\0virtual:robots`,o=await r({input:a,external:[`rari`],platform:`node`,write:!1,output:{format:`esm`,codeSplitting:!1},plugins:[{name:`virtual-robots`,resolveId(e){return e===a?e:e.startsWith(`.`)?n.resolve(n.dirname(s.path),e):null},load(e){if(e===a){let e=n.extname(s.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;default:throw Error(`Unsupported robots file extension: .${e}. Supported extensions are: .ts, .tsx, .js, .jsx, .mjs, .cjs`)}return{code:i,moduleType:t}}return null}}]});if(!o.output||o.output.length===0)throw Error(`Failed to build robots module`);let l=o.output.find(e=>e.type===`chunk`&&e.isEntry)||o.output.find(e=>e.type===`chunk`);if(!l||l.type!==`chunk`)throw Error(`No chunk output found in robots build result`);let d=l.code,f=await import(`data:text/javascript;base64,${e.from(d).toString(`base64`)}`);if(!f||f.default==null)throw Error(`Robots file must export a default export (either an object or a function)`);let p;if(typeof f.default==`function`){let e=f.default();p=e instanceof Promise?await e:e}else p=f.default;let m=c(p);return await t.writeFile(u,m),!0}catch(e){return console.error(`[rari] Failed to build/execute robots file:`,e),!1}}export{u as generateRobotsFile};