@autofleet/cli 2.5.3 → 2.5.5
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/chunk-HHWZRNVZ.js +14 -0
- package/dist/chunk-HHWZRNVZ.js.map +1 -0
- package/dist/chunk-UQU7WR36.js +2 -0
- package/dist/chunk-UQU7WR36.js.map +1 -0
- package/dist/e2e.js +2 -1
- package/dist/e2e.js.map +1 -0
- package/dist/git-autofleet.js +5 -4
- package/dist/git-autofleet.js.map +1 -0
- package/dist/index.js +10 -6
- package/dist/index.js.map +1 -0
- package/eslint.config.mjs +51 -0
- package/package.json +20 -16
- package/tsconfig.json +2 -1
- package/tsup.config.ts +3 -2
- package/vitest.config.ts +10 -0
- package/dist/chunk-CXYUFZMV.js +0 -1
- package/dist/chunk-DEQF3ODJ.js +0 -13
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
var x=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),b=t=>{throw TypeError(t)};var I=(t,e,n)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&b("Object expected");var s,r;n&&(s=e[x("asyncDispose")]),s===void 0&&(s=e[x("dispose")],n&&(r=s)),typeof s!="function"&&b("Object not disposable"),r&&(s=function(){try{r.call(this)}catch(a){return Promise.reject(a)}}),t.push([n,s,e])}else n&&t.push([n]);return e},k=(t,e,n)=>{var s=typeof SuppressedError=="function"?SuppressedError:function(i,p,l,o){return o=Error(l),o.name="SuppressedError",o.error=i,o.suppressed=p,o},r=i=>e=n?new s(i,e,"An error was suppressed during disposal"):(n=!0,i),a=i=>{for(;i=t.pop();)try{var p=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(p).then(a,l=>(r(l),a()))}catch(l){r(l)}if(n)throw e};return a()};import{parseArgs as A}from"node:util";var w="2.5.5";var _={help:{type:"boolean",short:"h",default:!1,description:"Show help (prints this message)"},version:{type:"boolean",short:"v",default:!1,description:"Show version number"}};function j(t){t.options={..._,...t.options};let e=A(t),{values:n}=e;n.version&&(console.log(w),process.exit(0));let s=t.commands?`
|
|
2
|
+
|
|
3
|
+
Commands:
|
|
4
|
+
${Object.entries(t.commands).map(([a,i])=>`${a.padEnd(30," ")} ${i}`).join(`
|
|
5
|
+
`)}
|
|
6
|
+
`:"",r=`
|
|
7
|
+
${t.binName} ${s?"[command] ":""}<options>${s}
|
|
8
|
+
Options:
|
|
9
|
+
${Object.entries(t.options).map(([a,{description:i,type:p,short:l}])=>`${(l?`--${a}, -${l}`:`--${a}`).padEnd(30," ")} ${i.padEnd(70," ")} [${p}]`).join(`
|
|
10
|
+
`)}
|
|
11
|
+
`;return n.help&&(console.log(r),process.exit(0)),{...e,help:r}}import{spawn as O}from"node:child_process";var R=()=>{if(Promise.withResolvers)return Promise.withResolvers();let t,e;return{promise:new Promise((s,r)=>{t=r,e=s}),reject:t,resolve:e}},h=async(t,e,{print:n=!0,env:s={}}={})=>{typeof e=="boolean"&&(n=e,e=void 0);let r=new Error,a=r.stack?r.stack.replace(/^.*/," ..."):null,{promise:i,reject:p,resolve:l}=R(),o=O(t,e,{env:Object.assign(s,process.env)});n&&(o.stdout.pipe(process.stdout),o.stderr.pipe(process.stderr));let d="",u="";o.stdout?.on("data",c=>{d+=c}),o.stderr?.on("data",c=>{u+=c});let g=n?"exit":"close";function v(c){o.removeListener(g,P),Object.assign(c,{pid:o.pid,stdout:d,stderr:u,status:null,signal:null}),p(c)}function P(c,f){o.removeListener("error",v);let y={pid:o.pid,stdout:d,stderr:u,status:c,signal:f};if(c!==0){let T=typeof e!="boolean"&&` ${e?.join(" ")}`||"",m=f?new Error(`${t}${T} exited with signal: ${f}`):new Error(`${t}${T} exited with non-zero code: ${c}`);m.stack&&a&&(m.stack+=`
|
|
12
|
+
${a}`),Object.assign(m,y),p(m)}else l(y)}return o.once(g,P),o.once("error",v),i};import E from"node:fs";var C="SERVICE_HOST",$={dev1:["dev-cluster-2","europe-west1","dev1-experiment-manager"],e2eManager:["e2e-cluster-2","europe-west1","e2e-project-1"],expManager:["af-experiment-manager","europe-west1"],staging:["autofleet-staging","europe-west1-b"]},H=Object.keys($),J=({newFilePath:t,filePath:e,linesToReplace:n})=>{let s=E.readFileSync(e,"utf8");for(let{find:r,replace:a}of n)s=s.replace(r,a);E.writeFileSync(t,s)},L=async t=>{let e=$[t];if(!e)throw new Error(`Cluster name ${t} does not exist!`);let[n,s,r]=e;await h("gcloud",["container","clusters","get-credentials",n,"--region",s,"--project",r||n],{print:!1})},V=async({clusterName:t,variationId:e})=>(await L(t),`--namespace=${e}`),X=t=>{let e=t.split(`
|
|
13
|
+
`).filter(Boolean);e.shift();let n=e.map(s=>{let[r,a,i,p,l,o]=s.split(/(\s+)/).map(g=>g.trim()).filter(Boolean);return`${r.replace(/-/g,"_").toUpperCase()}_${C}=${p}`});return n=n.filter(s=>!s.includes("none")&&!s.includes("undefined")),n},K=(t,e)=>(t instanceof Error||(t=new Error(t)),console.error(t),e&&console.log(e),process.exit(1));export{I as a,k as b,j as c,h as d,H as e,J as f,L as g,V as h,X as i,K as j};
|
|
14
|
+
//# sourceMappingURL=chunk-HHWZRNVZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../bin/utils/parser.ts","../package.json","../bin/utils/asyncSpawn.ts","../bin/utils/index.ts"],"sourcesContent":["import { parseArgs as nativeParseArgs, ParseArgsConfig } from 'node:util';\nimport { version } from '../../package.json';\n\ntype ParseArgsOptionConfig = NonNullable<ParseArgsConfig['options']>[string] & { description: string };\ntype ParseArgsParams = Omit<ParseArgsConfig, 'options'> & { binName: string; options: Record<string, ParseArgsOptionConfig>; commands?: Record<string, string> };\n\nconst GLOBAL_OPTIONS = {\n help: {\n type: 'boolean',\n short: 'h',\n default: false,\n description: 'Show help (prints this message)',\n },\n version: {\n type: 'boolean',\n short: 'v',\n default: false,\n description: 'Show version number',\n },\n} satisfies ParseArgsParams['options'];\n\ntype Expanded<T extends ParseArgsParams> = T & { options: T['options'] & typeof GLOBAL_OPTIONS };\ntype Parsed<T extends ParseArgsParams> = ReturnType<typeof nativeParseArgs<Expanded<T>>> & { help: string };\n\nexport default function parseArgs<T extends ParseArgsParams = ParseArgsParams>(params: T): Parsed<T> {\n params.options = { ...GLOBAL_OPTIONS, ...params.options };\n const data = nativeParseArgs(params as Expanded<T>);\n const { values } = data;\n if ((values as { version: boolean }).version) {\n console.log(version);\n process.exit(0);\n }\n\n const commands = !params.commands ? '' : `\n\nCommands:\n ${Object.entries(params.commands).map(([command, example]) => `${command.padEnd(30, ' ')} ${example}`).join('\\n ')}\n`;\n\n const help = `\n${params.binName} ${commands ? '[command] ' : ''}<options>${commands}\nOptions:\n ${Object.entries(params.options).map(([option, { description, type, short }]) => {\n const key = short ? `--${option}, -${short}` : `--${option}`;\n return `${key.padEnd(30, ' ')} ${description.padEnd(70, ' ')} [${type}]`;\n }).join('\\n ')}\n`;\n\n if ((values as { help: boolean }).help) {\n console.log(help);\n process.exit(0);\n }\n\n return { ...data, help };\n}\n","{\n \"name\": \"@autofleet/cli\",\n \"version\": \"2.5.5\",\n \"description\": \"\",\n \"main\": \"dist/index.js\",\n \"scripts\": {\n \"start\": \"tsx bin/index.ts\",\n \"dev\": \"tsup --watch\",\n \"build\": \"tsup\",\n \"linter\": \"eslint .\",\n \"test\": \"vitest\",\n \"coverage\": \"vitest --coverage\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^9.13.0\",\n \"@stylistic/eslint-plugin\": \"^2.9.0\",\n \"@types/eslint__js\": \"^8.42.3\",\n \"@types/node\": \"^22.7.8\",\n \"@vitest/coverage-v8\": \"^2.1.3\",\n \"eslint\": \"^9.13.0\",\n \"eslint-plugin-import\": \"^2.31.0\",\n \"tsup\": \"^8.3.0\",\n \"tsx\": \"^4.19.1\",\n \"typescript\": \"^5.6.3\",\n \"typescript-eslint\": \"^8.11.0\",\n \"vitest\": \"^2.1.3\"\n },\n \"bin\": {\n \"autofleet\": \"./dist/index.js\",\n \"autofleet-e2e\": \"./dist/e2e.js\",\n \"git-autofleet\": \"./dist/git-autofleet.js\"\n },\n \"engines\": {\n \"node\": \">= 18.3.0\"\n },\n \"type\": \"module\",\n \"author\": \"Autofleet\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"@inquirer/prompts\": \"^5.0.2\",\n \"p-retry\": \"^6.2.0\"\n },\n \"optionalDependencies\": {\n \"@rollup/rollup-linux-x64-gnu\": \"*\"\n }\n}\n","import { spawn } from 'node:child_process';\n\ndeclare global {\n interface PromiseWithResolvers<T> {\n promise: Promise<T>;\n resolve: (value: T | PromiseLike<T>) => void;\n reject: (reason?: any) => void; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n interface PromiseConstructor {\n /**\n * Creates a new Promise and returns it in an object, along with its resolve and reject functions.\n * @returns An object with the properties `promise`, `resolve`, and `reject`.\n *\n * ```ts\n * const { promise, resolve, reject } = Promise.withResolvers<T>();\n * ```\n */\n withResolvers<T>(): PromiseWithResolvers<T>;\n }\n}\n\ninterface SpawnResult {\n pid?: number;\n stdout: string;\n stderr: string;\n status: number | null;\n signal: string | null;\n}\n\nconst createDeferredPromise = <T>() => {\n if (Promise.withResolvers) {\n return Promise.withResolvers<T>();\n }\n let reject!: PromiseWithResolvers<T>['reject'];\n let resolve!: PromiseWithResolvers<T>['resolve'];\n const promise = new Promise<T>((res, rej) => {\n reject = rej;\n resolve = res;\n });\n return { promise, reject, resolve };\n};\n\nexport default async (command: string, args?: boolean | readonly string[], { print = true, env = {} }: { print?: boolean; env?: NodeJS.ProcessEnv } = {}) => {\n if (typeof args === 'boolean') {\n print = args;\n args = undefined;\n }\n const stubError = new Error();\n const callerStack = stubError.stack ? stubError.stack.replace(/^.*/, ' ...') : null;\n const { promise, reject, resolve } = createDeferredPromise<SpawnResult>();\n const child = spawn(command, args, { env: Object.assign(env, process.env) });\n if (print) {\n child.stdout.pipe(process.stdout);\n child.stderr.pipe(process.stderr);\n }\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (data) => {\n stdout += data;\n });\n child.stderr?.on('data', (data) => {\n stderr += data;\n });\n const completionEventName = print ? 'exit' : 'close';\n function errorListener(error: Error) {\n child.removeListener(completionEventName, completionListener);\n Object.assign(error, {\n pid: child.pid,\n stdout,\n stderr,\n status: null,\n signal: null,\n });\n reject(error);\n }\n function completionListener(code: number | null, signal: string | null) {\n child.removeListener('error', errorListener);\n const result: SpawnResult = {\n pid: child.pid,\n stdout,\n stderr,\n status: code,\n signal,\n };\n if (code !== 0) {\n const argumentString = (typeof args !== 'boolean' && ` ${args?.join(' ')}`) || '';\n const error = signal\n ? new Error(`${command}${argumentString} exited with signal: ${signal}`)\n : new Error(`${command}${argumentString} exited with non-zero code: ${code}`);\n if (error.stack && callerStack) {\n error.stack += `\\n${callerStack}`;\n }\n Object.assign(error, result);\n reject(error);\n } else {\n resolve(result);\n }\n }\n\n child.once(completionEventName, completionListener);\n child.once('error', errorListener);\n return promise;\n};\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport asyncSpawn from './asyncSpawn.js';\n\nconst IP_LINE_SUFFIX = 'SERVICE_HOST';\nconst CLUSTER_TO_CMD_MAP = {\n dev1: ['dev-cluster-2', 'europe-west1', 'dev1-experiment-manager'],\n e2eManager: ['e2e-cluster-2', 'europe-west1', 'e2e-project-1'],\n expManager: ['af-experiment-manager', 'europe-west1'],\n staging: ['autofleet-staging', 'europe-west1-b'],\n};\nexport const SUPPORTED_CLUSTERS = Object.keys(CLUSTER_TO_CMD_MAP) as (keyof typeof CLUSTER_TO_CMD_MAP)[];\n\nexport const replaceInFile = ({ newFilePath, filePath, linesToReplace }: { newFilePath: string; filePath: string; linesToReplace: { find: string; replace: string }[] }) => {\n let fileAsString = fs.readFileSync(filePath, 'utf8');\n for (const { find, replace } of linesToReplace) {\n fileAsString = fileAsString.replace(find, replace);\n }\n fs.writeFileSync(newFilePath, fileAsString);\n};\nexport const connectToCluster = async (clusterName: string) => {\n const command = CLUSTER_TO_CMD_MAP[clusterName as keyof typeof CLUSTER_TO_CMD_MAP];\n if (!command) {\n throw new Error(`Cluster name ${clusterName} does not exist!`);\n }\n const [name, region, project] = command;\n await asyncSpawn('gcloud', ['container', 'clusters', 'get-credentials', name, '--region', region, '--project', project || name], { print: false });\n};\nexport const connectAndGetPrefix = async ({ clusterName, variationId }: { clusterName: string; variationId: string }) => {\n await connectToCluster(clusterName);\n return `--namespace=${variationId}`;\n};\nexport const parseIps = (ips: string) => {\n const ipLines = ips.split('\\n').filter(Boolean);\n ipLines.shift();\n\n let formattedIps = ipLines.map((ipLine) => {\n const [name, _type, _clusterIp, externalIp, _port, _age] = ipLine.split(/(\\s+)/).map(s => s.trim()).filter(Boolean);\n const serviceName = name.replace(/-/g, '_').toUpperCase();\n const formattedLine = `${serviceName}_${IP_LINE_SUFFIX}=${externalIp}`;\n return formattedLine;\n });\n formattedIps = formattedIps.filter(formattedIp => !formattedIp.includes('none') && !formattedIp.includes('undefined'));\n return formattedIps;\n};\n\nexport const endWithError = (error: string | Error, helpText?: string): never => {\n if (!(error instanceof Error)) {\n error = new Error(error);\n }\n console.error(error);\n if (helpText) {\n console.log(helpText);\n }\n return process.exit(1);\n};\n"],"mappings":"wxBAAA,OAAS,aAAaA,MAAwC,YCE5D,IAAAC,EAAW,QDIb,IAAMC,EAAiB,CACrB,KAAM,CACJ,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,iCACf,EACA,QAAS,CACP,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,qBACf,CACF,EAKe,SAARC,EAAwEC,EAAsB,CACnGA,EAAO,QAAU,CAAE,GAAGF,EAAgB,GAAGE,EAAO,OAAQ,EACxD,IAAMC,EAAOC,EAAgBF,CAAqB,EAC5C,CAAE,OAAAG,CAAO,EAAIF,EACdE,EAAgC,UACnC,QAAQ,IAAIC,CAAO,EACnB,QAAQ,KAAK,CAAC,GAGhB,IAAMC,EAAYL,EAAO,SAAgB;AAAA;AAAA;AAAA,IAGvC,OAAO,QAAQA,EAAO,QAAQ,E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CACpB,IAAId,CAAc,IAAI2B,CAAU,EAEtE,CAAC,EACD,OAAAJ,EAAeA,EAAa,OAAOQ,GAAe,CAACA,EAAY,SAAS,MAAM,GAAK,CAACA,EAAY,SAAS,WAAW,CAAC,EAC9GR,CACT,EAEaS,EAAe,CAACC,EAAuBC,KAC5CD,aAAiB,QACrBA,EAAQ,IAAI,MAAMA,CAAK,GAEzB,QAAQ,MAAMA,CAAK,EACfC,GACF,QAAQ,IAAIA,CAAQ,EAEf,QAAQ,KAAK,CAAC","names":["nativeParseArgs","version","GLOBAL_OPTIONS","parseArgs","params","data","nativeParseArgs","values","version","commands","command","example","help","option","description","type","short","spawn","createDeferredPromise","reject","resolve","res","rej","asyncSpawn_default","command","args","print","env","stubError","callerStack","promise","child","stdout","stderr","data","completionEventName","errorListener","error","completionListener","code","signal","result","argumentString","fs","IP_LINE_SUFFIX","CLUSTER_TO_CMD_MAP","SUPPORTED_CLUSTERS","replaceInFile","newFilePath","filePath","linesToReplace","fileAsString","fs","find","replace","connectToCluster","clusterName","command","name","region","project","asyncSpawn_default","connectAndGetPrefix","variationId","parseIps","ips","ipLines","formattedIps","ipLine","_type","_clusterIp","externalIp","_port","_age","s","formattedIp","endWithError","error","helpText"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as d,b as m,d as s,e as y,j as u}from"./chunk-HHWZRNVZ.js";import{confirm as h,input as l,select as P}from"@inquirer/prompts";Symbol.dispose??=Symbol.for("nodejs.dispose");Symbol.asyncDispose??=Symbol.for("nodejs.asyncDispose");var f,g=()=>f?.();function b(){return process.once("beforeExit",g),{[Symbol.dispose](){process.off("beforeExit",g),f=void 0}}}async function n(e,...r){try{var t=[];try{let a=d(t,b());let p=e(...r);f=p.cancel;return await p}catch(o){var c=o,i=!0}finally{m(t,c,i)}}catch(a){a instanceof Error&&["CancelPromptError","ExitPromptError"].includes(a.constructor.name)&&u("Cancelled! \u{1F44B}"),u(a)}}function v(...e){return n(P,...e)}var x=e=>e.charAt(0).toUpperCase()+e.slice(1).split(/(?=[A-Z])/).join(" ");function S(){return v({message:"Which environment do you want to use?",choices:y.map(e=>({name:x(e),value:e})),default:"expManager"})}function T(){return n(l,{message:"Enter the service name:"})}function w(){return n(l,{message:"Enter your simulator id:"})}async function E(e="8080",r=!1){return n(l,{message:`Enter the ${r?"local ":""}port:`,default:e,validate(t){return/^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/.test(t)?!0:"Please enter a valid port number"}})}async function V(e="5432"){return E(e,!0)}var C={cluster:S,variationId:w,service:T,port:(e="8080")=>E(e),"local-port":V};async function k(e,r){for(let t of r){let o=typeof t=="object"?t.option:t,c=typeof t=="object"?t.defaultVal:void 0;if(typeof o!="string")throw new Error(`Invalid option ${String(o)}`);let i=C[o];if(!i)throw new Error(`No value getter for ${String(o)}`);e[o]??=await i(c)}return e}async function L(e,r=!0){return n(h,{message:e,default:r})}var q=async()=>{let{stdout:e}=await s("git",["branch","--show-current"],{print:!1});return e.trim()},M=async()=>{let{stdout:e}=await s("git",["rev-parse","--show-toplevel"],{print:!1});return e.trim()},D=async e=>{let{stdout:r}=await s("git",["diff","origin/master..",e],{print:!1});return r};export{v as a,w as b,V as c,k as d,L as e,q as f,M as g,D as h};
|
|
2
|
+
//# sourceMappingURL=chunk-UQU7WR36.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../bin/utils/inquirer.ts","../bin/utils/git.ts"],"sourcesContent":["import { confirm, input, select } from '@inquirer/prompts';\nimport type { Prompt } from '@inquirer/type';\nimport { SUPPORTED_CLUSTERS, endWithError } from './index.js';\n\ndeclare global {\n interface SymbolConstructor {\n /** A method that is used to release resources held by an object. Called by the semantics of the `using` statement. */\n readonly dispose: unique symbol;\n /** A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. */\n readonly asyncDispose: unique symbol;\n }\n}\n// @ts-expect-error polyfill for node < 18.18\nSymbol.dispose ??= Symbol.for('nodejs.dispose');\n// @ts-expect-error polyfill for node < 18.18\nSymbol.asyncDispose ??= Symbol.for('nodejs.asyncDispose');\nlet cancelFn: (() => void) | undefined;\nconst handler = () => cancelFn?.();\nfunction addExitListener() {\n process.once('beforeExit', handler);\n return {\n [Symbol.dispose]() {\n process.off('beforeExit', handler);\n cancelFn = undefined;\n },\n };\n}\n\nasync function inquirerWrapper<Value, Config>(fn: Prompt<Value, Config>, ...params: Parameters<Prompt<Value, Config>>) {\n try {\n using _ = addExitListener();\n const result = fn(...params);\n cancelFn = result.cancel;\n return await result;\n } catch (error) {\n if (error instanceof Error && ['CancelPromptError', 'ExitPromptError'].includes(error.constructor.name)) {\n endWithError('Cancelled! 👋');\n }\n endWithError(error as Error);\n }\n}\n\nexport function safeSelect<Value>(...params: Parameters<typeof select<Value>>) {\n return inquirerWrapper(select, ...params);\n}\n\nconst splitWordAtCapital = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).split(/(?=[A-Z])/).join(' ');\n\nfunction getEnvironment() {\n return safeSelect({\n message: 'Which environment do you want to use?',\n choices: SUPPORTED_CLUSTERS.map(cluster => ({ name: splitWordAtCapital(cluster), value: cluster })),\n default: 'expManager',\n });\n}\n\nfunction getServiceName() {\n return inquirerWrapper(input, { message: 'Enter the service name:' });\n}\n\nexport function getVariationId() {\n return inquirerWrapper(input, { message: 'Enter your simulator id:' });\n}\n\nasync function getPort(defaultVal = '8080', isLocal = false) {\n return inquirerWrapper(input, {\n message: `Enter the ${isLocal ? 'local ' : ''}port:`,\n default: defaultVal,\n validate(value) {\n // Regex source: https://stackoverflow.com/a/12968117\n if (!/^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/.test(value)) {\n return 'Please enter a valid port number';\n }\n return true;\n },\n });\n}\n\nexport async function getLocalPort(defaultVal = '5432') {\n return getPort(defaultVal, true);\n}\n\nconst VALUE_GETTER_MAP = {\n cluster: getEnvironment,\n variationId: getVariationId,\n service: getServiceName,\n port: (defaultVal = '8080') => getPort(defaultVal),\n 'local-port': getLocalPort,\n} as const;\n\nexport async function fillMissingRequiredValues<T extends { [key in keyof typeof VALUE_GETTER_MAP]?: string }>(values: T, requiredValues: (keyof T | { option: keyof T; defaultVal: string })[]) {\n for (const value of requiredValues) {\n const option = typeof value === 'object' ? value.option : value;\n const defaultVal = typeof value === 'object' ? value.defaultVal : undefined;\n if (typeof option !== 'string') {\n throw new Error(`Invalid option ${String(option)}`);\n }\n const getter = VALUE_GETTER_MAP[option as keyof typeof VALUE_GETTER_MAP];\n if (!getter) {\n throw new Error(`No value getter for ${String(option)}`);\n }\n\n values[option] ??= await getter(defaultVal) as T[keyof T & string];\n }\n return values;\n}\n\nexport async function promptForConfirmation(message: string, defaultVal = true) {\n return inquirerWrapper(confirm, { message, default: defaultVal });\n}\n","import asyncSpawn from './asyncSpawn.js';\n\nexport const getCurrentBranch = async () => {\n const { stdout: currentBranch } = await asyncSpawn('git', ['branch', '--show-current'], { print: false });\n return currentBranch.trim();\n};\n\nexport const getGitPath = async () => {\n const { stdout: gitPath } = await asyncSpawn('git', ['rev-parse', '--show-toplevel'], { print: false });\n return gitPath.trim();\n};\n\nexport const getChangesOfFile = async (filePath: string) => {\n const { stdout: changes } = await asyncSpawn('git', ['diff', 'origin/master..', filePath], { print: false });\n return changes;\n};\n"],"mappings":"oEAAA,OAAS,WAAAA,EAAS,SAAAC,EAAO,UAAAC,MAAc,oBAavC,OAAO,UAAY,OAAO,IAAI,gBAAgB,EAE9C,OAAO,eAAiB,OAAO,IAAI,qBAAqB,EACxD,IAAIC,EACEC,EAAU,IAAMD,IAAW,EACjC,SAASE,GAAkB,CACzB,eAAQ,KAAK,aAAcD,CAAO,EAC3B,CACL,CAAC,OAAO,OAAO,GAAI,CACjB,QAAQ,IAAI,aAAcA,CAAO,EACjCD,EAAW,MACb,CACF,CACF,CAEA,eAAeG,EAA+BC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EACT,YAAaK,EACb,QAASF,EACT,KAAM,CAACI,EAAa,SAAWD,EAAQC,CAAU,EACjD,aAAcG,CAChB,EAEA,eAAsBE,EAAyFC,EAAWC,EAAuE,CAC/L,QAAWL,KAASK,EAAgB,CAClC,IAAMC,EAAS,OAAON,GAAU,SAAWA,EAAM,OAASA,EACpDF,EAAa,OAAOE,GAAU,SAAWA,EAAM,WAAa,OAClE,GAAI,OAAOM,GAAW,SACpB,MAAM,IAAI,MAAM,kBAAkB,OAAOA,CAAM,CAAC,EAAE,EAEpD,IAAMC,EAASL,EAAiBI,CAAuC,EACvE,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,uBAAuB,OAAOD,CAAM,CAAC,EAAE,EAGzDF,EAAOE,CAAM,IAAM,MAAMC,EAAOT,CAAU,CAC5C,CACA,OAAOM,CACT,CAEA,eAAsBI,EAAsBC,EAAiBX,EAAa,GAAM,CAC9E,OAAOvB,EAAgBmC,EAAS,CAAE,QAAAD,EAAS,QAASX,CAAW,CAAC,CAClE,CC3GO,IAAMa,EAAmB,SAAY,CAC1C,GAAM,CAAE,OAAQC,CAAc,EAAI,MAAMC,EAAW,MAAO,CAAC,SAAU,gBAAgB,EAAG,CAAE,MAAO,EAAM,CAAC,EACxG,OAAOD,EAAc,KAAK,CAC5B,EAEaE,EAAa,SAAY,CACpC,GAAM,CAAE,OAAQC,CAAQ,EAAI,MAAMF,EAAW,MAAO,CAAC,YAAa,iBAAiB,EAAG,CAAE,MAAO,EAAM,CAAC,EACtG,OAAOE,EAAQ,KAAK,CACtB,EAEaC,EAAmB,MAAOC,GAAqB,CAC1D,GAAM,CAAE,OAAQC,CAAQ,EAAI,MAAML,EAAW,MAAO,CAAC,OAAQ,kBAAmBI,CAAQ,EAAG,CAAE,MAAO,EAAM,CAAC,EAC3G,OAAOC,CACT","names":["confirm","input","select","cancelFn","handler","addExitListener","inquirerWrapper","fn","params","_stack","_","__using","result","_error","_hasError","__callDispose","error","endWithError","safeSelect","select","splitWordAtCapital","str","getEnvironment","SUPPORTED_CLUSTERS","cluster","getServiceName","input","getVariationId","getPort","defaultVal","isLocal","value","getLocalPort","VALUE_GETTER_MAP","fillMissingRequiredValues","values","requiredValues","option","getter","promptForConfirmation","message","confirm","getCurrentBranch","currentBranch","asyncSpawn_default","getGitPath","gitPath","getChangesOfFile","filePath","changes"]}
|
package/dist/e2e.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
2
|
+
import{c as p,d as t,f as m,h as d,i as h,j as s}from"./chunk-HHWZRNVZ.js";import u from"node:path";import y from"p-retry";var E=["identity-ms","vehicle-ms","ride-ms","vehicle-live-data-ms","pricing-ms","payment-ms","route-plan-ms","task-ms","audit-ms","pgweb","queue-ms","placement-ms","demand-prediction-ms","control-center-ms","setting-ms","api-gateway-ms"],f={start:'--e2eBranch=<branchName> --branches="{\\"ride-ms\\": \\"AUT-7070\\"}"',getIpsForEnv:"--variationId=<yourVariationUuid> --cluster=<dev1/e2eManager>"},_=e=>Object.keys(f).includes(e),{positionals:g,values:o,help:c}=p({strict:!0,binName:"autofleet-e2e",allowPositionals:!0,options:{e2eBranch:{type:"string",default:"master",description:"Name of e2e branch"},branches:{type:"string",default:"",description:'"ride-ms": "AUT-7070"'},cluster:{type:"string",short:"c",description:"The cluster name. One of dev1, e2eManager, expManager"},variationId:{type:"string",short:"i",description:"The variation id"}},commands:f});g.length||(console.log(c),process.exit(0));var[a]=g;if(!_(a))throw s(new Error(`Command ${a} does not exist`),c),new Error("Typescript is not clever enough to understand that endWithError will exit the process");if(a==="start"){let i=(o.branches?.replace("{"," ")||"").replace(/[^a-z0-9]/gi,""),r=`${u.resolve()}/bin/utils/e2e.sh`,l=`${u.resolve()}/e2e.sh`;m({newFilePath:l,filePath:r,linesToReplace:[{find:"$E2E_BRANCH_PLACE_HOLDER$",replace:o.e2eBranch},{find:"$BRANCHES_PLACE_HOLDER$",replace:o.branches},{find:"$NAME_PLACE_HOLDER$",replace:i}]}),await t("chmod",[`+x ${l} && ${l}`]),console.log("finished e2e")}var{cluster:w,variationId:v}=o;if(!w)throw s(new Error("cluster required"),c),new Error("Typescript is not clever enough to understand that endWithError will exit the process");if(!v)throw s(new Error("variationId required"),c),new Error("Typescript is not clever enough to understand that endWithError will exit the process");var n;try{n=await d({clusterName:w,variationId:v})}catch(e){s(e)}a==="getIpsForEnv"&&(await Promise.all(E.map(e=>t("kubectl",["annotate",n,"service",e,"cloud.google.com/load-balancer-type-"],{print:!1}))),await Promise.all(E.map(e=>t("kubectl",["patch","svc",n,e,"-p",'{"spec": {"type": "LoadBalancer"}}'],{print:!1}))),console.log("exposed services successfully. the services are now creating public ips."),await y(async()=>{let{stdout:e}=await t("kubectl",[n,"get","services"],{print:!1}),i=h(e);if(i.some(r=>r.includes("<pending>")))throw new Error("Some services are still pending");i.forEach(r=>console.log(r))},{retries:10,factor:1,maxTimeout:5e3,randomize:!0}),process.exit(0));
|
|
3
|
+
//# sourceMappingURL=e2e.js.map
|
package/dist/e2e.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../bin/e2e.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport path from 'node:path';\nimport pRetry from 'p-retry';\nimport parseArgs from './utils/parser.js';\nimport asyncSpawn from './utils/asyncSpawn.js';\nimport {\n connectAndGetPrefix, endWithError, parseIps, replaceInFile,\n} from './utils/index.js';\n\nconst SERVICES_TO_EXPOSE = [\n 'identity-ms',\n 'vehicle-ms',\n 'ride-ms',\n 'vehicle-live-data-ms',\n 'pricing-ms',\n 'payment-ms',\n 'route-plan-ms',\n 'task-ms',\n 'audit-ms',\n 'pgweb',\n 'queue-ms',\n 'placement-ms',\n 'demand-prediction-ms',\n 'control-center-ms',\n 'setting-ms',\n 'api-gateway-ms',\n] as const;\n\nconst COMMANDS = {\n start: '--e2eBranch=<branchName> --branches=\"{\\\\\"ride-ms\\\\\": \\\\\"AUT-7070\\\\\"}\"',\n getIpsForEnv: '--variationId=<yourVariationUuid> --cluster=<dev1/e2eManager>',\n};\nconst isCommand = (c: string): c is keyof typeof COMMANDS => Object.keys(COMMANDS).includes(c);\n\nconst { positionals, values, help } = parseArgs({\n strict: true,\n binName: 'autofleet-e2e',\n allowPositionals: true,\n options: {\n e2eBranch: {\n type: 'string',\n default: 'master',\n description: 'Name of e2e branch',\n },\n branches: {\n type: 'string',\n default: '',\n description: '\"ride-ms\": \"AUT-7070\"',\n },\n cluster: {\n type: 'string',\n short: 'c',\n description: 'The cluster name. One of dev1, e2eManager, expManager',\n },\n variationId: {\n type: 'string',\n short: 'i',\n description: 'The variation id',\n },\n },\n commands: COMMANDS,\n});\n\nif (!positionals.length) {\n console.log(help);\n process.exit(0);\n}\n\nconst [command] = positionals;\nif (!isCommand(command)) {\n endWithError(new Error(`Command ${command} does not exist`), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\n\nif (command === 'start') {\n const name = values.branches?.replace('{', ' ') || '';\n const formattedName = name.replace(/[^a-z0-9]/gi, '');\n const E2E_SCRIPT_TEMPLATE_FILE_PATH = `${path.resolve()}/bin/utils/e2e.sh`;\n const NEW_E2E_SCRIPT_FILE_PATH = `${path.resolve()}/e2e.sh`;\n replaceInFile({\n newFilePath: NEW_E2E_SCRIPT_FILE_PATH,\n filePath: E2E_SCRIPT_TEMPLATE_FILE_PATH,\n linesToReplace: [\n {\n find: '$E2E_BRANCH_PLACE_HOLDER$',\n replace: values.e2eBranch,\n },\n {\n find: '$BRANCHES_PLACE_HOLDER$',\n replace: values.branches,\n },\n {\n find: '$NAME_PLACE_HOLDER$',\n replace: formattedName,\n },\n ],\n });\n await asyncSpawn('chmod', [`+x ${NEW_E2E_SCRIPT_FILE_PATH} && ${NEW_E2E_SCRIPT_FILE_PATH}`]);\n console.log('finished e2e');\n}\n\nconst { cluster, variationId } = values;\nif (!cluster) {\n endWithError(new Error('cluster required'), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\nif (!variationId) {\n endWithError(new Error('variationId required'), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\nlet prefix: string;\ntry {\n prefix = await connectAndGetPrefix({ clusterName: cluster, variationId });\n} catch (error) {\n endWithError(error as Error);\n}\n\nif (command === 'getIpsForEnv') {\n await Promise.all(SERVICES_TO_EXPOSE.map(service => asyncSpawn('kubectl', ['annotate', prefix, 'service', service, 'cloud.google.com/load-balancer-type-'], { print: false })));\n await Promise.all(SERVICES_TO_EXPOSE.map(service => asyncSpawn('kubectl', ['patch', 'svc', prefix, service, '-p', '{\"spec\": {\"type\": \"LoadBalancer\"}}'], { print: false })));\n console.log('exposed services successfully. the services are now creating public ips.');\n await pRetry(async () => {\n const { stdout } = await asyncSpawn('kubectl', [prefix, 'get', 'services'], { print: false });\n const ips = parseIps(stdout);\n if (ips.some(ip => ip.includes('<pending>'))) {\n throw new Error('Some services are still pending');\n }\n ips.forEach(ip => console.log(ip));\n }, {\n retries: 10, factor: 1, maxTimeout: 5000, randomize: true,\n });\n process.exit(0);\n}\n"],"mappings":";2EAEA,OAAOA,MAAU,YACjB,OAAOC,MAAY,UAOnB,IAAMC,EAAqB,CACzB,cACA,aACA,UACA,uBACA,aACA,aACA,gBACA,UACA,WACA,QACA,WACA,eACA,uBACA,oBACA,aACA,gBACF,EAEMC,EAAW,CACf,MAAO,wEACP,aAAc,+DAChB,EACMC,EAAaC,GAA0C,OAAO,KAAKF,CAAQ,EAAE,SAASE,CAAC,EAEvF,CAAE,YAAAC,EAAa,OAAAC,EAAQ,KAAAC,CAAK,EAAIC,EAAU,CAC9C,OAAQ,GACR,QAAS,gBACT,iBAAkB,GAClB,QAAS,CACP,UAAW,CACT,KAAM,SACN,QAAS,SACT,YAAa,oBACf,EACA,SAAU,CACR,KAAM,SACN,QAAS,GACT,YAAa,uBACf,EACA,QAAS,CACP,KAAM,SACN,MAAO,IACP,YAAa,uDACf,EACA,YAAa,CACX,KAAM,SACN,MAAO,IACP,Y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,sCAAsC,EAAG,CAAE,MAAO,EAAM,CAAC,CAAC,CAAC,EAC9K,MAAM,QAAQ,IAAIrB,EAAmB,IAAIqB,GAAWN,EAAW,UAAW,CAAC,QAAS,MAAOG,EAAQG,EAAS,KAAM,oCAAoC,EAAG,CAAE,MAAO,EAAM,CAAC,CAAC,CAAC,EAC3K,QAAQ,IAAI,0EAA0E,EACtF,MAAMC,EAAO,SAAY,CACvB,GAAM,CAAE,OAAAC,CAAO,EAAI,MAAMR,EAAW,UAAW,CAACG,EAAQ,MAAO,UAAU,EAAG,CAAE,MAAO,EAAM,CAAC,EACtFM,EAAMC,EAASF,CAAM,EAC3B,GAAIC,EAAI,KAAKE,GAAMA,EAAG,SAAS,WAAW,CAAC,EACzC,MAAM,IAAI,MAAM,iCAAiC,EAEnDF,EAAI,QAAQE,GAAM,QAAQ,IAAIA,CAAE,CAAC,CACnC,EAAG,CACD,QAAS,GAAI,OAAQ,EAAG,WAAY,IAAM,UAAW,EACvD,CAAC,EACD,QAAQ,KAAK,CAAC","names":["path","pRetry","SERVICES_TO_EXPOSE","COMMANDS","isCommand","c","positionals","values","help","parseArgs","command","endWithError","formattedName","E2E_SCRIPT_TEMPLATE_FILE_PATH","path","NEW_E2E_SCRIPT_FILE_PATH","replaceInFile","asyncSpawn_default","cluster","variationId","prefix","connectAndGetPrefix","error","service","pRetry","stdout","ips","parseIps","ip"]}
|
package/dist/git-autofleet.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as w,e as u,f as
|
|
3
|
-
Version type can be one of: ${h.join(", ")}`),p);let t=await
|
|
4
|
-
Version must be a prerelease type. (${
|
|
5
|
-
`).some(
|
|
2
|
+
import{a as w,e as u,f as l,g as d,h as b}from"./chunk-UQU7WR36.js";import{c as g,d as r,j as n}from"./chunk-HHWZRNVZ.js";import{basename as P}from"node:path";import{randomUUID as V}from"node:crypto";var m=["premajor","preminor","prepatch","prerelease"],h=["major","minor","patch",...m],v={bumpVersion:`[${h.join("|")}]`,openPR:"Opens github UI for creating a PR from the current branch.",releaseBeta:"Bumps version if needed, and publishes a beta release to NPM."},j=e=>Object.keys(v).includes(e),y=async(e,t="")=>{let{stdout:o}=await r("npm",["version",e,"--no-git-tag-version","--preid",t],{print:!1});return await r("git",["add","package*"],{print:!1}),await r("git",["commit","-m",`${e} version: ${o}`],{print:!1}),console.log(`Created commit for version bump: ${e}. Version is now ${o}`),o},x=async()=>{let e=await d(),{default:{version:t}}=await import(`${e}/package.json`,{assert:{type:"json"},with:{type:"json"}});return t.replace(/\d+\.\d+\.\d+(?:-beta-([\w]+)?\.\d+)?/,"$1")},{positionals:$,help:p}=g({strict:!0,binName:"git autofleet",allowPositionals:!0,options:{},commands:v});$.length||(console.log(p),process.exit(0));var[s,a]=$;if(!j(s))throw n(new Error(`Command ${s} does not exist`),p),new Error("Typescript is not clever enough to understand that endWithError will exit the process");if(s==="openPR"){let[e,t]=await Promise.all([d(),l()]),c=`https://github.com/Autofleet/${P(e)}/compare/${t}?expand=1`;await r("open",[c],{print:!1}),process.exit(0)}if(s==="bumpVersion"){let e=a||await w({message:"Which version type do you want to bump?",choices:(s==="bumpVersion"?h:m).map(o=>({name:o,value:o}))});if(!e)throw n(new Error(`Must explicitly define version type.
|
|
3
|
+
Version type can be one of: ${h.join(", ")}`),p),new Error("Typescript is not clever enough to understand that endWithError will exit the process");let t=await l();["main","master"].includes(t)&&(await u("Are you sure you want to bump version on main branch?")||process.exit(0)),await y(e),process.exit(0)}if(s==="releaseBeta"){a&&!m.includes(a)&&n(new Error(`Invalid version type: ${a}
|
|
4
|
+
Version must be a prerelease type. (${m.join(", ")})`),p);let e=await l();["main","master"].includes(e)&&n(new Error("Cannot release beta from main branch"),p);let c=!(await b("package.json")).split(`
|
|
5
|
+
`).some(i=>/^\+\s*"version":\s*"\d+\.\d+\.\d+(?:-(?:[\w-]+\.)?\d+)?",/.test(i))||await u("Version already bumped on branch. Should version be re-bumped?"),C=c&&await x(),f=c&&await y(a||"prerelease",`beta-${C||V().split("-")[0]}`);await r("npm",["run","build"]);try{await r("npm",["publish","--tag","beta","--@autofleet:registry=https://registry.npmjs.org"])}catch(i){console.error(i),n("Failed to publish beta version")}if(f)console.log(`Published beta version with new version: ${f}`);else{let{stdout:i}=await r("npm",["info",".","version"],{print:!1});console.log(`Published beta version with existing version: ${i}`)}process.exit(0)}
|
|
6
|
+
//# sourceMappingURL=git-autofleet.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../bin/git-autofleet.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { basename } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport parseArgs from './utils/parser.js';\nimport asyncSpawn from './utils/asyncSpawn.js';\nimport { endWithError } from './utils/index.js';\nimport { promptForConfirmation, safeSelect } from './utils/inquirer.js';\nimport { getChangesOfFile, getCurrentBranch, getGitPath } from './utils/git.js';\n\nconst preReleaseVersionTypes = ['premajor', 'preminor', 'prepatch', 'prerelease'] as const;\nconst versionTypes = ['major', 'minor', 'patch', ...preReleaseVersionTypes] as const;\n\nconst COMMANDS = {\n bumpVersion: `[${versionTypes.join('|')}]`,\n openPR: 'Opens github UI for creating a PR from the current branch.',\n releaseBeta: 'Bumps version if needed, and publishes a beta release to NPM.',\n};\nconst isCommand = (c: string): c is keyof typeof COMMANDS => Object.keys(COMMANDS).includes(c);\nconst bumpVersion = async (versionType: string, preReleaseId = ''): Promise<string> => {\n const { stdout: newVersion } = await asyncSpawn('npm', ['version', versionType, '--no-git-tag-version', '--preid', preReleaseId], { print: false });\n await asyncSpawn('git', ['add', 'package*'], { print: false });\n await asyncSpawn('git', ['commit', '-m', `${versionType} version: ${newVersion}`], { print: false });\n console.log(`Created commit for version bump: ${versionType}. Version is now ${newVersion}`);\n return newVersion;\n};\nconst getCurrentPackageVersionPrereleaseId = async () => {\n const path = await getGitPath();\n const { default: { version } } = await import(`${path}/package.json`, { assert: { type: 'json' }, with: { type: 'json' } } as ImportCallOptions) as { default: { version: string } };\n\n return version.replace(/\\d+\\.\\d+\\.\\d+(?:-beta-([\\w]+)?\\.\\d+)?/, '$1');\n};\n\nconst { positionals, help } = parseArgs({\n strict: true,\n binName: 'git autofleet',\n allowPositionals: true,\n options: {},\n commands: COMMANDS,\n});\n\nif (!positionals.length) {\n console.log(help);\n process.exit(0);\n}\n\nconst [command, versionType] = positionals;\nif (!isCommand(command)) {\n endWithError(new Error(`Command ${command} does not exist`), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\n\nif (command === 'openPR') {\n const [gitPath, currentBranch] = await Promise.all([getGitPath(), getCurrentBranch()]);\n const repoName = basename(gitPath);\n const url = `https://github.com/Autofleet/${repoName}/compare/${currentBranch}?expand=1`;\n await asyncSpawn('open', [url], { print: false });\n process.exit(0);\n}\n\nif (command === 'bumpVersion') {\n const finalVersionType = versionType || await safeSelect({\n message: 'Which version type do you want to bump?',\n choices: (command === 'bumpVersion' ? versionTypes : preReleaseVersionTypes).map(type => ({ name: type, value: type })),\n });\n if (!finalVersionType) {\n endWithError(new Error(`Must explicitly define version type.\\n\\tVersion type can be one of: ${versionTypes.join(', ')}`), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n }\n const currentBranch = await getCurrentBranch();\n if (['main', 'master'].includes(currentBranch)) {\n const shouldProceed = await promptForConfirmation('Are you sure you want to bump version on main branch?');\n if (!shouldProceed) {\n process.exit(0);\n }\n }\n await bumpVersion(finalVersionType);\n process.exit(0);\n}\n\nif (command === 'releaseBeta') {\n if (versionType && !preReleaseVersionTypes.includes(versionType as typeof preReleaseVersionTypes[number])) {\n endWithError(new Error(`Invalid version type: ${versionType}\\n\\tVersion must be a prerelease type. (${preReleaseVersionTypes.join(', ')})`), help);\n }\n const currentBranch = await getCurrentBranch();\n if (['main', 'master'].includes(currentBranch)) {\n endWithError(new Error('Cannot release beta from main branch'), help);\n }\n const packageChanges = await getChangesOfFile('package.json');\n const versionChanged = packageChanges.split('\\n').some(line => /^\\+\\s*\"version\":\\s*\"\\d+\\.\\d+\\.\\d+(?:-(?:[\\w-]+\\.)?\\d+)?\",/.test(line));\n const shouldReBump = !versionChanged || await promptForConfirmation('Version already bumped on branch. Should version be re-bumped?');\n const preReleaseId = shouldReBump && await getCurrentPackageVersionPrereleaseId();\n const newVersion = shouldReBump && await bumpVersion(versionType || 'prerelease', `beta-${preReleaseId || randomUUID().split('-')[0]}`);\n await asyncSpawn('npm', ['run', 'build']);\n try {\n await asyncSpawn('npm', ['publish', '--tag', 'beta', '--@autofleet:registry=https://registry.npmjs.org']);\n } catch (e) {\n console.error(e);\n endWithError('Failed to publish beta version');\n }\n if (newVersion) {\n console.log(`Published beta version with new version: ${newVersion}`);\n } else {\n const { stdout: previousVersion } = await asyncSpawn('npm', ['info', '.', 'version'], { print: false });\n console.log(`Published beta version with existing version: ${previousVersion}`);\n }\n process.exit(0);\n}\n"],"mappings":";0HAEA,OAAS,YAAAA,MAAgB,YACzB,OAAS,cAAAC,MAAkB,cAO3B,IAAMC,EAAyB,CAAC,WAAY,WAAY,WAAY,YAAY,EAC1EC,EAAe,CAAC,QAAS,QAAS,QAAS,GAAGD,CAAsB,EAEpEE,EAAW,CACf,YAAa,IAAID,EAAa,KAAK,GAAG,CAAC,IACvC,OAAQ,6DACR,YAAa,+DACf,EACME,EAAaC,GAA0C,OAAO,KAAKF,CAAQ,EAAE,SAASE,CAAC,EACvFC,EAAc,MAAOC,EAAqBC,EAAe,KAAwB,CACrF,GAAM,CAAE,OAAQC,CAAW,EAAI,MAAMC,EAAW,MAAO,CAAC,UAAWH,EAAa,uBAAwB,UAAWC,CAAY,EAAG,CAAE,MAAO,EAAM,CAAC,EAClJ,aAAME,EAAW,MAAO,CAAC,MAAO,UAAU,EAAG,CAAE,MAAO,EAAM,CAAC,EAC7D,MAAMA,EAAW,MAAO,CAAC,SAAU,KAAM,GAAGH,CAAW,aAAaE,CAAU,EAAE,EAAG,CAAE,MAAO,EAAM,C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G,QAAQ,IAAI,iDAAiDwB,CAAe,EAAE,CAChF,CACA,QAAQ,KAAK,CAAC,CAChB","names":["basename","randomUUID","preReleaseVersionTypes","versionTypes","COMMANDS","isCommand","c","bumpVersion","versionType","preReleaseId","newVersion","asyncSpawn_default","getCurrentPackageVersionPrereleaseId","path","getGitPath","version","positionals","help","parseArgs","command","endWithError","gitPath","currentBranch","getCurrentBranch","url","basename","finalVersionType","safeSelect","type","promptForConfirmation","shouldReBump","getChangesOfFile","line","randomUUID","e","previousVersion"]}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
https://www.telepresence.io/docs/latest/quick-start/`)}}function
|
|
4
|
-
access the DB at ${
|
|
5
|
-
Press ctrl+c to stop.`)
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import{a as P,b as T,c as I,d as _,f as C,g as D}from"./chunk-UQU7WR36.js";import{c as y,d as r,e as S,g as h,h as x,i as N,j as n}from"./chunk-HHWZRNVZ.js";import{cwd as F}from"node:process";import{basename as M}from"node:path";import{setTimeout as j}from"node:timers/promises";async function V(){try{await r("telepresence",["version"],{print:!1})}catch{n(`Telepresence is not installed. Please install it from:
|
|
3
|
+
https://www.telepresence.io/docs/latest/quick-start/`)}}function B(){return P({message:"Do you want to leave the connection or create a new one?",choices:[{name:"Leave the current connection",value:"leave"},{name:"Create a new connection",value:"connect"}],default:"connect"})}async function $(e){await V();let{cluster:o="",service:t=""}=e;await h(o);let a=await B();if(["leave","connect"].includes(a)||n("Invalid action, how did you get here? \u{1F914}"),a==="leave"){await r("telepresence",["leave",t]),console.log("Disconnected! \u{1F44B}");return}let u=e.variationId||await T(),s=e["local-port"]&&Number.parseInt(e["local-port"],10)||Number.parseInt(await I()||"",10);await r("telepresence",["connect",`--namespace=${u}`]),await r("telepresence",["intercept",t,"--port",s.toString(),"--env-file=./.env"]),console.log("Everything is set up! \u{1F680}"),console.log(`You can now access the service at localhost:${s}`),console.log("You can only have one connection at a time. If you want to connect to a different service, you need to leave the current connection first.")}import{EOL as A}from"node:os";import{resolve as L}from"node:path";import{readFile as U,writeFile as q}from"node:fs/promises";async function k(e,o,t){let a=L(e,".env"),s=(await U(a,"utf8")).split(A),g=`(?<!#\\s*)${o}(?==)`,w=s.find(R=>R.match(g));if(w?.split("=").at(-1)===t){console.log("env file already up to date!");return}let E=w?s.indexOf(w):-1;return E!==-1?s.splice(E,1,`${o}=${t}`):s.push(`${o}=${t}`),q(a,s.join(A))}var W=S.join("/"),p=`--variationId=<yourVariationUuid> --cluster=<${W}>`,O={switchCluster:`--cluster=<${W}>`,exposeService:`--service=<driver-ms> ${p}`,forwardDb:`${p} --local-port=<localPort>`,forwardService:`--service=<driver-ms> ${p} --port=<port> --local-port=<localPort>`,getIps:p,enableSimulator:p,rabbitCreds:p,updateExp:p,telepresenceWizard:`--service=<driver-ms> ${p} --local-port=<localPort>`,localDev:p},G=e=>Object.keys(O).includes(e),{positionals:b,values:m,help:l}=y({strict:!0,binName:"autofleet",allowPositionals:!0,options:{cluster:{type:"string",short:"c",description:"The cluster name. One of dev1, e2eManager, expManager"},variationId:{type:"string",short:"i",description:"The variation id"},service:{type:"string",short:"s",description:"The service name"},port:{type:"string",short:"p",description:"The remote port to forward"},"local-port":{type:"string",short:"l",description:"The local port to forward to"}},commands:O}),z={switchCluster:["cluster"],exposeService:["cluster","variationId","service"],forwardDb:["cluster","variationId",{option:"local-port",defaultVal:"5432"}],forwardService:["cluster","variationId","service","port"],telepresenceWizard:["cluster","service"]};b.length||(console.log(l),process.exit(0));b.length>1&&n("Only one command is allowed",l);var[c]=b;if(!G(c))throw n(new Error(`Command ${c} does not exist`),l),new Error("Typescript is not clever enough to understand that endWithError will exit the process");await _(m,z[c]??["cluster","variationId"]);var{cluster:v,variationId:f,service:d}=m;if(!v)throw n(new Error("cluster required"),l),new Error("Typescript is not clever enough to understand that endWithError will exit the process");c==="telepresenceWizard"&&(await $(m),process.exit(0));c==="switchCluster"&&(await h(v),console.log(`switched to ${v} successfully`),process.exit(0));if(!f)throw n(new Error("variationId required"),l),new Error("Typescript is not clever enough to understand that endWithError will exit the process");var i;try{i=await x({clusterName:v,variationId:f})}catch(e){throw n(e),new Error("Typescript is not clever enough to understand that endWithError will exit the process")}if(c==="exposeService"){if(!d)throw n(new Error("service is required for exposeService"),l),new Error("Typescript is not clever enough to understand that endWithError will exit the process");await r("kubectl",["patch","svc",i,d,"-p",'{"spec": {"type": "LoadBalancer"}}']),console.log(`exposed ${d} successfully. the service is now creating an internal load balancer ip to use with vpn`),process.exit(0)}if(c==="forwardDb"){let e=Number.parseInt(m["local-port"]??"5432",10);Number.isNaN(e)&&n(new Error("if defined, local-port must be a number"),l);let o=`afpass_${f}`,t="postgres",a=f.replaceAll("-","_"),u=d?`${d.replaceAll("-","_")||""}_${a}`:"postgres",s=`postgres://${t}:${o}@localhost:${e}/${u}?&nickname=var_${f}`;console.log(`Forwarding db to local port ${e}.
|
|
4
|
+
access the DB at ${s}
|
|
5
|
+
Press ctrl+c to stop.`);let g=` DB_USERNAME=${t}
|
|
6
|
+
DB_PASSWORD=${o}
|
|
7
|
+
DB_NAME=${d?u:`<service_name>_${a}`}`;console.log(`Generated database environment for local development:
|
|
8
|
+
`,g),j(1500).then(()=>r("open",[s],{print:!1})).catch(()=>null),await r("kubectl",[i,"port-forward",`statefulset/p${f}-postgresql`,`${e}:5432`],{print:!1}),process.exit(0)}if(c==="forwardService"){let e=Number.parseInt(m.port??"8080",10),o=Number.parseInt(m["local-port"]??"",10)||e;d||n(new Error("service is required for forwardService"),l),(!e||Number.isNaN(e))&&n(new Error("port is required and must be a numbers"),l),o&&Number.isNaN(o)&&n(new Error("local-port must be a number"),l);let{stdout:t}=await r("kubectl",["get","pods",i,"-l",`service=${d}`,"-o",'jsonpath="{.items[0].metadata.name}"'],{print:!1});t&&=t.trim(),t||n(new Error(`No pods found for service ${d}`)),t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1)),console.log(`Found pod ${t}, serving locally on port ${o} from remote port ${e}.
|
|
9
|
+
Press ctrl+c to stop.`),await r("kubectl",["port-forward",i,t,`${o}:${e}`],{print:!1}),process.exit(0)}if(c==="getIps"){let{stdout:e}=await r("kubectl",[i,"get","services"],{print:!1});N(e).forEach(t=>console.log(t)),process.exit(0)}if(c==="enableSimulator"){let e="simulation-cluster-front";await r("kubectl",["annotate",i,"service",e,"cloud.google.com/load-balancer-type-"]),await r("kubectl",["patch","svc",i,e,"-p",'{"spec": {"type": "LoadBalancer"}}']),await r("kubectl",["create",i,"rolebinding","admin","--clusterrole=cluster-admin",`--serviceaccount=${f}:default`]),console.log(`Successfully exposed ${e} and added role binding to dispatch simulations`),process.exit(0)}if(c==="rabbitCreds"){let e=a=>["get","secret","rabbitmq-default-user","-o",`jsonpath="{.data.${a}}"`],[{stdout:o},{stdout:t}]=await Promise.all([r("kubectl",e("username"),{print:!1}),r("kubectl",e("password"),{print:!1})]);console.log(`username: ${Buffer.from(o,"base64").toString("ascii")}`),console.log(`password: ${Buffer.from(t,"base64").toString("ascii")}`),process.exit(0)}if(c==="updateExp"){let e=M(F()),[o,t]=await Promise.all([C(),r("uname",["-m"],{print:!1})]),a=t.stdout.trim(),u=`${new Date().getHours().toString().padStart(2,"0")}-${new Date().getMinutes().toString().padStart(2,"0")}-${new Date().getSeconds().toString().padStart(2,"0")}`,s=`gcr.io/autofleetprod/${e}:${o}-${u}`;console.log(`Building and pushing image ${s}`),await r("docker",["build",".",...a==="x86_64"?[]:["--platform","linux/amd64"],"-t",s,"--build-arg",`NPM_TOKEN=${process.env.NPM_TOKEN}`]),await r("docker",["push",s]);let{stdout:w}=await r("kubectl",["describe","pod",i,"-l",`service=${e}`],{print:!1});w.includes("Init Containers:")&&await r("kubectl",["patch",`deployment/${e}`,i,"--patch",`{"spec": {"template": {"spec": {"initContainers": [{"name": "init","image": "${s}"}]}}}}`]),await r("kubectl",["set","image",`deployment/${e}`,`worker=${s}`,i]),await r("kubectl",["rollout","status","deployments",e,i]),process.exit(0)}if(c==="localDev"){let e="api-gateway-ms",o="control-center-ms",t=await D();M(t)!=="control-center"&&n(new Error("The `localDev` command must be run from the control-center repository"));let{stdout:a}=await r("kubectl",["get","ingress",`${e}-ingress`,i,"-o",'jsonpath="{.status.loadBalancer.ingress[0].ip}"'],{print:!1});a||n(new Error(`The IP of the Load balancer for ${e} was not found`)),await k(t,"API_GATEWAY_MS_SERVICE_HOST",a.replace(/"/g,"")),console.log(`Updated .env file to use ${e} IP (${a}). Will now start port-forwarding ${o} to port 8085.
|
|
10
|
+
Press ctrl+c to stop.`),await r("kubectl",["port-forward",i,`svc/${o}`,"8085:80"],{print:!1}),process.exit(0)}
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../bin/index.ts","../bin/utils/telepresenceWizard.ts","../bin/utils/env.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { cwd } from 'node:process';\nimport { basename } from 'node:path';\nimport { setTimeout } from 'node:timers/promises';\nimport parseArgs from './utils/parser.js';\nimport asyncSpawn from './utils/asyncSpawn.js';\nimport {\n SUPPORTED_CLUSTERS,\n connectAndGetPrefix, connectToCluster, endWithError, parseIps,\n} from './utils/index.js';\nimport { fillMissingRequiredValues } from './utils/inquirer.js';\nimport telepresenceWizard from './utils/telepresenceWizard.js';\nimport { getCurrentBranch, getGitPath } from './utils/git.js';\nimport { setEnvValue } from './utils/env.js';\n\nconst clusterOptions = SUPPORTED_CLUSTERS.join('/');\nconst variationAndCluster = `--variationId=<yourVariationUuid> --cluster=<${clusterOptions}>`;\n\nconst COMMANDS = {\n switchCluster: `--cluster=<${clusterOptions}>`,\n exposeService: `--service=<driver-ms> ${variationAndCluster}`,\n forwardDb: `${variationAndCluster} --local-port=<localPort>`,\n forwardService: `--service=<driver-ms> ${variationAndCluster} --port=<port> --local-port=<localPort>`,\n getIps: variationAndCluster,\n enableSimulator: variationAndCluster,\n rabbitCreds: variationAndCluster,\n updateExp: variationAndCluster,\n telepresenceWizard: `--service=<driver-ms> ${variationAndCluster} --local-port=<localPort>`,\n localDev: variationAndCluster,\n};\ntype Command = keyof typeof COMMANDS;\nconst isCommand = (c: string): c is Command => Object.keys(COMMANDS).includes(c);\n\nconst { positionals, values, help } = parseArgs({\n strict: true,\n binName: 'autofleet',\n allowPositionals: true,\n options: {\n cluster: {\n type: 'string',\n short: 'c',\n description: 'The cluster name. One of dev1, e2eManager, expManager',\n },\n variationId: {\n type: 'string',\n short: 'i',\n description: 'The variation id',\n },\n service: {\n type: 'string',\n short: 's',\n description: 'The service name',\n },\n port: {\n type: 'string',\n short: 'p',\n description: 'The remote port to forward',\n },\n 'local-port': {\n type: 'string',\n short: 'l',\n description: 'The local port to forward to',\n },\n },\n commands: COMMANDS,\n});\n\nexport type Values = typeof values;\ntype ValueWithDefault<T = keyof Values> = T | { option: T; defaultVal: string };\n\nconst COMMAND_REQUIRED_VALUES_MAP: Partial<Record<Command, ValueWithDefault[]>> = {\n switchCluster: ['cluster'],\n exposeService: ['cluster', 'variationId', 'service'],\n forwardDb: ['cluster', 'variationId', { option: 'local-port', defaultVal: '5432' }],\n forwardService: ['cluster', 'variationId', 'service', 'port'],\n telepresenceWizard: ['cluster', 'service'],\n};\n\nif (!positionals.length) {\n console.log(help);\n process.exit(0);\n}\n\nif (positionals.length > 1) {\n endWithError('Only one command is allowed', help);\n}\n\nconst [command] = positionals;\nif (!isCommand(command)) {\n endWithError(new Error(`Command ${command} does not exist`), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\n\nawait fillMissingRequiredValues(values, COMMAND_REQUIRED_VALUES_MAP[command] ?? ['cluster', 'variationId']);\nconst { cluster, variationId, service } = values;\n\nif (!cluster) {\n endWithError(new Error('cluster required'), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\n\nif (command === 'telepresenceWizard') {\n await telepresenceWizard(values);\n process.exit(0);\n}\n\nif (command === 'switchCluster') {\n await connectToCluster(cluster);\n console.log(`switched to ${cluster} successfully`);\n process.exit(0);\n}\n\nif (!variationId) {\n endWithError(new Error('variationId required'), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\nlet prefix: string;\ntry {\n prefix = await connectAndGetPrefix({ clusterName: cluster, variationId });\n} catch (error) {\n endWithError(error as Error);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n}\n\nif (command === 'exposeService') {\n if (!service) {\n endWithError(new Error('service is required for exposeService'), help);\n throw new Error('Typescript is not clever enough to understand that endWithError will exit the process');\n }\n await asyncSpawn('kubectl', ['patch', 'svc', prefix, service, '-p', '{\"spec\": {\"type\": \"LoadBalancer\"}}']);\n console.log(`exposed ${service} successfully. the service is now creating an internal load balancer ip to use with vpn`);\n process.exit(0);\n}\n\nif (command === 'forwardDb') {\n const localPort = Number.parseInt(values['local-port'] ?? '5432', 10);\n if (Number.isNaN(localPort)) {\n endWithError(new Error('if defined, local-port must be a number'), help);\n }\n const DB_PASSWORD = `afpass_${variationId}`;\n const USER_NAME = 'postgres';\n const variationUnderScore = variationId.replaceAll('-', '_');\n const DB_NAME = service ? `${service.replaceAll('-', '_') || ''}_${variationUnderScore}` : 'postgres';\n\n const postgressPath = `postgres://${USER_NAME}:${DB_PASSWORD}@localhost:${localPort}/${DB_NAME}?&nickname=var_${variationId}`;\n console.log(`Forwarding db to local port ${localPort}.\\naccess the DB at ${postgressPath}\\nPress ctrl+c to stop.`);\n\n const dbEnvs = ` DB_USERNAME=${USER_NAME}\n DB_PASSWORD=${DB_PASSWORD}\n DB_NAME=${service ? DB_NAME : `<service_name>_${variationUnderScore}`}`;\n console.log('Generated database environment for local development:\\n', dbEnvs);\n\n setTimeout(1500).then(() => asyncSpawn('open', [postgressPath], { print: false })).catch(() => null);\n await asyncSpawn('kubectl', [prefix, 'port-forward', `statefulset/p${variationId}-postgresql`, `${localPort}:5432`], { print: false });\n process.exit(0);\n}\n\nif (command === 'forwardService') {\n const port = Number.parseInt(values.port ?? '8080', 10);\n const localPort = Number.parseInt(values['local-port'] ?? '', 10) || port;\n if (!service) {\n endWithError(new Error('service is required for forwardService'), help);\n }\n if (!port || Number.isNaN(port)) {\n endWithError(new Error('port is required and must be a numbers'), help);\n }\n if (localPort && Number.isNaN(localPort)) {\n endWithError(new Error('local-port must be a number'), help);\n }\n let { stdout: podName } = await asyncSpawn('kubectl', ['get', 'pods', prefix, '-l', `service=${service}`, '-o', 'jsonpath=\"{.items[0].metadata.name}\"'], { print: false });\n podName &&= podName.trim();\n if (!podName) {\n endWithError(new Error(`No pods found for service ${service}`));\n }\n if (podName.startsWith('\"') && podName.endsWith('\"')) {\n podName = podName.slice(1, -1);\n }\n console.log(`Found pod ${podName}, serving locally on port ${localPort} from remote port ${port}.\\nPress ctrl+c to stop.`);\n await asyncSpawn('kubectl', ['port-forward', prefix, podName, `${localPort}:${port}`], { print: false });\n process.exit(0);\n}\n\nif (command === 'getIps') {\n const { stdout } = await asyncSpawn('kubectl', [prefix, 'get', 'services'], { print: false });\n const ips = parseIps(stdout);\n ips.forEach(ip => console.log(ip));\n process.exit(0);\n}\n\nif (command === 'enableSimulator') {\n const SIMULATION_CLUSTER_FRONT = 'simulation-cluster-front';\n await asyncSpawn('kubectl', ['annotate', prefix, 'service', SIMULATION_CLUSTER_FRONT, 'cloud.google.com/load-balancer-type-']);\n await asyncSpawn('kubectl', ['patch', 'svc', prefix, SIMULATION_CLUSTER_FRONT, '-p', '{\"spec\": {\"type\": \"LoadBalancer\"}}']);\n await asyncSpawn('kubectl', ['create', prefix, 'rolebinding', 'admin', '--clusterrole=cluster-admin', `--serviceaccount=${variationId}:default`]);\n console.log(`Successfully exposed ${SIMULATION_CLUSTER_FRONT} and added role binding to dispatch simulations`);\n process.exit(0);\n}\n\nif (command === 'rabbitCreds') {\n const getArgs = (dataKey: string) => ['get', 'secret', 'rabbitmq-default-user', '-o', `jsonpath=\"{.data.${dataKey}}\"`];\n const [{ stdout: username }, { stdout: password }] = await Promise.all([\n asyncSpawn('kubectl', getArgs('username'), { print: false }),\n asyncSpawn('kubectl', getArgs('password'), { print: false }),\n ]);\n console.log(`username: ${Buffer.from(username, 'base64').toString('ascii')}`);\n console.log(`password: ${Buffer.from(password, 'base64').toString('ascii')}`);\n process.exit(0);\n}\n\nif (command === 'updateExp') {\n const dir = basename(cwd());\n const [branchName, archResult] = await Promise.all([getCurrentBranch(), asyncSpawn('uname', ['-m'], { print: false })]);\n const arch = archResult.stdout.trim();\n const dateSuffix = `${new Date().getHours().toString().padStart(2, '0')}-${new Date().getMinutes().toString().padStart(2, '0')}-${new Date().getSeconds().toString().padStart(2, '0')}`;\n const imageName = `gcr.io/autofleetprod/${dir}:${branchName}-${dateSuffix}`;\n console.log(`Building and pushing image ${imageName}`);\n const platformFlag = arch === 'x86_64' ? [] : ['--platform', 'linux/amd64'];\n await asyncSpawn('docker', ['build', '.', ...platformFlag, '-t', imageName, '--build-arg', `NPM_TOKEN=${process.env.NPM_TOKEN}`]);\n await asyncSpawn('docker', ['push', imageName]);\n const { stdout: podDescription } = await asyncSpawn('kubectl', ['describe', 'pod', prefix, '-l', `service=${dir}`], { print: false });\n if (podDescription.includes('Init Containers:')) {\n await asyncSpawn('kubectl', ['patch', `deployment/${dir}`, prefix, '--patch', `{\"spec\": {\"template\": {\"spec\": {\"initContainers\": [{\"name\": \"init\",\"image\": \"${imageName}\"}]}}}}`]);\n }\n await asyncSpawn('kubectl', ['set', 'image', `deployment/${dir}`, `worker=${imageName}`, prefix]);\n await asyncSpawn('kubectl', ['rollout', 'status', 'deployments', dir, prefix]);\n process.exit(0);\n}\n\nif (command === 'localDev') {\n const API_GATEWAY_MS = 'api-gateway-ms';\n const CONTROL_CENTER_MS = 'control-center-ms';\n\n const repoPath = await getGitPath();\n if (basename(repoPath) !== 'control-center') {\n endWithError(new Error('The `localDev` command must be run from the control-center repository'));\n }\n const { stdout: apiGatewayMsIP } = await asyncSpawn('kubectl', ['get', 'ingress', `${API_GATEWAY_MS}-ingress`, prefix, '-o', 'jsonpath=\"{.status.loadBalancer.ingress[0].ip}\"'], { print: false });\n if (!apiGatewayMsIP) {\n endWithError(new Error(`The IP of the Load balancer for ${API_GATEWAY_MS} was not found`));\n }\n await setEnvValue(repoPath, 'API_GATEWAY_MS_SERVICE_HOST', apiGatewayMsIP.replace(/\"/g, ''));\n console.log(`Updated .env file to use ${API_GATEWAY_MS} IP (${apiGatewayMsIP}). Will now start port-forwarding ${CONTROL_CENTER_MS} to port 8085.\\nPress ctrl+c to stop.`);\n await asyncSpawn('kubectl', ['port-forward', prefix, `svc/${CONTROL_CENTER_MS}`, '8085:80'], { print: false });\n process.exit(0);\n}\n","import asyncSpawn from './asyncSpawn.js';\nimport { getVariationId, getLocalPort, safeSelect } from './inquirer.js';\nimport { connectToCluster, endWithError } from './index.js';\nimport type { Values } from '../index.js';\n\nasync function ensureTelepresenceInstalled() {\n try {\n await asyncSpawn('telepresence', ['version'], { print: false });\n } catch {\n endWithError('Telepresence is not installed. Please install it from:\\nhttps://www.telepresence.io/docs/latest/quick-start/');\n }\n}\n\nfunction leaveOrConnect() {\n return safeSelect({\n message: 'Do you want to leave the connection or create a new one?',\n choices: [\n { name: 'Leave the current connection', value: 'leave' },\n { name: 'Create a new connection', value: 'connect' },\n ] as const,\n default: 'connect',\n });\n}\n\nexport default async function telepresenceWizard(values: Values): Promise<void> {\n await ensureTelepresenceInstalled();\n\n const { cluster = '', service = '' } = values; // Values should be defined by now, thanks to inquirer. Default to hint to TS we always have values.\n await connectToCluster(cluster);\n\n const action = await leaveOrConnect();\n if (!['leave', 'connect'].includes(action!)) {\n endWithError('Invalid action, how did you get here? 🤔');\n }\n if (action === 'leave') {\n await asyncSpawn('telepresence', ['leave', service]);\n console.log('Disconnected! 👋');\n return;\n }\n const namespace = values.variationId || await getVariationId();\n const localPort = (values['local-port'] && Number.parseInt(values['local-port'], 10)) || Number.parseInt((await getLocalPort()) || '', 10);\n await asyncSpawn('telepresence', ['connect', `--namespace=${namespace}`]);\n await asyncSpawn('telepresence', ['intercept', service, '--port', localPort.toString(), '--env-file=./.env']);\n console.log('Everything is set up! 🚀');\n console.log(`You can now access the service at localhost:${localPort}`);\n console.log('You can only have one connection at a time. If you want to connect to a different service, you need to leave the current connection first.');\n}\n","import { EOL } from 'node:os';\nimport { resolve } from 'node:path';\nimport { readFile, writeFile } from 'node:fs/promises';\n\nexport async function setEnvValue(repoRoot: string, key: string, value: string): Promise<void> {\n const filePath = resolve(repoRoot, '.env');\n const envFileContent = await readFile(filePath, 'utf8');\n const envVars = envFileContent.split(EOL);\n\n // (?<!#\\\\s*) Negative lookbehind to avoid matching comments (lines that starts with #).\n // There is a double slash in the RegExp constructor to escape it.\n // (?==) Positive lookahead to check if there is an equal sign right after the key.\n // This is to prevent matching keys prefixed with the key of the env var to update.\n const regexString = `(?<!#\\\\s*)${key}(?==)`;\n const matchingLine = envVars.find((line: string) => line.match(regexString));\n\n if (matchingLine?.split('=').at(-1) === value) {\n console.log('env file already up to date!');\n return undefined;\n }\n\n const target = matchingLine ? envVars.indexOf(matchingLine) : -1;\n\n if (target !== -1) {\n envVars.splice(target, 1, `${key}=${value}`);\n } else {\n envVars.push(`${key}=${value}`);\n }\n\n return writeFile(filePath, envVars.join(EOL));\n}\n"],"mappings":";6JACA,OAAS,OAAAA,MAAW,eACpB,OAAS,YAAAC,MAAgB,YACzB,OAAS,cAAAC,MAAkB,uBCE3B,eAAeC,GAA8B,CAC3C,GAAI,CACF,MAAMC,EAAW,eAAgB,CAAC,SAAS,EAAG,CAAE,MAAO,EAAM,CAAC,CAChE,MAAQ,CACNC,EAAa;AAAA,qDAA8G,CAC7H,CACF,CAEA,SAASC,GAAiB,CACxB,OAAOC,EAAW,CAChB,QAAS,2DACT,QAAS,CACP,CAAE,KAAM,+BAAgC,MAAO,OAAQ,EACvD,CAAE,KAAM,0BAA2B,MAAO,SAAU,CACtD,EACA,QAAS,SACX,CAAC,CACH,CAEA,eAAOC,EAA0CC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setTimeout","ensureTelepresenceInstalled","asyncSpawn_default","endWithError","leaveOrConnect","safeSelect","telepresenceWizard","values","cluster","service","connectToCluster","action","namespace","getVariationId","localPort","getLocalPort","EOL","resolve","readFile","writeFile","setEnvValue","repoRoot","key","value","filePath","envVars","regexString","matchingLine","line","target","clusterOptions","SUPPORTED_CLUSTERS","variationAndCluster","COMMANDS","isCommand","c","positionals","values","help","parseArgs","COMMAND_REQUIRED_VALUES_MAP","endWithError","command","fillMissingRequiredValues","cluster","variationId","service","telepresenceWizard","connectToCluster","prefix","connectAndGetPrefix","error","asyncSpawn_default","localPort","DB_PASSWORD","USER_NAME","variationUnderScore","DB_NAME","postgressPath","dbEnvs","setTimeout","port","podName","stdout","parseIps","ip","SIMULATION_CLUSTER_FRONT","getArgs","dataKey","username","password","dir","basename","cwd","branchName","archResult","getCurrentBranch","arch","dateSuffix","imageName","podDescription","API_GATEWAY_MS","CONTROL_CENTER_MS","repoPath","getGitPath","apiGatewayMsIP","setEnvValue"]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import globals from 'globals';
|
|
4
|
+
import eslint from '@eslint/js';
|
|
5
|
+
import tseslint from 'typescript-eslint';
|
|
6
|
+
import importPlugin from 'eslint-plugin-import';
|
|
7
|
+
import stylistic from '@stylistic/eslint-plugin';
|
|
8
|
+
|
|
9
|
+
export default tseslint.config(
|
|
10
|
+
{
|
|
11
|
+
ignores: ['dist/*', '**/node_modules/'],
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
languageOptions: {
|
|
15
|
+
globals: globals.node,
|
|
16
|
+
parserOptions: {
|
|
17
|
+
project: true,
|
|
18
|
+
ecmaVersion: 2022,
|
|
19
|
+
tsconfigRootDir: import.meta.dirname,
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
eslint.configs.recommended,
|
|
24
|
+
importPlugin.flatConfigs.typescript,
|
|
25
|
+
...tseslint.configs.recommendedTypeChecked,
|
|
26
|
+
...tseslint.configs.stylisticTypeChecked,
|
|
27
|
+
stylistic.configs['recommended-flat'],
|
|
28
|
+
{
|
|
29
|
+
rules: {
|
|
30
|
+
'@stylistic/semi': ['error', 'always'],
|
|
31
|
+
'@stylistic/quote-props': ['error', 'as-needed'],
|
|
32
|
+
'@stylistic/multiline-ternary': 'off',
|
|
33
|
+
'@stylistic/brace-style': ['error', '1tbs', { allowSingleLine: true }],
|
|
34
|
+
'@stylistic/member-delimiter-style': ['error', { multiline: { delimiter: 'semi', requireLast: true }, multilineDetection: 'brackets', singleline: { delimiter: 'semi' } }],
|
|
35
|
+
'@typescript-eslint/prefer-nullish-coalescing': ['error', { ignorePrimitives: { string: true, number: true } }],
|
|
36
|
+
'@typescript-eslint/no-unused-vars': ['error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_', destructuredArrayIgnorePattern: '^_' }],
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
// disable type-aware linting on JS files
|
|
41
|
+
files: ['**/*.js', '**/*.mjs', '**/*.cjs'],
|
|
42
|
+
...tseslint.configs.disableTypeChecked,
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
files: ['**/tsup.config.ts'],
|
|
46
|
+
|
|
47
|
+
rules: {
|
|
48
|
+
'import/no-extraneous-dependencies': 'off',
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
);
|
package/package.json
CHANGED
|
@@ -1,28 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autofleet/cli",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.5",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"start": "tsx bin/index.ts",
|
|
8
8
|
"dev": "tsup --watch",
|
|
9
9
|
"build": "tsup",
|
|
10
|
-
"linter": "
|
|
11
|
-
"test": "
|
|
12
|
-
"coverage": "
|
|
10
|
+
"linter": "eslint .",
|
|
11
|
+
"test": "vitest",
|
|
12
|
+
"coverage": "vitest --coverage"
|
|
13
13
|
},
|
|
14
14
|
"devDependencies": {
|
|
15
|
-
"@
|
|
16
|
-
"@
|
|
17
|
-
"@
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"eslint
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"typescript": "^
|
|
15
|
+
"@eslint/js": "^9.13.0",
|
|
16
|
+
"@stylistic/eslint-plugin": "^2.9.0",
|
|
17
|
+
"@types/eslint__js": "^8.42.3",
|
|
18
|
+
"@types/node": "^22.7.8",
|
|
19
|
+
"@vitest/coverage-v8": "^2.1.3",
|
|
20
|
+
"eslint": "^9.13.0",
|
|
21
|
+
"eslint-plugin-import": "^2.31.0",
|
|
22
|
+
"tsup": "^8.3.0",
|
|
23
|
+
"tsx": "^4.19.1",
|
|
24
|
+
"typescript": "^5.6.3",
|
|
25
|
+
"typescript-eslint": "^8.11.0",
|
|
26
|
+
"vitest": "^2.1.3"
|
|
26
27
|
},
|
|
27
28
|
"bin": {
|
|
28
29
|
"autofleet": "./dist/index.js",
|
|
@@ -30,7 +31,7 @@
|
|
|
30
31
|
"git-autofleet": "./dist/git-autofleet.js"
|
|
31
32
|
},
|
|
32
33
|
"engines": {
|
|
33
|
-
"node": "
|
|
34
|
+
"node": ">= 18.3.0"
|
|
34
35
|
},
|
|
35
36
|
"type": "module",
|
|
36
37
|
"author": "Autofleet",
|
|
@@ -38,5 +39,8 @@
|
|
|
38
39
|
"dependencies": {
|
|
39
40
|
"@inquirer/prompts": "^5.0.2",
|
|
40
41
|
"p-retry": "^6.2.0"
|
|
42
|
+
},
|
|
43
|
+
"optionalDependencies": {
|
|
44
|
+
"@rollup/rollup-linux-x64-gnu": "*"
|
|
41
45
|
}
|
|
42
46
|
}
|
package/tsconfig.json
CHANGED
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
"esModuleInterop": true,
|
|
9
9
|
"experimentalDecorators": true,
|
|
10
10
|
"emitDecoratorMetadata": false,
|
|
11
|
-
"moduleResolution":"
|
|
11
|
+
"moduleResolution": "NodeNext",
|
|
12
|
+
"skipLibCheck": true,
|
|
12
13
|
"resolveJsonModule": true,
|
|
13
14
|
},
|
|
14
15
|
"exclude": ["node_modules", "**/*.test.ts"]
|
package/tsup.config.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { defineConfig } from 'tsup';
|
|
2
2
|
|
|
3
|
-
export default defineConfig(
|
|
3
|
+
export default defineConfig(options => ({
|
|
4
4
|
entry: ['bin/*.ts'],
|
|
5
|
-
target: 'node18',
|
|
5
|
+
target: 'node18.3',
|
|
6
6
|
format: 'esm',
|
|
7
7
|
clean: !options.watch,
|
|
8
8
|
minify: !options.watch,
|
|
9
|
+
sourcemap: !options.watch,
|
|
9
10
|
}));
|
package/vitest.config.ts
ADDED
package/dist/chunk-CXYUFZMV.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as d,b as m,d as s,e as y,j as u}from"./chunk-DEQF3ODJ.js";import{confirm as h,input as l,select as P}from"@inquirer/prompts";Symbol.dispose??=Symbol.for("nodejs.dispose");Symbol.asyncDispose??=Symbol.for("nodejs.asyncDispose");var f,g=()=>f?.();function b(){return process.once("beforeExit",g),{[Symbol.dispose](){process.off("beforeExit",g),f=void 0}}}async function n(e,...r){try{var t=[];try{let a=d(t,b());let p=e(...r);f=p.cancel;return await p}catch(o){var c=o,i=!0}finally{m(t,c,i)}}catch(a){throw a instanceof Error&&["CancelPromptError","ExitPromptError"].includes(a.constructor.name)?u("Cancelled! \u{1F44B}"):u(a)}}function w(...e){return n(P,...e)}var v=e=>e.charAt(0).toUpperCase()+e.slice(1).split(/(?=[A-Z])/).join(" ");function x(){return w({message:"Which environment do you want to use?",choices:y.map(e=>({name:v(e),value:e})),default:"expManager"})}function S(){return n(l,{message:"Enter the service name:"})}function V(){return n(l,{message:"Enter your simulator id:"})}async function E(e="8080",r=!1){return n(l,{message:`Enter the ${r?"local ":""}port:`,default:e,validate(t){return/^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/.test(t)?!0:"Please enter a valid port number"}})}async function C(e="5432"){return E(e,!0)}var T={cluster:x,variationId:V,service:S,port:(e="8080")=>E(e),"local-port":C};async function L(e,r){for(let t of r){let o=typeof t=="object"?t.option:t,c=typeof t=="object"?t.defaultVal:void 0;if(typeof o!="string")throw new Error(`Invalid option ${String(o)}`);let i=T[o];if(!i)throw new Error(`No value getter for ${String(o)}`);e[o]??=await i(c)}return e}async function R(e,r=!0){return n(h,{message:e,default:r})}var q=async()=>{let{stdout:e}=await s("git",["branch","--show-current"],{print:!1});return e.trim()},M=async()=>{let{stdout:e}=await s("git",["rev-parse","--show-toplevel"],{print:!1});return e.trim()},D=async e=>{let{stdout:r}=await s("git",["diff","origin/master..",e],{print:!1});return r};export{w as a,V as b,C as c,L as d,R as e,q as f,M as g,D as h};
|
package/dist/chunk-DEQF3ODJ.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
var x=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t);var L=(t,e,s)=>{if(e!=null){if(typeof e!="object"&&typeof e!="function")throw TypeError("Object expected");var n;if(s&&(n=e[x("asyncDispose")]),n===void 0&&(n=e[x("dispose")]),typeof n!="function")throw TypeError("Object not disposable");t.push([s,n,e])}else s&&t.push([s]);return e},I=(t,e,s)=>{var n=typeof SuppressedError=="function"?SuppressedError:function(o,p,l,r){return r=Error(l),r.name="SuppressedError",r.error=o,r.suppressed=p,r},i=o=>e=s?new n(o,e,"An error was suppressed during disposal"):(s=!0,o),a=o=>{for(;o=t.pop();)try{var p=o[1]&&o[1].call(o[2]);if(o[0])return Promise.resolve(p).then(a,l=>(i(l),a()))}catch(l){i(l)}if(s)throw e};return a()};import{parseArgs as j}from"node:util";var b="2.5.3";var A={help:{type:"boolean",short:"h",default:!1,description:"Show help (prints this message)"},version:{type:"boolean",short:"v",default:!1,description:"Show version number"}};function S(t){t.options={...A,...t.options};let e=j(t),{values:s}=e;s.version&&(console.log(b),process.exit(0));let n=t.commands?`
|
|
2
|
-
|
|
3
|
-
Commands:
|
|
4
|
-
${Object.entries(t.commands).map(([a,o])=>`${a.padEnd(30," ")} ${o}`).join(`
|
|
5
|
-
`)}
|
|
6
|
-
`:"",i=`
|
|
7
|
-
${t.binName} ${n?"[command] ":""}<options>${n}
|
|
8
|
-
Options:
|
|
9
|
-
${Object.entries(t.options).map(([a,{description:o,type:p,short:l}])=>`${(l?`--${a}, -${l}`:`--${a}`).padEnd(30," ")} ${o.padEnd(70," ")} [${p}]`).join(`
|
|
10
|
-
`)}
|
|
11
|
-
`;return s.help&&(console.log(i),process.exit(0)),{...e,help:i}}import{spawn as O}from"node:child_process";var _=()=>{if(Promise.withResolvers)return Promise.withResolvers();let t,e;return{promise:new Promise((n,i)=>{t=i,e=n}),reject:t,resolve:e}},w=async(t,e,{print:s=!0,env:n={}}={})=>{typeof e=="boolean"&&(s=e,e=void 0);let i=new Error,a=i.stack?i.stack.replace(/^.*/," ..."):null,{promise:o,reject:p,resolve:l}=_(),r=O(t,e,{env:Object.assign(n,process.env)});s&&(r.stdout.pipe(process.stdout),r.stderr.pipe(process.stderr));let d="",u="";r.stdout?.on("data",c=>{d+=c}),r.stderr?.on("data",c=>{u+=c});let m=s?"exit":"close";function v(c){r.removeListener(m,P),Object.assign(c,{pid:r.pid,stdout:d,stderr:u,status:null,signal:null}),p(c)}function P(c,f){r.removeListener("error",v);let y={pid:r.pid,stdout:d,stderr:u,status:c,signal:f};if(c!==0){let T=typeof e!="boolean"&&` ${e?.join(" ")}`||"",g=f?new Error(`${t}${T} exited with signal: ${f}`):new Error(`${t}${T} exited with non-zero code: ${c}`);g.stack&&a&&(g.stack+=`
|
|
12
|
-
${a}`),Object.assign(g,y),p(g)}else l(y)}return r.once(m,P),r.once("error",v),o};import E from"node:fs";var C="SERVICE_HOST",h={dev1:["dev-cluster-2","europe-west1","dev1-experiment-manager"],e2eManager:["e2e-cluster-2","europe-west1","e2e-project-1"],expManager:["af-experiment-manager","europe-west1"],staging:["autofleet-staging","europe-west1-b"]},z=Object.keys(h),H=({newFilePath:t,filePath:e,linesToReplace:s})=>{let n=E.readFileSync(e,"utf8");for(let{find:i,replace:a}of s)n=n.replace(i,a);E.writeFileSync(t,n)},R=async t=>{let e=h[t];if(!e)throw new Error(`Cluster name ${t} does not exist!`);let[s,n,i]=e;await w("gcloud",["container","clusters","get-credentials",s,"--region",n,"--project",i||s],{print:!1})},J=async({clusterName:t,variationId:e})=>(await R(t),`--namespace=${e}`),V=t=>{let e=t.split(`
|
|
13
|
-
`).filter(Boolean);e.shift();let s=e.map(n=>{let[i,a,o,p,l,r]=n.split(/(\s+)/).map(m=>m.trim()).filter(Boolean);return`${i.replace(/-/g,"_").toUpperCase()}_${C}=${p}`});return s=s.filter(n=>!n.includes("none")&&!n.includes("undefined")),s},X=(t,e)=>(t instanceof Error||(t=new Error(t)),console.error(t),e&&console.log(e),process.exit(1));export{L as a,I as b,S as c,w as d,z as e,H as f,R as g,J as h,V as i,X as j};
|