UNPKG

@eclipsejs/cli

Version:

Inject environment variables on runtime

2 lines (1 loc) 39.8 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("reflect-metadata");var e=require("inversify"),t=require("tslib"),r=require("minimist"),n=require("crypto"),i=require("http"),o=require("url"),s=require("open"),a=require("sanitize-html"),c=require("keytar"),u=require("fs"),l=require("figlet"),h=require("axios"),p=require("cli-table"),d=require("child_process"),g=require("inquirer");function _(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function f(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var m=_(r),v=f(n),w=_(i),y=_(o),b=_(s),C=_(a),j=_(c),E=_(l),S=_(h),I=_(p),P=_(g),A=function(){function r(){}return r.prototype.getKey=function(e,r){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,j.default.getPassword(e,r)]}))}))},r.prototype.setKey=function(e,r,n){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,j.default.setPassword(e,r,n)]}))}))},r.prototype.deleteKey=function(e,t){return j.default.deletePassword(e,t)},r=t.__decorate([e.injectable()],r)}(),T=function(){function r(e){this.FILE_PATH=e}return r.prototype.find=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:r=e?this.FILE_PATH+"."+e:this.FILE_PATH,t.label=1;case 1:return t.trys.push([1,3,,4]),[4,u.promises.stat(r)];case 2:return t.sent()?[2,!0]:[2,!1];case 3:return t.sent(),[2,!1];case 4:return[2]}}))}))},r.prototype.writeFile=function(e,r){return t.__awaiter(this,void 0,void 0,(function(){var n;return t.__generator(this,(function(t){n=r?this.FILE_PATH+"."+r:this.FILE_PATH;try{return[2,u.promises.writeFile(n,e).then((function(){return!0}))]}catch(e){return console.error(e),[2,!1]}return[2]}))}))},r.prototype.createOrUpdate=function(e){var r=e.data,n=e.fileComment,i=e.typeSuffix;return t.__awaiter(this,void 0,void 0,(function(){var e,o;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.find(i)];case 1:return t.sent()?[2,this.replaceOnFile(r)]:(e=k(r),o=n?n+"\n"+e:e,[2,this.writeFile(o,i)])}}))}))},r.prototype.read=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(e){try{return[2,u.promises.readFile(this.FILE_PATH).then((function(e){return e.toString()}))]}catch(e){return console.error(e),[2,""]}return[2]}))}))},r.prototype.readIntoObject=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i;return t.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.read()];case 1:return r=t.sent(),n=e?r.split("\n").slice(1).join("\n"):r,[2,L(n)];case 2:return i=t.sent(),console.error("Error reading file into object "+i),[2,null];case 3:return[2]}}))}))},r.prototype.replaceOnFile=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,o,s;return t.__generator(this,(function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,this.read()];case 1:return r=a.sent(),n=L(r),i=t.__assign(t.__assign({},n),e),o=k(i),[2,this.writeFile(o)];case 2:return s=a.sent(),console.error(s),[2,!1];case 3:return[2]}}))}))},r=t.__decorate([e.injectable(),t.__metadata("design:paramtypes",[String])],r)}(),L=function(e){return e.split("\n").filter((function(e){return""!==e})).reduce((function(e,r){var n,i=r.split("="),o=i[1],s=isNaN(+o)?"true"===o||"false"===o||R(o)?JSON.parse(o):o:+o;return t.__assign(t.__assign({},e),((n={})[i[0]]=s,n))}),{})},k=function(e){var r=t.__assign({},e),n="";for(var i in r)n+=i+"="+r[i]+"\n";return n},R=function(e){if("string"!=typeof e)return!1;try{var t=JSON.parse(e),r=Object.prototype.toString.call(t);return"[object Object]"===r||"[object Array]"===r}catch(e){return!1}},F=function(){function r(e){this.keychain=e}return r.prototype.get=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.keychain.getKey("eclipse","core")];case 1:return(e=t.sent())?[2,L(e)]:[2,null]}}))}))},r.prototype.set=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){return r=k(e),[2,this.keychain.setKey("eclipse","core",r)]}))}))},r.prototype.delete=function(){return this.keychain.deleteKey("eclipse","core")},r.prototype.initialize=function(e){var r=e.ECLIPSE_AUTH_TARGET_AUDIENCE,n=e.ECLIPSE_AUTH_CLIENT_ID,i=e.ECLIPSE_AUTH_DOMAIN;return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(e){switch(e.label){case 0:return[4,this.set({ECLIPSE_AUTH_SERVER_PORT:4242,ECLIPSE_AUTH_CLIENT_ID:n,ECLIPSE_AUTH_DOMAIN:i,ECLIPSE_AUTH_CALLBACK_URL:"http://localhost:4242",ECLIPSE_AUTH_TARGET_AUDIENCE:r,FIRST_RUN:!0})];case 1:return e.sent(),[2,!0]}}))}))},r=t.__decorate([e.injectable(),t.__param(0,e.inject("KeyChain")),t.__metadata("design:paramtypes",[A])],r)}(),O="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};"function"==typeof O.setTimeout&&setTimeout,"function"==typeof O.clearTimeout&&clearTimeout;function U(e,t){this.fun=e,this.array=t}U.prototype.run=function(){this.fun.apply(null,this.array)};var N=O.performance||{};N.now||N.mozNow||N.msNow||N.oNow||N.webkitNow;new Date;var x={};const{FORCE_COLOR:H,NODE_DISABLE_COLORS:D,TERM:M}=x,z={enabled:!D&&"dumb"!==M&&"0"!==H,reset:V(0,0),bold:V(1,22),dim:V(2,22),italic:V(3,23),underline:V(4,24),inverse:V(7,27),hidden:V(8,28),strikethrough:V(9,29),black:V(30,39),red:V(31,39),green:V(32,39),yellow:V(33,39),blue:V(34,39),magenta:V(35,39),cyan:V(36,39),white:V(37,39),gray:V(90,39),grey:V(90,39),bgBlack:V(40,49),bgRed:V(41,49),bgGreen:V(42,49),bgYellow:V(43,49),bgBlue:V(44,49),bgMagenta:V(45,49),bgCyan:V(46,49),bgWhite:V(47,49)};function q(e,t){let r,n=0,i="",o="";for(;n<e.length;n++)r=e[n],i+=r.open,o+=r.close,t.includes(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+o}function V(e,t){let r={open:`[${e}m`,close:`[${t}m`,rgx:new RegExp(`\\x1b\\[${t}m`,"g")};return function(t){return void 0!==this&&void 0!==this.has?(this.has.includes(e)||(this.has.push(e),this.keys.push(r)),void 0===t?this:z.enabled?q(this.keys,t+""):t+""):void 0===t?function(e,t){let r={has:e,keys:t};return r.reset=z.reset.bind(r),r.bold=z.bold.bind(r),r.dim=z.dim.bind(r),r.italic=z.italic.bind(r),r.underline=z.underline.bind(r),r.inverse=z.inverse.bind(r),r.hidden=z.hidden.bind(r),r.strikethrough=z.strikethrough.bind(r),r.black=z.black.bind(r),r.red=z.red.bind(r),r.green=z.green.bind(r),r.yellow=z.yellow.bind(r),r.blue=z.blue.bind(r),r.magenta=z.magenta.bind(r),r.cyan=z.cyan.bind(r),r.white=z.white.bind(r),r.gray=z.gray.bind(r),r.grey=z.grey.bind(r),r.bgBlack=z.bgBlack.bind(r),r.bgRed=z.bgRed.bind(r),r.bgGreen=z.bgGreen.bind(r),r.bgYellow=z.bgYellow.bind(r),r.bgBlue=z.bgBlue.bind(r),r.bgMagenta=z.bgMagenta.bind(r),r.bgCyan=z.bgCyan.bind(r),r.bgWhite=z.bgWhite.bind(r),r}([e],[r]):z.enabled?q([r],t+""):t+""}}var K=z;K.enabled=require("color-support").level;var B=function(){function r(){}return r.prototype.verticalSeparator=function(){console.log("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ \n")},r.prototype.message=function(e){console.log(K.dim(e))},r.prototype.success=function(e){console.log(K.green(e))},r.prototype.warning=function(e){console.warn(K.yellow(e))},r.prototype.error=function(e){console.error(K.red(e))},r.prototype.banner=function(e,t){console.log(K.yellow(E.default.textSync(e,t)))},r=t.__decorate([e.injectable()],r)}();function G(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function J(e,t,r){return S.default({method:"POST",url:r.ECLIPSE_AUTH_DOMAIN+"/oauth/token",headers:{"content-type":"application/x-www-form-urlencoded"},data:new URLSearchParams({grant_type:"authorization_code",client_id:r.ECLIPSE_AUTH_CLIENT_ID,code_verifier:e,code:t,redirect_uri:r.ECLIPSE_AUTH_CALLBACK_URL})}).then((function(e){var t=e.data;return{access_token:t.access_token,expires_in:t.expires_in}})).catch((function(e){throw new Error("Error attempting to request user token - "+e)}))}var Y=function(){function r(e,r,n){var i=this;this.keyChain=e,this.logger=r,this.coreConfig=n,this.handleAuthResponse=function(e,r,n,o,s){return function(a,c){return t.__awaiter(i,void 0,void 0,(function(){var i,u,l,h,p,d,g,_,f,m,v;return t.__generator(this,(function(t){switch(t.label){case 0:if(!a.url)return[2];if(i=y.default.parse(a.url,!0).query,u=i.code,l=i.state,h=i.error,p=i.error_description,!u||!l)return c.write("\n <html>\n <body>\n <h1>LOGIN FAILED</h1>\n "+C.default("<div>"+h+"</div>")+"\n "+C.default("<div>"+p+"</div>")+"\n </body>\n </html>\n "),[2];c.write("\n <html>\n <body>\n <h1>LOGIN SUCCEEDED</h1>\n <p>You can close this browser window and go back to your terminal.</p>\n </body>\n </html>\n "),t.label=1;case 1:return t.trys.push([1,4,,5]),[4,J(e,u,o)];case 2:return d=t.sent(),g=d.access_token,_=d.expires_in,f=(Date.now()+1e3*_).toString(),m=k({access_token:g,expiration_date:f}),[4,r.setKey("eclipse","auth",m)];case 3:return t.sent(),c.end(),s(),[3,5];case 4:return v=t.sent(),n.error("Error attempting to save access token: "+v),[2];case 5:return[2]}}))}))}},this.codeVerifier=this.createCodeVerifier(),this.authConfig=null}return r.prototype.checkIfAuthFlowRequired=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.keyChain.getKey("eclipse","auth")];case 1:return(e=t.sent())?(this.authConfig=L(e),[4,this.checkIfTokenExpired()]):[2,this.initializeAuthFlow()];case 2:return t.sent()?[2,this.initializeAuthFlow()]:(this.logger.success("\n Session restored. Welcome back!"),[2,!0])}}))}))},r.prototype.initializeAuthFlow=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r,n,i,o,s,a,c;return t.__generator(this,(function(t){switch(t.label){case 0:return e=this.createCodeChallenge(this.codeVerifier),[4,this.coreConfig.get()];case 1:return(r=t.sent())?(n=r.ECLIPSE_AUTH_DOMAIN,i=r.ECLIPSE_AUTH_CLIENT_ID,o=r.ECLIPSE_AUTH_CALLBACK_URL,s=r.ECLIPSE_AUTH_SERVER_PORT,a=r.ECLIPSE_AUTH_TARGET_AUDIENCE,c=this.constructAuthUrl(e,"abc123",{ECLIPSE_AUTH_DOMAIN:n,ECLIPSE_AUTH_CLIENT_ID:i,ECLIPSE_AUTH_TARGET_AUDIENCE:a,ECLIPSE_AUTH_CALLBACK_URL:o}),this.openAuthPage(c),this.logger.message("\nA new tab will open in your default browser. Please log in and come back to your terminal."),[4,this.createAuthServer({ECLIPSE_AUTH_DOMAIN:n,ECLIPSE_AUTH_CLIENT_ID:i,ECLIPSE_AUTH_CALLBACK_URL:o,ECLIPSE_AUTH_SERVER_PORT:s})]):(this.logger.error("Core config missing. Please run eclipse again."),[2,!1]);case 2:return t.sent(),console.clear(),this.logger.success("\nYou've been logged in successfully!"),[2,!0]}}))}))},r.prototype.getConfig=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.keyChain.getKey("eclipse","auth")];case 1:return(e=t.sent())?[2,L(e)]:[2,null]}}))}))},r.prototype.checkIfTokenExpired=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){return(e=this.authConfig.expiration_date)&&Number(e)<=Date.now()?[2,!0]:[2,!1]}))}))},r.prototype.createCodeVerifier=function(){return G(v.randomBytes(32))},r.prototype.createCodeChallenge=function(e){return G((t=e,v.createHash("sha256").update(t).digest()));var t},r.prototype.createAuthServer=function(e){var t=this;return new Promise((function(r){w.default.createServer(t.handleAuthResponse(t.codeVerifier,t.keyChain,t.logger,e,(function(){return r()}))).listen(e.ECLIPSE_AUTH_SERVER_PORT,(function(r){r&&t.logger.error("Unable to start an HTTP server on port "+e.ECLIPSE_AUTH_SERVER_PORT+": "+r)}))}))},r.prototype.constructAuthUrl=function(e,t,r){return[r.ECLIPSE_AUTH_DOMAIN+"/authorize","?response_type=code","&code_challenge_method=S256","&scope=email","&code_challenge="+e,"&client_id="+r.ECLIPSE_AUTH_CLIENT_ID,"&redirect_uri="+r.ECLIPSE_AUTH_CALLBACK_URL,"&audience="+r.ECLIPSE_AUTH_TARGET_AUDIENCE,"&state="+t].join("")},r.prototype.openAuthPage=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,b.default(e,{wait:!0,newInstance:!0})];case 1:return t.sent(),[2];case 2:return r=t.sent(),this.logger.error("Error attempting to open authentication page in browser: "+r),[2];case 3:return[2]}}))}))},r.prototype.logout=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(e){switch(e.label){case 0:return[4,this.keyChain.deleteKey("eclipse","auth")];case 1:return e.sent(),this.logger.message("You've been logged out successfully."),[2]}}))}))},r=t.__decorate([e.injectable(),t.__param(0,e.inject("KeyChain")),t.__param(1,e.inject("Logger")),t.__param(2,e.inject("CoreConfig")),t.__metadata("design:paramtypes",[A,B,F])],r)}(),W=function(){function r(e,t,r){this.auth=e,this.logger=t,this.coreConfig=r,this._http=S.default.create({baseURL:"https://api.eclipsejs.io/v1",headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiZWNsaXBzZS1jbGkifQ.61qSlLu8n-OcFP6cIAmHwpTyeYf5L27Ue7zcvjzFCwc"}})}return r.prototype.Initialize=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r,n;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.auth.getConfig()];case 1:return e=t.sent(),[4,this.coreConfig.get()];case 2:return r=t.sent(),e&&r?(n=e.access_token,this._http.interceptors.request.use((function(e){return e.headers||(e.headers={}),e.headers.Authorization="Bearer "+n,e})),[2]):(this.logger.error("Could not initialize API. Auth or core config not found"),[2])}}))}))},r.prototype.getCliValues=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(e){return[2,this._http.post("/cli").then((function(e){return e.data}))]}))}))},r.prototype.getUser=function(){return t.__awaiter(this,void 0,void 0,(function(){var e=this;return t.__generator(this,(function(t){return[2,this._http.get("/users").then((function(e){return e.data.payload})).catch((function(){return e.logger.error("Error when fetching user."),null}))]}))}))},r.prototype.getProjects=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n=this;return t.__generator(this,(function(t){return r=e?{params:{projectId:e}}:void 0,[2,this._http.get("/projects",r).then((function(e){var t=e.data,r=t.payload,n=t.statusCode,i=t.message;if(200!==n)throw new Error(i);return"string"==typeof r?JSON.parse(r):r})).catch((function(e){return n.logger.error("Error when attempting to fetch projects: "+e),[]}))]}))}))},r.prototype.getSecrets=function(e){var r=e.projectId,n=e.ownerId,i=e.component,o=e.environment;return t.__awaiter(this,void 0,void 0,(function(){var e=this;return t.__generator(this,(function(t){return[2,this._http.get("/secrets/reveal",{data:{projectId:r,ownerId:n,component:i,environment:o}}).then((function(e){var t=e.data,r=t.payload,n=t.statusCode,i=t.message;if(200!==n)throw new Error(i);return r})).catch((function(t){return e.logger.error("Error attempting to fetch secrets: "+t),[]}))]}))}))},r.prototype.createSecret=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r=this;return t.__generator(this,(function(t){return[2,this._http.post("/secrets",e).then((function(e){var t=e.data,r=t.payload,n=t.statusCode,i=t.message;if(200!==n)throw new Error(i);return r})).catch((function(e){return r.logger.error("Error attempting to create secret: "+e),null}))]}))}))},r.prototype.deleteSecret=function(e){var r=e.secretId,n=e.secretName;return t.__awaiter(this,void 0,void 0,(function(){var e=this;return t.__generator(this,(function(t){return[2,this._http.delete("/secrets/"+r).then((function(){e.logger.success("Secret "+n+" successfully deleted.")})).catch((function(t){return e.logger.error("Error attempting to delete secret: "+t),null}))]}))}))},r=t.__decorate([e.injectable(),t.__param(0,e.inject("Auth")),t.__param(1,e.inject("Logger")),t.__param(2,e.inject("CoreConfig")),t.__metadata("design:paramtypes",[Y,B,F])],r)}(),$=function(){function r(){}return r.prototype.initialize=function(e,r,n){var i=this.sanitizeEnv(t.__assign(t.__assign({},process.env),n));d.spawn(e,r,{stdio:"inherit",env:i})},r.prototype.sanitizeEnv=function(e){var r=t.__assign(t.__assign({},process.env),e);return Object.entries(r).reduce((function(e,r){var n=t.__read(r,2),i=n[0],o=n[1];return i.includes("ECLIPSE")||(e[i]=o),e}),{})},r=t.__decorate([e.injectable()],r)}(),X=function(){function r(e,t){this.logger=e,this.configFile=t}return r.prototype.createConfigFile=function(e,r){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.configFile.createOrUpdate({data:{PROJECT:e,COMPONENT:r},fileComment:"# This file was autogenerated by the Eclipse CLI and connects your working directory to an Eclipse project."})];case 1:return t.sent(),this.logger.success("Config file created on current directory."),[2]}}))}))},r.prototype.readConfigFile=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(e){return[2,this.configFile.readIntoObject()]}))}))},r.prototype.checkIfExists=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(e){return[2,this.configFile.find()]}))}))},r=t.__decorate([e.injectable(),t.__param(0,e.inject("Logger")),t.__param(1,e.inject("ConfigFile")),t.__metadata("design:paramtypes",[B,T])],r)}(),Z=[{name:"📋 Initialize a config file in this directory",value:"createConfig",short:"Create config file"},{name:"🔑 Add a secret to this project",value:"add",short:"Add secret"},{name:"🗑 Remove a secret from this project",value:"remove",short:"Remove secret"},{name:"🔭 View secrets from this project",value:"view",short:"View secrets"},{name:"🖊 Print project secrets to an .env file",value:"print",short:"Print secrets to env file"},{name:"🙋 Show help log",value:"help",short:"Show help log"},{name:"🚪 Exit",value:"exit",short:"Exit"}];function Q(e){var t=e.map((function(e){return{name:e.name+" - "+e.createdAt,value:e._id,short:e.name}}));return P.default.prompt([{type:"list",name:"projectId",message:"Please select a project.",choices:t},{type:"list",name:"action",message:"What would you like to do?",choices:Z}])}var ee=[{name:"🔑 Add a secret to this project.",value:"add",short:"Add secret"},{name:"🗑 Remove a secret from this project.",value:"remove",short:"Remove secret"},{name:"🔭 View secrets from this project.",value:"view",short:"View secrets"},{name:"🖊 Print project secrets to an .env file.",value:"print",short:"Print secrets to env file"},{name:"🙋 Show help log.",value:"help",short:"Show help log"},{name:"🚪 Exit",value:"exit",short:"Exit"}];function te(e,r){var n=e.length?t.__spread(new Set(e.map((function(e){return e.component})))):[];return r&&n.push("Other"),P.default.prompt([{type:"list",name:"component",message:"Please select a component.",choices:n}])}function re(e){var r=e.map((function(e){return e.environment}));return P.default.prompt([{type:"list",name:"environment",message:"Please select an environment.",choices:t.__spread(new Set(r))}])}function ne(){return P.default.prompt([{type:"input",name:"component",message:"Please set the name of the component:"}])}var ie=function(){function r(e,t){this._api=e,this.logger=t}return r.prototype.addSecretFromMenu=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,o,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,P.default.prompt([{type:"input",name:"name",message:"Please set the name of this secret:"},{type:"password",name:"value",message:"Please set the secret value"},{type:"input",name:"component",message:"Set this secret's component"},{type:"input",name:"environment",message:"Set this secret's environment"}])];case 1:return r=t.sent(),n=r.name,i=r.value,o=r.environment,s=r.component,[2,this.addSecret(e,n,i,s,o)]}}))}))},r.prototype.removeSecretFromMenu=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,(i=e.secrets,o=i.map((function(e){return{name:e.name+" - "+e.component+"/"+e.environment,value:{_id:e._id,name:e.name},short:e.name}})),P.default.prompt([{type:"list",name:"secret",message:"Please select the secret you would like to remove:",choices:o},{type:"confirm",name:"confirm",message:"This action cannot be undone. Please confirm deletion:"}]))];case 1:return r=t.sent(),n=r.secret,r.confirm?[2,this.removeSecret({secretId:n._id,secretName:n.name})]:(this.logger.message("Aborted."),[2])}var i,o}))}))},r.prototype.addSecret=function(e,r,n,i,o){return t.__awaiter(this,void 0,void 0,(function(){var s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this._api.createSecret({projectId:e._id,ownerId:e.ownerId,name:r,value:n,environment:o,component:i})];case 1:return(s=t.sent())?(this.logger.success("Secret "+s.name+" created under project "+e.name+"."),[2]):[2]}}))}))},r.prototype.getPartialSecrets=function(e,r,n){return t.__awaiter(this,void 0,void 0,(function(){var i,o;return t.__generator(this,(function(s){switch(s.label){case 0:return[4,this._api.getSecrets({projectId:e._id,ownerId:e.ownerId,component:r,environment:n})];case 1:return(i=s.sent()).length?(o=i.reduce((function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.name]=r.value,n))}),{}),[2,o]):[2]}}))}))},r.prototype.getFullSecrets=function(e,r,n){return t.__awaiter(this,void 0,void 0,(function(){var i,o;return t.__generator(this,(function(s){switch(s.label){case 0:return[4,this._api.getSecrets({projectId:e._id,ownerId:e.ownerId,component:r,environment:n})];case 1:return(i=s.sent()).length?(o=i.reduce((function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.name]=t.__assign({},r),n))}),{}),[2,o]):[2]}}))}))},r.prototype.removeSecret=function(e){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this._api.deleteSecret(e)]}))}))},r=t.__decorate([e.injectable(),t.__param(0,e.inject("API")),t.__param(1,e.inject("Logger")),t.__metadata("design:paramtypes",[W,B])],r)}(),oe="\nIt looks like this is your first time running Eclipse. \n \nUse the main menu to access your projects, manage secrets, and create configuration files\nin repos. \n\nTo start injecting environment variables, run eclipse on your repository,\nselect a project, and initialize a configuration file. \n\nThen run "+K.yellow("eclipse inject all node")+" and your project's environment variables\nshould be available in the process.env object.\n\nTo see more available commands, run "+K.yellow("eclipse help")+". Happy hacking!\n\n",se="\n"+K.underline("General commands")+"\n\n- "+K.green("eclipse v, version")+" - output version number\n\n- "+K.green("eclipse h, help")+" - output help log\n\n"+K.underline("Project commands")+"\n\n- "+K.green("eclipse i/inject component/environment <process>")+" - inject secrets unto an execution context\n\nFor example: \n"+K.yellow("eclipse i api/staging npm start")+" will inject secrets created for the API component under the staging environment into your node execution.\n"+K.yellow("eclipse inject web/prod npm start")+" will inject secrets for the web component under the prod environment.\n\n- "+K.green("eclipse ls/list component/environment")+" - list the secrets of the project tagged in your working directory, for the given component and environment.\n\nFor example:\n"+K.yellow("eclipse ls api/staging")+" will list all staging secrets for the API component.\n\n- "+K.green("eclipse a/add component/environment <secretname> <secretvalue>")+" - create a secret under the given component and environment for the project in your working directory.\n\nFor example:\n"+K.yellow("eclipse a api/staging MY_SECRET MY_TOKEN")+" will create MY_SECRET for the api component under the staging environment\n\n- "+K.green("eclipse rm/remove component/environment <secretname>")+" - delete a secret under the given component and environment.\n\nFor example:\n"+K.yellow("eclipse rm api/staging MY_SECRET")+" will delete MY_SECRET under the api component and staging environment.\n\nTo see this help log again, run "+K.green("eclipse help")+"\n",ae=function(){function r(e,t,r,n,i,o){this._api=e,this.logger=t,this.secrets=r,this.envFile=n,this.projectConfig=i,this.shell=o}return r.prototype.projectActions=function(e,t){switch(e){case"view":return this.viewProjectSecretsFromMenu(t);case"add":return this.secrets.addSecretFromMenu(t);case"remove":return this.secrets.removeSecretFromMenu(t);case"print":return this.printSecrets(t);case"createConfig":return this.createConfigFile(t);case"help":return void this.logger.message(se);case"exit":return;default:return void this.logger.warning("Command not recognized")}},r.prototype.projectSelection=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r,n,i,o;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this._api.getProjects()];case 1:return(e=t.sent()).length?[4,Q(e)]:(this.logger.warning("No projects found. Try creating one first."),[2]);case 2:return r=t.sent(),n=r.projectId,i=r.action,(o=e.find((function(e){return e._id===n})))?[2,this.projectActions(i,o)]:(this.logger.warning("No project selected."),[2])}}))}))},r.prototype.getProject=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(n){switch(n.label){case 0:return[4,this._api.getProjects(e)];case 1:return r=t.__read.apply(void 0,[n.sent(),1]),[2,r[0]]}}))}))},r.prototype.promptSingleProjectActions=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.getProject(e)];case 1:return(r=t.sent())?[4,(i=r.name,P.default.prompt([{type:"list",name:"action",message:"Looks like you are in the project "+i+" directory. What would you like to do?",choices:ee}]))]:(this.logger.error("It looks like you do not have access to the project tagged in this directory."),[2]);case 2:return n=t.sent().action,[2,this.projectActions(n,r)]}var i}))}))},r.prototype.viewProjectSecretsFromMenu=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,o,s;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,te(e.secrets)];case 1:return r=a.sent().component,[4,re(e.secrets.filter((function(e){return e.component===r})))];case 2:return n=a.sent().environment,[4,this.secrets.getFullSecrets(e,r,n)];case 3:return(i=a.sent())?(o=Object.entries(i).map((function(e){var r=t.__read(e,2),n=r[0],i=r[1];return[n,i.value,i.created_at]})),s=new I.default({head:["Name","Value","Created"],colWidths:[30,30,40],rows:o}),this.logger.success(s.toString()),[2]):(this.logger.warning("No secrets found for project "+e.name+": component "+r+" and environment "+n),[2])}}))}))},r.prototype.viewProjectSecrets=function(e,r,n){return t.__awaiter(this,void 0,void 0,(function(){var i,o,s;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.secrets.getFullSecrets(e,r,n)];case 1:return(i=a.sent())?(o=Object.entries(i).map((function(e){var r=t.__read(e,2),n=r[0],i=r[1];return[n,i.value,i.created_at]})),s=new I.default({head:["Name","Value","Created"],colWidths:[30,30,40],rows:o}),this.logger.success(s.toString()),[2]):(this.logger.warning("No secrets found for project "+e.name+": component "+r+" and environment "+n),[2])}}))}))},r.prototype.printSecrets=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,o;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,te(e.secrets)];case 1:return r=t.sent().component,(n=e.secrets.filter((function(e){return e.component===r})))?[4,re(n)]:(this.logger.warning("No secrets found under "+r+" component."),[2]);case 2:return i=t.sent().environment,[4,this.secrets.getPartialSecrets(e,r,i)];case 3:return(o=t.sent())?[4,this.envFile.createOrUpdate({data:o,typeSuffix:i,fileComment:"# Environment file generated by EclipseJS"})]:(this.logger.warning("No secrets found for project "+e.name),[2]);case 4:return t.sent(),this.logger.success(".env file for "+i+" environment printed on working directory."),[2]}}))}))},r.prototype.projectDirectoryMenu=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.projectConfig.checkIfExists()];case 1:return t.sent()?[4,this.projectConfig.readConfigFile()]:[2,!1];case 2:return(e=t.sent())&&e.PROJECT?[4,this.promptSingleProjectActions(e.PROJECT)]:(this.logger.error("Malformed config file. Try re-creating the .eclipserc file in your project directory."),[2,!1]);case 3:return t.sent(),[2,!0]}}))}))},r.prototype.checkIfOnProjectDirectory=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(e){return[2,this.projectConfig.checkIfExists()]}))}))},r.prototype.getCurrentContext=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.projectConfig.readConfigFile()];case 1:return(e=t.sent())&&e.PROJECT?[4,this.getProject(e.PROJECT)]:(this.logger.error("Malformed or inexistent config file. Try creating a configuration file in this directory using the main menu."),[2]);case 2:return[2,{project:t.sent(),component:e.COMPONENT}]}}))}))},r.prototype.getCurrentProjectSecrets=function(e,r){return t.__awaiter(this,void 0,void 0,(function(){var n,i;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.getCurrentContext()];case 1:return(n=t.sent())?[4,this.secrets.getPartialSecrets(n.project,e,r)]:[2];case 2:return(i=t.sent())?[2,i]:(this.logger.warning("No secrets found for project "+n.project.name),[2])}}))}))},r.prototype.injectLocalProjectSecrets=function(e,r,n,i){return t.__awaiter(this,void 0,void 0,(function(){var o;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.getCurrentProjectSecrets(n,i)];case 1:return o=t.sent(),[2,this.shell.initialize(e,r,o||{})]}}))}))},r.prototype.createConfigFile=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i;return t.__generator(this,(function(t){switch(t.label){case 0:return e.secrets.length?[3,2]:[4,ne()];case 1:return r=t.sent().component,this.projectConfig.createConfigFile(e._id,r),[2];case 2:return[4,te(e.secrets)];case 3:return"Other"!==(n=t.sent().component)?[3,5]:[4,ne()];case 4:return i=t.sent().component,this.projectConfig.createConfigFile(e._id,i),[2];case 5:return this.projectConfig.createConfigFile(e._id,n),[2]}}))}))},r=t.__decorate([e.injectable(),t.__param(0,e.inject("API")),t.__param(1,e.inject("Logger")),t.__param(2,e.inject("Secrets")),t.__param(3,e.inject("EnvFile")),t.__param(4,e.inject("ProjectConfig")),t.__param(5,e.inject("Shell")),t.__metadata("design:paramtypes",[W,B,ie,T,X,$])],r)}();var ce={list:!0,ls:!0,add:!0,a:!0,rm:!0,remove:!0,inject:!0,i:!0},ue=function(){function r(e,t,r,n){this.logger=e,this.projects=t,this.auth=r,this.secrets=n}return r.prototype.processCommand=function(e,r){return t.__awaiter(this,void 0,void 0,(function(){var n,i;return t.__generator(this,(function(o){return n=t.__read(e,1),i=n[0],ce[i]?r?[2,this.processProjectCommand(e)]:(this.logger.warning("You need to be on a project directory to use this command."),[2,!1]):[2,this.processGenericCommand(e)]}))}))},r.prototype.processGenericCommand=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n;return t.__generator(this,(function(i){switch(i.label){case 0:switch(r=t.__read(e,1),n=r[0],n){case"help":case"h":return[3,1];case"version":case"v":return[3,2];case"logout":return[3,3]}return[3,5];case 1:return this.showHelpLog(),[2,!0];case 2:return this.showToolVersion(),[2,!0];case 3:return[4,this.auth.logout()];case 4:return i.sent(),[2,!0];case 5:return this.logger.warning("Command not recognized"),[2,!1]}}))}))},r.prototype.processProjectCommand=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i;return t.__generator(this,(function(o){switch(r=t.__read(e),n=r[0],i=r.slice(1),n){case"inject":case"i":return[2,this.processInjectCommand(i)];case"add":case"a":return[2,this.processAddCommand(i)];case"list":case"ls":return[2,this.processListCommand(i)];case"remove":case"rm":return[2,this.processRemoveCommand(i)];default:return this.logger.warning("Command not recognized"),[2,!1]}return[2]}))}))},r.prototype.processRemoveCommand=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,o,s,a;return t.__generator(this,(function(c){switch(c.label){case 0:return r=t.__read(e,2),n=r[0],i=r[1],n&&i?[4,this.projects.getCurrentContext()]:(this.logger.error("Please specify an environment and secret: `eclipse rm staging secret_name`"),[2,!1]);case 1:return(o=c.sent())?[4,this.secrets.getFullSecrets(o.project,o.component,n)]:[2,!1];case 2:return(s=c.sent())?(a=s[i])?[4,(u="This action cannot be undone. Please confirm deletion:",P.default.prompt([{type:"confirm",name:"confirm",message:u}]))]:(this.logger.error("Secret "+i+" not found under project "+o.project.name),[2,!1]):[2,!1];case 3:return c.sent().confirm?[4,this.secrets.removeSecret({secretId:a._id,secretName:i})]:(this.logger.message("Aborted."),[2,!1]);case 4:return c.sent(),[2,!0]}var u}))}))},r.prototype.processListCommand=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i;return t.__generator(this,(function(o){switch(o.label){case 0:return r=t.__read(e,1),(n=r[0])?[4,this.projects.getCurrentContext()]:(this.logger.error("Please specify an environment: `eclipse ls staging`"),[2,!1]);case 1:return(i=o.sent())?[4,this.projects.viewProjectSecrets(i.project,i.component,n)]:[2,!1];case 2:return o.sent(),[2,!0]}}))}))},r.prototype.processAddCommand=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,o,s;return t.__generator(this,(function(a){switch(a.label){case 0:return r=t.__read(e,3),n=r[0],i=r[1],o=r[2],n&&i&&o?[4,this.projects.getCurrentContext()]:(this.logger.error("Please specify an environment, secret name, and secret value: `eclipse add <environment> <secret_name> <secret_value>`"),[2,!1]);case 1:return(s=a.sent())?[4,this.secrets.addSecret(s.project,i,o,s.component,n)]:[2,!1];case 2:return a.sent(),[2,!0]}}))}))},r.prototype.processInjectCommand=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i,o,s;return t.__generator(this,(function(a){switch(a.label){case 0:return r=t.__read(e),n=r[0],i=r[1],o=r.slice(2),n?[4,this.projects.getCurrentContext()]:(this.logger.error("Please specify an environment: `eclipse i staging node`"),[2,!1]);case 1:return(s=a.sent())?[4,this.projects.injectLocalProjectSecrets(i,o,s.component,n)]:[2,!1];case 2:return a.sent(),[2,!0]}}))}))},r.prototype.showToolVersion=function(){this.logger.message("Version: 1.1.0")},r.prototype.showHelpLog=function(){this.logger.message(se)},r=t.__decorate([e.injectable(),t.__param(0,e.inject("Logger")),t.__param(1,e.inject("Projects")),t.__param(2,e.inject("Auth")),t.__param(3,e.inject("Secrets")),t.__metadata("design:paramtypes",[B,ae,Y,ie])],r)}(),le=[{name:"🔐 See my projects",value:"view",short:"View projects"},{name:"🙋 Show help log.",value:"help",short:"Show help log"},{name:"💤 Log out",value:"logout",short:"Log out"},{name:"🚪 Exit",value:"exit",short:"Exit"}];var he=function(){function r(e,t,r,n,i,o){var s=this;this.auth=e,this.logger=t,this._api=r,this.projects=n,this.coreConfig=i,this.commands=o,this.suppressError=!1;try{this.execute().then((function(e){s.logger.verticalSeparator(),e||s.suppressError||process.exit(1)})).catch((function(e){return t.error(e)}))}catch(e){e instanceof Error?t.error(e.message):t.error(""+e),this.suppressError||process.exit(1)}}return r.prototype.execute=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r,n;return t.__generator(this,(function(t){switch(t.label){case 0:return console.clear(),this.showIntroLog(),e=m.default(process.argv.slice(2)),this.suppressError=e.suppressError,[4,this.checkForCoreConfig()];case 1:return t.sent()?[4,this.auth.checkIfAuthFlowRequired()]:[2,!0];case 2:return t.sent()?[4,this.checkIfFirstRun()]:[2,!1];case 3:return t.sent(),[4,this._api.Initialize()];case 4:return t.sent(),this.logger.verticalSeparator(),r=e._,[4,this.projects.checkIfOnProjectDirectory()];case 5:return n=t.sent(),r.length?[2,this.commands.processCommand(r,n)]:n?[4,this.projects.projectDirectoryMenu()]:[3,7];case 6:return t.sent(),[3,9];case 7:return[4,this.showTopLevelMenu()];case 8:t.sent(),t.label=9;case 9:return[2,!0]}}))}))},r.prototype.checkIfFirstRun=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.coreConfig.get()];case 1:return(e=r.sent())&&e.FIRST_RUN?(this.logger.message(oe),[4,this.coreConfig.set(t.__assign(t.__assign({},e),{FIRST_RUN:!1}))]):[2];case 2:return r.sent(),[2]}}))}))},r.prototype.checkForCoreConfig=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.coreConfig.get()];case 1:return t.sent()?[2,!0]:(this.logger.warning("The CLI is syncing with Eclipse servers.. 🛰"),[4,this._api.getCliValues()]);case 2:return(e=t.sent())?[4,this.coreConfig.initialize(e)]:(this.logger.error("We were not able to contact the Eclipse servers. Please retry, or if the problem persists contact support @ support@eclipsejs.io"),[2,!1]);case 3:return t.sent(),this.logger.success("Eclipse has been configured successfully. 🚀"),[2,!0]}}))}))},r.prototype.showTopLevelMenu=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,P.default.prompt([{type:"list",name:"action",message:"What would you like to do?",choices:le}])];case 1:return"view"!==(e=t.sent().action)?[3,3]:[4,this.projects.projectSelection()];case 2:t.sent(),t.label=3;case 3:return"logout"!==e?[3,5]:[4,this.auth.logout()];case 4:t.sent(),t.label=5;case 5:return"help"===e&&this.logger.message(se),[2,!0]}}))}))},r.prototype.showIntroLog=function(){this.logger.banner("EclipseJS",{horizontalLayout:"full"}),this.logger.message("Inject environment variables on runtime.")},r=t.__decorate([e.injectable(),t.__param(0,e.inject("Auth")),t.__param(1,e.inject("Logger")),t.__param(2,e.inject("API")),t.__param(3,e.inject("Projects")),t.__param(4,e.inject("CoreConfig")),t.__param(5,e.inject("Commands")),t.__metadata("design:paramtypes",[Y,B,W,ae,F,ue])],r)}();function pe(){var t=new e.Container;return t.bind("Main").to(he).inSingletonScope(),t.bind("Auth").to(Y).inRequestScope(),t.bind("Logger").to(B).inSingletonScope(),t.bind("API").to(W).inSingletonScope(),t.bind("Projects").to(ae).inSingletonScope(),t.bind("Secrets").to(ie).inSingletonScope(),t.bind("KeyChain").to(A).inSingletonScope(),t.bind("Shell").to($).inSingletonScope(),t.bind("Commands").to(ue).inSingletonScope(),t.bind("CoreConfig").to(F).inSingletonScope(),t.bind("ProjectConfig").to(X).inSingletonScope(),t.bind("EnvFile").toDynamicValue((function(){return new T("./.env")})),t.bind("ConfigFile").toDynamicValue((function(){return new T("./.eclipserc")})),t.get("Main")}pe(),exports.index=pe;