eitri-cli 1.0.5 → 1.1.0-beta

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.
@@ -0,0 +1,71 @@
1
+ const { default: axios } = require("../../../node_modules/axios/index");
2
+ const BlindGuardian = require("../../service/BlindGuardian");
3
+ const Http = require("../../service/Http");
4
+ const config = require("config");
5
+ const getWorkspace = require("../../util/getWorkspace");
6
+
7
+ module.exports = class VegvisirService {
8
+ constructor() {
9
+ const blindGuardian = new BlindGuardian();
10
+ this.http = new Http(blindGuardian);
11
+ this.config = config.get("vegvisir");
12
+ }
13
+
14
+ async listMyWorkspaces() {
15
+ try {
16
+ const url = `${this.config.url}${this.config.basePath}${this.config.my}`;
17
+ const workspaces = await this.http.get(url);
18
+ return workspaces;
19
+ } catch (error) {
20
+ if (axios.isAxiosError(error)) {
21
+ if (error.response.status === 404) {
22
+ console.error(
23
+ "Você não possui workspaces cadastrados, utilize o comando 'eitri workspace create' para cadastrar"
24
+ );
25
+ }
26
+ } else {
27
+ console.error("Houve um erro inesperado ao listar workspaces");
28
+ }
29
+ }
30
+ }
31
+
32
+ async create(createData) {
33
+ const url = `${this.config.url}${this.config.basePath}${this.config.workspace}`;
34
+ await this.http.post(url, createData);
35
+ }
36
+
37
+ async check(slug) {
38
+ try {
39
+ const workspace = await getWorkspace()
40
+ if(!workspace) {
41
+ console.log("É necessário ter um workspace definido para realizar essa ação, certifique-se de estar em um workspace.")
42
+ console.log("Execute o comando 'eitri workspace current' para checar você está em um workspace.")
43
+ return process.exit(0)
44
+ }
45
+
46
+ const data = {
47
+ slug,
48
+ id: workspace.id
49
+ }
50
+
51
+ const url =`${this.config.url}${this.config.basePath}${this.config.check}`;
52
+
53
+ await this.http.put(url, data)
54
+ } catch (error) {
55
+ console.error(error.message)
56
+ if (axios.isAxiosError(error)) {
57
+ if (error?.response?.status === 404) {
58
+ console.error(
59
+ "O Workspace atual não foi encontrado."
60
+ );
61
+ return process.exit(0)
62
+ }
63
+ console.error("Houve um erro inesperado ao listar workspaces");
64
+ return process.exit(0)
65
+ }
66
+ console.error(error.message)
67
+ return process.exit(0)
68
+ }
69
+
70
+ }
71
+ };
@@ -0,0 +1,43 @@
1
+ const inquirer = require("inquirer");
2
+ const VegvisirService = require("../VegvisirService");
3
+
4
+ const NAME_REGEX = /^([a-zA-ZÀ-ú0-9\s]|_|\+|&|!)+$/;
5
+
6
+ const vegvisirService = new VegvisirService();
7
+ module.exports = async function create(cmdObj) {
8
+ console.log(
9
+ "\x1b[34mVamos criar o seu workspace. Para isso basta responder algumas perguntas:\x1b[0m"
10
+ );
11
+ const questions = createQuestions();
12
+
13
+ const res = await inquirer.prompt(questions);
14
+
15
+ const createData = {
16
+ name: res.name,
17
+ };
18
+ await vegvisirService.create(createData);
19
+ console.log(
20
+ "\n\x1b[34mWorkspace criado com sucesso! Para utilizá-lo basta executar o comando 'eitri workspace use' e selecionar seu novo workspace!\x1b[0m"
21
+ );
22
+ };
23
+
24
+ const nameValidate = (inpt) => {
25
+ if (!NAME_REGEX.test(inpt)) {
26
+ return "Não use caracteres especiais";
27
+ }
28
+ return true;
29
+ };
30
+
31
+ function createQuestions() {
32
+ return [
33
+ {
34
+ type: "input",
35
+ name: "name",
36
+ message: "Nome do Workspace (Ex: MY_WORKSPACE)",
37
+ validate: nameValidate,
38
+ default: () => {
39
+ return "DEFAULT";
40
+ },
41
+ },
42
+ ];
43
+ }
@@ -0,0 +1,20 @@
1
+ const getWorkspace = require("../../../util/getWorkspace");
2
+
3
+ module.exports = async function current(cmdObj) {
4
+ try {
5
+ const workspace = await getWorkspace()
6
+ console.log("====================================================")
7
+ console.log('\t Workspace Atual: ', workspace.name)
8
+ console.log("====================================================")
9
+ } catch (error) {
10
+ if (error.code === "ENOENT") {
11
+ throw new Error(
12
+ "Você não tem nenhum workspace definido para desenvolvimento, execute o comando 'eitri workspace use' para definir um workspace."
13
+ );
14
+ }
15
+ console.log(error)
16
+ throw new Error(
17
+ "Houve um erro inesperado ao tentar ler o workspace atual."
18
+ );
19
+ }
20
+ };
@@ -0,0 +1,13 @@
1
+ const VegvisirService = require("../VegvisirService");
2
+
3
+ const vegvisirService = new VegvisirService();
4
+ module.exports = async function list(cmdObj) {
5
+ const workspaces = await vegvisirService.listMyWorkspaces();
6
+ if (!workspaces) return;
7
+ console.log("\n=======================================");
8
+ console.log("\tWorkspaces Disponíveis");
9
+ console.log("=======================================\n");
10
+ for (const workspace of workspaces) {
11
+ console.log("Workspace: ", workspace.name);
12
+ }
13
+ };
@@ -0,0 +1,71 @@
1
+ const os = require("os");
2
+ const inquirer = require("inquirer");
3
+ const VegvisirService = require("../VegvisirService");
4
+ const path = require("path");
5
+ const { mkdir, writeFile } = require("fs/promises");
6
+ const { existsSync } = require("fs");
7
+ const vegvisirService = new VegvisirService();
8
+
9
+ module.exports = async function use(cmdArgs) {
10
+ const workspaces = await vegvisirService.listMyWorkspaces();
11
+ if (!workspaces) return;
12
+
13
+ const { workspaceName } = await inquirer.prompt([
14
+ {
15
+ name: "workspaceName",
16
+ type: "rawlist",
17
+ message: "Selecione qual workspace você deseja utilizar:",
18
+ choices: workspaces,
19
+ },
20
+ ]);
21
+
22
+ const selectedWorkspace = workspaces.find(
23
+ (work) => work.name === workspaceName
24
+ );
25
+
26
+ if (cmdArgs.local) {
27
+ await writeLocalWorkspaceConfig(selectedWorkspace);
28
+ return;
29
+ }
30
+ await writeGlobalWorkspaceConfig(selectedWorkspace);
31
+ };
32
+
33
+ async function writeGlobalWorkspaceConfig(selectedWorkspace) {
34
+ const eitriFolderPath = path.resolve(os.homedir(), ".eitri");
35
+ const workspaceFolderPath = path.resolve(eitriFolderPath, "workspaces");
36
+ const workspaceFilePath = path.resolve(workspaceFolderPath, "workspace");
37
+
38
+ await mkdir(workspaceFolderPath, { recursive: true });
39
+
40
+ const workspaceConfig = JSON.stringify({
41
+ name: selectedWorkspace.name,
42
+ id: selectedWorkspace.id,
43
+ });
44
+
45
+ await writeFile(workspaceFilePath, workspaceConfig, { encoding: "utf8" });
46
+
47
+ console.log("\nWorkspace configurado com sucesso!");
48
+ }
49
+
50
+ async function writeLocalWorkspaceConfig(selectedWorkspace) {
51
+ const miniAppConfPath = path.resolve(process.cwd(), "miniapp.conf.js");
52
+ if (!existsSync(miniAppConfPath)) {
53
+ console.error(
54
+ "Você só pode selecionar um workspace como local dentro de um eitri-app"
55
+ );
56
+ return;
57
+ }
58
+ const workspaceFolderPath = path.resolve(process.cwd(), ".workspaces");
59
+ const workspaceFilePath = path.resolve(workspaceFolderPath, "workspace");
60
+
61
+ await mkdir(workspaceFolderPath, { recursive: true });
62
+
63
+ const workspaceConfig = JSON.stringify({
64
+ name: selectedWorkspace.name,
65
+ id: selectedWorkspace.id,
66
+ });
67
+
68
+ await writeFile(workspaceFilePath, workspaceConfig, { encoding: "utf8" });
69
+
70
+ console.log("\nWorkspace configurado com sucesso!");
71
+ }
@@ -0,0 +1,32 @@
1
+ const config = require('config')
2
+ const Http = require("./Http")
3
+
4
+ class EitriAppManager {
5
+ constructor(blindGuardian) {
6
+ this.http = new Http(blindGuardian)
7
+ this.config = config.get('eitriManager')
8
+ this.managerBaseURL = this.config.url
9
+ }
10
+
11
+ async findAllApplications() {
12
+ const url = `${this.managerBaseURL}/p/users/self/targets`
13
+ return await this.http.get(url)
14
+ }
15
+
16
+ async findApplicationById(applicationId) {
17
+ const url = `${this.managerBaseURL}/applications/${applicationId}`
18
+ return await this.http.get(url)
19
+ }
20
+
21
+ async create(eitriApp) {
22
+ const url = `${this.managerBaseURL}/eitri-apps`
23
+ try {
24
+ const res = await this.http.post(url, { ...eitriApp, publicKey: '', secretKey: '', status: 'ACTIVE' })
25
+ return res.data
26
+ } catch (e) {
27
+ Http.printLeanLogAxiosError(e)
28
+ }
29
+ }
30
+ }
31
+
32
+ module.exports = EitriAppManager
@@ -6,6 +6,7 @@ const { v4: uuidv4 } = require('uuid')
6
6
  const os = require('os')
7
7
  const path = require('path')
8
8
  const getCliVersion = require('../util/getCliVersion')
9
+ const getWorkspace = require('../util/getWorkspace')
9
10
 
10
11
  const filePath = path.join(os.homedir(), './.eitri.cookie.json')
11
12
  const jar = new CookieJar(new FileCookieStore(filePath))
@@ -20,13 +21,13 @@ axios.interceptors.response.use(function (response) {
20
21
  const YELLOW_COLOR = '\x1b[33m'
21
22
  const BLUE_COLOR = '\x1b[94m'
22
23
  const RESET_COLORS = '\x1b[0m'
23
- const {warning} = response.data
24
- const {greeting} = response.data
25
- if(canShowLog) {
26
- if(warning) {
24
+ const { warning } = response.data
25
+ const { greeting } = response.data
26
+ if (canShowLog) {
27
+ if (warning) {
27
28
  console.warn(`${YELLOW_COLOR}\nAtenção: ${warning.message}${YELLOW_COLOR}${RESET_COLORS}\n`)
28
29
  }
29
- if(greeting) {
30
+ if (greeting) {
30
31
  console.log(`${BLUE_COLOR}\n${greeting.message}${BLUE_COLOR}${RESET_COLORS}\n`)
31
32
  }
32
33
  canShowLog = (warning || greeting) ? false : true
@@ -61,7 +62,7 @@ class Http {
61
62
  this.token = await this.tokenFactory.getToken()
62
63
  }
63
64
  const mergedHeaders = {
64
- ...this._getHeader(), ...headers
65
+ ...(await this._getHeader(url)), ...headers
65
66
  }
66
67
  return await axios.post(url, data, { headers: mergedHeaders })
67
68
  }
@@ -72,19 +73,24 @@ class Http {
72
73
  }
73
74
 
74
75
  const headers = {
75
- ...this._getHeader(),
76
+ ...(await this._getHeader(url)),
76
77
  'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}`,
77
78
  }
78
79
  return await this._postForm(url, formData, headers)
79
80
  }
80
81
 
81
- _getHeader() {
82
+ async _getHeader(url) {
82
83
  const tid = uuidv4()
83
- return {
84
+ const headers = {
84
85
  Authorization: `Bearer ${this.token.accessToken}`,
85
86
  'X-Transaction-Id': tid,
86
87
  'App-Tools-Version': getCliVersion()
87
88
  }
89
+ if (url.includes("foundry") || url.includes("runes-foundry")) {
90
+ headers["Workspace-Id"] = (await getWorkspace()).id;
91
+ }
92
+
93
+ return headers
88
94
  }
89
95
 
90
96
  __postForm(url, formData, headers, resolve, reject) {
@@ -103,7 +109,7 @@ class Http {
103
109
  if (!this.token) {
104
110
  this.token = await this.tokenFactory.getToken()
105
111
  }
106
- const headers = this._getHeader()
112
+ const headers = await this._getHeader(url)
107
113
  return await this._delete(url, options, headers)
108
114
  }
109
115
 
@@ -124,7 +130,7 @@ class Http {
124
130
  if (!this.token) {
125
131
  this.token = await this.tokenFactory.getToken()
126
132
  }
127
- const headers = this._getHeader()
133
+ const headers = await this._getHeader(url)
128
134
  return await this._get({ url, options, headers })
129
135
  }
130
136
 
@@ -135,7 +141,7 @@ class Http {
135
141
  }
136
142
 
137
143
  __get(args, resolve, reject) {
138
- const mergedHeaders = { ...args.headers, ...args.options.headers}
144
+ const mergedHeaders = { ...args.headers, ...args.options.headers }
139
145
  args.options.headers = mergedHeaders
140
146
  axios
141
147
  .get(args.url, args.options)
@@ -150,7 +156,7 @@ class Http {
150
156
  .getToken()
151
157
  .then((token) => {
152
158
  this.token = token
153
- args.headers = this._getHeader()
159
+ args.headers = this._getHeader(args.url)
154
160
  this.__get(args, resolve, reject)
155
161
  })
156
162
  .catch(reject)
@@ -171,7 +177,7 @@ class Http {
171
177
  if (!this.token) {
172
178
  this.token = await this.tokenFactory.getToken()
173
179
  }
174
- const mergedHeaders = { ...this._getHeader(), ...headers }
180
+ const mergedHeaders = { ...(await this._getHeader(url)), ...headers }
175
181
  return await this._put(url, data, mergedHeaders)
176
182
  }
177
183
 
@@ -229,6 +235,31 @@ class Http {
229
235
  headersCopy['Authorization'] = `Bearer ${token}`
230
236
  return headersCopy
231
237
  }
238
+
239
+ static printLeanLogAxiosError(e) {
240
+ const axios = require('axios')
241
+ if (axios.isAxiosError(e)) {
242
+ console.log(`AxiosError: ${JSON.stringify({
243
+ status: e.status,
244
+ config: {
245
+ headers: e.config?.headers,
246
+ method: e.config?.method,
247
+ url: e.config?.url,
248
+ data: Http.parseJson(e.config?.data),
249
+ },
250
+ responseData: e.response?.data,
251
+ }, null, 4)}`)
252
+ } else {
253
+ console.log(e)
254
+ }
255
+ }
256
+ static parseJson(data) {
257
+ try {
258
+ return JSON.parse(data ?? '{}')
259
+ } catch (e) {
260
+ return {}
261
+ }
262
+ }
232
263
  }
233
264
 
234
265
  module.exports = Http
@@ -35,46 +35,22 @@ class Server {
35
35
  static startServer(args) {
36
36
  Server.stop(args)
37
37
  const { qrCodePath, qrPrinter, verbose } = args
38
- const requestListener = function (req, res) {
39
- if (req.url === '/') {
40
- res.setHeader('Content-Type', 'text/html; charset=utf-8')
41
- res.writeHead(200)
42
38
 
43
- let readStream = fs.createReadStream(
44
- path.resolve(__dirname, '../view/index.html')
45
- )
46
- readStream.pipe(res)
47
- } else {
48
- res.setHeader('Content-Type', 'image/png')
49
- res.writeHead(200)
50
-
51
- let readStream = fs.createReadStream(qrCodePath)
52
- readStream.pipe(res)
53
- }
39
+ if (!qrPrinter && !process.env.AAT_QRCODE_PRINTER) {
40
+ open(qrCodePath)
41
+ } else if (qrPrinter && qrPrinter !== TERMINAL_PRINTER_NAME) {
42
+ open(qrCodePath, { app: qrPrinter })
43
+ } else if (
44
+ process.env.AAT_QRCODE_PRINTER &&
45
+ process.env.AAT_QRCODE_PRINTER !== TERMINAL_PRINTER_NAME
46
+ ) {
47
+ open(qrCodePath, {
48
+ app: process.env.AAT_QRCODE_PRINTER,
49
+ })
50
+ }
51
+ if (verbose) {
52
+ console.log(`Server is running on http://${host}:${port}`)
54
53
  }
55
-
56
- serverInstance = Express().disable('x-powered-by')
57
- serverInstance.use(expressRateLimiter)
58
- serverInstance.use(requestListener)
59
-
60
- serverInstance.listen(port, host, () => {
61
- // Prioridade no printer informado pelo argumento do programa, depois o que foi informado na variavel de ambiente
62
- if (!qrPrinter && !process.env.AAT_QRCODE_PRINTER) {
63
- open(`http://${host}:${port}`)
64
- } else if (qrPrinter && qrPrinter !== TERMINAL_PRINTER_NAME) {
65
- open(`http://${host}:${port}`, { app: qrPrinter })
66
- } else if (
67
- process.env.AAT_QRCODE_PRINTER &&
68
- process.env.AAT_QRCODE_PRINTER !== TERMINAL_PRINTER_NAME
69
- ) {
70
- open(`http://${host}:${port}`, {
71
- app: process.env.AAT_QRCODE_PRINTER,
72
- })
73
- }
74
- if (verbose) {
75
- console.log(`Server is running on http://${host}:${port}`)
76
- }
77
- })
78
54
  }
79
55
 
80
56
  static startServerMinhaContaEmulator(args) {