@stacksjs/rpx
Version:
A modern and smart reverse proxy.
9 lines (7 loc) • 12.6 kB
JavaScript
import{E as B,F as U,a as N,b as d,g as q,z as O}from"../chunk-1rkjbws7.js";import"../chunk-ny83tnrp.js";import"../chunk-7am1svx0.js";import g from"node:process";import{EventEmitter as R}from"events";function C(e){return e==null?[]:Array.isArray(e)?e:[e]}function H(e,t,n,s){var i,a=e[t],r=~s.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~s.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((i=+n,i*0===0)?i:n),!!n):(i=+n,i*0===0)?i:n;e[t]=a==null?r:Array.isArray(a)?a.concat(r):[a,r]}function G(e,t){e=e||[],t=t||{};var n,s,i,a,r,h={_:[]},o=0,l=0,m=0,c=e.length;let u=t.alias!==void 0,w=t.unknown!==void 0,_=t.default!==void 0;if(t.alias=t.alias||{},t.string=C(t.string),t.boolean=C(t.boolean),u)for(n in t.alias){s=t.alias[n]=C(t.alias[n]);for(o=0;o<s.length;o++)(t.alias[s[o]]=s.concat(n)).splice(o,1)}for(o=t.boolean.length;o-- >0;){s=t.alias[t.boolean[o]]||[];for(l=s.length;l-- >0;)t.boolean.push(s[l])}for(o=t.string.length;o-- >0;){s=t.alias[t.string[o]]||[];for(l=s.length;l-- >0;)t.string.push(s[l])}if(_){for(n in t.default)if(a=typeof t.default[n],s=t.alias[n]=t.alias[n]||[],t[a]!==void 0){t[a].push(n);for(o=0;o<s.length;o++)t[a].push(s[o])}}let D=w?Object.keys(t.alias):[];for(o=0;o<c;o++){if(i=e[o],i==="--"){h._=h._.concat(e.slice(++o));break}for(l=0;l<i.length;l++)if(i.charCodeAt(l)!==45)break;if(l===0)h._.push(i);else if(i.substring(l,l+3)==="no-"){if(a=i.substring(l+3),w&&!~D.indexOf(a))return t.unknown(i);h[a]=!1}else{for(m=l+1;m<i.length;m++)if(i.charCodeAt(m)===61)break;a=i.substring(l,m),r=i.substring(++m)||(o+1===c||(""+e[o+1]).charCodeAt(0)===45||e[++o]),s=l===2?[a]:a;for(m=0;m<s.length;m++){if(a=s[m],w&&!~D.indexOf(a))return t.unknown("-".repeat(l)+a);H(h,a,m+1<s.length||r,t)}}}if(_){for(n in t.default)if(h[n]===void 0)h[n]=t.default[n]}if(u)for(n in h){s=t.alias[n]||[];while(s.length>0)h[s.shift()]=h[n]}return h}var v=(e)=>e.replace(/[<[].+/,"").trim(),L=(e)=>{let t=/<([^>]+)>/g,n=/\[([^\]]+)\]/g,s=[],i=(h)=>{let o=!1,l=h[1];if(l.startsWith("..."))l=l.slice(3),o=!0;return{required:h[0].startsWith("<"),value:l,variadic:o}},a;while(a=t.exec(e))s.push(i(a));let r;while(r=n.exec(e))s.push(i(r));return s},M=(e)=>{let t={alias:{},boolean:[]};for(let[n,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((a,r)=>{return r!==n&&a.names.some((h)=>s.names.includes(h))&&typeof a.required==="boolean"}))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t},E=(e)=>{return e.sort((t,n)=>{return t.length>n.length?-1:1})[0]},V=(e,t)=>{return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`},S=(e)=>{return e.replace(/([a-z])-([a-z])/g,(t,n,s)=>{return n+s.toUpperCase()})},y=(e,t,n)=>{let s=0,i=t.length,a=e,r;for(;s<i;++s)r=a[t[s]],a=a[t[s]]=s===i-1?n:r!=null?r:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]},F=(e,t)=>{for(let n of Object.keys(t)){let s=t[n];if(s.shouldTransform){if(e[n]=Array.prototype.concat.call([],e[n]),typeof s.transformFunction==="function")e[n]=e[n].map(s.transformFunction)}}},x=(e)=>{let t=/([^\\\/]+)$/.exec(e);return t?t[1]:""},j=(e)=>{return e.split(".").map((t,n)=>{return n===0?S(t):t}).join(".")};class p extends Error{constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=new Error(e).stack}}class T{constructor(e,t,n){if(this.rawName=e,this.description=t,this.config=Object.assign({},n),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=v(e).split(",").map((s)=>{let i=s.trim().replace(/^-{1,2}/,"");if(i.startsWith("no-"))this.negated=!0,i=i.replace(/^no-/,"");return j(i)}).sort((s,i)=>s.length>i.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var P=process.argv,W=`${process.platform}-${process.arch} node-${process.version}`;class ${constructor(e,t,n={},s){this.rawName=e,this.description=t,this.config=n,this.cli=s,this.options=[],this.aliasNames=[],this.name=v(e),this.args=L(e),this.examples=[]}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,n){let s=new T(e,t,n);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}isMatched(e){return this.name===e||this.aliasNames.includes(e)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof k}hasOption(e){return e=e.split(".")[0],this.options.find((t)=>{return t.names.includes(e)})}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:n,options:s,helpCallback:i}=this.cli.globalCommand,a=[{body:`${e}${n?`/${n}`:""}`}];if(a.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let o=E(t.map((l)=>l.rawName));a.push({title:"Commands",body:t.map((l)=>{return` ${V(l.rawName,o.length)} ${l.description}`}).join(`
`)}),a.push({title:"For more info, run any command with the `--help` flag",body:t.map((l)=>` $ ${e}${l.name===""?"":` ${l.name}`} --help`).join(`
`)})}let h=this.isGlobalCommand?s:[...this.options,...s||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)h=h.filter((o)=>o.name!=="version");if(h.length>0){let o=E(h.map((l)=>l.rawName));a.push({title:"Options",body:h.map((l)=>{return` ${V(l.rawName,o.length)} ${l.description} ${l.config.default===void 0?"":`(default: ${l.config.default})`}`}).join(`
`)})}if(this.examples.length>0)a.push({title:"Examples",body:this.examples.map((o)=>{if(typeof o==="function")return o(e);return o}).join(`
`)});if(i)a=i(a)||a;console.log(a.map((o)=>{return o.title?`${o.title}:
${o.body}`:o.body}).join(`
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${W}`)}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e)throw new p(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let n of Object.keys(e))if(n!=="--"&&!this.hasOption(n)&&!t.hasOption(n))throw new p(`Unknown option \`${n.length>1?`--${n}`:`-${n}`}\``)}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,n=[...t.options,...this.options];for(let s of n){let i=e[s.name.split(".")[0]];if(s.required){let a=n.some((r)=>r.negated&&r.names.includes(s.name));if(i===!0||i===!1&&!a)throw new p(`option \`${s.rawName}\` value is missing`)}}}}class k extends ${constructor(e){super("@@global@@","",{},e)}}var b=Object.assign;class A extends R{constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new k(this),this.globalCommand.usage("<command> [options]")}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let s=new $(e,t||"",n,this);return s.globalCommand=this.globalCommand,this.commands.push(s),s}option(e,t,n){return this.globalCommand.option(e,t,n),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},n,s){if(this.args=e,this.options=t,n)this.matchedCommand=n;if(s)this.matchedCommandName=s;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e=P,{run:t=!0}={}){if(this.rawArgs=e,!this.name)this.name=e[1]?x(e[1]):"cli";let n=!0;for(let i of this.commands){let a=this.mri(e.slice(2),i),r=a.args[0];if(i.isMatched(r)){n=!1;let h=b(b({},a),{args:a.args.slice(1)});this.setParsedInfo(h,i,r),this.emit(`command:${r}`,i)}}if(n){for(let i of this.commands)if(i.name===""){n=!1;let a=this.mri(e.slice(2),i);this.setParsedInfo(a,i),this.emit("command:!",i)}}if(n){let i=this.mri(e.slice(2));this.setParsedInfo(i)}if(this.options.help&&this.showHelpOnExit)this.outputHelp(),t=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),t=!1,this.unsetMatchedCommand();let s={args:this.args,options:this.options};if(t)this.runMatchedCommand();if(!this.matchedCommand&&this.args[0])this.emit("command:*");return s}mri(e,t){let n=[...this.globalCommand.options,...t?t.options:[]],s=M(n),i=[],a=e.indexOf("--");if(a>-1)i=e.slice(a+1),e=e.slice(0,a);let r=G(e,s);r=Object.keys(r).reduce((c,u)=>{return b(b({},c),{[j(u)]:r[u]})},{_:[]});let h=r._,o={"--":i},l=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,m=Object.create(null);for(let c of n){if(!l&&c.config.default!==void 0)for(let u of c.names)o[u]=c.config.default;if(Array.isArray(c.config.type)){if(m[c.name]===void 0)m[c.name]=Object.create(null),m[c.name].shouldTransform=!0,m[c.name].transformFunction=c.config.type[0]}}for(let c of Object.keys(r))if(c!=="_"){let u=c.split(".");y(o,u,r[c]),F(o,m)}return{args:h,options:o}}runMatchedCommand(){let{args:e,options:t,matchedCommand:n}=this;if(!n||!n.commandAction)return;n.checkUnknownOptions(),n.checkOptionValue(),n.checkRequiredArgs();let s=[];return n.args.forEach((i,a)=>{if(i.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t),n.commandAction.apply(this,s)}}var f=new A("rpx");f.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").action(async(e)=>{if(!e?.from||!e.to)return U(d);let t={from:e.from,to:e.to,https:{keyPath:e.keyPath,certPath:e.certPath,caCertPath:e.caCertPath},cleanup:{certs:e.certsCleanup||!1,hosts:e.hostsCleanup||!1},verbose:e.verbose||!1};if(e.startCommand){let n={command:e.startCommand};if(e.startCwd)n.cwd=e.startCwd;if(e.startEnv)try{n.env=JSON.parse(e.startEnv)}catch(s){console.error("Failed to parse start-env JSON:",s),g.exit(1)}t.start=n}return B(t)});f.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{let n=q(d)?d.proxies.find((s)=>s.to===e||`${s.from}-${s.to}`===e):d.to===e?d:null;if(!n?.start)console.error(`No watch configuration found for proxy: ${e}`),g.exit(1);try{await O.startProcess(e,n.start,t.verbose),console.log(`Started dev server for ${e}`)}catch(s){console.error(`Failed to start dev server for ${e}:`,s),g.exit(1)}});f.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{try{await O.stopProcess(e,t.verbose),console.log(`Stopped dev server for ${e}`)}catch(n){console.error(`Failed to stop dev server for ${e}:`,n),g.exit(1)}});f.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(e)=>{try{await O.stopAll(e.verbose),console.log("Stopped all dev servers")}catch(t){console.error("Failed to stop all dev servers:",t),g.exit(1)}});f.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(N)});f.version(N);f.help();f.parse();