@stacksjs/rpx 0.11.22 → 0.11.23
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/bin/cli.js +99 -99
- package/dist/{chunk-ybpnwmfx.js → chunk-c5scw35a.js} +1 -1
- package/dist/{chunk-cqkz06bg.js → chunk-prvgnh82.js} +1 -1
- package/dist/{chunk-c9brkawa.js → chunk-q6q2dhrg.js} +1 -1
- package/dist/{chunk-cd843mzv.js → chunk-vy2pj4at.js} +93 -93
- package/dist/daemon.d.ts +10 -0
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/daemon.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { OnDemandCertManager } from './on-demand';
|
|
1
2
|
import type { OnDemandSitesConfig, OnDemandTlsConfig, ProductionTlsConfig, TlsOption } from './types';
|
|
2
3
|
import type { SiteSnapshot } from './site-supervisor';
|
|
3
4
|
export declare function getDaemonRpxDir(): string;
|
|
@@ -20,6 +21,14 @@ export declare function isDaemonRunning(rpxDir?: string): Promise<boolean>;
|
|
|
20
21
|
*/
|
|
21
22
|
export declare function acquireDaemonLock(rpxDir?: string): Promise<string>;
|
|
22
23
|
export declare function releaseDaemonLock(rpxDir?: string): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* The shared `:80` handler: serve ACME http-01 challenges, kick off on-demand
|
|
26
|
+
* issuance for an approved-but-uncovered host, then 301 to HTTPS. The request
|
|
27
|
+
* target is parsed defensively — scanners constantly send malformed/relative
|
|
28
|
+
* targets, and a thrown `new URL` would reject the fetch handler and make Bun
|
|
29
|
+
* drop the connection with no response. A bad target becomes a 400 instead.
|
|
30
|
+
*/
|
|
31
|
+
export declare function handleHttpRedirect(req: Request, onDemand: OnDemandCertManager | null, acmeChallengeWebroot?: string): Response;
|
|
23
32
|
// `opts` IS used throughout; pickier's no-unused-vars mis-fires on this fn after
|
|
24
33
|
// the on-demand serve refactor (its --fix would wrongly rename to `_opts`).
|
|
25
34
|
// eslint-disable-next-line pickier/no-unused-vars
|
|
@@ -73,6 +82,7 @@ export declare interface DaemonOptions {
|
|
|
73
82
|
productionCerts?: ProductionTlsConfig
|
|
74
83
|
onDemandTls?: OnDemandTlsConfig
|
|
75
84
|
onDemandSites?: OnDemandSitesConfig
|
|
85
|
+
acmeChallengeWebroot?: string
|
|
76
86
|
gcIntervalMs?: number
|
|
77
87
|
workers?: number
|
|
78
88
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as wR,$a as LS,A as C_,Aa as YS,B as U,Ba as $S,C as o,Ca as GS,D as WR,Da as XS,E as y_,Ea as JS,F as f_,Fa as QS,G as RR,Ga as VS,H as U_,Ha as ZS,I as zR,Ia as IS,J as P_,Ja as WS,K as MR,Ka as zS,L as L_,La as MS,M as O_,Ma as FS,N as c_,Na as TS,O as h_,P as m_,Pa as jS,Q as FR,Qa as xS,R as TR,Ra as HS,S as v_,Sa as kS,T as jR,Ta as wS,U as xR,Ua as ES,V as GR,Va as qS,W as u_,Wa as CS,X as HR,Xa as yS,Y as a_,Ya as fS,Z as kR,Za as US,_ as l_,_a as PS,a as G,aa as b_,ab as OS,b as s,ba as ER,bb as cS,c as B_,ca as p_,cb as hS,d as K_,da as d_,db as mS,e as Y_,ea as g_,eb as BR,f as $_,fa as i_,fb as vS,g as G_,ga as n_,gb as uS,h as X_,ha as r_,i as J_,ia as t_,j as Q_,ja as s_,k as V_,ka as e_,l as Z_,la as o_,m as I_,ma as C,n as W_,na as RS,o as z_,oa as qR,p as M_,pa as _S,q as F_,qa as SR,r as T_,ra as DR,s as j_,sa as SS,t as x_,ta as NR,u as H_,ua as AR,v as k_,va as DS,w as w_,wa as NS,x as E_,xa as AS,y as q_,ya as BS,z as e,za as KS}from"./chunk-vy2pj4at.js";import{hb as ZR,ib as h,jb as cR,kb as $N,lb as D,mb as vR,nb as GN,ob as E,pb as XN,qb as JN,rb as QN,sb as VN,tb as ZN,ub as IN,vb as WN,wb as zN,xb as MN}from"./chunk-prvgnh82.js";import{execSync as eR}from"node:child_process";import*as _R from"node:http";import*as uR from"node:net";import*as W from"node:process";var l=(_,R)=>(S)=>`\x1B[${_}m${S}\x1B[${R}m`,H={bold:l(1,22),dim:l(2,22),green:l(32,39),cyan:l(36,39)};import*as UR from"node:fs";import*as PR from"node:path";import*as k from"node:process";function LR(_,R){let A=(R&&R!=="/"?`${_}${R}`:_).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function b(_){if(_.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=_.verbose??!1,S=_.registryDir,A=new Set,B=_.proxies.map((V)=>{let I=V.id??LR(V.to,V.path);if(!DR(I))throw Error(`invalid registry id "${I}" derived from to="${V.to}"`);if(A.has(I))throw Error(`duplicate registry id "${I}" — set an explicit \`id\` on one of the proxies`);return A.add(I),{...V,id:I}}),N=new Date().toISOString();for(let V of B)await NR({id:V.id,from:V.from,to:V.to,path:V.path,pid:_.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:N,cleanUrls:V.cleanUrls,changeOrigin:V.changeOrigin,pathRewrites:V.pathRewrites,static:V.static},S,R);let K=await BR({rpxDir:_.rpxDir,verbose:R,spawnCommand:_.spawnCommand,startupTimeoutMs:_.startupTimeoutMs,spawnEnv:_.spawnEnv});for(let V of B){let I=V.static?`static ${typeof V.static==="string"?V.static:V.static.dir}`:V.from;G.success(`https://${V.to} → ${I}`)}if(G.info(`(via rpx daemon pid=${K.pid}; \`rpx daemon:status\` to inspect)`),_.detached)return;let Q=!1,Y=S??SR(),X=B.map((V)=>V.id),J=async()=>{if(Q)return;Q=!0;for(let V of X)await AR(V,S,R).catch((I)=>{D("runner",`removeEntry(${V}) failed: ${I}`,R)})},Z=(V)=>{D("runner",`received ${V}, unregistering ${X.length} entries`,R),J().finally(()=>k.exit(0))};k.once("SIGINT",Z),k.once("SIGTERM",Z),k.once("exit",()=>{if(Q)return;for(let V of X)try{UR.unlinkSync(PR.join(Y,`${V}.json`))}catch{}}),await new Promise(()=>{})}import{exec as dR}from"node:child_process";import q from"node:fs";import hR from"node:os";import YR from"node:path";import*as m from"node:process";import{promisify as gR}from"node:util";var c=gR(dR);function OR(_){let R=_.trim().toLowerCase();return R==="localhost"||R.endsWith(".localhost")||R.endsWith(".localhost.")}var x=m.platform==="win32"?YR.join(m.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",KR=!1;async function p(_){if(m.platform==="win32")throw Error("Administrator privileges required on Windows");if(cR()){let{stdout:A}=await c(_);return A}let R=h(),S=_.replace(/'/g,"'\\''");try{if(R){let{stdout:A}=await c(`echo '${R}' | sudo -S sh -c '${S}' 2>/dev/null`);return KR=!0,A}if(KR)try{let{stdout:A}=await c(`sudo -n sh -c '${S}'`);return A}catch(A){D("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await c(`sudo -n sh -c '${S}'`);return KR=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}async function y(_,R){let S=_.filter((B)=>!OR(B)),A=_.filter((B)=>OR(B));if(A.length>0)D("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,R);if(S.length===0)return;D("hosts",`Adding hosts: ${S.join(", ")}`,R),D("hosts",`Using hosts file at: ${x}`,R);try{let B;try{B=await q.promises.readFile(x,"utf-8")}catch{D("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{B=await p(`cat "${x}"`)}catch(Y){throw console.log(" Could not read hosts file — skipping hosts setup"),D("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let N=S.filter((Y)=>{let X=`127.0.0.1 ${Y}`,J=`::1 ${Y}`;return!B.includes(X)&&!B.includes(J)});if(N.length===0){D("hosts","All hosts already exist in hosts file",R);return}let K=N.map((Y)=>`
|
|
2
2
|
# Added by rpx
|
|
3
3
|
127.0.0.1 ${Y}
|
|
4
4
|
::1 ${Y}`).join(`
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
5
|
+
`),Q=YR.join(hR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await q.promises.writeFile(Q,B+K,"utf8"),await p(`cat "${Q}" | tee "${x}" > /dev/null`),console.log(` Hosts updated: ${N.join(", ")}`)}catch(Y){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),N.forEach((X)=>{console.log(` 127.0.0.1 ${X}`),console.log(` ::1 ${X}`)}),console.log(` Or run: sudo nano ${x}`)}finally{try{await q.promises.unlink(Q)}catch{}}}catch(B){D("hosts",`Failed to manage hosts file: ${B.message}`,R)}}async function $R(_,R){D("hosts",`Removing hosts: ${_.join(", ")}`,R);try{let S;try{S=await q.promises.readFile(x,"utf-8")}catch{D("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{S=await p(`cat "${x}"`)}catch(Y){throw D("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let A=S.split(`
|
|
6
|
+
`),B=!1,N=A.filter((Y)=>{if(_.some((J)=>Y.includes(` ${J}`)&&(Y.includes("127.0.0.1")||Y.includes("::1"))))return B=!0,!1;if(Y.trim()==="# Added by rpx")return B=!0,!1;return!0});if(!B){D("hosts","No matching hosts found to remove",R);return}while(N[N.length-1]?.trim()==="")N.pop();let K=`${N.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`,
|
|
9
|
-
`,A=(Y)=>{let J=i(Y);return D.has(J)||B.some((Q)=>GR(J,Q))},V=(Y)=>{let J=RS(Y);if(!A(J))return;let Q="/";try{Q=new URL(Y.url).pathname}catch{}if(K.some((Z)=>Q.startsWith(Z)))return;if(eR(Y.headers.get(R),S.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return V.protects=A,V}import*as hR from"node:fs";import*as uR from"node:path";var QR="/.well-known/acme-challenge/";function VR(S,R){if(!S||!R.startsWith(QR))return null;let D=R.slice(QR.length);if(!D||!/^[A-Za-z0-9_-]+$/.test(D))return null;try{return hR.readFileSync(uR.join(S,D),"utf8")}catch{return null}}var r=new g,DS="0.12.0",_S=new CR("0.0.0.0"),t=new Set,XR=!1,n=null,ZR=null;async function u(S){if(XR)return _("cleanup","Cleanup already in progress, skipping",S?.verbose),ZR||Promise.resolve();XR=!0,_("cleanup","Starting cleanup process",S?.verbose),ZR=new Promise((R)=>{n=R});try{await r.stopAll(S?.verbose),G.info("Shutting down proxy servers...");let R=[],D=Array.from(t).map((B)=>new Promise((K)=>{let N=B;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",S?.verbose),K();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){_("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));if(R.push(...D),t.clear(),S?.hosts&&S.domains?.length){_("cleanup","Cleaning up hosts file entries",S?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let B=S.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(B)}`,S?.verbose),B.length>0)G.info("Cleaning up hosts file entries..."),R.push($R(B,S?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${B.join(", ")}`,S?.verbose)}).catch((K)=>{_("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),G.warn(`Failed to clean up hosts file entries for ${B.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){_("cleanup","Cleaning up SSL certificates",S?.verbose),G.info("Cleaning up SSL certificates...");let B=S.domains.map(async(K)=>{try{await FR(K,S?.verbose),_("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${K}: ${N}`,S?.verbose),G.warn(`Failed to clean up certificates for ${K}:`,N)}});R.push(...B)}await Promise.allSettled(R),_("cleanup","All cleanup tasks completed successfully",S?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){_("cleanup",`Error during cleanup: ${R}`,S?.verbose),G.error("Error during cleanup:",R)}finally{if(n)n();n=null,XR=!1;let R=S&&"vitePluginUsage"in S&&S.vitePluginUsage===!0;if(z.env.NODE_ENV!=="test"&&z.env.BUN_ENV!=="test"&&!R)z.exit(0)}return ZR}var WR=!1;function pR(S){if(WR){_("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}WR=!0,_("signal",`Received ${S} signal, initiating cleanup`,!0),u().catch((R)=>{_("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{WR=!1})}z.once("SIGINT",()=>pR("SIGINT"));z.once("SIGTERM",()=>pR("SIGTERM"));z.on("uncaughtException",(S)=>{G.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{G.error("Unhandled rejection (continuing):",S)});async function h(S,R,D,B=5){_("connection",`Testing connection to ${S}:${R} (retries left: ${B})`,D);let K=15000,N=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,D);return}let A=()=>new Promise((V,Y)=>{let J=aR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{_("connection",`Successfully connected to ${S}:${R}`,D),J.end(),V()}),J.once("timeout",()=>{_("connection",`Connection to ${S}:${R} timed out`,D),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(Q)=>{_("connection",`Failed to connect to ${S}:${R}: ${Q}`,D),J.destroy(),Y(Q)})});try{await A()}catch(V){let Y=V;if(Date.now()-N>K){_("connection",`Connection test timed out after ${K}ms, but continuing anyway`,D),G.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&B>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${B} retries left)`,D),await new Promise((Q)=>setTimeout(Q,2000)),h(S,R,D,B-1);if(B>0)try{_("connection",`Trying HTTP request to ${S}:${R}`,D),await new Promise((Q,Z)=>{let X=SR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(W)=>{_("connection",`Received HTTP response with status: ${W.statusCode}`,D),Q()});X.on("error",(W)=>Z(W)),X.on("timeout",()=>{X.destroy(),Z(Error("HTTP request timed out"))}),X.end()}),_("connection",`HTTP request to ${S}:${R} succeeded`,D);return}catch(Q){return _("connection",`HTTP request to ${S}:${R} failed: ${Q}`,D),_("connection",`Retrying socket connection in 2 seconds... (${B} retries left)`,D),await new Promise((Z)=>setTimeout(Z,2000)),h(S,R,D,B-1)}let J=`Failed to connect to ${S}:${R} after ${5-B} attempts: ${Y.message}`;_("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,D),G.warn(J),G.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 yR(S){_("server",`Starting server with options: ${E(S)}`,S.verbose);let R=new URL((S.from?.startsWith("http")?S.from:`http://${S.from}`)||"localhost:5173"),D=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),B=Number.parseInt(R.port)||(R.protocol.includes("https:")?443:80),K=[D.hostname];if(fR(S)&&!D.hostname.includes("localhost")&&!D.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${D.hostname}`,S?.verbose);try{if(!(await f(K,S.verbose))[0]){G.info(`Adding ${D.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(K,S.verbose)}catch(V){if(G.error("Failed to add hosts entry:",V.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${D.hostname}`),G.warn(`::1 ${D.hostname}`),z.platform==="win32")G.warn("On Windows:"),G.warn("1. Run notepad as administrator"),G.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else G.warn("On Unix systems:"),G.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${D.hostname}`,S.verbose)}catch(A){G.error("Failed to check hosts file:",A.message)}}try{await h(R.hostname,B,S.verbose)}catch(A){_("server",`Connection test failed: ${A}`,S.verbose),G.error(A.message),G.warn("Continuing with proxy setup despite connection test failure..."),G.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let N=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=o({...S,to:D.hostname});if(N=await U({...S,to:D.hostname,https:S.https}),!N){if(_("ssl",`Generating new certificates for ${D.hostname}`,S.verbose),await e({...S,from:R.toString(),to:D.hostname,https:S.https}),N=await U({...S,to:D.hostname,https:S.https}),!N)throw Error(`Failed to load SSL configuration after generating certificates for ${D.hostname}`)}}catch(A){throw _("server",`SSL setup failed: ${A}`,S.verbose),A}_("server",`Setting up reverse proxy with SSL config for ${D.hostname}`,S.verbose),await BS({...S,from:S.from||"localhost:5173",to:D.hostname,fromPort:B,sourceUrl:{hostname:R.hostname,host:R.host},ssl:N})}async function NS(S,R,D,B,K,N,A,V,Y,J){_("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${V}`,A);let Q=[{host:R,route:{sourceHost:B.host,cleanUrls:V||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!IR({routeEntries:Q,listenPort:D,sslConfig:K,originGuard:null,verbose:A??!1}))throw Error(`Failed to start proxy server for ${R} on port ${D}`);YS({from:S,to:R,vitePluginUsage:N,listenPort:D,ssl:!!K,cleanUrls:V,verbose:A})}async function BS(S){_("setup",`Setting up reverse proxy: ${E(S)}`,S.verbose);let{from:R,to:D,sourceUrl:B,ssl:K,verbose:N,cleanup:A,vitePluginUsage:V,changeOrigin:Y,cleanUrls:J}=S,Q=80,Z=443,X="0.0.0.0",W=S.portManager||_S,P=fR(S);try{if(P&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1")){if(!(await f([D],N))[0]){G.warn(`The hostname ${D} isn't in your hosts file. Adding it now...`);try{await y([D],N),G.success(`Added ${D} to your hosts file.`)}catch(L){G.error(`Failed to add ${D} to your hosts file: ${L}`),G.info(`You may need to manually add '127.0.0.1 ${D}' to your /etc/hosts file.`)}}}else if(P&&z.platform!=="darwin"&&D&&D.includes("localhost")&&!D.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await f([D],N))[0]){_("hosts",`${D} not found in hosts file, adding...`,N);try{await y([D],N)}catch(L){_("hosts",`Failed to add ${D} to hosts file: ${L}`,N)}}}if(K&&!W.usedPorts.has(Q)){if(!await C(Q,X,N))_("setup","Starting HTTP redirect server",N),dR(N),W.usedPorts.add(Q);else if(_("setup","Port 80 is in use, skipping HTTP redirect",N),N)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let x=K?Z:Q,w=await C(x,X,N),F;if(w){if(_("setup",`Port ${x} is already in use`,N),N)G.warn(`Port ${x} is already in use. This may be another instance of rpx or another service.`);if(x===443){if(F=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at https://${D}:${F}`)}else if(F=await W.getNextAvailablePort(x+1000,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at http://${D}:${F}`)}else F=x,W.usedPorts.add(F),_("setup",`Using standard ${x===443?"HTTPS":"HTTP"} port ${x} for ${D}`,N);await NS(R,D,F,B,K,V,N,J,Y,RR(S.auth))}catch(x){_("setup",`Setup failed: ${x}`,N),G.error(`Failed to setup reverse proxy: ${x.message}`),u({domains:[D],hosts:typeof A==="boolean"?A:A?.hosts,certs:typeof A==="boolean"?A:A?.certs,verbose:N,vitePluginUsage:V})}}function dR(S,R=80,D=443,B){_("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=SR.createServer((N,A)=>{if(B&&N.url){let Q=N.url.split("?",1)[0],Z=VR(B,Q);if(Z!=null){_("redirect",`Serving ACME challenge ${Q}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let V=N.headers.host||"",Y=V.includes(":")?V.slice(0,V.indexOf(":")):V,J=D===443?Y:`${Y}:${D}`;_("redirect",`Redirecting request from ${V}${N.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${N.url}`}),A.end()}).listen(R);t.add(K),_("redirect","HTTP redirect server started",S)}function KS(S){let R={...s,...S};if(_("proxy",`Starting proxy with options: ${E(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}a({proxies:[{id:R.id,from:R.from,to:R.to,path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}],verbose:R.verbose}).catch((Y)=>{G.error(`Failed to register with rpx daemon: ${Y.message}`),z.exit(1)});return}let D=R.to||"",B=D.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&N.includes(B)&&R?.verbose)G.warn(`The .${B} TLD may not work reliably for local development`),G.info(` Google owns .${B} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-ybpnwmfx.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[D],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(B))G.success(`DNS server started for .${B} domains`);else G.success(`DNS server started for .${B} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${D} may not resolve in browser`,R.verbose)})}).catch((Y)=>{_("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let V={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:o(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};_("proxy",`Server options: ${E(V)}`,R.verbose),yR(V).catch((Y)=>{_("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),u({domains:[R.to],hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose})})}function AS(S){return S?.verbose||!1}function fR(S){if(S?.hostsManagement===!1)return!1;let R=S?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function UR(S){let R={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(S)R={...R,...S};let D=AS(R),B=fR(R);if(_("config",`Starting with config: ${E(R,2)}`,D),_("config",`Is multi-proxy? ${"proxies"in R}`,D),_("config",`Hosts management enabled? ${B}`,D),R.viaDaemon){let I="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??R.cleanUrls,changeOrigin:M.changeOrigin??R.changeOrigin,pathRewrites:M.pathRewrites})):[{id:R.id,from:R.from,to:R.to??"rpx.localhost",path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}];await a({proxies:I,verbose:D});return}if("proxies"in R&&Array.isArray(R.proxies)){_("servers",`Found ${R.proxies.length} proxies in config`,D);for(let $ of R.proxies)if($.start){let I=`${$.from}-${$.to}`;try{_("watch",`Starting command for ${I} with command: ${$.start.command}`,D),G.info(`Starting command for ${I}...`),await r.startProcess(I,$.start,D);let M=new URL($.from?.startsWith("http")?$.from:`http://${$.from}`),T=M.hostname||"localhost",b=Number(M.port)||80;try{await h(T,b,D),_("watch",`Dev server is ready at ${T}:${b}`,D)}catch(iR){_("watch",`Connection check failed, but continuing with proxy setup: ${iR}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw _("watch",`Failed to start command for ${I}: ${M}`,D),Error(`Failed to start command for ${I}: ${M}`)}}else _("watch",`No start command for proxy ${$.from} -> ${$.to}`,D)}else if("start"in R&&R.start){_("watch","Found start command in single proxy config",D);let $=`${R.from}-${R.to}`;try{if(R.start)_("watch",`Starting command: ${R.start.command}`,D),await r.startProcess($,R.start,D);let I=new URL(R.from?.startsWith("http")?R.from:`http://${R.from}`),M=I.hostname||"localhost",T=Number(I.port)||80;try{await h(M,T,D),_("watch",`Dev server is ready at ${M}:${T}`,D)}catch(b){_("watch",`Connection check failed, but continuing with proxy setup: ${b}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw _("watch",`Failed to run start command: ${I}`,D),Error(`Failed to run start command: ${I}`)}}else _("watch","No start command found in config",D);let K="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(z.platform!=="win32"&&(R.https||B)){if(!m())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",D),SS("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",D)}}let N=[];if(R.productionCerts){if(N=await qR(R.productionCerts,D),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map(($)=>$.serverName).join(", ")}`,D)}if(R.https){let $=N.length>0?null:await U(R);if(!$&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await e(R),$=await U(R),!$)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else _("ssl",`Using existing and trusted certificates for ${K}`,R.verbose);R._cachedSSLConfig=$}let A="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map(($)=>({...$,https:R.https,cleanup:R.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:$.changeOrigin??R.changeOrigin,verbose:D,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,auth:"auth"in R?R.auth:void 0,verbose:D,_cachedSSLConfig:R._cachedSSLConfig}],V=A.map(($)=>$.to||"rpx.localhost"),Y=N.length>0?N:R._cachedSSLConfig??null,J=V.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),Q=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],X=[...new Set(J.map(($)=>$.split(".").pop()?.toLowerCase()))],W=X.filter(($)=>!!$&&Q.includes($));if(W.length>0&&D)G.warn(`The following TLDs may not work reliably for local development: ${W.map(($)=>`.${$}`).join(", ")}`),G.info(" These TLDs have HSTS preloading which can bypass local DNS"),G.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(B&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:$}=await import("./chunk-ybpnwmfx.js");if(await $({domains:J,verbose:D})){if(D)if(X.every((T)=>!!T&&Z.includes(T)))G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains`);else G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",D)}let P=async()=>{_("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-ybpnwmfx.js");await $({verbose:R.verbose})}catch($){_("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await r.stopAll(R.verbose)}catch($){_("cleanup",`Error stopping processes: ${$}`,R.verbose)}await u({domains:V,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};z.on("SIGINT",P),z.on("SIGTERM",P);let x=R.singlePortMode===!0,w=R.httpsPort??443,F=R.httpPort??80,O=R.originGuard?JR(R.originGuard):null,L=!!Y&&(A.length>1||x),gR=!Y&&x&&A.length>0;if(L&&Y){_("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${w}`,D);let $=await bR(A,B,D);if(!await C(F,"0.0.0.0",D))dR(D,F,w,R.acmeChallengeWebroot);if(await C(w,"0.0.0.0",D)){if(_("proxies",`Port ${w} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${w} is in use. Shared HTTPS proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:w,sslConfig:Y,originGuard:O,verbose:D})){G.error(`Shared HTTPS proxy failed to bind :${w}; not exiting`);return}}else if(gR){_("proxies",`Creating shared HTTP server for ${A.length} domains on port ${F}`,D);let $=await bR(A,B,D);if(await C(F,"0.0.0.0",D)){if(_("proxies",`Port ${F} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${F} is in use. Shared HTTP proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:F,sslConfig:null,originGuard:O,verbose:D})){G.error(`Shared HTTP proxy failed to bind :${F}; not exiting`);return}}else for(let $ of A)try{let I=$.to||"rpx.localhost";_("proxy",`Starting proxy for ${I} with SSL config: ${!!Y}`,$.verbose),await yR({from:$.from||"localhost:5173",to:I,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1})}catch(I){_("proxies",`Failed to start proxy for ${$.to}: ${I}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,I)}}async function bR(S,R,D){let B=[],K=new Set;for(let N of S){let A=N.to||"rpx.localhost",V=N.cleanUrls||!1,Y=N.path,J=kR(Y),Q=RR(N.auth);if(N.redirect){let Z=MR(N.redirect);B.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${Q?" (auth)":""}`,D)}else if(N.static)B.push({host:A,path:Y,route:{static:xR(N.static,V),cleanUrls:V,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${Q?" (auth)":""}`,D);else{let Z=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);B.push({host:A,path:Y,route:{sourceHost:Z.host,cleanUrls:V,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → ${Z.host}${Q?" (auth)":""}`,D)}if(K.has(A))continue;if(K.add(A),R&&!HR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await f([A],D))[0])await y([A],D)}catch{_("hosts",`Could not add hosts entry for ${A}`,D)}}return B}function IR(S){let{routeEntries:R,listenPort:D,sslConfig:B,originGuard:K,verbose:N}=S,A=wR(R),V=TR((Q,Z)=>ER(A,Q,Z),N),Y=K?(Q,Z)=>K(Q)??V(Q,Z):V,J=jR(N);try{let Q=Bun.serve({port:D,hostname:"0.0.0.0",reusePort:lR(),...B?{tls:Array.isArray(B)?B.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:B.key,cert:B.cert,ca:B.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,X){return Y(Z,X)},websocket:J,error(Z){return _("server",`Shared proxy server error: ${Z}`,N),new Response(`Server Error: ${Z.message}`,{status:500})}});return t.add(Q),_("proxies",`Shared ${B?"HTTPS":"HTTP"} proxy listening on port ${D} for ${A.size} domains`,N),Q}catch(Q){return _("proxies",`Failed to start shared proxy: ${Q}`,N),console.error("Failed to start shared proxy:",Q),null}}function YS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${DS}`)}`),console.log(` ${H.green("➜")} ${H.dim(S?.from??"")} ${H.dim("➜")} ${H.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var JN=UR;export{NR as writeEntry,YD as watchRegistry,VS as verifyHttpsChain,HS as trustRootCaForBrowsers,yD as tearDownDevelopmentDns,CD as syncDevelopmentDnsFromRegistry,bS as stripBasePath,TD as stopDnsServer,bD as stopDaemon,yR as startServer,KS as startProxy,UR as startProxies,xD as startDnsServer,tS as siteIdForHost,lR as shouldReusePort,wD as setupResolver,qD as setupDevelopmentDns,dS as serverNameFromCertFilename,uS as serveStaticFile,E as safeStringify,vS as safeRelativePath,TN as safeDeleteFile,a as runViaDaemon,hD as runDaemon,HD as resolverFilePath,zD as resolverBasenamesForDomains,WD as resolverBasenameForDomain,xR as resolveStaticRoute,hS as resolveStaticFile,MR as resolveRedirect,xN as resolvePathRewrite,RR as resolveAuth,JD as renderStartingPage,QD as renderFailedPage,fD as removeResolver,ED as removeLegacyTldResolvers,$R as removeHosts,BR as removeEntry,vD as releaseDaemonLock,VN as redactSensitive,UD as reconcileStaleDevelopmentDns,lD as reconcileDevelopmentDnsOnIdle,eS as readSiteManifest,BD as readEntry,LD as readDaemonPid,GS as readCertSha256Fingerprint,JS as readCertCommonName,KD as readAll,VR as readAcmeChallenge,xS as pruneStaleRootCas,sS as projectNameFromHost,_D as portManager,aS as pathPrefixMatches,XS as parseSha256HashesFromSecurityListing,OS as parseHtpasswd,$S as normalizeSha256Fingerprint,kR as normalizePathPrefix,ZD as normalizeDevDomain,GR as matchesWildcard,gS as matchesAllowedSuffix,ER as matchHostRoute,pS as matchHostList,lS as matchHost,yS as loadSSLConfig,SD as listDiscoverableSites,MS as listCertSha256HashesByCommonName,HR as isWildcardPattern,ZN as isValidRootCA,_R as isValidId,FN as isSingleProxyOptions,MN as isSingleProxyConfig,TS as isRootCaTrustedForSsl,jS as isRootCaFingerprintInKeychains,mR as isProcessElevated,C as isPortInUse,ND as isPidAlive,IN as isMultiProxyOptions,zN as isMultiProxyConfig,iS as isLikelyHostname,jD as isDnsServerRunning,cD as isDaemonRunning,PS as isCertTrusted,o as httpsConfig,m as getSudoPassword,CS as getSharedDaemonCertPaths,qS as getRootCAPaths,DR as getRegistryDir,WN as getPrimaryDomain,FS as getMacosTrustKeychains,IS as getMacosLoginKeychainPath,PD as getDaemonRpxDir,OD as getDaemonPidPath,e as generateCertificate,AD as gcStaleEntries,fS as forceTrustCertificate,DD as findAvailablePort,XN as extractHostname,rS as expandHome,QN as execSudoSync,GD as escapeHtml,KR as ensureDaemonRunning,LS as enforceBasicAuth,wS as devSslToSniEntries,ID as devDomainsFromHosts,oS as detectProjectPreset,LR as deriveIdFromTarget,uD as defaultDaemonSpawnCommand,s as defaultConfig,JN as default,_ as debugLog,RD as createSiteResolver,jR as createProxyWebSocketHandler,TR as createProxyFetchHandler,JR as createOriginGuard,mS as contentTypeFor,kD as contentLooksLikeRpxResolver,s as config,H as colors,US as clearSslConfigCache,FR as cleanupCertificates,u as cleanup,f as checkHosts,U as checkExistingCertificates,QS as certIncludesSanHostnames,qR as buildSniTlsConfig,ES as buildRegistryTlsProxyOptions,cS as buildRedirectLocation,wR as buildHostRoutes,y as addHosts,mD as acquireDaemonLock,$D as SiteSupervisor,kS as SHARED_DEV_HOST_CERT_PATH,zS as RPX_ROOT_CA_COMMON_NAME,MD as RPX_RESOLVER_MARKER,nS as OnDemandCertManager,WS as MACOS_SYSTEM_KEYCHAIN,ZS as MACOS_CA_TRUST_FLAGS,XD as LEGACY_TLD_RESOLVER_LABELS,CR as DefaultPortManager,VD as DNS_STATE_VERSION,FD as DNS_PORT,QR as ACME_CHALLENGE_PREFIX};
|
|
8
|
+
`,Q=YR.join(hR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await q.promises.writeFile(Q,K,"utf8"),await p(`cat "${Q}" | tee "${x}" > /dev/null`),D("hosts","Hosts removed successfully",R)}catch(Y){D("hosts","Could not clean up hosts file automatically",R)}finally{try{await q.promises.unlink(Q)}catch(Y){D("hosts",`Failed to remove temporary file: ${Y}`,R)}}}catch(S){D("hosts",`Failed to clean up hosts file: ${S.message}`,R)}}async function f(_,R){D("hosts",`Checking hosts: ${_}`,R);let S;try{S=await q.promises.readFile(x,"utf-8")}catch(A){D("hosts",`Error reading hosts file: ${A}`,R);try{let B=h(),N;if(B)N=`echo '${B}' | sudo -S cat "${x}" 2>/dev/null`;else N=`sudo -n cat "${x}" 2>/dev/null || cat "${x}" 2>/dev/null || echo ""`;let{stdout:K}=await c(N);S=K}catch(B){return D("hosts",`Cannot read hosts file, assuming entries don't exist: ${B}`,R),_.map(()=>!1)}}return _.map((A)=>{let B=`127.0.0.1 ${A}`,N=`::1 ${A}`;return S.includes(B)||S.includes(N)})}import{spawn as iR}from"node:child_process";import*as d from"node:process";class g{processes=new Map;isShuttingDown=!1;async startProcess(_,R,S){if(this.processes.has(_)){D("start",`Process ${_} is already running`,S);return}let[A,...B]=R.command.split(" "),N=R.cwd||d.cwd();D("start",`Starting process ${_}:`,S),D("start",` Command: ${A} ${B.join(" ")}`,S),D("start",` Working directory: ${N}`,S),D("start",` Environment variables: ${E(R.env)}`,S);let K=iR(A,B,{cwd:N,env:{...d.env,...R.env},shell:!0,stdio:"inherit"});return this.processes.set(_,{command:R.command,cwd:N,process:K,env:R.env}),new Promise((Q,Y)=>{if(K.on("error",(X)=>{if(!this.isShuttingDown)D("start",`Process ${_} failed to start: ${X}`,S),this.processes.delete(_),Y(X)}),K.on("exit",(X)=>{if(!this.isShuttingDown&&X!==null&&X!==0)D("start",`Process ${_} exited with code ${X}; leaving the proxy running`,S),this.processes.delete(_),Y(Error(`Process ${_} exited with code ${X}`))}),S)K.stdout?.on("data",(X)=>{D("process",`[${_}] ${X.toString().trim()}`,!0)}),K.stderr?.on("data",(X)=>{D("process",`[${_}] ERR: ${X.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&K.killed)this.processes.delete(_),Y(Error(`Process ${_} was killed during startup`));else D("start",`Process ${_} started successfully`,S),Q()},1000)})}async stopProcess(_,R){let S=this.processes.get(_);if(!S?.process){D("start",`No process found for ${_}`,R);return}return D("start",`Stopping process ${_}`,R),new Promise((A)=>{if(!S.process){A();return}S.process.once("exit",()=>{this.processes.delete(_),D("start",`Process ${_} stopped`,R),A()});try{S.process.kill("SIGTERM"),setTimeout(()=>{if(S.process){D("start",`Force killing process ${_}`,R);try{S.process.kill("SIGKILL")}catch(B){}}},3000)}catch(B){D("start",`Error stopping process ${_}: ${B}`,R),this.processes.delete(_),A()}})}async stopAll(_){if(this.isShuttingDown){D("start","Already shutting down, skipping duplicate stopAll call",_);return}this.isShuttingDown=!0,D("start","Stopping all processes",_);let R=Array.from(this.processes.keys()).map((S)=>this.stopProcess(S,_).catch((A)=>{G.error(`Failed to stop process ${S}:`,A)}));await Promise.allSettled(R),this.processes.clear(),this.isShuttingDown=!1}isRunning(_){let R=this.processes.get(_);return!!R?.process&&!R.process.killed}}var DD=new g;import{timingSafeEqual as nR}from"node:crypto";function rR(_,R){if(_==null)return!1;let S=Buffer.from(_),A=Buffer.from(R);if(S.length!==A.length)return!1;return nR(S,A)}function i(_){return _.toLowerCase().replace(/\.$/,"")}var tR=["/.well-known/acme-challenge/"];function sR(_){let R=_.headers.get("host");if(R)return i(R.split(":")[0]);try{return i(new URL(_.url).hostname)}catch{return""}}function XR(_){let R=_.header.toLowerCase(),S=new Set,A=[];for(let Y of _.hosts){let X=i(Y);if(X.startsWith("*."))A.push(X);else S.add(X)}let B=_.exemptPaths??tR,N=_.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
9
|
+
`,K=(Y)=>{let X=i(Y);return S.has(X)||A.some((J)=>GR(X,J))},Q=(Y)=>{let X=sR(Y);if(!K(X))return;let J="/";try{J=new URL(Y.url).pathname}catch{}if(B.some((Z)=>J.startsWith(Z)))return;if(rR(Y.headers.get(R),_.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return Q.protects=K,Q}var r=new g,oR="0.12.0",R_=new qR("0.0.0.0"),t=new Set,JR=!1,n=null,QR=null;async function u(_){if(JR)return D("cleanup","Cleanup already in progress, skipping",_?.verbose),QR||Promise.resolve();JR=!0,D("cleanup","Starting cleanup process",_?.verbose),QR=new Promise((R)=>{n=R});try{await r.stopAll(_?.verbose),G.info("Shutting down proxy servers...");let R=[],S=Array.from(t).map((A)=>new Promise((B)=>{let N=A;try{if(typeof N.stop==="function")N.stop(!0),D("cleanup","Bun server stopped",_?.verbose),B();else if(typeof N.close==="function")N.close(()=>{D("cleanup","Server closed successfully",_?.verbose),B()});else B()}catch(K){D("cleanup",`Error stopping server: ${K}`,_?.verbose),B()}}));if(R.push(...S),t.clear(),_?.hosts&&_.domains?.length){D("cleanup","Cleaning up hosts file entries",_?.verbose),D("cleanup",`Original domains for cleanup: ${JSON.stringify(_.domains)}`,_?.verbose);let A=_.domains.filter((B)=>{if(B==="test.local")return!0;return B!=="localhost"&&!B.startsWith("localhost.")&&B!=="127.0.0.1"});if(D("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,_?.verbose),A.length>0)G.info("Cleaning up hosts file entries..."),R.push($R(A,_?.verbose).then(()=>{D("cleanup",`Removed hosts entries for ${A.join(", ")}`,_?.verbose)}).catch((B)=>{D("cleanup",`Failed to remove hosts entries: ${B}`,_?.verbose),G.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,B)}))}if(_?.certs&&_.domains?.length){D("cleanup","Cleaning up SSL certificates",_?.verbose),G.info("Cleaning up SSL certificates...");let A=_.domains.map(async(B)=>{try{await WR(B,_?.verbose),D("cleanup",`Removed certificates for ${B}`,_?.verbose)}catch(N){D("cleanup",`Failed to remove certificates for ${B}: ${N}`,_?.verbose),G.warn(`Failed to clean up certificates for ${B}:`,N)}});R.push(...A)}await Promise.allSettled(R),D("cleanup","All cleanup tasks completed successfully",_?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){D("cleanup",`Error during cleanup: ${R}`,_?.verbose),G.error("Error during cleanup:",R)}finally{if(n)n();n=null,JR=!1;let R=_&&"vitePluginUsage"in _&&_.vitePluginUsage===!0;if(W.env.NODE_ENV!=="test"&&W.env.BUN_ENV!=="test"&&!R)W.exit(0)}return QR}var VR=!1;function aR(_){if(VR){D("signal",`Received second ${_} signal, forcing exit`,!0),W.exit(1);return}VR=!0,D("signal",`Received ${_} signal, initiating cleanup`,!0),u().catch((R)=>{D("signal",`Cleanup failed after ${_}: ${R}`,!0),W.exit(1)}).finally(()=>{VR=!1})}W.once("SIGINT",()=>aR("SIGINT"));W.once("SIGTERM",()=>aR("SIGTERM"));W.on("uncaughtException",(_)=>{G.error("Uncaught exception (continuing):",_)});W.on("unhandledRejection",(_)=>{G.error("Unhandled rejection (continuing):",_)});async function v(_,R,S,A=5){D("connection",`Testing connection to ${_}:${R} (retries left: ${A})`,S);let B=15000,N=Date.now();if(W.env.RPX_BYPASS_CONNECTION_TEST==="true"){D("connection",`Bypassing connection test for ${_}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,S);return}let K=()=>new Promise((Q,Y)=>{let X=uR.connect({host:_,port:R,timeout:3000});X.once("connect",()=>{D("connection",`Successfully connected to ${_}:${R}`,S),X.end(),Q()}),X.once("timeout",()=>{D("connection",`Connection to ${_}:${R} timed out`,S),X.destroy(),Y(Error("Connection timed out"))}),X.once("error",(J)=>{D("connection",`Failed to connect to ${_}:${R}: ${J}`,S),X.destroy(),Y(J)})});try{await K()}catch(Q){let Y=Q;if(Date.now()-N>B){D("connection",`Connection test timed out after ${B}ms, but continuing anyway`,S),G.warn(`Connection test to ${_}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&A>0)return D("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,S),await new Promise((J)=>setTimeout(J,2000)),v(_,R,S,A-1);if(A>0)try{D("connection",`Trying HTTP request to ${_}:${R}`,S),await new Promise((J,Z)=>{let V=_R.request({hostname:_,port:R,path:"/",method:"HEAD",timeout:5000},(I)=>{D("connection",`Received HTTP response with status: ${I.statusCode}`,S),J()});V.on("error",(I)=>Z(I)),V.on("timeout",()=>{V.destroy(),Z(Error("HTTP request timed out"))}),V.end()}),D("connection",`HTTP request to ${_}:${R} succeeded`,S);return}catch(J){return D("connection",`HTTP request to ${_}:${R} failed: ${J}`,S),D("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,S),await new Promise((Z)=>setTimeout(Z,2000)),v(_,R,S,A-1)}let X=`Failed to connect to ${_}:${R} after ${5-A} attempts: ${Y.message}`;D("connection",`${X}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,S),G.warn(X),G.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 CR(_){D("server",`Starting server with options: ${E(_)}`,_.verbose);let R=new URL((_.from?.startsWith("http")?_.from:`http://${_.from}`)||"localhost:5173"),S=new URL((_.to?.startsWith("http")?_.to:`http://${_.to}`)||"rpx.localhost"),A=Number.parseInt(R.port)||(R.protocol.includes("https:")?443:80),B=[S.hostname];if(yR(_)&&!S.hostname.includes("localhost")&&!S.hostname.includes("127.0.0.1")){D("hosts",`Checking if hosts file entry exists for: ${S.hostname}`,_?.verbose);try{if(!(await f(B,_.verbose))[0]){G.info(`Adding ${S.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(B,_.verbose)}catch(Q){if(G.error("Failed to add hosts entry:",Q.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${S.hostname}`),G.warn(`::1 ${S.hostname}`),W.platform==="win32")G.warn("On Windows:"),G.warn("1. Run notepad as administrator"),G.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else G.warn("On Unix systems:"),G.warn("sudo nano /etc/hosts")}}else D("hosts",`Host entry already exists for ${S.hostname}`,_.verbose)}catch(K){G.error("Failed to check hosts file:",K.message)}}try{await v(R.hostname,A,_.verbose)}catch(K){D("server",`Connection test failed: ${K}`,_.verbose),G.error(K.message),G.warn("Continuing with proxy setup despite connection test failure..."),G.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let N=_._cachedSSLConfig||null;if(_.https)try{if(_.https===!0)_.https=o({..._,to:S.hostname});if(N=await U({..._,to:S.hostname,https:_.https}),!N){if(D("ssl",`Generating new certificates for ${S.hostname}`,_.verbose),await e({..._,from:R.toString(),to:S.hostname,https:_.https}),N=await U({..._,to:S.hostname,https:_.https}),!N)throw Error(`Failed to load SSL configuration after generating certificates for ${S.hostname}`)}}catch(K){throw D("server",`SSL setup failed: ${K}`,_.verbose),K}D("server",`Setting up reverse proxy with SSL config for ${S.hostname}`,_.verbose),await S_({..._,from:_.from||"localhost:5173",to:S.hostname,fromPort:A,sourceUrl:{hostname:R.hostname,host:R.host},ssl:N})}async function __(_,R,S,A,B,N,K,Q,Y,X){D("proxy",`Creating proxy server ${_} -> ${R} with cleanUrls: ${Q}`,K);let J=[{host:R,route:{sourceHost:A.host,cleanUrls:Q||!1,changeOrigin:Y||!1,basePath:"/",auth:X}}];if(!IR({routeEntries:J,listenPort:S,sslConfig:B,originGuard:null,verbose:K??!1}))throw Error(`Failed to start proxy server for ${R} on port ${S}`);A_({from:_,to:R,vitePluginUsage:N,listenPort:S,ssl:!!B,cleanUrls:Q,verbose:K})}async function S_(_){D("setup",`Setting up reverse proxy: ${E(_)}`,_.verbose);let{from:R,to:S,sourceUrl:A,ssl:B,verbose:N,cleanup:K,vitePluginUsage:Q,changeOrigin:Y,cleanUrls:X}=_,J=80,Z=443,V="0.0.0.0",I=_.portManager||R_,P=yR(_);try{if(P&&S&&!S.includes("localhost")&&!S.includes("127.0.0.1")){if(!(await f([S],N))[0]){G.warn(`The hostname ${S} isn't in your hosts file. Adding it now...`);try{await y([S],N),G.success(`Added ${S} to your hosts file.`)}catch(O){G.error(`Failed to add ${S} to your hosts file: ${O}`),G.info(`You may need to manually add '127.0.0.1 ${S}' to your /etc/hosts file.`)}}}else if(P&&W.platform!=="darwin"&&S&&S.includes("localhost")&&!S.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await f([S],N))[0]){D("hosts",`${S} not found in hosts file, adding...`,N);try{await y([S],N)}catch(O){D("hosts",`Failed to add ${S} to hosts file: ${O}`,N)}}}if(B&&!I.usedPorts.has(J)){if(!await C(J,V,N))D("setup","Starting HTTP redirect server",N),lR(N),I.usedPorts.add(J);else if(D("setup","Port 80 is in use, skipping HTTP redirect",N),N)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let T=B?Z:J,w=await C(T,V,N),M;if(w){if(D("setup",`Port ${T} is already in use`,N),N)G.warn(`Port ${T} is already in use. This may be another instance of rpx or another service.`);if(T===443){if(M=await I.getNextAvailablePort(3443,!0),D("setup",`Using port ${M} instead of ${T}`,N),N)G.info(`Using port ${M} instead. Access your site at https://${S}:${M}`)}else if(M=await I.getNextAvailablePort(T+1000,!0),D("setup",`Using port ${M} instead of ${T}`,N),N)G.info(`Using port ${M} instead. Access your site at http://${S}:${M}`)}else M=T,I.usedPorts.add(M),D("setup",`Using standard ${T===443?"HTTPS":"HTTP"} port ${T} for ${S}`,N);await __(R,S,M,A,B,Q,N,X,Y,RR(_.auth))}catch(T){D("setup",`Setup failed: ${T}`,N),G.error(`Failed to setup reverse proxy: ${T.message}`),u({domains:[S],hosts:typeof K==="boolean"?K:K?.hosts,certs:typeof K==="boolean"?K:K?.certs,verbose:N,vitePluginUsage:Q})}}function lR(_,R=80,S=443,A){D("redirect",`Starting HTTP redirect server on port ${R}`,_);let B=_R.createServer((N,K)=>{if(A&&N.url){let J=N.url.split("?",1)[0],Z=jR(A,J);if(Z!=null){D("redirect",`Serving ACME challenge ${J}`,_),K.writeHead(200,{"content-type":"text/plain"}),K.end(Z);return}}let Q=N.headers.host||"",Y=Q.includes(":")?Q.slice(0,Q.indexOf(":")):Q,X=S===443?Y:`${Y}:${S}`;D("redirect",`Redirecting request from ${Q}${N.url} to https://${X}`,_),K.writeHead(301,{Location:`https://${X}${N.url}`}),K.end()}).listen(R);t.add(B),D("redirect","HTTP redirect server started",_)}function D_(_){let R={...s,..._};if(D("proxy",`Starting proxy with options: ${E(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}b({proxies:[{id:R.id,from:R.from,to:R.to,path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}],verbose:R.verbose}).catch((Y)=>{G.error(`Failed to register with rpx daemon: ${Y.message}`),W.exit(1)});return}let S=R.to||"",A=S.split(".").pop()?.toLowerCase()||"",B=W.platform==="darwin"&&S&&!S.includes("localhost")&&!S.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],K=["test","localhost","local","example","invalid"];if(B&&N.includes(A)&&R?.verbose)G.warn(`The .${A} TLD may not work reliably for local development`),G.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(B)import("./chunk-c5scw35a.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[S],verbose:R.verbose}).then((X)=>{if(X)Promise.resolve().then(()=>{if(R.verbose)if(K.includes(A))G.success(`DNS server started for .${A} domains`);else G.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else D("dns",`Could not start DNS server - ${S} may not resolve in browser`,R.verbose)})}).catch((Y)=>{D("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let Q={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:o(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};D("proxy",`Server options: ${E(Q)}`,R.verbose),CR(Q).catch((Y)=>{D("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),u({domains:[R.to],hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose})})}function N_(_){return _?.verbose||!1}function yR(_){if(_?.hostsManagement===!1)return!1;let R=_?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function fR(_){let R={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={...R,..._};let S=N_(R),A=yR(R);if(D("config",`Starting with config: ${E(R,2)}`,S),D("config",`Is multi-proxy? ${"proxies"in R}`,S),D("config",`Hosts management enabled? ${A}`,S),R.viaDaemon){let z="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((F)=>({id:F.id,from:F.from,to:F.to,path:F.path,cleanUrls:F.cleanUrls??R.cleanUrls,changeOrigin:F.changeOrigin??R.changeOrigin,pathRewrites:F.pathRewrites})):[{id:R.id,from:R.from,to:R.to??"rpx.localhost",path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}];await b({proxies:z,verbose:S});return}if("proxies"in R&&Array.isArray(R.proxies)){D("servers",`Found ${R.proxies.length} proxies in config`,S);for(let $ of R.proxies)if($.start){let z=`${$.from}-${$.to}`;try{D("watch",`Starting command for ${z} with command: ${$.start.command}`,S),G.info(`Starting command for ${z}...`),await r.startProcess(z,$.start,S);let F=new URL($.from?.startsWith("http")?$.from:`http://${$.from}`),j=F.hostname||"localhost",a=Number(F.port)||80;try{await v(j,a,S),D("watch",`Dev server is ready at ${j}:${a}`,S)}catch(pR){D("watch",`Connection check failed, but continuing with proxy setup: ${pR}`,S),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(F){throw D("watch",`Failed to start command for ${z}: ${F}`,S),Error(`Failed to start command for ${z}: ${F}`)}}else D("watch",`No start command for proxy ${$.from} -> ${$.to}`,S)}else if("start"in R&&R.start){D("watch","Found start command in single proxy config",S);let $=`${R.from}-${R.to}`;try{if(R.start)D("watch",`Starting command: ${R.start.command}`,S),await r.startProcess($,R.start,S);let z=new URL(R.from?.startsWith("http")?R.from:`http://${R.from}`),F=z.hostname||"localhost",j=Number(z.port)||80;try{await v(F,j,S),D("watch",`Dev server is ready at ${F}:${j}`,S)}catch(a){D("watch",`Connection check failed, but continuing with proxy setup: ${a}`,S),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(z){throw D("watch",`Failed to run start command: ${z}`,S),Error(`Failed to run start command: ${z}`)}}else D("watch","No start command found in config",S);let B="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(W.platform!=="win32"&&(R.https||A)){if(!h())try{D("sudo","Pre-acquiring sudo credentials for privileged operations",S),eR("sudo -v",{stdio:"inherit"})}catch{D("sudo","Could not pre-acquire sudo credentials",S)}}let N=[];if(R.productionCerts){if(N=await ER(R.productionCerts,S),N.length>0)D("ssl",`Using ${N.length} production SNI cert(s): ${N.map(($)=>$.serverName).join(", ")}`,S)}if(R.https){let $=N.length>0?null:await U(R);if(!$&&N.length===0){if(D("ssl",`No valid or trusted certificates found for ${B}, generating new ones`,R.verbose),await e(R),$=await U(R),!$)throw Error(`Failed to load SSL certificates after generation for ${B}`)}else D("ssl",`Using existing and trusted certificates for ${B}`,R.verbose);R._cachedSSLConfig=$}let K="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map(($)=>({...$,https:R.https,cleanup:R.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:$.changeOrigin??R.changeOrigin,verbose:S,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,auth:"auth"in R?R.auth:void 0,verbose:S,_cachedSSLConfig:R._cachedSSLConfig}],Q=K.map(($)=>$.to||"rpx.localhost"),Y=N.length>0?N:R._cachedSSLConfig??null,X=Q.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),J=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],V=[...new Set(X.map(($)=>$.split(".").pop()?.toLowerCase()))],I=V.filter(($)=>!!$&&J.includes($));if(I.length>0&&S)G.warn(`The following TLDs may not work reliably for local development: ${I.map(($)=>`.${$}`).join(", ")}`),G.info(" These TLDs have HSTS preloading which can bypass local DNS"),G.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&W.platform==="darwin"&&X.length>0){let{setupDevelopmentDns:$}=await import("./chunk-c5scw35a.js");if(await $({domains:X,verbose:S})){if(S)if(V.every((j)=>!!j&&Z.includes(j)))G.success(`DNS server started for ${V.map((j)=>`.${j}`).join(", ")} domains`);else G.success(`DNS server started for ${V.map((j)=>`.${j}`).join(", ")} domains (hosts file entries also added)`)}else D("dns","Could not start DNS server - custom domains may not resolve",S)}let P=async()=>{D("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-c5scw35a.js");await $({verbose:R.verbose})}catch($){D("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await r.stopAll(R.verbose)}catch($){D("cleanup",`Error stopping processes: ${$}`,R.verbose)}await u({domains:Q,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};W.on("SIGINT",P),W.on("SIGTERM",P);let T=R.singlePortMode===!0,w=R.httpsPort??443,M=R.httpPort??80,L=R.originGuard?XR(R.originGuard):null,O=!!Y&&(K.length>1||T),bR=!Y&&T&&K.length>0;if(O&&Y){D("proxies",`Creating shared HTTPS server for ${K.length} domains on port ${w}`,S);let $=await mR(K,A,S);if(!await C(M,"0.0.0.0",S))lR(S,M,w,R.acmeChallengeWebroot);if(await C(w,"0.0.0.0",S)){if(D("proxies",`Port ${w} is already in use, cannot start shared proxy`,S),S)G.warn(`Port ${w} is in use. Shared HTTPS proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:w,sslConfig:Y,originGuard:L,verbose:S})){G.error(`Shared HTTPS proxy failed to bind :${w}; not exiting`);return}}else if(bR){D("proxies",`Creating shared HTTP server for ${K.length} domains on port ${M}`,S);let $=await mR(K,A,S);if(await C(M,"0.0.0.0",S)){if(D("proxies",`Port ${M} is already in use, cannot start shared proxy`,S),S)G.warn(`Port ${M} is in use. Shared HTTP proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:M,sslConfig:null,originGuard:L,verbose:S})){G.error(`Shared HTTP proxy failed to bind :${M}; not exiting`);return}}else for(let $ of K)try{let z=$.to||"rpx.localhost";D("proxy",`Starting proxy for ${z} with SSL config: ${!!Y}`,$.verbose),await CR({from:$.from||"localhost:5173",to:z,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1})}catch(z){D("proxies",`Failed to start proxy for ${$.to}: ${z}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,z)}}async function mR(_,R,S){let A=[],B=new Set;for(let N of _){let K=N.to||"rpx.localhost",Q=N.cleanUrls||!1,Y=N.path,X=HR(Y),J=RR(N.auth);if(N.redirect){let Z=zR(N.redirect);A.push({host:K,path:Y,route:{redirect:Z,basePath:X,auth:J}}),D("proxies",`Route: ${K}${Y??""} → redirect ${Z.status} ${Z.to}${J?" (auth)":""}`,S)}else if(N.static)A.push({host:K,path:Y,route:{static:MR(N.static,Q),cleanUrls:Q,basePath:X,auth:J}}),D("proxies",`Route: ${K}${Y??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${J?" (auth)":""}`,S);else{let Z=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);A.push({host:K,path:Y,route:{sourceHost:Z.host,cleanUrls:Q,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:X,auth:J}}),D("proxies",`Route: ${K}${Y??""} → ${Z.host}${J?" (auth)":""}`,S)}if(B.has(K))continue;if(B.add(K),R&&!xR(K)&&!K.includes("localhost")&&!K.includes("127.0.0.1"))try{if(!(await f([K],S))[0])await y([K],S)}catch{D("hosts",`Could not add hosts entry for ${K}`,S)}}return A}function IR(_){let{routeEntries:R,listenPort:S,sslConfig:A,originGuard:B,verbose:N}=_,K=kR(R),Q=FR((J,Z)=>wR(K,J,Z),N),Y=B?(J,Z)=>B(J)??Q(J,Z):Q,X=TR(N);try{let J=Bun.serve({port:S,hostname:"0.0.0.0",reusePort:vR(),...A?{tls:Array.isArray(A)?A.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,V){return Y(Z,V)},websocket:X,error(Z){return D("server",`Shared proxy server error: ${Z}`,N),new Response(`Server Error: ${Z.message}`,{status:500})}});return t.add(J),D("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${S} for ${K.size} domains`,N),J}catch(J){return D("proxies",`Failed to start shared proxy: ${J}`,N),console.error("Failed to start shared proxy:",J),null}}function A_(_){if(_?.vitePluginUsage||!_?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${oR}`)}`),console.log(` ${H.green("➜")} ${H.dim(_?.from??"")} ${H.dim("➜")} ${H.cyan(_?.ssl?`https://${_?.to}`:`http://${_?.to}`)}`),_?.listenPort!==(_?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${_?.listenPort}`);if(_?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var YN=fR;export{NR as writeEntry,BS as watchRegistry,G_ as verifyHttpsChain,T_ as trustRootCaForBrowsers,qS as tearDownDevelopmentDns,ES as syncDevelopmentDnsFromRegistry,m_ as stripBasePath,FS as stopDnsServer,vS as stopDaemon,CR as startServer,D_ as startProxy,fR as startProxies,MS as startDnsServer,n_ as siteIdForHost,vR as shouldReusePort,HS as setupResolver,wS as setupDevelopmentDns,b_ as serverNameFromCertFilename,h_ as serveStaticFile,E as safeStringify,O_ as safeRelativePath,MN as safeDeleteFile,b as runViaDaemon,hS as runDaemon,jS as resolverFilePath,ZS as resolverBasenamesForDomains,VS as resolverBasenameForDomain,MR as resolveStaticRoute,c_ as resolveStaticFile,zR as resolveRedirect,zN as resolvePathRewrite,RR as resolveAuth,$S as renderStartingPage,GS as renderFailedPage,CS as removeResolver,kS as removeLegacyTldResolvers,$R as removeHosts,AR as removeEntry,cS as releaseDaemonLock,GN as redactSensitive,yS as reconcileStaleDevelopmentDns,uS as reconcileDevelopmentDnsOnIdle,t_ as readSiteManifest,DS as readEntry,PS as readDaemonPid,K_ as readCertSha256Fingerprint,Y_ as readCertCommonName,NS as readAll,jR as readAcmeChallenge,z_ as pruneStaleRootCas,r_ as projectNameFromHost,_S as portManager,a_ as pathPrefixMatches,X_ as parseSha256HashesFromSecurityListing,f_ as parseHtpasswd,B_ as normalizeSha256Fingerprint,HR as normalizePathPrefix,QS as normalizeDevDomain,GR as matchesWildcard,p_ as matchesAllowedSuffix,wR as matchHostRoute,l_ as matchHostList,u_ as matchHost,E_ as loadSSLConfig,o_ as listDiscoverableSites,W_ as listCertSha256HashesByCommonName,xR as isWildcardPattern,JN as isValidRootCA,DR as isValidId,IN as isSingleProxyOptions,WN as isSingleProxyConfig,M_ as isRootCaTrustedForSsl,F_ as isRootCaFingerprintInKeychains,cR as isProcessElevated,C as isPortInUse,SS as isPidAlive,ZN as isMultiProxyOptions,VN as isMultiProxyConfig,d_ as isLikelyHostname,TS as isDnsServerRunning,LS as isDaemonRunning,y_ as isCertTrusted,o as httpsConfig,h as getSudoPassword,w_ as getSharedDaemonCertPaths,k_ as getRootCAPaths,SR as getRegistryDir,QN as getPrimaryDomain,I_ as getMacosTrustKeychains,Z_ as getMacosLoginKeychainPath,fS as getDaemonRpxDir,US as getDaemonPidPath,e as generateCertificate,AS as gcStaleEntries,q_ as forceTrustCertificate,RS as findAvailablePort,XN as extractHostname,i_ as expandHome,$N as execSudoSync,YS as escapeHtml,BR as ensureDaemonRunning,U_ as enforceBasicAuth,x_ as devSslToSniEntries,IS as devDomainsFromHosts,s_ as detectProjectPreset,LR as deriveIdFromTarget,mS as defaultDaemonSpawnCommand,s as defaultConfig,YN as default,D as debugLog,e_ as createSiteResolver,TR as createProxyWebSocketHandler,FR as createProxyFetchHandler,XR as createOriginGuard,L_ as contentTypeFor,xS as contentLooksLikeRpxResolver,s as config,H as colors,C_ as clearSslConfigCache,WR as cleanupCertificates,u as cleanup,f as checkHosts,U as checkExistingCertificates,$_ as certIncludesSanHostnames,ER as buildSniTlsConfig,H_ as buildRegistryTlsProxyOptions,P_ as buildRedirectLocation,kR as buildHostRoutes,y as addHosts,OS as acquireDaemonLock,KS as SiteSupervisor,j_ as SHARED_DEV_HOST_CERT_PATH,V_ as RPX_ROOT_CA_COMMON_NAME,zS as RPX_RESOLVER_MARKER,g_ as OnDemandCertManager,Q_ as MACOS_SYSTEM_KEYCHAIN,J_ as MACOS_CA_TRUST_FLAGS,JS as LEGACY_TLD_RESOLVER_LABELS,qR as DefaultPortManager,XS as DNS_STATE_VERSION,WS as DNS_PORT,v_ as ACME_CHALLENGE_PREFIX};
|