rari 0.15.2 → 0.15.3
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/vite.mjs +28 -28
- package/package.json +8 -8
package/dist/vite.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./api-routes-ChRr3O5-.mjs";import{i as t,n,o as r,r as i,t as a}from"./constants-De7aSsCq.mjs";import{a as o,c as s,d as c,g as l,h as u,i as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./regex-constants-Wm7xRA3u.mjs";import{a as b,i as ee,n as te,o as ne,r as re,t as x}from"./alias-resolver-CHTPYtdq.mjs";import{t as S}from"./http-C5Y9ZrK9.mjs";import{t as C}from"./timer-Duul5JHq.mjs";import{t as ie}from"./names-N6JRDeT1.mjs";import{builtinModules as ae}from"node:module";import{Buffer as oe}from"node:buffer";import{spawn as se,spawnSync as w}from"node:child_process";import T,{promises as E}from"node:fs";import D from"node:path";import O from"node:process";import{fileURLToPath as k,pathToFileURL as A}from"node:url";import j from"node:crypto";import{build as M}from"rolldown";function ce(e){return e}function N(e){return e}function le(e={}){let{root:t=O.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=D.join(t,n);try{return await E.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=D.join(t,n);try{await E.access(e);for(let t of i){let i=`${r}${t}`,a=D.join(e,i);try{return await E.access(a),s(`Found proxy file: ${D.join(n,i)}`),{filePath:a,exists:!0,relativePath:D.join(n,i)}}catch{}}}catch{}return null}return N({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 P={PAGE:`page`,LAYOUT:`layout`,LOADING:`loading`,ERROR:`error`,NOT_FOUND:`not-found`,TEMPLATE:`template`,DEFAULT:`default`,ROUTE:`route`,OG_IMAGE:`opengraph-image`,TWITTER_IMAGE:`twitter-image`,ICON:`icon`,APPLE_ICON:`apple-icon`},F={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},ue=[{pattern:F.OPTIONAL_CATCH_ALL,type:`optional-catch-all`,format:e=>`[[...${e}]]`},{pattern:F.CATCH_ALL,type:`catch-all`,format:e=>`[...${e}]`},{pattern:F.DYNAMIC,type:`dynamic`,format:e=>`[${e}]`}],de=/^\([^/]+\)$/;function fe(e){return de.test(e)}function pe(e){return e?e.replace(v,`/`).split(`/`).filter(Boolean).some(fe):!1}function me(e){for(let t of ue){let n=e.match(t.pattern);if(n)return{type:t.type,param:n[1],format:t.format}}}function he(e){let t=me(e);return t?t.format(t.param):e}function ge(e){let t=me(e);return t?{type:t.type,value:e,param:t.param}:{type:`static`,value:e}}const _e=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,ve=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,ye=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var be=class{appDir;extensions;verbose;constructor(e){this.appDir=D.resolve(e.appDir),this.extensions=e.extensions||[`.tsx`,`.jsx`,`.ts`,`.js`],this.verbose=e.verbose||!1}async generateManifest(){this.verbose&&console.warn(`[rari] Router: Scanning app directory: ${this.appDir}`);let e=[],t=[],n=[],r=[],i=[],a=[],o=[],s=[];await this.scanDirectory(``,e,t,n,r,i,a,o,s);for(let o of[t,n,r,i,a,s])this.finalizeGroupEntries(e,o);return this.assertNoDuplicateRoutes(e),this.assertNoDuplicateRoutes(o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} templates`),console.warn(`[rari] Router: Found ${o.length} API routes`),console.warn(`[rari] Router: Found ${s.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,templates:this.sortTemplates(a),apiRoutes:this.sortApiRoutes(o),ogImages:s,generated:new Date().toISOString()}}finalizeGroupEntries(e,t){for(let n=t.length-1;n>=0;n--){let r=t[n],i=D.dirname(r.filePath).replace(v,`/`);if(!pe(i))continue;let a=e.filter(e=>{let t=D.dirname(e.filePath).replace(v,`/`);return t===i||t.startsWith(`${i}/`)}).map(e=>e.path);if(a.length===0){t.splice(n,1);continue}let o=Array.from(new Set(a)).sort();r.path=o[0],o.length>1&&(r.additionalPaths=o.slice(1))}}assertNoDuplicateRoutes(e){let t=new Map;for(let n of e){let e=t.get(n.path);if(e)throw Error(`[rari] Route conflict: path '${n.path}' is defined by both '${e}' and '${n.filePath}'.`);t.set(n.path,n.filePath)}}async scanDirectory(e,t,n,r,i,a,o,s,c){let l=D.join(this.appDir,e),u;try{u=await E.readdir(l)}catch{return}let d=[],f=[];for(let e of u){let t=D.join(l,e),n=await E.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&f.push(e):n.isFile()&&d.push(e)}await this.processSpecialFiles(e,d,t,n,r,i,a,o,s,c);for(let l of f){let u=e?D.join(e,l):l;await this.scanDirectory(u,t,n,r,i,a,o,s,c)}}async processSpecialFiles(e,t,n,r,i,a,o,s,c,l){let u=this.pathToRoute(e),d=this.findFile(t,P.PAGE);if(d){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:u,filePath:D.join(e,d).replace(v,`/`),segments:t,params:r,isDynamic:r.length>0})}let f=this.findFile(t,P.LAYOUT);if(f){let t=this.getParentPath(e);r.push({path:u,filePath:D.join(e,f).replace(v,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let p=this.findFile(t,P.LOADING);if(p){let t=this.generateComponentId(u,`loading`);i.push({path:u,filePath:D.join(e,p).replace(v,`/`),componentId:t})}let m=this.findFile(t,P.ERROR);m&&a.push({path:u,filePath:D.join(e,m).replace(v,`/`)});let h=this.findFile(t,P.NOT_FOUND);h&&o.push({path:u,filePath:D.join(e,h).replace(v,`/`)});let g=this.findFile(t,P.TEMPLATE);if(g){let t=this.getParentPath(e);s.push({path:u,filePath:D.join(e,g).replace(v,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let _=this.findFile(t,P.OG_IMAGE);if(_){let t=D.join(e,_).replace(v,`/`),n=D.join(this.appDir,t),r,i,a;try{let e=await E.readFile(n,`utf-8`),t=e.match(_e);t&&(r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10));let o=e.match(ve);o&&(a=o[1])}catch{}l.push({path:u,filePath:t,width:r,height:i,contentType:a})}let y=this.findFile(t,P.ROUTE);if(y){let t=await this.processApiRouteFile(e,y);c.push(t)}}findFile(e,t){for(let n of this.extensions){let r=`${t}${n}`;if(e.includes(r))return r}}pathToRoute(e){return e?`/${e.replace(v,`/`).split(`/`).filter(Boolean).filter(e=>!fe(e)).map(he).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(c).filter(Boolean).filter(e=>!fe(e)).map(ge):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(c).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`_`)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}sortTemplates(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=D.join(this.appDir,e),n=await E.readFile(t,`utf-8`),r=[];for(let e of ye){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||i.test(n))&&r.push(e)}return r}async processApiRouteFile(e,t){let n=D.join(e,t).replace(v,`/`),r=this.pathToRoute(e),i=this.parseRouteSegments(e),a=this.extractParams(i),o=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:i,params:a,isDynamic:a.length>0,methods:o}}};async function xe(e,t={}){return new be({appDir:e,...t}).generateManifest()}const Se=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,Ce=/title\s*:\s*['"]([^'"]+)['"]/,we=/description\s*:\s*['"]([^'"]+)['"]/,Te=/keywords\s*:\s*\[([\s\S]*?)\]/,Ee={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function De(e){switch(D.basename(e).replace(u,``)){case`page`:return`page`;case`layout`:return`layout`;case`template`:return`template`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function Oe(e){return/^\([^/]+\)$/.test(e)}function ke(e){if(!e||e===`/`)return`/`;let t=e.replace(v,`/`).split(`/`).filter(e=>!!e&&!Oe(e));return t.length>0?`/${t.join(`/`)}`:`/`}function Ae(e,t){let n=D.relative(t,D.dirname(e));return!n||n===`.`?`/`:ke(`/${n.replace(v,`/`).split(`/`).filter(Boolean).join(`/`)}`)}function je(e,t,n){if(t===`page`)return[e];let r=`${e}${e===`/`?``:`/`}`,i=n.filter(t=>t===e||t.startsWith(r));return i.length>0?i:[e]}function Me(e){try{let t=e.match(Se);if(!t)return null;let n=t[1],r={},i=n.match(Ce);i&&(r.title=i[1]);let a=n.match(we);a&&(r.description=a[1]);let o=n.match(Te);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(h,``)).filter(Boolean));for(let e of[`author`,`viewport`,`themeColor`,`robots`,`openGraph`,`twitter`]){let t=RegExp(`${e}\\s*:\\s*['"]([^'"]+)['"]`,`m`),i=n.match(t);i&&(r[e]=i[1])}return Object.keys(r).length>0?r:null}catch(e){return console.error(`[rari] Router: Failed to extract metadata:`,e),null}}function Ne(e){let t=[];for(let n of[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]){let r=RegExp(`export\\s+(?:async\\s+)?function\\s+${n}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${n}\\s*=`);(r.test(e)||i.test(e))&&t.push(n)}return t}async function Pe(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 Fe(e={}){let t={...Ee,...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 E.readdir(e,{withFileTypes:!0});for(let a of i){let i=D.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&De(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=D.resolve(e,t.appDir);try{await E.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let d=await xe(c,{extensions:t.extensions}),f=JSON.stringify(d),p=D.resolve(e,t.outDir);await E.mkdir(p,{recursive:!0});let m=D.join(p,`server`);return await E.mkdir(m,{recursive:!0}),await E.writeFile(D.join(m,`routes.json`),f,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),f}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=D.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=De(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 N({name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`The above dynamic import cannot be analyzed`)&&e.includes(`packages/rari/dist/`)||t(e,n)}},async writeBundle(){let e=u||O.cwd();n=await c(e,!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=D.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=De(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=Ae(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=je(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=Me(await E.readFile(i,`utf-8`));e&&(m=e,h=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{g=Ne(await E.readFile(i,`utf-8`)),await Pe(D.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:D.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear();let e=u||O.cwd(),n=D.resolve(e,t.outDir,`server`),i=D.join(n,`routes.json`);try{let e=await E.readFile(i,`utf-8`),t=JSON.parse(e),r=!1;for(let e of t.routes){if(!e.isDynamic)continue;let t=e.componentId;if(!t)continue;let i=t.startsWith(`app/`)?t.slice(4):t,a=D.resolve(n,`app`,`${i}.js`);try{let t=await import(a);if(typeof t.generateStaticParams==`function`){let n=await t.generateStaticParams();Array.isArray(n)&&n.length>0&&(e.staticParams=n,r=!0)}}catch{}}r&&await E.writeFile(i,JSON.stringify(t),`utf-8`)}catch{}}})}function Ie(e,t){let n=t.indexOf(`var boundCache = new WeakMap();`),r=t.indexOf(`function createBoundServerReference`,n);if(n===-1||r===-1)throw Error(`Failed to locate edge client form-action helpers for browser patch`);let i=t.slice(n,r).replace(`return {
|
|
1
|
+
import{t as e}from"./api-routes-ChRr3O5-.mjs";import{i as t,n,o as r,r as i,t as a}from"./constants-De7aSsCq.mjs";import{a as o,c as s,d as c,g as l,h as u,i as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./regex-constants-Wm7xRA3u.mjs";import{a as b,i as ee,n as te,o as ne,r as x,t as S}from"./alias-resolver-CHTPYtdq.mjs";import{t as re}from"./http-C5Y9ZrK9.mjs";import{t as C}from"./timer-Duul5JHq.mjs";import{t as ie}from"./names-N6JRDeT1.mjs";import{builtinModules as ae,createRequire as w}from"node:module";import{Buffer as oe}from"node:buffer";import{spawn as se,spawnSync as T}from"node:child_process";import E,{promises as D}from"node:fs";import O from"node:path";import k from"node:process";import{fileURLToPath as A,pathToFileURL as j}from"node:url";import M from"node:crypto";import{build as N}from"rolldown";function ce(e){return e}function P(e){return e}function le(e={}){let{root:t=k.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=O.join(t,n);try{return await D.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=O.join(t,n);try{await D.access(e);for(let t of i){let i=`${r}${t}`,a=O.join(e,i);try{return await D.access(a),s(`Found proxy file: ${O.join(n,i)}`),{filePath:a,exists:!0,relativePath:O.join(n,i)}}catch{}}}catch{}return null}return P({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 F={PAGE:`page`,LAYOUT:`layout`,LOADING:`loading`,ERROR:`error`,NOT_FOUND:`not-found`,TEMPLATE:`template`,DEFAULT:`default`,ROUTE:`route`,OG_IMAGE:`opengraph-image`,TWITTER_IMAGE:`twitter-image`,ICON:`icon`,APPLE_ICON:`apple-icon`},ue={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},de=[{pattern:ue.OPTIONAL_CATCH_ALL,type:`optional-catch-all`,format:e=>`[[...${e}]]`},{pattern:ue.CATCH_ALL,type:`catch-all`,format:e=>`[...${e}]`},{pattern:ue.DYNAMIC,type:`dynamic`,format:e=>`[${e}]`}],fe=/^\([^/]+\)$/;function pe(e){return fe.test(e)}function me(e){return e?e.replace(v,`/`).split(`/`).filter(Boolean).some(pe):!1}function he(e){for(let t of de){let n=e.match(t.pattern);if(n)return{type:t.type,param:n[1],format:t.format}}}function ge(e){let t=he(e);return t?t.format(t.param):e}function _e(e){let t=he(e);return t?{type:t.type,value:e,param:t.param}:{type:`static`,value:e}}const ve=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,ye=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,be=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var xe=class{appDir;extensions;verbose;constructor(e){this.appDir=O.resolve(e.appDir),this.extensions=e.extensions||[`.tsx`,`.jsx`,`.ts`,`.js`],this.verbose=e.verbose||!1}async generateManifest(){this.verbose&&console.warn(`[rari] Router: Scanning app directory: ${this.appDir}`);let e=[],t=[],n=[],r=[],i=[],a=[],o=[],s=[];await this.scanDirectory(``,e,t,n,r,i,a,o,s);for(let o of[t,n,r,i,a,s])this.finalizeGroupEntries(e,o);return this.assertNoDuplicateRoutes(e),this.assertNoDuplicateRoutes(o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} templates`),console.warn(`[rari] Router: Found ${o.length} API routes`),console.warn(`[rari] Router: Found ${s.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,templates:this.sortTemplates(a),apiRoutes:this.sortApiRoutes(o),ogImages:s,generated:new Date().toISOString()}}finalizeGroupEntries(e,t){for(let n=t.length-1;n>=0;n--){let r=t[n],i=O.dirname(r.filePath).replace(v,`/`);if(!me(i))continue;let a=e.filter(e=>{let t=O.dirname(e.filePath).replace(v,`/`);return t===i||t.startsWith(`${i}/`)}).map(e=>e.path);if(a.length===0){t.splice(n,1);continue}let o=Array.from(new Set(a)).sort();r.path=o[0],o.length>1&&(r.additionalPaths=o.slice(1))}}assertNoDuplicateRoutes(e){let t=new Map;for(let n of e){let e=t.get(n.path);if(e)throw Error(`[rari] Route conflict: path '${n.path}' is defined by both '${e}' and '${n.filePath}'.`);t.set(n.path,n.filePath)}}async scanDirectory(e,t,n,r,i,a,o,s,c){let l=O.join(this.appDir,e),u;try{u=await D.readdir(l)}catch{return}let d=[],f=[];for(let e of u){let t=O.join(l,e),n=await D.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&f.push(e):n.isFile()&&d.push(e)}await this.processSpecialFiles(e,d,t,n,r,i,a,o,s,c);for(let l of f){let u=e?O.join(e,l):l;await this.scanDirectory(u,t,n,r,i,a,o,s,c)}}async processSpecialFiles(e,t,n,r,i,a,o,s,c,l){let u=this.pathToRoute(e),d=this.findFile(t,F.PAGE);if(d){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:u,filePath:O.join(e,d).replace(v,`/`),segments:t,params:r,isDynamic:r.length>0})}let f=this.findFile(t,F.LAYOUT);if(f){let t=this.getParentPath(e);r.push({path:u,filePath:O.join(e,f).replace(v,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let p=this.findFile(t,F.LOADING);if(p){let t=this.generateComponentId(u,`loading`);i.push({path:u,filePath:O.join(e,p).replace(v,`/`),componentId:t})}let m=this.findFile(t,F.ERROR);m&&a.push({path:u,filePath:O.join(e,m).replace(v,`/`)});let h=this.findFile(t,F.NOT_FOUND);h&&o.push({path:u,filePath:O.join(e,h).replace(v,`/`)});let g=this.findFile(t,F.TEMPLATE);if(g){let t=this.getParentPath(e);s.push({path:u,filePath:O.join(e,g).replace(v,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let _=this.findFile(t,F.OG_IMAGE);if(_){let t=O.join(e,_).replace(v,`/`),n=O.join(this.appDir,t),r,i,a;try{let e=await D.readFile(n,`utf-8`),t=e.match(ve);t&&(r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10));let o=e.match(ye);o&&(a=o[1])}catch{}l.push({path:u,filePath:t,width:r,height:i,contentType:a})}let y=this.findFile(t,F.ROUTE);if(y){let t=await this.processApiRouteFile(e,y);c.push(t)}}findFile(e,t){for(let n of this.extensions){let r=`${t}${n}`;if(e.includes(r))return r}}pathToRoute(e){return e?`/${e.replace(v,`/`).split(`/`).filter(Boolean).filter(e=>!pe(e)).map(ge).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(c).filter(Boolean).filter(e=>!pe(e)).map(_e):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(c).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`_`)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}sortTemplates(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=O.join(this.appDir,e),n=await D.readFile(t,`utf-8`),r=[];for(let e of be){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||i.test(n))&&r.push(e)}return r}async processApiRouteFile(e,t){let n=O.join(e,t).replace(v,`/`),r=this.pathToRoute(e),i=this.parseRouteSegments(e),a=this.extractParams(i),o=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:i,params:a,isDynamic:a.length>0,methods:o}}};async function Se(e,t={}){return new xe({appDir:e,...t}).generateManifest()}const Ce=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,we=/title\s*:\s*['"]([^'"]+)['"]/,Te=/description\s*:\s*['"]([^'"]+)['"]/,Ee=/keywords\s*:\s*\[([\s\S]*?)\]/,De={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function Oe(e){switch(O.basename(e).replace(u,``)){case`page`:return`page`;case`layout`:return`layout`;case`template`:return`template`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function ke(e){return/^\([^/]+\)$/.test(e)}function Ae(e){if(!e||e===`/`)return`/`;let t=e.replace(v,`/`).split(`/`).filter(e=>!!e&&!ke(e));return t.length>0?`/${t.join(`/`)}`:`/`}function je(e,t){let n=O.relative(t,O.dirname(e));return!n||n===`.`?`/`:Ae(`/${n.replace(v,`/`).split(`/`).filter(Boolean).join(`/`)}`)}function Me(e,t,n){if(t===`page`)return[e];let r=`${e}${e===`/`?``:`/`}`,i=n.filter(t=>t===e||t.startsWith(r));return i.length>0?i:[e]}function Ne(e){try{let t=e.match(Ce);if(!t)return null;let n=t[1],r={},i=n.match(we);i&&(r.title=i[1]);let a=n.match(Te);a&&(r.description=a[1]);let o=n.match(Ee);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(h,``)).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 Pe(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 Fe(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 Ie(e={}){let t={...De,...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 D.readdir(e,{withFileTypes:!0});for(let a of i){let i=O.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&Oe(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=O.resolve(e,t.appDir);try{await D.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let d=await Se(c,{extensions:t.extensions}),f=JSON.stringify(d),p=O.resolve(e,t.outDir);await D.mkdir(p,{recursive:!0});let m=O.join(p,`server`);return await D.mkdir(m,{recursive:!0}),await D.writeFile(O.join(m,`routes.json`),f,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),f}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=O.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=Oe(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 P({name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`The above dynamic import cannot be analyzed`)&&e.includes(`packages/rari/dist/`)||t(e,n)}},async writeBundle(){let e=u||k.cwd();n=await c(e,!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=O.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=Oe(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=je(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=Me(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=Ne(await D.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=Pe(await D.readFile(i,`utf-8`)),await Fe(O.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:O.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear();let e=u||k.cwd(),n=O.resolve(e,t.outDir,`server`),i=O.join(n,`routes.json`);try{let e=await D.readFile(i,`utf-8`),t=JSON.parse(e),r=!1;for(let e of t.routes){if(!e.isDynamic)continue;let t=e.componentId;if(!t)continue;let i=t.startsWith(`app/`)?t.slice(4):t,a=O.resolve(n,`app`,`${i}.js`);try{let t=await import(a);if(typeof t.generateStaticParams==`function`){let n=await t.generateStaticParams();Array.isArray(n)&&n.length>0&&(e.staticParams=n,r=!0)}}catch{}}r&&await D.writeFile(i,JSON.stringify(t),`utf-8`)}catch{}}})}function Le(e,t){let n=t.indexOf(`var boundCache = new WeakMap();`),r=t.indexOf(`function createBoundServerReference`,n);if(n===-1||r===-1)throw Error(`Failed to locate edge client form-action helpers for browser patch`);let i=t.slice(n,r).replace(`return {
|
|
2
2
|
name: referenceClosure,
|
|
3
3
|
method: "POST",
|
|
4
4
|
encType: "multipart/form-data",
|
|
@@ -25,8 +25,8 @@ import{t as e}from"./api-routes-ChRr3O5-.mjs";import{i as t,n,o as r,r as i,t as
|
|
|
25
25
|
originalBind: reference.bind,
|
|
26
26
|
bound: bound
|
|
27
27
|
});
|
|
28
|
-
}`,i)}function Le(e){return e.replace(/(?<!\$)\$FORM_ACTION/g,()=>`$$FORM_ACTION`).replace(/(?<!\$)\$IS_SIGNATURE_EQUAL/g,()=>`$$IS_SIGNATURE_EQUAL`)}const Re=/^\.\.(?:[/\\]|$)/;function I(e,t=8){return j.createHash(`sha256`).update(e).digest(`hex`).slice(0,t)}function L(e,t=O.cwd()){let n=D.isAbsolute(e)?e:D.resolve(t,e),r=D.relative(t,n);return(Re.test(r)||D.isAbsolute(r)?e:r).replace(v,`/`)}function ze(e){return e.replace(u,``).replace(p,`_`).replace(f,``)}function R(e,t=O.cwd()){let n=L(e,t);return`${ze(n)}_${I(n)}`}const Be=new Set([`return`,`throw`,`case`,`typeof`,`instanceof`,`new`,`delete`,`void`,`in`,`of`]),Ve=8232,He=8233;function z(e){return e===32||e===9||e===13||e===10||e===Ve||e===He||e===65279}function B(e){return e===13||e===10||e===Ve||e===He}function V(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Ue(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function We(e,t,n){for(;t<n&&z(e.charCodeAt(t));)t++;return t}function H(e,t,n){for(;t<n;){let r=We(e,t,n);if(r!==t){t=r;continue}let i=e.charCodeAt(t);if(i===47&&e.charCodeAt(t+1)===47){t=Ge(e,t,n);continue}if(i===47&&e.charCodeAt(t+1)===42){t=Ke(e,t,n);continue}break}return t}function Ge(e,t,n){for(;t<n&&!B(e.charCodeAt(t));)t++;return t}function Ke(e,t,n){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;return t+2}function U(e,t,n,r){for(t++;t<n;){let n=e.charCodeAt(t);if(n===92){t+=2;continue}if(n===r)return t+1;t++}return t}function qe(e,t,n){t++;let r=e.charCodeAt(t)===47;for(r&&t++;t<n;){let n=e.charCodeAt(t);if(V(n)||n===46||n===45)t++;else break}let i=+!r;for(;t<n&&i>0;){let a=e.charCodeAt(t);if(a===39||a===34||a===96){t=U(e,t,n,a);continue}if(a===123){t++;let r=1;for(;t<n&&r>0;){let i=e.charCodeAt(t);if(i===39||i===34||i===96){t=U(e,t,n,i);continue}i===123&&r++,i===125&&r--,t++}continue}if(a===47&&e.charCodeAt(t+1)===62){i--,t+=2;continue}if(a===62){t++,r&&i--;continue}if(a===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||Ue(r)){for(r===47?(i--,t++):r!==33&&i++,t++;t<n;){let n=e.charCodeAt(t);if(V(n)||n===46||n===45)t++;else break}continue}t++;continue}t++}return t}function Je(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function W(e,t,n){if(t+n.length>e.length)return!1;for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;let r=t>0?e.charCodeAt(t-1):-1,i=e.charCodeAt(t+n.length);return!(r!==-1&&V(r)||i!==void 0&&V(i))}function Ye(e,t,n){let r=H(e,t,n);if(r>=n)return null;let i=e.charCodeAt(r);if(i!==39&&i!==34)return null;let a=r+1,o=U(e,r,n,i);return o<=a?null:{source:e.slice(a,o-1),end:o}}function Xe(e,t,n){if(!W(e,t,`import`))return{sources:[],end:t+6};let r=t+6;if(r=H(e,r,n),W(e,r,`type`)&&(r=H(e,r+4,n)),e.charCodeAt(r)===46){for(r++;r<n&&V(e.charCodeAt(r));)r++;for(;r<n&&e.charCodeAt(r)===46;)for(r++;r<n&&V(e.charCodeAt(r));)r++;return{sources:[],end:r}}if(e.charCodeAt(r)===40){r++;let t=Ye(e,r,n);return t?{sources:[t.source],end:t.end}:{sources:[],end:r}}let i=Ye(e,r,n);if(i)return{sources:[i.source],end:i.end};let a=0;for(;r<n&&(r=H(e,r,n),!(r>=n));){let t=e.charCodeAt(r);if(a===0&&W(e,r,`from`)){let t=Ye(e,r+4,n);if(t)return{sources:[t.source],end:t.end};break}if(t===39||t===34||t===96){r=U(e,r,n,t);continue}t===123||t===40||t===91?a++:(t===125||t===41||t===93)&&(a=Math.max(0,a-1)),r++}return{sources:[],end:r}}function Ze(e,t){return e.charCodeAt(t)===101&&e.charCodeAt(t+1)===120&&e.charCodeAt(t+2)===112&&e.charCodeAt(t+3)===111&&e.charCodeAt(t+4)===114&&e.charCodeAt(t+5)===116}function Qe(e,t){return e.charCodeAt(t)===100&&e.charCodeAt(t+1)===101&&e.charCodeAt(t+2)===102&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===117&&e.charCodeAt(t+5)===108&&e.charCodeAt(t+6)===116}function G(e){let t={hasUseClient:!1,hasUseServer:!1},n=!1,r=!1,i=!1,a=!1,o=[],s=!0,c=!1,l=0,u=e.length;for(;l<u;){let d=e.charCodeAt(l);if(z(d)){l++;continue}if(d===47&&e.charCodeAt(l+1)===47){l=Ge(e,l,u);continue}if(d===47&&e.charCodeAt(l+1)===42){l=Ke(e,l,u);continue}if(s&&(d===39||d===34)){let i=l+1,a=U(e,l,u,d);if(a<=i){s=!1,l++;continue}let o=a-1-i,f=o===10&&Je(e,i,`use client`),p=o===10&&Je(e,i,`use server`);c||(c=!0,n=f,r=p),f&&(t.hasUseClient=!0),p&&(t.hasUseServer=!0);let m=a,h=!1;for(;m<u;){let t=e.charCodeAt(m);if(z(t)&&!B(t)){m++;continue}if(B(t)||t===59){h=!0,l=m+1;break}if(t===47&&e.charCodeAt(m+1)===47){m=Ge(e,m,u);continue}if(t===47&&e.charCodeAt(m+1)===42){m=Ke(e,m,u);continue}s=!1,h=!1;break}if(!h){m>=u&&(s=!1),l=s?a:m;continue}continue}if(s=!1,d===39||d===34||d===96){l=U(e,l,u,d);continue}if(d===47&&e.charCodeAt(l+1)!==47&&e.charCodeAt(l+1)!==42&&rt(e,l)){l=it(e,l,u);continue}if(d===60){let t=e.charCodeAt(l+1);if(t===47||t===46||t===62||Ue(t)){l=qe(e,l,u);continue}l++;continue}if(W(e,l,`import`)){let t=Xe(e,l,u);for(let e of t.sources)o.push(e);l=t.end;continue}if(Ze(e,l)){let t=l+6;if(t<u){let n=e.charCodeAt(t);if(z(n)||n===123||n===47&&(e.charCodeAt(t+1)===47||e.charCodeAt(t+1)===42)){let n=H(e,t,u);if(Qe(e,n)){i=!0,a=!0;let r=n+7;if(r>=u||!V(e.charCodeAt(r))){l=t;continue}}if(e.charCodeAt(n)===123){let t=n+1;for(;t<u&&(t=H(e,t,u),e.charCodeAt(t)!==125);){let n=t;for(;t<u&&V(e.charCodeAt(t));)t++;let r=t-n;if(r===0)break;t=H(e,t,u);let o=!1;if(e.charCodeAt(t)===97&&e.charCodeAt(t+1)===115){o=!0;let n=t+2;if(n<u&&!V(e.charCodeAt(n))){t=H(e,n,u);let r=t;for(;t<u&&V(e.charCodeAt(t));)t++;t-r===7&&Qe(e,r)&&(i=!0,a=!0)}}if(!o&&r===7&&Qe(e,n)&&(i=!0,a=!0),e.charCodeAt(t)===44){t++;continue}if(e.charCodeAt(t)===125)break;t++}}else(W(e,n,`async`)||W(e,n,`function`)||W(e,n,`class`))&&(a=!0)}}}l++}return{directives:t,topLevelUseClient:n,topLevelUseServer:r,hasDefaultExport:i,hasComponentExport:a,importSources:[...new Set(o)]}}function $e(e){return G(e).hasDefaultExport}function et(e){return e===40||e===91||e===123||e===44||e===59||e===61||e===58||e===63||e===33||e===43||e===45||e===42||e===37||e===38||e===124||e===94||e===126||e===60||e===62}function tt(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(z(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}break}if(n<0||!V(e.charCodeAt(n)))return;let r=n;for(;n>=0&&V(e.charCodeAt(n));)n--;return e.slice(n+1,r+1)}function nt(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(z(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return-1;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}return t}return-1}function rt(e,t){let n=nt(e,t);if(n===-1||et(n))return!0;let r=tt(e,t);return r?Be.has(r):!1}function it(e,t,n){t++;let r=!1;for(;t<n;){let i=e.charCodeAt(t);if(i===92){t+=2;continue}if(r){i===93&&(r=!1),t++;continue}if(i===91){r=!0,t++;continue}if(i===47){for(t++;t<n&&V(e.charCodeAt(t));)t++;return t}if(B(i))return t;t++}return t}const at=new Set([`node_modules`,`.git`,`.cache`,`dist`]);function ot(e,t){let n=new Set,r=e=>{if(!T.existsSync(e))return;let i=T.readdirSync(e,{withFileTypes:!0});for(let a of i){let i=D.join(e,a.name);if(a.isDirectory()){if(at.has(a.name))continue;r(i)}else if(a.isFile()&&u.test(a.name)){if(n.has(i))continue;n.add(i),t(i)}}};for(let t of e)t&&T.existsSync(t)&&r(t)}function st(e){let t=[];return ot(e,e=>{t.push(e)}),t}function ct(e,t=[]){let n=[e],r=D.resolve(e);for(let e of t){if(!e)continue;let t=D.resolve(e);if(t===r)continue;let i=D.relative(r,t);if(!(i===``||!i.startsWith(`..`)&&!D.isAbsolute(i)))try{T.statSync(e).isDirectory()&&n.push(e)}catch{}}return n}const lt=new Set(ae);function K(e){return lt.has(e)}function ut(e){for(let t of e.importSources)if(t.startsWith(`node:`)||K(t))return!0;return!1}function dt(e,t=lt){let n=[];for(let r of e)!r.startsWith(`.`)&&!r.startsWith(`/`)&&!r.startsWith(`@/`)&&!r.startsWith(`node:`)&&!t.has(r)&&n.push(r);return[...new Set(n)]}function ft(e){let t=[];for(let n of e)(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`@/`))&&t.push(n);return t}function q(e){try{return T.realpathSync(e)}catch{return D.resolve(e)}}function pt(e,t){e.delete(t);try{e.delete(T.realpathSync(t))}catch{e.delete(D.resolve(t))}}function mt(e,t){let n=[];for(let r of st(e))try{t.get(r).directives.hasUseClient&&n.push(r)}catch{}return n}var ht=class{cache=new Map;get(e,t){let n=q(e),r=this.cache.get(n);if(t!==void 0){if(r&&r.source===t)return r.analysis}else if(r){let e=this.readMtimeMs(n);if(e>=0&&r.mtimeMs===e)return r.analysis}t===void 0&&(t=T.readFileSync(n,`utf-8`));let i=this.readMtimeMs(n),a=G(t);return this.cache.set(n,{mtimeMs:i,source:t,analysis:a}),a}getSource(e){return this.get(e),this.cache.get(q(e)).source}invalidate(e){pt(this.cache,e)}clear(){this.cache.clear()}readMtimeMs(e){try{return T.statSync(e).mtimeMs}catch{return-1}}},gt=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer=C(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=C(this.resetTimer)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.reset()}},_t=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 gt({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=D.relative(O.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=this.collectDependentPageComponents(e);for(let e of n)this.serverComponentBuilder.invalidateBuildCacheFor(e);let r=[...e,...n],i=await Promise.allSettled(r.map(async e=>{let t=D.relative(O.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),a=[],o=[];if(i.forEach(e=>{e.status===`fulfilled`&&e.value.success?a.push(e.value):e.status===`fulfilled`&&!e.value.success?o.push(e.value):e.status===`rejected`&&o.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),a.length>0){let e=Date.now();a.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(o.length>0){let e=Date.now();o.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});await S(n);let r=await n.text(),i;try{i=JSON.parse(r)}catch(e){throw Error(`Failed to parse server response (status ${n.status}): ${e instanceof Error?e.message:String(e)}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`)}if(!i||typeof i!=`object`)throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);let a=i;if(!a.success)throw Error(a.message||a.error||`Component reload failed`)}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}collectDependentPageComponents(e){let t=this.serverComponentBuilder.getImportGraph(),n=new Set,r=new Set,i=a=>{if(r.has(a))return;r.add(a);let o=t.get(a);if(o)for(let t of o)(t.includes(`/app/`)||t.includes(`\\app\\`))&&!e.includes(t)&&n.add(t),i(t)};for(let t of e)i(t);return[...n]}detectComponentType(e){try{return this.serverComponentBuilder.getModuleAnalysis(e).topLevelUseClient?`client`:`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
|
|
29
|
-
• `);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
|
|
28
|
+
}`,i)}function Re(e){return e.replace(/(?<!\$)\$FORM_ACTION/g,()=>`$$FORM_ACTION`).replace(/(?<!\$)\$IS_SIGNATURE_EQUAL/g,()=>`$$IS_SIGNATURE_EQUAL`)}function I(e,t=8){return M.createHash(`sha256`).update(e).digest(`hex`).slice(0,t)}function L(e,t=k.cwd()){let n=O.isAbsolute(e)?e:O.resolve(t,e),r=O.relative(t,n);return O.isAbsolute(r)?n.replace(v,`/`):r.replace(v,`/`)}function ze(e){return e.replace(u,``).replace(p,`_`).replace(f,``)}function R(e,t=k.cwd()){let n=L(e,t);return`${ze(n)}_${I(n)}`}const Be=new Set([`return`,`throw`,`case`,`typeof`,`instanceof`,`new`,`delete`,`void`,`in`,`of`]),Ve=8232,He=8233;function z(e){return e===32||e===9||e===13||e===10||e===Ve||e===He||e===65279}function B(e){return e===13||e===10||e===Ve||e===He}function V(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Ue(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function We(e,t,n){for(;t<n&&z(e.charCodeAt(t));)t++;return t}function H(e,t,n){for(;t<n;){let r=We(e,t,n);if(r!==t){t=r;continue}let i=e.charCodeAt(t);if(i===47&&e.charCodeAt(t+1)===47){t=Ge(e,t,n);continue}if(i===47&&e.charCodeAt(t+1)===42){t=Ke(e,t,n);continue}break}return t}function Ge(e,t,n){for(;t<n&&!B(e.charCodeAt(t));)t++;return t}function Ke(e,t,n){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;return t+2}function U(e,t,n,r){for(t++;t<n;){let n=e.charCodeAt(t);if(n===92){t+=2;continue}if(n===r)return t+1;t++}return t}function qe(e,t,n){t++;let r=e.charCodeAt(t)===47;for(r&&t++;t<n;){let n=e.charCodeAt(t);if(V(n)||n===46||n===45)t++;else break}let i=+!r;for(;t<n&&i>0;){let a=e.charCodeAt(t);if(a===39||a===34||a===96){t=U(e,t,n,a);continue}if(a===123){t++;let r=1;for(;t<n&&r>0;){let i=e.charCodeAt(t);if(i===39||i===34||i===96){t=U(e,t,n,i);continue}i===123&&r++,i===125&&r--,t++}continue}if(a===47&&e.charCodeAt(t+1)===62){i--,t+=2;continue}if(a===62){t++,r&&i--;continue}if(a===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||Ue(r)){for(r===47?(i--,t++):r!==33&&i++,t++;t<n;){let n=e.charCodeAt(t);if(V(n)||n===46||n===45)t++;else break}continue}t++;continue}t++}return t}function Je(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function W(e,t,n){if(t+n.length>e.length)return!1;for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;let r=t>0?e.charCodeAt(t-1):-1,i=e.charCodeAt(t+n.length);return!(r!==-1&&V(r)||i!==void 0&&V(i))}function G(e,t,n){let r=H(e,t,n);if(r>=n)return null;let i=e.charCodeAt(r);if(i!==39&&i!==34)return null;let a=r+1,o=U(e,r,n,i);return o<=a?null:{source:e.slice(a,o-1),end:o}}function Ye(e,t,n){if(!W(e,t,`import`))return{sources:[],end:t+6};let r=t+6;if(r=H(e,r,n),W(e,r,`type`)&&(r=H(e,r+4,n)),e.charCodeAt(r)===46){for(r++;r<n&&V(e.charCodeAt(r));)r++;for(;r<n&&e.charCodeAt(r)===46;)for(r++;r<n&&V(e.charCodeAt(r));)r++;return{sources:[],end:r}}if(e.charCodeAt(r)===40){r++;let t=G(e,r,n);return t?{sources:[t.source],end:t.end}:{sources:[],end:r}}let i=G(e,r,n);if(i)return{sources:[i.source],end:i.end};let a=0;for(;r<n&&(r=H(e,r,n),!(r>=n));){let t=e.charCodeAt(r);if(a===0&&W(e,r,`from`)){let t=G(e,r+4,n);if(t)return{sources:[t.source],end:t.end};break}if(t===39||t===34||t===96){r=U(e,r,n,t);continue}t===123||t===40||t===91?a++:(t===125||t===41||t===93)&&(a=Math.max(0,a-1)),r++}return{sources:[],end:r}}function Xe(e,t){return e.charCodeAt(t)===101&&e.charCodeAt(t+1)===120&&e.charCodeAt(t+2)===112&&e.charCodeAt(t+3)===111&&e.charCodeAt(t+4)===114&&e.charCodeAt(t+5)===116}function Ze(e,t){return e.charCodeAt(t)===100&&e.charCodeAt(t+1)===101&&e.charCodeAt(t+2)===102&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===117&&e.charCodeAt(t+5)===108&&e.charCodeAt(t+6)===116}function K(e){let t={hasUseClient:!1,hasUseServer:!1},n=!1,r=!1,i=!1,a=!1,o=[],s=!0,c=!1,l=0,u=e.length;for(;l<u;){let d=e.charCodeAt(l);if(z(d)){l++;continue}if(d===47&&e.charCodeAt(l+1)===47){l=Ge(e,l,u);continue}if(d===47&&e.charCodeAt(l+1)===42){l=Ke(e,l,u);continue}if(s&&(d===39||d===34)){let i=l+1,a=U(e,l,u,d);if(a<=i){s=!1,l++;continue}let o=a-1-i,f=o===10&&Je(e,i,`use client`),p=o===10&&Je(e,i,`use server`);c||(c=!0,n=f,r=p),f&&(t.hasUseClient=!0),p&&(t.hasUseServer=!0);let m=a,h=!1;for(;m<u;){let t=e.charCodeAt(m);if(z(t)&&!B(t)){m++;continue}if(B(t)||t===59){h=!0,l=m+1;break}if(t===47&&e.charCodeAt(m+1)===47){m=Ge(e,m,u);continue}if(t===47&&e.charCodeAt(m+1)===42){m=Ke(e,m,u);continue}s=!1,h=!1;break}if(!h){m>=u&&(s=!1),l=s?a:m;continue}continue}if(s=!1,d===39||d===34||d===96){l=U(e,l,u,d);continue}if(d===47&&e.charCodeAt(l+1)!==47&&e.charCodeAt(l+1)!==42&&nt(e,l)){l=rt(e,l,u);continue}if(d===60){let t=e.charCodeAt(l+1);if(t===47||t===46||t===62||Ue(t)){l=qe(e,l,u);continue}l++;continue}if(W(e,l,`import`)){let t=Ye(e,l,u);for(let e of t.sources)o.push(e);l=t.end;continue}if(Xe(e,l)){let t=l+6;if(t<u){let n=e.charCodeAt(t);if(z(n)||n===123||n===47&&(e.charCodeAt(t+1)===47||e.charCodeAt(t+1)===42)){let n=H(e,t,u);if(Ze(e,n)){i=!0,a=!0;let r=n+7;if(r>=u||!V(e.charCodeAt(r))){l=t;continue}}if(e.charCodeAt(n)===123){let t=n+1;for(;t<u&&(t=H(e,t,u),e.charCodeAt(t)!==125);){let n=t;for(;t<u&&V(e.charCodeAt(t));)t++;let r=t-n;if(r===0)break;t=H(e,t,u);let o=!1;if(e.charCodeAt(t)===97&&e.charCodeAt(t+1)===115){o=!0;let n=t+2;if(n<u&&!V(e.charCodeAt(n))){t=H(e,n,u);let r=t;for(;t<u&&V(e.charCodeAt(t));)t++;t-r===7&&Ze(e,r)&&(i=!0,a=!0)}}if(!o&&r===7&&Ze(e,n)&&(i=!0,a=!0),e.charCodeAt(t)===44){t++;continue}if(e.charCodeAt(t)===125)break;t++}}else(W(e,n,`async`)||W(e,n,`function`)||W(e,n,`class`))&&(a=!0)}}}l++}return{directives:t,topLevelUseClient:n,topLevelUseServer:r,hasDefaultExport:i,hasComponentExport:a,importSources:[...new Set(o)]}}function Qe(e){return K(e).hasDefaultExport}function $e(e){return e===40||e===91||e===123||e===44||e===59||e===61||e===58||e===63||e===33||e===43||e===45||e===42||e===37||e===38||e===124||e===94||e===126||e===60||e===62}function et(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(z(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}break}if(n<0||!V(e.charCodeAt(n)))return;let r=n;for(;n>=0&&V(e.charCodeAt(n));)n--;return e.slice(n+1,r+1)}function tt(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(z(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return-1;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}return t}return-1}function nt(e,t){let n=tt(e,t);if(n===-1||$e(n))return!0;let r=et(e,t);return r?Be.has(r):!1}function rt(e,t,n){t++;let r=!1;for(;t<n;){let i=e.charCodeAt(t);if(i===92){t+=2;continue}if(r){i===93&&(r=!1),t++;continue}if(i===91){r=!0,t++;continue}if(i===47){for(t++;t<n&&V(e.charCodeAt(t));)t++;return t}if(B(i))return t;t++}return t}const it=new Set([`node_modules`,`.git`,`.cache`,`dist`]);function at(e,t){let n=new Set,r=e=>{if(!E.existsSync(e))return;let i=E.readdirSync(e,{withFileTypes:!0});for(let a of i){let i=O.join(e,a.name);if(a.isDirectory()){if(it.has(a.name))continue;r(i)}else if(a.isFile()&&u.test(a.name)){if(n.has(i))continue;n.add(i),t(i)}}};for(let t of e)t&&E.existsSync(t)&&r(t)}function ot(e){let t=[];return at(e,e=>{t.push(e)}),t}function st(e,t=[]){let n=[e],r=O.resolve(e);for(let e of t){if(!e)continue;let t=O.resolve(e);if(t===r)continue;let i=O.relative(r,t);if(!(i===``||!i.startsWith(`..`)&&!O.isAbsolute(i)))try{E.statSync(e).isDirectory()&&n.push(e)}catch{}}return n}const ct=new Set(ae);function q(e){return ct.has(e)}function lt(e){for(let t of e.importSources)if(t.startsWith(`node:`)||q(t))return!0;return!1}function ut(e,t=ct){let n=[];for(let r of e)!r.startsWith(`.`)&&!r.startsWith(`/`)&&!r.startsWith(`@/`)&&!r.startsWith(`node:`)&&!t.has(r)&&n.push(r);return[...new Set(n)]}function dt(e){let t=[];for(let n of e)(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`@/`))&&t.push(n);return t}function J(e){try{return E.realpathSync(e)}catch{return O.resolve(e)}}function ft(e,t){e.delete(t);try{e.delete(E.realpathSync(t))}catch{e.delete(O.resolve(t))}}function pt(e,t){let n=[];for(let r of ot(e))try{t.get(r).directives.hasUseClient&&n.push(r)}catch{}return n}var mt=class{cache=new Map;get(e,t){let n=J(e),r=this.cache.get(n);if(t!==void 0){if(r&&r.source===t)return r.analysis}else if(r){let e=this.readMtimeMs(n);if(e>=0&&r.mtimeMs===e)return r.analysis}t===void 0&&(t=E.readFileSync(n,`utf-8`));let i=this.readMtimeMs(n),a=K(t);return this.cache.set(n,{mtimeMs:i,source:t,analysis:a}),a}getSource(e){return this.get(e),this.cache.get(J(e)).source}invalidate(e){ft(this.cache,e)}clear(){this.cache.clear()}readMtimeMs(e){try{return E.statSync(e).mtimeMs}catch{return-1}}},ht=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer=C(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=C(this.resetTimer)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.reset()}},gt=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 ht({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=O.relative(k.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=this.collectDependentPageComponents(e);for(let e of n)this.serverComponentBuilder.invalidateBuildCacheFor(e);let r=[...e,...n],i=await Promise.allSettled(r.map(async e=>{let t=O.relative(k.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),a=[],o=[];if(i.forEach(e=>{e.status===`fulfilled`&&e.value.success?a.push(e.value):e.status===`fulfilled`&&!e.value.success?o.push(e.value):e.status===`rejected`&&o.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),a.length>0){let e=Date.now();a.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(o.length>0){let e=Date.now();o.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});await re(n);let r=await n.text(),i;try{i=JSON.parse(r)}catch(e){throw Error(`Failed to parse server response (status ${n.status}): ${e instanceof Error?e.message:String(e)}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`)}if(!i||typeof i!=`object`)throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);let a=i;if(!a.success)throw Error(a.message||a.error||`Component reload failed`)}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}collectDependentPageComponents(e){let t=this.serverComponentBuilder.getImportGraph(),n=new Set,r=new Set,i=a=>{if(r.has(a))return;r.add(a);let o=t.get(a);if(o)for(let t of o)(t.includes(`/app/`)||t.includes(`\\app\\`))&&!e.includes(t)&&n.add(t),i(t)};for(let t of e)i(t);return[...n]}detectComponentType(e){try{return this.serverComponentBuilder.getModuleAnalysis(e).topLevelUseClient?`client`:`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
|
|
29
|
+
• `);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 _t=/\.mdx$/;function vt(e){let t=e.replace(v,`/`);return t===`rari/mdx/registry`||t.startsWith(`rari/mdx/registry?`)?!0:t.endsWith(`/mdx/registry.ts`)||t.endsWith(`/mdx/registry.mts`)||t.endsWith(`/mdx/registry.mjs`)||t.endsWith(`/mdx/registry.js`)||t.endsWith(`/mdx/registry`)?t.includes(`/node_modules/rari/`)||t.includes(`/packages/rari/`):!1}function yt(e,t){let n=e=>{if(E.existsSync(e))for(let r of E.readdirSync(e,{withFileTypes:!0})){let i=O.join(e,r.name);if(r.isDirectory()){if(r.name===`node_modules`||r.name===`.git`||r.name===`dist`)continue;n(i)}else r.isFile()&&_t.test(r.name)&&t(i)}};for(let t of e)t&&E.existsSync(t)&&n(t)}function bt(e){let t=new Set;return yt(e,e=>{try{let n=E.readFileSync(e,`utf-8`);for(let e of ie(n))t.add(e)}catch{}}),t}function xt(e,t){try{if(t.get(e).hasDefaultExport)return O.basename(e,O.extname(e));let n=t.getSource(e).match(m);if(n?.[1])return n[1]}catch{}return O.basename(e,O.extname(e))}function St(e){let t=bt(e.contentDirs.map(t=>O.join(e.projectRoot,t)));if(t.size===0)return[];let n=pt(e.componentScanDirs,e.cache),r=[],i=new Set;for(let a of n){let n=xt(a,e.cache);if(!n||!t.has(n))continue;let o=L(a,e.projectRoot).replace(v,`/`),s=o.startsWith(`/`)?o:`/${o}`,c=n.replace(/[^\w$]/g,`_`);i.has(c)&&(c=`${c}_${r.length}`),i.add(c),r.push({name:n,binding:c,importPath:s,moduleId:o,client:!0})}return r.sort((e,t)=>e.name.localeCompare(t.name))}function Ct(e){let t=Tt(e.projectRoot,e.mdxOptions),n=e.srcDir??O.join(e.projectRoot,`src`),r=Et(e.projectRoot,t.componentsDir,st(n,Object.values(e.alias??{})));return St({projectRoot:e.projectRoot,componentsDir:t.componentsDir,contentDirs:t.contentDirs,cache:e.cache,componentScanDirs:r})}function wt(e,t={}){let n=t.importStyle??`root-absolute`,r=t.mode??`vite`;return e.length===0?`import { defineMdxComponents } from 'rari/mdx/define'
|
|
30
30
|
|
|
31
31
|
export const getMDXComponents = defineMdxComponents([])
|
|
32
32
|
`:r===`production`?`import { defineMdxComponents } from 'rari/mdx/define'
|
|
@@ -43,8 +43,8 @@ export const getMDXComponents = defineMdxComponents([
|
|
|
43
43
|
${e.map(e=>` { name: ${JSON.stringify(e.name)}, component: ${e.binding}, id: ${JSON.stringify(e.moduleId)}, client: ${e.client} }`).join(`,
|
|
44
44
|
`)},
|
|
45
45
|
])
|
|
46
|
-
`}function
|
|
47
|
-
`)}\n`,i=`${I(e+r,12)}.css`,a=
|
|
46
|
+
`}function Tt(e,t){return{componentsDir:t?.componentsDir??`src/components`,contentDirs:t?.contentDirs??[`public/content`,`content`]}}function Et(e,t,n){let r=O.join(e,t),i=new Set(n);return E.existsSync(r)&&i.add(r),[...i]}const Dt=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,Ot=/<script\b[^>]*>/gi;function kt(e,t,n){n?.startsWith(`/src/`)&&e.add(J(O.join(t,n.slice(1))))}function At(e){return/\btype\s*=\s*["']module["']/i.test(e)?e.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1]??null:null}function jt(e){let t=new Set,n=O.join(e,`index.html`);if(!E.existsSync(n))return t;try{let r=E.readFileSync(n,`utf-8`);for(let n of r.matchAll(Dt))kt(t,e,n[1]||n[2]);for(let n of r.matchAll(Ot))kt(t,e,At(n[0]))}catch{}return t}let Y;async function Mt(){if(Y!==void 0)return Y;try{return Y=(await import(`@rari/use-cache`)).transformUseCacheModule??null,Y}catch{return Y=null,null}}const Nt=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,Pt=/import\s+(?:(\w+)|\{([^}]+)\})\s+from\s+['"]([^'"]+)['"];?\s*$/gm,Ft=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,It=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,Lt=/[/\\]components[/\\](\w+)(?:\.tsx?|\.jsx?)?$/,Rt=/^(?:robots|sitemap|feed)\.(?:tsx?|jsx?)$/,zt=`react-server-dom-rari/server`,Bt=/^node:/,Vt=`[hash]_[local]`;function Ht(e){if(e.startsWith(`@`)){let t=e.split(`/`);return t.length>=2?`${t[0]}/${t[1]}`:e}return e.split(`/`)[0]??e}function Ut(e,t){let n=Ht(t),r=e;for(;;){let e=O.join(r,`node_modules`,...n.split(`/`));if(E.existsSync(O.join(e,`package.json`)))return!0;let t=O.dirname(r);if(t===r)return!1;r=t}}const Wt=[{componentId:`rari/image`,devSourceSegments:[`src`,`image`,`image.tsx`],publishedExport:`rari/image`,exports:[`Image`]}],Gt=O.dirname(A(import.meta.url)),X=O.dirname(Gt);function Kt(e){return e.startsWith(X)}function qt(e,t){return Kt(e)?O.join(X,`src`):O.join(t,`src`)}function Jt(){let e=O.join(X,`src`,`runtime`,`boundaries`,`error-boundary-wrapper.tsx`);if(E.existsSync(e))return e;try{let e=A(import.meta.resolve(`rari/runtime/ErrorBoundaryWrapper`));if(E.existsSync(e))return e}catch{}return null}function Yt(e){let t=e.replace(v,`/`);return t.includes(`ErrorBoundaryWrapper`)||t.includes(`/boundaries/error-boundary-wrapper`)||t.endsWith(`/error-boundary-wrapper.tsx`)}function Xt(e,t){if(Yt(e))return`virtual:error-boundary-wrapper.tsx`;let n=O.relative(t,e).replace(v,`/`);return n.startsWith(`..`)||O.isAbsolute(n)?e.replace(v,`/`):n}function Zt(e,t){if(Yt(e))return`error_boundary_wrapper_${I(`virtual:error-boundary-wrapper.tsx`)}`;if(Kt(e)){let t=O.relative(X,e).replace(v,`/`);return`${ze(t)}_${I(t)}`}return R(e,t)}let Qt=null;async function $t(){return Qt||=(await import(`lightningcss`)).transform,Qt}function Z(e,t,n,r){return e.includes(`node_modules`)||n.has(r??J(e))?!1:!t.directives.hasUseClient&&!t.directives.hasUseServer}var en=class{serverComponents=new Map;serverActions=new Map;options;projectRoot;buildCache=new Map;useCacheBuildId=null;htmlOnlyImports=new Set;fileImporters=new Map;moduleAnalysisCache;discoveredExternalClientComponents=new Set;clientComponentFiles=new Map;recordClientComponent(e,t){this.clientComponentFiles.set(e,t)}getClientComponentFiles(){return[...this.clientComponentFiles.entries()].map(([e,t])=>({filePath:e,code:t}))}getClientComponentPaths(){return[...this.clientComponentFiles.keys()]}getModuleAnalysisCache(){return this.moduleAnalysisCache}clearClientComponentFiles(){this.clientComponentFiles.clear()}getComponentCount(){return this.serverComponents.size+this.serverActions.size}hasComponent(e){return this.serverComponents.has(e)||this.serverActions.has(e)}removeComponent(e){this.serverComponents.delete(e),this.serverActions.delete(e),this.moduleAnalysisCache.invalidate(e)}getImportGraph(){let e=new Map;for(let[t,n]of this.fileImporters)e.set(t,new Set(n));return e}getHtmlOnlyImports(){return new Set(this.htmlOnlyImports)}async writeComponentCssAsset(e,t){if(t.length===0)return[];let n=O.join(this.options.outDir,`assets`,`server`);await E.promises.mkdir(n,{recursive:!0});let r=`${t.join(`
|
|
47
|
+
`)}\n`,i=`${I(e+r,12)}.css`,a=O.join(n,i);return await E.promises.writeFile(a,r,`utf-8`),[`/assets/server/${i}`]}getComponentIdFromRouteManifestPath(e){return this.getComponentId(O.join(this.projectRoot,`src`,`app`,e))}getComponentReferenceId(e){return this.getReadableComponentId(this.getProjectRelativePath(e))}async writeRouteCssEntries(e){let t=O.join(this.options.outDir,this.options.rscDir,`routes.json`);if(!E.existsSync(t))return;let n=await E.promises.readFile(t,`utf-8`),r=JSON.parse(n),i=t=>{if(t)for(let n of t){if(!n.filePath)continue;let t=this.getComponentIdFromRouteManifestPath(n.filePath);n.componentId=t;let r=e.components[t]?.css??[];r.length?n.css=r:delete n.css}};if(i(r.routes),i(r.layouts),i(r.loading),i(r.errors),i(r.notFound),r.apiRoutes)for(let e of r.apiRoutes)e.filePath&&(e.componentId=this.getComponentIdFromRouteManifestPath(e.filePath));await E.promises.writeFile(t,JSON.stringify(r),`utf-8`)}constructor(e,t={}){this.projectRoot=e,this.moduleAnalysisCache=t.moduleAnalysisCache??new mt;let n=t.rscDir||`server`;this.options={outDir:t.outDir||O.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath||O.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath||O.join(n,`config.json`),minify:t.minify??k.env.NODE_ENV===`production`,alias:t.alias||{},define:t.define,csp:t.csp,cacheControl:t.cacheControl,experimental:t.experimental,mdx:t.mdx},this.parseHtmlImports()}parseHtmlImports(){for(let e of jt(this.projectRoot))this.htmlOnlyImports.add(e)}getModuleAnalysis(e,t){return this.moduleAnalysisCache.get(e,t)}isServerComponent(e,t){try{return Z(e,this.moduleAnalysisCache.get(e,t),this.htmlOnlyImports)}catch{return!1}}isClientComponent(e,t){try{return this.moduleAnalysisCache.get(e,t).directives.hasUseClient}catch{return!1}}resolveImportedFilePath(e,t){let n=null;if(t.startsWith(`./`)||t.startsWith(`../`)){let r=O.dirname(e);n=O.resolve(r,t)}else if(n=S(t,this.options.alias,this.projectRoot),!n&&t.startsWith(`@/`)){let e=t.slice(2);n=O.join(this.projectRoot,`src`,e)}return n?ne(n,[``,`.ts`,`.tsx`,`.js`,`.jsx`]):null}populateImportGraphFromFiles(e){this.fileImporters.clear();for(let{filePath:t,analysis:n}of e)for(let e of dt(n.importSources)){let n=this.resolveImportedFilePath(t,e);n&&(this.fileImporters.has(n)||this.fileImporters.set(n,new Set),this.fileImporters.get(n).add(t))}}buildImportGraph(e){let t=tn(this,[e]);this.populateImportGraphFromFiles(t)}isOnlyImportedByClientComponents(e){let t=this.fileImporters.get(e);if(!t||t.size===0)return!1;for(let e of t)if(!this.isClientComponent(e)&&!this.isOnlyImportedByClientComponents(e))return!1;return!0}addServerComponent(e,t,n){let r=t??E.readFileSync(e,`utf-8`),i=n??this.moduleAnalysisCache.get(e,r),a=ut(i.importSources),o=lt(i);if(i.directives.hasUseServer){this.serverActions.set(e,{filePath:e,originalCode:r,dependencies:a,hasNodeImports:o});return}Z(e,i,this.htmlOnlyImports)&&this.serverComponents.set(e,{filePath:e,originalCode:r,dependencies:a,hasNodeImports:o})}isServerAction(e,t){return t?this.moduleAnalysisCache.get(t,e).directives.hasUseServer:K(e).directives.hasUseServer}extractDependencies(e,t){return ut((t?this.moduleAnalysisCache.get(t,e):K(e)).importSources)}hasNodeImports(e,t){return lt(t?this.moduleAnalysisCache.get(t,e):K(e))}async getTransformedComponentsForDevelopment(){let e=[];for(let[t]of this.serverComponents){let n=O.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i,isAction:!1})}for(let[t]of this.serverActions){let n=O.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i,isAction:!0})}return e}transformComponentImportsToGlobal(e){let t=[];for(let n of e.matchAll(Nt)){let[e,r,i]=n;if(!i.startsWith(`.`)&&!i.startsWith(`@`)&&!i.startsWith(`~`)&&!i.startsWith(`#`))continue;let a=null;if(i.startsWith(`.`)){if(i.includes(`/components/`)){let n=i.match(It);if(n){let i=n[1],a=[O.resolve(this.projectRoot,`src`,`components`,`${i}.tsx`),O.resolve(this.projectRoot,`src`,`components`,`${i}.ts`),O.resolve(this.projectRoot,`src`,`components`,`${i}.jsx`),O.resolve(this.projectRoot,`src`,`components`,`${i}.js`)],o=!1;for(let e of a)if(E.existsSync(e)&&this.isClientComponent(e)){o=!0;break}if(!o)continue;let s=`// Component reference: ${i}
|
|
48
48
|
const ${r} = (props) => {
|
|
49
49
|
let Component = globalThis['~clientComponents']?.['components/${i}']?.component
|
|
50
50
|
|| globalThis['components/${i}'];
|
|
@@ -62,7 +62,7 @@ const ${r} = (props) => {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
return Component(props);
|
|
65
|
-
}`;t.push({original:e,replacement:s})}}continue}let o=this.options.alias||{};for(let[e,t]of Object.entries(o))if(i.startsWith(`${e}/`)||i===e){let n=i.slice(e.length).replace(/^\/+/,``);a=
|
|
65
|
+
}`;t.push({original:e,replacement:s})}}continue}let o=this.options.alias||{};for(let[e,t]of Object.entries(o))if(i.startsWith(`${e}/`)||i===e){let n=i.slice(e.length).replace(/^\/+/,``);a=O.join(t,n);break}if(a){let n=a.match(Lt);if(n){let i=n[1],o=O.isAbsolute(a)?a:O.resolve(this.projectRoot,a),s=[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`],c=!1,l=o;for(let e of s)if(E.existsSync(e)){l=e,this.isClientComponent(e)&&(c=!0);break}if(!c)continue;let u=this.getComponentReferenceId(l),d=`// Component reference: ${i}
|
|
66
66
|
const ${r} = (props) => {
|
|
67
67
|
let Component = globalThis['~clientComponents']?.['${u}']?.component
|
|
68
68
|
|| globalThis['${u}'];
|
|
@@ -80,12 +80,12 @@ const ${r} = (props) => {
|
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
return Component(props);
|
|
83
|
-
}`;t.push({original:e,replacement:d})}}}let n=e;for(let{original:e,replacement:r}of t)n=n.replace(e,r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createRolldownModuleInfoPlugin(e){let t=new Set;return{name:`rari-rolldown-module-info`,moduleParsed(e){for(let n of e.importedIds)!n.startsWith(`.`)&&!n.startsWith(`/`)&&!n.startsWith(`node:`)&&!
|
|
83
|
+
}`;t.push({original:e,replacement:d})}}}let n=e;for(let{original:e,replacement:r}of t)n=n.replace(e,r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createRolldownModuleInfoPlugin(e){let t=new Set;return{name:`rari-rolldown-module-info`,moduleParsed(e){for(let n of e.importedIds)!n.startsWith(`.`)&&!n.startsWith(`/`)&&!n.startsWith(`node:`)&&!q(n)&&t.add(n);for(let n of e.dynamicallyImportedIds)!n.startsWith(`.`)&&!n.startsWith(`/`)&&!n.startsWith(`node:`)&&!q(n)&&t.add(n)},buildEnd:()=>{if(t.size===0)return;let n=[...t].sort(),r=this.serverComponents.get(e)||this.serverActions.get(e);r&&(r.dependencies=n);let i=this.buildCache.get(e);i&&(i.bundledDependencies=n)}}}createBuildPlugins(e,t,n,r,i=!1,a){let o=O.dirname(r),c=Ft.test(O.basename(r)),l=new Map,u=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){if(t.endsWith(`.module.css`))return null;let e=O.resolve(o,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(E.existsSync(n)&&E.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=O.join(e,`index${t}`);if(E.existsSync(n))return n}return e}return null},load(r){return r===e?{code:t,moduleType:n}:null}},{name:`resolve-client-server-boundaries`,enforce:`pre`,resolveId:(t,n)=>{if(!n||n.includes(`node_modules`)||Kt(n)||t.startsWith(`node:`)||q(t)||t===`react`||t===`react-dom`||t===`react/jsx-runtime`||t===`react/jsx-dev-runtime`)return null;let r=null;if(r=S(t,this.options.alias||{},this.projectRoot),!r&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?o:O.dirname(n);r=O.resolve(i,t)}if(!r&&O.isAbsolute(t)&&(r=t),r)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(E.existsSync(t)&&E.statSync(t).isFile()){if(this.isClientComponent(t)){let e=O.relative(this.projectRoot,t),n=(e.startsWith(`..`)?t:e).replace(v,`/`);return l.set(t,n),e.startsWith(`..`)&&this.discoveredExternalClientComponents.add(t),{id:`\0client-ref:${t}`}}try{let e=this.moduleAnalysisCache.get(t);if(e.directives.hasUseServer){let n=this.getComponentId(t);return u.set(t,{actionId:n,hasDefaultExport:e.hasDefaultExport}),{id:`\0server-action:${t}`}}}catch(e){console.error(`[rari] Failed to read file for server action detection: ${t}`,e)}break}}return null},load:e=>{if(e.startsWith(`\0client-ref:`)){let t=e.slice(12),n=O.relative(this.projectRoot,t),r=(l.get(t)||(n.startsWith(`..`)?t:n)).replace(v,`/`);return{code:`import { registerClientReference } from ${JSON.stringify(zt)};
|
|
84
84
|
export default registerClientReference(null, ${JSON.stringify(r)}, "default");
|
|
85
|
-
`,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=u.get(t)?.actionId??this.getComponentId(t);return{code:this.generateServerActionRuntimeModule(t,n),moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!i)return null;if(e.startsWith(`file://`)){let t=e.replace(s,``);return T.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null;n=x(e,this.options.alias||{},this.projectRoot);let r=t?.startsWith(`\0`)?o:t?D.dirname(t):o;if(!n&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=D.resolve(r,e)),!n||r.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(T.existsSync(t)&&T.statSync(t).isFile()){if(this.isClientComponent(t)||this.isServerActionFile(t))return null;let e=D.join(this.projectRoot,`src`);if(!t.startsWith(e))return null;let n=this.getComponentId(t),r=D.join(this.options.outDir,this.options.rscDir,`${n}.js`);if(T.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:T.readFileSync(t,`utf-8`),moduleType:`js`}}return null}},{name:`resolve-aliases`,resolveId:e=>{if(e.startsWith(`\0`))return null;let t=x(e,this.options.alias||{},this.projectRoot);if(!t)return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let n=t+e;if(T.existsSync(n)&&T.statSync(n).isFile()){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return u.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=D.join(t,`index${e}`);if(T.existsSync(n)){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return u.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}return t}},{name:`resolve-rari-proxy`,resolveId:e=>{if(c&&e===`rari`){let e=D.join(Wt,`proxy/RariResponse.mjs`);if(T.existsSync(e))return e;let t=D.join(Y,`src/proxy/http/response.ts`);if(T.existsSync(t))return t}return null}},{name:`css-modules`,resolveId:(e,t)=>{if(e.endsWith(`.module.css`)){let n=!t?.startsWith(`\0`)&&t?D.dirname(t):o,r=D.resolve(n,e);if(T.existsSync(r))return{id:`\0css-module:${r}`}}return null},load:async e=>{if(!e.startsWith(`\0css-module:`))return null;let t=e.slice(12);try{let e=await Qt(),n=T.readFileSync(t),r=e({filename:D.relative(this.projectRoot,t),code:n,cssModules:{pattern:Ht}});a&&a.push(new TextDecoder().decode(r.code));let i={};if(r.exports)for(let[e,t]of Object.entries(r.exports))i[e]=t.name;return{code:`export default ${JSON.stringify(i)}`,moduleType:`js`}}catch(t){throw Error(`[rari] Failed to process CSS module ${e}: ${t instanceof Error?t.message:String(t)}`)}}},{name:`externalize-deps`,resolveId:e=>e.startsWith(`\0`)?null:e.startsWith(`node:`)||K(e)||[`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`rari/image`].includes(e)||e in{"rari/runtime/cache-wrapper":`node_modules/rari/dist/runtime/cache-wrapper.mjs`,"react-server-dom-rari/server":`node_modules/rari/dist/runtime/rsc-references.mjs`}?{id:e,external:!0}:e===`rari`||x(e,this.options.alias||{},this.projectRoot)?null:!e.startsWith(`.`)&&!e.startsWith(`/`)?{id:e,external:!0}:null},this.createRolldownModuleInfoPlugin(r),{name:`use-cache`,transform:async(e,t)=>{if(!this.options.experimental?.useCache&&!this.options.experimental?.useCacheRemote)return null;let n=await Nt();return n?n(e,t,{hashSalt:`${this.useCacheBuildId??`development`}:rari-use-cache-v1`}):null}}]}async buildComponentCodeOnly(e){let t=await T.promises.readFile(e,`utf-8`),n=this.transformClientImports(t,e),r=this.isPageComponent(e),i=r?this.transformComponentImportsToGlobal(n):n,a=D.extname(e),o;o=a===`.tsx`?`tsx`:a===`.ts`?`ts`:a===`.jsx`?`jsx`:`js`;let s=`\0virtual:${e}`,c=await M({input:s,platform:`node`,write:!1,external:[Vt,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${o}`]:o},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(O.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(s,i,o,e,r,[])});if(!c.output||c.output.length===0)throw Error(`No output generated from Rolldown`);let l=c.output.find(e=>e.type===`chunk`&&e.isEntry);if(!l||l.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let u=l.code;return u=`// Built: ${new Date().toISOString()}\n${u}`,u}async buildComponentBatch(e,t,n){let r=0,i=0,a=[];if(await new Promise(o=>{let s=()=>{for(;r<n&&i<e.length;){let[n,c]=e[i++],l=D.relative(this.projectRoot,n),u=this.getComponentId(n),d=D.join(this.options.rscDir,`${u}.js`),f=D.join(this.options.outDir,d);r++,(async()=>{try{let e=D.dirname(f);await T.promises.mkdir(e,{recursive:!0});let r=await this.buildSingleComponent(n,f),i=await this.writeComponentCssAsset(u,r.css),a=A(D.resolve(this.projectRoot,f)).href;t.components[u]={id:u,filePath:n,relativePath:l,bundlePath:d,moduleSpecifier:a,dependencies:c.dependencies,hasNodeImports:c.hasNodeImports,css:i}}catch(e){a.push(e instanceof Error?e:Error(String(e)))}finally{r--,i>=e.length&&r===0?o():s()}})()}e.length===0&&o()};s()}),a.length>0)throw a[0]}async buildServerComponents(){let e=D.join(this.options.outDir,this.options.rscDir);await T.promises.mkdir(e,{recursive:!0});let t={components:{},buildTime:new Date().toISOString()},n=this.options.experimental?.useCache||this.options.experimental?.useCacheRemote,r=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),i=[...this.serverComponents.entries()].filter(([e])=>!this.isPageComponent(e)),a=[...this.serverComponents.entries()].filter(([e])=>this.isPageComponent(e)),o=[...this.serverActions.entries()];await Promise.all([this.buildComponentBatch(i,t,r),this.buildComponentBatch(o,t,r)]),await this.buildComponentBatch(a,t,r),n&&(this.useCacheBuildId=I(JSON.stringify(t.components),16),t.useCacheBuildId=this.useCacheBuildId);let s=D.join(this.options.outDir,this.options.manifestPath);await T.promises.writeFile(s,JSON.stringify(t),`utf-8`),await this.writeRouteCssEntries(t);let c={};this.options.csp&&(c.csp=this.options.csp),this.options.cacheControl&&(c.cacheControl=this.options.cacheControl),this.options.cache&&(c.cache=this.options.cache),(this.options.experimental?.useCacheRemote||this.useCacheBuildId)&&(c.useCache={...this.options.experimental?.useCacheRemote?{remote:this.options.experimental.useCacheRemote}:{},...this.useCacheBuildId?{buildId:this.useCacheBuildId}:{}},!this.options.experimental?.useCache&&this.options.experimental?.useCacheRemote&&console.warn(`[server-build] experimental.useCacheRemote is set without experimental.useCache; the 'use cache' transform will still run because useCacheRemote is configured.`));let l=D.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(c).length===0)try{await T.promises.unlink(l)}catch(e){e.code!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await T.promises.writeFile(l,JSON.stringify(c),`utf-8`);return t}async buildMdxRegistry(e){let t=wt({projectRoot:this.projectRoot,mdxOptions:e,alias:this.options.alias||{},cache:this.moduleAnalysisCache}),n=D.join(this.options.outDir,this.options.manifestPath),r;if(T.existsSync(n)){let e=await T.promises.readFile(n,`utf-8`);r=JSON.parse(e)}else r={components:{},buildTime:new Date().toISOString()};r.mdxRegistry=t.map(e=>({name:e.name,id:e.moduleId,client:e.client})),await T.promises.writeFile(n,JSON.stringify(r),`utf-8`)}async buildSSRClientComponents(){let e=D.join(this.options.outDir,`ssr`);await T.promises.mkdir(e,{recursive:!0});let t=[...this.getClientComponentFiles()];for(let e of this.discoveredExternalClientComponents)if(!t.some(t=>t.filePath===e))try{let n=T.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}catch{}try{let e=qt();if(e){let n=T.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}}catch{}if(t.length===0){let t={};await this.buildExternalClientComponents(t,new Map),await this.writeClientReferenceManifest(e,t);return}let n=new Map;for(let{filePath:e}of t){let t=Xt(e,this.projectRoot);n.set(D.resolve(e),`file:///ssr/${t}.js`)}let r={},i=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),a=0,o=0;await new Promise(e=>{let s=()=>{for(;a<i&&o<t.length;){let{filePath:i,code:c}=t[o++],l=Yt(i,this.projectRoot),u=`ssr/${Xt(i,this.projectRoot)}.js`,d=D.join(this.options.outDir,u);a++,(async()=>{try{let e=D.dirname(d);await T.promises.mkdir(e,{recursive:!0}),await this.buildSSRSingleClient(i,d,n);let t=this.extractExportNames(c);r[l]={id:l,filePath:i,bundlePath:u,exports:t}}catch(e){console.warn(`[rari] SSR build failed for ${l}:`,e instanceof Error?e.message:e)}finally{a--,o>=t.length&&a===0?e():s()}})()}t.length===0&&e()};s()}),await this.buildExternalClientComponents(r,n),await this.writeClientReferenceManifest(e,r)}async writeClientReferenceManifest(e,t){let n=D.join(e,`manifest.json`);await T.promises.writeFile(n,JSON.stringify(t),`utf-8`);let r={};for(let[e,n]of Object.entries(t))for(let t of n.exports){let i=`${e}#${t}`;r[i]={id:i,chunks:`/${n.bundlePath}`,name:t}}let i=D.join(this.options.outDir,`server`);await T.promises.mkdir(i,{recursive:!0});let a=D.join(i,`client-reference-manifest.json`);await T.promises.writeFile(a,JSON.stringify(r),`utf-8`)}resolveExternalClientSourcePath(e,t){let n=D.join(Y,...e);if(T.existsSync(n))return n;try{let e=k(import.meta.resolve(t));if(T.existsSync(e))return e}catch{}return null}async buildExternalClientComponents(e,t){for(let{componentId:n,devSourceSegments:r,publishedExport:i,exports:a}of Ut){let o=this.resolveExternalClientSourcePath(r,i);if(o)try{let r=`ssr/${`external_${I(n)}`}.js`,i=D.join(this.options.outDir,r);await T.promises.mkdir(D.dirname(i),{recursive:!0}),await this.buildSSRSingleClient(o,i,t),e[n]={id:n,filePath:o,bundlePath:r,exports:[...a]}}catch(e){console.warn(`[rari] SSR build failed for ${n}:`,e instanceof Error?e.message:e)}}}extractExportNames(e){let t=[];/export\s+default\b/.test(e)&&t.push(`default`);for(let n of e.matchAll(/export\s+(?:async\s+)?(?:function|const|let|var|class)\s+(\w+)/g))t.push(n[1]);return t.length>0?t:[`default`]}isServerActionFile(e){try{let t=T.readFileSync(e,`utf-8`);return this.isServerAction(t,e)}catch{return!1}}generateServerActionRuntimeModule(e,t){let n=T.readFileSync(e,`utf-8`),r=this.extractExportNames(n),i=[`const __rariActionMod = globalThis.__rari_rsc_require__(${JSON.stringify(t)});`,`if (!__rariActionMod) throw new Error("Server action module ${t} is not registered");`];for(let e of r)e==="default"?i.push(`export default __rariActionMod.default;`):i.push(`export const ${e} = __rariActionMod.${e};`);return`${i.join(`
|
|
86
|
-
`)}\n`}generateServerActionReferenceModule(e){let t=
|
|
85
|
+
`,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=u.get(t)?.actionId??this.getComponentId(t);return{code:this.generateServerActionRuntimeModule(t,n),moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!i)return null;if(e.startsWith(`file://`)){let t=e.replace(s,``);return E.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null;n=S(e,this.options.alias||{},this.projectRoot);let r=t?.startsWith(`\0`)?o:t?O.dirname(t):o;if(!n&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=O.resolve(r,e)),!n||r.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(E.existsSync(t)&&E.statSync(t).isFile()){if(this.isClientComponent(t)||this.isServerActionFile(t))return null;let e=O.join(this.projectRoot,`src`);if(!t.startsWith(e))return null;let n=this.getComponentId(t),r=O.join(this.options.outDir,this.options.rscDir,`${n}.js`);if(E.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:E.readFileSync(t,`utf-8`),moduleType:`js`}}return null}},{name:`resolve-aliases`,resolveId:e=>{if(e.startsWith(`\0`))return null;let t=S(e,this.options.alias||{},this.projectRoot);if(!t)return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let n=t+e;if(E.existsSync(n)&&E.statSync(n).isFile()){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return u.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=O.join(t,`index${e}`);if(E.existsSync(n)){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return u.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}return t}},{name:`resolve-rari-proxy`,resolveId:e=>{if(c&&e===`rari`){let e=O.join(Gt,`proxy/RariResponse.mjs`);if(E.existsSync(e))return e;let t=O.join(X,`src/proxy/http/response.ts`);if(E.existsSync(t))return t}return null}},{name:`css-modules`,resolveId:(e,t)=>{if(e.endsWith(`.module.css`)){let n=!t?.startsWith(`\0`)&&t?O.dirname(t):o,r=O.resolve(n,e);if(E.existsSync(r))return{id:`\0css-module:${r}`}}return null},load:async e=>{if(!e.startsWith(`\0css-module:`))return null;let t=e.slice(12);try{let e=await $t(),n=E.readFileSync(t),r=e({filename:O.relative(this.projectRoot,t),code:n,cssModules:{pattern:Vt}});a&&a.push(new TextDecoder().decode(r.code));let i={};if(r.exports)for(let[e,t]of Object.entries(r.exports))i[e]=t.name;return{code:`export default ${JSON.stringify(i)}`,moduleType:`js`}}catch(t){throw Error(`[rari] Failed to process CSS module ${e}: ${t instanceof Error?t.message:String(t)}`)}}},{name:`externalize-deps`,resolveId:(e,t)=>{if(e.startsWith(`\0`))return null;if(e.startsWith(`node:`)||q(e)||[`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`rari/image`].includes(e)||e in{"rari/runtime/cache-wrapper":`node_modules/rari/dist/runtime/cache-wrapper.mjs`,"react-server-dom-rari/server":`node_modules/rari/dist/runtime/rsc-references.mjs`})return{id:e,external:!0};if(e===`rari`||S(e,this.options.alias||{},this.projectRoot))return null;if(!e.startsWith(`.`)&&!e.startsWith(`/`)){if(Ut(this.projectRoot,e))return{id:e,external:!0};let n=[t&&!t.startsWith(`\0`)?t:null,r].filter(e=>!!e);for(let t of n)try{return{id:w(t).resolve(e)}}catch{try{return{id:A(import.meta.resolve(e,j(t).href))}}catch{}}return null}return null}},this.createRolldownModuleInfoPlugin(r),{name:`use-cache`,transform:async(e,t)=>{if(!this.options.experimental?.useCache&&!this.options.experimental?.useCacheRemote)return null;let n=await Mt();return n?n(e,t,{hashSalt:`${this.useCacheBuildId??`development`}:rari-use-cache-v1`}):null}}]}async buildComponentCodeOnly(e){let t=await E.promises.readFile(e,`utf-8`),n=this.transformClientImports(t,e),r=this.isPageComponent(e),i=r?this.transformComponentImportsToGlobal(n):n,a=O.extname(e),o;o=a===`.tsx`?`tsx`:a===`.ts`?`ts`:a===`.jsx`?`jsx`:`js`;let s=`\0virtual:${e}`,c=await N({input:s,platform:`node`,write:!1,external:[Bt,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${o}`]:o},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(k.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(s,i,o,e,r,[])});if(!c.output||c.output.length===0)throw Error(`No output generated from Rolldown`);let l=c.output.find(e=>e.type===`chunk`&&e.isEntry);if(!l||l.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let u=l.code;return u=`// Built: ${new Date().toISOString()}\n${u}`,u}async buildComponentBatch(e,t,n){let r=0,i=0,a=[];if(await new Promise(o=>{let s=()=>{for(;r<n&&i<e.length;){let[n,c]=e[i++],l=O.relative(this.projectRoot,n),u=this.getComponentId(n),d=O.join(this.options.rscDir,`${u}.js`),f=O.join(this.options.outDir,d);r++,(async()=>{try{let e=O.dirname(f);await E.promises.mkdir(e,{recursive:!0});let r=await this.buildSingleComponent(n,f),i=await this.writeComponentCssAsset(u,r.css),a=j(O.resolve(this.projectRoot,f)).href;t.components[u]={id:u,filePath:n,relativePath:l,bundlePath:d,moduleSpecifier:a,dependencies:c.dependencies,hasNodeImports:c.hasNodeImports,css:i}}catch(e){a.push(e instanceof Error?e:Error(String(e)))}finally{r--,i>=e.length&&r===0?o():s()}})()}e.length===0&&o()};s()}),a.length>0)throw a[0]}async buildServerComponents(){let e=O.join(this.options.outDir,this.options.rscDir);await E.promises.mkdir(e,{recursive:!0});let t={components:{},buildTime:new Date().toISOString()},n=this.options.experimental?.useCache||this.options.experimental?.useCacheRemote,r=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),i=[...this.serverComponents.entries()].filter(([e])=>!this.isPageComponent(e)),a=[...this.serverComponents.entries()].filter(([e])=>this.isPageComponent(e)),o=[...this.serverActions.entries()];await Promise.all([this.buildComponentBatch(i,t,r),this.buildComponentBatch(o,t,r)]),await this.buildComponentBatch(a,t,r),n&&(this.useCacheBuildId=I(JSON.stringify(t.components),16),t.useCacheBuildId=this.useCacheBuildId);let s=O.join(this.options.outDir,this.options.manifestPath);await E.promises.writeFile(s,JSON.stringify(t),`utf-8`),await this.writeRouteCssEntries(t);let c={};this.options.csp&&(c.csp=this.options.csp),this.options.cacheControl&&(c.cacheControl=this.options.cacheControl),this.options.cache&&(c.cache=this.options.cache),(this.options.experimental?.useCacheRemote||this.useCacheBuildId)&&(c.useCache={...this.options.experimental?.useCacheRemote?{remote:this.options.experimental.useCacheRemote}:{},...this.useCacheBuildId?{buildId:this.useCacheBuildId}:{}},!this.options.experimental?.useCache&&this.options.experimental?.useCacheRemote&&console.warn(`[server-build] experimental.useCacheRemote is set without experimental.useCache; the 'use cache' transform will still run because useCacheRemote is configured.`));let l=O.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(c).length===0)try{await E.promises.unlink(l)}catch(e){e.code!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await E.promises.writeFile(l,JSON.stringify(c),`utf-8`);return t}async buildMdxRegistry(e){let t=Ct({projectRoot:this.projectRoot,mdxOptions:e,alias:this.options.alias||{},cache:this.moduleAnalysisCache}),n=O.join(this.options.outDir,this.options.manifestPath),r;if(E.existsSync(n)){let e=await E.promises.readFile(n,`utf-8`);r=JSON.parse(e)}else r={components:{},buildTime:new Date().toISOString()};r.mdxRegistry=t.map(e=>({name:e.name,id:e.moduleId,client:e.client})),await E.promises.writeFile(n,JSON.stringify(r),`utf-8`)}async buildSSRClientComponents(){let e=O.join(this.options.outDir,`ssr`);await E.promises.mkdir(e,{recursive:!0});let t=[...this.getClientComponentFiles()];for(let e of this.discoveredExternalClientComponents)if(!t.some(t=>t.filePath===e))try{let n=E.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}catch{}try{let e=Jt();if(e){let n=E.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}}catch{}if(t.length===0){let t={};await this.buildExternalClientComponents(t,new Map),await this.writeClientReferenceManifest(e,t);return}let n=new Map;for(let{filePath:e}of t){let t=Zt(e,this.projectRoot);n.set(O.resolve(e),`file:///ssr/${t}.js`)}let r={},i=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),a=0,o=0;await new Promise(e=>{let s=()=>{for(;a<i&&o<t.length;){let{filePath:i,code:c}=t[o++],l=Xt(i,this.projectRoot),u=`ssr/${Zt(i,this.projectRoot)}.js`,d=O.join(this.options.outDir,u);a++,(async()=>{try{let e=O.dirname(d);await E.promises.mkdir(e,{recursive:!0}),await this.buildSSRSingleClient(i,d,n);let t=this.extractExportNames(c);r[l]={id:l,filePath:i,bundlePath:u,exports:t}}catch(e){console.warn(`[rari] SSR build failed for ${l}:`,e instanceof Error?e.message:e)}finally{a--,o>=t.length&&a===0?e():s()}})()}t.length===0&&e()};s()}),await this.buildExternalClientComponents(r,n),await this.writeClientReferenceManifest(e,r)}async writeClientReferenceManifest(e,t){let n=O.join(e,`manifest.json`);await E.promises.writeFile(n,JSON.stringify(t),`utf-8`);let r={};for(let[e,n]of Object.entries(t))for(let t of n.exports){let i=`${e}#${t}`;r[i]={id:i,chunks:`/${n.bundlePath}`,name:t}}let i=O.join(this.options.outDir,`server`);await E.promises.mkdir(i,{recursive:!0});let a=O.join(i,`client-reference-manifest.json`);await E.promises.writeFile(a,JSON.stringify(r),`utf-8`)}resolveExternalClientSourcePath(e,t){let n=O.join(X,...e);if(E.existsSync(n))return n;try{let e=A(import.meta.resolve(t));if(E.existsSync(e))return e}catch{}return null}async buildExternalClientComponents(e,t){for(let{componentId:n,devSourceSegments:r,publishedExport:i,exports:a}of Wt){let o=this.resolveExternalClientSourcePath(r,i);if(o)try{let r=`ssr/${`external_${I(n)}`}.js`,i=O.join(this.options.outDir,r);await E.promises.mkdir(O.dirname(i),{recursive:!0}),await this.buildSSRSingleClient(o,i,t),e[n]={id:n,filePath:o,bundlePath:r,exports:[...a]}}catch(e){console.warn(`[rari] SSR build failed for ${n}:`,e instanceof Error?e.message:e)}}}extractExportNames(e){let t=[];/export\s+default\b/.test(e)&&t.push(`default`);for(let n of e.matchAll(/export\s+(?:async\s+)?(?:function|const|let|var|class)\s+(\w+)/g))t.push(n[1]);return t.length>0?t:[`default`]}isServerActionFile(e){try{let t=E.readFileSync(e,`utf-8`);return this.isServerAction(t,e)}catch{return!1}}generateServerActionRuntimeModule(e,t){let n=E.readFileSync(e,`utf-8`),r=this.extractExportNames(n),i=[`const __rariActionMod = globalThis.__rari_rsc_require__(${JSON.stringify(t)});`,`if (!__rariActionMod) throw new Error("Server action module ${t} is not registered");`];for(let e of r)e==="default"?i.push(`export default __rariActionMod.default;`):i.push(`export const ${e} = __rariActionMod.${e};`);return`${i.join(`
|
|
86
|
+
`)}\n`}generateServerActionReferenceModule(e){let t=E.readFileSync(e,`utf-8`),n=this.extractExportNames(t),r=this.getComponentId(e),i=`import { createServerReference } from 'react-server-dom-webpack/client';
|
|
87
87
|
`;i+=`import { callServer } from 'rari/runtime/call-server';
|
|
88
|
-
`;for(let e of n){let t=`${r}#${e}`;e==="default"?i+=`export default createServerReference(${JSON.stringify(t)}, callServer);\n`:i+=`export const ${e} = createServerReference(${JSON.stringify(t)}, callServer);\n`}return i}async buildSSRSingleClient(e,t,n){let r=(await
|
|
88
|
+
`;for(let e of n){let t=`${r}#${e}`;e==="default"?i+=`export default createServerReference(${JSON.stringify(t)}, callServer);\n`:i+=`export const ${e} = createServerReference(${JSON.stringify(t)}, callServer);\n`}return i}async buildSSRSingleClient(e,t,n){let r=(await E.promises.readFile(e,`utf-8`)).replace(/^['"]use client['"];?\s*/m,``),i=O.extname(e),a;a=i===`.tsx`?`tsx`:i===`.ts`?`ts`:i===`.jsx`?`jsx`:`js`;let o=`\0ssr-virtual:${e}`,s=this.projectRoot,c=qt(e,s),l=this,u=(await N({input:o,platform:`node`,write:!1,external:[Bt,`react`,`react-dom`,/^react\//,/^rari/,`react-server-dom-webpack/client`,/^react-server-dom-webpack\//],output:{format:`esm`,minify:!1},moduleTypes:{[`.${a}`]:a},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react-jsx`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(k.env.NODE_ENV||`production`)}},plugins:[{name:`ssr-client-virtual`,resolveId(e){return e===o?e:null},load(e){if(e===o)return{code:r,moduleType:a};if(e.startsWith(`\0server-action-ref:`)){let t=e.slice(19);return{code:l.generateServerActionReferenceModule(t),moduleType:`js`}}return null}},{name:`ssr-client-resolve`,resolveId(t,r){if(t.startsWith(`\0server-action-ref:`))return t;if(t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`@/`)){let i=t;t.startsWith(`@/`)?i=O.join(c,t.slice(2)):r===o?i=O.resolve(O.dirname(e),t):r&&(i=O.resolve(O.dirname(r.replace(`\0ssr-virtual:`,``).replace(`\0server-action-ref:`,``)),t));let a=b(i,[`.mjs`,`.mts`,`.ts`,`.tsx`,`.js`,`.jsx`])||ee(i,[`.mjs`,`.mts`,`.ts`,`.tsx`,`.js`,`.jsx`]);if(a&&l.isServerActionFile(a))return`\0server-action-ref:${O.resolve(a)}`;if(a&&n){let t=O.resolve(a),r=n.get(t);if(r&&t!==O.resolve(e))return{id:r,external:!0}}return a||null}return null}}]})).output[0],d=typeof u==`object`&&`code`in u?u.code:``;return await E.promises.writeFile(t,d,`utf-8`),{code:d}}async buildSingleComponent(e,t){let n=await E.promises.readFile(e,`utf-8`),r=this.transformClientImports(n,e),i=this.isPageComponent(e),a=i?this.transformComponentImportsToGlobal(r):r,o=O.extname(e),s;s=o===`.tsx`?`tsx`:o===`.ts`?`ts`:o===`.jsx`?`jsx`:`js`;let c=`\0virtual:${e}`,l=[],u=await N({input:c,platform:`node`,write:!1,external:[Bt,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${s}`]:s},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(k.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(c,a,s,e,i,l)});if(!u.output||u.output.length===0)throw Error(`No output generated from Rolldown`);let d=u.output.find(e=>e.type===`chunk`&&e.isEntry);if(!d||d.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let f=d.code;f=`// Built: ${new Date().toISOString()}\n${f}`,await E.promises.writeFile(t,f,`utf-8`);let p=await E.promises.open(t,`r+`);return await p.sync(),await p.close(),{code:f,css:l}}transformClientImports(e,t){let n=e,r,i=[],a=!1,o=Wt.map(e=>e.componentId);for(Pt.lastIndex=0;r=Pt.exec(e),r!==null;){let[e,n,s,c]=r,l=!1,u=c;if(o.includes(c))l=!0;else{let e=this.resolveImportPath(c,t);this.isClientComponent(e)&&(l=!0,u=O.relative(this.projectRoot,e).replace(v,`/`))}if(l){a=!0;let t=``;n?t=`const ${n} = registerClientReference(
|
|
89
89
|
null,
|
|
90
90
|
${JSON.stringify(u)},
|
|
91
91
|
"default"
|
|
@@ -94,9 +94,9 @@ export default registerClientReference(null, ${JSON.stringify(r)}, "default");
|
|
|
94
94
|
${JSON.stringify(u)},
|
|
95
95
|
${JSON.stringify(t)}
|
|
96
96
|
);`}).join(`
|
|
97
|
-
`)),i.push({original:e,replacement:t})}}a&&(n=`import { registerClientReference } from ${JSON.stringify(
|
|
98
|
-
const ${e} = createClientModuleProxy(${JSON.stringify(t)});`}const
|
|
99
|
-
`)},\n])`;return t.replace(
|
|
97
|
+
`)),i.push({original:e,replacement:t})}}a&&(n=`import { registerClientReference } from ${JSON.stringify(zt)};\n\n${n}`);for(let{original:e,replacement:t}of i)n=n.replace(e,t);return n}resolveImportPath(e,t){let n=e,r=this.options.alias||{};for(let[t,i]of Object.entries(r))if(e.startsWith(`${t}/`)||e===t){let r=e.slice(t.length).replace(/^\/+/,``);n=O.join(i,r);break}O.isAbsolute(n)||(n=O.resolve(O.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];return b(n,i)||ee(n,i)||`${n}.tsx`}getProjectRelativePath(e){return L(e,this.projectRoot)}getReadableComponentId(e){return ze(e)}getComponentId(e){return R(e,this.projectRoot)}async rebuildComponent(e){let t=this.getComponentId(e),n=await E.promises.readFile(e,`utf-8`),r=this.extractDependencies(n,e),i={filePath:e,originalCode:n,dependencies:r,hasNodeImports:this.hasNodeImports(n,e)};this.isServerAction(n,e)?(this.serverActions.set(e,i),this.serverComponents.delete(e)):(this.serverComponents.set(e,i),this.serverActions.delete(e));let a=O.join(this.options.rscDir,`${t}.js`),o=O.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await E.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.sourceDependencies)===JSON.stringify(r)){let n=this.serverActions.get(e)||this.serverComponents.get(e);return n&&s.bundledDependencies.length>0&&(n.dependencies=s.bundledDependencies),await E.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a,s.css),{componentId:t,bundlePath:O.join(this.options.outDir,a),success:!0}}let l=O.dirname(o);await E.promises.mkdir(l,{recursive:!0});let u=await this.buildSingleComponent(e,o),d=await this.writeComponentCssAsset(t,u.css),f=this.serverActions.get(e)||this.serverComponents.get(e);return this.buildCache.set(e,{code:u.code,css:d,timestamp:Date.now(),sourceDependencies:r,bundledDependencies:f?.dependencies??r}),await this.updateManifestForComponent(t,e,a,d),{componentId:t,bundlePath:O.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,t,n,r=[]){let i=O.join(this.options.outDir,this.options.manifestPath),a;if(this.manifestCache)a=this.manifestCache;else if(E.existsSync(i)){let e=await E.promises.readFile(i,`utf-8`);a=JSON.parse(e),this.manifestCache=a}else a={components:{},buildTime:new Date().toISOString()},this.manifestCache=a;let o=this.serverComponents.get(t)||this.serverActions.get(t),s=O.join(this.options.outDir,n),c=j(O.resolve(this.projectRoot,s)).href;if(o)a.components[e]={id:e,filePath:t,relativePath:O.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:c,dependencies:o.dependencies,hasNodeImports:o.hasNodeImports,css:r};else{let i=await E.promises.readFile(t,`utf-8`);a.components[e]={id:e,filePath:t,relativePath:O.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:c,dependencies:this.extractDependencies(i,t),hasNodeImports:this.hasNodeImports(i,t),css:r}}a.buildTime=new Date().toISOString(),await E.promises.writeFile(i,JSON.stringify(a),`utf-8`),await this.writeRouteCssEntries(a),this.manifestCache=a}clearCache(){this.buildCache.clear(),this.manifestCache=null}invalidateBuildCacheFor(e){this.buildCache.delete(e)}async getTransformedComponentCode(e){return await this.buildComponentCodeOnly(e)}};function tn(e,t){let n=[];for(let r of ot(t))try{let t=J(r),i=E.readFileSync(r,`utf-8`),a=e.getModuleAnalysis(r,i);n.push({filePath:r,cacheKey:t,code:i,analysis:a})}catch(e){console.warn(`[server-build] Error reading ${r}:`,e instanceof Error?e.message:e)}return n}function nn(e,t){return(t??K(e)).hasComponentExport||o.test(e)||d.test(e)||g.test(e)}function rn(e,t,n,r,i){let a=O.basename(e);if(Rt.test(a)||a.endsWith(`.d.ts`))return!1;let o=r??n.getModuleAnalysis(e,t);return o.directives.hasUseClient?!1:o.directives.hasUseServer?!0:n.isOnlyImportedByClientComponents(e)?!1:Z(e,o,n.getHtmlOnlyImports(),i)&&nn(t,o)}function an(e,t,n=[]){let r=tn(t,st(e,n));t.clearClientComponentFiles(),t.populateImportGraphFromFiles(r);let i=[],a=[];for(let{filePath:e,cacheKey:n,code:o,analysis:s}of r)s.directives.hasUseClient&&(a.push(e),t.recordClientComponent(e,o)),rn(e,o,t,s,n)&&(t.addServerComponent(e,o,s),i.push(e));return{serverComponentPaths:i,clientComponentPaths:a}}function on(e={}){let t=null,n,r=!1,i={};return{name:`rari-server-build`,configResolved(a){n=a.root,r=a.command===`serve`;let o=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react-dom/client`]),s={};if(a.resolve?.alias){let e=a.resolve.alias;Array.isArray(e)?e.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!o.has(e.find)&&(s[e.find]=e.replacement)}):typeof e==`object`&&Object.entries(e).forEach(([e,t])=>{typeof t==`string`&&!o.has(e)&&(s[e]=t)})}i=s,t=new en(n,{...e,alias:s})},buildStart(){if(!t)return;let e=k.env.NODE_ENV===`production`,r=[O.join(n,`dist`,`cache`,`og`),O.join(n,`dist`,`cache`,`images`)];e&&r.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of r)try{E.existsSync(e)&&E.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let a=O.join(n,`src`);E.existsSync(a)&&an(a,t,Object.values(i))},async closeBundle(){if(t){await t.buildServerComponents(),await t.buildSSRClientComponents();try{await t.buildMdxRegistry(e.mdx)}catch(e){console.warn(`[rari] Failed to build MDX component registry:`,e)}try{let{generateRobotsFile:e}=await import(`./robots-CsTVq3Jp.mjs`);await e({appDir:O.join(n,`src`,`app`),outDir:O.join(n,`dist`)})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-BekxZtgA.mjs`);await e({appDir:O.join(n,`src`,`app`),outDir:O.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}try{let{generateFeedFile:e}=await import(`./feed-B3mYPCnT.mjs`);await e({appDir:O.join(n,`src`,`app`),outDir:O.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate feed:`,e)}}},async handleHotUpdate({file:e}){if(!t||!r)return;let i=O.relative(n,e).replace(v,`/`);if(!(!i.startsWith(`src/`)||!u.test(i)))try{let n=await E.promises.readFile(e,`utf-8`),r=t.getModuleAnalysis(e,n),i=t.hasComponent(e);if(!rn(e,n,t,r)){i&&t.removeComponent(e);return}i||t.addServerComponent(e,n,r),await t.rebuildComponent(e)}catch(e){console.error(`[rari] Build: Error rebuilding ${i}:`,e)}}}}const sn=/^\s*import\s+\*\s+as\s+(\w+)\s+from\s+['"]([./@][^'"]+)['"].*$/;function cn(e,t){return`import { createClientModuleProxy } from "react-server-dom-rari/server";
|
|
98
|
+
const ${e} = createClientModuleProxy(${JSON.stringify(t)});`}const ln=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,un=/import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g,dn=/import\s+(\w+)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g,fn=/defineMdxComponents\s*\(\s*\{([\s\S]*?)\}\s*\)/;function pn(e,t,n){for(let r of t.split(`,`)){let t=r.trim();if(!t||(t=t.replace(/^type\s+/i,``).trim(),!t))continue;let i=t.split(/\s+as\s+/i),a=(i[1]??i[0])?.trim();a&&n.set(a,e)}}function mn(e){let t=new Map;for(let n of e.matchAll(dn))t.set(n[1],n[3]),pn(n[3],n[2],t);for(let n of e.matchAll(ln))t.set(n[1],n[2]);for(let n of e.matchAll(un))pn(n[2],n[1],t);return t}function hn(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(!e)continue;let r=e.indexOf(`:`);if(r===-1){t.push({name:e,binding:e});continue}let i=e.slice(0,r).trim(),a=e.slice(r+1).trim();i&&a&&t.push({name:i,binding:a})}return t}function gn(e){try{return K(E.readFileSync(e,`utf-8`)).topLevelUseClient}catch{return!1}}function _n(e){let{code:t,id:n,projectRoot:r,resolvedAlias:i}=e;if(!t.includes(`defineMdxComponents`)||t.includes(`__RARI_MDX_RESOLVED__`))return null;let a=t.match(fn);if(!a)return null;let o=mn(t),s=hn(a[1]);if(s.length===0)return null;let c=`defineMdxComponents(/* __RARI_MDX_RESOLVED__ */[\n${s.map(({name:e,binding:t})=>{let a=o.get(t);if(!a)throw Error(`[rari/mdx] Could not resolve import for MDX component "${e}" (binding "${t}") in ${n}`);let s=x(a,n,i),c=L(s,r).replace(v,`/`),l=gn(s);return` { name: ${JSON.stringify(e)}, component: ${t}, id: ${JSON.stringify(c)}, client: ${l} }`}).join(`,
|
|
99
|
+
`)},\n])`;return t.replace(fn,c)}function vn(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 yn(e,t,n,r){typeof e.getData==`function`&&vn(await e.getData({params:t,searchParams:n}),r)}async function bn(e,t,n,r){typeof e.getServerSideProps==`function`&&vn(await e.getServerSideProps({params:t,searchParams:n}),r)}async function xn(e,t,n){typeof e.getStaticProps==`function`&&vn(await e.getStaticProps({params:t}),n)}async function Sn(e,t,n){try{let r=await import(e),i={props:{}};return await yn(r,t,n,i),await bn(r,t,n,i),await xn(r,t,i),i}catch(t){return console.error(`[rari] Router: Failed to extract server props from ${e}:`,t),{props:{}}}}async function Cn(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 wn(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 Tn(e){try{let t=await import(e);return!!(t.getData||t.getServerSideProps||t.getStaticProps||t.generateMetadata||t.generateStaticParams)}catch{return!1}}const Q=new Map;async function En(e,t,n,r=6e4){let i=`${e}:${JSON.stringify(t)}:${JSON.stringify(n)}`,a=Q.get(i);if(a&&Date.now()-a.timestamp<r)return a.result;let o=await Sn(e,t,n);return Q.set(i,{result:o,timestamp:Date.now()}),o}function Dn(){Q.clear()}function On(e){for(let t of Q.keys())t.startsWith(e)&&Q.delete(t)}const kn="[rari] Runtime dist not built. Run `pnpm build` in the rari package first.",An=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,jn=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Mn=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Nn=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Pn=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Fn=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,In=/import\s+["']\.\.?\/([^"']+)["'];?/g,Ln=/export\s*\{([^}]+)\}/g,Rn=/\s+as\s+/,zn=/export\s+default\s+(?:function|class)\s+\w+/,Bn=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,Vn=/export\s+default\s+([^;]+)/,Hn=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,Un=/^['"]use client['"];?\s*$/gm,Wn=/import\s+["']([^"']+)["']/g,Gn=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,Kn=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,qn=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,Jn=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,Yn=/import\s+["']([^"']+)["']/g,Xn=/from(\s*)(['"])(?:\.\/vendor\/react-flight-client\/index|rari\/runtime\/vendor\/react-flight-client\/index)\.mjs\2/g,Zn=/\bJSX\b/,Qn=/\{([^}]*)\}/,$n=/^['"]use client['"];?\s*\n/;function er(e,t){let n=[];t&&n.push({bindingName:t,exportName:`default`});let r=e.match(/\{([^}]+)\}/)?.[1];if(r)for(let e of r.split(`,`)){let t=e.trim();if(!t)continue;let r=t.split(/\s+as\s+/i);r.length===2&&r[0]&&r[1]?n.push({bindingName:r[1].trim(),exportName:r[0].trim()}):n.push({bindingName:t,exportName:t})}return n}function tr(e,t){return`import { registerClientReference } from "react-server-dom-rari/server";
|
|
100
100
|
${e.map(({bindingName:e,exportName:n})=>`const ${e} = registerClientReference(
|
|
101
101
|
function() {
|
|
102
102
|
throw new Error("Attempted to call ${e} from the server but it's on the client. It can only be rendered as a Component or passed to props of a Client Component.");
|
|
@@ -104,12 +104,12 @@ ${e.map(({bindingName:e,exportName:n})=>`const ${e} = registerClientReference(
|
|
|
104
104
|
${JSON.stringify(t)},
|
|
105
105
|
${JSON.stringify(n)}
|
|
106
106
|
);`).join(`
|
|
107
|
-
`)}`}const
|
|
107
|
+
`)}`}const nr={remotePatterns:[],localPatterns:[],deviceSizes:a,imageSizes:i,formats:n,qualityAllowlist:r,minimumCacheTTL:60,maxCacheSize:t},rr=new Map;async function ir(e){let t=rr.get(e);if(t)return t;let n=import.meta.url,r=A(n),i=O.dirname(r),a=[O.join(i,`runtime`,e),O.join(i,`../runtime`,e)];for(let t of a)try{let n=await E.promises.readFile(t,`utf-8`);return t.endsWith(`.ts`)&&(n=n.replace(An,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(jn,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(Mn,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(Nn,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(Pn,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(Fn,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(In,(e,t)=>`import "rari/${t}";`)),rr.set(e,n),n}catch(e){e.code!==`ENOENT`&&e.code!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${t}:`,e)}throw Error(`Could not find ${e}. Tried: ${a.join(`, `)}`)}const ar=O.dirname(A(import.meta.url)),or=O.dirname(ar);function $(e){let t=[O.join(ar,`runtime`,e),O.join(ar,`../runtime`,e)];for(let e of t)if(E.existsSync(e))return e;return null}function sr(e){return e.startsWith(or)}async function cr(){return ir(`rsc-client-runtime.mjs`)}async function lr(e,t){return(await ir(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function ur(){return ir(`rsc-references.mjs`)}async function dr(e,t){let n=O.join(e,`src`),{getBinaryPath:r}=await import(`./platform.mjs`),i=T(r(),[`scan-images`,`--src`,n],{encoding:`utf8`,cwd:e,shell:!1,timeout:6e4});if(i.error)throw Error(`Failed to scan for image usage: ${i.error.message}`);if(i.signal)throw Error(`Failed to scan for image usage: process terminated by signal ${i.signal}`);if(i.status!==0)throw Error(`Failed to scan for image usage: ${i.stderr||i.stdout||`exit code ${i.status}`}`);let a;try{a=JSON.parse(i.stdout)}catch(e){let t=e instanceof SyntaxError||e instanceof Error?e.message:String(e),n=(i.stdout||i.stderr||`(empty)`).slice(0,500);throw Error(`Failed to parse image scanner output as JSON: ${t}. Scanner output: ${n}`,{cause:e})}let o={...nr,...t.images,preoptimizeManifest:a.images},s=O.join(e,`dist`),c=O.join(s,`server`);E.existsSync(c)||E.mkdirSync(c,{recursive:!0});let l=O.join(c,`image.json`);E.writeFileSync(l,JSON.stringify(o))}function fr(e){return e}function pr(e={}){let t=new Map,n=new Set,r=new mt,i=null,a=null,o=null,s={},c=null;function d(){c=null}function f(){return c||(c=wt(Ct({projectRoot:e.projectRoot||k.cwd(),mdxOptions:e.mdx,alias:s,cache:r})),c)}function p(e){return t.get(J(e))}function h(e,n){t.set(J(e),n)}function g(e){ft(t,e)}function b(e){n.add(J(e))}function ee(e){return n.has(J(e))}function ne(e){n.delete(e);try{n.delete(E.realpathSync(e))}catch{n.delete(O.resolve(e))}}function S(){let e=new Set(n);if(i)for(let t of i.getClientComponentPaths())e.add(t);return e}function re(e){let t={hasUseServer:!1,hasUseClient:!1},n=e.replace(v,`/`);if(!u.test(n)||!n.includes(`/src/`))return t;try{let n=r.get(e);t.hasUseServer=n.directives.hasUseServer,t.hasUseClient=n.directives.hasUseClient}catch{}return t}let C=null,ie=null;function ae(){if(i)return i.getHtmlOnlyImports();let t=e.projectRoot||k.cwd(),n=O.join(t,`index.html`);try{let e=E.statSync(n).mtimeMs;if(C!==null&&e===ie)return C;ie=e}catch{return C===null&&(C=new Set),C}return C=jt(t),C}function w(e){if(e.includes(`node_modules`)||sr(e))return!1;let t=J(e);try{return Z(t,r.get(e),ae(),t)}catch{return!1}}function T(e,t){try{let n=[],r=e.matchAll(Ln);for(let e of r){let t=e[1].split(`,`);for(let e of t){let t=e.trim().split(Rn).at(-1)?.trim();t&&n.push(t)}}(zn.test(e)||(t?.hasDefaultExport??Qe(e)))&&n.push(`default`);let i=e.matchAll(Hn);for(let e of i)e[1]&&n.push(e[1]);return[...new Set(n)]}catch{return[]}}function D(t,n,r){if(!r.topLevelUseServer)return t;let i=T(t,r);if(i.length===0)return t;let a=R(n,e.projectRoot||k.cwd()),o=JSON.stringify(a),s=t;s+=`
|
|
108
108
|
|
|
109
109
|
import {registerServerReference} from "react-server-dom-rari/server";
|
|
110
|
-
`;for(let e of i)if(e==="default"){let n=t.match(
|
|
110
|
+
`;for(let e of i)if(e==="default"){let n=t.match(Bn);if(n){let t=n[1];s+=`
|
|
111
111
|
// Register server reference for default export
|
|
112
|
-
`,s+=`registerServerReference(${t}, ${o}, ${JSON.stringify(e)});\n`}else{let n=t.match(
|
|
112
|
+
`,s+=`registerServerReference(${t}, ${o}, ${JSON.stringify(e)});\n`}else{let n=t.match(Vn);if(n){let t=n[1].trim(),r=`__default_export__`;s=s.replace(Vn,`const ${r} = ${t};\nexport default ${r}`),s+=`
|
|
113
113
|
// Register server reference for default export
|
|
114
114
|
`,s+=`if (typeof ${r} === "function") {\n`,s+=` registerServerReference(${r}, ${o}, ${JSON.stringify(e)});\n`,s+=`}
|
|
115
115
|
`}}}else s+=`\n// Register server reference for ${e}\n`,s+=`if (typeof ${e} === "function") {\n`,s+=` registerServerReference(${e}, ${o}, ${JSON.stringify(e)});\n`,s+=`}
|
|
@@ -118,11 +118,11 @@ import {registerServerReference} from "react-server-dom-rari/server";
|
|
|
118
118
|
if (import.meta.hot) {
|
|
119
119
|
import.meta.hot.accept(() => {
|
|
120
120
|
});
|
|
121
|
-
}`,s}function j(t,n,r){let i=e.projectRoot||
|
|
121
|
+
}`,s}function j(t,n,r){let i=e.projectRoot||k.cwd(),a=w(n);if(r.topLevelUseServer){let e=T(t,r);if(e.length===0)return``;let a=R(n,i),o=`import { createServerReference } from "virtual:react-flight-client";
|
|
122
122
|
`;o+=`import { callServer } from "rari/runtime/call-server";
|
|
123
|
-
`;for(let t of e){let e=`${a}#${t}`,n=JSON.stringify(e);t==="default"?o+=`export default createServerReference(${n}, callServer);\n`:o+=`export const ${t} = createServerReference(${n}, callServer);\n`}return o}if(a)return console.warn(`[rari] Server component ${n} should not be imported in client bundle`),``;if(!r.topLevelUseClient)return t;let o=
|
|
124
|
-
`;for(let e of o){if(e==="default"){let e=`Attempted to call the default export of ${n} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export default `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(e)});`}else{let t=`Attempted to call ${e}() from the server but ${e} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export const ${e} = `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(t)});`}c+=`},`,c+=`${s},`,c+=`${JSON.stringify(e)});\n`}return c}function M(e,t,n){return!n.topLevelUseClient||
|
|
125
|
-
`);for(let t of e){let e=t.match(
|
|
123
|
+
`;for(let t of e){let e=`${a}#${t}`,n=JSON.stringify(e);t==="default"?o+=`export default createServerReference(${n}, callServer);\n`:o+=`export const ${t} = createServerReference(${n}, callServer);\n`}return o}if(a)return console.warn(`[rari] Server component ${n} should not be imported in client bundle`),``;if(!r.topLevelUseClient)return t;let o=T(t,r);if(o.length===0)return``;let s=JSON.stringify(n),c=`import {registerClientReference} from "react-server-dom-rari/server";
|
|
124
|
+
`;for(let e of o){if(e==="default"){let e=`Attempted to call the default export of ${n} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export default `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(e)});`}else{let t=`Attempted to call ${e}() from the server but ${e} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export const ${e} = `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(t)});`}c+=`},`,c+=`${s},`,c+=`${JSON.stringify(e)});\n`}return c}function M(e,t,n){return!n.topLevelUseClient||T(e,n).length===0?e:e.replace(Un,``)}let N=!1;async function P(){let e=`http://localhost:${k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3)}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return N=t,t}catch{return N=!1,!1}}let F=[{name:`rari`,config(t,{command:n}){if(t.define=t.define||{},n===`serve`||k.env.RARI_SERVER_URL||k.env.RARI_HOST){let e=k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3),n;if(k.env.RARI_SERVER_URL)n=k.env.RARI_SERVER_URL;else if(k.env.RARI_HOST){let t=k.env.RARI_HOST.startsWith(`http`)?k.env.RARI_HOST:`http://${k.env.RARI_HOST}`;n=t.replace(y,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}let r=typeof t.css?.modules==`object`?t.css.modules:{};if(t.css={...t.css,transformer:t.css?.transformer??`lightningcss`,modules:{...r,pattern:Vt}},n===`build`){let n=e.projectRoot||k.cwd(),r=O.join(n,`index.html`);if(E.existsSync(r))try{let e=E.readFileSync(r,`utf-8`),n=[];for(let t of e.matchAll(Wn)){let e=t[1];if(e.startsWith(`/src/`)&&u.test(e)){let t=e.slice(1),r=O.basename(t,O.extname(t));n.push({path:t,name:r})}}if(n.length>0){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{};let e=t.build.rolldownOptions.input||{main:`./index.html`},r;r=typeof e==`string`?{main:e}:Array.isArray(e)?{main:e[0]||`./index.html`}:{...e},n.forEach(({path:e,name:t})=>{r[t]=`./${e}`}),t.build.rolldownOptions.input=r}}catch(e){console.warn(`[rari] Error parsing index.html for build inputs:`,e)}}t.resolve=t.resolve||{};let i=Array.isArray(t.resolve.dedupe)?t.resolve.dedupe:[],a=[`react`,`react-dom`];t.resolve.dedupe=[...new Set([...i||[],...a])];let o=[];Array.isArray(t.resolve.alias)?o=t.resolve.alias:t.resolve.alias&&typeof t.resolve.alias==`object`&&(o=Object.entries(t.resolve.alias).map(([e,t])=>({find:e,replacement:t})));let s=new Set(o.map(e=>String(e.find)));try{let e=A(import.meta.resolve(`react`)),n=A(import.meta.resolve(`react-dom/client`)),r=A(import.meta.resolve(`react/jsx-runtime`)),i=[];s.has(`react/jsx-runtime`)||i.push({find:`react/jsx-runtime`,replacement:r});try{let e=A(import.meta.resolve(`react/jsx-dev-runtime`));s.has(`react/jsx-dev-runtime`)||i.push({find:`react/jsx-dev-runtime`,replacement:e})}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving react/jsx-dev-runtime:`,e)}s.has(`react`)||i.push({find:`react`,replacement:e}),s.has(`react-dom/client`)||i.push({find:`react-dom/client`,replacement:n}),i.length>0&&(t.resolve.alias=[...o,...i])}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error configuring React aliases:`,e)}t.environments=t.environments||{},t.environments.rsc={resolve:{conditions:[`react-server`,`node`,`import`]},...t.environments.rsc},t.environments.ssr={resolve:{conditions:[`node`,`import`]},...t.environments.ssr},t.environments.client={resolve:{conditions:[`browser`,`import`]},...t.environments.client},t.optimizeDeps=t.optimizeDeps||{},t.optimizeDeps.include=t.optimizeDeps.include||[];for(let e of[`react`,`react-dom`,`react-dom/client`,`react-dom/server`,`react/jsx-runtime`,`react/jsx-dev-runtime`])t.optimizeDeps.include.includes(e)||t.optimizeDeps.include.push(e);if(t.optimizeDeps.exclude=t.optimizeDeps.exclude||[],t.optimizeDeps.exclude.includes(`rari`)||t.optimizeDeps.exclude.push(`rari`),n===`build`)for(let e of[`rsc`,`ssr`,`client`]){let n=t.environments[e];n&&n.build&&(n.build.rolldownOptions=n.build.rolldownOptions||{})}t.server=t.server||{},t.server.proxy=t.server.proxy||{};let c=k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3);if(t.server.proxy[`/api`]={target:`http://localhost:${c}`,changeOrigin:!0,secure:!1,ws:!0},t.server.proxy[`/_rari`]={target:`http://localhost:${c}`,changeOrigin:!0,secure:!1,ws:!0},n===`build`){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{},t.build.rolldownOptions.input||(t.build.rolldownOptions.input={main:`./index.html`}),t.build.rolldownOptions.output=t.build.rolldownOptions.output||{};let e=Array.isArray(t.build.rolldownOptions.output)?t.build.rolldownOptions.output:[t.build.rolldownOptions.output];for(let t of e){if(t.codeSplitting!==!1&&typeof t.codeSplitting!=`object`&&(t.codeSplitting={}),typeof t.codeSplitting==`object`){t.codeSplitting.groups=t.codeSplitting.groups||[];let e=t.codeSplitting.groups;t.codeSplitting.groups.push({name(t){if(t.includes(`node_modules`)){for(let n of e)if(n.test){let e=!1;if(typeof n.test==`function`?e=!!n.test(t):n.test instanceof RegExp?e=n.test.test(t):typeof n.test==`string`&&(e=t.includes(n.test)),e)return null}return t.includes(`node_modules/react-dom`)?`react-dom`:t.includes(`node_modules/react`)?`react`:`vendor`}return null}})}t.chunkFileNames||=e=>e.moduleIds?.some(e=>re(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds?.some(e=>re(e).hasUseClient)?`client/components/[name]-[hash].js`:`assets/[name]-[hash].js`}}if(t.environments&&t.environments.client){t.environments.client.build||(t.environments.client.build={}),t.environments.client.build.rolldownOptions||(t.environments.client.build.rolldownOptions={}),t.environments.client.build.rolldownOptions.input||(t.environments.client.build.rolldownOptions.input={}),t.environments.client.build.rolldownOptions.external||(t.environments.client.build.rolldownOptions.external=[]);let e=t.environments.client.build.rolldownOptions.external;if(Array.isArray(e)){let t=e.indexOf(`react-server-dom-webpack/client`);t!==-1&&e.splice(t,1)}}return t},configResolved(e){let t=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react-dom/client`]);if(e.resolve?.alias){let n=e.resolve.alias;Array.isArray(n)?n.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!t.has(e.find)&&(s[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(s[e]=n)})}},async transform(t,n){if(n.endsWith(`.mdx`)&&d(),/\.(?:tsx?|jsx?|mts|mjs)$/.test(n)&&t.includes(`defineMdxComponents`)){let r=_n({code:t,id:n,projectRoot:e.projectRoot||k.cwd(),resolvedAlias:s});if(r)return{code:r,map:null}}if(!u.test(n))return null;let i=t,a=!1;if(e.experimental?.useCache||e.experimental?.useCacheRemote){let e=await Mt();if(e){let r=e(t,n);r&&(t=r,a=!0)}}let o=this.environment,c=r.get(n,i);if(c.topLevelUseClient){h(n,`client`),b(n);let e=t.split(`
|
|
125
|
+
`);for(let t of e){let e=t.match(sn),r=e?null:t.match(Gn);if(!e&&!r)continue;let i=e?.[2]??r[4];if(!i)continue;let a=x(i,n,s);E.existsSync(a)&&(h(a,`client`),b(a))}return M(t,n,c)}if(p(n)===`client`||ee(n))return M(t,n,c);if(w(n)){if(h(n,`server`),o&&(o.name===`rsc`||o.name===`ssr`))return D(t,n,c);{let e=j(t,n,c);return e=`// HMR acceptance for server component
|
|
126
126
|
if (import.meta.hot) {
|
|
127
127
|
import.meta.hot.accept();
|
|
128
128
|
if (typeof globalThis !== 'undefined') {
|
|
@@ -132,9 +132,9 @@ if (import.meta.hot) {
|
|
|
132
132
|
}
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
-
${e}`,e}}if(c.topLevelUseServer)return h(n,`server`),o&&(o.name===`rsc`||o.name===`ssr`)?
|
|
136
|
-
`),m=t,g=!1,_=!1,v=n.includes(`entry-client`);for(let e of f){let t=e.match(
|
|
137
|
-
`),t&&(m=t+m),!m.includes(`Suspense`)){let e=m.match(
|
|
135
|
+
${e}`,e}}if(c.topLevelUseServer)return h(n,`server`),o&&(o.name===`rsc`||o.name===`ssr`)?D(t,n,c):j(t,n,c);let l=p(n);if(l===`server`)return o&&(o.name===`rsc`||o.name===`ssr`)?D(t,n,c):j(t,n,c);if(l===`client`)return M(t,n,c);h(n,`unknown`);let f=t.split(`
|
|
136
|
+
`),m=t,g=!1,_=!1,v=n.includes(`entry-client`);for(let e of f){let t=e.match(sn),i=t?null:e.match(Gn);if(!t&&!i)continue;let a=i?.[1],c=x(t?.[2]??i[4],n,s),l=p(c)===`client`||E.existsSync(c)&&r.get(c).topLevelUseClient;if(l&&(h(c,`client`),b(c)),l&&o&&(o.name===`rsc`||o.name===`ssr`)&&!v){let n=e;if(t){let e=cn(t[1],c);m=m.replace(n,e),g=!0,_=!0;continue}let r=er(e,a);if(r.length===0)continue;let i=tr(r,c);m=m.replace(n,i),g=!0,_=!0}}if(g){let e=m.includes(`import React`)||m.match(Kn)||m.match(qn),t=``;if(_&&!e&&(t+=`import React from 'react';
|
|
137
|
+
`),t&&(m=t+m),!m.includes(`Suspense`)){let e=m.match(Jn);e&&(e[1]&&!e[2].includes(`Suspense`)?m=m.replace(e[0],e[0].replace(Qn,`{ Suspense, $1 }`)):e[1]||(m=m.replace(e[0],`import React, { Suspense } from 'react';`)))}let r=k.env.NODE_ENV!==`production`;return(m.includes(`</`)||m.includes(`/>`)||Zn.test(m))&&r&&(m=`'use client';\n\n${m}`,h(n,`client`)),m}return a?t:null},async configureServer(t){let n=e.projectRoot||k.cwd(),c=O.join(n,`src`);await dr(n,e);let l=async()=>{try{let a=new en(n,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:s,csp:e.csp,cacheControl:e.cacheControl,cache:e.cache,experimental:e.experimental,moduleAnalysisCache:r});if(i=a,o||=new gt(a,k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3)),E.existsSync(c)){let e=an(c,a,Object.values(s));e.serverComponentPaths.length>0&&t.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:e.serverComponentPaths}})}let l=await a.getTransformedComponentsForDevelopment(),u=`http://localhost:${k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3)}`;for(let e of l)try{if(e.id.startsWith(`app/`)||e.isAction)continue;let t=await fetch(`${u}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Runtime: Failed to register component ${e.id}:`,t instanceof Error?t.message:String(t))}}catch(e){console.error(`[rari] Runtime: Component discovery failed:`,e instanceof Error?e.message:String(e))}},d=async()=>{try{let e=`http://localhost:${k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3)}`,t=S();for(let n of t){let t=O.relative(k.cwd(),n),r=O.basename(n).replace(_,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:t,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${r}:`,e)}}}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},f=async()=>{if(a)return;let{getBinaryPath:e,getInstallationInstructions:n}=await import(`./platform.mjs`),r;try{r=e()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(n());return}let i=k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3),o=k.env.NODE_ENV===`production`?`production`:`development`,s=t.config.server.port||5173,c=[`--mode`,o,`--port`,i.toString(),`--host`,`127.0.0.1`];a=se(r,c,{stdio:[`ignore`,`pipe`,`pipe`],cwd:k.cwd(),env:{...k.env,RUST_LOG:k.env.RUST_LOG||`error`,RARI_VITE_PORT:s.toString()}}),a.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),a.on(`error`,e=>{N=!1,console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),a.on(`exit`,(e,t)=>{a=null,N=!1,t?console.error(`rari server stopped by signal ${t}`):e===0?console.error(`rari server stopped successfully`):e&&console.error(`rari server exited with code ${e}`)});let u=!1;for(let e=0;e<20&&(u=await P(),!u);e++)await new Promise(e=>setTimeout(e,500));u?(await l(),await d()):console.error(`Server failed to become ready for component registration`)},p=async e=>{try{if(!w(e)||!i&&(await l(),!i))return;let t=r.getSource(e);i.addServerComponent(e,t);let n=await i.getTransformedComponentsForDevelopment();if(n.length===0)return;let a=`http://localhost:${k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3)}`;for(let e of n)try{let t=await fetch(`${a}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}catch(t){console.error(`[rari] Targeted HMR failed for`,`${e}:`,t instanceof Error?t.message:String(t)),setTimeout(l,1e3)}};f().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),t.middlewares.use(async(e,t,n)=>{let r=e.headers.accept;if(r&&r.includes(`text/x-component`)&&e.url&&!e.url.startsWith(`/api`)&&!e.url.startsWith(`/rsc`)&&!e.url.includes(`.`)){if(!N&&!await P()){let e=Date.now();for(;Date.now()-e<1e4&&!await P();)await new Promise(e=>setTimeout(e,100));if(!N){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}}let n=k.env.SERVER_PORT?Number(k.env.SERVER_PORT):Number(k.env.PORT||k.env.RSC_PORT||3e3),r=`http://localhost:${n}${e.url}`;try{let i={};for(let[t,n]of Object.entries(e.headers))typeof n==`string`?i[t]=n:Array.isArray(n)&&(i[t]=n.join(`,`));i.host=`localhost:${n}`,i[`accept-encoding`]=`identity`;let a=await fetch(r,{method:e.method,headers:i});if(t.statusCode=a.status,a.headers.forEach((e,n)=>{n.toLowerCase()!==`content-encoding`&&t.setHeader(n,e)}),a.body){let e=a.body.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)break;t.write(oe.from(r))}t.end()}catch(e){console.error(`[rari] Stream error:`,e),t.headersSent||(t.statusCode=500),t.end()}}else t.end();return}catch(e){console.error(`[rari] Failed to proxy RSC request:`,e),t.headersSent||(t.statusCode=500,t.end(`Internal Server Error`));return}}n()}),t.watcher.on(`change`,async e=>{u.test(e)&&(g(e),ne(e),r.invalidate(e)),u.test(e)&&e.includes(c)&&(w(e)?(t.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await p(e)):setTimeout(l,1e3))}),t.middlewares.use(`/api/vite/hmr-transform`,async(e,t)=>{if(e.method!==`POST`){t.statusCode=405,t.end(`Method Not Allowed`);return}let n=``;e.on(`data`,e=>{n+=e.toString()}),e.on(`end`,async()=>{try{let{filePath:e}=JSON.parse(n);if(!e){t.statusCode=400,t.end(JSON.stringify({error:`filePath is required`}));return}await p(e),t.statusCode=200,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!0,filePath:e,message:`Component transformation completed`}))}catch(e){t.statusCode=500,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)}))}})}),t.httpServer?.on(`close`,()=>{if(o&&=(o.dispose(),null),a){let e=a;a=null,N=!1;let t=!1,n=setTimeout(()=>{t||e.kill(`SIGKILL`)},5e3);n.unref?.(),e.once(`exit`,()=>{t=!0,clearTimeout(n)}),e.kill(`SIGTERM`);return}N=!1})},resolveId(e,t){if(e===`virtual:rsc-integration`||e===`virtual:rsc-integration.ts`)return`virtual:rsc-integration.ts`;if(e===`virtual:rari-entry-client`||e===`virtual:rari-entry-client.ts`)return`virtual:rari-entry-client.ts`;if(e===`virtual:react-flight-client`||e===`virtual:react-flight-client.ts`)return`virtual:react-flight-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`virtual:error-boundary-wrapper`||e===`virtual:error-boundary-wrapper.tsx`)return`virtual:error-boundary-wrapper.tsx`;if(vt(e)||e===`virtual:rari-mdx-components`||e===`virtual:rari-mdx-components.ts`)return`virtual:rari-mdx-components.ts`;if(e===`react-server-dom-webpack/client`||e===`react-server-dom-webpack/client.browser`)return`virtual:react-flight-client.ts`;if(e===`./LoadingErrorBoundary`||e===`./LoadingErrorBoundary.tsx`)return`virtual:loading-error-boundary.tsx`;if(e===`react-server-dom-rari/server`)return e;if(t&&t.startsWith(`virtual:`)&&e.startsWith(`./`)){let t=$(O.basename(e));if(t)return t}if(t&&t.startsWith(`virtual:`)&&e.startsWith(`../`)){let n=import.meta.url,r=A(n),i=O.dirname(r),a=null,o=[O.join(i,`runtime`),O.join(i,`../runtime`)];for(let e of o)if(E.existsSync(e)){a=e;break}if(a){let t=O.join(a,e);if(E.existsSync(t))return t;let n=O.join(a,`../dist`,O.basename(e));if(E.existsSync(n))return n}else console.warn(`[rari] Runtime directory not found, attempting fallback resolution for virtual import.\n Importer: ${t}\n ID: ${e}\n Current Dir: ${i}\n Hint: Runtime lookup failed, trying currentDir as fallback`);let s=O.join(i,e);if(E.existsSync(s))return s;let c=O.join(i,`../dist`,O.basename(e));if(E.existsSync(c))return c}if(k.env.NODE_ENV===`production`)try{let t=O.resolve(e);if(E.existsSync(t)&&w(t))return{id:e,external:!0}}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving server component:`,e,t)}return null},async load(t){if(u.test(t)){let e=this.environment;if(e&&e.name===`client`)try{let e=r.get(t);if(e.topLevelUseServer)return j(r.getSource(t),t,e)}catch{}}if(t===`virtual:rari-mdx-components.ts`)return f();if(t===`virtual:rari-entry-client.ts`){let t=e.projectRoot||k.cwd(),n=pt(st(O.join(t,`src`),Object.values(s)),r),i=new Set([...S(),...n]),a=[{path:`rari/image`,exports:[`Image`]},{path:`virtual:error-boundary-wrapper.tsx`,exports:[`ErrorBoundaryWrapper`]}],o=[...i].filter(e=>{try{return r.get(e).topLevelUseClient}catch{return!1}}).map(e=>{let t=O.relative(k.cwd(),e).replace(v,`/`),n=t.replace(u,``),i=t.startsWith(`..`)?e.replace(v,`/`):t,a=!1,o=``;try{if(!r.get(e).hasDefaultExport){let t=r.getSource(e).match(m);t&&(a=!0,o=t[1])}}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let s=a?o:`default`,c=a?o:O.basename(e,O.extname(e)),d=i.replace(v,`/`),f=d.startsWith(`/`)||l.test(d)?d:`/${d}`;return` "${i}": {
|
|
138
138
|
id: "${n}",
|
|
139
139
|
path: "${i}",
|
|
140
140
|
exportName: "${s}",
|
|
@@ -159,7 +159,7 @@ globalThis['~clientComponents']["${e.path}"] = globalThis['~clientComponents']["
|
|
|
159
159
|
globalThis['~clientComponents']["${e.path}"].component = ExternalModule${t};
|
|
160
160
|
globalThis['~clientComponentPaths'] = globalThis['~clientComponentPaths'] || {};
|
|
161
161
|
globalThis['~clientComponentPaths']["${e.path}"] = "${n}";`)).join(`
|
|
162
|
-
`);return await
|
|
162
|
+
`);return await lr(c,[`
|
|
163
163
|
const lazyComponentRegistry = {
|
|
164
164
|
${o}
|
|
165
165
|
};
|
|
@@ -172,9 +172,9 @@ for (const [path, config] of Object.entries(lazyComponentRegistry)) {
|
|
|
172
172
|
globalThis['~clientComponentPaths'][path] = config.id;
|
|
173
173
|
}
|
|
174
174
|
`,d].filter(Boolean).join(`
|
|
175
|
-
`))}if(t===`react-server-dom-rari/server`)return await
|
|
175
|
+
`))}if(t===`react-server-dom-rari/server`)return await ur();if(t===`virtual:app-router-provider.tsx`){let e=$(`AppRouterProvider.mjs`);if(e)return E.readFileSync(e,`utf-8`);throw Error(kn)}if(t===`virtual:loading-error-boundary.tsx`){let e=$(`LoadingErrorBoundary.mjs`);if(e)return E.readFileSync(e,`utf-8`);throw Error(kn)}if(t===`virtual:error-boundary-wrapper.tsx`){let e=$(`ErrorBoundaryWrapper.mjs`);if(e){let t=E.readFileSync(e,`utf-8`);if(!t.includes(`import React`)&&!t.includes(`from "react"`)&&!t.includes(`from 'react'`)){let e=t.match($n);if(e){let n=e[0];return`
|
|
176
176
|
${n}import * as React from 'react';\n${t.slice(n.length)}`}return`
|
|
177
|
-
import * as React from 'react';\n${t}`}return t}throw Error(
|
|
177
|
+
import * as React from 'react';\n${t}`}return t}throw Error(kn)}if(t===`virtual:rsc-integration.ts`)return(await cr()).replace(Xn,(e,t,n)=>`from${t}${n}virtual:react-flight-client.ts${n}`);if(t===`virtual:react-flight-client.ts`){let e,t;try{let n=O.dirname(A(import.meta.resolve(`react-server-dom-webpack/package.json`)));e=O.join(n,`cjs/react-server-dom-webpack-client.browser.production.js`),t=O.join(n,`cjs/react-server-dom-webpack-client.edge.production.js`)}catch{let n=O.dirname(A(import.meta.url)),r=O.resolve(n,`../../node_modules`);e=O.join(r,`react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.js`),t=O.join(r,`react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.production.js`)}return{code:`
|
|
178
178
|
import * as React from 'react';
|
|
179
179
|
import * as ReactDOM from 'react-dom';
|
|
180
180
|
import { callServer as rariCallServer } from 'rari/runtime/call-server';
|
|
@@ -182,7 +182,7 @@ import { callServer as rariCallServer } from 'rari/runtime/call-server';
|
|
|
182
182
|
const module = { exports: {} };
|
|
183
183
|
const exports = module.exports;
|
|
184
184
|
(function(module, exports, require) {
|
|
185
|
-
${Le(
|
|
185
|
+
${Re(Le(E.readFileSync(e,`utf-8`),E.readFileSync(t,`utf-8`)))}
|
|
186
186
|
})(module, module.exports, function require(id) {
|
|
187
187
|
if (id === 'react') return React;
|
|
188
188
|
if (id === 'react-dom') return ReactDOM;
|
|
@@ -198,4 +198,4 @@ export function createFromReadableStream(stream, options) {
|
|
|
198
198
|
export const createServerReference = module.exports.createServerReference;
|
|
199
199
|
export const encodeReply = module.exports.encodeReply;
|
|
200
200
|
export const createTemporaryReferenceSet = module.exports.createTemporaryReferenceSet;
|
|
201
|
-
`}}if(t.endsWith(`.mjs`)&&
|
|
201
|
+
`}}if(t.endsWith(`.mjs`)&&E.existsSync(t))try{let n=e.projectRoot||k.cwd(),r=E.realpathSync(t),i=O.relative(n,r),a=!i.startsWith(`..`)&&!O.isAbsolute(i),o=r.includes(`${O.sep}node_modules${O.sep}`),s=r.includes(`${O.sep}packages${O.sep}rari${O.sep}`)||r.includes(`${O.sep}node_modules${O.sep}rari${O.sep}`);return a||o||s?E.readFileSync(t,`utf-8`):(console.warn(`[rari] Refusing to load .mjs file outside project root and node_modules: ${t}`),null)}catch(e){return console.warn(`[rari] Error validating .mjs file path: ${t}`,e),null}},async handleHotUpdate({file:e,server:t}){if(te(),e.endsWith(`.mdx`)&&d(),!u.test(e))return;if(g(e),ne(e),r.invalidate(e),d(),e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let n=o?.detectComponentType(e)||`unknown`,i=e.includes(`/app/`)||e.includes(`\\app\\`),a=(e,t)=>e.endsWith(`${t}.tsx`)||e.endsWith(`${t}.jsx`)||e.endsWith(`${t}.ts`)||e.endsWith(`${t}.js`),s=[`page`,`layout`,`template`,`loading`,`error`,`not-found`].some(t=>a(e,t));if(!(i&&s)&&n!==`client`&&n===`server`)return o&&await o.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(Yn)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}let n=[];n.push({tag:`script`,attrs:{type:`module`},children:`import 'virtual:rari-entry-client';`,injectTo:`head-prepend`}),t.length>0&&n.push(...t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`})));let r=e;r=r.replace(/^\s*import\s+["']\/src\/[^"']+["'];?\s*$/gm,``),r=r.replace(/^\s*import\s+["']virtual:rari-entry-client["'];?\s*$/gm,``);let i;do i=r,r=r.replace(/<script\s+type=["']module["'][^>]*>\s*<\/script>/gi,``);while(r!==i);return{html:r,tags:n}}},async writeBundle(){await dr(e.projectRoot||k.cwd(),e)}},{name:`rari:patch-react-server-dom-webpack`,transform(e){if(!e.includes(`__webpack_require__`)&&!e.includes(`__webpack_chunk_load__`))return null;let t=e;return t.includes(`__webpack_chunk_load__`)&&(t=t.replaceAll(`__webpack_chunk_load__`,`__rari_chunk_load__`)),t.includes(`__webpack_require__.u`)&&(t=t.replaceAll(`__webpack_require__.u`,`({}).u`)),t.includes(`__webpack_require__`)&&(t=t.replaceAll(`__webpack_require__`,`__rari_rsc_require__`)),t===e?null:{code:t,map:null}}},on({...e.serverBuild,csp:e.csp,cacheControl:e.cacheControl,cache:e.cache,experimental:e.experimental,moduleAnalysisCache:r,mdx:e.mdx})];return e.proxy!==!1&&F.push(le(e.proxy||{})),e.router!==!1&&F.push(Ie(e.router||{})),ce(F)}function mr(e){return{...e,plugins:[pr(),...e.plugins||[]]}}export{e as ApiResponse,Dn as clearPropsCache,On as clearPropsCacheForComponent,mr as defineRariConfig,fr as defineRariOptions,Cn as extractMetadata,Sn as extractServerProps,En as extractServerPropsWithCache,wn as extractStaticParams,Se as generateAppRouteManifest,Tn as hasServerSideDataFetching,pr as rari,le as rariProxy,Ie as rariRouter};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rari",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.15.
|
|
4
|
+
"version": "0.15.3",
|
|
5
5
|
"description": "Runtime Accelerated Rendering Infrastructure (rari)",
|
|
6
6
|
"author": "Ryan Skinner",
|
|
7
7
|
"license": "MIT",
|
|
@@ -145,13 +145,13 @@
|
|
|
145
145
|
"rolldown": "^1.1.5"
|
|
146
146
|
},
|
|
147
147
|
"optionalDependencies": {
|
|
148
|
-
"@rari/use-cache": "0.15.
|
|
149
|
-
"rari-darwin-arm64": "0.15.
|
|
150
|
-
"rari-darwin-x64": "0.15.
|
|
151
|
-
"rari-linux-arm64": "0.15.
|
|
152
|
-
"rari-linux-x64": "0.15.
|
|
153
|
-
"rari-win32-arm64": "0.15.
|
|
154
|
-
"rari-win32-x64": "0.15.
|
|
148
|
+
"@rari/use-cache": "0.15.3",
|
|
149
|
+
"rari-darwin-arm64": "0.15.3",
|
|
150
|
+
"rari-darwin-x64": "0.15.3",
|
|
151
|
+
"rari-linux-arm64": "0.15.3",
|
|
152
|
+
"rari-linux-x64": "0.15.3",
|
|
153
|
+
"rari-win32-arm64": "0.15.3",
|
|
154
|
+
"rari-win32-x64": "0.15.3"
|
|
155
155
|
},
|
|
156
156
|
"devDependencies": {
|
|
157
157
|
"@mdx-js/mdx": "^3.1.1",
|