rari 0.14.1 → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +1 -1
- package/dist/client.d.mts +5 -6
- package/dist/client.mjs +1 -1
- package/dist/{get-client-component-DOUGb2xc.mjs → get-client-component-B4Y2T40R.mjs} +1 -1
- package/dist/headers.d.mts +1 -1
- package/dist/image/index.mjs +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/mdx.mjs +1 -1
- package/dist/{preload-modules-C1zd75Lc.mjs → preload-modules-xvnJ_8eh.mjs} +2 -2
- package/dist/proxy/RariRequest.d.mts +1 -1
- package/dist/proxy/RariResponse.d.mts +1 -1
- package/dist/{railway-BQNsu-l4.mjs → railway-bxKRJ0Cg.mjs} +1 -1
- package/dist/{render-DHDWCmpf.mjs → render-CXNCiz-E.mjs} +1 -1
- package/dist/router.d.mts +1 -3
- package/dist/router.mjs +1 -1
- package/dist/runtime/AppRouterProvider.d.mts +1 -2
- package/dist/runtime/AppRouterProvider.mjs +1 -1
- package/dist/runtime/ErrorBoundaryWrapper.mjs +1 -1
- package/dist/runtime/entry-client.mjs +2 -2
- package/dist/runtime/react-server-dom-shim.mjs +1 -1
- package/dist/runtime/rsc-client-runtime.d.mts +1 -1
- package/dist/runtime/rsc-client-runtime.mjs +1 -1
- package/dist/runtime/vendor/react-flight-client/ReactFlightClient.d.mts +1 -1
- package/dist/runtime/vendor/react-flight-client/ReactFlightClientConfig.d.mts +1 -1
- package/dist/runtime/vendor/react-flight-client/ReactFlightClientConfig.mjs +1 -1
- package/dist/{sitemap-generator-CB5dtfYm.mjs → sitemap-generator-BTG9lURQ.mjs} +1 -1
- package/dist/vite.d.mts +4 -4
- package/dist/vite.mjs +118 -17
- package/package.json +12 -12
- package/dist/rolldown-runtime-DR3Ue2cl.mjs +0 -1
- package/dist/routes-CTeHh8gJ.mjs +0 -1
- package/dist/server-build-z4tShJEq.mjs +0 -102
- /package/dist/{ReactFlightClientConfig-DdCyeIZx.d.mts → ReactFlightClientConfig-C_nD8rsi.d.mts} +0 -0
- /package/dist/{alias-resolver-D1GHg-4o.mjs → alias-resolver-BintHkb_.mjs} +0 -0
- /package/dist/{constants-B68HGlJT.mjs → constants-De7aSsCq.mjs} +0 -0
- /package/dist/{metadata-route-D0xSj7FK.d.mts → metadata-route-85WvBQcW.d.mts} +0 -0
- /package/dist/{navigate-hfIqe3MK.mjs → navigate-DuyUa6qD.mjs} +0 -0
- /package/dist/{regex-constants-iGdnDzFV.mjs → regex-constants-B4P386OY.mjs} +0 -0
- /package/dist/{robots-generator-Byiwomr5.mjs → robots-generator-l2O5neuR.mjs} +0 -0
- /package/dist/{runtime-client-CbbckLpl.mjs → runtime-client-DHeO6y_7.mjs} +0 -0
- /package/dist/{server-config-CGmxgSPb.d.mts → server-config-CwWYmtA0.d.mts} +0 -0
- /package/dist/{timer-utils-DnyOf3e6.mjs → timer-utils-Duul5JHq.mjs} +0 -0
- /package/dist/{types-DOgYNbON.d.mts → types-3dq9RGI5.d.mts} +0 -0
- /package/dist/{types-Bl4Eog4T.d.mts → types-m74grfbN.d.mts} +0 -0
- /package/dist/{types-R2tg78dF.d.mts → types-zPQ3RHgH.d.mts} +0 -0
- /package/dist/{utils-BK4N0qFr-BCy19luN.mjs → utils-BK4N0qFr-QFbF96eD.mjs} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(){return globalThis}function t(e){return{specifier:e.id,name:e.name||`default`}}function n(t){let n=e()[`~clientComponents`];if(!n)return null;let r=`${t.specifier}#${t.name}`,i=r.replace(/\\/g,`/`),a=t.specifier.replace(/\\/g,`/`),o=n[i]||n[r]||(t.name
|
|
1
|
+
function e(){return globalThis}function t(e){return{specifier:e.id,name:e.name||`default`}}function n(t){let n=e()[`~clientComponents`];if(!n)return null;let r=`${t.specifier}#${t.name}`,i=r.replace(/\\/g,`/`),a=t.specifier.replace(/\\/g,`/`),o=n[i]||n[r]||(t.name==="default"?n[a]||n[t.specifier]:void 0);return!o||o.component?null:o.loadPromise?o.loadPromise:o.loader?(o.loading=!0,o.loadPromise=o.loader().then(e=>(o.component=e,o.registered=!0,o.loading=!1,e)).catch(e=>{throw o.loading=!1,o.loadPromise=void 0,e}),o.loadPromise):null}function r(t){let n=e()[`~clientComponents`];if(!n)throw Error(`[rari] Client components registry not found`);let r=`${t.specifier}#${t.name}`,i=r.replace(/\\/g,`/`),a=t.specifier.replace(/\\/g,`/`),o=n[i]||n[r]||(t.name==="default"?n[a]||n[t.specifier]:void 0);if(!o)throw Error(`[rari] Component not registered: ${r}`);if(o.component){let e=o.component;return t.name==="default"?e.default??e:e[t.name]===void 0?e.default?.[t.name]===void 0?e:e.default[t.name]:e[t.name]}throw o.loadPromise?o.loadPromise:o.loader?(o.loading=!0,o.loadPromise=o.loader().then(e=>(o.component=e,o.registered=!0,o.loading=!1,e)).catch(e=>{throw o.loading=!1,o.loadPromise=void 0,e}),o.loadPromise):Error(`[rari] Module not found: ${r}`)}function i(e,t){return e.decode(t,{stream:!0})}function a(e,t){return e.decode(t)}function o(){return new TextDecoder}export{o as createStringDecoder,n as preloadModule,a as readFinalStringChunk,i as readPartialStringChunk,r as requireModule,t as resolveClientReference};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{C as e,S as t,T as n,w as r,x as i}from"./regex-constants-
|
|
1
|
+
import{C as e,S as t,T as n,w as r,x as i}from"./regex-constants-B4P386OY.mjs";import{t as a}from"./alias-resolver-BintHkb_.mjs";import{Buffer as o}from"node:buffer";import{existsSync as s,promises as c}from"node:fs";import l from"node:path";const u=/[^\w-]/g,d=`\0virtual:sitemap`;function f(a){return a.replace(i,`&`).replace(r,`<`).replace(e,`>`).replace(n,`"`).replace(t,`'`)}function p(e){return(typeof e==`string`?new Date(e):e).toISOString()}function m(e){return[` <image:image>`,` <image:loc>${f(e)}</image:loc>`,` </image:image>`].join(`
|
|
2
2
|
`)}function h(e){let t=[` <image:image>`,` <image:loc>${f(e.loc)}</image:loc>`];return e.title&&t.push(` <image:title>${f(e.title)}</image:title>`),e.caption&&t.push(` <image:caption>${f(e.caption)}</image:caption>`),e.geoLocation&&t.push(` <image:geo_location>${f(e.geoLocation)}</image:geo_location>`),e.license&&t.push(` <image:license>${f(e.license)}</image:license>`),t.push(` </image:image>`),t.join(`
|
|
3
3
|
`)}function g(e){let t=[];for(let n of e)typeof n==`string`?t.push(m(n)):t.push(h(n));return t.join(`
|
|
4
4
|
`)}function _(e){let t=[];if(t.push(` <video:video>`),t.push(` <video:title>${f(e.title)}</video:title>`),t.push(` <video:thumbnail_loc>${f(e.thumbnail_loc)}</video:thumbnail_loc>`),t.push(` <video:description>${f(e.description)}</video:description>`),e.content_loc&&t.push(` <video:content_loc>${f(e.content_loc)}</video:content_loc>`),e.player_loc&&t.push(` <video:player_loc>${f(e.player_loc)}</video:player_loc>`),e.duration!==void 0&&t.push(` <video:duration>${e.duration}</video:duration>`),e.expiration_date&&t.push(` <video:expiration_date>${f(e.expiration_date)}</video:expiration_date>`),e.rating!==void 0&&t.push(` <video:rating>${e.rating}</video:rating>`),e.view_count!==void 0&&t.push(` <video:view_count>${e.view_count}</video:view_count>`),e.publication_date&&t.push(` <video:publication_date>${f(e.publication_date)}</video:publication_date>`),e.family_friendly!==void 0&&t.push(` <video:family_friendly>${e.family_friendly?`yes`:`no`}</video:family_friendly>`),e.requires_subscription!==void 0&&t.push(` <video:requires_subscription>${e.requires_subscription?`yes`:`no`}</video:requires_subscription>`),e.live!==void 0&&t.push(` <video:live>${e.live?`yes`:`no`}</video:live>`),e.restriction&&t.push(` <video:restriction relationship="${f(e.restriction.relationship)}">${f(e.restriction.content)}</video:restriction>`),e.platform&&t.push(` <video:platform relationship="${f(e.platform.relationship)}">${f(e.platform.content)}</video:platform>`),e.uploader){let n=e.uploader.info?` info="${f(e.uploader.info)}"`:``;t.push(` <video:uploader${n}>${f(e.uploader.name)}</video:uploader>`)}if(e.tag)for(let n of e.tag)t.push(` <video:tag>${f(n)}</video:tag>`);return t.push(` </video:video>`),t.join(`
|
package/dist/vite.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as hasServerSideDataFetching, S as extractStaticParams, _ as clearPropsCache, b as extractServerProps, f as createHttpRuntimeClient, g as StaticParamsResult, h as ServerSidePropsResult, m as MetadataResult, n as ServerCacheControlConfig, r as ServerConfig, s as HttpRuntimeClient, t as ServerCSPConfig, u as RuntimeClient, v as clearPropsCacheForComponent, x as extractServerPropsWithCache, y as extractMetadata } from "./server-config-
|
|
2
|
-
import { a as ErrorProps, c as LayoutEntry, d as Metadata, f as NotFoundEntry, h as RouteSegmentType, i as ErrorEntry, l as LayoutProps, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, p as PageProps, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-
|
|
3
|
-
import { a as SitemapImage, i as SitemapEntry, n as RobotsRule, o as SitemapVideo, r as Sitemap, t as Robots } from "./metadata-route-
|
|
4
|
-
import { a as ProxyModule, c as RariURL, i as ProxyMatcher, l as RequestCookies, n as ProxyConfig, o as ProxyResult, r as ProxyFunction, s as RariFetchEvent, t as CookieOptions, u as ResponseCookies } from "./types-
|
|
1
|
+
import { C as hasServerSideDataFetching, S as extractStaticParams, _ as clearPropsCache, b as extractServerProps, f as createHttpRuntimeClient, g as StaticParamsResult, h as ServerSidePropsResult, m as MetadataResult, n as ServerCacheControlConfig, r as ServerConfig, s as HttpRuntimeClient, t as ServerCSPConfig, u as RuntimeClient, v as clearPropsCacheForComponent, x as extractServerPropsWithCache, y as extractMetadata } from "./server-config-CwWYmtA0.mjs";
|
|
2
|
+
import { a as ErrorProps, c as LayoutEntry, d as Metadata, f as NotFoundEntry, h as RouteSegmentType, i as ErrorEntry, l as LayoutProps, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, p as PageProps, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-m74grfbN.mjs";
|
|
3
|
+
import { a as SitemapImage, i as SitemapEntry, n as RobotsRule, o as SitemapVideo, r as Sitemap, t as Robots } from "./metadata-route-85WvBQcW.mjs";
|
|
4
|
+
import { a as ProxyModule, c as RariURL, i as ProxyMatcher, l as RequestCookies, n as ProxyConfig, o as ProxyResult, r as ProxyFunction, s as RariFetchEvent, t as CookieOptions, u as ResponseCookies } from "./types-3dq9RGI5.mjs";
|
|
5
5
|
import { RariRequest } from "./proxy/RariRequest.mjs";
|
|
6
6
|
import { RariResponse } from "./proxy/RariResponse.mjs";
|
|
7
7
|
import { Plugin, UserConfig } from "vite-plus";
|
package/dist/vite.mjs
CHANGED
|
@@ -1,11 +1,112 @@
|
|
|
1
|
-
import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{_ as n,c as r,d as i,f as a,g as o,h as s,i as c,m as l,p as u,u as d}from"./runtime-client-CbbckLpl.mjs";import{i as f,n as p,o as m,r as h,t as g}from"./constants-B68HGlJT.mjs";import{_,a as v,b as y,f as b,i as ee,r as x,t as S,v as C,y as w}from"./regex-constants-iGdnDzFV.mjs";import{a as T,i as te,o as E,r as ne,s as D,t as re}from"./server-build-z4tShJEq.mjs";import{t as O}from"./timer-utils-DnyOf3e6.mjs";import{t as ie}from"./routes-CTeHh8gJ.mjs";import{Buffer as ae}from"node:buffer";import{spawn as oe}from"node:child_process";import k,{promises as A}from"node:fs";import j from"node:path";import M from"node:process";import{fileURLToPath as N}from"node:url";import P from"node:fs/promises";import{build as se}from"rolldown";function F(e={}){let{root:t=M.cwd(),srcDir:n=`src`,proxyFileName:r=`proxy`,extensions:i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`],verbose:a=!1}=e,o=null,s=e=>{a&&console.warn(`[rari] Proxy: ${e}`)};async function c(){for(let e of i){let n=`${r}${e}`,i=j.join(t,n);try{return await A.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=j.join(t,n);try{await A.access(e);for(let t of i){let i=`${r}${t}`,a=j.join(e,i);try{return await A.access(a),s(`Found proxy file: ${j.join(n,i)}`),{filePath:a,exists:!0,relativePath:j.join(n,i)}}catch{}}}catch{}return null}return{name:`rari:proxy`,async buildStart(){o=await c(),s(o?`Proxy enabled: ${o.relativePath}`:`No proxy file found`)},configureServer(e){o&&(e.watcher.add(o.filePath),e.watcher.on(`change`,t=>{t===o?.filePath&&(s(`Proxy file changed, reloading...`),e.ws.send({type:`custom`,event:`rari:proxy-reload`}))}))},async handleHotUpdate({file:e,server:t}){if(o&&e===o.filePath)return s(`Hot reloading proxy...`),t.ws.send({type:`custom`,event:`rari:proxy-reload`,data:{file:o.relativePath}}),[]}}}const ce=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,le=/title\s*:\s*['"]([^'"]+)['"]/,ue=/description\s*:\s*['"]([^'"]+)['"]/,de=/keywords\s*:\s*\[([\s\S]*?)\]/,fe={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function I(e){switch(j.basename(e).replace(w,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function pe(e,t){let n=j.relative(t,j.dirname(e));return!n||n===`.`?`/`:`/${n.replace(S,`/`).split(`/`).filter(Boolean).join(`/`)}`}function L(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function R(e){try{let t=e.match(ce);if(!t)return null;let n=t[1],r={},i=n.match(le);i&&(r.title=i[1]);let a=n.match(ue);a&&(r.description=a[1]);let o=n.match(de);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(_,``)).filter(Boolean));for(let e of[`author`,`viewport`,`themeColor`,`robots`,`openGraph`,`twitter`]){let t=RegExp(`${e}\\s*:\\s*['"]([^'"]+)['"]`,`m`),i=n.match(t);i&&(r[e]=i[1])}return Object.keys(r).length>0?r:null}catch(e){return console.error(`[rari] Router: Failed to extract metadata:`,e),null}}function z(e){let t=[];for(let n of[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]){let r=RegExp(`export\\s+(?:async\\s+)?function\\s+${n}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${n}\\s*=`);(r.test(e)||i.test(e))&&t.push(n)}return t}async function B(e){try{let t=await fetch(`http://localhost:3000/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate-api-route`,filePath:e})});if(!t.ok){console.error(`[rari] Router: Failed to invalidate API route cache: ${t.statusText}`);return}let n=await t.json();n.success||console.error(`[rari] HMR: Failed to invalidate API route cache: ${n.error||`Unknown error`}`)}catch(e){console.error(`[rari] Router: Failed to notify API route invalidation:`,e)}}function V(e={}){let t={...fe,...e},n=null,r=new Map,i=null,a=new Set,o=e=>[...e].toSorted().join(`|`),s=async e=>{let n=new Set,r=async e=>{try{let i=await A.readdir(e,{withFileTypes:!0});for(let a of i){let i=j.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&I(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=j.resolve(e,t.appDir);try{await A.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let{generateAppRouteManifest:d}=await import(`./routes-CTeHh8gJ.mjs`).then(e=>e.n),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=j.resolve(e,t.outDir);await A.mkdir(m,{recursive:!0});let h=j.join(m,`server`);return await A.mkdir(h,{recursive:!0}),await A.writeFile(j.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=j.resolve(e.config.root,t.appDir);e.watcher.on(`all`,async(r,i)=>{if(i.startsWith(n)&&t.extensions.some(e=>i.endsWith(e)))try{let n=I(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||M.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=j.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=I(i);if(e){let t=r.get(i);t&&clearTimeout(t);let l=setTimeout(async()=>{r.delete(i);let t=!a.has(i),l=n;n=await c(o.config.root,t);let u=l!==n,d=pe(i,s),f=[d];if(n)try{f=JSON.parse(n).routes.map(e=>e.path)}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let p=L(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=R(await A.readFile(i,`utf-8`));e&&(m=e,h=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{g=z(await A.readFile(i,`utf-8`)),await B(j.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:j.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear();let e=u||M.cwd(),n=j.resolve(e,t.outDir,`server`),i=j.join(n,`routes.json`);try{let t=await A.readFile(i,`utf-8`),n=JSON.parse(t),r=!1;for(let t of n.routes){if(!t.isDynamic)continue;let n=t.filePath.replace(/\[\.\.\.([^\]]+)\]/g,`____$1_`).replace(/\[([^\]]+)\]/g,`_$1_`).replace(/\.tsx?$/,`.js`),i=j.resolve(e,`dist`,`server`,`app`,n);try{let e=await import(i);if(typeof e.generateStaticParams==`function`){let n=await e.generateStaticParams();Array.isArray(n)&&n.length>0&&(t.staticParams=n,r=!0)}}catch{}}r&&await A.writeFile(i,JSON.stringify(n,null,2),`utf-8`)}catch{}}}}var me=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer=O(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=O(this.resetTimer)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.reset()}};const he=/^(["'])use client\1\s*(?:;\s*)?(?:\/\/.*)?$/;var ge=class{serverComponentBuilder;rustServerUrl;pendingUpdates=new Map;pendingFiles=new Set;batchTimer=null;DEBOUNCE_DELAY=200;errorHandler;logBatch=[];logBatchTimer=null;LOG_BATCH_DELAY=500;constructor(e,t=3e3){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new me({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=j.relative(M.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=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=j.relative(M.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),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 d(n);let r=await n.text(),i;try{i=JSON.parse(r)}catch(e){throw Error(`Failed to parse server response (status ${n.status}): ${e instanceof Error?e.message:String(e)}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`)}if(!i||typeof i!=`object`)throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);let a=i;if(!a.success)throw Error(a.message||a.error||`Component reload failed`)}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}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{let t=k.readFileSync(e,`utf-8`).split(`
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{_ as n,c as r,d as i,f as a,g as o,h as s,i as c,m as l,p as u,u as d}from"./runtime-client-DHeO6y_7.mjs";import{i as f,n as p,o as m,r as h,t as g}from"./constants-De7aSsCq.mjs";import{_,a as v,b as y,f as b,h as ee,i as te,o as ne,r as x,t as S,v as C,y as w}from"./regex-constants-B4P386OY.mjs";import{t as re}from"./timer-utils-Duul5JHq.mjs";import{t as ie}from"./alias-resolver-BintHkb_.mjs";import{Buffer as ae}from"node:buffer";import{spawn as oe}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:fs/promises";import{build as M}from"rolldown";var N=Object.defineProperty,se=(e,t)=>{let n={};for(var r in e)N(n,r,{get:e[r],enumerable:!0});return t||N(n,Symbol.toStringTag,{value:`Module`}),n};function ce(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{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 le=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,ue=/title\s*:\s*['"]([^'"]+)['"]/,de=/description\s*:\s*['"]([^'"]+)['"]/,fe=/keywords\s*:\s*\[([\s\S]*?)\]/,pe={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function P(e){switch(D.basename(e).replace(w,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function me(e,t){let n=D.relative(t,D.dirname(e));return!n||n===`.`?`/`:`/${n.replace(S,`/`).split(`/`).filter(Boolean).join(`/`)}`}function he(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function ge(e){try{let t=e.match(le);if(!t)return null;let n=t[1],r={},i=n.match(ue);i&&(r.title=i[1]);let a=n.match(de);a&&(r.description=a[1]);let o=n.match(fe);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(_,``)).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 _e(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 ve(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 ye(e={}){let t={...pe,...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))&&P(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{generateAppRouteManifest:d}=await Promise.resolve().then(()=>an),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=D.resolve(e,t.outDir);await E.mkdir(m,{recursive:!0});let h=D.join(m,`server`);return await E.mkdir(h,{recursive:!0}),await E.writeFile(D.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=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=P(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||O.cwd(),!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=P(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=me(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=he(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=ge(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=_e(await E.readFile(i,`utf-8`)),await ve(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 t=await E.readFile(i,`utf-8`),n=JSON.parse(t),r=!1;for(let t of n.routes){if(!t.isDynamic)continue;let n=t.filePath.replace(/\[\.\.\.([^\]]+)\]/g,`____$1_`).replace(/\[([^\]]+)\]/g,`_$1_`).replace(/\.tsx?$/,`.js`),i=D.resolve(e,`dist`,`server`,`app`,n);try{let e=await import(i);if(typeof e.generateStaticParams==`function`){let n=await e.generateStaticParams();Array.isArray(n)&&n.length>0&&(t.staticParams=n,r=!0)}}catch{}}r&&await E.writeFile(i,JSON.stringify(n,null,2),`utf-8`)}catch{}}}}const be=new Set([`return`,`throw`,`case`,`typeof`,`instanceof`,`new`,`delete`,`void`,`in`,`of`]);function F(e){return e===` `||e===` `||e===`\r`||e===`
|
|
2
|
+
`||e===`\u2028`||e===`\u2029`||e===``}function I(e){return e===`\r`||e===`
|
|
3
|
+
`||e===`\u2028`||e===`\u2029`}function xe(e,t,n){for(;t<n&&F(e[t]);)t++;return t}function L(e,t,n){for(;t<n;){let r=xe(e,t,n);if(r!==t){t=r;continue}if(e[t]===`/`&&e[t+1]===`/`){t=R(e,t,n);continue}if(e[t]===`/`&&e[t+1]===`*`){t=z(e,t,n);continue}break}return t}function R(e,t,n){for(;t<n&&!I(e[t]);)t++;return t}function z(e,t,n){for(t+=2;t<n-1&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}function B(e,t,n,r){for(t++;t<n;){if(e[t]===`\\`){t+=2;continue}if(e[t]===r)return t+1;t++}return t}function Se(e,t,n){t++;let r=e[t]===`/`;for(r&&t++;t<n&&(U(e[t])||e[t]===`.`||e[t]===`-`);)t++;let i=+!r;for(;t<n&&i>0;){let a=e[t]===`'`||e[t]===`"`||e[t]==="`"?e[t]:null;if(a){t=B(e,t,n,a);continue}if(e[t]===`{`){t++;let r=1;for(;t<n&&r>0;){let i=e[t]===`'`||e[t]===`"`||e[t]==="`"?e[t]:null;if(i){t=B(e,t,n,i);continue}e[t]===`{`&&r++,e[t]===`}`&&r--,t++}continue}if(e[t]===`/`&&e[t+1]===`>`){i--,t+=2;continue}if(e[t]===`>`){t++,r&&i--;continue}if(e[t]===`<`){let r=e[t+1];if(r===`/`||r===`.`||r===`>`||we(r)){for(r===`/`?(i--,t++):r!==`!`&&i++,t++;t<n&&(U(e[t])||e[t]===`.`||e[t]===`-`);)t++;continue}t++;continue}t++}return t}function Ce(e,t){let n=0,r=e.length;for(;n<r;){if(F(e[n])){n++;continue}if(e[n]===`/`&&e[n+1]===`/`){n=R(e,n,r);continue}if(e[n]===`/`&&e[n+1]===`*`){n=z(e,n,r);continue}let i=e[n]===`'`||e[n]===`"`?e[n]:null;if(i){let a=n+1,o=B(e,n,r,i);if(o>a){let i=e.slice(a,o-1),s=o;for(;s<r;){if(F(e[s])&&!I(e[s])){s++;continue}if(I(e[s])||e[s]===`;`){if(i===t)return!0;n=s+1;break}if(e[s]===`/`&&e[s+1]===`/`){s=R(e,s,r);continue}if(e[s]===`/`&&e[s+1]===`*`){s=z(e,s,r);continue}return!1}if(s>=r)return i===t;if(s<r&&(I(e[s])||e[s]===`;`))continue;return!1}}return!1}return!1}function V(e){return Ce(e,`use server`)}function H(e){return Ce(e,`use client`)}function U(e){return!!e&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`_`||e===`$`)}function we(e){return!!e&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`_`||e===`$`)}function Te(e){return!e||e===`(`||e===`[`||e===`{`||e===`,`||e===`;`||e===`=`||e===`:`||e===`?`||e===`!`||e===`+`||e===`-`||e===`*`||e===`%`||e===`&`||e===`|`||e===`^`||e===`~`||e===`<`||e===`>`}function Ee(e,t){let n=t-1;for(;n>=0;){if(F(e[n])){n--;continue}if(n>=1&&e[n]===`/`&&e[n-1]===`*`){for(n-=2;n>=1;){if(e[n]===`*`&&e[n-1]===`/`){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&e[n]===`/`&&e[n-1]===`/`){n-=2;continue}let t=n;for(;t>=0&&e[t]!==`
|
|
4
|
+
`&&e[t]!==`\r`;)t--;let r=t+1;for(;r<n&&(e[r]===` `||e[r]===` `);)r++;if(r<n&&e[r]===`/`&&e[r+1]===`/`){n=r-1;continue}break}if(n<0||!U(e[n]))return;let r=n;for(;n>=0&&U(e[n]);)n--;return e.slice(n+1,r+1)}function De(e,t){if(Te(ke(e,t)))return!0;let n=Ee(e,t);return n?be.has(n):!1}function Oe(e,t,n){t++;let r=!1;for(;t<n;){if(e[t]===`\\`){t+=2;continue}if(r){e[t]===`]`&&(r=!1),t++;continue}if(e[t]===`[`){r=!0,t++;continue}if(e[t]===`/`){for(t++;t<n&&U(e[t]);)t++;return t}if(I(e[t]))return t;t++}return t}function ke(e,t){let n=t-1;for(;n>=0;){if(F(e[n])){n--;continue}if(n>=1&&e[n]===`/`&&e[n-1]===`*`){for(n-=2;n>=1;){if(e[n]===`*`&&e[n-1]===`/`){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&e[n]===`/`&&e[n-1]===`/`){n-=2;continue}let t=n;for(;t>=0&&e[t]!==`
|
|
5
|
+
`&&e[t]!==`\r`;)t--;let r=t+1;for(;r<n&&(e[r]===` `||e[r]===` `);)r++;if(r<n&&e[r]===`/`&&e[r+1]===`/`){n=r-1;continue}return e[n]}}function W(e){let t=0,n=e.length;for(;t<n;){if(F(e[t])){t++;continue}if(e[t]===`/`&&e[t+1]===`/`){t=R(e,t,n);continue}if(e[t]===`/`&&e[t+1]===`*`){t=z(e,t,n);continue}let r=e[t]===`'`||e[t]===`"`||e[t]==="`"?e[t]:null;if(r){t=B(e,t,n,r);continue}if(e[t]===`/`&&e[t+1]!==`/`&&e[t+1]!==`*`&&De(e,t)){t=Oe(e,t,n);continue}if(e[t]===`<`){let r=e[t+1];if(r===`/`||r===`.`||r===`>`||we(r)){t=Se(e,t,n);continue}t++;continue}if(e.slice(t,t+6)===`export`){let r=t+6;if(r<n&&(F(e[r])||e[r]===`{`||e[r]===`/`&&(e[r+1]===`/`||e[r+1]===`*`))){let t=L(e,r,n);if(e.slice(t,t+7)==="default"){let r=t+7;if(r>=n||!U(e[r]))return!0}if(e[t]===`{`){let r=t+1;for(;r<n&&(r=L(e,r,n),e[r]!==`}`);){let t=r;for(;r<n&&U(e[r]);)r++;let i=e.slice(t,r);if(!i)break;r=L(e,r,n);let a=!1;if(e.slice(r,r+2)===`as`){a=!0;let t=r+2;if(t<n&&!U(e[t])){r=L(e,t,n);let i=r;for(;r<n&&U(e[r]);)r++;if(e.slice(i,r)==="default")return!0}}if(!a&&i==="default")return!0;if(e[r]===`,`){r++;continue}if(e[r]===`}`)break;r++}}}}t++}return!1}function Ae(e,t){let n=null;for(let r of t)if(e.endsWith(r)&&(n??=T.existsSync(e),n))return e;for(let n of t){let t=`${e}${n}`;if(T.existsSync(t))return t}return null}function je(e,t){if(T.existsSync(e)){if(!T.statSync(e).isDirectory())return null;for(let n of t){let t=D.join(e,`index${n}`);if(T.existsSync(t))return t}}return null}var Me=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer=re(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=re(this.resetTimer)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.reset()}};const Ne=/^(["'])use client\1\s*(?:;\s*)?(?:\/\/.*)?$/;var Pe=class{serverComponentBuilder;rustServerUrl;pendingUpdates=new Map;pendingFiles=new Set;batchTimer=null;DEBOUNCE_DELAY=200;errorHandler;logBatch=[];logBatchTimer=null;LOG_BATCH_DELAY=500;constructor(e,t=3e3){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new Me({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=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 d(n);let r=await n.text(),i;try{i=JSON.parse(r)}catch(e){throw Error(`Failed to parse server response (status ${n.status}): ${e instanceof Error?e.message:String(e)}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`)}if(!i||typeof i!=`object`)throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);let a=i;if(!a.success)throw Error(a.message||a.error||`Component reload failed`)}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}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{let t=T.readFileSync(e,`utf-8`).split(`
|
|
6
|
+
`),n=!1;function r(e){return Ne.test(e.trim())}function i(e){let t=e;for(;t.includes(`/*`)&&t.includes(`*/`);){let e=t.indexOf(`/*`),n=t.indexOf(`*/`,e);if(n===-1)break;t=t.substring(0,e)+t.substring(n+2)}if(t.includes(`/*`)){let e=t.indexOf(`/*`);t=t.substring(0,e)}return t}for(let e of t){let t=e.trim();if(n){if(t.includes(`*/`)){n=!1;let e=t.substring(t.indexOf(`*/`)+2).trim();if(!e||e.startsWith(`//`))continue;let a=i(e).trim();if(!a||a.startsWith(`//`))continue;if(r(a))return`client`;break}continue}if(!(!t||t.startsWith(`//`))){if(t.includes(`/*`))if(t.includes(`*/`)){let e=i(t).trim();if(!e||e.startsWith(`//`))continue;if(r(e))return`client`;break}else{let e=t.substring(0,t.indexOf(`/*`)).trim();if(e){if(r(e))return`client`;break}n=!0;continue}if(r(t))return`client`;break}}return`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
|
|
7
|
+
• `);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 Fe=/import\s+(\w+)\s+from\s+['"]rari\/image['"]/g,Ie=/import\s+\{[^}]*\b(?:Image\s+as\s+(\w+)|Image)\b[^}]*\}\s+from\s+['"]rari\/image['"]/g,Le=/src:\s*["']([^"']+)["']/,Re=/[.*+?^${}()|[\]\\]/g,ze=/^[A-Z_$][\w$]*$/i,Be=/width:\s*(\d+)/,Ve=/quality:\s*(\d+)/,He=/preload:\s*(true|!0)/,Ue=/preload:\s*(false|!1)/,We=/src=\{?["']([^"']+)["']\}?|src=\{([^}]+)\}/,Ge=/width=\{?(\d+)\}?/,Ke=/quality=\{?(\d+)\}?/,qe=/preload(?:=\{?true\}?)?/,Je=/preload=\{?false\}?/;async function Ye(e,t){try{await st(await j.readFile(e,`utf8`),e,t)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to process ${e}:`,t)}}const Xe=new class{permits;queue=[];constructor(e){this.permits=e}async acquire(){if(this.permits>0){this.permits--;return}return new Promise(e=>{this.queue.push(e)})}release(){this.permits++;let e=this.queue.shift();e&&(this.permits--,e())}async run(e){await this.acquire();try{return await e()}finally{this.release()}}}(50);async function G(e,t){try{await j.access(e)}catch{return}let n=await j.readdir(e,{withFileTypes:!0}),r=[];for(let i of n){let n=D.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`dist`)continue;r.push(G(n,t))}else i.isFile()&&w.test(i.name)&&r.push(Xe.run(()=>Ye(n,t)))}await Promise.all(r)}async function Ze(e,t=[]){let n=new Map;try{await j.access(e),await G(e,n)}catch(t){throw t.code===`ENOENT`?Error(`Required source directory does not exist: ${e}`):t}for(let e of t)try{await j.access(e),await G(e,n)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to scan directory ${e}:`,t)}return{images:[...n.values()]}}function Qe(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:e.endsWith(`.ts`)?`ts`:`js`}async function $e(e,t,n){let r=`\0virtual:${t}`,i=await M({input:r,external:[`rari/image`],platform:`browser`,write:!1,output:{format:`esm`},moduleTypes:{[`.${n}`]:n},transform:{jsx:`react`},plugins:[{name:`virtual-module`,resolveId(e){return e===r?e:null},load(t){return t===r?{code:e,moduleType:n}:null}}]});if(!i.output||i.output.length===0)throw Error(`Transform produced no output`);return i.output[0].code}function et(e){let t=new Set;for(let n of e.matchAll(Fe))t.add(n[1]);for(let n of e.matchAll(Ie))n[1]?t.add(n[1]):t.add(`Image`);return t}function tt(e){return et(e)}function nt(e){let t=e.match(Le);if(!t)return null;let n=t[1];if(!n.startsWith(`/`)&&!n.startsWith(`http`))return null;let r=e.match(Be),i=r?Number.parseInt(r[1],10):void 0,a=e.match(Ve),o=a?Number.parseInt(a[1],10):void 0,s=e.match(He),c=e.match(Ue);return{src:n,width:i,quality:o,preload:!!s&&!c}}function rt(e,t){let n=`${e.src}:${e.width??`auto`}:${e.quality??75}`;(!t.has(n)||e.preload)&&t.set(n,e)}function it(e,t){let n=0,r=!1,i=``,a=!1,o=0;for(let s=t;s<e.length;s++){let c=e[s];if(a){a=!1;continue}if(c===`\\`){a=!0;continue}if(!r&&(c===`"`||c===`'`||c==="`")){r=!0,i=c,c==="`"&&(o=1);continue}if(r&&c===i){i==="`"?(o--,o===0&&(r=!1,i=``)):(r=!1,i=``);continue}if(r&&i==="`"&&c===`$`&&s+1<e.length&&e[s+1]===`{`){n++,s++;continue}if(r&&i==="`"&&n>0&&c==="`"){o++;continue}if(r&&i==="`"&&c===`}`&&n>0){n--;continue}if(!r){if(c===`{`)n++;else if(c===`}`&&(n--,n===0))return e.substring(t+1,s)}}return null}function at(e,t,n){for(let r of t){if(!ze.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe identifier: ${r}`);continue}let t=r.replace(Re,`\\$&`),i=RegExp(`React\\.createElement\\(\\s*${t}\\s*,\\s*\\{`,`g`);for(let t of e.matchAll(i)){let r=it(e,t.index+t[0].length-1);if(r){let e=nt(r);e&&rt(e,n)}}}}function ot(e){return et(e)}async function st(e,t,n){let r=ot(e);if(r.size!==0)try{let r=await $e(e,t,Qe(t)),i=tt(r);if(i.size===0)return;at(r,i,n)}catch{ct(e,r,n)}}function ct(e,t,n){for(let r of t){if(!ze.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe alias: ${r}`);continue}let t=r.replace(Re,`\\$&`),i=RegExp(`<${t}\\s([^/>]+)\\/>`,`g`),a=RegExp(`<${t}\\s([^>]+)>`,`g`);for(let t of e.matchAll(i))lt(t[1],n);for(let t of e.matchAll(a))lt(t[1],n)}}function lt(e,t){let n=e.match(We);if(!n)return;let r=n[1]||n[2];if(!r||r.includes(`{`)||!r.startsWith(`/`)&&!r.startsWith(`http`))return;let i=e.match(Ge),a=i?Number.parseInt(i[1],10):void 0,o=e.match(Ke),s=o?Number.parseInt(o[1],10):void 0,c=qe.test(e)&&!Je.test(e),l=`${r}:${a??`auto`}:${s??75}`;(!t.has(l)||c)&&t.set(l,{src:r,width:a,quality:s,preload:c})}var ut=se({ServerComponentBuilder:()=>xt,createServerBuildPlugin:()=>X,scanDirectory:()=>Y});const dt=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,K=/from\s+['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s+['"]([^'"]+)['"]/g,ft=/import(?:\s+(?:\w+|\{[^}]*\}|\*\s+as\s+\w+)(?:\s*,\s*(?:\w+|\{[^}]*\}|\*\s+as\s+\w+))*\s+from\s+)?['"]([^'"]+)['"]/g,pt=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,mt=/import\s+(?:(\w+)|\{([^}]+)\})\s+from\s+['"]([^'"]+)['"];?\s*$/gm,ht=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,gt=/\\/g,q=/\.(tsx?|jsx?)$/,_t=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,vt=/[/\\]components[/\\](\w+)(?:\.tsx?|\.jsx?)?$/,yt=/^(?:robots|sitemap)\.(?:tsx?|jsx?)$/,bt=/^node:/,J=/\\/g;var xt=class{serverComponents=new Map;serverActions=new Map;options;projectRoot;buildCache=new Map;htmlOnlyImports=new Set;fileImporters=new Map;getComponentCount(){return this.serverComponents.size+this.serverActions.size}getImportGraph(){let e=new Map;for(let[t,n]of this.fileImporters)e.set(t,new Set(n));return e}getHtmlOnlyImports(){return new Set(this.htmlOnlyImports)}constructor(e,t={}){this.projectRoot=e;let n=t.rscDir||`server`;this.options={outDir:t.outDir||D.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath||D.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath||D.join(n,`config.json`),minify:t.minify??O.env.NODE_ENV===`production`,alias:t.alias||{},define:t.define,csp:t.csp,cacheControl:t.cacheControl},this.parseHtmlImports()}parseHtmlImports(){let e=D.join(this.projectRoot,`index.html`);if(T.existsSync(e))try{let t=T.readFileSync(e,`utf-8`);for(let e of t.matchAll(dt)){let t=e[1]||e[2];if(t.startsWith(`/src/`)){let e=D.join(this.projectRoot,t.slice(1));this.htmlOnlyImports.add(e)}}}catch(e){console.warn(`[server-build] Error parsing index.html:`,e)}}isHtmlOnlyImport(e){return this.htmlOnlyImports.has(e)}isServerComponent(e,t){if(e.includes(`node_modules`)||this.isHtmlOnlyImport(e))return!1;try{let n=t??(T.existsSync(e)?T.readFileSync(e,`utf-8`):null);return n===null?!1:!H(n)&&!V(n)}catch{return!1}}isClientComponent(e,t){try{let n=t??(T.existsSync(e)?T.readFileSync(e,`utf-8`):null);return n===null?!1:H(n)}catch{return!1}}buildImportGraph(e){this.fileImporters.clear();let t=e=>{if(!T.existsSync(e))return;let n=T.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=D.join(e,r.name);if(r.isDirectory()){if(r.name===`node_modules`)continue;t(n)}else if(r.isFile()&&w.test(r.name))try{let e=T.readFileSync(n,`utf-8`),t;for(K.lastIndex=0,t=K.exec(e);t!==null;){let r=t[1]||t[2]||t[3],i=null;if(r.startsWith(`./`)||r.startsWith(`../`)){let e=D.dirname(n);i=D.resolve(e,r)}else if(r.startsWith(`@/`)){let e=r.slice(2);i=D.join(this.projectRoot,`src`,e)}if(i){let e=[``,`.ts`,`.tsx`,`.js`,`.jsx`],t=null;for(let n of e){let e=i+n;if(T.existsSync(e)&&T.statSync(e).isFile()){t=e;break}}t&&(this.fileImporters.has(t)||this.fileImporters.set(t,new Set),this.fileImporters.get(t).add(n))}t=K.exec(e)}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error building import graph:`,n,e)}}};t(e)}isOnlyImportedByClientComponents(e){let t=this.fileImporters.get(e);if(!t||t.size===0)return!1;for(let e of t)if(!this.isClientComponent(e)&&!this.isOnlyImportedByClientComponents(e))return!1;return!0}addServerComponent(e,t){let n=t??T.readFileSync(e,`utf-8`);if(this.isServerAction(n)){let t=this.extractDependencies(n),r=this.hasNodeImports(n);this.serverActions.set(e,{filePath:e,originalCode:n,dependencies:t,hasNodeImports:r});return}if(!this.isServerComponent(e,n))return;let r=this.extractDependencies(n),i=this.hasNodeImports(n);this.serverComponents.set(e,{filePath:e,originalCode:n,dependencies:r,hasNodeImports:i})}isServerAction(e){return V(e)}extractDependencies(e){let t=[],n;for(ft.lastIndex=0;n=ft.exec(e),n!==null;){let e=n[1];!e.startsWith(`.`)&&!e.startsWith(`/`)&&!e.startsWith(`node:`)&&!this.isNodeBuiltin(e)&&t.push(e)}return[...new Set(t)]}isNodeBuiltin(e){return[`fs`,`path`,`os`,`crypto`,`util`,`stream`,`events`,`process`,`buffer`,`url`,`querystring`,`zlib`,`http`,`https`,`net`,`tls`,`child_process`,`cluster`,`worker_threads`].includes(e)}hasNodeImports(e){return e.includes(`from 'node:`)||e.includes(`from "node:`)||e.includes(`from 'fs'`)||e.includes(`from "fs"`)||e.includes(`from 'path'`)||e.includes(`from "path"`)||e.includes(`from 'os'`)||e.includes(`from "os"`)||e.includes(`from 'crypto'`)||e.includes(`from "crypto"`)||e.includes(`from 'util'`)||e.includes(`from "util"`)||e.includes(`from 'stream'`)||e.includes(`from "stream"`)||e.includes(`from 'events'`)||e.includes(`from "events"`)}async getTransformedComponentsForDevelopment(){let e=[];for(let[t]of this.serverComponents){let n=D.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i})}for(let[t]of this.serverActions){let n=D.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i})}return e}transformComponentImportsToGlobal(e){let t=[];for(let n of e.matchAll(pt)){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(_t);if(n){let i=n[1],a=[D.resolve(this.projectRoot,`src`,`components`,`${i}.tsx`),D.resolve(this.projectRoot,`src`,`components`,`${i}.ts`),D.resolve(this.projectRoot,`src`,`components`,`${i}.jsx`),D.resolve(this.projectRoot,`src`,`components`,`${i}.js`)],o=!1;for(let e of a)if(T.existsSync(e)&&this.isClientComponent(e)){o=!0;break}if(!o)continue;let s=`// Component reference: ${i}
|
|
8
|
+
const ${r} = (props) => {
|
|
9
|
+
let Component = globalThis['~clientComponents']?.['components/${i}']?.component
|
|
10
|
+
|| globalThis['components/${i}'];
|
|
11
|
+
|
|
12
|
+
if (Component && typeof Component === 'object' && Component.default) {
|
|
13
|
+
Component = Component.default;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (!Component) {
|
|
17
|
+
throw new Error('Component components/${i} not loaded');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (typeof Component !== 'function') {
|
|
21
|
+
throw new Error('Component components/${i} is not a function, got: ' + typeof Component);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return Component(props);
|
|
25
|
+
}`;t.push({original:e,replacement:s})}}continue}let o=this.options.alias||{};for(let[e,t]of Object.entries(o))if(i.startsWith(`${e}/`)||i===e){let n=i.slice(e.length);a=D.join(t,n);break}if(a){let n=a.match(vt);if(n){let i=n[1],o=D.isAbsolute(a)?a:D.resolve(this.projectRoot,a),s=[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`],c=!1,l=o;for(let e of s)if(T.existsSync(e)){l=e,this.isClientComponent(e)&&(c=!0);break}if(!c)continue;let u=D.relative(this.projectRoot,l),d=this.getComponentId(u),f=`// Component reference: ${i}
|
|
26
|
+
const ${r} = (props) => {
|
|
27
|
+
let Component = globalThis['~clientComponents']?.['${d}']?.component
|
|
28
|
+
|| globalThis['${d}'];
|
|
29
|
+
|
|
30
|
+
if (Component && typeof Component === 'object' && Component.default) {
|
|
31
|
+
Component = Component.default;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (!Component) {
|
|
35
|
+
throw new Error('Component ${d} not loaded');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (typeof Component !== 'function') {
|
|
39
|
+
throw new Error('Component ${d} is not a function, got: ' + typeof Component);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return Component(props);
|
|
43
|
+
}`;t.push({original:e,replacement:f})}}}let n=e;for(let{original:e,replacement:r}of t)n=n.replace(e,r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createBuildPlugins(e,t,n,r,i=!1){let a=D.dirname(r),o=ht.test(D.basename(r)),s=this,c=new Map,l=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){let e=D.resolve(a,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(T.existsSync(n)&&T.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=D.join(e,`index${t}`);if(T.existsSync(n))return n}return e}return null},load(r){return r===e?{code:t,moduleType:n}:null}},{name:`resolve-client-server-boundaries`,resolveId:(t,n)=>{if(!n||n.includes(`node_modules`)||n.includes(`/packages/rari/dist`)||t.startsWith(`node:`)||s.isNodeBuiltin(t)||t===`react`||t===`react-dom`||t===`react/jsx-runtime`||t===`react/jsx-dev-runtime`)return null;let r=null;if(r=ie(t,s.options.alias||{},s.projectRoot),!r&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?a:D.dirname(n);r=D.resolve(i,t)}if(r)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(T.existsSync(t)&&T.statSync(t).isFile()){if(s.isClientComponent(t)){let e=D.relative(s.projectRoot,t),n=(e.startsWith(`..`)?t:e).replace(J,`/`);return c.set(t,n),{id:`\0client-ref:${t}`}}try{let e=T.readFileSync(t,`utf-8`);if(V(e)){let n=D.relative(s.projectRoot,t),r=n.startsWith(`..`)?t:n,i=W(e);return l.set(t,{actionId:r,hasDefaultExport:i}),{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=D.relative(s.projectRoot,t),r=(c.get(t)||(n.startsWith(`..`)?t:n)).replace(J,`/`);return{code:`
|
|
44
|
+
function registerClientReference(clientReference, id, exportName) {
|
|
45
|
+
const key = id + '#' + exportName;
|
|
46
|
+
const clientProxy = {};
|
|
47
|
+
Object.defineProperty(clientProxy, '$$typeof', {
|
|
48
|
+
value: Symbol.for('react.client.reference'),
|
|
49
|
+
enumerable: false
|
|
50
|
+
});
|
|
51
|
+
Object.defineProperty(clientProxy, '$$id', {
|
|
52
|
+
value: key,
|
|
53
|
+
enumerable: false
|
|
54
|
+
});
|
|
55
|
+
Object.defineProperty(clientProxy, '$$async', {
|
|
56
|
+
value: false,
|
|
57
|
+
enumerable: false
|
|
58
|
+
});
|
|
59
|
+
return clientProxy;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export default registerClientReference(null, ${JSON.stringify(r)}, "default");
|
|
63
|
+
`,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=D.relative(s.projectRoot,t).replace(J,`/`),r=n.startsWith(`src/`)?n.slice(4):n,i=D.join(s.options.outDir,s.options.rscDir,r.replace(q,`.js`)),a=A(D.resolve(s.projectRoot,i)).href;return{code:l.get(t)?.hasDefaultExport??!1?`export * from ${JSON.stringify(a)};\nexport { default } from ${JSON.stringify(a)};`:`export * from ${JSON.stringify(a)};`,moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!i)return null;if(e.startsWith(`file://`)){let t=e.replace(ne,``);return T.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null;n=ie(e,s.options.alias||{},s.projectRoot);let r=t?.startsWith(`\0`)?a:t?D.dirname(t):a;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(s.isClientComponent(t))return null;let e=D.join(s.projectRoot,`src`);if(!t.startsWith(e))return null;let n=D.relative(e,t),r=D.join(s.options.outDir,s.options.rscDir,n.replace(q,`.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=s.options.alias||{};for(let[n,r]of Object.entries(t))if(e.startsWith(`${n}/`)||e===n){let t=e.slice(n.length),i=D.join(r,t),a=D.isAbsolute(i)?i:D.resolve(s.projectRoot,i);for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=a+e;if(T.existsSync(t)&&T.statSync(t).isFile())return t}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let t=D.join(a,`index${e}`);if(T.existsSync(t))return t}return a}return null}},{name:`resolve-rari-proxy`,resolveId:e=>{if(o&&e===`rari`){let e=D.resolve(s.projectRoot,`node_modules/rari/dist/proxy/RariResponse.mjs`);if(T.existsSync(e))return e;let t=D.resolve(s.projectRoot,`node_modules/rari/src/proxy/RariResponse.ts`);if(T.existsSync(t))return t}return null}},{name:`externalize-deps`,resolveId:e=>e.startsWith(`\0`)?null:e.startsWith(`node:`)||s.isNodeBuiltin(e)||[`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`rari/image`].includes(e)?{id:e,external:!0}:e===`rari`||e===`rari/client`?null:!e.startsWith(`.`)&&!e.startsWith(`/`)?{id:e,external:!0}:null}]}async buildComponentCodeOnly(e){let t=await 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:[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(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 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()};for(let[e,n]of this.serverComponents){if(this.isPageComponent(e))continue;let r=D.relative(this.projectRoot,e),i=this.getComponentId(r),a=D.join(this.options.rscDir,`${i}.js`),o=D.join(this.options.outDir,a),s=D.dirname(o);await T.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=A(D.resolve(this.projectRoot,o)).href;t.components[i]={id:i,filePath:e,relativePath:r,bundlePath:a,moduleSpecifier:c,dependencies:n.dependencies,hasNodeImports:n.hasNodeImports}}for(let[e,n]of this.serverComponents){if(!this.isPageComponent(e))continue;let r=D.relative(this.projectRoot,e),i=this.getComponentId(r),a=D.join(this.options.rscDir,`${i}.js`),o=D.join(this.options.outDir,a),s=D.dirname(o);await T.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=A(D.resolve(this.projectRoot,o)).href;t.components[i]={id:i,filePath:e,relativePath:r,bundlePath:a,moduleSpecifier:c,dependencies:n.dependencies,hasNodeImports:n.hasNodeImports}}for(let[e,n]of this.serverActions){let r=D.relative(this.projectRoot,e),i=this.getComponentId(r),a=D.join(this.options.rscDir,`${i}.js`),o=D.join(this.options.outDir,a),s=D.dirname(o);await T.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=A(D.resolve(this.projectRoot,o)).href;t.components[i]={id:i,filePath:e,relativePath:r,bundlePath:a,moduleSpecifier:c,dependencies:n.dependencies,hasNodeImports:n.hasNodeImports}}let n=D.join(this.options.outDir,this.options.manifestPath);await T.promises.writeFile(n,JSON.stringify(t,null,2),`utf-8`);let r={};this.options.csp&&(r.csp=this.options.csp),this.options.cacheControl&&(r.cacheControl=this.options.cacheControl);let i=D.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(r).length===0)try{await T.promises.unlink(i)}catch(e){e.code!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await T.promises.writeFile(i,JSON.stringify(r,null,2),`utf-8`);return t}async buildSingleComponent(e,t,n=!1){let r=await T.promises.readFile(e,`utf-8`),i=this.transformClientImports(r,e),a=this.isPageComponent(e),o=a?this.transformComponentImportsToGlobal(i):i,s=D.extname(e),c;c=s===`.tsx`?`tsx`:s===`.ts`?`ts`:s===`.jsx`?`jsx`:`js`;let l=`\0virtual:${e}`,u=await M({input:l,platform:`node`,write:!1,external:[bt,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${c}`]:c},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(O.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(l,o,c,e,a)});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 T.promises.writeFile(t,f,`utf-8`);let p=await T.promises.open(t,`r+`);if(await p.sync(),await p.close(),n)return f}transformClientImports(e,t){let n=e,r,i=[],a=!1,o=[`rari/image`];for(mt.lastIndex=0;r=mt.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=D.relative(this.projectRoot,e).replace(J,`/`))}if(l){a=!0;let t=``;n?t=`const ${n} = registerClientReference(
|
|
64
|
+
null,
|
|
65
|
+
${JSON.stringify(u)},
|
|
66
|
+
"default"
|
|
67
|
+
);`:s&&(t=s.split(`,`).map(e=>e.trim()).map(e=>{let[t,n]=e.includes(` as `)?e.split(` as `).map(e=>e.trim()):[e,e];return`const ${n} = registerClientReference(
|
|
68
|
+
null,
|
|
69
|
+
${JSON.stringify(u)},
|
|
70
|
+
${JSON.stringify(t)}
|
|
71
|
+
);`}).join(`
|
|
72
|
+
`)),i.push({original:e,replacement:t})}}a&&(n=`
|
|
73
|
+
function registerClientReference(clientReference, id, exportName) {
|
|
74
|
+
const key = id + '#' + exportName;
|
|
75
|
+
|
|
76
|
+
const clientProxy = {};
|
|
77
|
+
|
|
78
|
+
Object.defineProperty(clientProxy, '$$typeof', {
|
|
79
|
+
value: Symbol.for('react.client.reference'),
|
|
80
|
+
enumerable: false
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
Object.defineProperty(clientProxy, '$$id', {
|
|
84
|
+
value: key,
|
|
85
|
+
enumerable: false
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
Object.defineProperty(clientProxy, '$$async', {
|
|
89
|
+
value: false,
|
|
90
|
+
enumerable: false
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
if (typeof globalThis.registerClientComponent === 'function') {
|
|
95
|
+
globalThis.registerClientComponent(key, id, clientProxy);
|
|
96
|
+
}
|
|
97
|
+
} catch (error) {
|
|
98
|
+
console.error('[rari] Build: Failed to register client reference:', error);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return clientProxy;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
`+n);for(let{original:e,replacement:t}of i)n=n.replace(e,t);return n}resolveImportPath(e,t){let n=e,r=this.options.alias||{};for(let[t,i]of Object.entries(r))if(e.startsWith(`${t}/`)||e===t){let r=e.slice(t.length);n=D.join(i,r);break}D.isAbsolute(n)||(n=D.resolve(D.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];return Ae(n,i)||je(n,i)||`${n}.tsx`}getComponentId(e){return e.replace(gt,`/`).replace(q,``).replace(x,`_`).replace(C,``)}async rebuildComponent(e){let t=this.getComponentId(D.relative(this.projectRoot,e)),n=await T.promises.readFile(e,`utf-8`),r=this.extractDependencies(n),i={filePath:e,originalCode:n,dependencies:r,hasNodeImports:this.hasNodeImports(n)};this.isServerAction(n)?this.serverActions.set(e,i):this.serverComponents.set(e,i);let a=D.join(this.options.rscDir,`${t}.js`),o=D.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await T.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.dependencies)===JSON.stringify(r))return await T.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a),{componentId:t,bundlePath:D.join(this.options.outDir,a),success:!0};let l=D.dirname(o);await T.promises.mkdir(l,{recursive:!0});let u=await this.buildSingleComponent(e,o,!0);return this.buildCache.set(e,{code:u,timestamp:Date.now(),dependencies:r}),await this.updateManifestForComponent(t,e,a),{componentId:t,bundlePath:D.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,t,n){let r=D.join(this.options.outDir,this.options.manifestPath),i;if(this.manifestCache)i=this.manifestCache;else if(T.existsSync(r)){let e=await T.promises.readFile(r,`utf-8`);i=JSON.parse(e),this.manifestCache=i}else i={components:{},buildTime:new Date().toISOString()},this.manifestCache=i;let a=this.serverComponents.get(t)||this.serverActions.get(t),o=D.join(this.options.outDir,n),s=A(D.resolve(this.projectRoot,o)).href;if(a)i.components[e]={id:e,filePath:t,relativePath:D.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:s,dependencies:a.dependencies,hasNodeImports:a.hasNodeImports};else{let r=await T.promises.readFile(t,`utf-8`);i.components[e]={id:e,filePath:t,relativePath:D.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:s,dependencies:this.extractDependencies(r),hasNodeImports:this.hasNodeImports(r)}}i.buildTime=new Date().toISOString(),await T.promises.writeFile(r,JSON.stringify(i,null,2),`utf-8`),this.manifestCache=i}clearCache(){this.buildCache.clear(),this.manifestCache=null}invalidateBuildCacheFor(e){this.buildCache.delete(e)}async getTransformedComponentCode(e){return await this.buildComponentCodeOnly(e)}};function Y(e,t,n=!0){n&&t.buildImportGraph(e);let r=T.readdirSync(e,{withFileTypes:!0});for(let n of r){let r=D.join(e,n.name);if(n.isDirectory())Y(r,t,!1);else if(n.isFile()&&w.test(n.name)){if(yt.test(n.name)||n.name.endsWith(`.d.ts`))continue;try{let e=T.readFileSync(r,`utf-8`);if(V(e)){t.addServerComponent(r,e);continue}if(t.isOnlyImportedByClientComponents(r))continue;t.isServerComponent(r,e)&&t.addServerComponent(r,e)}catch(e){console.warn(`[server-build] Error checking ${r}:`,e instanceof Error?e.message:e)}}}}function X(e={}){let t=null,n,r=!1,i={};return{name:`rari-server-build`,configResolved(a){n=a.root,r=a.command===`serve`;let o={};if(a.resolve?.alias){let e=a.resolve.alias;Array.isArray(e)?e.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&(o[e.find]=e.replacement)}):typeof e==`object`&&Object.entries(e).forEach(([e,t])=>{typeof t==`string`&&(o[e]=t)})}i=o,t=new xt(n,{...e,alias:o})},buildStart(){if(!t)return;let e=O.env.NODE_ENV===`production`,r=[D.join(n,`dist`,`cache`,`og`),D.join(n,`dist`,`cache`,`images`)];e&&r.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of r)try{T.existsSync(e)&&T.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let i=D.join(n,`src`);T.existsSync(i)&&Y(i,t)},async closeBundle(){if(t){await t.buildServerComponents();try{let{generateRobotsFile:e}=await import(`./robots-generator-l2O5neuR.mjs`);await e({appDir:D.join(n,`src`,`app`),outDir:D.join(n,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-generator-BTG9lURQ.mjs`);await e({appDir:D.join(n,`src`,`app`),outDir:D.join(n,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`],aliases:i})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}}},async handleHotUpdate({file:e}){if(!t||!r)return;let i=D.relative(n,e).replace(gt,`/`);if(!(!i.startsWith(`src/`)||!w.test(i)))try{if(H(await T.promises.readFile(e,`utf-8`)))return;await t.buildServerComponents()}catch(e){console.error(`[rari] Build: Error rebuilding ${i}:`,e)}}}}const St=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ct=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,wt=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Tt=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Et=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Dt=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ot=/import\s+["']\.\.?\/([^"']+)["'];?/g,kt=/import\s*(?:\(\s*)?["']([^"']+)["']\)?/g,At=/export\s*\{([^}]+)\}/g,jt=/\s+as\s+/,Mt=/export\s+default\s+(?:function|class)\s+\w+/,Nt=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,Pt=/export\s+default\s+([^;]+)/,Ft=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,It=/^['"]use client['"];?\s*$/gm,Lt=/import\s+["']([^"']+)["']/g,Rt=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,zt=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,Bt=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,Vt=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,Ht=/import\s+["']([^"']+)["']/g,Ut=/from(\s*)(['"])(?:\.\/vendor\/react-flight-client\/index|rari\/runtime\/vendor\/react-flight-client\/index)\.mjs\2/g,Wt=/\bJSX\b/,Gt=/^components\//,Kt=/\{([^}]*)\}/,qt=/^['"]use client['"];?\s*\n/,Jt={remotePatterns:[],localPatterns:[],deviceSizes:g,imageSizes:h,formats:p,qualityAllowlist:m,minimumCacheTTL:60,maxCacheSize:f};async function Z(e){let t=import.meta.url,n=k(t),r=D.dirname(n),i=[D.join(r,`runtime`,e),D.join(r,`../runtime`,e)];for(let e of i)try{let t=await T.promises.readFile(e,`utf-8`);return e.endsWith(`.ts`)&&(t=t.replace(St,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Ct,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(wt,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Tt,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(Et,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(Dt,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(Ot,(e,t)=>`import "rari/${t}";`)),t}catch(t){t.code!==`ENOENT`&&t.code!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${e}:`,t)}throw Error(`Could not find ${e}. Tried: ${i.join(`, `)}`)}async function Yt(){return Z(`rsc-client-runtime.mjs`)}async function Xt(e,t){return(await Z(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function Zt(){return Z(`react-server-dom-shim.mjs`)}async function Qt(e,t){let n=await Ze(D.join(e,`src`)),r={...Jt,...t.images,preoptimizeManifest:n.images},i=D.join(e,`dist`),a=D.join(i,`server`);T.existsSync(a)||T.mkdirSync(a,{recursive:!0});let o=D.join(a,`image.json`);T.writeFileSync(o,JSON.stringify(r,null,2))}function $t(e,t=[]){let n=new Set;function r(e){if(!T.existsSync(e))return;let t=T.readdirSync(e,{withFileTypes:!0});for(let i of t){let t=D.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;r(t)}else if(i.isFile()&&w.test(i.name))try{H(T.readFileSync(t,`utf8`))&&n.add(t)}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error during file scan:`,t,e)}}}r(e);for(let e of t)T.existsSync(e)&&r(e);return n}function en(e){return e}function tn(e={}){let t=new Map,n=new Set,r=new Map,i=null,a=null,o={};function s(e){if(r.has(e))return r.get(e);let t={hasUseServer:!1,hasUseClient:!1},n=e.replace(S,`/`);if(!w.test(n)||!n.includes(`/src/`))return r.set(e,t),t;try{let n=T.readFileSync(e,`utf-8`);t.hasUseServer=V(n),t.hasUseClient=H(n),r.set(e,t)}catch{r.set(e,t)}return t}function c(t){if(t.includes(`node_modules`)||t.includes(`/rari/dist/`)||t.includes(`\\rari\\dist\\`))return!1;let n=e.projectRoot||O.cwd(),r=D.join(n,`index.html`);if(T.existsSync(r))try{let e=T.readFileSync(r,`utf-8`);for(let r of e.matchAll(kt)){let e=r[1];if(e.startsWith(`/src/`)&&D.join(n,e.slice(1))===t)return!1}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading index.html:`,e)}let i;try{i=T.realpathSync(t)}catch{return!1}try{if(!T.existsSync(i))return!1;let e=T.readFileSync(i,`utf-8`),t=H(e);return V(e)?!1:!t}catch{return!1}}function l(e){try{let t=[],n=e.matchAll(At);for(let e of n){let n=e[1].split(`,`);for(let e of n){let n=e.trim().split(jt).at(-1)?.trim();n&&t.push(n)}}(Mt.test(e)||W(e))&&t.push(`default`);let r=e.matchAll(Ft);for(let e of r)e[1]&&t.push(e[1]);return[...new Set(t)]}catch{return[]}}function u(e,t){if(!V(e))return e;let n=l(e);if(n.length===0)return e;let r=e;r+=`
|
|
4
105
|
|
|
5
106
|
import {registerServerReference} from "react-server-dom-rari/server";
|
|
6
|
-
`;for(let i of n)if(i
|
|
107
|
+
`;for(let i of n)if(i==="default"){let n=e.match(Nt);if(n){let e=n[1];r+=`
|
|
7
108
|
// Register server reference for default export
|
|
8
|
-
`,r+=`registerServerReference(${e}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`}else{let n=e.match(
|
|
109
|
+
`,r+=`registerServerReference(${e}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`}else{let n=e.match(Pt);if(n){let e=n[1].trim(),a=`__default_export__`;r=r.replace(Pt,`const ${a} = ${e};\nexport default ${a}`),r+=`
|
|
9
110
|
// Register server reference for default export
|
|
10
111
|
`,r+=`if (typeof ${a} === "function") {\n`,r+=` registerServerReference(${a}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`,r+=`}
|
|
11
112
|
`}}}else r+=`\n// Register server reference for ${i}\n`,r+=`if (typeof ${i} === "function") {\n`,r+=` registerServerReference(${i}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`,r+=`}
|
|
@@ -14,11 +115,11 @@ import {registerServerReference} from "react-server-dom-rari/server";
|
|
|
14
115
|
if (import.meta.hot) {
|
|
15
116
|
import.meta.hot.accept(() => {
|
|
16
117
|
});
|
|
17
|
-
}`,r}function d(e,t){let n=
|
|
18
|
-
`;for(let e of n)e
|
|
19
|
-
`;for(let e of n)e
|
|
20
|
-
`;for(let e of i){if(e
|
|
21
|
-
`);for(let e of i){let i=e.match(
|
|
118
|
+
}`,r}function d(e,t){let n=V(e),r=c(t);if(n){let n=l(e);if(n.length===0)return``;let r=D.relative(O.cwd(),t).replace(S,`/`).replace(w,``).replace(x,`_`).replace(C,``),i=`import { createServerReference } from "rari/runtime/actions";
|
|
119
|
+
`;for(let e of n)e==="default"?i+=`export default createServerReference("default", ${JSON.stringify(r)}, "default");\n`:i+=`export const ${e} = createServerReference("${e}", ${JSON.stringify(r)}, "${e}");\n`;return i}if(r){let n=l(e);if(n.length===0)return``;let r=D.relative(O.cwd(),t).replace(S,`/`).replace(w,``).replace(x,`_`).replace(C,``).replace(Gt,``),i=`import { createServerComponentWrapper } from "virtual:rsc-integration.ts";
|
|
120
|
+
`;for(let e of n)e==="default"?i+=`export default createServerComponentWrapper("${r}", ${JSON.stringify(t)});\n`:i+=`export const ${e} = createServerComponentWrapper("${r}_${e}", ${JSON.stringify(t)});\n`;return i}if(!H(e))return e;let i=l(e);if(i.length===0)return``;let a=`import {registerClientReference} from "react-server-dom-rari/server";
|
|
121
|
+
`;for(let e of i){if(e==="default"){let e=`Attempted to call the default export of ${t} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;a+=`export default `,a+=`registerClientReference(function() {`,a+=`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.`;a+=`export const ${e} = `,a+=`registerClientReference(function() {`,a+=`throw new Error(${JSON.stringify(t)});`}a+=`},`,a+=`${JSON.stringify(t)},`,a+=`${JSON.stringify(e)});\n`}return a}function f(e,t){return!H(e)||l(e).length===0?e:e.replace(It,``)}function p(e,t){let n=e;for(let[t,r]of Object.entries(o))if(e.startsWith(`${t}/`)){n=e.replace(t,r);break}else if(e===t){n=r;break}let r=D.resolve(D.dirname(t),n),i=[`.tsx`,`.jsx`,`.ts`,`.js`];return Ae(r,i)||je(r,i)||`${r}.tsx`}function m(e){return(e.split(`/`).pop()||e).replace(v,``)}let h=!1;async function g(){let e=`http://localhost:${O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.env.RSC_PORT||3e3)}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return h=t,t}catch{return h=!1,!1}}let _=[{name:`rari`,config(t,{command:n}){if(t.define=t.define||{},n===`serve`||O.env.RARI_SERVER_URL||O.env.RARI_HOST){let e=O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.env.RSC_PORT||3e3),n;if(O.env.RARI_SERVER_URL)n=O.env.RARI_SERVER_URL;else if(O.env.RARI_HOST){let t=O.env.RARI_HOST.startsWith(`http`)?O.env.RARI_HOST:`http://${O.env.RARI_HOST}`;n=t.replace(b,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}if(n===`build`){let n=e.projectRoot||O.cwd(),r=D.join(n,`index.html`);if(T.existsSync(r))try{let e=T.readFileSync(r,`utf-8`),n=[];for(let t of e.matchAll(Lt)){let e=t[1];if(e.startsWith(`/src/`)&&w.test(e)){let t=e.slice(1),r=D.basename(t,D.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 r=Array.isArray(t.resolve.dedupe)?t.resolve.dedupe:[],i=[`react`,`react-dom`];t.resolve.dedupe=[...new Set([...r||[],...i])];let a=[];Array.isArray(t.resolve.alias)?a=t.resolve.alias:t.resolve.alias&&typeof t.resolve.alias==`object`&&(a=Object.entries(t.resolve.alias).map(([e,t])=>({find:e,replacement:t})));let o=new Set(a.map(e=>String(e.find)));try{let e=k(import.meta.resolve(`react`)),n=k(import.meta.resolve(`react-dom/client`)),r=k(import.meta.resolve(`react/jsx-runtime`)),i=[];o.has(`react/jsx-runtime`)||i.push({find:`react/jsx-runtime`,replacement:r});try{let e=k(import.meta.resolve(`react/jsx-dev-runtime`));o.has(`react/jsx-dev-runtime`)||i.push({find:`react/jsx-dev-runtime`,replacement:e})}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving react/jsx-dev-runtime:`,e)}o.has(`react`)||i.push({find:`react`,replacement:e}),o.has(`react-dom/client`)||i.push({find:`react-dom/client`,replacement:n}),i.length>0&&(t.resolve.alias=[...a,...i])}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error configuring React aliases:`,e)}t.environments=t.environments||{},t.environments.rsc={resolve:{conditions:[`react-server`,`node`,`import`]},...t.environments.rsc},t.environments.ssr={resolve:{conditions:[`node`,`import`]},...t.environments.ssr},t.environments.client={resolve:{conditions:[`browser`,`import`]},...t.environments.client},t.optimizeDeps=t.optimizeDeps||{},t.optimizeDeps.include=t.optimizeDeps.include||[];for(let e of[`react`,`react-dom`,`react-dom/client`,`react-dom/server`,`react/jsx-runtime`,`react/jsx-dev-runtime`])t.optimizeDeps.include.includes(e)||t.optimizeDeps.include.push(e);if(t.optimizeDeps.exclude=t.optimizeDeps.exclude||[],t.optimizeDeps.exclude.includes(`rari`)||t.optimizeDeps.exclude.push(`rari`),n===`build`)for(let e of[`rsc`,`ssr`,`client`]){let n=t.environments[e];n&&n.build&&(n.build.rolldownOptions=n.build.rolldownOptions||{})}t.server=t.server||{},t.server.proxy=t.server.proxy||{};let c=O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.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=>s(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds?.some(e=>s(e).hasUseClient)?`client/components/[name]-[hash].js`:`assets/[name]-[hash].js`}}return t.environments&&t.environments.client&&(t.environments.client.build||(t.environments.client.build={}),t.environments.client.build.rolldownOptions||(t.environments.client.build.rolldownOptions={}),t.environments.client.build.rolldownOptions.input||(t.environments.client.build.rolldownOptions.input={})),t},configResolved(e){let t=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react-dom/client`]);if(e.resolve?.alias){let n=e.resolve.alias;Array.isArray(n)?n.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!t.has(e.find)&&(o[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(o[e]=n)})}},transform(e,r){if(!w.test(r))return null;let i=this.environment;if(H(e)){t.set(r,`client`),n.add(r);let i=e.split(`
|
|
122
|
+
`);for(let e of i){let i=e.match(Rt);if(!i)continue;let a=i[4];if(!a)continue;let o=p(a,r);T.existsSync(o)&&(t.set(o,`client`),n.add(o))}return f(e,r)}if(t.get(r)===`client`||n.has(r))return f(e,r);if(c(r)){if(t.set(r,`server`),i&&(i.name===`rsc`||i.name===`ssr`))return u(e,r);{let t=d(e,r);return t=`// HMR acceptance for server component
|
|
22
123
|
if (import.meta.hot) {
|
|
23
124
|
import.meta.hot.accept();
|
|
24
125
|
}
|
|
@@ -29,8 +130,8 @@ if (typeof globalThis !== 'undefined') {
|
|
|
29
130
|
globalThis['~rari'].serverComponents.add(${JSON.stringify(r)});
|
|
30
131
|
}
|
|
31
132
|
|
|
32
|
-
${t}`,t}}if(
|
|
33
|
-
`),s=e,l=!1,h=!1,g=!1,_=[];for(let a of o){let o=a.match(
|
|
133
|
+
${t}`,t}}if(V(e))return t.set(r,`server`),i&&(i.name===`rsc`||i.name===`ssr`)?u(e,r):d(e,r);let a=t.get(r);if(a===`server`)return i&&(i.name===`rsc`||i.name===`ssr`)?u(e,r):d(e,r);if(a===`client`)return f(e,r);t.set(r,`unknown`);let o=e.split(`
|
|
134
|
+
`),s=e,l=!1,h=!1,g=!1,_=[];for(let a of o){let o=a.match(Rt);if(!o)continue;let u=o[1],d=o[4],f=m(d),v=p(d,r),y=H(e)||t.get(r)===`client`||r.includes(`entry-client`),b=t.get(v)===`client`||T.existsSync(v)&&H(T.readFileSync(v,`utf-8`));if(b&&(t.set(v,`client`),n.add(v)),b&&i&&(i.name===`rsc`||i.name===`ssr`)){if(!y){let e=a,t=u||`default`,n=`
|
|
34
135
|
import { registerClientReference } from "react-server-dom-rari/server";
|
|
35
136
|
const ${t} = registerClientReference(
|
|
36
137
|
function() {
|
|
@@ -38,10 +139,10 @@ const ${t} = registerClientReference(
|
|
|
38
139
|
},
|
|
39
140
|
${JSON.stringify(v)},
|
|
40
141
|
${JSON.stringify(u||`default`)}
|
|
41
|
-
);`;s=s.replace(e,n),l=!0,h=!0}}else if(!y&&c(v)){l=!0,h=!0,g=!0;let e=a;u&&u!==`_`&&_.push(`const ${u} = createServerComponentWrapper('${f}', '${d}');`),s=s.replace(e,``)}}if(l){let e=s.includes(`import React`)||s.match(
|
|
142
|
+
);`;s=s.replace(e,n),l=!0,h=!0}}else if(!y&&c(v)){l=!0,h=!0,g=!0;let e=a;u&&u!==`_`&&_.push(`const ${u} = createServerComponentWrapper('${f}', '${d}');`),s=s.replace(e,``)}}if(l){let e=s.includes(`import React`)||s.match(zt)||s.match(Bt),n=s.includes(`createServerComponentWrapper`),i=``;if(h&&!e&&(i+=`import React from 'react';
|
|
42
143
|
`),g&&!n&&(i+=`import { createServerComponentWrapper } from 'virtual:rsc-integration.ts';
|
|
43
144
|
`),_.length>0&&(i+=`${_.join(`
|
|
44
|
-
`)}\n`),i&&(s=i+s),!s.includes(`Suspense`)){let e=s.match(
|
|
145
|
+
`)}\n`),i&&(s=i+s),!s.includes(`Suspense`)){let e=s.match(Vt);e&&(e[1]&&!e[2].includes(`Suspense`)?s=s.replace(e[0],e[0].replace(Kt,`{ Suspense, $1 }`)):e[1]||(s=s.replace(e[0],`import React, { Suspense } from 'react';`)))}let a=O.env.NODE_ENV!==`production`,o=s.includes(`</`)||s.includes(`/>`)||Wt.test(s);return!H(s)&&o&&a&&(s=`'use client';\n\n${s}`,t.set(r,`client`)),s}return null},async configureServer(n){let r=e.projectRoot||O.cwd(),s=D.join(r,`src`);await Qt(r,e);let l=null,u=async()=>{try{let{ServerComponentBuilder:t,scanDirectory:i}=await Promise.resolve().then(()=>ut),s=new t(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,cacheControl:e.cacheControl});if(l=s,!a&&l){let e=O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.env.RSC_PORT||3e3);a=new Pe(l,e)}let u=D.join(r,`src`),d=[];if(T.existsSync(u)){let e=t=>{let n=T.readdirSync(t,{withFileTypes:!0});for(let r of n){let n=D.join(t,r.name);if(r.isDirectory())e(n);else if(r.isFile()&&w.test(r.name))try{c(n)&&d.push(n)}catch(e){console.error(`[rari] Error checking ${n}:`,e)}}};e(u),i(u,s)}d.length>0&&n.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:d}});let f=await s.getTransformedComponentsForDevelopment(),p=`http://localhost:${O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.env.RSC_PORT||3e3)}`;for(let e of f)try{if(e.id.startsWith(`app/`)||V(e.code))continue;let t=await fetch(`${p}/_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:${O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.env.RSC_PORT||3e3)}`,t=$t(s,Object.values(o));for(let n of t){let t=D.relative(O.cwd(),n),r=D.basename(n).replace(v,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:t,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${r}:`,e)}}}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},f=async()=>{if(i)return;let{getBinaryPath:e,getInstallationInstructions:t}=await import(`./platform.mjs`),r;try{r=e()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(t());return}let a=O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.env.RSC_PORT||3e3),o=O.env.NODE_ENV===`production`?`production`:`development`,s=n.config.server.port||5173,c=[`--mode`,o,`--port`,a.toString(),`--host`,`127.0.0.1`];i=oe(r,c,{stdio:[`ignore`,`pipe`,`pipe`],cwd:O.cwd(),env:{...O.env,RUST_LOG:O.env.RUST_LOG||`error`,RARI_VITE_PORT:s.toString()}}),i.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),i.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),i.on(`error`,e=>{h=!1,console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),i.on(`exit`,(e,t)=>{i=null,h=!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 l=!1;for(let e=0;e<20&&(l=await g(),!l);e++)await new Promise(e=>setTimeout(e,500));l?(await d(),await u()):console.error(`Server failed to become ready for component registration`)},p=async t=>{try{if(!c(t))return;let{ServerComponentBuilder:n}=await Promise.resolve().then(()=>ut),i=new n(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,cacheControl:e.cacheControl});i.addServerComponent(t);let a=await i.getTransformedComponentsForDevelopment();if(a.length===0)return;let s=`http://localhost:${O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.env.RSC_PORT||3e3)}`;for(let e of a)try{let t=await fetch(`${s}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}catch(e){console.error(`[rari] Targeted HMR failed for`,`${t}:`,e instanceof Error?e.message:String(e)),setTimeout(u,1e3)}};f().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),n.middlewares.use(async(e,t,n)=>{let r=e.headers.accept;if(r&&r.includes(`text/x-component`)&&e.url&&!e.url.startsWith(`/api`)&&!e.url.startsWith(`/rsc`)&&!e.url.includes(`.`)){if(!h&&!await g()){let e=Date.now();for(;Date.now()-e<1e4&&!await g();)await new Promise(e=>setTimeout(e,100));if(!h){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}}let n=O.env.SERVER_PORT?Number(O.env.SERVER_PORT):Number(O.env.PORT||O.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(ae.from(r))}t.end()}catch(e){console.error(`[rari] Stream error:`,e),t.headersSent||(t.statusCode=500),t.end()}}else t.end();return}catch(e){console.error(`[rari] Failed to proxy RSC request:`,e),t.headersSent||(t.statusCode=500,t.end(`Internal Server Error`));return}}n()}),n.watcher.on(`change`,async e=>{w.test(e)&&t.delete(e),w.test(e)&&e.includes(s)&&(c(e)?(n.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await p(e)):setTimeout(u,1e3))}),n.middlewares.use(`/api/vite/hmr-transform`,async(e,t)=>{if(e.method!==`POST`){t.statusCode=405,t.end(`Method Not Allowed`);return}let n=``;e.on(`data`,e=>{n+=e.toString()}),e.on(`end`,async()=>{try{let{filePath:e}=JSON.parse(n);if(!e){t.statusCode=400,t.end(JSON.stringify({error:`filePath is required`}));return}await p(e),t.statusCode=200,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!0,filePath:e,message:`Component transformation completed`}))}catch(e){t.statusCode=500,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)}))}})}),n.httpServer?.on(`close`,()=>{a&&=(a.dispose(),null),i&&=(i.kill(`SIGTERM`),null),h=!1})},resolveId(e,t){if(e===`virtual:rsc-integration`||e===`virtual:rsc-integration.ts`)return`virtual:rsc-integration.ts`;if(e===`virtual:rari-entry-client`||e===`virtual:rari-entry-client.ts`)return`virtual:rari-entry-client.ts`;if(e===`virtual:react-flight-client`||e===`virtual:react-flight-client.ts`)return`virtual:react-flight-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`virtual:error-boundary-wrapper`||e===`virtual:error-boundary-wrapper.tsx`)return`virtual:error-boundary-wrapper.tsx`;if(e===`./DefaultLoadingIndicator`||e===`./DefaultLoadingIndicator.tsx`)return`virtual:default-loading-indicator.tsx`;if(e===`./LoadingErrorBoundary`||e===`./LoadingErrorBoundary.tsx`)return`virtual:loading-error-boundary.tsx`;if(e===`react-server-dom-rari/server`)return e;if(t&&t.startsWith(`virtual:`)&&e.startsWith(`../`)){let n=import.meta.url,r=k(n),i=D.dirname(r),a=null,o=[D.join(i,`runtime`),D.join(i,`../runtime`)];for(let e of o)if(T.existsSync(e)){a=e;break}if(a){let t=D.join(a,e);if(T.existsSync(t))return t;let n=D.join(a,`../dist`,D.basename(e));if(T.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=D.join(i,e);if(T.existsSync(s))return s;let c=D.join(i,`../dist`,D.basename(e));if(T.existsSync(c))return c}if(O.env.NODE_ENV===`production`)try{let t=D.resolve(e);if(T.existsSync(t)&&c(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(w.test(t)){let e=this.environment;if(e&&e.name===`client`)try{let e=T.readFileSync(t,`utf-8`);if(V(e))return d(e,t)}catch{}}if(t===`virtual:rari-entry-client.ts`){let e=$t(D.join(O.cwd(),`src`),Object.values(o)),t=new Set([...n,...e]),r=[{path:`rari/image`,exports:[`Image`]},{path:`virtual:error-boundary-wrapper.tsx`,exports:[`ErrorBoundaryWrapper`]}],i=[...t].filter(e=>{try{return H(T.readFileSync(e,`utf-8`))}catch{return!1}}).map(e=>{let t=D.relative(O.cwd(),e).replace(S,`/`),n=t.replace(w,``),r=t.startsWith(`..`)?e.replace(S,`/`):t,i=!1,a=``;try{let t=T.readFileSync(e,`utf-8`),n=W(t),r=t.match(te);!n&&r&&(i=!0,a=r[1])}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let o=i?a:D.basename(e,D.extname(e)),s=r.replace(S,`/`),c=s.startsWith(`/`)||y.test(s)?s:`/${s}`;return` "${r}": {
|
|
45
146
|
id: "${n}",
|
|
46
147
|
path: "${r}",
|
|
47
148
|
exportName: "${o}",
|
|
@@ -65,7 +166,7 @@ globalThis['~clientComponents']["${e.path}"] = globalThis['~clientComponents']["
|
|
|
65
166
|
globalThis['~clientComponents']["${e.path}"].component = ExternalModule${t};
|
|
66
167
|
globalThis['~clientComponentPaths'] = globalThis['~clientComponentPaths'] || {};
|
|
67
168
|
globalThis['~clientComponentPaths']["${e.path}"] = "${n}";`)).join(`
|
|
68
|
-
`);return await
|
|
169
|
+
`);return await Xt(a,[`
|
|
69
170
|
const lazyComponentRegistry = {
|
|
70
171
|
${i}
|
|
71
172
|
};
|
|
@@ -78,7 +179,7 @@ for (const [path, config] of Object.entries(lazyComponentRegistry)) {
|
|
|
78
179
|
globalThis['~clientComponentPaths'][path] = config.id;
|
|
79
180
|
}
|
|
80
181
|
`,s].filter(Boolean).join(`
|
|
81
|
-
`))}if(t===`react-server-dom-rari/server`)return await
|
|
182
|
+
`))}if(t===`react-server-dom-rari/server`)return await Zt();if(t===`virtual:app-router-provider.tsx`){let e=[D.join(O.cwd(),`packages/rari/dist/runtime/AppRouterProvider.mjs`),D.join(O.cwd(),`node_modules/rari/dist/runtime/AppRouterProvider.mjs`)];for(let t of e)if(T.existsSync(t))return T.readFileSync(t,`utf-8`);return`export function AppRouterProvider({ children }) { return children; }`}if(t===`virtual:default-loading-indicator.tsx`){let e=[D.join(O.cwd(),`packages/rari/dist/runtime/DefaultLoadingIndicator.mjs`),D.join(O.cwd(),`node_modules/rari/dist/runtime/DefaultLoadingIndicator.mjs`)];for(let t of e)if(T.existsSync(t))return T.readFileSync(t,`utf-8`);return`export function DefaultLoadingIndicator() { return null; }`}if(t===`virtual:loading-error-boundary.tsx`){let e=[D.join(O.cwd(),`packages/rari/dist/runtime/LoadingErrorBoundary.mjs`),D.join(O.cwd(),`node_modules/rari/dist/runtime/LoadingErrorBoundary.mjs`)];for(let t of e)if(T.existsSync(t))return T.readFileSync(t,`utf-8`);return`export class LoadingErrorBoundary extends React.Component { render() { return this.props.children; } }`}if(t===`virtual:error-boundary-wrapper.tsx`){let e=[D.join(O.cwd(),`packages/rari/dist/runtime/ErrorBoundaryWrapper.mjs`),D.join(O.cwd(),`node_modules/rari/dist/runtime/ErrorBoundaryWrapper.mjs`),D.join(O.cwd(),`packages/rari/src/runtime/ErrorBoundaryWrapper.tsx`)];for(let t of e)if(T.existsSync(t)){let e=T.readFileSync(t,`utf-8`);if(!e.includes(`import React`)&&!e.includes(`from "react"`)&&!e.includes(`from 'react'`)){let t=e.match(qt);if(t){let n=t[0];return`
|
|
82
183
|
${n}import * as React from 'react';\n${e.slice(n.length)}`}return`
|
|
83
184
|
import * as React from 'react';\n${e}`}return e}return`'use client';
|
|
84
185
|
import * as React from 'react';
|
|
@@ -152,4 +253,4 @@ export class ErrorBoundaryWrapper extends React.Component {
|
|
|
152
253
|
}
|
|
153
254
|
return this.props.children;
|
|
154
255
|
}
|
|
155
|
-
}`}if(t===`virtual:rsc-integration.ts`)return(await
|
|
256
|
+
}`}if(t===`virtual:rsc-integration.ts`)return(await Yt()).replace(Ut,(e,t,n)=>`from${t}${n}virtual:react-flight-client.ts${n}`);if(t===`virtual:react-flight-client.ts`)return{code:`export * from 'rari/runtime/vendor/react-flight-client'`};if(t.endsWith(`.mjs`)&&T.existsSync(t))try{let n=e.projectRoot||O.cwd(),r=T.realpathSync(t),i=D.relative(n,r),a=!i.startsWith(`..`)&&!D.isAbsolute(i),o=r.includes(`${D.sep}node_modules${D.sep}`),s=r.includes(`${D.sep}packages${D.sep}rari${D.sep}`)||r.includes(`${D.sep}node_modules${D.sep}rari${D.sep}`);return a||o||s?T.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(!w.test(e))return;if(e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let n=a?.detectComponentType(e)||`unknown`,r=e.includes(`/app/`)||e.includes(`\\app\\`),i=e.endsWith(`page.tsx`)||e.endsWith(`page.jsx`),o=e.endsWith(`layout.tsx`)||e.endsWith(`layout.jsx`),s=e.endsWith(`loading.tsx`)||e.endsWith(`loading.jsx`),c=e.endsWith(`error.tsx`)||e.endsWith(`error.jsx`),l=e.endsWith(`not-found.tsx`)||e.endsWith(`not-found.jsx`);if(!(r&&(i||o||s||c||l))&&n!==`client`&&n===`server`)return a&&await a.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(Ht)){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 Qt(e.projectRoot||O.cwd(),e)}},X({...e.serverBuild,csp:e.csp,cacheControl:e.cacheControl})];return e.proxy!==!1&&_.push(ce(e.proxy||{})),e.router!==!1&&_.push(ye(e.router||{})),_}function nn(e){return{plugins:[tn(),...e.plugins||[]],...e}}var rn=class extends Response{static json(e,t){let n=new Headers(t?.headers);return n.has(`content-type`)||n.set(`content-type`,`application/json`),new Response(JSON.stringify(e),{...t,headers:n})}static redirect(e,t=307){return new Response(null,{status:t,headers:{location:e}})}static noContent(e){return new Response(null,{...e,status:204})}},an=se({generateAppRouteManifest:()=>un});const Q={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`},$={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},on=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,sn=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,cn=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var ln=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=[];return await this.scanDirectory(``,e,t,n,r,i,a,o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} API routes`),console.warn(`[rari] Router: Found ${o.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,apiRoutes:this.sortApiRoutes(a),ogImages:o,generated:new Date().toISOString()}}async scanDirectory(e,t,n,r,i,a,o,s){let c=D.join(this.appDir,e),l;try{l=await E.readdir(c)}catch{return}let u=[],d=[];for(let e of l){let t=D.join(c,e),n=await E.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&d.push(e):n.isFile()&&u.push(e)}await this.processSpecialFiles(e,u,t,n,r,i,a,o,s);for(let c of d){let l=e?D.join(e,c):c;await this.scanDirectory(l,t,n,r,i,a,o,s)}}async processSpecialFiles(e,t,n,r,i,a,o,s,c){let l=this.pathToRoute(e),u=this.findFile(t,Q.PAGE);if(u){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:l,filePath:D.join(e,u).replace(S,`/`),segments:t,params:r,isDynamic:r.length>0})}let d=this.findFile(t,Q.LAYOUT);if(d){let t=this.getParentPath(e);r.push({path:l,filePath:D.join(e,d).replace(S,`/`),parentPath:t?this.pathToRoute(t):void 0})}let f=this.findFile(t,Q.LOADING);if(f){let t=this.generateComponentId(l,`loading`);i.push({path:l,filePath:D.join(e,f).replace(S,`/`),componentId:t})}let p=this.findFile(t,Q.ERROR);p&&a.push({path:l,filePath:D.join(e,p).replace(S,`/`)});let m=this.findFile(t,Q.NOT_FOUND);m&&o.push({path:l,filePath:D.join(e,m).replace(S,`/`)});let h=this.findFile(t,Q.OG_IMAGE);if(h){let t=D.join(e,h).replace(S,`/`),n=D.join(this.appDir,t),r,i,a;try{let e=await E.readFile(n,`utf-8`),t=e.match(on);t&&(r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10));let o=e.match(sn);o&&(a=o[1])}catch{}c.push({path:l,filePath:t,width:r,height:i,contentType:a})}let g=this.findFile(t,Q.ROUTE);if(g){let t=await this.processApiRouteFile(e,g);s.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(S,`/`).split(`/`).filter(Boolean).map(e=>$.OPTIONAL_CATCH_ALL.test(e)?`[[...${e.match($.OPTIONAL_CATCH_ALL)[1]}]]`:$.CATCH_ALL.test(e)?`[...${e.match($.CATCH_ALL)[1]}]`:$.DYNAMIC.test(e)?`[${e.match($.DYNAMIC)[1]}]`:e).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(ee).filter(Boolean).map(e=>$.OPTIONAL_CATCH_ALL.test(e)?{type:`optional-catch-all`,value:e,param:e.match($.OPTIONAL_CATCH_ALL)[1]}:$.CATCH_ALL.test(e)?{type:`catch-all`,value:e,param:e.match($.CATCH_ALL)[1]}:$.DYNAMIC.test(e)?{type:`dynamic`,value:e,param:e.match($.DYNAMIC)[1]}:{type:`static`,value:e}):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(ee).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=D.join(this.appDir,e),n=await E.readFile(t,`utf-8`),r=[];for(let e of cn){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(S,`/`),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 un(e,t={}){return new ln({appDir:e,...t}).generateManifest()}function dn(e){return tn(e)}export{rn as ApiResponse,c as HttpRuntimeClient,e as RariRequest,t as RariResponse,i as clearPropsCache,a as clearPropsCacheForComponent,r as createHttpRuntimeClient,nn as defineRariConfig,en as defineRariOptions,u as extractMetadata,l as extractServerProps,s as extractServerPropsWithCache,o as extractStaticParams,un as generateAppRouteManifest,n as hasServerSideDataFetching,dn as rari,ce as rariProxy,ye as rariRouter};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rari",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.14.
|
|
4
|
+
"version": "0.14.2",
|
|
5
5
|
"description": "Runtime Accelerated Rendering Infrastructure (rari)",
|
|
6
6
|
"author": "Ryan Skinner",
|
|
7
7
|
"license": "MIT",
|
|
@@ -107,24 +107,24 @@
|
|
|
107
107
|
"react-dom": "^19.2.6"
|
|
108
108
|
},
|
|
109
109
|
"dependencies": {
|
|
110
|
-
"rolldown": "^1.0.
|
|
110
|
+
"rolldown": "^1.0.3"
|
|
111
111
|
},
|
|
112
112
|
"optionalDependencies": {
|
|
113
|
-
"rari-darwin-arm64": "0.14.
|
|
114
|
-
"rari-darwin-x64": "0.14.
|
|
115
|
-
"rari-linux-arm64": "0.14.
|
|
116
|
-
"rari-linux-x64": "0.14.
|
|
117
|
-
"rari-win32-arm64": "0.14.
|
|
118
|
-
"rari-win32-x64": "0.14.
|
|
113
|
+
"rari-darwin-arm64": "0.14.2",
|
|
114
|
+
"rari-darwin-x64": "0.14.2",
|
|
115
|
+
"rari-linux-arm64": "0.14.2",
|
|
116
|
+
"rari-linux-x64": "0.14.2",
|
|
117
|
+
"rari-win32-arm64": "0.14.2",
|
|
118
|
+
"rari-win32-x64": "0.14.2"
|
|
119
119
|
},
|
|
120
120
|
"devDependencies": {
|
|
121
121
|
"@types/node": "^25.9.1",
|
|
122
122
|
"@types/react": "^19.2.15",
|
|
123
123
|
"@types/react-dom": "^19.2.3",
|
|
124
|
-
"@typescript/native-preview": "^7.0.0-dev.
|
|
125
|
-
"vite-plus": "^0.1.
|
|
126
|
-
"@rari/
|
|
127
|
-
"@rari/
|
|
124
|
+
"@typescript/native-preview": "^7.0.0-dev.20260527.2",
|
|
125
|
+
"vite-plus": "^0.1.23",
|
|
126
|
+
"@rari/deploy": "0.1.0",
|
|
127
|
+
"@rari/logger": "0.1.0"
|
|
128
128
|
},
|
|
129
129
|
"scripts": {
|
|
130
130
|
"build": "pnpm clean && pnpm typecheck && vp pack",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
|
package/dist/routes-CTeHh8gJ.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{h as t,t as n}from"./regex-constants-iGdnDzFV.mjs";import{promises as r}from"node:fs";import i from"node:path";var a=e({generateAppRouteManifest:()=>f});const o={PAGE:`page`,LAYOUT:`layout`,LOADING:`loading`,ERROR:`error`,NOT_FOUND:`not-found`,TEMPLATE:`template`,DEFAULT:`default`,ROUTE:`route`,OG_IMAGE:`opengraph-image`,TWITTER_IMAGE:`twitter-image`,ICON:`icon`,APPLE_ICON:`apple-icon`},s={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},c=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,l=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,u=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var d=class{appDir;extensions;verbose;constructor(e){this.appDir=i.resolve(e.appDir),this.extensions=e.extensions||[`.tsx`,`.jsx`,`.ts`,`.js`],this.verbose=e.verbose||!1}async generateManifest(){this.verbose&&console.warn(`[rari] Router: Scanning app directory: ${this.appDir}`);let e=[],t=[],n=[],r=[],i=[],a=[],o=[];return await this.scanDirectory(``,e,t,n,r,i,a,o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} API routes`),console.warn(`[rari] Router: Found ${o.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,apiRoutes:this.sortApiRoutes(a),ogImages:o,generated:new Date().toISOString()}}async scanDirectory(e,t,n,a,o,s,c,l){let u=i.join(this.appDir,e),d;try{d=await r.readdir(u)}catch{return}let f=[],p=[];for(let e of d){let t=i.join(u,e),n=await r.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&p.push(e):n.isFile()&&f.push(e)}await this.processSpecialFiles(e,f,t,n,a,o,s,c,l);for(let r of p){let u=e?i.join(e,r):r;await this.scanDirectory(u,t,n,a,o,s,c,l)}}async processSpecialFiles(e,t,a,s,u,d,f,p,m){let h=this.pathToRoute(e),g=this.findFile(t,o.PAGE);if(g){let t=this.parseRouteSegments(e),r=this.extractParams(t);a.push({path:h,filePath:i.join(e,g).replace(n,`/`),segments:t,params:r,isDynamic:r.length>0})}let _=this.findFile(t,o.LAYOUT);if(_){let t=this.getParentPath(e);s.push({path:h,filePath:i.join(e,_).replace(n,`/`),parentPath:t?this.pathToRoute(t):void 0})}let v=this.findFile(t,o.LOADING);if(v){let t=this.generateComponentId(h,`loading`);u.push({path:h,filePath:i.join(e,v).replace(n,`/`),componentId:t})}let y=this.findFile(t,o.ERROR);y&&d.push({path:h,filePath:i.join(e,y).replace(n,`/`)});let b=this.findFile(t,o.NOT_FOUND);b&&f.push({path:h,filePath:i.join(e,b).replace(n,`/`)});let x=this.findFile(t,o.OG_IMAGE);if(x){let t=i.join(e,x).replace(n,`/`),a=i.join(this.appDir,t),o,s,u;try{let e=await r.readFile(a,`utf-8`),t=e.match(c);t&&(o=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10));let n=e.match(l);n&&(u=n[1])}catch{}m.push({path:h,filePath:t,width:o,height:s,contentType:u})}let S=this.findFile(t,o.ROUTE);if(S){let t=await this.processApiRouteFile(e,S);p.push(t)}}findFile(e,t){for(let n of this.extensions){let r=`${t}${n}`;if(e.includes(r))return r}}pathToRoute(e){return e?`/${e.replace(n,`/`).split(`/`).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?`[[...${e.match(s.OPTIONAL_CATCH_ALL)[1]}]]`:s.CATCH_ALL.test(e)?`[...${e.match(s.CATCH_ALL)[1]}]`:s.DYNAMIC.test(e)?`[${e.match(s.DYNAMIC)[1]}]`:e).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(t).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?{type:`optional-catch-all`,value:e,param:e.match(s.OPTIONAL_CATCH_ALL)[1]}:s.CATCH_ALL.test(e)?{type:`catch-all`,value:e,param:e.match(s.CATCH_ALL)[1]}:s.DYNAMIC.test(e)?{type:`dynamic`,value:e,param:e.match(s.DYNAMIC)[1]}:{type:`static`,value:e}):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let n=e.split(t).filter(Boolean);return n.length===0?null:n.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=i.join(this.appDir,e),n=await r.readFile(t,`utf-8`),a=[];for(let e of u){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),r=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||r.test(n))&&a.push(e)}return a}async processApiRouteFile(e,t){let r=i.join(e,t).replace(n,`/`),a=this.pathToRoute(e),o=this.parseRouteSegments(e),s=this.extractParams(o),c=await this.detectHttpMethods(r);return{path:a,filePath:r,segments:o,params:s,isDynamic:s.length>0,methods:c}}};async function f(e,t={}){return new d({appDir:e,...t}).generateManifest()}export{a as n,f as t};
|