@stacksjs/rpx 0.11.39 → 0.11.41

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.
@@ -1 +1 @@
1
- import{ab as a,bb as b,cb as c,db as d,eb as e,fb as f,gb as g,hb as h,ib as i,jb as j,kb as k,lb as l,mb as m,nb as n,ob as o}from"./chunk-mgh5b3ak.js";import"./chunk-w4t1nar9.js";export{m as tearDownDevelopmentDns,l as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,i as setupResolver,k as setupDevelopmentDns,g as resolverFilePath,n as removeResolver,j as removeLegacyTldResolvers,o as reconcileStaleDevelopmentDns,f as isRpxDevelopmentDnsAnswering,e as isDnsServerRunning,h as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
1
+ import{ab as a,bb as b,cb as c,db as d,eb as e,fb as f,gb as g,hb as h,ib as i,jb as j,kb as k,lb as l,mb as m,nb as n,ob as o}from"./chunk-fbachxy5.js";import"./chunk-w4t1nar9.js";export{m as tearDownDevelopmentDns,l as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,i as setupResolver,k as setupDevelopmentDns,g as resolverFilePath,n as removeResolver,j as removeLegacyTldResolvers,o as reconcileStaleDevelopmentDns,f as isRpxDevelopmentDnsAnswering,e as isDnsServerRunning,h as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{$ as Fx,$a as c6,A as OR,Aa as Bx,B as q,Ba as G6,C as e,Ca as Hx,D as Qx,Da as Kx,E as hR,Ea as X6,F as U,Fa as Y6,G as o,Ga as $6,H as mR,Ha as J6,I as vR,Ia as V6,J as lR,Ja as D6,K as xx,Ka as Q6,L as Rx,La as Z6,M as bR,Ma as E6,N as Sx,Na as k6,O as aR,Oa as I6,P as Zx,Pa as f6,Q as iR,Qa as F6,R as Ex,Ra as c,S as dR,Sa as Ux,T as pR,Ta as u,U as nR,Ua as M6,V as gR,Va as W6,W as tR,Wa as T6,X as kx,Xa as y6,Y as Ix,Ya as C6,Z as sR,Za as q6,_ as fx,_a as U6,a as j,aa as Xx,ab as u6,b as s,ba as rR,bb as P6,c as YR,ca as Mx,cb as L6,d as $R,da as eR,db as O6,e as JR,ea as Wx,eb as h6,f as VR,fa as oR,g as DR,ga as Tx,gb as m6,h as QR,ha as px,hb as v6,i as ZR,ia as x6,ib as l6,j as ER,ja as yx,jb as b6,k as kR,ka as nx,kb as a6,l as IR,la as R6,lb as i6,m as fR,ma as S6,mb as d6,n as FR,na as Cx,nb as p6,o as MR,oa as _6,ob as n6,p as WR,pa as w6,pb as g6,q as TR,qa as z6,qb as t6,r as yR,ra as A6,rb as s6,s as CR,sa as N6,sb as r6,t as qR,ta as j6,tb as e6,u as UR,ua as B6,ub as o6,v as cR,va as C,vb as x4,w as uR,wa as H6,wb as R4,x as PR,xa as qx,xb as Gx,y as LR,ya as K6,yb as S4,z as r,za as jx,zb as _4}from"./chunk-mgh5b3ak.js";import{Ab as Dx,Bb as ix,Cb as TS,Db as yS,Eb as CS,Fb as _,Gb as dx,Hb as qS,Ib as y,Jb as US,Kb as cS,Lb as uS,Mb as PS,Nb as LS,Ob as OS,Pb as hS,Qb as mS,Rb as vS}from"./chunk-w4t1nar9.js";import{execSync as NR}from"node:child_process";import*as _x from"node:http";import*as gx from"node:net";import*as tx from"node:os";import*as sx from"node:path";import*as V from"node:process";var l=(R,x)=>(S)=>`\x1B[${R}m${S}\x1B[${x}m`,I={bold:l(1,22),dim:l(2,22),green:l(32,39),cyan:l(36,39)};import*as hx from"node:fs";import*as mx from"node:path";import*as M from"node:process";function vx(R,x){let w=(x&&x!=="/"?`${R}${x}`:R).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function b(R){if(R.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let x=R.verbose??!1,S=R.registryDir,w=new Set,B=R.proxies.map((H)=>{let D=H.id??vx(H.to,H.path);if(!Bx(D))throw Error(`invalid registry id "${D}" derived from to="${H.to}"`);if(w.has(D))throw Error(`duplicate registry id "${D}" — set an explicit \`id\` on one of the proxies`);return w.add(D),{...H,id:D}}),N=new Date().toISOString();for(let H of B)await Hx({id:H.id,from:H.from,to:H.to,path:H.path,pid:R.persistent?void 0:M.pid,cwd:M.cwd(),createdAt:N,cleanUrls:H.cleanUrls,changeOrigin:H.changeOrigin,pathRewrites:H.pathRewrites,static:H.static,loadBalancer:H.loadBalancer},S,x);let z=await Gx({rpxDir:R.rpxDir,verbose:x,spawnCommand:R.spawnCommand,startupTimeoutMs:R.startupTimeoutMs,spawnEnv:R.spawnEnv});for(let H of B){let D=H.static?`static ${typeof H.static==="string"?H.static:H.static.dir}`:H.from;j.success(`https://${H.to} → ${D}`)}if(j.info(`(via rpx daemon pid=${z.pid}; \`rpx daemon:status\` to inspect)`),R.detached)return;let X=!1,K=S??jx(),G=B.map((H)=>H.id),Y=async()=>{if(X)return;X=!0;for(let H of G)await Kx(H,S,x).catch((D)=>{_("runner",`removeEntry(${H}) failed: ${D}`,x)})},$=(H)=>{_("runner",`received ${H}, unregistering ${G.length} entries`,x),Y().finally(()=>M.exit(0))};M.once("SIGINT",$),M.once("SIGTERM",$),M.once("exit",()=>{if(X)return;for(let H of G)try{hx.unlinkSync(mx.join(K,`${H}.json`))}catch{}}),await new Promise(()=>{})}import{spawn as RR}from"node:child_process";import*as a from"node:process";class i{processes=new Map;isShuttingDown=!1;async startProcess(R,x,S){if(this.processes.has(R)){_("start",`Process ${R} is already running`,S);return}let[w,...B]=x.command.split(" "),N=x.cwd||a.cwd();_("start",`Starting process ${R}:`,S),_("start",` Command: ${w} ${B.join(" ")}`,S),_("start",` Working directory: ${N}`,S),_("start",` Environment variables: ${y(x.env)}`,S);let z=RR(w,B,{cwd:N,env:{...a.env,...x.env},shell:!0,stdio:"inherit"});return this.processes.set(R,{command:x.command,cwd:N,process:z,env:x.env}),new Promise((X,K)=>{if(z.on("error",(G)=>{if(!this.isShuttingDown)_("start",`Process ${R} failed to start: ${G}`,S),this.processes.delete(R),K(G)}),z.on("exit",(G)=>{if(!this.isShuttingDown&&G!==null&&G!==0)_("start",`Process ${R} exited with code ${G}; leaving the proxy running`,S),this.processes.delete(R),K(Error(`Process ${R} exited with code ${G}`))}),S)z.stdout?.on("data",(G)=>{_("process",`[${R}] ${G.toString().trim()}`,!0)}),z.stderr?.on("data",(G)=>{_("process",`[${R}] ERR: ${G.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&z.killed)this.processes.delete(R),K(Error(`Process ${R} was killed during startup`));else _("start",`Process ${R} started successfully`,S),X()},1000)})}async stopProcess(R,x){let S=this.processes.get(R);if(!S?.process){_("start",`No process found for ${R}`,x);return}return _("start",`Stopping process ${R}`,x),new Promise((w)=>{if(!S.process){w();return}S.process.once("exit",()=>{this.processes.delete(R),_("start",`Process ${R} stopped`,x),w()});try{S.process.kill("SIGTERM"),setTimeout(()=>{if(S.process){_("start",`Force killing process ${R}`,x);try{S.process.kill("SIGKILL")}catch(B){}}},3000)}catch(B){_("start",`Error stopping process ${R}: ${B}`,x),this.processes.delete(R),w()}})}async stopAll(R){if(this.isShuttingDown){_("start","Already shutting down, skipping duplicate stopAll call",R);return}this.isShuttingDown=!0,_("start","Stopping all processes",R);let x=Array.from(this.processes.keys()).map((S)=>this.stopProcess(S,R).catch((w)=>{j.error(`Failed to stop process ${S}:`,w)}));await Promise.allSettled(x),this.processes.clear(),this.isShuttingDown=!1}isRunning(R){let x=this.processes.get(R);return!!x?.process&&!x.process.killed}}var $4=new i;import{timingSafeEqual as SR}from"node:crypto";function _R(R,x){if(R==null)return!1;let S=Buffer.from(R),w=Buffer.from(x);if(S.length!==w.length)return!1;return SR(S,w)}function d(R){return R.toLowerCase().replace(/\.$/,"")}var wR=["/.well-known/acme-challenge/"];function zR(R){let x=R.headers.get("host");if(x)return d(x.split(":")[0]);try{return d(new URL(R.url).hostname)}catch{return""}}function Yx(R){let x=R.header.toLowerCase(),S=new Set,w=[];for(let K of R.hosts){let G=d(K);if(G.startsWith("*."))w.push(G);else S.add(G)}let B=R.exemptPaths??wR,N=R.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
2
- `,z=(K)=>{let G=d(K);return S.has(G)||w.some((Y)=>Xx(G,Y))},X=(K)=>{let G=zR(K);if(!z(G))return;let Y="/";try{Y=new URL(K.url).pathname}catch{}if(B.some(($)=>Y.startsWith($)))return;if(_R(K.headers.get(x),R.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return X.protects=z,X}var lx={name:"@stacksjs/rpx",type:"module",version:"0.11.39",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var bx=lx.version;var n=new i,jR=new qx("0.0.0.0"),O=new Set,t=new Set,$x=!1,p=null,Jx=null;async function m(R){if($x)return _("cleanup","Cleanup already in progress, skipping",R?.verbose),Jx||Promise.resolve();$x=!0,_("cleanup","Starting cleanup process",R?.verbose),Jx=new Promise((x)=>{p=x});try{await n.stopAll(R?.verbose),j.info("Shutting down proxy servers...");let x=[],S=Array.from(O).map((w)=>new Promise((B)=>{let N=w;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",R?.verbose),B();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",R?.verbose),B()});else B()}catch(z){_("cleanup",`Error stopping server: ${z}`,R?.verbose),B()}}));x.push(...S),O.clear();for(let w of t)Rx(w);if(t.clear(),R?.hosts&&R.domains?.length){_("cleanup","Cleaning up hosts file entries",R?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(R.domains)}`,R?.verbose);let w=R.domains.filter((B)=>{if(B==="test.local")return!0;return B!=="localhost"&&!B.startsWith("localhost.")&&B!=="127.0.0.1"});if(_("cleanup",`Filtered domains for cleanup: ${JSON.stringify(w)}`,R?.verbose),w.length>0)j.info("Cleaning up hosts file entries..."),x.push(Ux(w,R?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${w.join(", ")}`,R?.verbose)}).catch((B)=>{_("cleanup",`Failed to remove hosts entries: ${B}`,R?.verbose),j.warn(`Failed to clean up hosts file entries for ${w.join(", ")}:`,B)}))}if(R?.certs&&R.domains?.length){_("cleanup","Cleaning up SSL certificates",R?.verbose),j.info("Cleaning up SSL certificates...");let w=R.domains.map(async(B)=>{try{await Qx(B,R?.verbose),_("cleanup",`Removed certificates for ${B}`,R?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${B}: ${N}`,R?.verbose),j.warn(`Failed to clean up certificates for ${B}:`,N)}});x.push(...w)}await Promise.allSettled(x),_("cleanup","All cleanup tasks completed successfully",R?.verbose),j.success("All cleanup tasks completed successfully")}catch(x){_("cleanup",`Error during cleanup: ${x}`,R?.verbose),j.error("Error during cleanup:",x)}finally{if(p)p();p=null,$x=!1;let x=R&&"vitePluginUsage"in R&&R.vitePluginUsage===!0;if(V.env.NODE_ENV!=="test"&&V.env.BUN_ENV!=="test"&&!x)V.exit(0)}return Jx}var Vx=!1;function rx(R){if(Vx){_("signal",`Received second ${R} signal, forcing exit`,!0),V.exit(1);return}Vx=!0,_("signal",`Received ${R} signal, initiating cleanup`,!0),m().catch((x)=>{_("signal",`Cleanup failed after ${R}: ${x}`,!0),V.exit(1)}).finally(()=>{Vx=!1})}V.once("SIGINT",()=>rx("SIGINT"));V.once("SIGTERM",()=>rx("SIGTERM"));V.on("uncaughtException",(R)=>{j.error("Uncaught exception (continuing):",R)});V.on("unhandledRejection",(R)=>{j.error("Unhandled rejection (continuing):",R)});async function h(R,x,S,w=5){_("connection",`Testing connection to ${R}:${x} (retries left: ${w})`,S);let B=15000,N=Date.now();if(V.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${R}:${x} due to RPX_BYPASS_CONNECTION_TEST flag`,S);return}let z=()=>new Promise((X,K)=>{let G=gx.connect({host:R,port:x,timeout:3000});G.once("connect",()=>{_("connection",`Successfully connected to ${R}:${x}`,S),G.end(),X()}),G.once("timeout",()=>{_("connection",`Connection to ${R}:${x} timed out`,S),G.destroy(),K(Error("Connection timed out"))}),G.once("error",(Y)=>{_("connection",`Failed to connect to ${R}:${x}: ${Y}`,S),G.destroy(),K(Y)})});try{await z()}catch(X){let K=X;if(Date.now()-N>B){_("connection",`Connection test timed out after ${B}ms, but continuing anyway`,S),j.warn(`Connection test to ${R}:${x} timed out, but RPX will try to proceed anyway.`);return}if(K.code==="ECONNREFUSED"&&w>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${w} retries left)`,S),await new Promise((Y)=>setTimeout(Y,2000)),h(R,x,S,w-1);if(w>0)try{_("connection",`Trying HTTP request to ${R}:${x}`,S),await new Promise((Y,$)=>{let H=_x.request({hostname:R,port:x,path:"/",method:"HEAD",timeout:5000},(D)=>{_("connection",`Received HTTP response with status: ${D.statusCode}`,S),Y()});H.on("error",(D)=>$(D)),H.on("timeout",()=>{H.destroy(),$(Error("HTTP request timed out"))}),H.end()}),_("connection",`HTTP request to ${R}:${x} succeeded`,S);return}catch(Y){return _("connection",`HTTP request to ${R}:${x} failed: ${Y}`,S),_("connection",`Retrying socket connection in 2 seconds... (${w} retries left)`,S),await new Promise(($)=>setTimeout($,2000)),h(R,x,S,w-1)}let G=`Failed to connect to ${R}:${x} after ${5-w} attempts: ${K.message}`;_("connection",`${G}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,S),j.warn(G),j.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function cx(R){_("server",`Starting server with options: ${y(R)}`,R.verbose);let x=U(R.from),S=new URL(x.startsWith("http")?x:`http://${x}`),w=new URL((R.to?.startsWith("http")?R.to:`http://${R.to}`)||"rpx.localhost"),B=Number.parseInt(S.port)||(S.protocol.includes("https:")?443:80),N=[w.hostname];if(ux(R)&&!w.hostname.includes("localhost")&&!w.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${w.hostname}`,R?.verbose);try{if(!(await u(N,R.verbose))[0]){j.info(`Adding ${w.hostname} to hosts file...`),j.info("This may require sudo/administrator privileges");try{await c(N,R.verbose)}catch(K){if(j.error("Failed to add hosts entry:",K.message),j.warn("You can manually add this entry to your hosts file:"),j.warn(`127.0.0.1 ${w.hostname}`),j.warn(`::1 ${w.hostname}`),V.platform==="win32")j.warn("On Windows:"),j.warn("1. Run notepad as administrator"),j.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else j.warn("On Unix systems:"),j.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${w.hostname}`,R.verbose)}catch(X){j.error("Failed to check hosts file:",X.message)}}try{await h(S.hostname,B,R.verbose)}catch(X){_("server",`Connection test failed: ${X}`,R.verbose),j.error(X.message),j.warn("Continuing with proxy setup despite connection test failure..."),j.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let z=R._cachedSSLConfig||null;if(R.https)try{if(R.https===!0)R.https=e({...R,to:w.hostname});if(z=await q({...R,to:w.hostname,https:R.https}),!z){if(_("ssl",`Generating new certificates for ${w.hostname}`,R.verbose),await r({...R,from:S.toString(),to:w.hostname,https:R.https}),z=await q({...R,to:w.hostname,https:R.https}),!z)throw Error(`Failed to load SSL configuration after generating certificates for ${w.hostname}`)}}catch(X){throw _("server",`SSL setup failed: ${X}`,R.verbose),X}_("server",`Setting up reverse proxy with SSL config for ${w.hostname}`,R.verbose),await HR({...R,from:x,originalFrom:R.from||x,to:w.hostname,fromPort:B,sourceUrl:{hostname:S.hostname,host:S.host},ssl:z})}async function BR(R,x,S,w,B,N,z,X,K,G,Y,$){_("proxy",`Creating proxy server ${R} -> ${x} with cleanUrls: ${X}`,z);let H=o(Y??w.host,$);xx(H);let D=[{host:x,route:{sourceHost:w.host,upstreamPool:H,cleanUrls:X||!1,changeOrigin:K||!1,basePath:"/",auth:G}}];if(!g({routeEntries:D,listenPort:S,sslConfig:B,originGuard:null,verbose:z??!1}))throw Rx(H),Error(`Failed to start proxy server for ${x} on port ${S}`);t.add(H),XR({from:R,to:x,vitePluginUsage:N,listenPort:S,ssl:!!B,cleanUrls:X,verbose:z})}async function HR(R){_("setup",`Setting up reverse proxy: ${y(R)}`,R.verbose);let{from:x,originalFrom:S,to:w,sourceUrl:B,ssl:N,verbose:z,cleanup:X,vitePluginUsage:K,changeOrigin:G,cleanUrls:Y}=R,$=80,H=443,D="0.0.0.0",W=R.portManager||jR,P=ux(R);try{if(P&&w&&!w.includes("localhost")&&!w.includes("127.0.0.1")){if(!(await u([w],z))[0]){j.warn(`The hostname ${w} isn't in your hosts file. Adding it now...`);try{await c([w],z),j.success(`Added ${w} to your hosts file.`)}catch(L){j.error(`Failed to add ${w} to your hosts file: ${L}`),j.info(`You may need to manually add '127.0.0.1 ${w}' to your /etc/hosts file.`)}}}else if(P&&V.platform!=="darwin"&&w&&w.includes("localhost")&&!w.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await u([w],z))[0]){_("hosts",`${w} not found in hosts file, adding...`,z);try{await c([w],z)}catch(L){_("hosts",`Failed to add ${w} to hosts file: ${L}`,z)}}}if(N&&!W.usedPorts.has($)){if(!await C($,D,z))_("setup","Starting HTTP redirect server",z),ex(z),W.usedPorts.add($);else if(_("setup","Port 80 is in use, skipping HTTP redirect",z),z)j.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Q=N?H:$,f=await C(Q,D,z),k;if(f){if(_("setup",`Port ${Q} is already in use`,z),z)j.warn(`Port ${Q} is already in use. This may be another instance of rpx or another service.`);if(Q===443){if(k=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${k} instead of ${Q}`,z),z)j.info(`Using port ${k} instead. Access your site at https://${w}:${k}`)}else if(k=await W.getNextAvailablePort(Q+1000,!0),_("setup",`Using port ${k} instead of ${Q}`,z),z)j.info(`Using port ${k} instead. Access your site at http://${w}:${k}`)}else k=Q,W.usedPorts.add(k),_("setup",`Using standard ${Q===443?"HTTPS":"HTTP"} port ${Q} for ${w}`,z);await BR(x,w,k,B,N,K,z,Y,G,Sx(R.auth),S,R.loadBalancer)}catch(Q){_("setup",`Setup failed: ${Q}`,z),j.error(`Failed to setup reverse proxy: ${Q.message}`),m({domains:[w],hosts:typeof X==="boolean"?X:X?.hosts,certs:typeof X==="boolean"?X:X?.certs,verbose:z,vitePluginUsage:K})}}function ex(R,x=80,S=443,w,B){_("redirect",`Starting HTTP redirect server on port ${x}`,R);let N=_x.createServer((z,X)=>{let K=z.url?z.url.split("?",1)[0]:"";if(K.startsWith("/.well-known/acme-challenge/")){if(B){let H=B.challengeStore.handlePath(K);if(H!==void 0){_("redirect",`Serving on-demand ACME challenge ${K}`,R),X.writeHead(200,{"content-type":"text/plain"}),X.end(H);return}}if(w){let H=fx(w,K);if(H!=null){_("redirect",`Serving ACME challenge ${K}`,R),X.writeHead(200,{"content-type":"text/plain"}),X.end(H);return}}if(B){X.writeHead(404,{"content-type":"text/plain"}),X.end("challenge not found");return}}let G=z.headers.host||"",Y=G.includes(":")?G.slice(0,G.indexOf(":")):G;if(B&&Y&&!B.hasCert(Y))B.ensureCert(Y).catch(()=>{});let $=S===443?Y:`${Y}:${S}`;_("redirect",`Redirecting request from ${G}${z.url} to https://${$}`,R),X.writeHead(301,{Location:`https://${$}${z.url}`}),X.end()}).listen(x);O.add(N),_("redirect","HTTP redirect server started",R)}function KR(R){let x={...s,...R};if(_("proxy",`Starting proxy with options: ${y(x)}`,x?.verbose),x.viaDaemon){if(!x.from||!x.to){j.error("viaDaemon mode requires both `from` and `to`");return}b({proxies:[{id:x.id,from:x.from,to:x.to,path:x.path,cleanUrls:x.cleanUrls,changeOrigin:x.changeOrigin,pathRewrites:x.pathRewrites}],verbose:x.verbose}).catch((K)=>{j.error(`Failed to register with rpx daemon: ${K.message}`),V.exit(1)});return}let S=x.to||"",w=S.split(".").pop()?.toLowerCase()||"",B=V.platform==="darwin"&&S&&!S.includes("localhost")&&!S.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"];if(B&&N.includes(w)&&x?.verbose)j.warn(`The .${w} TLD may not work reliably for local development`),j.info(` Google owns .${w} with HSTS preloading, which can bypass local DNS`),j.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(B)import("./chunk-jjef3xg4.js").then(({setupDevelopmentDns:K})=>{K({domains:[S],verbose:x.verbose}).then((G)=>{if(G)Promise.resolve().then(()=>{if(x.verbose)if(z.includes(w))j.success(`DNS server started for .${w} domains`);else j.success(`DNS server started for .${w} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${S} may not resolve in browser`,x.verbose)})}).catch((K)=>{_("dns",`Failed to start DNS server: ${K}`,x.verbose)});let X={from:x.from,to:x.to,cleanUrls:x.cleanUrls,https:e(x),cleanup:x.cleanup,vitePluginUsage:x.vitePluginUsage,changeOrigin:x.changeOrigin,verbose:x.verbose,regenerateUntrustedCerts:x.regenerateUntrustedCerts};_("proxy",`Server options: ${y(X)}`,x.verbose),cx(X).catch((K)=>{_("proxy",`Failed to start proxy: ${K}`,x.verbose),j.error(`Failed to start proxy: ${K.message}`),m({domains:[x.to],hosts:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.hosts,certs:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.certs,verbose:x.verbose})})}function GR(R){return R?.verbose||!1}function ux(R){if(R?.hostsManagement===!1)return!1;let x=R?.cleanup;if(x===!1)return!1;if(x&&typeof x==="object"&&x.hosts===!1)return!1;return!0}async function Px(R){let x={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(R)x={...x,...R};let S=GR(x),w=ux(x);if(_("config",`Starting with config: ${y(x,2)}`,S),_("config",`Is multi-proxy? ${"proxies"in x}`,S),_("config",`Hosts management enabled? ${w}`,S),x.viaDaemon){let J="proxies"in x&&Array.isArray(x.proxies)?x.proxies.map((Z)=>({id:Z.id,from:Z.from,to:Z.to,path:Z.path,cleanUrls:Z.cleanUrls??x.cleanUrls,changeOrigin:Z.changeOrigin??x.changeOrigin,pathRewrites:Z.pathRewrites})):[{id:x.id,from:x.from,to:x.to??"rpx.localhost",path:x.path,cleanUrls:x.cleanUrls,changeOrigin:x.changeOrigin,pathRewrites:x.pathRewrites}];await b({proxies:J,verbose:S});return}if("proxies"in x&&Array.isArray(x.proxies)){_("servers",`Found ${x.proxies.length} proxies in config`,S);for(let A of x.proxies)if(A.start){let J=`${A.from}-${A.to}`;try{_("watch",`Starting command for ${J} with command: ${A.start.command}`,S),j.info(`Starting command for ${J}...`),await n.startProcess(J,A.start,S);let Z=U(A.from),E=new URL(Z.startsWith("http")?Z:`http://${Z}`),F=E.hostname||"localhost",T=Number(E.port)||80;try{await h(F,T,S),_("watch",`Dev server is ready at ${F}:${T}`,S)}catch(wx){_("watch",`Connection check failed, but continuing with proxy setup: ${wx}`,S),j.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw _("watch",`Failed to start command for ${J}: ${Z}`,S),Error(`Failed to start command for ${J}: ${Z}`)}}else _("watch",`No start command for proxy ${A.from} -> ${A.to}`,S)}else if("start"in x&&x.start){_("watch","Found start command in single proxy config",S);let A=`${x.from}-${x.to}`;try{if(x.start)_("watch",`Starting command: ${x.start.command}`,S),await n.startProcess(A,x.start,S);let J=U(x.from),Z=new URL(J.startsWith("http")?J:`http://${J}`),E=Z.hostname||"localhost",F=Number(Z.port)||80;try{await h(E,F,S),_("watch",`Dev server is ready at ${E}:${F}`,S)}catch(T){_("watch",`Connection check failed, but continuing with proxy setup: ${T}`,S),j.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(J){throw _("watch",`Failed to run start command: ${J}`,S),Error(`Failed to run start command: ${J}`)}}else _("watch","No start command found in config",S);let B="proxies"in x&&Array.isArray(x.proxies)?x.proxies[0]?.to:("to"in x)?x.to:"rpx.localhost";if(V.platform!=="win32"&&(x.https||w)){if(!ix())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",S),NR("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",S)}}let N=[];if(x.productionCerts){if(N=await yx(x.productionCerts,S),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map((A)=>A.serverName).join(", ")}`,S)}if(x.https){let A=N.length>0?null:await q(x);if(!A&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${B}, generating new ones`,x.verbose),await r(x),A=await q(x),!A)throw Error(`Failed to load SSL certificates after generation for ${B}`)}else _("ssl",`Using existing and trusted certificates for ${B}`,x.verbose);x._cachedSSLConfig=A}let z="proxies"in x&&Array.isArray(x.proxies)?x.proxies.map((A)=>({...A,https:x.https,cleanup:x.cleanup,cleanUrls:A.cleanUrls??("cleanUrls"in x?x.cleanUrls:!1),vitePluginUsage:x.vitePluginUsage,changeOrigin:A.changeOrigin??x.changeOrigin,verbose:S,_cachedSSLConfig:x._cachedSSLConfig})):[{from:"from"in x?x.from:"localhost:5173",to:"to"in x?x.to:"rpx.localhost",cleanUrls:"cleanUrls"in x?x.cleanUrls:!1,https:x.https,cleanup:x.cleanup,vitePluginUsage:x.vitePluginUsage,start:"start"in x?x.start:void 0,changeOrigin:x.changeOrigin,auth:"auth"in x?x.auth:void 0,verbose:S,_cachedSSLConfig:x._cachedSSLConfig}],X=z.map((A)=>A.to||"rpx.localhost"),K=N.length>0?N:x._cachedSSLConfig??null,G=X.filter((A)=>A&&!A.includes("localhost")&&!A.includes("127.0.0.1")),Y=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"],H=[...new Set(G.map((A)=>A.split(".").pop()?.toLowerCase()))],D=H.filter((A)=>!!A&&Y.includes(A));if(D.length>0&&S)j.warn(`The following TLDs may not work reliably for local development: ${D.map((A)=>`.${A}`).join(", ")}`),j.info(" These TLDs have HSTS preloading which can bypass local DNS"),j.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(w&&V.platform==="darwin"&&G.length>0){let{setupDevelopmentDns:A}=await import("./chunk-jjef3xg4.js");if(await A({domains:G,verbose:S})){if(S)if(H.every((E)=>!!E&&$.includes(E)))j.success(`DNS server started for ${H.map((E)=>`.${E}`).join(", ")} domains`);else j.success(`DNS server started for ${H.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",S)}let W=async()=>{_("cleanup","Starting cleanup handler",x.verbose);try{let{tearDownDevelopmentDns:A}=await import("./chunk-jjef3xg4.js");await A({verbose:x.verbose})}catch(A){_("cleanup",`Error stopping DNS server: ${A}`,x.verbose)}try{await n.stopAll(x.verbose)}catch(A){_("cleanup",`Error stopping processes: ${A}`,x.verbose)}await m({domains:X,hosts:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.hosts,certs:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.certs,verbose:x.verbose||!1})};V.on("SIGINT",W),V.on("SIGTERM",W);let P=x.singlePortMode===!0,Q=x.httpsPort??443,f=x.httpPort??80,k=x.originGuard?Yx(x.originGuard):null,v=!!K&&(z.length>1||P||N.length>0),L=!K&&P&&z.length>0;if(v&&K){_("proxies",`Creating shared HTTPS server for ${z.length} domains on port ${Q}`,S);let A=await ax(z,w,S),J=null,Z=x.onDemandTls,E=Z?.enabled?new Cx({config:Z,certsDir:Z.certsDir??x.productionCerts?.certsDir??sx.join(tx.homedir(),".stacks","rpx","on-demand-certs"),initial:N,verbose:S,onCertAdded:(zx)=>{if(nx()==="restart")_("on-demand","certificate installed; restarting supervised gateway to reload TLS",S),setTimeout(()=>V.kill(V.pid,"SIGTERM"),10).unref();else wx(zx)}}):null,F=null,T=!1;async function wx(zx){if(F=zx,T)return;T=!0;try{while(F){let Lx=F;if(F=null,_("proxies",`rebuilding :${Q} with ${Lx.length} SNI cert(s)`,S),J)O.delete(J),J.stop(!1);let Ax=!1;for(let Nx=0;!Ax&&Nx<60;Nx++){let Ox=g({routeEntries:A,listenPort:Q,sslConfig:Lx,originGuard:k,verbose:S});if(Ox){J=Ox,Ax=!0;break}await new Promise((xR)=>setTimeout(xR,Math.min(25*2**Math.min(Nx,4),500)))}if(!Ax)j.error(`rpx: CRITICAL — could not rebind :${Q} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{T=!1}}if(!await C(f,"0.0.0.0",S))ex(S,f,Q,x.acmeChallengeWebroot,E);if(await C(Q,"0.0.0.0",S)){if(_("proxies",`Port ${Q} is already in use, cannot start shared proxy`,S),S)j.warn(`Port ${Q} is in use. Shared HTTPS proxy cannot start.`);return}let ox=E&&E.sniEntries().length>0?E.sniEntries():K;if(J=g({routeEntries:A,listenPort:Q,sslConfig:ox,originGuard:k,verbose:S}),!J){j.error(`Shared HTTPS proxy failed to bind :${Q}; not exiting`);return}}else if(L){_("proxies",`Creating shared HTTP server for ${z.length} domains on port ${f}`,S);let A=await ax(z,w,S);if(await C(f,"0.0.0.0",S)){if(_("proxies",`Port ${f} is already in use, cannot start shared proxy`,S),S)j.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!g({routeEntries:A,listenPort:f,sslConfig:null,originGuard:k,verbose:S})){j.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let A of z)try{let J=A.to||"rpx.localhost";_("proxy",`Starting proxy for ${J} with SSL config: ${!!K}`,A.verbose),await cx({from:A.from||"localhost:5173",to:J,cleanUrls:A.cleanUrls||!1,https:A.https||!1,cleanup:A.cleanup||!1,vitePluginUsage:A.vitePluginUsage||!1,verbose:A.verbose||!1,_cachedSSLConfig:x._cachedSSLConfig,changeOrigin:A.changeOrigin||!1,loadBalancer:A.loadBalancer,auth:A.auth,path:A.path,pathRewrites:A.pathRewrites})}catch(J){_("proxies",`Failed to start proxy for ${A.to}: ${J}`,A.verbose),j.error(`Failed to start proxy for ${A.to}:`,J)}}async function ax(R,x,S){let w=[],B=new Set;for(let N of R){let z=N.to||"rpx.localhost",X=N.cleanUrls||!1,K=N.path,G=Mx(K),Y=Sx(N.auth);if(N.redirect){let $=Zx(N.redirect);w.push({host:z,path:K,route:{redirect:$,basePath:G,auth:Y}}),_("proxies",`Route: ${z}${K??""} → redirect ${$.status} ${$.to}${Y?" (auth)":""}`,S)}else if(N.static)w.push({host:z,path:K,route:{static:Ex(N.static,X),cleanUrls:X,basePath:G,auth:Y}}),_("proxies",`Route: ${z}${K??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${Y?" (auth)":""}`,S);else{let $=U(N.from),H=new URL($.startsWith("http")?$:`http://${$}`),D=o(N.from??H.host,N.loadBalancer);xx(D),t.add(D),w.push({host:z,path:K,route:{sourceHost:H.host,upstreamPool:D,cleanUrls:X,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:G,auth:Y}}),_("proxies",`Route: ${z}${K??""} → ${H.host}${Y?" (auth)":""}`,S)}if(B.has(z))continue;if(B.add(z),x&&!Fx(z)&&!z.includes("localhost")&&!z.includes("127.0.0.1"))try{if(!(await u([z],S))[0])await c([z],S)}catch{_("hosts",`Could not add hosts entry for ${z}`,S)}}return w}function g(R){let{routeEntries:x,listenPort:S,sslConfig:w,originGuard:B,verbose:N}=R,z=Wx(x),X=kx((Y,$)=>Tx(z,Y,$),N),K=B?(Y,$)=>B(Y)??X(Y,$):X,G=Ix(N);try{let Y=Bun.serve({port:S,hostname:"0.0.0.0",reusePort:dx(),...w?{tls:px(Array.isArray(w)?w.map(($)=>({serverName:$.serverName,key:$.key,cert:$.cert})):{key:w.key,cert:w.cert,ca:w.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch($,H){return K($,H)},websocket:G,error($){return _("server",`Shared proxy server error: ${$}`,N),new Response(`Server Error: ${$.message}`,{status:500})}});return O.add(Y),_("proxies",`Shared ${w?"HTTPS":"HTTP"} proxy listening on port ${S} for ${z.size} domains`,N),Y}catch(Y){return _("proxies",`Failed to start shared proxy: ${Y}`,N),console.error("Failed to start shared proxy:",Y),null}}function XR(R){if(R?.vitePluginUsage||!R?.verbose)return;if(console.log(""),console.log(` ${I.green(I.bold("rpx"))} ${I.green(`v${bx}`)}`),console.log(` ${I.green("➜")} ${I.dim(R?.from??"")} ${I.dim("➜")} ${I.cyan(R?.ssl?`https://${R?.to}`:`http://${R?.to}`)}`),R?.listenPort!==(R?.ssl?443:80))console.log(` ${I.green("➜")} Listening on port ${R?.listenPort}`);if(R?.cleanUrls)console.log(` ${I.green("➜")} Clean URLs enabled`)}var WS=Px;export{Hx as writeEntry,J6 as watchRegistry,DR as verifyHttpsChain,yR as trustRootCaForBrowsers,d6 as tearDownDevelopmentDns,i6 as syncDevelopmentDnsFromRegistry,tR as stripBasePath,Rx as stopHealthChecks,O6 as stopDnsServer,S4 as stopDaemon,cx as startServer,KR as startProxy,Px as startProxies,xx as startHealthChecks,L6 as startDnsServer,w6 as siteIdForHost,dx as shouldReusePort,l6 as setupResolver,a6 as setupDevelopmentDns,x6 as serverNameFromCertFilename,gR as serveStaticFile,mR as selectUpstream,y as safeStringify,pR as safeRelativePath,vS as safeDeleteFile,b as runViaDaemon,x4 as runDaemon,m6 as resolverFilePath,U6 as resolverBasenamesForDomains,q6 as resolverBasenameForDomain,Ex as resolveStaticRoute,nR as resolveStaticFile,Zx as resolveRedirect,mS as resolvePathRewrite,Sx as resolveAuth,Q6 as renderStartingPage,Z6 as renderFailedPage,W6 as removeStaleRpxHosts,p6 as removeResolver,b6 as removeLegacyTldResolvers,Ux as removeHosts,Kx as removeEntry,o6 as releaseDaemonLock,qS as redactSensitive,n6 as reconcileStaleDevelopmentDns,_4 as reconcileDevelopmentDnsOnIdle,A6 as readSiteManifest,X6 as readEntry,s6 as readDaemonPid,$R as readCertSha256Fingerprint,JR as readCertCommonName,Y6 as readAll,fx as readAcmeChallenge,MR as pruneStaleRootCas,z6 as projectNameFromHost,U as primaryUpstreamUrl,K6 as portManager,eR as pathPrefixMatches,QR as parseSha256HashesFromSecurityListing,bR as parseHtpasswd,k6 as parseHostsLine,YR as normalizeSha256Fingerprint,Mx as normalizePathPrefix,C6 as normalizeDevDomain,Xx as matchesWildcard,R6 as matchesAllowedSuffix,Tx as matchHostRoute,oR as matchHostList,rR as matchHost,vR as markSuccess,lR as markFailure,PR as loadSSLConfig,B6 as listDiscoverableSites,FR as listCertSha256HashesByCommonName,Fx as isWildcardPattern,cS as isValidRootCA,Bx as isValidId,OS as isSingleProxyOptions,hS as isSingleProxyConfig,WR as isRootCaTrustedForSsl,TR as isRootCaFingerprintInKeychains,TS as isProcessElevated,C as isPortInUse,G6 as isPidAlive,LS as isMultiProxyOptions,PS as isMultiProxyConfig,S6 as isLikelyHostname,h6 as isDnsServerRunning,r6 as isDaemonRunning,hR as isCertTrusted,e as httpsConfig,I6 as hostsLineMapsHost,ix as getSudoPassword,uR as getSharedDaemonCertPaths,cR as getRootCAPaths,jx as getRegistryDir,uS as getPrimaryDomain,fR as getMacosTrustKeychains,IR as getMacosLoginKeychainPath,g6 as getDaemonRpxDir,t6 as getDaemonPidPath,r as generateCertificate,$6 as gcStaleEntries,LR as forceTrustCertificate,M6 as findStaleRpxHosts,H6 as findAvailablePort,f6 as filterRpxHostsEntries,US as extractHostname,_6 as expandHome,CS as execSudoSync,D6 as escapeHtml,Gx as ensureDaemonRunning,aR as enforceBasicAuth,F6 as dropStaleRpxHostsLines,qR as devSslToSniEntries,c6 as devDomainsFromHosts,N6 as detectProjectPreset,vx as deriveIdFromTarget,R4 as defaultDaemonSpawnCommand,s as defaultConfig,WS as default,_ as debugLog,o as createUpstreamPool,j6 as createSiteResolver,Ix as createProxyWebSocketHandler,kx as createProxyFetchHandler,Yx as createOriginGuard,dR as contentTypeFor,v6 as contentLooksLikeRpxResolver,s as config,I as colors,OR as clearSslConfigCache,Qx as cleanupCertificates,m as cleanup,u as checkHosts,q as checkExistingCertificates,VR as certIncludesSanHostnames,yx as buildSniTlsConfig,UR as buildRegistryTlsProxyOptions,iR as buildRedirectLocation,Wx as buildHostRoutes,yS as authorizeSystemAccess,c as addHosts,e6 as acquireDaemonLock,V6 as SiteSupervisor,CR as SHARED_DEV_HOST_CERT_PATH,kR as RPX_ROOT_CA_COMMON_NAME,P6 as RPX_RESOLVER_MARKER,E6 as RPX_HOSTS_MARKER,Cx as OnDemandCertManager,ER as MACOS_SYSTEM_KEYCHAIN,ZR as MACOS_CA_TRUST_FLAGS,y6 as LEGACY_TLD_RESOLVER_LABELS,qx as DefaultPortManager,T6 as DNS_STATE_VERSION,u6 as DNS_PORT,sR as ACME_CHALLENGE_PREFIX};
1
+ import{$ as Wx,$a as P6,A as mR,Aa as Xx,B as q,Ba as B6,C as o,Ca as Yx,D as Ex,Da as $x,E as vR,Ea as J6,F as U,Fa as V6,G as xx,Ga as D6,H as lR,Ha as H6,I as bR,Ia as Q6,J as aR,Ja as Z6,K as Rx,Ka as E6,L as Sx,La as k6,M as iR,Ma as I6,N as _x,Na as f6,O as pR,Oa as F6,P as kx,Pa as M6,Q as dR,Qa as W6,R as Ix,Ra as c,S as nR,Sa as ux,T as gR,Ta as u,U as tR,Ua as T6,V as sR,Va as y6,W as rR,Wa as C6,X as fx,Xa as q6,Y as Fx,Ya as U6,Z as eR,Za as c6,_ as Mx,_a as u6,a as j,aa as Jx,ab as L6,b as r,ba as oR,bb as O6,c as VR,ca as Tx,cb as h6,d as DR,da as x6,db as m6,e as HR,ea as yx,eb as v6,f as QR,fa as R6,g as ZR,ga as Cx,gb as l6,h as ER,ha as gx,hb as b6,i as kR,ia as S6,ib as a6,j as IR,ja as qx,jb as i6,k as fR,ka as tx,kb as p6,l as FR,la as _6,lb as d6,m as MR,ma as w6,mb as n6,n as WR,na as Ux,nb as g6,o as TR,oa as z6,ob as t6,p as yR,pa as A6,pb as s6,q as CR,qa as N6,qb as r6,r as qR,ra as j6,rb as e6,s as UR,sa as K6,sb as o6,t as cR,ta as G6,tb as x4,u as uR,ua as X6,ub as R4,v as PR,va as C,vb as S4,w as LR,wa as Y6,wb as _4,x as OR,xa as cx,xb as Bx,y as hR,ya as $6,yb as w4,z as e,za as Gx,zb as z4}from"./chunk-fbachxy5.js";import{Ab as Zx,Bb as dx,Cb as CS,Db as qS,Eb as US,Fb as _,Gb as nx,Hb as cS,Ib as y,Jb as uS,Kb as PS,Lb as LS,Mb as OS,Nb as hS,Ob as mS,Pb as vS,Qb as lS,Rb as bS}from"./chunk-w4t1nar9.js";import{execSync as KR}from"node:child_process";import*as wx from"node:http";import*as sx from"node:net";import*as zx from"node:os";import*as rx from"node:path";import*as D from"node:process";var b=(R,x)=>(S)=>`\x1B[${R}m${S}\x1B[${x}m`,I={bold:b(1,22),dim:b(2,22),green:b(32,39),cyan:b(36,39)};import*as vx from"node:fs";import*as lx from"node:path";import*as M from"node:process";function bx(R,x){let w=(x&&x!=="/"?`${R}${x}`:R).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function a(R){if(R.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let x=R.verbose??!1,S=R.registryDir,w=new Set,K=R.proxies.map((G)=>{let H=G.id??bx(G.to,G.path);if(!Xx(H))throw Error(`invalid registry id "${H}" derived from to="${G.to}"`);if(w.has(H))throw Error(`duplicate registry id "${H}" — set an explicit \`id\` on one of the proxies`);return w.add(H),{...G,id:H}}),N=new Date().toISOString();for(let G of K)await Yx({id:G.id,from:G.from,to:G.to,path:G.path,pid:R.persistent?void 0:M.pid,cwd:M.cwd(),createdAt:N,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin,pathRewrites:G.pathRewrites,static:G.static,loadBalancer:G.loadBalancer},S,x);let z=await Bx({rpxDir:R.rpxDir,verbose:x,spawnCommand:R.spawnCommand,startupTimeoutMs:R.startupTimeoutMs,spawnEnv:R.spawnEnv});for(let G of K){let H=G.static?`static ${typeof G.static==="string"?G.static:G.static.dir}`:G.from;j.success(`https://${G.to} → ${H}`)}if(j.info(`(via rpx daemon pid=${z.pid}; \`rpx daemon:status\` to inspect)`),R.detached)return;let $=!1,X=S??Gx(),Y=K.map((G)=>G.id),B=async()=>{if($)return;$=!0;for(let G of Y)await $x(G,S,x).catch((H)=>{_("runner",`removeEntry(${G}) failed: ${H}`,x)})},J=(G)=>{_("runner",`received ${G}, unregistering ${Y.length} entries`,x),B().finally(()=>M.exit(0))};M.once("SIGINT",J),M.once("SIGTERM",J),M.once("exit",()=>{if($)return;for(let G of Y)try{vx.unlinkSync(lx.join(X,`${G}.json`))}catch{}}),await new Promise(()=>{})}import{spawn as _R}from"node:child_process";import*as i from"node:process";class p{processes=new Map;isShuttingDown=!1;async startProcess(R,x,S){if(this.processes.has(R)){_("start",`Process ${R} is already running`,S);return}let[w,...K]=x.command.split(" "),N=x.cwd||i.cwd();_("start",`Starting process ${R}:`,S),_("start",` Command: ${w} ${K.join(" ")}`,S),_("start",` Working directory: ${N}`,S),_("start",` Environment variables: ${y(x.env)}`,S);let z=_R(w,K,{cwd:N,env:{...i.env,...x.env},shell:!0,stdio:"inherit"});return this.processes.set(R,{command:x.command,cwd:N,process:z,env:x.env}),new Promise(($,X)=>{if(z.on("error",(Y)=>{if(!this.isShuttingDown)_("start",`Process ${R} failed to start: ${Y}`,S),this.processes.delete(R),X(Y)}),z.on("exit",(Y)=>{if(!this.isShuttingDown&&Y!==null&&Y!==0)_("start",`Process ${R} exited with code ${Y}; leaving the proxy running`,S),this.processes.delete(R),X(Error(`Process ${R} exited with code ${Y}`))}),S)z.stdout?.on("data",(Y)=>{_("process",`[${R}] ${Y.toString().trim()}`,!0)}),z.stderr?.on("data",(Y)=>{_("process",`[${R}] ERR: ${Y.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&z.killed)this.processes.delete(R),X(Error(`Process ${R} was killed during startup`));else _("start",`Process ${R} started successfully`,S),$()},1000)})}async stopProcess(R,x){let S=this.processes.get(R);if(!S?.process){_("start",`No process found for ${R}`,x);return}return _("start",`Stopping process ${R}`,x),new Promise((w)=>{if(!S.process){w();return}S.process.once("exit",()=>{this.processes.delete(R),_("start",`Process ${R} stopped`,x),w()});try{S.process.kill("SIGTERM"),setTimeout(()=>{if(S.process){_("start",`Force killing process ${R}`,x);try{S.process.kill("SIGKILL")}catch(K){}}},3000)}catch(K){_("start",`Error stopping process ${R}: ${K}`,x),this.processes.delete(R),w()}})}async stopAll(R){if(this.isShuttingDown){_("start","Already shutting down, skipping duplicate stopAll call",R);return}this.isShuttingDown=!0,_("start","Stopping all processes",R);let x=Array.from(this.processes.keys()).map((S)=>this.stopProcess(S,R).catch((w)=>{j.error(`Failed to stop process ${S}:`,w)}));await Promise.allSettled(x),this.processes.clear(),this.isShuttingDown=!1}isRunning(R){let x=this.processes.get(R);return!!x?.process&&!x.process.killed}}var D4=new p;import{timingSafeEqual as wR}from"node:crypto";function zR(R,x){if(R==null)return!1;let S=Buffer.from(R),w=Buffer.from(x);if(S.length!==w.length)return!1;return wR(S,w)}function d(R){return R.toLowerCase().replace(/\.$/,"")}var AR=["/.well-known/acme-challenge/"];function NR(R){let x=R.headers.get("host");if(x)return d(x.split(":")[0]);try{return d(new URL(R.url).hostname)}catch{return""}}function Vx(R){let x=R.header.toLowerCase(),S=new Set,w=[];for(let X of R.hosts){let Y=d(X);if(Y.startsWith("*."))w.push(Y);else S.add(Y)}let K=R.exemptPaths??AR,N=R.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
2
+ `,z=(X)=>{let Y=d(X);return S.has(Y)||w.some((B)=>Jx(Y,B))},$=(X)=>{let Y=NR(X);if(!z(Y))return;let B="/";try{B=new URL(X.url).pathname}catch{}if(K.some((J)=>B.startsWith(J)))return;if(zR(X.headers.get(x),R.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return $.protects=z,$}var ax={name:"@stacksjs/rpx",type:"module",version:"0.11.41",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var ix=ax.version;var g=new p,GR=new cx("0.0.0.0"),h=new Set,s=new Set,Dx=!1,n=null,Hx=null;async function v(R){if(Dx)return _("cleanup","Cleanup already in progress, skipping",R?.verbose),Hx||Promise.resolve();Dx=!0,_("cleanup","Starting cleanup process",R?.verbose),Hx=new Promise((x)=>{n=x});try{await g.stopAll(R?.verbose),j.info("Shutting down proxy servers...");let x=[],S=Array.from(h).map((w)=>new Promise((K)=>{let N=w;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",R?.verbose),K();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",R?.verbose),K()});else K()}catch(z){_("cleanup",`Error stopping server: ${z}`,R?.verbose),K()}}));x.push(...S),h.clear();for(let w of s)Sx(w);if(s.clear(),R?.hosts&&R.domains?.length){_("cleanup","Cleaning up hosts file entries",R?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(R.domains)}`,R?.verbose);let w=R.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(_("cleanup",`Filtered domains for cleanup: ${JSON.stringify(w)}`,R?.verbose),w.length>0)j.info("Cleaning up hosts file entries..."),x.push(ux(w,R?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${w.join(", ")}`,R?.verbose)}).catch((K)=>{_("cleanup",`Failed to remove hosts entries: ${K}`,R?.verbose),j.warn(`Failed to clean up hosts file entries for ${w.join(", ")}:`,K)}))}if(R?.certs&&R.domains?.length){_("cleanup","Cleaning up SSL certificates",R?.verbose),j.info("Cleaning up SSL certificates...");let w=R.domains.map(async(K)=>{try{await Ex(K,R?.verbose),_("cleanup",`Removed certificates for ${K}`,R?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${K}: ${N}`,R?.verbose),j.warn(`Failed to clean up certificates for ${K}:`,N)}});x.push(...w)}await Promise.allSettled(x),_("cleanup","All cleanup tasks completed successfully",R?.verbose),j.success("All cleanup tasks completed successfully")}catch(x){_("cleanup",`Error during cleanup: ${x}`,R?.verbose),j.error("Error during cleanup:",x)}finally{if(n)n();n=null,Dx=!1;let x=R&&"vitePluginUsage"in R&&R.vitePluginUsage===!0;if(D.env.NODE_ENV!=="test"&&D.env.BUN_ENV!=="test"&&!x)D.exit(0)}return Hx}var Qx=!1;function ex(R){if(Qx){_("signal",`Received second ${R} signal, forcing exit`,!0),D.exit(1);return}Qx=!0,_("signal",`Received ${R} signal, initiating cleanup`,!0),v().catch((x)=>{_("signal",`Cleanup failed after ${R}: ${x}`,!0),D.exit(1)}).finally(()=>{Qx=!1})}D.once("SIGINT",()=>ex("SIGINT"));D.once("SIGTERM",()=>ex("SIGTERM"));D.on("uncaughtException",(R)=>{j.error("Uncaught exception (continuing):",R)});D.on("unhandledRejection",(R)=>{j.error("Unhandled rejection (continuing):",R)});async function m(R,x,S,w=5){_("connection",`Testing connection to ${R}:${x} (retries left: ${w})`,S);let K=15000,N=Date.now();if(D.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${R}:${x} due to RPX_BYPASS_CONNECTION_TEST flag`,S);return}let z=()=>new Promise(($,X)=>{let Y=sx.connect({host:R,port:x,timeout:3000});Y.once("connect",()=>{_("connection",`Successfully connected to ${R}:${x}`,S),Y.end(),$()}),Y.once("timeout",()=>{_("connection",`Connection to ${R}:${x} timed out`,S),Y.destroy(),X(Error("Connection timed out"))}),Y.once("error",(B)=>{_("connection",`Failed to connect to ${R}:${x}: ${B}`,S),Y.destroy(),X(B)})});try{await z()}catch($){let X=$;if(Date.now()-N>K){_("connection",`Connection test timed out after ${K}ms, but continuing anyway`,S),j.warn(`Connection test to ${R}:${x} timed out, but RPX will try to proceed anyway.`);return}if(X.code==="ECONNREFUSED"&&w>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${w} retries left)`,S),await new Promise((B)=>setTimeout(B,2000)),m(R,x,S,w-1);if(w>0)try{_("connection",`Trying HTTP request to ${R}:${x}`,S),await new Promise((B,J)=>{let G=wx.request({hostname:R,port:x,path:"/",method:"HEAD",timeout:5000},(H)=>{_("connection",`Received HTTP response with status: ${H.statusCode}`,S),B()});G.on("error",(H)=>J(H)),G.on("timeout",()=>{G.destroy(),J(Error("HTTP request timed out"))}),G.end()}),_("connection",`HTTP request to ${R}:${x} succeeded`,S);return}catch(B){return _("connection",`HTTP request to ${R}:${x} failed: ${B}`,S),_("connection",`Retrying socket connection in 2 seconds... (${w} retries left)`,S),await new Promise((J)=>setTimeout(J,2000)),m(R,x,S,w-1)}let Y=`Failed to connect to ${R}:${x} after ${5-w} attempts: ${X.message}`;_("connection",`${Y}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,S),j.warn(Y),j.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function Px(R){_("server",`Starting server with options: ${y(R)}`,R.verbose);let x=U(R.from),S=new URL(x.startsWith("http")?x:`http://${x}`),w=new URL((R.to?.startsWith("http")?R.to:`http://${R.to}`)||"rpx.localhost"),K=Number.parseInt(S.port)||(S.protocol.includes("https:")?443:80),N=[w.hostname];if(Lx(R)&&!w.hostname.includes("localhost")&&!w.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${w.hostname}`,R?.verbose);try{if(!(await u(N,R.verbose))[0]){j.info(`Adding ${w.hostname} to hosts file...`),j.info("This may require sudo/administrator privileges");try{await c(N,R.verbose)}catch(X){if(j.error("Failed to add hosts entry:",X.message),j.warn("You can manually add this entry to your hosts file:"),j.warn(`127.0.0.1 ${w.hostname}`),j.warn(`::1 ${w.hostname}`),D.platform==="win32")j.warn("On Windows:"),j.warn("1. Run notepad as administrator"),j.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else j.warn("On Unix systems:"),j.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${w.hostname}`,R.verbose)}catch($){j.error("Failed to check hosts file:",$.message)}}try{await m(S.hostname,K,R.verbose)}catch($){_("server",`Connection test failed: ${$}`,R.verbose),j.error($.message),j.warn("Continuing with proxy setup despite connection test failure..."),j.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let z=R._cachedSSLConfig||null;if(R.https)try{if(R.https===!0)R.https=o({...R,to:w.hostname});if(z=await q({...R,to:w.hostname,https:R.https}),!z){if(_("ssl",`Generating new certificates for ${w.hostname}`,R.verbose),await e({...R,from:S.toString(),to:w.hostname,https:R.https}),z=await q({...R,to:w.hostname,https:R.https}),!z)throw Error(`Failed to load SSL configuration after generating certificates for ${w.hostname}`)}}catch($){throw _("server",`SSL setup failed: ${$}`,R.verbose),$}_("server",`Setting up reverse proxy with SSL config for ${w.hostname}`,R.verbose),await YR({...R,from:x,originalFrom:R.from||x,to:w.hostname,fromPort:K,sourceUrl:{hostname:S.hostname,host:S.host},ssl:z})}async function XR(R,x,S,w,K,N,z,$,X,Y,B,J){_("proxy",`Creating proxy server ${R} -> ${x} with cleanUrls: ${$}`,z);let G=xx(B??w.host,J);Rx(G);let H=[{host:x,route:{sourceHost:w.host,upstreamPool:G,cleanUrls:$||!1,changeOrigin:X||!1,basePath:"/",auth:Y}}];if(!t({routeEntries:H,listenPort:S,sslConfig:K,originGuard:null,verbose:z??!1}))throw Sx(G),Error(`Failed to start proxy server for ${x} on port ${S}`);s.add(G),JR({from:R,to:x,vitePluginUsage:N,listenPort:S,ssl:!!K,cleanUrls:$,verbose:z})}async function YR(R){_("setup",`Setting up reverse proxy: ${y(R)}`,R.verbose);let{from:x,originalFrom:S,to:w,sourceUrl:K,ssl:N,verbose:z,cleanup:$,vitePluginUsage:X,changeOrigin:Y,cleanUrls:B}=R,J=80,G=443,H=xR(),W=R.portManager||GR,P=Lx(R);try{if(P&&w&&!w.includes("localhost")&&!w.includes("127.0.0.1")){if(!(await u([w],z))[0]){j.warn(`The hostname ${w} isn't in your hosts file. Adding it now...`);try{await c([w],z),j.success(`Added ${w} to your hosts file.`)}catch(L){j.error(`Failed to add ${w} to your hosts file: ${L}`),j.info(`You may need to manually add '127.0.0.1 ${w}' to your /etc/hosts file.`)}}}else if(P&&D.platform!=="darwin"&&w&&w.includes("localhost")&&!w.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await u([w],z))[0]){_("hosts",`${w} not found in hosts file, adding...`,z);try{await c([w],z)}catch(L){_("hosts",`Failed to add ${w} to hosts file: ${L}`,z)}}}if(N&&!W.usedPorts.has(J)){if(!await C(J,H,z))_("setup","Starting HTTP redirect server",z),ox(z),W.usedPorts.add(J);else if(_("setup","Port 80 is in use, skipping HTTP redirect",z),z)j.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Q=N?G:J,f=await C(Q,H,z),k;if(f){if(_("setup",`Port ${Q} is already in use`,z),z)j.warn(`Port ${Q} is already in use. This may be another instance of rpx or another service.`);if(Q===443){if(k=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${k} instead of ${Q}`,z),z)j.info(`Using port ${k} instead. Access your site at https://${w}:${k}`)}else if(k=await W.getNextAvailablePort(Q+1000,!0),_("setup",`Using port ${k} instead of ${Q}`,z),z)j.info(`Using port ${k} instead. Access your site at http://${w}:${k}`)}else k=Q,W.usedPorts.add(k),_("setup",`Using standard ${Q===443?"HTTPS":"HTTP"} port ${Q} for ${w}`,z);await XR(x,w,k,K,N,X,z,B,Y,_x(R.auth),S,R.loadBalancer)}catch(Q){_("setup",`Setup failed: ${Q}`,z),j.error(`Failed to setup reverse proxy: ${Q.message}`),v({domains:[w],hosts:typeof $==="boolean"?$:$?.hosts,certs:typeof $==="boolean"?$:$?.certs,verbose:z,vitePluginUsage:X})}}function ox(R,x=80,S=443,w,K){_("redirect",`Starting HTTP redirect server on port ${x}`,R);let N=wx.createServer((z,$)=>{let X=z.url?z.url.split("?",1)[0]:"";if(X.startsWith("/.well-known/acme-challenge/")){if(K){let G=K.challengeStore.handlePath(X);if(G!==void 0){_("redirect",`Serving on-demand ACME challenge ${X}`,R),$.writeHead(200,{"content-type":"text/plain"}),$.end(G);return}}if(w){let G=Mx(w,X);if(G!=null){_("redirect",`Serving ACME challenge ${X}`,R),$.writeHead(200,{"content-type":"text/plain"}),$.end(G);return}}if(K){$.writeHead(404,{"content-type":"text/plain"}),$.end("challenge not found");return}}let Y=z.headers.host||"",B=Y.includes(":")?Y.slice(0,Y.indexOf(":")):Y;if(K&&B&&!K.hasCert(B))K.ensureCert(B).catch(()=>{});let J=S===443?B:`${B}:${S}`;_("redirect",`Redirecting request from ${Y}${z.url} to https://${J}`,R),$.writeHead(301,{Location:`https://${J}${z.url}`}),$.end()}).listen(x);h.add(N),_("redirect","HTTP redirect server started",R)}function $R(R){let x={...r,...R};if(_("proxy",`Starting proxy with options: ${y(x)}`,x?.verbose),x.viaDaemon){if(!x.from||!x.to){j.error("viaDaemon mode requires both `from` and `to`");return}a({proxies:[{id:x.id,from:x.from,to:x.to,path:x.path,cleanUrls:x.cleanUrls,changeOrigin:x.changeOrigin,pathRewrites:x.pathRewrites}],verbose:x.verbose}).catch((X)=>{j.error(`Failed to register with rpx daemon: ${X.message}`),D.exit(1)});return}let S=x.to||"",w=S.split(".").pop()?.toLowerCase()||"",K=D.platform==="darwin"&&S&&!S.includes("localhost")&&!S.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"];if(K&&N.includes(w)&&x?.verbose)j.warn(`The .${w} TLD may not work reliably for local development`),j.info(` Google owns .${w} with HSTS preloading, which can bypass local DNS`),j.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-x3ay10n1.js").then(({setupDevelopmentDns:X})=>{X({domains:[S],verbose:x.verbose}).then((Y)=>{if(Y)Promise.resolve().then(()=>{if(x.verbose)if(z.includes(w))j.success(`DNS server started for .${w} domains`);else j.success(`DNS server started for .${w} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${S} may not resolve in browser`,x.verbose)})}).catch((X)=>{_("dns",`Failed to start DNS server: ${X}`,x.verbose)});let $={from:x.from,to:x.to,cleanUrls:x.cleanUrls,https:o(x),cleanup:x.cleanup,vitePluginUsage:x.vitePluginUsage,changeOrigin:x.changeOrigin,verbose:x.verbose,regenerateUntrustedCerts:x.regenerateUntrustedCerts};_("proxy",`Server options: ${y($)}`,x.verbose),Px($).catch((X)=>{_("proxy",`Failed to start proxy: ${X}`,x.verbose),j.error(`Failed to start proxy: ${X.message}`),v({domains:[x.to],hosts:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.hosts,certs:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.certs,verbose:x.verbose})})}function BR(R){return R?.verbose||!1}function Lx(R){if(R?.hostsManagement===!1)return!1;let x=R?.cleanup;if(x===!1)return!1;if(x&&typeof x==="object"&&x.hosts===!1)return!1;return!0}async function Ox(R){let x={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(R)x={...x,...R};let S=BR(x),w=Lx(x);if(_("config",`Starting with config: ${y(x,2)}`,S),_("config",`Is multi-proxy? ${"proxies"in x}`,S),_("config",`Hosts management enabled? ${w}`,S),x.viaDaemon){let V="proxies"in x&&Array.isArray(x.proxies)?x.proxies.map((Z)=>({id:Z.id,from:Z.from,to:Z.to,path:Z.path,cleanUrls:Z.cleanUrls??x.cleanUrls,changeOrigin:Z.changeOrigin??x.changeOrigin,pathRewrites:Z.pathRewrites})):[{id:x.id,from:x.from,to:x.to??"rpx.localhost",path:x.path,cleanUrls:x.cleanUrls,changeOrigin:x.changeOrigin,pathRewrites:x.pathRewrites}];await a({proxies:V,verbose:S});return}if("proxies"in x&&Array.isArray(x.proxies)){_("servers",`Found ${x.proxies.length} proxies in config`,S);for(let A of x.proxies)if(A.start){let V=`${A.from}-${A.to}`;try{_("watch",`Starting command for ${V} with command: ${A.start.command}`,S),j.info(`Starting command for ${V}...`),await g.startProcess(V,A.start,S);let Z=U(A.from),E=new URL(Z.startsWith("http")?Z:`http://${Z}`),F=E.hostname||"localhost",T=Number(E.port)||80;try{await m(F,T,S),_("watch",`Dev server is ready at ${F}:${T}`,S)}catch(Ax){_("watch",`Connection check failed, but continuing with proxy setup: ${Ax}`,S),j.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw _("watch",`Failed to start command for ${V}: ${Z}`,S),Error(`Failed to start command for ${V}: ${Z}`)}}else _("watch",`No start command for proxy ${A.from} -> ${A.to}`,S)}else if("start"in x&&x.start){_("watch","Found start command in single proxy config",S);let A=`${x.from}-${x.to}`;try{if(x.start)_("watch",`Starting command: ${x.start.command}`,S),await g.startProcess(A,x.start,S);let V=U(x.from),Z=new URL(V.startsWith("http")?V:`http://${V}`),E=Z.hostname||"localhost",F=Number(Z.port)||80;try{await m(E,F,S),_("watch",`Dev server is ready at ${E}:${F}`,S)}catch(T){_("watch",`Connection check failed, but continuing with proxy setup: ${T}`,S),j.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(V){throw _("watch",`Failed to run start command: ${V}`,S),Error(`Failed to run start command: ${V}`)}}else _("watch","No start command found in config",S);let K="proxies"in x&&Array.isArray(x.proxies)?x.proxies[0]?.to:("to"in x)?x.to:"rpx.localhost";if(D.platform!=="win32"&&(x.https||w)){if(!dx())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",S),KR("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",S)}}let N=[];if(x.productionCerts){if(N=await qx(x.productionCerts,S),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map((A)=>A.serverName).join(", ")}`,S)}if(x.https){let A=N.length>0?null:await q(x);if(!A&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,x.verbose),await e(x),A=await q(x),!A)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else _("ssl",`Using existing and trusted certificates for ${K}`,x.verbose);x._cachedSSLConfig=A}let z="proxies"in x&&Array.isArray(x.proxies)?x.proxies.map((A)=>({...A,https:x.https,cleanup:x.cleanup,cleanUrls:A.cleanUrls??("cleanUrls"in x?x.cleanUrls:!1),vitePluginUsage:x.vitePluginUsage,changeOrigin:A.changeOrigin??x.changeOrigin,verbose:S,_cachedSSLConfig:x._cachedSSLConfig})):[{from:"from"in x?x.from:"localhost:5173",to:"to"in x?x.to:"rpx.localhost",cleanUrls:"cleanUrls"in x?x.cleanUrls:!1,https:x.https,cleanup:x.cleanup,vitePluginUsage:x.vitePluginUsage,start:"start"in x?x.start:void 0,changeOrigin:x.changeOrigin,auth:"auth"in x?x.auth:void 0,verbose:S,_cachedSSLConfig:x._cachedSSLConfig}],$=z.map((A)=>A.to||"rpx.localhost"),X=N.length>0?N:x._cachedSSLConfig??null,Y=$.filter((A)=>A&&!A.includes("localhost")&&!A.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],J=["test","localhost","local","example","invalid"],G=[...new Set(Y.map((A)=>A.split(".").pop()?.toLowerCase()))],H=G.filter((A)=>!!A&&B.includes(A));if(H.length>0&&S)j.warn(`The following TLDs may not work reliably for local development: ${H.map((A)=>`.${A}`).join(", ")}`),j.info(" These TLDs have HSTS preloading which can bypass local DNS"),j.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(w&&D.platform==="darwin"&&Y.length>0){let{setupDevelopmentDns:A}=await import("./chunk-x3ay10n1.js");if(await A({domains:Y,verbose:S})){if(S)if(G.every((E)=>!!E&&J.includes(E)))j.success(`DNS server started for ${G.map((E)=>`.${E}`).join(", ")} domains`);else j.success(`DNS server started for ${G.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",S)}let W=async()=>{_("cleanup","Starting cleanup handler",x.verbose);try{let{tearDownDevelopmentDns:A}=await import("./chunk-x3ay10n1.js");await A({verbose:x.verbose})}catch(A){_("cleanup",`Error stopping DNS server: ${A}`,x.verbose)}try{await g.stopAll(x.verbose)}catch(A){_("cleanup",`Error stopping processes: ${A}`,x.verbose)}await v({domains:$,hosts:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.hosts,certs:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.certs,verbose:x.verbose||!1})};D.on("SIGINT",W),D.on("SIGTERM",W);let P=x.singlePortMode===!0,Q=x.httpsPort??443,f=x.httpPort??80,k=x.originGuard?Vx(x.originGuard):null,l=!!X&&(z.length>1||P||N.length>0),L=!X&&P&&z.length>0;if(l&&X){_("proxies",`Creating shared HTTPS server for ${z.length} domains on port ${Q}`,S);let A=await px(z,w,S),V=null,Z=x.onDemandTls,E=Z?.enabled?new Ux({config:Z,certsDir:Z.certsDir??x.productionCerts?.certsDir??rx.join(zx.homedir(),".stacks","rpx","on-demand-certs"),initial:N,verbose:S,onCertAdded:(Nx)=>{if(tx()==="restart")_("on-demand","certificate installed; restarting supervised gateway to reload TLS",S),setTimeout(()=>D.kill(D.pid,"SIGTERM"),10).unref();else Ax(Nx)}}):null,F=null,T=!1;async function Ax(Nx){if(F=Nx,T)return;T=!0;try{while(F){let hx=F;if(F=null,_("proxies",`rebuilding :${Q} with ${hx.length} SNI cert(s)`,S),V)h.delete(V),V.stop(!1);let jx=!1;for(let Kx=0;!jx&&Kx<60;Kx++){let mx=t({routeEntries:A,listenPort:Q,sslConfig:hx,originGuard:k,verbose:S});if(mx){V=mx,jx=!0;break}await new Promise((SR)=>setTimeout(SR,Math.min(25*2**Math.min(Kx,4),500)))}if(!jx)j.error(`rpx: CRITICAL — could not rebind :${Q} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{T=!1}}if(!await C(f,"0.0.0.0",S))ox(S,f,Q,x.acmeChallengeWebroot,E);if(await C(Q,"0.0.0.0",S)){if(_("proxies",`Port ${Q} is already in use, cannot start shared proxy`,S),S)j.warn(`Port ${Q} is in use. Shared HTTPS proxy cannot start.`);return}let RR=E&&E.sniEntries().length>0?E.sniEntries():X;if(V=t({routeEntries:A,listenPort:Q,sslConfig:RR,originGuard:k,verbose:S}),!V){j.error(`Shared HTTPS proxy failed to bind :${Q}; not exiting`);return}}else if(L){_("proxies",`Creating shared HTTP server for ${z.length} domains on port ${f}`,S);let A=await px(z,w,S);if(await C(f,"0.0.0.0",S)){if(_("proxies",`Port ${f} is already in use, cannot start shared proxy`,S),S)j.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!t({routeEntries:A,listenPort:f,sslConfig:null,originGuard:k,verbose:S})){j.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let A of z)try{let V=A.to||"rpx.localhost";_("proxy",`Starting proxy for ${V} with SSL config: ${!!X}`,A.verbose),await Px({from:A.from||"localhost:5173",to:V,cleanUrls:A.cleanUrls||!1,https:A.https||!1,cleanup:A.cleanup||!1,vitePluginUsage:A.vitePluginUsage||!1,verbose:A.verbose||!1,_cachedSSLConfig:x._cachedSSLConfig,changeOrigin:A.changeOrigin||!1,loadBalancer:A.loadBalancer,auth:A.auth,path:A.path,pathRewrites:A.pathRewrites})}catch(V){_("proxies",`Failed to start proxy for ${A.to}: ${V}`,A.verbose),j.error(`Failed to start proxy for ${A.to}:`,V)}}async function px(R,x,S){let w=[],K=new Set;for(let N of R){let z=N.to||"rpx.localhost",$=N.cleanUrls||!1,X=N.path,Y=Tx(X),B=_x(N.auth);if(N.redirect){let J=kx(N.redirect);w.push({host:z,path:X,route:{redirect:J,basePath:Y,auth:B}}),_("proxies",`Route: ${z}${X??""} → redirect ${J.status} ${J.to}${B?" (auth)":""}`,S)}else if(N.static)w.push({host:z,path:X,route:{static:Ix(N.static,$),cleanUrls:$,basePath:Y,auth:B}}),_("proxies",`Route: ${z}${X??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${B?" (auth)":""}`,S);else{let J=U(N.from),G=new URL(J.startsWith("http")?J:`http://${J}`),H=xx(N.from??G.host,N.loadBalancer);Rx(H),s.add(H),w.push({host:z,path:X,route:{sourceHost:G.host,upstreamPool:H,cleanUrls:$,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:Y,auth:B}}),_("proxies",`Route: ${z}${X??""} → ${G.host}${B?" (auth)":""}`,S)}if(K.has(z))continue;if(K.add(z),x&&!Wx(z)&&!z.includes("localhost")&&!z.includes("127.0.0.1"))try{if(!(await u([z],S))[0])await c([z],S)}catch{_("hosts",`Could not add hosts entry for ${z}`,S)}}return w}var O=null;function xR(){if(D.env.RPX_BIND_HOSTNAME)return D.env.RPX_BIND_HOSTNAME;if(O)return O;try{O=Object.values(zx.networkInterfaces()).flat().some((S)=>S&&S.family==="IPv6")?"::":"0.0.0.0"}catch{O="0.0.0.0"}return O}function t(R){let{routeEntries:x,listenPort:S,sslConfig:w,originGuard:K,verbose:N}=R,z=yx(x),$=fx((B,J)=>Cx(z,B,J),N),X=K?(B,J)=>K(B)??$(B,J):$,Y=Fx(N);try{let B=Bun.serve({port:S,hostname:xR(),reusePort:nx(),...w?{tls:gx(Array.isArray(w)?w.map((J)=>({serverName:J.serverName,key:J.key,cert:J.cert})):{key:w.key,cert:w.cert,ca:w.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(J,G){return X(J,G)},websocket:Y,error(J){return _("server",`Shared proxy server error: ${J}`,N),new Response(`Server Error: ${J.message}`,{status:500})}});return h.add(B),_("proxies",`Shared ${w?"HTTPS":"HTTP"} proxy listening on port ${S} for ${z.size} domains`,N),B}catch(B){return _("proxies",`Failed to start shared proxy: ${B}`,N),console.error("Failed to start shared proxy:",B),null}}function JR(R){if(R?.vitePluginUsage||!R?.verbose)return;if(console.log(""),console.log(` ${I.green(I.bold("rpx"))} ${I.green(`v${ix}`)}`),console.log(` ${I.green("➜")} ${I.dim(R?.from??"")} ${I.dim("➜")} ${I.cyan(R?.ssl?`https://${R?.to}`:`http://${R?.to}`)}`),R?.listenPort!==(R?.ssl?443:80))console.log(` ${I.green("➜")} Listening on port ${R?.listenPort}`);if(R?.cleanUrls)console.log(` ${I.green("➜")} Clean URLs enabled`)}var yS=Ox;export{Yx as writeEntry,H6 as watchRegistry,ZR as verifyHttpsChain,qR as trustRootCaForBrowsers,n6 as tearDownDevelopmentDns,d6 as syncDevelopmentDnsFromRegistry,rR as stripBasePath,Sx as stopHealthChecks,m6 as stopDnsServer,w4 as stopDaemon,Px as startServer,$R as startProxy,Ox as startProxies,Rx as startHealthChecks,h6 as startDnsServer,A6 as siteIdForHost,nx as shouldReusePort,a6 as setupResolver,p6 as setupDevelopmentDns,S6 as serverNameFromCertFilename,sR as serveStaticFile,lR as selectUpstream,y as safeStringify,gR as safeRelativePath,bS as safeDeleteFile,a as runViaDaemon,S4 as runDaemon,l6 as resolverFilePath,u6 as resolverBasenamesForDomains,c6 as resolverBasenameForDomain,Ix as resolveStaticRoute,tR as resolveStaticFile,kx as resolveRedirect,lS as resolvePathRewrite,_x as resolveAuth,E6 as renderStartingPage,k6 as renderFailedPage,y6 as removeStaleRpxHosts,g6 as removeResolver,i6 as removeLegacyTldResolvers,ux as removeHosts,$x as removeEntry,R4 as releaseDaemonLock,cS as redactSensitive,t6 as reconcileStaleDevelopmentDns,z4 as reconcileDevelopmentDnsOnIdle,j6 as readSiteManifest,J6 as readEntry,e6 as readDaemonPid,DR as readCertSha256Fingerprint,HR as readCertCommonName,V6 as readAll,Mx as readAcmeChallenge,TR as pruneStaleRootCas,N6 as projectNameFromHost,U as primaryUpstreamUrl,$6 as portManager,x6 as pathPrefixMatches,ER as parseSha256HashesFromSecurityListing,iR as parseHtpasswd,f6 as parseHostsLine,VR as normalizeSha256Fingerprint,Tx as normalizePathPrefix,U6 as normalizeDevDomain,Jx as matchesWildcard,_6 as matchesAllowedSuffix,Cx as matchHostRoute,R6 as matchHostList,oR as matchHost,bR as markSuccess,aR as markFailure,OR as loadSSLConfig,X6 as listDiscoverableSites,WR as listCertSha256HashesByCommonName,Wx as isWildcardPattern,PS as isValidRootCA,Xx as isValidId,mS as isSingleProxyOptions,vS as isSingleProxyConfig,yR as isRootCaTrustedForSsl,CR as isRootCaFingerprintInKeychains,CS as isProcessElevated,C as isPortInUse,B6 as isPidAlive,hS as isMultiProxyOptions,OS as isMultiProxyConfig,w6 as isLikelyHostname,v6 as isDnsServerRunning,o6 as isDaemonRunning,vR as isCertTrusted,o as httpsConfig,F6 as hostsLineMapsHost,dx as getSudoPassword,LR as getSharedDaemonCertPaths,PR as getRootCAPaths,Gx as getRegistryDir,LS as getPrimaryDomain,MR as getMacosTrustKeychains,FR as getMacosLoginKeychainPath,s6 as getDaemonRpxDir,r6 as getDaemonPidPath,e as generateCertificate,D6 as gcStaleEntries,hR as forceTrustCertificate,T6 as findStaleRpxHosts,Y6 as findAvailablePort,M6 as filterRpxHostsEntries,uS as extractHostname,z6 as expandHome,US as execSudoSync,Z6 as escapeHtml,Bx as ensureDaemonRunning,pR as enforceBasicAuth,W6 as dropStaleRpxHostsLines,cR as devSslToSniEntries,P6 as devDomainsFromHosts,K6 as detectProjectPreset,bx as deriveIdFromTarget,_4 as defaultDaemonSpawnCommand,r as defaultConfig,yS as default,_ as debugLog,xx as createUpstreamPool,G6 as createSiteResolver,Fx as createProxyWebSocketHandler,fx as createProxyFetchHandler,Vx as createOriginGuard,nR as contentTypeFor,b6 as contentLooksLikeRpxResolver,r as config,I as colors,mR as clearSslConfigCache,Ex as cleanupCertificates,v as cleanup,u as checkHosts,q as checkExistingCertificates,QR as certIncludesSanHostnames,qx as buildSniTlsConfig,uR as buildRegistryTlsProxyOptions,dR as buildRedirectLocation,yx as buildHostRoutes,qS as authorizeSystemAccess,c as addHosts,x4 as acquireDaemonLock,Q6 as SiteSupervisor,UR as SHARED_DEV_HOST_CERT_PATH,fR as RPX_ROOT_CA_COMMON_NAME,O6 as RPX_RESOLVER_MARKER,I6 as RPX_HOSTS_MARKER,Ux as OnDemandCertManager,IR as MACOS_SYSTEM_KEYCHAIN,kR as MACOS_CA_TRUST_FLAGS,q6 as LEGACY_TLD_RESOLVER_LABELS,cx as DefaultPortManager,C6 as DNS_STATE_VERSION,L6 as DNS_PORT,eR as ACME_CHALLENGE_PREFIX};
package/dist/start.d.ts CHANGED
@@ -24,6 +24,7 @@ export declare function startProxies(options?: ProxyOptions): Promise<void>;
24
24
  * whether TLS is terminated.
25
25
  */
26
26
  export declare function collectRouteEntries(proxyOptions: ProxyOption[], hostsEnabled: boolean, verbose: boolean): Promise<Array<{ host: string, path?: string, route: ProxyRoute }>>;
27
+ export declare function bindHostname(): string;
27
28
  /**
28
29
  * Create a single shared `Bun.serve` listener that routes every request by
29
30
  * `Host` header (and path) to the right upstream. When `sslConfig` is provided
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/rpx",
3
3
  "type": "module",
4
- "version": "0.11.39",
4
+ "version": "0.11.41",
5
5
  "description": "A modern and smart reverse proxy.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",