rari 0.12.2 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +1 -1
- package/dist/client.mjs +1 -1
- package/dist/platform.mjs +1 -1
- package/dist/proxy/RariRequest.mjs +1 -1
- package/dist/{railway-2u_Vq-71.mjs → railway-C_CGHd0f.mjs} +1 -1
- package/dist/{render-jhijat1L.mjs → render-BlHTT8CS.mjs} +1 -1
- package/dist/runtime-client-CbbckLpl.mjs +6 -0
- package/dist/vite.mjs +1 -1
- package/package.json +10 -9
- package/dist/runtime-client-D57-4ZUQ.mjs +0 -6
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-
|
|
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-C_CGHd0f.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-BlHTT8CS.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.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as e,t}from"./navigate-hfIqe3MK.mjs";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _}from"./runtime-client-D57-4ZUQ.mjs";import{Component as v,useEffect as y,useLayoutEffect as b,useRef as x,useState as S}from"react";import{Fragment as C,jsx as w,jsxs as T}from"react/jsx-runtime";function E(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;return o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e))return h(e);let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0:h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}const D=/fetch|networkerror|load failed/i;function O(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function k(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function A(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function j(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function M(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function N(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function P(e,t){if(e instanceof Error&&e.name===`AbortError`)return O(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return k(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?A(e,n,t):N(e,t)}return e instanceof TypeError&&D.test(e.message)?j(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?M(e,t):N(e,t)}var F=class{options;retryCount;constructor(e={}){this.options={timeout:e.timeout??1e4,maxRetries:e.maxRetries??3,onError:e.onError??(()=>{}),onRetry:e.onRetry??(()=>{})},this.retryCount=new Map}handleError(e,t){let n=P(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};function I(e){if(!e||e===`/`)return`/`;let t=e;for(;t.endsWith(`/`)&&t.length>1;)t=t.slice(0,-1);return t.startsWith(`/`)||(t=`/${t}`),t}function L(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function R(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}function z({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return w(`div`,{style:{position:`fixed`,top:0,left:0,right:0,bottom:0,background:`rgba(0, 0, 0, 0.5)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:1e4,padding:`20px`},onClick:e=>{e.target===e.currentTarget&&r&&r()},children:T(`div`,{style:{background:`white`,borderRadius:`8px`,padding:`24px`,maxWidth:`500px`,width:`100%`,boxShadow:`0 4px 12px rgba(0, 0, 0, 0.15)`},onClick:e=>e.stopPropagation(),children:[T(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[w(`span`,{style:{fontSize:`32px`},children:(()=>{switch(e.type){case`timeout`:return`⏱️`;case`network-error`:return`📡`;case`not-found`:return`🔍`;case`server-error`:return`⚠️`;case`parse-error`:return`📄`;case`abort`:return`🚫`;default:return`❌`}})()}),w(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),w(`p`,{style:{margin:`0 0 16px 0`,fontSize:`15px`,lineHeight:`1.5`,color:`#4b5563`},children:(()=>{switch(e.type){case`timeout`:return`The page took too long to load. Please try again.`;case`network-error`:return`Unable to connect to the server. Please check your internet connection.`;case`not-found`:return`The page you're looking for doesn't exist.`;case`server-error`:return`The server encountered an error. Please try again in a moment.`;case`parse-error`:return`Unable to load the page content. Please try reloading.`;case`abort`:return`Navigation was cancelled.`;default:return e.message||`An unexpected error occurred.`}})()}),e.url&&T(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[w(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),T(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`Status:`}),` `,e.statusCode]}),T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&T(`div`,{children:[w(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&T(`div`,{style:{marginBottom:`16px`,padding:`8px 12px`,background:`#fef3c7`,border:`1px solid #fbbf24`,borderRadius:`4px`,fontSize:`13px`,color:`#92400e`},children:[`Retry attempt`,` `,i,` `,`of`,` `,a]}),T(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&w(`button`,{onClick:t,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#3b82f6`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#2563eb`},onMouseLeave:e=>{e.currentTarget.style.background=`#3b82f6`},children:`Try Again`}),n&&w(`button`,{onClick:n,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#6b7280`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.background=`#6b7280`},children:`Reload Page`}),r&&w(`button`,{onClick:r,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`transparent`,color:`#6b7280`,border:`1px solid #d1d5db`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`all 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#f9fafb`,e.currentTarget.style.borderColor=`#9ca3af`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`#d1d5db`},children:`Dismiss`})]}),w(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const B=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}async fetchRouteInfo(e){let t=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})});if(!t.ok){let e=null;try{e=await t.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${t.status} ${t.statusText}`)}let n=t.clone();try{return await t.json()}catch(t){try{let e=await n.text();return JSON.parse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=B}var V=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize||50,this.scrollableSelector=e.scrollableSelector||`[data-scrollable], .scrollable, [style*="overflow"]`}captureState(e){let t={scrollPositions:this.captureScrollPositions(),formData:this.captureFormData(),focusedElement:this.captureFocusedElement()};return this.storeState(e,t),t}captureScrollPositions(){let e=new Map;try{e.set(`window`,{x:window.scrollX,y:window.scrollY,element:`window`}),document.querySelectorAll(this.scrollableSelector).forEach((t,n)=>{if(t instanceof HTMLElement){let r=t.id||`scrollable-${n}`;(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)&&e.set(r,{x:t.scrollLeft,y:t.scrollTop,element:r})}})}catch{}return e}captureFormData(){let e=new Map;try{document.querySelectorAll(`form`).forEach((t,n)=>{let r=t.id||t.name||`form-${n}`,i=new FormData(t);i.entries().next().done||e.set(r,i)})}catch{}return e}captureFocusedElement(){try{let e=document.activeElement;if(e&&e!==document.body){if(e.id)return`#${e.id}`;if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.name)return`[name="${e.name}"]`}}catch{}return null}storeState(e,t){let n=this.routeAccessOrder.indexOf(e);for(n!==-1&&this.routeAccessOrder.splice(n,1),this.routeAccessOrder.push(e),this.stateHistory.set(e,t);this.routeAccessOrder.length>this.maxHistorySize;){let e=this.routeAccessOrder.shift();e&&this.stateHistory.delete(e)}}getHistorySize(){return this.stateHistory.size}hasState(e){return this.stateHistory.has(e)}getState(e){return this.stateHistory.get(e)}clearAll(){this.stateHistory.clear(),this.routeAccessOrder=[]}clearState(e){this.stateHistory.delete(e);let t=this.routeAccessOrder.indexOf(e);t!==-1&&this.routeAccessOrder.splice(t,1)}restoreState(e){let t=this.stateHistory.get(e);if(!t)return!1;let n=!0;return this.restoreScrollPositions(t.scrollPositions)||(n=!1),this.restoreFormData(t.formData)||(n=!1),t.focusedElement&&this.restoreFocus(t.focusedElement),n}restoreScrollPositions(e){let t=!0;try{e.forEach((e,n)=>{try{if(n===`window`)window.scrollTo(e.x,e.y);else{let r=document.getElementById(n)||document.querySelector(`[data-scrollable-id="${n}"]`);r instanceof HTMLElement?(r.scrollLeft=e.x,r.scrollTop=e.y):t=!1}}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore scroll positions:`,e),t=!1}return t}restoreFormData(e){let t=!0;try{e.forEach((e,n)=>{try{let r=document.getElementById(n)||document.querySelector(`form[name="${n}"]`)||document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];r instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=r.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e:t.value=e)}):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t instanceof HTMLInputElement&&(t.type===`checkbox`||t.type===`radio`)?t.checked=t.value===e:t.value=e)}catch{t=!1}}):t=!1}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore form data:`,e),t=!1}return t}restoreFocus(e){try{let t=document.querySelector(e);t instanceof HTMLElement&&requestAnimationFrame(()=>{try{t.focus()}catch{}})}catch{}}};function H(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function U(e){let t=document.querySelector(e);t&&t.remove()}function W(e){e.title&&(document.title=e.title),e.description?H(`meta[name="description"]`,{name:`description`,content:e.description}):U(`meta[name="description"]`),e.keywords&&e.keywords.length>0?H(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):U(`meta[name="keywords"]`),e.viewport&&H(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function G(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function K(e){if(e===void 0){U(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?H(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):U(`meta[name="robots"]`)}function q(e){if(e===void 0){U(`meta[property="og:title"]`),U(`meta[property="og:description"]`),U(`meta[property="og:url"]`),U(`meta[property="og:site_name"]`),U(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?H(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):U(`meta[property="og:title"]`),e.description?H(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):U(`meta[property="og:description"]`),e.url?H(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):U(`meta[property="og:url"]`),e.siteName?H(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):U(`meta[property="og:site_name"]`),e.type?H(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):U(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove())}function J(e){if(e===void 0){U(`meta[name="twitter:card"]`),U(`meta[name="twitter:site"]`),U(`meta[name="twitter:creator"]`),U(`meta[name="twitter:title"]`),U(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?H(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):U(`meta[name="twitter:card"]`),e.site?H(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):U(`meta[name="twitter:site"]`),e.creator?H(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):U(`meta[name="twitter:creator"]`),e.title?H(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):U(`meta[name="twitter:title"]`),e.description?H(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):U(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove())}function Y(e){W(e),G(e.canonical),K(e.robots),q(e.openGraph),J(e.twitter)}function X({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=S(()=>({currentRoute:I(r),navigationId:0,error:null})),s=x(null),c=x(!0),l=x(I(r)),u=x(0),d=x(new F({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),f=x(new Map),p=x([]),m=x(new V({maxHistorySize:50})),h=x(null),g=x(i),_=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,v=()=>{s.current&&=(s.current.abort(),null)},D=()=>{for(let[,e]of f.current.entries())e.abortController.abort();f.current.clear()},O=(e,t)=>{f.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},k=x(null),A=(e,t)=>{if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))},j=e=>{try{let t=e.headers.get(`x-rari-metadata`);t&&Y(JSON.parse(decodeURIComponent(t)))}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},M=(e,t,n,r,i,a)=>{u.current===r&&window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,abortSignal:a.signal,rscResponsePromise:e}}))},N=(e,t,n)=>{n.historyKey?requestAnimationFrame(()=>{m.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=(n=0)=>{let r=document.getElementById(t);r?r.scrollIntoView({behavior:`smooth`,block:`start`}):n<10&&setTimeout(e,50,n+1)};e()})},P=(e,t,n,r)=>{c.current&&(l.current=e,o(t=>({...t,currentRoute:e,navigationId:r,error:null})),d.current.resetRetry(e),N(e,t,n))},H=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){O(t,n);return}let i=d.current.handleError(e,t);c.current&&(o(e=>({...e,error:i})),window.history.replaceState(window.history.state,``,r)),f.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),k.current?.()},U=async(e,t={})=>{if(!e||typeof e!=`string`)return;let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=I(n);if(i===l.current&&!t.replace){A(i,r);return}let a=f.current.get(i);if(a)return a.promise;D(),v();let o=new AbortController;s.current=o,u.current+=1;let c=u.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:c,targetPath:i}}));let d=(async()=>{let e=l.current;try{t.historyKey||m.current.captureState(e);let n=t.historyKey||_(),a=window.location.origin+i,s=r?`${i}#${r}`:i,l={route:i,navigationId:c,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(l,``,s):window.history.pushState(l,``,s);let u=await fetch(a,{headers:{Accept:`text/x-component`},signal:o.signal}).then(e=>{if(!e.ok&&e.status!==404)throw Error(`Failed to fetch: ${e.status}`);return e});if(o.signal.aborted){O(i,c);return}let d=new URL(u.url).pathname;if(o.signal.aborted){O(i,c);return}if(d!==i){let e=r?`${d}#${r}`:d;window.history.replaceState({...l,route:d},``,e)}if(M(Promise.resolve(u),e,d,c,t,o),j(u),o.signal.aborted){O(i,c);return}P(d,r,t,c),f.current.delete(i),k.current?.()}catch(t){H(t,i,c,e)}})();return f.current.set(i,{targetPath:i,navigationId:c,promise:d,abortController:o}),d},W=async()=>{if(p.current.length===0)return;let e=p.current.at(-1);e&&(p.current=[],await U(e.path,e.options))},G=x(U);b(()=>(k.current=W,G.current=U,()=>{k.current=null,G.current=null}));let K=x(null);K.current||=E((e,t)=>{G.current?.(e,t)},50,{leading:!0,trailing:!0,maxWait:200});let q=e=>{if(e.button!==0||e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)return;let t=e.target;for(;t&&t.tagName!==`A`;)t=t.parentElement;if(!t||t.tagName!==`A`)return;let n=t;if(n.target&&n.target!==`_self`||n.hasAttribute(`download`))return;let r=n.getAttribute(`href`);if(!r||L(r))return;if(r.startsWith(`#`)){e.preventDefault();let t=r.slice(1),n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,r));return}e.preventDefault();let i=R(r);K.current&&K.current(i,{replace:!1})},J=e=>{let t=window.location.pathname,n=e.state;G.current&&G.current(t,{replace:!0,scroll:!1,historyKey:n?.key})},X=()=>{if(a.error&&a.error.url){let e=a.error.url;d.current.incrementRetry(e),U(e,{replace:!1})}},Z=()=>{window.location.reload()},ee=()=>{o(e=>({...e,error:null}))};y(()=>{let e=window.history.state;if(!e||!e.key){let e={route:I(r),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:_()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[r]);let Q=e=>{if(e.persisted){let e=window.location.pathname;m.current.captureState(e)}},$=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{m.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return y(()=>(document.addEventListener(`click`,q),window.addEventListener(`popstate`,J),window.addEventListener(`pagehide`,Q),window.addEventListener(`pageshow`,$),()=>{document.removeEventListener(`click`,q),window.removeEventListener(`popstate`,J),window.removeEventListener(`pagehide`,Q),window.removeEventListener(`pageshow`,$)}),[]),y(()=>{g.current=i;let e=()=>{document.hidden?h.current=Date.now():h.current!==null&&Date.now()-h.current>g.current&&B.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[i]),y(()=>(c.current=!0,e((e,t)=>G.current?.(e,t)??Promise.resolve()),()=>{c.current=!1,t(),v(),D(),K.current?.cancel&&K.current.cancel()}),[]),T(C,{children:[n,a.error&&w(z,{error:a.error,onRetry:X,onReload:Z,onDismiss:ee,retryCount:d.current.getRetryCount(a.error.url||``),maxRetries:3})]})}var Z=class extends v{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`[rari] Layout: Error in layout "${this.props.layoutPath}":`,e,t),this.props.onError&&this.props.onError(e,t),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:layout-error`,{detail:{layoutPath:this.props.layoutPath,error:e,errorInfo:t,timestamp:Date.now()}}))}reset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError&&this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):T(`div`,{style:{padding:`16px`,margin:`16px 0`,background:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`},children:[w(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`},children:`Layout Error`}),T(`p`,{style:{margin:`0 0 8px 0`,fontSize:`14px`},children:[`An error occurred in layout:`,` `,w(`code`,{children:this.props.layoutPath})]}),T(`details`,{style:{fontSize:`12px`,marginBottom:`8px`},children:[w(`summary`,{style:{cursor:`pointer`},children:`Error details`}),T(`pre`,{style:{marginTop:`8px`,padding:`8px`,background:`#fff`,border:`1px solid #ddd`,borderRadius:`2px`,overflow:`auto`},children:[this.state.error.message,`
|
|
1
|
+
import{i as e,t}from"./navigate-hfIqe3MK.mjs";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _}from"./runtime-client-CbbckLpl.mjs";import{Component as v,useEffect as y,useLayoutEffect as b,useRef as x,useState as S}from"react";import{Fragment as C,jsx as w,jsxs as T}from"react/jsx-runtime";function E(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;return o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e))return h(e);let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0:h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}const D=/fetch|networkerror|load failed/i;function O(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function k(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function A(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function j(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function M(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function N(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function P(e,t){if(e instanceof Error&&e.name===`AbortError`)return O(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return k(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?A(e,n,t):N(e,t)}return e instanceof TypeError&&D.test(e.message)?j(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?M(e,t):N(e,t)}var F=class{options;retryCount;constructor(e={}){this.options={timeout:e.timeout??1e4,maxRetries:e.maxRetries??3,onError:e.onError??(()=>{}),onRetry:e.onRetry??(()=>{})},this.retryCount=new Map}handleError(e,t){let n=P(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};function I(e){if(!e||e===`/`)return`/`;let t=e;for(;t.endsWith(`/`)&&t.length>1;)t=t.slice(0,-1);return t.startsWith(`/`)||(t=`/${t}`),t}function L(e,t){try{return new URL(e,t||window.location.origin).origin!==(t||window.location.origin)}catch{return!1}}function R(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}function z({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return w(`div`,{style:{position:`fixed`,top:0,left:0,right:0,bottom:0,background:`rgba(0, 0, 0, 0.5)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:1e4,padding:`20px`},onClick:e=>{e.target===e.currentTarget&&r&&r()},children:T(`div`,{style:{background:`white`,borderRadius:`8px`,padding:`24px`,maxWidth:`500px`,width:`100%`,boxShadow:`0 4px 12px rgba(0, 0, 0, 0.15)`},onClick:e=>e.stopPropagation(),children:[T(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[w(`span`,{style:{fontSize:`32px`},children:(()=>{switch(e.type){case`timeout`:return`⏱️`;case`network-error`:return`📡`;case`not-found`:return`🔍`;case`server-error`:return`⚠️`;case`parse-error`:return`📄`;case`abort`:return`🚫`;default:return`❌`}})()}),w(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),w(`p`,{style:{margin:`0 0 16px 0`,fontSize:`15px`,lineHeight:`1.5`,color:`#4b5563`},children:(()=>{switch(e.type){case`timeout`:return`The page took too long to load. Please try again.`;case`network-error`:return`Unable to connect to the server. Please check your internet connection.`;case`not-found`:return`The page you're looking for doesn't exist.`;case`server-error`:return`The server encountered an error. Please try again in a moment.`;case`parse-error`:return`Unable to load the page content. Please try reloading.`;case`abort`:return`Navigation was cancelled.`;default:return e.message||`An unexpected error occurred.`}})()}),e.url&&T(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[w(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),T(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`Status:`}),` `,e.statusCode]}),T(`div`,{style:{marginBottom:`4px`},children:[w(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&T(`div`,{children:[w(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&T(`div`,{style:{marginBottom:`16px`,padding:`8px 12px`,background:`#fef3c7`,border:`1px solid #fbbf24`,borderRadius:`4px`,fontSize:`13px`,color:`#92400e`},children:[`Retry attempt`,` `,i,` `,`of`,` `,a]}),T(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&w(`button`,{onClick:t,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#3b82f6`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#2563eb`},onMouseLeave:e=>{e.currentTarget.style.background=`#3b82f6`},children:`Try Again`}),n&&w(`button`,{onClick:n,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#6b7280`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.background=`#6b7280`},children:`Reload Page`}),r&&w(`button`,{onClick:r,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`transparent`,color:`#6b7280`,border:`1px solid #d1d5db`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`all 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#f9fafb`,e.currentTarget.style.borderColor=`#9ca3af`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`#d1d5db`},children:`Dismiss`})]}),w(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const B=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}async fetchRouteInfo(e){let t=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})});if(!t.ok){let e=null;try{e=await t.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${t.status} ${t.statusText}`)}let n=t.clone();try{return await t.json()}catch(t){try{let e=await n.text();return JSON.parse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=B}var V=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize||50,this.scrollableSelector=e.scrollableSelector||`[data-scrollable], .scrollable, [style*="overflow"]`}captureState(e){let t={scrollPositions:this.captureScrollPositions(),formData:this.captureFormData(),focusedElement:this.captureFocusedElement()};return this.storeState(e,t),t}captureScrollPositions(){let e=new Map;try{e.set(`window`,{x:window.scrollX,y:window.scrollY,element:`window`}),document.querySelectorAll(this.scrollableSelector).forEach((t,n)=>{if(t instanceof HTMLElement){let r=t.id||`scrollable-${n}`;(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)&&e.set(r,{x:t.scrollLeft,y:t.scrollTop,element:r})}})}catch{}return e}captureFormData(){let e=new Map;try{document.querySelectorAll(`form`).forEach((t,n)=>{let r=t.id||t.name||`form-${n}`,i=new FormData(t);i.entries().next().done||e.set(r,i)})}catch{}return e}captureFocusedElement(){try{let e=document.activeElement;if(e&&e!==document.body){if(e.id)return`#${e.id}`;if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.name)return`[name="${e.name}"]`}}catch{}return null}storeState(e,t){let n=this.routeAccessOrder.indexOf(e);for(n!==-1&&this.routeAccessOrder.splice(n,1),this.routeAccessOrder.push(e),this.stateHistory.set(e,t);this.routeAccessOrder.length>this.maxHistorySize;){let e=this.routeAccessOrder.shift();e&&this.stateHistory.delete(e)}}getHistorySize(){return this.stateHistory.size}hasState(e){return this.stateHistory.has(e)}getState(e){return this.stateHistory.get(e)}clearAll(){this.stateHistory.clear(),this.routeAccessOrder=[]}clearState(e){this.stateHistory.delete(e);let t=this.routeAccessOrder.indexOf(e);t!==-1&&this.routeAccessOrder.splice(t,1)}restoreState(e){let t=this.stateHistory.get(e);if(!t)return!1;let n=!0;return this.restoreScrollPositions(t.scrollPositions)||(n=!1),this.restoreFormData(t.formData)||(n=!1),t.focusedElement&&this.restoreFocus(t.focusedElement),n}restoreScrollPositions(e){let t=!0;try{e.forEach((e,n)=>{try{if(n===`window`)window.scrollTo(e.x,e.y);else{let r=document.getElementById(n)||document.querySelector(`[data-scrollable-id="${n}"]`);r instanceof HTMLElement?(r.scrollLeft=e.x,r.scrollTop=e.y):t=!1}}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore scroll positions:`,e),t=!1}return t}restoreFormData(e){let t=!0;try{e.forEach((e,n)=>{try{let r=document.getElementById(n)||document.querySelector(`form[name="${n}"]`)||document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];r instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=r.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e:t.value=e)}):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t instanceof HTMLInputElement&&(t.type===`checkbox`||t.type===`radio`)?t.checked=t.value===e:t.value=e)}catch{t=!1}}):t=!1}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore form data:`,e),t=!1}return t}restoreFocus(e){try{let t=document.querySelector(e);t instanceof HTMLElement&&requestAnimationFrame(()=>{try{t.focus()}catch{}})}catch{}}};function H(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function U(e){let t=document.querySelector(e);t&&t.remove()}function W(e){e.title&&(document.title=e.title),e.description?H(`meta[name="description"]`,{name:`description`,content:e.description}):U(`meta[name="description"]`),e.keywords&&e.keywords.length>0?H(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):U(`meta[name="keywords"]`),e.viewport&&H(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function G(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function K(e){if(e===void 0){U(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?H(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):U(`meta[name="robots"]`)}function q(e){if(e===void 0){U(`meta[property="og:title"]`),U(`meta[property="og:description"]`),U(`meta[property="og:url"]`),U(`meta[property="og:site_name"]`),U(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?H(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):U(`meta[property="og:title"]`),e.description?H(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):U(`meta[property="og:description"]`),e.url?H(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):U(`meta[property="og:url"]`),e.siteName?H(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):U(`meta[property="og:site_name"]`),e.type?H(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):U(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove())}function J(e){if(e===void 0){U(`meta[name="twitter:card"]`),U(`meta[name="twitter:site"]`),U(`meta[name="twitter:creator"]`),U(`meta[name="twitter:title"]`),U(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?H(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):U(`meta[name="twitter:card"]`),e.site?H(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):U(`meta[name="twitter:site"]`),e.creator?H(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):U(`meta[name="twitter:creator"]`),e.title?H(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):U(`meta[name="twitter:title"]`),e.description?H(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):U(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove())}function Y(e){W(e),G(e.canonical),K(e.robots),q(e.openGraph),J(e.twitter)}function X({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=S(()=>({currentRoute:I(r),navigationId:0,error:null})),s=x(null),c=x(!0),l=x(I(r)),u=x(0),d=x(new F({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),f=x(new Map),p=x([]),m=x(new V({maxHistorySize:50})),h=x(null),g=x(i),_=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,v=()=>{s.current&&=(s.current.abort(),null)},D=()=>{for(let[,e]of f.current.entries())e.abortController.abort();f.current.clear()},O=(e,t)=>{f.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},k=x(null),A=(e,t)=>{if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))},j=e=>{try{let t=e.headers.get(`x-rari-metadata`);t&&Y(JSON.parse(decodeURIComponent(t)))}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},M=(e,t,n,r,i,a)=>{u.current===r&&window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,abortSignal:a.signal,rscResponsePromise:e}}))},N=(e,t,n)=>{n.historyKey?requestAnimationFrame(()=>{m.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=(n=0)=>{let r=document.getElementById(t);r?r.scrollIntoView({behavior:`smooth`,block:`start`}):n<10&&setTimeout(e,50,n+1)};e()})},P=(e,t,n,r)=>{c.current&&(l.current=e,o(t=>({...t,currentRoute:e,navigationId:r,error:null})),d.current.resetRetry(e),N(e,t,n))},H=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){O(t,n);return}let i=d.current.handleError(e,t);c.current&&(o(e=>({...e,error:i})),window.history.replaceState(window.history.state,``,r)),f.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),k.current?.()},U=async(e,t={})=>{if(!e||typeof e!=`string`)return;let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=I(n);if(i===l.current&&!t.replace){A(i,r);return}let a=f.current.get(i);if(a)return a.promise;D(),v();let o=new AbortController;s.current=o,u.current+=1;let c=u.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:c,targetPath:i}}));let d=(async()=>{let e=l.current;try{t.historyKey||m.current.captureState(e);let n=t.historyKey||_(),a=window.location.origin+i,s=r?`${i}#${r}`:i,l={route:i,navigationId:c,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(l,``,s):window.history.pushState(l,``,s);let u=await fetch(a,{headers:{Accept:`text/x-component`},signal:o.signal}).then(e=>{if(!e.ok&&e.status!==404)throw Error(`Failed to fetch: ${e.status}`);return e});if(o.signal.aborted){O(i,c);return}let d=new URL(u.url).pathname;if(o.signal.aborted){O(i,c);return}if(d!==i){let e=r?`${d}#${r}`:d;window.history.replaceState({...l,route:d},``,e)}if(M(Promise.resolve(u),e,d,c,t,o),j(u),o.signal.aborted){O(i,c);return}P(d,r,t,c),f.current.delete(i),k.current?.()}catch(t){H(t,i,c,e)}})();return f.current.set(i,{targetPath:i,navigationId:c,promise:d,abortController:o}),d},W=async()=>{if(p.current.length===0)return;let e=p.current.at(-1);e&&(p.current=[],await U(e.path,e.options))},G=x(U);b(()=>(k.current=W,G.current=U,()=>{k.current=null,G.current=null}));let K=x(null);K.current||=E((e,t)=>{G.current?.(e,t)},50,{leading:!0,trailing:!0,maxWait:200});let q=e=>{if(e.button!==0||e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)return;let t=e.target;for(;t&&t.tagName!==`A`;)t=t.parentElement;if(!t||t.tagName!==`A`)return;let n=t;if(n.target&&n.target!==`_self`||n.hasAttribute(`download`))return;let r=n.getAttribute(`href`);if(!r||L(r))return;if(r.startsWith(`#`)){e.preventDefault();let t=r.slice(1),n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,r));return}e.preventDefault();let i=R(r);K.current&&K.current(i,{replace:!1})},J=e=>{let t=window.location.pathname,n=e.state;G.current&&G.current(t,{replace:!0,scroll:!1,historyKey:n?.key})},X=()=>{if(a.error&&a.error.url){let e=a.error.url;d.current.incrementRetry(e),U(e,{replace:!1})}},Z=()=>{window.location.reload()},ee=()=>{o(e=>({...e,error:null}))};y(()=>{let e=window.history.state;if(!e||!e.key){let e={route:I(r),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:_()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[r]);let Q=e=>{if(e.persisted){let e=window.location.pathname;m.current.captureState(e)}},$=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{m.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return y(()=>(document.addEventListener(`click`,q),window.addEventListener(`popstate`,J),window.addEventListener(`pagehide`,Q),window.addEventListener(`pageshow`,$),()=>{document.removeEventListener(`click`,q),window.removeEventListener(`popstate`,J),window.removeEventListener(`pagehide`,Q),window.removeEventListener(`pageshow`,$)}),[]),y(()=>{g.current=i;let e=()=>{document.hidden?h.current=Date.now():h.current!==null&&Date.now()-h.current>g.current&&B.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[i]),y(()=>(c.current=!0,e((e,t)=>G.current?.(e,t)??Promise.resolve()),()=>{c.current=!1,t(),v(),D(),K.current?.cancel&&K.current.cancel()}),[]),T(C,{children:[n,a.error&&w(z,{error:a.error,onRetry:X,onReload:Z,onDismiss:ee,retryCount:d.current.getRetryCount(a.error.url||``),maxRetries:3})]})}var Z=class extends v{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`[rari] Layout: Error in layout "${this.props.layoutPath}":`,e,t),this.props.onError&&this.props.onError(e,t),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:layout-error`,{detail:{layoutPath:this.props.layoutPath,error:e,errorInfo:t,timestamp:Date.now()}}))}reset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError&&this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):T(`div`,{style:{padding:`16px`,margin:`16px 0`,background:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`},children:[w(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`},children:`Layout Error`}),T(`p`,{style:{margin:`0 0 8px 0`,fontSize:`14px`},children:[`An error occurred in layout:`,` `,w(`code`,{children:this.props.layoutPath})]}),T(`details`,{style:{fontSize:`12px`,marginBottom:`8px`},children:[w(`summary`,{style:{cursor:`pointer`},children:`Error details`}),T(`pre`,{style:{marginTop:`8px`,padding:`8px`,background:`#fff`,border:`1px solid #ddd`,borderRadius:`2px`,overflow:`auto`},children:[this.state.error.message,`
|
|
2
2
|
`,this.state.error.stack]})]}),w(`button`,{onClick:this.reset,type:`button`,style:{padding:`6px 12px`,background:`#c00`,color:`white`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},children:`Try Again`})]}):this.props.children}};export{X as ClientRouter,_ as DefaultError,f as DefaultLoading,h as ErrorBoundary,l as HttpRuntimeClient,Z as LayoutErrorBoundary,r as LoadingSpinner,F as NavigationErrorHandler,z as NavigationErrorOverlay,p as NotFound,V as StatePreserver,a as clearPropsCache,o as clearPropsCacheForComponent,g as createErrorBoundary,i as createHttpRuntimeClient,u as createLoadingBoundary,m as extractMetadata,d as extractServerProps,c as extractServerPropsWithCache,s as extractStaticParams,n as hasServerSideDataFetching};
|
package/dist/platform.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as e}from"node:fs";import{dirname as t,join as n,parse as r}from"node:path";import i from"node:process";import{fileURLToPath as a}from"node:url";const o={"linux-x64":`rari-linux-x64`,"linux-arm64":`rari-linux-arm64`,"darwin-x64":`rari-darwin-x64`,"darwin-arm64":`rari-darwin-arm64`,"win32-x64":`rari-win32-x64`};function s(){let e=i.platform,t=i.arch,n;switch(e){case`darwin`:n=`darwin`;break;case`linux`:n=`linux`;break;case`win32`:n=`win32`;break;default:throw Error(`Unsupported platform: ${e}. rari supports Linux, macOS, and Windows.`)}let r;switch(t){case`x64`:r=`x64`;break;case`arm64`:r=`arm64`;break;default:throw Error(`Unsupported architecture: ${t}. rari supports x64 and ARM64.`)}let a=o[`${n}-${r}`];if(!a)throw Error(`Unsupported platform combination: ${n}-${r}. Supported platforms: ${Object.keys(o).join(`, `)}`);return{platform:n,arch:r,packageName:a,binaryName:n===`win32`?`rari.exe`:`rari`}}function c(){let{packageName:o,binaryName:c}=s();try{let a=i.cwd(),s=null,l=r(a).root;for(;a!==l&&a!==``;){if(e(n(a,`packages`))){s=a;break}let r=t(a);if(r===a)break;a=r}if(s){let t=n(n(s,`packages`,o),`bin`,c);if(e(t))return t}}catch{}try{let t=import.meta.resolve(`${o}/package.json`),r=n(a(new URL(`.`,t)),`bin`,c);if(e(r))return r;throw Error(`Binary not found at ${r}`)}catch{throw Error(`Failed to locate rari binary for ${o}. Please ensure the platform package is installed: npm install ${o}`)}}function l(){let{packageName:e}=s();return`
|
|
1
|
+
import{existsSync as e}from"node:fs";import{dirname as t,join as n,parse as r}from"node:path";import i from"node:process";import{fileURLToPath as a}from"node:url";const o={"linux-x64":`rari-linux-x64`,"linux-arm64":`rari-linux-arm64`,"darwin-x64":`rari-darwin-x64`,"darwin-arm64":`rari-darwin-arm64`,"win32-arm64":`rari-win32-arm64`,"win32-x64":`rari-win32-x64`};function s(){let e=i.platform,t=i.arch,n;switch(e){case`darwin`:n=`darwin`;break;case`linux`:n=`linux`;break;case`win32`:n=`win32`;break;default:throw Error(`Unsupported platform: ${e}. rari supports Linux, macOS, and Windows.`)}let r;switch(t){case`x64`:r=`x64`;break;case`arm64`:r=`arm64`;break;default:throw Error(`Unsupported architecture: ${t}. rari supports x64 and ARM64.`)}let a=o[`${n}-${r}`];if(!a)throw Error(`Unsupported platform combination: ${n}-${r}. Supported platforms: ${Object.keys(o).join(`, `)}`);return{platform:n,arch:r,packageName:a,binaryName:n===`win32`?`rari.exe`:`rari`}}function c(){let{packageName:o,binaryName:c}=s();try{let a=i.cwd(),s=null,l=r(a).root;for(;a!==l&&a!==``;){if(e(n(a,`packages`))){s=a;break}let r=t(a);if(r===a)break;a=r}if(s){let t=n(n(s,`packages`,o),`bin`,c);if(e(t))return t}}catch{}try{let t=import.meta.resolve(`${o}/package.json`),r=n(a(new URL(`.`,t)),`bin`,c);if(e(r))return r;throw Error(`Binary not found at ${r}`)}catch{throw Error(`Failed to locate rari binary for ${o}. Please ensure the platform package is installed: npm install ${o}`)}}function l(){let{packageName:e}=s();return`
|
|
2
2
|
To install rari for your platform, run:
|
|
3
3
|
|
|
4
4
|
npm install ${e}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class{cookies;pendingDeletes;pendingSets;constructor(e){this.cookies=new Map,this.pendingDeletes=new Set,this.pendingSets=new Map,e&&this.parseCookieHeader(e)}parseCookieHeader(e){let t=e.split(`;`).map(e=>e.trim());for(let e of t){let[t,...n]=e.split(`=`);if(t){let e=n.join(`=`);this.cookies.set(t,{name:t,value:e})}}}get(e){if(this.pendingDeletes.has(e))return;let t=this.pendingSets.get(e);return t?{name:t.name,value:t.value,path:t.options?.path}:this.cookies.get(e)}getAll(){let e=[];return this.cookies.forEach(t=>{this.pendingDeletes.has(t.name)||e.push(t)}),this.pendingSets.forEach(t=>{e.push({name:t.name,value:t.value,path:t.options?.path})}),e}has(e){return this.pendingDeletes.has(e)?!1:this.pendingSets.has(e)||this.cookies.has(e)}delete(e){this.pendingDeletes.add(e),this.pendingSets.delete(e)}set(e,t,n){if(typeof e==`string`)this.pendingSets.set(e,{name:e,value:t,options:n}),this.pendingDeletes.delete(e);else{let{name:t,value:n,...r}=e;this.pendingSets.set(t,{name:t,value:n,options:r}),this.pendingDeletes.delete(t)}}},t=class{url;constructor(e){this.url=typeof e==`string`?new URL(e):e}get href(){return this.url.href}get origin(){return this.url.origin}get protocol(){return this.url.protocol}get hostname(){return this.url.hostname}get port(){return this.url.port}get pathname(){return this.url.pathname}set pathname(e){this.url.pathname=e}get search(){return this.url.search}set search(e){this.url.search=e}get searchParams(){return this.url.searchParams}get hash(){return this.url.hash}set hash(e){this.url.hash=e}toString(){return this.url.toString()}},n=class n{url;method;headers;cookies;rariUrl;ip;geo;constructor(n,r){n instanceof Request
|
|
1
|
+
var e=class{cookies;pendingDeletes;pendingSets;constructor(e){this.cookies=new Map,this.pendingDeletes=new Set,this.pendingSets=new Map,e&&this.parseCookieHeader(e)}parseCookieHeader(e){let t=e.split(`;`).map(e=>e.trim());for(let e of t){let[t,...n]=e.split(`=`);if(t){let e=n.join(`=`);this.cookies.set(t,{name:t,value:e})}}}get(e){if(this.pendingDeletes.has(e))return;let t=this.pendingSets.get(e);return t?{name:t.name,value:t.value,path:t.options?.path}:this.cookies.get(e)}getAll(){let e=[];return this.cookies.forEach(t=>{this.pendingDeletes.has(t.name)||e.push(t)}),this.pendingSets.forEach(t=>{e.push({name:t.name,value:t.value,path:t.options?.path})}),e}has(e){return this.pendingDeletes.has(e)?!1:this.pendingSets.has(e)||this.cookies.has(e)}delete(e){this.pendingDeletes.add(e),this.pendingSets.delete(e)}set(e,t,n){if(typeof e==`string`)this.pendingSets.set(e,{name:e,value:t,options:n}),this.pendingDeletes.delete(e);else{let{name:t,value:n,...r}=e;this.pendingSets.set(t,{name:t,value:n,options:r}),this.pendingDeletes.delete(t)}}},t=class{url;constructor(e){this.url=typeof e==`string`?new URL(e):e}get href(){return this.url.href}get origin(){return this.url.origin}get protocol(){return this.url.protocol}get hostname(){return this.url.hostname}get port(){return this.url.port}get pathname(){return this.url.pathname}set pathname(e){this.url.pathname=e}get search(){return this.url.search}set search(e){this.url.search=e}get searchParams(){return this.url.searchParams}get hash(){return this.url.hash}set hash(e){this.url.hash=e}toString(){return this.url.toString()}},n=class n{url;method;headers;cookies;rariUrl;ip;geo;constructor(n,r){if(n instanceof Request)this.url=n.url,this.method=n.method,this.headers=new Headers(n.headers);else{let e=typeof n==`string`?n:n.toString();this.url=e,this.method=r?.method||`GET`,this.headers=new Headers(r?.headers)}this.rariUrl=new t(this.url),this.cookies=new e(this.headers.get(`cookie`)||void 0),this.ip=r?.ip,this.geo=r?.geo}static fromRequest(e,t){return new n(e,t)}};export{n as RariRequest};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import*as e from"react";import{Component as t,Suspense as n}from"react";function r(e,t){e&&(e.notFound&&(t.notFound=!0),e.redirect&&(t.redirect=typeof e.redirect==`string`?e.redirect:e.redirect.destination),e.revalidate!==void 0&&(t.revalidate=e.revalidate),e.props&&(t.props={...t.props,...e.props}))}async function i(e,t,n,i){typeof e.getData==`function`&&r(await e.getData({params:t,searchParams:n}),i)}async function a(e,t,n,i){typeof e.getServerSideProps==`function`&&r(await e.getServerSideProps({params:t,searchParams:n}),i)}async function o(e,t,n){typeof e.getStaticProps==`function`&&r(await e.getStaticProps({params:t}),n)}async function s(e,t,n){try{let r=await import(e),s={props:{}};return await i(r,t,n,s),await a(r,t,n,s),await o(r,t,s),s}catch(t){return console.error(`[rari] Router: Failed to extract server props from ${e}:`,t),{props:{}}}}async function c(e,t,n){try{let r=await import(e);if(typeof r.generateMetadata==`function`){let e=await r.generateMetadata({params:t,searchParams:n});if(e&&typeof e==`object`)return e}return r.metadata&&typeof r.metadata==`object`?r.metadata:{}}catch(t){return console.error(`[rari] Router: Failed to extract metadata from ${e}:`,t),{}}}async function l(e){try{let t=await import(e);if(typeof t.generateStaticParams==`function`){let e=await t.generateStaticParams();if(Array.isArray(e))return e}return[]}catch(t){return console.error(`[rari] Router: Failed to extract static params from ${e}:`,t),[]}}async function u(e){try{let t=await import(e);return!!(t.getData||t.getServerSideProps||t.getStaticProps||t.generateMetadata||t.generateStaticParams)}catch{return!1}}const d=new Map;async function f(e,t,n,r=6e4){let i=`${e}:${JSON.stringify(t)}:${JSON.stringify(n)}`,a=d.get(i);if(a&&Date.now()-a.timestamp<r)return a.result;let o=await s(e,t,n);return d.set(i,{result:o,timestamp:Date.now()}),o}function p(){d.clear()}function m(e){for(let t of d.keys())t.startsWith(e)&&d.delete(t)}async function h(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 g=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 h(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 h(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. Client component registration will be delayed.`);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(){try{this.initialized=!1,this.components=[]}catch(e){console.error(`[rari] Runtime: Error during shutdown:`,e)}}async getServerStatus(){return await this.request(`/_rari/status`)}async checkHealth(){return await this.request(`/_rari/health`)}isInitialized(){return this.initialized}getBaseUrl(){return this.baseUrl}};function _(e){return new g(e)}function v({children:t,fallback:r}){return e.createElement(n,{fallback:r},t)}function y(t){return({children:n})=>e.createElement(v,{fallback:t,children:n})}var b=class extends t{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){this.props.onError?.(e,t)}render(){if(this.state.hasError){let t=()=>this.setState({hasError:!1,error:null});return this.props.fallback?this.props.fallback(this.state.error,t):e.createElement(`div`,{style:{padding:`1rem`,border:`1px solid #ef4444`,borderRadius:`0.5rem`,backgroundColor:`#fef2f2`}},[e.createElement(`h2`,{style:{color:`#dc2626`,margin:`0 0 0.5rem 0`}},`Something went wrong`),e.createElement(`p`,{style:{color:`#991b1b`,margin:`0 0 1rem 0`}},this.state.error?.message||`An unexpected error occurred`),e.createElement(`button`,{onClick:t,style:{padding:`0.5rem 1rem`,backgroundColor:`#dc2626`,color:`white`,border:`none`,borderRadius:`0.25rem`,cursor:`pointer`}},`Try again`)])}return this.props.children}};function x({children:t,fallback:n}){return e.createElement(b,{fallback:n},t)}function S(t){return({children:n})=>e.createElement(x,{fallback:t,children:n})}function C(){return e.createElement(`div`,{style:{padding:`2rem`,textAlign:`center`}},[e.createElement(`h1`,{style:{fontSize:`2rem`,margin:`0 0 1rem 0`}},`404 - Page Not Found`),e.createElement(`p`,{style:{color:`#6b7280`,margin:`0 0 1rem 0`}},`The page you're looking for doesn't exist.`),e.createElement(`button`,{onClick:()=>window.history.back(),style:{padding:`0.5rem 1rem`,backgroundColor:`#3b82f6`,color:`white`,border:`none`,borderRadius:`0.25rem`,cursor:`pointer`}},`Go back`)])}function w({size:t=`medium`}){let n={small:`1rem`,medium:`2rem`,large:`3rem`};return e.createElement(`div`,{style:{display:`inline-block`,width:n[t],height:n[t],border:`2px solid #e5e7eb`,borderTop:`2px solid #3b82f6`,borderRadius:`50%`,animation:`spin 1s linear infinite`}})}function T(){return e.createElement(`div`,{style:{display:`flex`,justifyContent:`center`,alignItems:`center`,padding:`2rem`,minHeight:`200px`}},e.createElement(w))}function E({error:t,reset:n}){return e.createElement(`div`,{style:{padding:`2rem`,border:`1px solid #ef4444`,borderRadius:`0.5rem`,backgroundColor:`#fef2f2`,textAlign:`center`}},[e.createElement(`h2`,{style:{color:`#dc2626`,margin:`0 0 1rem 0`}},`Something went wrong`),e.createElement(`p`,{style:{color:`#991b1b`,margin:`0 0 1rem 0`}},t.message||`An unexpected error occurred`),e.createElement(`button`,{onClick:n,style:{padding:`0.5rem 1rem`,backgroundColor:`#dc2626`,color:`white`,border:`none`,borderRadius:`0.25rem`,cursor:`pointer`}},`Try again`)])}if(typeof document<`u`){let e=document.createElement(`style`);e.textContent=`
|
|
2
|
+
@keyframes spin {
|
|
3
|
+
0% { transform: rotate(0deg); }
|
|
4
|
+
100% { transform: rotate(360deg); }
|
|
5
|
+
}
|
|
6
|
+
`,document.head.appendChild(e)}export{u as _,w as a,_ as c,p as d,m as f,l as g,f as h,g as i,y as l,s as m,T as n,C as o,c as p,b as r,S as s,E as t,h as u};
|
package/dist/vite.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{_ as n,c as r,d as i,f as a,g as o,h as s,i as c,m as l,p as u,u as d}from"./runtime-client-D57-4ZUQ.mjs";import{i as f,n as p,o as m,r as h,t as g}from"./constants-B68HGlJT.mjs";import{C as _,S as v,T as y,_ as b,l as ee,r as x,t as S,u as C,w}from"./regex-constants-CmOAY1_W.mjs";import{a as T,i as te,o as E,r as ne,s as D,t as re}from"./server-build-CbYBD7z1.mjs";import{t as O}from"./timer-utils-DnyOf3e6.mjs";import{t as ie}from"./routes-DAS3afh_.mjs";import{Buffer as ae}from"node:buffer";import{spawn as oe}from"node:child_process";import k,{promises as A}from"node:fs";import j from"node:path";import M from"node:process";import{fileURLToPath as N}from"node:url";import P from"node:fs/promises";import{build as se}from"rolldown";function F(e={}){let{root:t=M.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=j.join(t,n);try{return await A.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=j.join(t,n);try{await A.access(e);for(let t of i){let i=`${r}${t}`,a=j.join(e,i);try{return await A.access(a),s(`Found proxy file: ${j.join(n,i)}`),{filePath:a,exists:!0,relativePath:j.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 ce=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,le=/title\s*:\s*['"]([^'"]+)['"]/,ue=/description\s*:\s*['"]([^'"]+)['"]/,de=/keywords\s*:\s*\[([\s\S]*?)\]/,fe={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function I(e){switch(j.basename(e).replace(w,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function pe(e,t){let n=j.relative(t,j.dirname(e));return!n||n===`.`?`/`:`/${n.replace(S,`/`).split(`/`).filter(Boolean).join(`/`)}`}function L(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function R(e){try{let t=e.match(ce);if(!t)return null;let n=t[1],r={},i=n.match(le);i&&(r.title=i[1]);let a=n.match(ue);a&&(r.description=a[1]);let o=n.match(de);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(v,``)).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 z(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 B(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 V(e={}){let t={...fe,...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 A.readdir(e,{withFileTypes:!0});for(let a of i){let i=j.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&I(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=j.resolve(e,t.appDir);try{await A.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let{generateAppRouteManifest:d}=await import(`./routes-DAS3afh_.mjs`).then(e=>e.n),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=j.resolve(e,t.outDir);await A.mkdir(m,{recursive:!0});let h=j.join(m,`server`);return await A.mkdir(h,{recursive:!0}),await A.writeFile(j.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=j.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=I(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||M.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=j.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=I(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=pe(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=L(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=R(await A.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=z(await A.readFile(i,`utf-8`)),await B(j.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:j.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var me=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=O(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=O(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()}};const he=/^(["'])use client\1\s*(?:;\s*)?(?:\/\/.*)?$/;var ge=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 me({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=j.relative(M.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=await Promise.allSettled(e.map(async e=>{let t=j.relative(M.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),r=[],i=[];if(n.forEach(e=>{e.status===`fulfilled`&&e.value.success?r.push(e.value):e.status===`fulfilled`&&!e.value.success?i.push(e.value):e.status===`rejected`&&i.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),r.length>0){let e=Date.now();r.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(i.length>0){let e=Date.now();i.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});await d(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}}detectComponentType(e){try{let t=k.readFileSync(e,`utf-8`).split(`
|
|
1
|
+
import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{_ as n,c as r,d as i,f as a,g as o,h as s,i as c,m as l,p as u,u as d}from"./runtime-client-CbbckLpl.mjs";import{i as f,n as p,o as m,r as h,t as g}from"./constants-B68HGlJT.mjs";import{C as _,S as v,T as y,_ as b,l as ee,r as x,t as S,u as C,w}from"./regex-constants-CmOAY1_W.mjs";import{a as T,i as te,o as E,r as ne,s as D,t as re}from"./server-build-CbYBD7z1.mjs";import{t as O}from"./timer-utils-DnyOf3e6.mjs";import{t as ie}from"./routes-DAS3afh_.mjs";import{Buffer as ae}from"node:buffer";import{spawn as oe}from"node:child_process";import k,{promises as A}from"node:fs";import j from"node:path";import M from"node:process";import{fileURLToPath as N}from"node:url";import P from"node:fs/promises";import{build as se}from"rolldown";function F(e={}){let{root:t=M.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=j.join(t,n);try{return await A.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=j.join(t,n);try{await A.access(e);for(let t of i){let i=`${r}${t}`,a=j.join(e,i);try{return await A.access(a),s(`Found proxy file: ${j.join(n,i)}`),{filePath:a,exists:!0,relativePath:j.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 ce=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,le=/title\s*:\s*['"]([^'"]+)['"]/,ue=/description\s*:\s*['"]([^'"]+)['"]/,de=/keywords\s*:\s*\[([\s\S]*?)\]/,fe={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function I(e){switch(j.basename(e).replace(w,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function pe(e,t){let n=j.relative(t,j.dirname(e));return!n||n===`.`?`/`:`/${n.replace(S,`/`).split(`/`).filter(Boolean).join(`/`)}`}function L(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function R(e){try{let t=e.match(ce);if(!t)return null;let n=t[1],r={},i=n.match(le);i&&(r.title=i[1]);let a=n.match(ue);a&&(r.description=a[1]);let o=n.match(de);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(v,``)).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 z(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 B(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 V(e={}){let t={...fe,...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 A.readdir(e,{withFileTypes:!0});for(let a of i){let i=j.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&I(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=j.resolve(e,t.appDir);try{await A.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let{generateAppRouteManifest:d}=await import(`./routes-DAS3afh_.mjs`).then(e=>e.n),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=j.resolve(e,t.outDir);await A.mkdir(m,{recursive:!0});let h=j.join(m,`server`);return await A.mkdir(h,{recursive:!0}),await A.writeFile(j.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=j.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=I(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||M.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=j.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=I(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=pe(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=L(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=R(await A.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=z(await A.readFile(i,`utf-8`)),await B(j.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:j.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var me=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=O(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=O(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()}};const he=/^(["'])use client\1\s*(?:;\s*)?(?:\/\/.*)?$/;var ge=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 me({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=j.relative(M.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=await Promise.allSettled(e.map(async e=>{let t=j.relative(M.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),r=[],i=[];if(n.forEach(e=>{e.status===`fulfilled`&&e.value.success?r.push(e.value):e.status===`fulfilled`&&!e.value.success?i.push(e.value):e.status===`rejected`&&i.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),r.length>0){let e=Date.now();r.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(i.length>0){let e=Date.now();i.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});await d(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}}detectComponentType(e){try{let t=k.readFileSync(e,`utf-8`).split(`
|
|
2
2
|
`),n=!1;function r(e){return he.test(e.trim())}function i(e){let t=e;for(;t.includes(`/*`)&&t.includes(`*/`);){let e=t.indexOf(`/*`),n=t.indexOf(`*/`,e);if(n===-1)break;t=t.substring(0,e)+t.substring(n+2)}if(t.includes(`/*`)){let e=t.indexOf(`/*`);t=t.substring(0,e)}return t}for(let e of t){let t=e.trim();if(n){if(t.includes(`*/`)){n=!1;let e=t.substring(t.indexOf(`*/`)+2).trim();if(!e||e.startsWith(`//`))continue;let a=i(e).trim();if(!a||a.startsWith(`//`))continue;if(r(a))return`client`;break}continue}if(!(!t||t.startsWith(`//`))){if(t.includes(`/*`))if(t.includes(`*/`)){let e=i(t).trim();if(!e||e.startsWith(`//`))continue;if(r(e))return`client`;break}else{let e=t.substring(0,t.indexOf(`/*`)).trim();if(e){if(r(e))return`client`;break}n=!0;continue}if(r(t))return`client`;break}}return`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
|
|
3
3
|
• `);this.outputLog(t,`${n.length} updates:\n • ${e}`)}this.logBatch=[],this.logBatchTimer=null}outputLog(e,t){let n=`[rari] HMR:`;switch(e){case`success`:console.warn(`\x1B[32m${n}\x1B[0m ${t}`);break;case`warning`:console.warn(`\x1B[33m${n}\x1B[0m ${t}`);break;case`error`:console.error(`\x1B[31m${n}\x1B[0m ${t}`);break;default:console.warn(`${n} ${t}`);break}}dispose(){this.logBatchTimer&&(clearTimeout(this.logBatchTimer),this.flushLogs()),this.batchTimer&&=(clearTimeout(this.batchTimer),null);for(let e of this.pendingUpdates.values())clearTimeout(e);this.pendingUpdates.clear(),this.pendingFiles.clear(),this.errorHandler.dispose()}};const _e=/import\s+(\w+)\s+from\s+['"]rari\/image['"]/g,ve=/import\s+\{[^}]*\b(?:Image\s+as\s+(\w+)|Image)\b[^}]*\}\s+from\s+['"]rari\/image['"]/g,ye=/src:\s*["']([^"']+)["']/,H=/[.*+?^${}()|[\]\\]/g,U=/^[A-Z_$][\w$]*$/i,be=/width:\s*(\d+)/,xe=/quality:\s*(\d+)/,Se=/preload:\s*(true|!0)/,Ce=/preload:\s*(false|!1)/,we=/src=\{?["']([^"']+)["']\}?|src=\{([^}]+)\}/,Te=/width=\{?(\d+)\}?/,Ee=/quality=\{?(\d+)\}?/,De=/preload(?:=\{?true\}?)?/,Oe=/preload=\{?false\}?/;async function ke(e,t){try{await Be(await P.readFile(e,`utf8`),e,t)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to process ${e}:`,t)}}const Ae=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 W(e,t){try{await P.access(e)}catch{return}let n=await P.readdir(e,{withFileTypes:!0}),r=[];for(let i of n){let n=j.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`dist`)continue;r.push(W(n,t))}else i.isFile()&&w.test(i.name)&&r.push(Ae.run(()=>ke(n,t)))}await Promise.all(r)}async function je(e,t=[]){let n=new Map;try{await P.access(e),await W(e,n)}catch(t){throw t.code===`ENOENT`?Error(`Required source directory does not exist: ${e}`):t}for(let e of t)try{await P.access(e),await W(e,n)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to scan directory ${e}:`,t)}return{images:[...n.values()]}}function Me(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:e.endsWith(`.ts`)?`ts`:`js`}async function Ne(e,t,n){let r=`\0virtual:${t}`,i=await se({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 G(e){let t=new Set;for(let n of e.matchAll(_e))t.add(n[1]);for(let n of e.matchAll(ve))n[1]?t.add(n[1]):t.add(`Image`);return t}function Pe(e){return G(e)}function Fe(e){let t=e.match(ye);if(!t)return null;let n=t[1];if(!n.startsWith(`/`)&&!n.startsWith(`http`))return null;let r=e.match(be),i=r?Number.parseInt(r[1],10):void 0,a=e.match(xe),o=a?Number.parseInt(a[1],10):void 0,s=e.match(Se),c=e.match(Ce);return{src:n,width:i,quality:o,preload:!!s&&!c}}function Ie(e,t){let n=`${e.src}:${e.width??`auto`}:${e.quality??75}`;(!t.has(n)||e.preload)&&t.set(n,e)}function Le(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 Re(e,t,n){for(let r of t){if(!U.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe identifier: ${r}`);continue}let t=r.replace(H,`\\$&`),i=RegExp(`React\\.createElement\\(\\s*${t}\\s*,\\s*\\{`,`g`);for(let t of e.matchAll(i)){let r=Le(e,t.index+t[0].length-1);if(r){let e=Fe(r);e&&Ie(e,n)}}}}function ze(e){return G(e)}async function Be(e,t,n){let r=ze(e);if(r.size!==0)try{let r=await Ne(e,t,Me(t)),i=Pe(r);if(i.size===0)return;Re(r,i,n)}catch{Ve(e,r,n)}}function Ve(e,t,n){for(let r of t){if(!U.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe alias: ${r}`);continue}let t=r.replace(H,`\\$&`),i=RegExp(`<${t}\\s([^/>]+)\\/>`,`g`),a=RegExp(`<${t}\\s([^>]+)>`,`g`);for(let t of e.matchAll(i))K(t[1],n);for(let t of e.matchAll(a))K(t[1],n)}}function K(e,t){let n=e.match(we);if(!n)return;let r=n[1]||n[2];if(!r||r.includes(`{`)||!r.startsWith(`/`)&&!r.startsWith(`http`))return;let i=e.match(Te),a=i?Number.parseInt(i[1],10):void 0,o=e.match(Ee),s=o?Number.parseInt(o[1],10):void 0,c=De.test(e)&&!Oe.test(e),l=`${r}:${a??`auto`}:${s??75}`;(!t.has(l)||c)&&t.set(l,{src:r,width:a,quality:s,preload:c})}const He=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ue=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,We=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ge=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ke=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,qe=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Je=/import\s+["']\.\.?\/([^"']+)["'];?/g,Ye=/import\s*(?:\(\s*)?["']([^"']+)["']\)?/g,Xe=/export\s*\{([^}]+)\}/g,Ze=/\s+as\s+/,Qe=/export\s+default\s+(?:function|class)\s+\w+/,$e=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,q=/export\s+default\s+([^;]+)/,et=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,tt=/^['"]use client['"];?\s*$/gm,nt=/import\s+["']([^"']+)["']/g,J=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,rt=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,it=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,at=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,ot=/import\s+["']([^"']+)["']/g,st=/from(\s*)(['"])(?:\.\/vendor\/react-flight-client\/index|rari\/runtime\/vendor\/react-flight-client\/index)\.mjs\2/g,ct=/\bJSX\b/,Y=/^components\//,lt=/\{([^}]*)\}/,ut=/^['"]use client['"];?\s*\n/,dt={remotePatterns:[],localPatterns:[],deviceSizes:g,imageSizes:h,formats:p,qualityAllowlist:m,minimumCacheTTL:60,maxCacheSize:f};async function X(e){let t=import.meta.url,n=N(t),r=j.dirname(n),i=[j.join(r,`runtime`,e),j.join(r,`../runtime`,e)];for(let e of i)try{let t=await k.promises.readFile(e,`utf-8`);return e.endsWith(`.ts`)&&(t=t.replace(He,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Ue,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(We,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Ge,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(Ke,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(qe,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(Je,(e,t)=>`import "rari/${t}";`)),t}catch(t){t.code!==`ENOENT`&&t.code!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${e}:`,t)}throw Error(`Could not find ${e}. Tried: ${i.join(`, `)}`)}async function ft(){return X(`rsc-client-runtime.mjs`)}async function pt(e,t){return(await X(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function mt(){return X(`react-server-dom-shim.mjs`)}async function Z(e,t){let n=await je(j.join(e,`src`)),r={...dt,...t.images,preoptimizeManifest:n.images},i=j.join(e,`dist`),a=j.join(i,`server`);k.existsSync(a)||k.mkdirSync(a,{recursive:!0});let o=j.join(a,`image.json`);k.writeFileSync(o,JSON.stringify(r,null,2))}function Q(e,t=[]){let n=new Set;function r(e){if(!k.existsSync(e))return;let t=k.readdirSync(e,{withFileTypes:!0});for(let i of t){let t=j.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;r(t)}else if(i.isFile()&&w.test(i.name))try{E(k.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)k.existsSync(e)&&r(e);return n}function ht(e){return e}function $(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(S,`/`);if(!w.test(n)||!n.includes(`/src/`))return r.set(e,t),t;try{let n=k.readFileSync(e,`utf-8`);t.hasUseServer=D(n),t.hasUseClient=E(n),r.set(e,t)}catch{r.set(e,t)}return t}function c(t){if(t.includes(`node_modules`)||t.includes(`/rari/dist/`)||t.includes(`\\rari\\dist\\`))return!1;let n=e.projectRoot||M.cwd(),r=j.join(n,`index.html`);if(k.existsSync(r))try{let e=k.readFileSync(r,`utf-8`);for(let r of e.matchAll(Ye)){let e=r[1];if(e.startsWith(`/src/`)&&j.join(n,e.slice(1))===t)return!1}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading index.html:`,e)}let i;try{i=k.realpathSync(t)}catch{return!1}try{if(!k.existsSync(i))return!1;let e=k.readFileSync(i,`utf-8`),t=E(e);return D(e)?!1:!t}catch{return!1}}function l(e){try{let t=[],n=e.matchAll(Xe);for(let e of n){let n=e[1].split(`,`);for(let e of n){let n=e.trim().split(Ze).at(-1)?.trim();n&&t.push(n)}}(Qe.test(e)||T(e))&&t.push(`default`);let r=e.matchAll(et);for(let e of r)e[1]&&t.push(e[1]);return[...new Set(t)]}catch{return[]}}function u(e,t){if(!D(e))return e;let n=l(e);if(n.length===0)return e;let r=e;r+=`
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rari",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.13.1",
|
|
5
5
|
"description": "Runtime Accelerated Rendering Infrastructure (rari)",
|
|
6
6
|
"author": "Ryan Skinner",
|
|
7
7
|
"license": "MIT",
|
|
@@ -107,21 +107,22 @@
|
|
|
107
107
|
"react-dom": "^19.2.4"
|
|
108
108
|
},
|
|
109
109
|
"dependencies": {
|
|
110
|
-
"rolldown": "^1.0.0-rc.
|
|
110
|
+
"rolldown": "^1.0.0-rc.17"
|
|
111
111
|
},
|
|
112
112
|
"optionalDependencies": {
|
|
113
|
-
"rari-darwin-arm64": "0.
|
|
114
|
-
"rari-darwin-x64": "0.
|
|
115
|
-
"rari-linux-arm64": "0.
|
|
116
|
-
"rari-linux-x64": "0.
|
|
117
|
-
"rari-win32-
|
|
113
|
+
"rari-darwin-arm64": "0.13.1",
|
|
114
|
+
"rari-darwin-x64": "0.13.1",
|
|
115
|
+
"rari-linux-arm64": "0.13.1",
|
|
116
|
+
"rari-linux-x64": "0.13.1",
|
|
117
|
+
"rari-win32-arm64": "0.13.1",
|
|
118
|
+
"rari-win32-x64": "0.13.1"
|
|
118
119
|
},
|
|
119
120
|
"devDependencies": {
|
|
120
121
|
"@types/node": "^25.6.0",
|
|
121
122
|
"@types/react": "^19.2.14",
|
|
122
123
|
"@types/react-dom": "^19.2.3",
|
|
123
|
-
"@typescript/native-preview": "^7.0.0-dev.
|
|
124
|
-
"vite-plus": "^0.1.
|
|
124
|
+
"@typescript/native-preview": "^7.0.0-dev.20260424.2",
|
|
125
|
+
"vite-plus": "^0.1.19",
|
|
125
126
|
"@rari/deploy": "0.1.0",
|
|
126
127
|
"@rari/logger": "0.1.0"
|
|
127
128
|
},
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import*as e from"react";import{Component as t,Suspense as n}from"react";function r(e,t){e&&(e.notFound&&(t.notFound=!0),e.redirect&&(t.redirect=typeof e.redirect==`string`?e.redirect:e.redirect.destination),e.revalidate!==void 0&&(t.revalidate=e.revalidate),e.props&&(t.props={...t.props,...e.props}))}async function i(e,t,n,i){typeof e.getData==`function`&&r(await e.getData({params:t,searchParams:n}),i)}async function a(e,t,n,i){typeof e.getServerSideProps==`function`&&r(await e.getServerSideProps({params:t,searchParams:n}),i)}async function o(e,t,n){typeof e.getStaticProps==`function`&&r(await e.getStaticProps({params:t}),n)}async function s(e,t,n){try{let r=await import(e),s={props:{}};return await i(r,t,n,s),await a(r,t,n,s),await o(r,t,s),s}catch(t){return console.error(`[rari] Router: Failed to extract server props from ${e}:`,t),{props:{}}}}async function c(e,t,n){try{let r=await import(e);if(typeof r.generateMetadata==`function`){let e=await r.generateMetadata({params:t,searchParams:n});if(e&&typeof e==`object`)return e}return r.metadata&&typeof r.metadata==`object`?r.metadata:{}}catch(t){return console.error(`[rari] Router: Failed to extract metadata from ${e}:`,t),{}}}async function l(e){try{let t=await import(e);if(typeof t.generateStaticParams==`function`){let e=await t.generateStaticParams();if(Array.isArray(e))return e}return[]}catch(t){return console.error(`[rari] Router: Failed to extract static params from ${e}:`,t),[]}}async function u(e){try{let t=await import(e);return!!(t.getData||t.getServerSideProps||t.getStaticProps||t.generateMetadata||t.generateStaticParams)}catch{return!1}}const d=new Map;async function f(e,t,n,r=6e4){let i=`${e}:${JSON.stringify(t)}:${JSON.stringify(n)}`,a=d.get(i);if(a&&Date.now()-a.timestamp<r)return a.result;let o=await s(e,t,n);return d.set(i,{result:o,timestamp:Date.now()}),o}function p(){d.clear()}function m(e){for(let t of d.keys())t.startsWith(e)&&d.delete(t)}async function h(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 g=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;this.baseUrl=`${i?`https`:`http`}://${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 h(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 h(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. Client component registration will be delayed.`);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(){try{this.initialized=!1,this.components=[]}catch(e){console.error(`[rari] Runtime: Error during shutdown:`,e)}}async getServerStatus(){return await this.request(`/_rari/status`)}async checkHealth(){return await this.request(`/_rari/health`)}isInitialized(){return this.initialized}getBaseUrl(){return this.baseUrl}};function _(e){return new g(e)}function v({children:t,fallback:r}){return e.createElement(n,{fallback:r},t)}function y(t){return({children:n})=>e.createElement(v,{fallback:t,children:n})}var b=class extends t{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){this.props.onError?.(e,t)}render(){if(this.state.hasError){let t=()=>this.setState({hasError:!1,error:null});return this.props.fallback?this.props.fallback(this.state.error,t):e.createElement(`div`,{style:{padding:`1rem`,border:`1px solid #ef4444`,borderRadius:`0.5rem`,backgroundColor:`#fef2f2`}},[e.createElement(`h2`,{style:{color:`#dc2626`,margin:`0 0 0.5rem 0`}},`Something went wrong`),e.createElement(`p`,{style:{color:`#991b1b`,margin:`0 0 1rem 0`}},this.state.error?.message||`An unexpected error occurred`),e.createElement(`button`,{onClick:t,style:{padding:`0.5rem 1rem`,backgroundColor:`#dc2626`,color:`white`,border:`none`,borderRadius:`0.25rem`,cursor:`pointer`}},`Try again`)])}return this.props.children}};function x({children:t,fallback:n}){return e.createElement(b,{fallback:n},t)}function S(t){return({children:n})=>e.createElement(x,{fallback:t,children:n})}function C(){return e.createElement(`div`,{style:{padding:`2rem`,textAlign:`center`}},[e.createElement(`h1`,{style:{fontSize:`2rem`,margin:`0 0 1rem 0`}},`404 - Page Not Found`),e.createElement(`p`,{style:{color:`#6b7280`,margin:`0 0 1rem 0`}},`The page you're looking for doesn't exist.`),e.createElement(`button`,{onClick:()=>window.history.back(),style:{padding:`0.5rem 1rem`,backgroundColor:`#3b82f6`,color:`white`,border:`none`,borderRadius:`0.25rem`,cursor:`pointer`}},`Go back`)])}function w({size:t=`medium`}){let n={small:`1rem`,medium:`2rem`,large:`3rem`};return e.createElement(`div`,{style:{display:`inline-block`,width:n[t],height:n[t],border:`2px solid #e5e7eb`,borderTop:`2px solid #3b82f6`,borderRadius:`50%`,animation:`spin 1s linear infinite`}})}function T(){return e.createElement(`div`,{style:{display:`flex`,justifyContent:`center`,alignItems:`center`,padding:`2rem`,minHeight:`200px`}},e.createElement(w))}function E({error:t,reset:n}){return e.createElement(`div`,{style:{padding:`2rem`,border:`1px solid #ef4444`,borderRadius:`0.5rem`,backgroundColor:`#fef2f2`,textAlign:`center`}},[e.createElement(`h2`,{style:{color:`#dc2626`,margin:`0 0 1rem 0`}},`Something went wrong`),e.createElement(`p`,{style:{color:`#991b1b`,margin:`0 0 1rem 0`}},t.message||`An unexpected error occurred`),e.createElement(`button`,{onClick:n,style:{padding:`0.5rem 1rem`,backgroundColor:`#dc2626`,color:`white`,border:`none`,borderRadius:`0.25rem`,cursor:`pointer`}},`Try again`)])}if(typeof document<`u`){let e=document.createElement(`style`);e.textContent=`
|
|
2
|
-
@keyframes spin {
|
|
3
|
-
0% { transform: rotate(0deg); }
|
|
4
|
-
100% { transform: rotate(360deg); }
|
|
5
|
-
}
|
|
6
|
-
`,document.head.appendChild(e)}export{u as _,w as a,_ as c,p as d,m as f,l as g,f as h,g as i,y as l,s as m,T as n,C as o,c as p,b as r,S as s,E as t,h as u};
|