rari 0.7.12 → 0.7.14

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/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./vite-D4TzV89n.mjs";import{t as s}from"./RariRequest-CW-JhbGM.mjs";import{c,d as l,f as u,g as d,h as f,i as p,m,p as h,u as g}from"./runtime-client-B15ZQXrE.mjs";import{t as _}from"./routes-Bq7zysPc.mjs";import"./constants-CD3aqqK8.mjs";import"./server-build-BTHZMYd8.mjs";export{a as ApiResponse,p as HttpRuntimeClient,s as RariRequest,r as RariResponse,g as clearPropsCache,l as clearPropsCacheForComponent,c as createHttpRuntimeClient,o as defineRariConfig,n as defineRariOptions,u as extractMetadata,h as extractServerProps,m as extractServerPropsWithCache,f as extractStaticParams,_ as generateAppRouteManifest,d as hasServerSideDataFetching,i as rari,e as rariProxy,t as rariRouter};
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./vite-BzhJ1Li7.mjs";import{t as s}from"./RariRequest-CW-JhbGM.mjs";import{c,d as l,f as u,g as d,h as f,i as p,m,p as h,u as g}from"./runtime-client-B15ZQXrE.mjs";import{t as _}from"./routes-Bq7zysPc.mjs";import"./constants-CD3aqqK8.mjs";import"./server-build-CQpOd0dQ.mjs";export{a as ApiResponse,p as HttpRuntimeClient,s as RariRequest,r as RariResponse,g as clearPropsCache,l as clearPropsCacheForComponent,c as createHttpRuntimeClient,o as defineRariConfig,n as defineRariOptions,u as extractMetadata,h as extractServerProps,m as extractServerPropsWithCache,f as extractStaticParams,_ as generateAppRouteManifest,d as hasServerSideDataFetching,i as rari,e as rariProxy,t as rariRouter};
@@ -0,0 +1 @@
1
+ import{n as e,r as t,t as n}from"./server-build-CQpOd0dQ.mjs";export{n as ServerComponentBuilder,t as scanDirectory};
@@ -38,8 +38,36 @@ const ${r} = (props) => {
38
38
  }
39
39
 
40
40
  return Component(props);
41
- }`;i.push({original:n,replacement:p})}}}let a=n;for(let{original:e,replacement:t}of i)a=a.replace(e,t);return a}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}async buildComponentCodeOnly(n,a,o){let s=await e.promises.readFile(n,`utf-8`),c=this.transformClientImports(s,n),l=this.isPageComponent(n)?this.transformComponentImportsToGlobal(c):c,u=t.extname(n),d;d=u===`.tsx`?`tsx`:u===`.ts`?`ts`:u===`.jsx`?`jsx`:`js`;try{let a=await r({stdin:{contents:l,resolveDir:t.dirname(n),sourcefile:n,loader:d},bundle:!0,platform:`node`,target:`es2022`,format:`esm`,mainFields:[`module`,`main`],conditions:[`import`,`module`,`default`],jsx:`transform`,jsxFactory:`React.createElement`,jsxFragment:`React.Fragment`,define:{global:`globalThis`,"process.env.NODE_ENV":`"production"`,...this.options.define},loader:{".ts":`ts`,".tsx":`tsx`,".js":`js`,".jsx":`jsx`},resolveExtensions:[`.ts`,`.tsx`,`.js`,`.jsx`],minify:!1,minifyWhitespace:!0,minifyIdentifiers:!0,minifySyntax:!0,sourcemap:!1,metafile:!1,write:!1,plugins:[{name:`resolve-aliases`,setup:n=>{let r=this,i=this.options.alias||{};for(let[a,o]of Object.entries(i)){let i=a.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),s=RegExp(`^${i}(/|$)`);n.onResolve({filter:s},n=>{let i=n.path.slice(a.length),s=t.join(o,i),c=t.isAbsolute(s)?s:t.resolve(n.resolveDir,s);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=c+t;if(e.existsSync(i)&&e.statSync(i).isFile()){if(r.isClientComponent(i))return{path:n.path,external:!0};try{let t=e.readFileSync(i,`utf-8`);if(t.includes(`'use server'`)||t.includes(`"use server"`))return{path:n.path,external:!0}}catch{}return{path:i}}}return{path:c}})}}},{name:`replace-react-imports`,setup(e){e.onLoad({filter:/runtime-client.*\.js$/},async e=>{let t=await(await import(`node:fs/promises`)).readFile(e.path,`utf-8`);return t=t.replace(/import\s+React\d*(?:\s*,\s*\{[^}]*\})?\s+from\s+['"]react['"];?/g,`// React is available as globalThis.React`),t=t.replace(/React2/g,`React`),{contents:t,loader:`js`}})}},{name:`hmr-auto-external`,setup:n=>{let r=this;n.onResolve({filter:/.*/},async n=>{if(n.path.includes(`../components/`)||n.path.includes(`./components/`)){let i=t.resolve(n.resolveDir,n.path);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let a=i+t;if(e.existsSync(a)&&e.statSync(a).isFile()&&r.isClientComponent(a))return{path:n.path,namespace:`component-stub`}}}if(n.path===`react`||n.path===`react-dom`||n.path===`react/jsx-runtime`||n.path===`react/jsx-dev-runtime`||n.path.startsWith(`node:`)||i(n.path)||n.path===`rari/image`||n.path.startsWith(`rari/image/`))return{path:n.path,external:!0};if(n.path===`rari/client`)return null;if(n.path.startsWith(`@/actions/`)||n.path.includes(`/actions/`)){let r=t.resolve(n.resolveDir,n.path);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=r+t;if(e.existsSync(i)){try{let t=e.readFileSync(i,`utf-8`);if(t.includes(`'use server'`)||t.includes(`"use server"`))return{path:n.path,external:!0}}catch{}break}}}return null}),n.onLoad({filter:/.*/,namespace:`component-stub`},async e=>{let t=e.path.match(/\/components\/(\w+)/);return{contents:`// Component stub for ${t?t[1]:`Unknown`} - replaced by global reference`,loader:`js`}})}},{name:`resolve-server-functions`,setup(n){n.onResolve({filter:/^\.\.?\/.*(functions|actions)/},async n=>{let r=t.resolve(t.dirname(n.importer),n.path);for(let t of[`.ts`,`.js`,`.tsx`,`.jsx`,`/index.ts`,`/index.js`]){let n=r+t;if(e.existsSync(n))return{path:n}}return null})}}]});if(a.outputFiles&&a.outputFiles.length>0)return a.outputFiles[0].text;throw a.errors.length>0?(console.error(`[rari] Build: ESBuild errors:`,a.errors),Error(`ESBuild compilation failed with ${a.errors.length} errors`)):Error(`No output generated from ESBuild`)}catch(e){throw console.error(`[rari] Build: ESBuild failed for ${n}:`,e),e}}async buildServerComponents(){let n=t.join(this.options.outDir,this.options.serverDir);await e.promises.mkdir(n,{recursive:!0});let r={react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`},i=this.options.alias||{};for(let[e,n]of Object.entries(i)){let i=t.isAbsolute(n)?n:t.resolve(this.projectRoot,n);r[`${e}/`]=`file://${i}/`}let a={components:{},importMap:{imports:r},version:`1.0.0`,buildTime:new Date().toISOString(),csp:this.options.csp,rateLimit:this.options.rateLimit,spamBlocker:this.options.spamBlocker};for(let[n,r]of this.serverComponents){if(this.isPageComponent(n))continue;let i=t.relative(this.projectRoot,n),o=this.getComponentId(i),s=t.join(this.options.serverDir,`${o}.js`),c=t.join(this.options.outDir,s),l=t.dirname(c);await e.promises.mkdir(l,{recursive:!0}),await this.buildSingleComponent(n,c,r);let u=`file://${t.resolve(this.projectRoot,c)}`;a.components[o]={id:o,filePath:n,relativePath:i,bundlePath:s,moduleSpecifier:u,dependencies:r.dependencies,hasNodeImports:r.hasNodeImports}}for(let[n,r]of this.serverComponents){if(!this.isPageComponent(n))continue;let i=t.relative(this.projectRoot,n),o=this.getComponentId(i),s=t.join(this.options.serverDir,`${o}.js`),c=t.join(this.options.outDir,s),l=t.dirname(c);await e.promises.mkdir(l,{recursive:!0}),await this.buildSingleComponent(n,c,r);let u=`file://${t.resolve(this.projectRoot,c)}`;a.components[o]={id:o,filePath:n,relativePath:i,bundlePath:s,moduleSpecifier:u,dependencies:r.dependencies,hasNodeImports:r.hasNodeImports}}for(let[n,r]of this.serverActions){let i=t.relative(this.projectRoot,n),o=this.getComponentId(i),s=t.join(this.options.serverDir,`${o}.js`),c=t.join(this.options.outDir,s),l=t.dirname(c);await e.promises.mkdir(l,{recursive:!0}),await this.buildSingleComponent(n,c,r);let u=`file://${t.resolve(this.projectRoot,c)}`;a.components[o]={id:o,filePath:n,relativePath:i,bundlePath:s,moduleSpecifier:u,dependencies:r.dependencies,hasNodeImports:r.hasNodeImports}}let o=t.join(this.options.outDir,this.options.manifestPath);return await e.promises.writeFile(o,JSON.stringify(a,null,2),`utf-8`),a}async buildSingleComponent(n,a,o,s=!1){let c=await e.promises.readFile(n,`utf-8`),l=this.transformClientImports(c,n),u=this.isPageComponent(n),d=u?this.transformComponentImportsToGlobal(l):l,f=t.extname(n),p;p=f===`.tsx`?`tsx`:f===`.ts`?`ts`:f===`.jsx`?`jsx`:`js`;try{let o=await r({stdin:{contents:d,resolveDir:t.dirname(n),sourcefile:n,loader:p},bundle:!0,platform:`node`,target:`es2022`,format:`esm`,outfile:a,mainFields:[`module`,`main`],conditions:[`import`,`module`,`default`],jsx:`transform`,jsxFactory:`React.createElement`,jsxFragment:`React.Fragment`,define:{global:`globalThis`,"process.env.NODE_ENV":`"production"`,...this.options.define},loader:{".ts":`ts`,".tsx":`tsx`,".js":`js`,".jsx":`jsx`},resolveExtensions:[`.ts`,`.tsx`,`.js`,`.jsx`],minify:this.options.minify,minifyWhitespace:this.options.minify,minifyIdentifiers:this.options.minify,minifySyntax:this.options.minify,sourcemap:!1,metafile:!1,write:!1,plugins:[{name:`external-server-actions`,setup:n=>{n.onResolve({filter:/.*/},async n=>{if(n.namespace!==`file`&&n.namespace!==``||n.path.startsWith(`node:`)||i(n.path)||n.path===`react`||n.path===`react-dom`||n.path===`react/jsx-runtime`||n.path===`react/jsx-dev-runtime`)return null;let r=null,a=this.options.alias||{};for(let[e,i]of Object.entries(a))if(n.path.startsWith(`${e}/`)||n.path===e){let a=n.path.slice(e.length),o=t.join(i,a);r=t.isAbsolute(o)?o:t.resolve(n.resolveDir,o);break}if(!r&&(n.path.startsWith(`./`)||n.path.startsWith(`../`))&&(r=t.resolve(n.resolveDir,n.path)),r)for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=r+t;if(e.existsSync(i)&&e.statSync(i).isFile()){try{let t=e.readFileSync(i,`utf-8`).split(`
42
- `);for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`)return{path:n.path,namespace:`server-action-reference`};if(t)break}}}catch{}break}}return null}),n.onLoad({filter:/.*/,namespace:`server-action-reference`},e=>{let n=this.options.alias||{},r=e.path;for(let[i,a]of Object.entries(n))if(e.path.startsWith(`${i}/`)||e.path===i){let n=e.path.slice(i.length),o=t.isAbsolute(a)?t.join(a,n):t.resolve(this.projectRoot,a,n);r=t.relative(this.projectRoot,o);break}return{contents:`export * from "./${r}";`,loader:`js`,resolveDir:this.projectRoot}})}},{name:`use-transformed-server-components`,setup:n=>{if(!u)return;let r=this,i=r.options.alias||{};n.onResolve({filter:/^file:\/\//},t=>{let n=t.path.replace(/^file:\/\//,``);return e.existsSync(n)?{path:n,namespace:`transformed-server-component`}:null}),n.onResolve({filter:/.*/},n=>{let a=null;for(let[e,r]of Object.entries(i))if(n.path.startsWith(`${e}/`)||n.path===e){let i=n.path.slice(e.length),o=t.join(r,i);a=t.isAbsolute(o)?o:t.resolve(n.resolveDir,o);break}if(!a&&(n.path.startsWith(`./`)||n.path.startsWith(`../`))&&(a=t.resolve(n.resolveDir,n.path)),!a||n.resolveDir.includes(`node_modules`))return null;for(let n of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=a+n;if(e.existsSync(i)&&e.statSync(i).isFile()){if(r.isClientComponent(i))return null;let n=t.join(r.projectRoot,`src`);if(!i.startsWith(n))return null;let a=t.relative(n,i),o=t.join(r.projectRoot,`dist`,`server`,a.replace(/\.(tsx?|jsx?)$/,`.js`));if(e.existsSync(o))return{path:o,namespace:`transformed-server-component`};break}}return null}),n.onLoad({filter:/.*/,namespace:`transformed-server-component`},n=>({contents:e.readFileSync(n.path,`utf-8`),loader:`js`,resolveDir:t.dirname(n.path)}))}},{name:`resolve-aliases`,setup:n=>{let r=this,i=this.options.alias||{};for(let[a,o]of Object.entries(i)){let i=a.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),s=RegExp(`^${i}(/|$)`);n.onResolve({filter:s},n=>{let i=n.path.slice(a.length),s=t.join(o,i),c=t.isAbsolute(s)?s:t.resolve(n.resolveDir,s);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=c+t;if(e.existsSync(i)&&e.statSync(i).isFile()){if(r.isClientComponent(i))return{path:n.path,namespace:`client-component-reference`};try{let t=e.readFileSync(i,`utf-8`);if(t.includes(`'use server'`)||t.includes(`"use server"`))return{path:n.path,external:!0}}catch{}return{path:i}}}return{path:c}})}n.onLoad({filter:/.*/,namespace:`client-component-reference`},e=>{let n=e.path;for(let[a,o]of Object.entries(i))if(e.path.startsWith(`${a}/`)||e.path===a){let i=e.path.slice(a.length),s=t.isAbsolute(o)?t.join(o,i):t.resolve(r.projectRoot,o,i);n=t.relative(r.projectRoot,s);break}return{contents:`
41
+ }`;i.push({original:n,replacement:p})}}}let a=n;for(let{original:e,replacement:t}of i)a=a.replace(e,t);return a}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}async buildComponentCodeOnly(n,a,o){let s=await e.promises.readFile(n,`utf-8`),c=this.transformClientImports(s,n),l=this.isPageComponent(n)?this.transformComponentImportsToGlobal(c):c,u=t.extname(n),d;d=u===`.tsx`?`tsx`:u===`.ts`?`ts`:u===`.jsx`?`jsx`:`js`;try{let a=await r({stdin:{contents:l,resolveDir:t.dirname(n),sourcefile:n,loader:d},bundle:!0,platform:`node`,target:`es2022`,format:`esm`,mainFields:[`module`,`main`],conditions:[`import`,`module`,`default`],jsx:`transform`,jsxFactory:`React.createElement`,jsxFragment:`React.Fragment`,define:{global:`globalThis`,"process.env.NODE_ENV":`"production"`,...this.options.define},loader:{".ts":`ts`,".tsx":`tsx`,".js":`js`,".jsx":`jsx`},resolveExtensions:[`.ts`,`.tsx`,`.js`,`.jsx`],minify:!1,minifyWhitespace:!0,minifyIdentifiers:!0,minifySyntax:!0,sourcemap:!1,metafile:!1,write:!1,plugins:[{name:`resolve-aliases`,setup:n=>{let r=this,i=this.options.alias||{};for(let[a,o]of Object.entries(i)){let i=a.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),s=RegExp(`^${i}(/|$)`);n.onResolve({filter:s},n=>{let i=n.path.slice(a.length),s=t.join(o,i),c=t.isAbsolute(s)?s:t.resolve(n.resolveDir,s);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=c+t;if(e.existsSync(i)&&e.statSync(i).isFile()){if(r.isClientComponent(i))return{path:n.path,external:!0};try{let t=e.readFileSync(i,`utf-8`);if(t.includes(`'use server'`)||t.includes(`"use server"`))return{path:n.path,external:!0}}catch{}return{path:i}}}return{path:c}})}}},{name:`replace-react-imports`,setup(e){e.onLoad({filter:/runtime-client.*\.js$/},async e=>{let t=await(await import(`node:fs/promises`)).readFile(e.path,`utf-8`);return t=t.replace(/import\s+React\d*(?:\s*,\s*\{[^}]*\})?\s+from\s+['"]react['"];?/g,`// React is available as globalThis.React`),t=t.replace(/React2/g,`React`),{contents:t,loader:`js`}})}},{name:`hmr-auto-external`,setup:n=>{let r=this;n.onResolve({filter:/.*/},async n=>{if(n.path.includes(`../components/`)||n.path.includes(`./components/`)){let i=t.resolve(n.resolveDir,n.path);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let a=i+t;if(e.existsSync(a)&&e.statSync(a).isFile()&&r.isClientComponent(a))return{path:n.path,namespace:`component-stub`}}}if(n.path===`react`||n.path===`react-dom`||n.path===`react/jsx-runtime`||n.path===`react/jsx-dev-runtime`||n.path.startsWith(`node:`)||i(n.path)||n.path===`rari/image`||n.path.startsWith(`rari/image/`))return{path:n.path,external:!0};if(n.path===`rari/client`)return null;if(n.path.startsWith(`@/actions/`)||n.path.includes(`/actions/`)){let r=t.resolve(n.resolveDir,n.path);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=r+t;if(e.existsSync(i)){try{let t=e.readFileSync(i,`utf-8`);if(t.includes(`'use server'`)||t.includes(`"use server"`))return{path:n.path,external:!0}}catch{}break}}}return null}),n.onLoad({filter:/.*/,namespace:`component-stub`},async e=>{let t=e.path.match(/\/components\/(\w+)/);return{contents:`// Component stub for ${t?t[1]:`Unknown`} - replaced by global reference`,loader:`js`}})}},{name:`resolve-server-functions`,setup(n){n.onResolve({filter:/^\.\.?\/.*(functions|actions)/},async n=>{let r=t.resolve(t.dirname(n.importer),n.path);for(let t of[`.ts`,`.js`,`.tsx`,`.jsx`,`/index.ts`,`/index.js`]){let n=r+t;if(e.existsSync(n))return{path:n}}return null})}}]});if(a.outputFiles&&a.outputFiles.length>0)return a.outputFiles[0].text;throw a.errors.length>0?(console.error(`[rari] Build: ESBuild errors:`,a.errors),Error(`ESBuild compilation failed with ${a.errors.length} errors`)):Error(`No output generated from ESBuild`)}catch(e){throw console.error(`[rari] Build: ESBuild failed for ${n}:`,e),e}}async buildServerComponents(){let n=t.join(this.options.outDir,this.options.serverDir);await e.promises.mkdir(n,{recursive:!0});let r={react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`},i=this.options.alias||{};for(let[e,n]of Object.entries(i)){let i=t.isAbsolute(n)?n:t.resolve(this.projectRoot,n);r[`${e}/`]=`file://${i}/`}let a={components:{},importMap:{imports:r},version:`1.0.0`,buildTime:new Date().toISOString(),csp:this.options.csp,rateLimit:this.options.rateLimit,spamBlocker:this.options.spamBlocker};for(let[n,r]of this.serverComponents){if(this.isPageComponent(n))continue;let i=t.relative(this.projectRoot,n),o=this.getComponentId(i),s=t.join(this.options.serverDir,`${o}.js`),c=t.join(this.options.outDir,s),l=t.dirname(c);await e.promises.mkdir(l,{recursive:!0}),await this.buildSingleComponent(n,c,r);let u=`file://${t.resolve(this.projectRoot,c)}`;a.components[o]={id:o,filePath:n,relativePath:i,bundlePath:s,moduleSpecifier:u,dependencies:r.dependencies,hasNodeImports:r.hasNodeImports}}for(let[n,r]of this.serverComponents){if(!this.isPageComponent(n))continue;let i=t.relative(this.projectRoot,n),o=this.getComponentId(i),s=t.join(this.options.serverDir,`${o}.js`),c=t.join(this.options.outDir,s),l=t.dirname(c);await e.promises.mkdir(l,{recursive:!0}),await this.buildSingleComponent(n,c,r);let u=`file://${t.resolve(this.projectRoot,c)}`;a.components[o]={id:o,filePath:n,relativePath:i,bundlePath:s,moduleSpecifier:u,dependencies:r.dependencies,hasNodeImports:r.hasNodeImports}}for(let[n,r]of this.serverActions){let i=t.relative(this.projectRoot,n),o=this.getComponentId(i),s=t.join(this.options.serverDir,`${o}.js`),c=t.join(this.options.outDir,s),l=t.dirname(c);await e.promises.mkdir(l,{recursive:!0}),await this.buildSingleComponent(n,c,r);let u=`file://${t.resolve(this.projectRoot,c)}`;a.components[o]={id:o,filePath:n,relativePath:i,bundlePath:s,moduleSpecifier:u,dependencies:r.dependencies,hasNodeImports:r.hasNodeImports}}let o=t.join(this.options.outDir,this.options.manifestPath);return await e.promises.writeFile(o,JSON.stringify(a,null,2),`utf-8`),a}async buildSingleComponent(n,a,o,s=!1){let c=await e.promises.readFile(n,`utf-8`),l=this.transformClientImports(c,n),u=this.isPageComponent(n),d=u?this.transformComponentImportsToGlobal(l):l,f=t.extname(n),p;p=f===`.tsx`?`tsx`:f===`.ts`?`ts`:f===`.jsx`?`jsx`:`js`;try{let o=await r({stdin:{contents:d,resolveDir:t.dirname(n),sourcefile:n,loader:p},bundle:!0,platform:`node`,target:`es2022`,format:`esm`,outfile:a,mainFields:[`module`,`main`],conditions:[`import`,`module`,`default`],jsx:`transform`,jsxFactory:`React.createElement`,jsxFragment:`React.Fragment`,define:{global:`globalThis`,"process.env.NODE_ENV":`"production"`,...this.options.define},loader:{".ts":`ts`,".tsx":`tsx`,".js":`js`,".jsx":`jsx`},resolveExtensions:[`.ts`,`.tsx`,`.js`,`.jsx`],minify:this.options.minify,minifyWhitespace:this.options.minify,minifyIdentifiers:this.options.minify,minifySyntax:this.options.minify,sourcemap:!1,metafile:!1,write:!1,plugins:[{name:`resolve-client-server-boundaries`,setup:n=>{n.onResolve({filter:/.*/},async n=>{if(n.namespace!==`file`&&n.namespace!==``||n.path.startsWith(`node:`)||i(n.path)||n.path===`react`||n.path===`react-dom`||n.path===`react/jsx-runtime`||n.path===`react/jsx-dev-runtime`||n.resolveDir.includes(`node_modules`)||n.resolveDir.includes(`/packages/rari/dist`))return null;let r=null,a=this.options.alias||{};for(let[e,i]of Object.entries(a))if(n.path.startsWith(`${e}/`)||n.path===e){let a=n.path.slice(e.length),o=t.join(i,a);r=t.isAbsolute(o)?o:t.resolve(n.resolveDir,o);break}if(!r&&(n.path.startsWith(`./`)||n.path.startsWith(`../`))&&(r=t.resolve(n.resolveDir,n.path)),r)for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let n=r+t;if(e.existsSync(n)&&e.statSync(n).isFile()){if(this.isClientComponent(n))return{path:n,namespace:`client-component-reference`};try{let t=e.readFileSync(n,`utf-8`).split(`
42
+ `);for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`)return{path:n,namespace:`server-action-reference`};if(t)break}}}catch{}break}}return null}),n.onLoad({filter:/.*/,namespace:`server-action-reference`},e=>({contents:`export * from "./${t.relative(this.projectRoot,e.path)}";`,loader:`js`,resolveDir:this.projectRoot})),n.onLoad({filter:/.*/,namespace:`client-component-reference`},e=>{let n=t.relative(this.projectRoot,e.path);return{contents:`
43
+ function registerClientReference(clientReference, id, exportName) {
44
+ const key = id + '#' + exportName;
45
+ const clientProxy = {};
46
+ Object.defineProperty(clientProxy, '$$typeof', {
47
+ value: Symbol.for('react.client.reference'),
48
+ enumerable: false
49
+ });
50
+ Object.defineProperty(clientProxy, '$$id', {
51
+ value: key,
52
+ enumerable: false
53
+ });
54
+ Object.defineProperty(clientProxy, '$$async', {
55
+ value: false,
56
+ enumerable: false
57
+ });
58
+ try {
59
+ if (typeof globalThis['~rari']?.bridge !== 'undefined' &&
60
+ typeof globalThis['~rari'].bridge.registerClientReference === 'function') {
61
+ globalThis['~rari'].bridge.registerClientReference(key, id, exportName);
62
+ }
63
+ } catch (error) {
64
+ console.error('[rari] Build: Failed to register client reference:', error);
65
+ }
66
+ return clientProxy;
67
+ }
68
+
69
+ export default registerClientReference(null, ${JSON.stringify(n)}, "default");
70
+ `,loader:`js`}})}},{name:`use-transformed-server-components`,setup:n=>{if(!u)return;let r=this,i=r.options.alias||{};n.onResolve({filter:/^file:\/\//},t=>{let n=t.path.replace(/^file:\/\//,``);return e.existsSync(n)?{path:n,namespace:`transformed-server-component`}:null}),n.onResolve({filter:/.*/},n=>{let a=null;for(let[e,r]of Object.entries(i))if(n.path.startsWith(`${e}/`)||n.path===e){let i=n.path.slice(e.length),o=t.join(r,i);a=t.isAbsolute(o)?o:t.resolve(n.resolveDir,o);break}if(!a&&(n.path.startsWith(`./`)||n.path.startsWith(`../`))&&(a=t.resolve(n.resolveDir,n.path)),!a||n.resolveDir.includes(`node_modules`))return null;for(let n of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=a+n;if(e.existsSync(i)&&e.statSync(i).isFile()){if(r.isClientComponent(i))return null;let n=t.join(r.projectRoot,`src`);if(!i.startsWith(n))return null;let a=t.relative(n,i),o=t.join(r.projectRoot,`dist`,`server`,a.replace(/\.(tsx?|jsx?)$/,`.js`));if(e.existsSync(o))return{path:o,namespace:`transformed-server-component`};break}}return null}),n.onLoad({filter:/.*/,namespace:`transformed-server-component`},n=>({contents:e.readFileSync(n.path,`utf-8`),loader:`js`,resolveDir:t.dirname(n.path)}))}},{name:`resolve-aliases`,setup:n=>{let r=this,i=this.options.alias||{};for(let[a,o]of Object.entries(i)){let i=a.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),s=RegExp(`^${i}(/|$)`);n.onResolve({filter:s},n=>{let i=n.path.slice(a.length),s=t.join(o,i),c=t.isAbsolute(s)?s:t.resolve(n.resolveDir,s);for(let t of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let i=c+t;if(e.existsSync(i)&&e.statSync(i).isFile()){if(r.isClientComponent(i))return{path:n.path,namespace:`client-component-reference`};try{let t=e.readFileSync(i,`utf-8`);if(t.includes(`'use server'`)||t.includes(`"use server"`))return{path:n.path,external:!0}}catch{}return{path:i}}}return{path:c}})}n.onLoad({filter:/.*/,namespace:`client-component-reference`},e=>{let n=e.path;for(let[a,o]of Object.entries(i))if(e.path.startsWith(`${a}/`)||e.path===a){let i=e.path.slice(a.length),s=t.isAbsolute(o)?t.join(o,i):t.resolve(r.projectRoot,o,i);n=t.relative(r.projectRoot,s);break}return{contents:`
43
71
  function registerClientReference(clientReference, id, exportName) {
44
72
  const key = id + '#' + exportName;
45
73
  const clientProxy = {};
@@ -1,4 +1,4 @@
1
- import{t as e}from"./chunk-TmZEKRxo.mjs";import{a as t,i as n,n as r,o as i,r as a,t as o}from"./constants-CD3aqqK8.mjs";import{n as s}from"./server-build-BTHZMYd8.mjs";import c,{promises as l}from"node:fs";import u from"node:path";import d from"node:process";import{Buffer as f}from"node:buffer";import{spawn as p}from"node:child_process";import{fileURLToPath as m}from"node:url";import{transformSync as h}from"esbuild";var g=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})}},_=class{cookies;constructor(){this.cookies=new Map}get(e){let t=this.cookies.get(e);if(t)return{name:t.name,value:t.value,path:t.options?.path}}getAll(){return Array.from(this.cookies.values()).map(e=>({name:e.name,value:e.value,path:e.options?.path}))}set(e,t,n){if(typeof e==`string`)this.cookies.set(e,{name:e,value:t,options:n});else{let{name:t,value:n,...r}=e;this.cookies.set(t,{name:t,value:n,options:r})}}delete(e){this.cookies.delete(e)}toSetCookieHeaders(){return Array.from(this.cookies.values()).map(e=>{let t=`${e.name}=${e.value}`;return e.options&&(e.options.path&&(t+=`; Path=${e.options.path}`),e.options.domain&&(t+=`; Domain=${e.options.domain}`),e.options.maxAge&&(t+=`; Max-Age=${e.options.maxAge}`),e.options.expires&&(t+=`; Expires=${e.options.expires.toUTCString()}`),e.options.httpOnly&&(t+=`; HttpOnly`),e.options.secure&&(t+=`; Secure`),e.options.sameSite&&(t+=`; SameSite=${e.options.sameSite}`)),t})}},v=class e extends Response{cookies;constructor(e,t){super(e,t),this.cookies=new _}static next(t){let n=new e(null,{status:200,headers:{"x-rari-proxy-continue":`true`}});return t?.request?.headers&&(t.request.headers instanceof Headers?t.request.headers:new Headers(t.request.headers)).forEach((e,t)=>{n.headers.set(`x-rari-proxy-request-${t}`,e)}),n}static redirect(t,n){return new e(null,{status:n||307,headers:{Location:t.toString()}})}static rewrite(t){return new e(null,{status:200,headers:{"x-rari-proxy-rewrite":t.toString()}})}static json(t,n){return new e(JSON.stringify(t),{...n,headers:{"Content-Type":`application/json`,...n?.headers}})}};function y(e={}){let{root:t=d.cwd(),srcDir:n=`src`,proxyFileName:r=`proxy`,extensions:i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`],verbose:a=!1}=e,o=null,s=e=>{a&&console.warn(`[rari] Proxy: ${e}`)};async function c(){for(let e of i){let n=`${r}${e}`,i=u.join(t,n);try{return await l.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=u.join(t,n);try{await l.access(e);for(let t of i){let i=`${r}${t}`,a=u.join(e,i);try{return await l.access(a),s(`Found proxy file: ${u.join(n,i)}`),{filePath:a,exists:!0,relativePath:u.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 b={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function x(e){switch(u.basename(e).replace(/\.(tsx?|jsx?)$/,``)){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 S(e,t){let n=u.relative(t,u.dirname(e));return!n||n===`.`?`/`:`/${n.replace(/\\/g,`/`).split(`/`).filter(Boolean).join(`/`)}`}function C(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 w(e){try{let t=e.match(/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/);if(!t)return null;let n=t[1],r={},i=n.match(/title\s*:\s*['"]([^'"]+)['"]/);i&&(r.title=i[1]);let a=n.match(/description\s*:\s*['"]([^'"]+)['"]/);a&&(r.description=a[1]);let o=n.match(/keywords\s*:\s*\[([\s\S]*?)\]/);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(/['"]/g,``)).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 T(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 E(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 D(e={}){let t={...b,...e},n=null,r=new Map,i=null,a=new Set,o=e=>Array.from(e).sort().join(`|`),s=async e=>{let n=new Set,r=async e=>{try{let i=await l.readdir(e,{withFileTypes:!0});for(let a of i){let i=u.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&x(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=u.resolve(e,t.appDir);try{await l.access(c)}catch{return null}try{let d=await s(c),f=o(d);if(!r&&i===f&&n)return n;let{generateAppRouteManifest:p}=await import(`./routes-VWQ7KgNh.mjs`),m=await p(c,{extensions:t.extensions}),h=JSON.stringify(m,null,2),g=u.resolve(e,t.outDir);await l.mkdir(g,{recursive:!0});let _=u.join(g,`server`);return await l.mkdir(_,{recursive:!0}),await l.writeFile(u.join(_,`routes.json`),h,`utf-8`),i=f,a.clear(),d.forEach(e=>a.add(e)),h}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},f=e=>{let n=u.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=x(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)}})},p;return{name:`rari-router`,configResolved(e){p=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(p||d.cwd(),!0)},configureServer(e){f(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=u.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=x(i);if(e){let t=r.get(i);t&&clearTimeout(t);let d=setTimeout(async()=>{r.delete(i);let t=!a.has(i),d=n;n=await c(o.config.root,t);let f=d!==n,p=S(i,s),m=[p];if(n)try{m=JSON.parse(n).routes.map(e=>e.path)}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let h=C(p,e,m),g,_=!1,v;if(e===`page`||e===`layout`)try{let e=w(await l.readFile(i,`utf-8`));e&&(g=e,_=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{v=T(await l.readFile(i,`utf-8`)),await E(u.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let y={fileType:e,filePath:u.relative(o.config.root,i),routePath:p,affectedRoutes:h,manifestUpdated:f,timestamp:Date.now(),metadata:g,metadataChanged:_,methods:v};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:y})},200);return r.set(i,d),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var O=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer&&=(clearTimeout(this.resetTimer),null)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.resetTimer&&=(clearTimeout(this.resetTimer),null),this.reset()}},k=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 O({maxErrors:5,resetTimeout:3e4})}async handleClientComponentUpdate(e,t){let n=u.relative(d.cwd(),e),r=Date.now();this.queueLog(`info`,`Client component changed: ${n}`);try{let i=t.moduleGraph.getModuleById(e);if(i){t.moduleGraph.invalidateModule(i);let e=Date.now()-r;this.queueLog(`success`,`Client component updated: ${n} (${e}ms)`),this.errorHandler.reset()}else this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=Array.from(this.pendingFiles);if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=Date.now();if(e.length===1){let t=u.relative(d.cwd(),e[0]);this.queueLog(`info`,`Rebuilding server component: ${t}`)}else this.queueLog(`info`,`Rebuilding ${e.length} server components in batch`);let r=await Promise.allSettled(e.map(async e=>{let t=u.relative(d.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),i=[],a=[];r.forEach(e=>{e.status===`fulfilled`&&e.value.success?i.push(e.value):e.status===`fulfilled`&&!e.value.success?a.push(e.value):e.status===`rejected`&&a.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})});let o=Date.now()-n;if(i.length>0){let e=Date.now();i.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),i.length===1?this.queueLog(`success`,`Server component updated: ${i[0].relativePath} (${o}ms)`):this.queueLog(`success`,`${i.length} server components updated (${o}ms)`),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(a.length>0){let e=Date.now();a.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});if(!n.ok){let e=await n.text();throw Error(`HTTP ${n.status}: ${e}`)}}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}detectComponentType(e){try{let t=c.readFileSync(e,`utf-8`).split(`
1
+ import{t as e}from"./chunk-TmZEKRxo.mjs";import{a as t,i as n,n as r,o as i,r as a,t as o}from"./constants-CD3aqqK8.mjs";import{n as s}from"./server-build-CQpOd0dQ.mjs";import c,{promises as l}from"node:fs";import u from"node:path";import d from"node:process";import{Buffer as f}from"node:buffer";import{spawn as p}from"node:child_process";import{fileURLToPath as m}from"node:url";import{transformSync as h}from"esbuild";var g=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})}},_=class{cookies;constructor(){this.cookies=new Map}get(e){let t=this.cookies.get(e);if(t)return{name:t.name,value:t.value,path:t.options?.path}}getAll(){return Array.from(this.cookies.values()).map(e=>({name:e.name,value:e.value,path:e.options?.path}))}set(e,t,n){if(typeof e==`string`)this.cookies.set(e,{name:e,value:t,options:n});else{let{name:t,value:n,...r}=e;this.cookies.set(t,{name:t,value:n,options:r})}}delete(e){this.cookies.delete(e)}toSetCookieHeaders(){return Array.from(this.cookies.values()).map(e=>{let t=`${e.name}=${e.value}`;return e.options&&(e.options.path&&(t+=`; Path=${e.options.path}`),e.options.domain&&(t+=`; Domain=${e.options.domain}`),e.options.maxAge&&(t+=`; Max-Age=${e.options.maxAge}`),e.options.expires&&(t+=`; Expires=${e.options.expires.toUTCString()}`),e.options.httpOnly&&(t+=`; HttpOnly`),e.options.secure&&(t+=`; Secure`),e.options.sameSite&&(t+=`; SameSite=${e.options.sameSite}`)),t})}},v=class e extends Response{cookies;constructor(e,t){super(e,t),this.cookies=new _}static next(t){let n=new e(null,{status:200,headers:{"x-rari-proxy-continue":`true`}});return t?.request?.headers&&(t.request.headers instanceof Headers?t.request.headers:new Headers(t.request.headers)).forEach((e,t)=>{n.headers.set(`x-rari-proxy-request-${t}`,e)}),n}static redirect(t,n){return new e(null,{status:n||307,headers:{Location:t.toString()}})}static rewrite(t){return new e(null,{status:200,headers:{"x-rari-proxy-rewrite":t.toString()}})}static json(t,n){return new e(JSON.stringify(t),{...n,headers:{"Content-Type":`application/json`,...n?.headers}})}};function y(e={}){let{root:t=d.cwd(),srcDir:n=`src`,proxyFileName:r=`proxy`,extensions:i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`],verbose:a=!1}=e,o=null,s=e=>{a&&console.warn(`[rari] Proxy: ${e}`)};async function c(){for(let e of i){let n=`${r}${e}`,i=u.join(t,n);try{return await l.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=u.join(t,n);try{await l.access(e);for(let t of i){let i=`${r}${t}`,a=u.join(e,i);try{return await l.access(a),s(`Found proxy file: ${u.join(n,i)}`),{filePath:a,exists:!0,relativePath:u.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 b={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function x(e){switch(u.basename(e).replace(/\.(tsx?|jsx?)$/,``)){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 S(e,t){let n=u.relative(t,u.dirname(e));return!n||n===`.`?`/`:`/${n.replace(/\\/g,`/`).split(`/`).filter(Boolean).join(`/`)}`}function C(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 w(e){try{let t=e.match(/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/);if(!t)return null;let n=t[1],r={},i=n.match(/title\s*:\s*['"]([^'"]+)['"]/);i&&(r.title=i[1]);let a=n.match(/description\s*:\s*['"]([^'"]+)['"]/);a&&(r.description=a[1]);let o=n.match(/keywords\s*:\s*\[([\s\S]*?)\]/);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(/['"]/g,``)).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 T(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 E(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 D(e={}){let t={...b,...e},n=null,r=new Map,i=null,a=new Set,o=e=>Array.from(e).sort().join(`|`),s=async e=>{let n=new Set,r=async e=>{try{let i=await l.readdir(e,{withFileTypes:!0});for(let a of i){let i=u.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&x(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=u.resolve(e,t.appDir);try{await l.access(c)}catch{return null}try{let d=await s(c),f=o(d);if(!r&&i===f&&n)return n;let{generateAppRouteManifest:p}=await import(`./routes-VWQ7KgNh.mjs`),m=await p(c,{extensions:t.extensions}),h=JSON.stringify(m,null,2),g=u.resolve(e,t.outDir);await l.mkdir(g,{recursive:!0});let _=u.join(g,`server`);return await l.mkdir(_,{recursive:!0}),await l.writeFile(u.join(_,`routes.json`),h,`utf-8`),i=f,a.clear(),d.forEach(e=>a.add(e)),h}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},f=e=>{let n=u.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=x(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)}})},p;return{name:`rari-router`,configResolved(e){p=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(p||d.cwd(),!0)},configureServer(e){f(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=u.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=x(i);if(e){let t=r.get(i);t&&clearTimeout(t);let d=setTimeout(async()=>{r.delete(i);let t=!a.has(i),d=n;n=await c(o.config.root,t);let f=d!==n,p=S(i,s),m=[p];if(n)try{m=JSON.parse(n).routes.map(e=>e.path)}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let h=C(p,e,m),g,_=!1,v;if(e===`page`||e===`layout`)try{let e=w(await l.readFile(i,`utf-8`));e&&(g=e,_=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{v=T(await l.readFile(i,`utf-8`)),await E(u.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let y={fileType:e,filePath:u.relative(o.config.root,i),routePath:p,affectedRoutes:h,manifestUpdated:f,timestamp:Date.now(),metadata:g,metadataChanged:_,methods:v};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:y})},200);return r.set(i,d),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var O=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer&&clearTimeout(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer&&=(clearTimeout(this.resetTimer),null)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.resetTimer&&=(clearTimeout(this.resetTimer),null),this.reset()}},k=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 O({maxErrors:5,resetTimeout:3e4})}async handleClientComponentUpdate(e,t){let n=u.relative(d.cwd(),e),r=Date.now();this.queueLog(`info`,`Client component changed: ${n}`);try{let i=t.moduleGraph.getModuleById(e);if(i){t.moduleGraph.invalidateModule(i);let e=Date.now()-r;this.queueLog(`success`,`Client component updated: ${n} (${e}ms)`),this.errorHandler.reset()}else this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{let e=Array.from(this.pendingFiles);if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=Date.now();if(e.length===1){let t=u.relative(d.cwd(),e[0]);this.queueLog(`info`,`Rebuilding server component: ${t}`)}else this.queueLog(`info`,`Rebuilding ${e.length} server components in batch`);let r=await Promise.allSettled(e.map(async e=>{let t=u.relative(d.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error||`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),i=[],a=[];r.forEach(e=>{e.status===`fulfilled`&&e.value.success?i.push(e.value):e.status===`fulfilled`&&!e.value.success?a.push(e.value):e.status===`rejected`&&a.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})});let o=Date.now()-n;if(i.length>0){let e=Date.now();i.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),i.length===1?this.queueLog(`success`,`Server component updated: ${i[0].relativePath} (${o}ms)`):this.queueLog(`success`,`${i.length} server components updated (${o}ms)`),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(a.length>0){let e=Date.now();a.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack||``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}},this.DEBOUNCE_DELAY)}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});if(!n.ok){let e=await n.text();throw Error(`HTTP ${n.status}: ${e}`)}}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}detectComponentType(e){try{let t=c.readFileSync(e,`utf-8`).split(`
2
2
  `);for(let e of t){let t=e.trim();if(!(!t||t.startsWith(`//`)||t.startsWith(`/*`))){if(t===`'use client'`||t===`"use client"`)return`client`;break}}return`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
3
3
  • `);this.outputLog(t,`${n.length} updates:\n • ${e}`)}this.logBatch=[],this.logBatchTimer=null}outputLog(e,t){let n=`[rari] HMR:`;switch(e){case`success`:console.warn(`\x1B[32m${n}\x1B[0m ${t}`);break;case`warning`:console.warn(`\x1B[33m${n}\x1B[0m ${t}`);break;case`error`:console.error(`\x1B[31m${n}\x1B[0m ${t}`);break;default:console.warn(`${n} ${t}`);break}}dispose(){this.logBatchTimer&&(clearTimeout(this.logBatchTimer),this.flushLogs()),this.batchTimer&&=(clearTimeout(this.batchTimer),null);for(let e of this.pendingUpdates.values())clearTimeout(e);this.pendingUpdates.clear(),this.pendingFiles.clear(),this.errorHandler.dispose()}};const A={remotePatterns:[],localPatterns:[],deviceSizes:o,imageSizes:a,formats:r,quality:i,minimumCacheTTL:t,maxCacheSize:n};async function j(e){let t=import.meta.url,n=m(t),r=u.dirname(n),i=[u.join(r,`../runtime`,e),u.join(r,`../src/runtime`,e)];for(let e of i)try{return await c.promises.readFile(e,`utf-8`)}catch{}throw Error(`Could not find ${e}. Tried: ${i.join(`, `)}`)}async function M(){return j(`rsc-client-runtime.js`)}async function N(e,t){return(await j(`entry-client.js`)).replace(`// CLIENT_COMPONENT_IMPORTS_PLACEHOLDER`,e).replace(`// CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER`,t)}async function P(){return j(`react-server-dom-shim.js`)}function F(e,t=[]){let n=new Set;function r(e){if(!c.existsSync(e))return;let t=c.readdirSync(e,{withFileTypes:!0});for(let i of t){let t=u.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;r(t)}else if(i.isFile()&&/\.(?:tsx?|jsx?)$/.test(i.name))try{let e=c.readFileSync(t,`utf8`);(e.includes(`'use client'`)||e.includes(`"use client"`))&&n.add(t)}catch{}}}r(e);for(let e of t)c.existsSync(e)&&r(e);return n}function I(e){return e}function L(t={}){let n=new Map,r=new Set,i=new Set,a=null,o=new Set,l=null,m={};function g(e){if(e.includes(`node_modules`)||e.includes(`/rari/dist/`)||e.includes(`\\rari\\dist\\`))return!1;let t=e;try{t=c.realpathSync(e)}catch{return!1}try{if(!c.existsSync(t))return!1;let e=c.readFileSync(t,`utf-8`),n=v(e,`use client`);return v(e,`use server`)?!1:!n}catch{return!1}}function _(e){try{let t=h(e,{loader:`tsx`,format:`esm`,target:`esnext`,logLevel:`silent`}).code.match(/export\s*\{([^}]+)\}/);if(!t){let t=e.match(/export\s*\{([^}]+)\}/);if(t){let e=[],n=t[1].split(`,`);for(let t of n){let n=t.trim().split(/\s+as\s+/),r=n[n.length-1].trim();r&&e.push(r)}return e}return[]}let n=[],r=t[1].split(`,`);for(let e of r){let t=e.trim().split(/\s+as\s+/),r=t[t.length-1].trim();r&&n.push(r)}return n}catch{return[]}}function v(e,t){try{let n=h(e,{loader:`tsx`,format:`esm`,target:`esnext`,logLevel:`silent`}).code.trimStart();return RegExp(`^(['"\`])${t.replace(/\s/g,`\\s+`)}\\1\\s*;?`).test(n)}catch{return!1}}function b(e,t){if(!v(e,`use server`))return e;let n=_(e);if(n.length===0)return e;let r=e;r+=`
4
4
 
@@ -41,7 +41,7 @@ const ${t} = registerClientReference(
41
41
  );`;u=u.replace(e,n),f=!0,p=!0}}else if(!S&&g(x)){f=!0,p=!0,m=!0,r.add(x);let e=s;d&&d!==`_`&&h.push(`const ${d} = createServerComponentWrapper('${b}', '${y}');`),u=u.replace(e,``)}}if(f){let e=u.includes(`import React`)||u.match(/import\s+\{[^}]*\}\s+from\s+['"]react['"]/)||u.match(/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/),r=u.includes(`createServerComponentWrapper`),i=``;if(p&&!e&&(i+=`import React from 'react';
42
42
  `),m&&!r&&(i+=`import { createServerComponentWrapper } from 'virtual:rsc-integration';
43
43
  `),h.length>0&&(i+=`${h.join(`
44
- `)}\n`),i&&(u=i+u),!u.includes(`Suspense`)){let e=u.match(/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/);e&&(e[1]&&!e[2].includes(`Suspense`)?u=u.replace(e[0],e[0].replace(/\{([^}]*)\}/,`{ Suspense, $1 }`)):e[1]||(u=u.replace(e[0],`import React, { Suspense } from 'react';`)))}let a=d.env.NODE_ENV!==`production`,o=u.includes(`</`)||u.includes(`/>`)||/\bJSX\b/.test(u);return!u.includes(`'use client'`)&&!u.includes(`"use client"`)&&o&&a&&(u=`'use client';\n\n${u}`,n.set(t,`client`)),u}return null},configureServer(e){let r=t.projectRoot||d.cwd(),i=u.join(r,`src`),o={...A,...t.images},s=u.join(r,`dist`),h=u.join(s,`server`);c.existsSync(h)||c.mkdirSync(h,{recursive:!0});let _=u.join(h,`image.json`);c.writeFileSync(_,JSON.stringify(o,null,2));let v=null,y=async()=>{try{let{ServerComponentBuilder:n,scanDirectory:i}=await import(`./server-build-k25VDgDe.mjs`),a=new n(r,{outDir:`dist`,serverDir:`server`,manifestPath:`server/manifest.json`,alias:m,csp:t.csp,rateLimit:t.rateLimit,spamBlocker:t.spamBlocker});if(v=a,!l&&v){let e=d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3);l=new k(v,e)}let o=u.join(r,`src`),s=[];if(c.existsSync(o)){let e=t=>{let n=c.readdirSync(t,{withFileTypes:!0});for(let r of n){let n=u.join(t,r.name);if(r.isDirectory())e(n);else if(r.isFile()&&/\.(?:tsx?|jsx?)$/.test(r.name))try{g(n)&&s.push(n)}catch(e){console.error(`[rari] Error checking ${n}:`,e)}}};e(o),i(o,a)}s.length>0&&e.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:s}});let f=await a.getTransformedComponentsForDevelopment(),p=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`;for(let e of f)try{if(e.id.startsWith(`app/`)||e.code.includes(`"use server"`)||e.code.includes(`'use server'`))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))}},b=async()=>{try{let e=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`,t=F(i,Object.values(m));for(let n of t){let t=u.relative(d.cwd(),n),r=u.basename(n).replace(/\.[^.]+$/,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:t,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${r}:`,e)}}}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},x=async()=>{if(a)return;let{getBinaryPath:t,getInstallationInstructions:n}=await import(`./platform.mjs`),r;try{r=t()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(n());return}let i=d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3),o=d.env.NODE_ENV===`production`?`production`:`development`,s=e.config.server.port||5173,c=[`--mode`,o,`--port`,i.toString(),`--host`,`127.0.0.1`];a=p(r,c,{stdio:[`ignore`,`pipe`,`pipe`],cwd:d.cwd(),env:{...d.env,RUST_LOG:d.env.RUST_LOG||`error`,RARI_VITE_PORT:s.toString()}}),a.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),a.on(`error`,e=>{console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),a.on(`exit`,(e,t)=>{a=null,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}`)}),setTimeout(async()=>{try{let e=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`,t=!1;for(let n=0;n<10;n++)try{if((await fetch(`${e}/_rari/health`)).ok){t=!0;break}}catch{await new Promise(e=>setTimeout(e,500))}t?(await b(),await y()):console.error(`Server failed to become ready for component registration`)}catch(e){console.error(`Failed during component registration:`,e)}},1e3)},S=async e=>{try{if(!g(e))return;let{ServerComponentBuilder:n}=await import(`./server-build-k25VDgDe.mjs`),i=new n(r,{outDir:`dist`,serverDir:`server`,manifestPath:`server/manifest.json`,alias:m,csp:t.csp,rateLimit:t.rateLimit,spamBlocker:t.spamBlocker});i.addServerComponent(e);let a=await i.getTransformedComponentsForDevelopment();if(a.length===0)return;let o=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`;for(let e of a)try{let t=await fetch(`${o}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}catch(t){console.error(`[rari] Targeted HMR failed for`,`${e}:`,t instanceof Error?t.message:String(t)),setTimeout(y,1e3)}};x(),e.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(`.`)){let n=d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3),r=`http://localhost:${n}${e.url}`;try{let i={};for(let[t,n]of Object.entries(e.headers))n&&typeof n==`string`&&(i[t]=n);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(f.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()}),e.watcher.on(`change`,async t=>{/\.(?:tsx?|jsx?)$/.test(t)&&n.delete(t),/\.(?:tsx?|jsx?)$/.test(t)&&t.includes(i)&&(g(t)?(e.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:t}}),await S(t)):setTimeout(y,1e3))}),e.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 S(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)}))}})}),e.httpServer?.on(`close`,()=>{l&&=(l.dispose(),null),a&&=(a.kill(`SIGTERM`),null)})},resolveId(e){if(e===`virtual:rsc-integration`||e===`virtual:rari-entry-client`||e===`virtual:react-server-dom-rari-client`)return e;if(e===`virtual:app-router-provider`)return`${e}.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===`../router/LoadingComponentRegistry`||e===`../router/LoadingComponentRegistry.ts`)return`virtual:loading-component-registry.ts`;if(e===`react-server-dom-rari/server`)return e;if(d.env.NODE_ENV===`production`)try{let t=u.resolve(e);if(c.existsSync(t)&&g(t))return{id:e,external:!0}}catch{}return null},async load(e){if(e===`virtual:rari-entry-client`){let e=F(u.join(d.cwd(),`src`),Object.values(m)),t=new Set([...i,...e]),n=[{path:`rari/image`,exports:[`Image`]}],r=Array.from(t).filter(e=>{try{let t=c.readFileSync(e,`utf-8`).split(`
44
+ `)}\n`),i&&(u=i+u),!u.includes(`Suspense`)){let e=u.match(/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/);e&&(e[1]&&!e[2].includes(`Suspense`)?u=u.replace(e[0],e[0].replace(/\{([^}]*)\}/,`{ Suspense, $1 }`)):e[1]||(u=u.replace(e[0],`import React, { Suspense } from 'react';`)))}let a=d.env.NODE_ENV!==`production`,o=u.includes(`</`)||u.includes(`/>`)||/\bJSX\b/.test(u);return!u.includes(`'use client'`)&&!u.includes(`"use client"`)&&o&&a&&(u=`'use client';\n\n${u}`,n.set(t,`client`)),u}return null},configureServer(e){let r=t.projectRoot||d.cwd(),i=u.join(r,`src`),o={...A,...t.images},s=u.join(r,`dist`),h=u.join(s,`server`);c.existsSync(h)||c.mkdirSync(h,{recursive:!0});let _=u.join(h,`image.json`);c.writeFileSync(_,JSON.stringify(o,null,2));let v=null,y=async()=>{try{let{ServerComponentBuilder:n,scanDirectory:i}=await import(`./server-build-BwFXhFbR.mjs`),a=new n(r,{outDir:`dist`,serverDir:`server`,manifestPath:`server/manifest.json`,alias:m,csp:t.csp,rateLimit:t.rateLimit,spamBlocker:t.spamBlocker});if(v=a,!l&&v){let e=d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3);l=new k(v,e)}let o=u.join(r,`src`),s=[];if(c.existsSync(o)){let e=t=>{let n=c.readdirSync(t,{withFileTypes:!0});for(let r of n){let n=u.join(t,r.name);if(r.isDirectory())e(n);else if(r.isFile()&&/\.(?:tsx?|jsx?)$/.test(r.name))try{g(n)&&s.push(n)}catch(e){console.error(`[rari] Error checking ${n}:`,e)}}};e(o),i(o,a)}s.length>0&&e.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:s}});let f=await a.getTransformedComponentsForDevelopment(),p=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`;for(let e of f)try{if(e.id.startsWith(`app/`)||e.code.includes(`"use server"`)||e.code.includes(`'use server'`))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))}},b=async()=>{try{let e=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`,t=F(i,Object.values(m));for(let n of t){let t=u.relative(d.cwd(),n),r=u.basename(n).replace(/\.[^.]+$/,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:t,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${r}:`,e)}}}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},x=async()=>{if(a)return;let{getBinaryPath:t,getInstallationInstructions:n}=await import(`./platform.mjs`),r;try{r=t()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(n());return}let i=d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3),o=d.env.NODE_ENV===`production`?`production`:`development`,s=e.config.server.port||5173,c=[`--mode`,o,`--port`,i.toString(),`--host`,`127.0.0.1`];a=p(r,c,{stdio:[`ignore`,`pipe`,`pipe`],cwd:d.cwd(),env:{...d.env,RUST_LOG:d.env.RUST_LOG||`error`,RARI_VITE_PORT:s.toString()}}),a.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),a.on(`error`,e=>{console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),a.on(`exit`,(e,t)=>{a=null,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}`)}),setTimeout(async()=>{try{let e=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`,t=!1;for(let n=0;n<10;n++)try{if((await fetch(`${e}/_rari/health`)).ok){t=!0;break}}catch{await new Promise(e=>setTimeout(e,500))}t?(await b(),await y()):console.error(`Server failed to become ready for component registration`)}catch(e){console.error(`Failed during component registration:`,e)}},1e3)},S=async e=>{try{if(!g(e))return;let{ServerComponentBuilder:n}=await import(`./server-build-BwFXhFbR.mjs`),i=new n(r,{outDir:`dist`,serverDir:`server`,manifestPath:`server/manifest.json`,alias:m,csp:t.csp,rateLimit:t.rateLimit,spamBlocker:t.spamBlocker});i.addServerComponent(e);let a=await i.getTransformedComponentsForDevelopment();if(a.length===0)return;let o=`http://localhost:${d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3)}`;for(let e of a)try{let t=await fetch(`${o}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}catch(t){console.error(`[rari] Targeted HMR failed for`,`${e}:`,t instanceof Error?t.message:String(t)),setTimeout(y,1e3)}};x(),e.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(`.`)){let n=d.env.SERVER_PORT?Number(d.env.SERVER_PORT):Number(d.env.PORT||d.env.RSC_PORT||3e3),r=`http://localhost:${n}${e.url}`;try{let i={};for(let[t,n]of Object.entries(e.headers))n&&typeof n==`string`&&(i[t]=n);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(f.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()}),e.watcher.on(`change`,async t=>{/\.(?:tsx?|jsx?)$/.test(t)&&n.delete(t),/\.(?:tsx?|jsx?)$/.test(t)&&t.includes(i)&&(g(t)?(e.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:t}}),await S(t)):setTimeout(y,1e3))}),e.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 S(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)}))}})}),e.httpServer?.on(`close`,()=>{l&&=(l.dispose(),null),a&&=(a.kill(`SIGTERM`),null)})},resolveId(e){if(e===`virtual:rsc-integration`||e===`virtual:rari-entry-client`||e===`virtual:react-server-dom-rari-client`)return e;if(e===`virtual:app-router-provider`)return`${e}.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===`../router/LoadingComponentRegistry`||e===`../router/LoadingComponentRegistry.ts`)return`virtual:loading-component-registry.ts`;if(e===`react-server-dom-rari/server`)return e;if(d.env.NODE_ENV===`production`)try{let t=u.resolve(e);if(c.existsSync(t)&&g(t))return{id:e,external:!0}}catch{}return null},async load(e){if(e===`virtual:rari-entry-client`){let e=F(u.join(d.cwd(),`src`),Object.values(m)),t=new Set([...i,...e]),n=[{path:`rari/image`,exports:[`Image`]}],r=Array.from(t).filter(e=>{try{let t=c.readFileSync(e,`utf-8`).split(`
45
45
  `);for(let e of t){let t=e.trim();if(!(!t||t.startsWith(`//`)||t.startsWith(`/*`))){if(t===`'use client'`||t===`"use client"`||t===`'use client';`||t===`"use client";`)return!0;break}}return!1}catch{return!1}}),a=r.map((e,t)=>{let n=u.relative(d.cwd(),e),r=`ClientComponent${t}`;try{let t=c.readFileSync(e,`utf-8`),i=/export\s+default\s+/.test(t),a=t.match(/export\s+(?:function|const|class)\s+(\w+)/);if(!i&&a)return`import { ${a[1]} as ${r} } from '/${n}';`}catch{}return`import ${r} from '/${n}';`}).join(`
46
46
  `),o=r.map((e,t)=>{let n=u.relative(d.cwd(),e),r=`ClientComponent${t}`,i=u.basename(e,u.extname(e));return`
47
47
  globalThis['~clientComponents']["${n}"] = {
package/dist/vite.mjs CHANGED
@@ -1 +1 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./vite-D4TzV89n.mjs";import{t as s}from"./RariRequest-CW-JhbGM.mjs";import{c,d as l,f as u,g as d,h as f,i as p,m,p as h,u as g}from"./runtime-client-B15ZQXrE.mjs";import{t as _}from"./routes-Bq7zysPc.mjs";import"./constants-CD3aqqK8.mjs";import"./server-build-BTHZMYd8.mjs";export{a as ApiResponse,p as HttpRuntimeClient,s as RariRequest,r as RariResponse,g as clearPropsCache,l as clearPropsCacheForComponent,c as createHttpRuntimeClient,o as defineRariConfig,n as defineRariOptions,u as extractMetadata,h as extractServerProps,m as extractServerPropsWithCache,f as extractStaticParams,_ as generateAppRouteManifest,d as hasServerSideDataFetching,i as rari,e as rariProxy,t as rariRouter};
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./vite-BzhJ1Li7.mjs";import{t as s}from"./RariRequest-CW-JhbGM.mjs";import{c,d as l,f as u,g as d,h as f,i as p,m,p as h,u as g}from"./runtime-client-B15ZQXrE.mjs";import{t as _}from"./routes-Bq7zysPc.mjs";import"./constants-CD3aqqK8.mjs";import"./server-build-CQpOd0dQ.mjs";export{a as ApiResponse,p as HttpRuntimeClient,s as RariRequest,r as RariResponse,g as clearPropsCache,l as clearPropsCacheForComponent,c as createHttpRuntimeClient,o as defineRariConfig,n as defineRariOptions,u as extractMetadata,h as extractServerProps,m as extractServerPropsWithCache,f as extractStaticParams,_ as generateAppRouteManifest,d as hasServerSideDataFetching,i as rari,e as rariProxy,t as rariRouter};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rari",
3
3
  "type": "module",
4
- "version": "0.7.12",
4
+ "version": "0.7.14",
5
5
  "description": "Runtime Accelerated Rendering Infrastructure (rari)",
6
6
  "author": "Ryan Skinner",
7
7
  "license": "MIT",
@@ -952,7 +952,7 @@ const ${importName} = (props) => {
952
952
  write: false,
953
953
  plugins: [
954
954
  {
955
- name: 'external-server-actions',
955
+ name: 'resolve-client-server-boundaries',
956
956
  setup: (build) => {
957
957
  build.onResolve({ filter: /.*/ }, async (args) => {
958
958
  if (args.namespace !== 'file' && args.namespace !== '')
@@ -964,6 +964,9 @@ const ${importName} = (props) => {
964
964
  return null
965
965
  }
966
966
 
967
+ if (args.resolveDir.includes('node_modules') || args.resolveDir.includes('/packages/rari/dist'))
968
+ return null
969
+
967
970
  let resolvedPath: string | null = null
968
971
 
969
972
  const aliases = this.options.alias || {}
@@ -984,6 +987,13 @@ const ${importName} = (props) => {
984
987
  for (const ext of possibleExtensions) {
985
988
  const pathWithExt = resolvedPath + ext
986
989
  if (fs.existsSync(pathWithExt) && fs.statSync(pathWithExt).isFile()) {
990
+ if (this.isClientComponent(pathWithExt)) {
991
+ return {
992
+ path: pathWithExt,
993
+ namespace: 'client-component-reference',
994
+ }
995
+ }
996
+
987
997
  try {
988
998
  const content = fs.readFileSync(pathWithExt, 'utf-8')
989
999
  const lines = content.split('\n')
@@ -995,7 +1005,7 @@ const ${importName} = (props) => {
995
1005
  if (trimmed === '\'use server\'' || trimmed === '"use server"'
996
1006
  || trimmed === '\'use server\';' || trimmed === '"use server";') {
997
1007
  return {
998
- path: args.path,
1008
+ path: pathWithExt,
999
1009
  namespace: 'server-action-reference',
1000
1010
  }
1001
1011
  }
@@ -1012,27 +1022,52 @@ const ${importName} = (props) => {
1012
1022
  })
1013
1023
 
1014
1024
  build.onLoad({ filter: /.*/, namespace: 'server-action-reference' }, (args) => {
1015
- const aliases = this.options.alias || {}
1016
- let resolvedPath = args.path
1017
-
1018
- for (const [alias, replacement] of Object.entries(aliases)) {
1019
- if (args.path.startsWith(`${alias}/`) || args.path === alias) {
1020
- const relativePath = args.path.slice(alias.length)
1021
- const fullPath = path.isAbsolute(replacement)
1022
- ? path.join(replacement, relativePath)
1023
- : path.resolve(this.projectRoot, replacement, relativePath)
1025
+ const componentId = path.relative(this.projectRoot, args.path)
1026
+ const contents = `export * from "./${componentId}";`
1024
1027
 
1025
- resolvedPath = path.relative(this.projectRoot, fullPath)
1026
- break
1027
- }
1028
+ return {
1029
+ contents,
1030
+ loader: 'js',
1031
+ resolveDir: this.projectRoot,
1028
1032
  }
1033
+ })
1034
+
1035
+ build.onLoad({ filter: /.*/, namespace: 'client-component-reference' }, (args) => {
1036
+ const componentId = path.relative(this.projectRoot, args.path)
1037
+
1038
+ const contents = `
1039
+ function registerClientReference(clientReference, id, exportName) {
1040
+ const key = id + '#' + exportName;
1041
+ const clientProxy = {};
1042
+ Object.defineProperty(clientProxy, '$$typeof', {
1043
+ value: Symbol.for('react.client.reference'),
1044
+ enumerable: false
1045
+ });
1046
+ Object.defineProperty(clientProxy, '$$id', {
1047
+ value: key,
1048
+ enumerable: false
1049
+ });
1050
+ Object.defineProperty(clientProxy, '$$async', {
1051
+ value: false,
1052
+ enumerable: false
1053
+ });
1054
+ try {
1055
+ if (typeof globalThis['~rari']?.bridge !== 'undefined' &&
1056
+ typeof globalThis['~rari'].bridge.registerClientReference === 'function') {
1057
+ globalThis['~rari'].bridge.registerClientReference(key, id, exportName);
1058
+ }
1059
+ } catch (error) {
1060
+ console.error('[rari] Build: Failed to register client reference:', error);
1061
+ }
1062
+ return clientProxy;
1063
+ }
1029
1064
 
1030
- const contents = `export * from "./${resolvedPath}";`
1065
+ export default registerClientReference(null, ${JSON.stringify(componentId)}, "default");
1066
+ `
1031
1067
 
1032
1068
  return {
1033
1069
  contents,
1034
1070
  loader: 'js',
1035
- resolveDir: this.projectRoot,
1036
1071
  }
1037
1072
  })
1038
1073
  },
@@ -1 +0,0 @@
1
- import{n as e,r as t,t as n}from"./server-build-BTHZMYd8.mjs";export{n as ServerComponentBuilder,t as scanDirectory};