-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.js
executable file
·3 lines (2 loc) · 7.19 KB
/
exec.js
1
2
3
#!/usr/bin/env node
import*as e from"colors";import*as r from"@capacitor/core";import{createRequire as o}from"module";var t={n:e=>{var r=e&&e.__esModule?()=>e.default:()=>e;return t.d(r,{a:r}),r},d:(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)};const n=(s={default:()=>e.default},a={},t.d(a,s),a);var s,a;const l=(e=>{var r={};return t.d(r,e),r})({Capacitor:()=>r.Capacitor}),i=("undefined"!=typeof window&&window.location.hostname.split(".").pop(),l.Capacitor.isNativePlatform(),"localhost"),d=`http://${i}:8910`,c="undefined"!=typeof process&&process.argv.includes("webpackWatch"),p=[d],u=/Development server running!/,g=/Local: |\n/g,v=/hmr update/,m=()=>{if("undefined"==typeof process)throw new Error("Error: Incompatible environment: This script is supposed to run in a nodeJS environment")},y=e=>{switch(e){case 200:return"OK";case 400:return"Bad Request";case 401:return"Unauthorized";case 403:return"Forbidden";case 404:return"Not Found";case 413:return"Content Too Large";case 500:return"Internal Server Error";default:return"Unknown Error"}},f=(e,r)=>{!1!==e?console.log("Shutting down proxy server for web app development ... "+(r?n.default.red(`\nError: ${null==r?void 0:r.message}`):"")+"\n"):console.log("Proxy server is not running\n")},h=(e,r)=>{var o,t;let s;s="EADDRINUSE"===e.code?`Error: listen EADDRINUSE: [${d}] is already in use.`:(null===(t=null===(o=e.stack)||void 0===o?void 0:o.split("\n"))||void 0===t?void 0:t[0])||`Error: ${e.code}: ${e.message}`,console.log(n.default.red((r?w:" ➜ ")+E(s)+(r?"":"\n")))},w=n.default.grey((new Date).toLocaleTimeString(Intl.DateTimeFormat().resolvedOptions().locale))+n.default.cyan.bold(" [webAppDevProxy] "),I=(e,r,o)=>{console.log(w+(o?n.default.yellow("resolving preflight request ➜ "):n.default.green("resolving request ➜ "))+n.default.gray("Status: ")+(e>=200&&e<=299?n.default.green(`${e} - ${y(e)}`):n.default.red(`${e} - ${y(e)}`+(r?`: ${r}`:""))))},S=e=>{!1!==e?console.log("Shutting down Ionic app development server ...\n"):console.log("Ionic app development server is not running\n")},$=e=>{console.log(n.default.red(" ➜ Error: Unable to serve Ionic App")+n.default.cyan(`\n\nNote: The ${n.default.yellow("serveWithProxy")} script is supposed to run in an Ionic project directory.\nPlease make sure that the Ionic CLI is installed on your system and that \nthis script is executed in the root directory of your Ionic project.\nIf you intend to run the proxy server only, use the ${n.default.yellow("startProxyServer")} script.\nFor more information, read the original error message below.\n\n`)+n.default.red(e.message))},x=(e,r)=>{var o;console.log(n.default.red(((null===(o=e.stack)||void 0===o?void 0:o.split("\n")[0])||`Error: ${e.code}: ${E(e.message)}`)+(r?n.default.cyan(`\n\n${E(r)}\n`):"")))},E=e=>e.replace(/ionic-web-app-dev-proxy|\[[^\]]+\]/g,(e=>n.default.yellow(e.replace(/[[\]]/g,"")))),b=o(import.meta.url)("child_process"),T=o(import.meta.url)("http");var P=t.n(T);const N=(e,r=null)=>{e.setHeader("Access-Control-Allow-Origin",r||"*"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization")},R=(e,r,o)=>{const t=(null==o?void 0:o.contentType)||"application/json";I(r),o&&e.setHeader("Content-Type",t),e.writeHead(r),e.end(o?((e,r)=>"application/json"===r?JSON.stringify(e):e.toString())(o.data,t):null)},O=(e,r,o,t,n=null)=>{I(o,t),r.setHeader("Content-Type","application/json"),r.writeHead(o),r.end(JSON.stringify({error:{code:o,http_status:o,message:`${o}: ${y(o)}`,data:n?{debug:n}:{}}})),e.destroy()},A=e=>!!/^(https?:\/\/(www\.)?([\w0-9-]+\.?)+([a-z]{2,63})?|([0-9]{1,3}\.){3}[0-9]{1,3})(:[0-9]{1,5})?$/.test(e),k=e=>{m(),console.log((c?"\n":"")+"Starting proxy server for web app development ...\n");let r=null;try{if(!A(e))throw new Error(`Invalid Parameter: [${e}] is not a valid Ionic app development server address`);r=P().createServer(((r,o)=>{var t;const s=(null===(t=r.url)||void 0===t?void 0:t.replace(/^\//,""))||"/";((e,r)=>{const o="OPTIONS"===r;console.log(w+(o?n.default.yellow("incoming preflight request ➜ "):n.default.green("incoming request ➜ "))+n.default.grey(`URL: ${(o?n.default.yellow:n.default.green)(e)}`+(o?"":` Method: ${n.default.green(r||"UNKNOWN")}`)))})(s,r.method),"OPTIONS"!==r.method?(N(o,r.headers.origin),((e,r,o)=>!!/^https?:\/\/(www\.)?([\w0-9-]+\.)+[a-z]{2,63}(\/[\w0-9-]+)*(\.[\w0-9]+)*([?&][\w0-9-_]+=[\w0-9-_%]*)*$/.test(o)||(O(e,r,400,"Target URL is invalid"),!1))(r,o,s)&&((e,r,o)=>{const t=e.headers["content-type"]||"application/json";let n="",s=0;e.on("data",(o=>{if(s+=o.length,s>2097152){const o="Request body size exceeds proxy server maximum limit (2MB)";O(e,r,413,o,`HTTP Error: 413: ${o}`)}else n+=o})),e.on("end",(async()=>{try{const s=await fetch(o,{method:e.method,headers:{"Content-Type":t},body:n}),a=s.headers.get("content-type")||"application/json",l="application/json"===t?await s.json():s.text();R(r,s.status,{contentType:a,data:l})}catch(o){const{stack:t,code:n,message:s}=o,a=(null==t?void 0:t.split("\n")[0])||`Error: ${n}: ${s}`;O(e,r,500,a,t)}}))})(r,o,s)):((e,r,o)=>{const{origin:t}=e.headers;N(r);let n=null;t?[...p,o].includes(t)||(n={code:403,message:`Origin [${t}] is not allowed to access proxy server`}):n={code:400,message:"Proxy server is unable to determine request origin"},n?O(e,r,n.code,n.message):R(r,200)})(r,o,e)})).listen(8910,i,(()=>{console.log(`${n.default.green(` ➜ ${d}`)}\n`)})).on("error",(e=>{h(e,!0)}))}catch(e){j(r,e)}return r},j=(e,r)=>{r&&h(r),e&&e.listening?e.close((e=>{f(!0,e),process.exit(e?1:0)})):f(!1)},C=(e,r,o)=>{o&&$(o),e&&!e.killed?e.kill(r):S(!1)};let M,D;switch(process.argv.length<=2&&(x({code:"EMISSARG",message:"Missing argument: ionic-web-app-dev-proxy needs to be provided with a command to execute"},"Note: Valid commands are [serveWithProxy] and [startProxyServer]"),process.exit(1)),process.argv[2]){case"serveWithProxy":M=(()=>{m(),console.log((c?"\n":"")+"Starting Ionic app development server ...\n");const e=(0,b.spawn)("ionic",["serve"]);e.on("error",(e=>{$(e)})),e.stderr.on("data",(e=>{$({message:e.toString()})}));let r=null;return e.stdout.on("data",(o=>{const t=o.toString();if(u.test(o)){const o=((e,r)=>{const o=e.match(/Local: .*\n/);if(!o||!o.length)return C(r,"SIGTERM",{message:"Error: Unable to retrieve local Ionic app development server URL"}),null;const t=o[0].replace(g,"");return A(t)?t:(C(r,"SIGTERM",{message:`Error: [${t}] is not a valid Ionic app development server address`}),null)})(t,e);if(!o)return;return s=o,console.log(n.default.green(` ➜ ${s}\n`)),r=k(o),void(r||C(e,"SIGTERM"))}var s;(e=>{v.test(e)&&console.log(e.replace(/^\[(vite|webpack)\] |\n/g,""))})(t)})),e.on("close",(()=>{S(),r&&j(r)})),e})();break;case"startProxyServer":if(process.argv.length<=3){x({code:"ENOIONADDRARG",message:"Missing argument: [startProxyServer] has to be provided with an Ionic serve address to resolve preflight requests"},"Example: ionic-web-app-dev-proxy [startProxyServer http://localhost:8100]");break}D=k(process.argv[3]);break;default:x({code:"EINVARG",message:`Invalid argument: [${process.argv[2]}] is not a valid command`}),process.exit(1)}process.on("SIGINT",(()=>{process.stdout.write("\n"),M&&C(M,"SIGINT"),D&&j(D)})),process.on("SIGTERM",(()=>{M&&C(M,"SIGTERM"),D&&j(D)}));