eitri-cli 1.0.2

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.
Files changed (122) hide show
  1. package/README.md +54 -0
  2. package/bitbucket-pipelines.toBeChanged.yml +64 -0
  3. package/boilerplate/mini-app-cafe-madeira.zip +0 -0
  4. package/check-version.js +12 -0
  5. package/config/default-eitri.js +1 -0
  6. package/config/dev.js +91 -0
  7. package/config/k8s-eitri.js +92 -0
  8. package/config/loc-eitri.js +92 -0
  9. package/config/prod-eitri.js +92 -0
  10. package/config/test-eitri.js +2 -0
  11. package/index-eitri.js +6 -0
  12. package/index.js +182 -0
  13. package/install-dev.bat +1 -0
  14. package/install-dev.sh +1 -0
  15. package/jest.config.js +6 -0
  16. package/jsconfig.json +9 -0
  17. package/package.json +80 -0
  18. package/publisher.js +53 -0
  19. package/src/cmd/clean.js +179 -0
  20. package/src/cmd/create.js +281 -0
  21. package/src/cmd/credentials.js +105 -0
  22. package/src/cmd/invite.js +87 -0
  23. package/src/cmd/list.js +36 -0
  24. package/src/cmd/login.js +51 -0
  25. package/src/cmd/manage-env.js +129 -0
  26. package/src/cmd/open-share.js +6 -0
  27. package/src/cmd/order-details.js +6 -0
  28. package/src/cmd/push-version.js +182 -0
  29. package/src/cmd/show-message-if-outdated-package.js +32 -0
  30. package/src/cmd/signup.js +69 -0
  31. package/src/cmd/start.js +171 -0
  32. package/src/cmd/tail-logs.js +26 -0
  33. package/src/cmd/test-initialization-params.js +6 -0
  34. package/src/cmd/validate.js +170 -0
  35. package/src/cmd/version.js +29 -0
  36. package/src/enum/WatcherOpts.js +3 -0
  37. package/src/enum/target.js +6 -0
  38. package/src/helpers/request-listener-helper.js +55 -0
  39. package/src/model/Payload.js +45 -0
  40. package/src/model/Target.js +76 -0
  41. package/src/model/User.js +11 -0
  42. package/src/service/AuthConfig.js +88 -0
  43. package/src/service/BlindGuardian.js +134 -0
  44. package/src/service/CliLogin.js +47 -0
  45. package/src/service/ConfigService.js +16 -0
  46. package/src/service/CredentialsService.js +47 -0
  47. package/src/service/GATrackingStrategy.js +16 -0
  48. package/src/service/HashFolder.js +79 -0
  49. package/src/service/Http.js +234 -0
  50. package/src/service/InviteService.js +45 -0
  51. package/src/service/ManageEnvService.js +10 -0
  52. package/src/service/MiniLog.js +132 -0
  53. package/src/service/QRCodeFactory.js +43 -0
  54. package/src/service/Server.js +239 -0
  55. package/src/service/StarterService.js +31 -0
  56. package/src/service/TagTree.js +101 -0
  57. package/src/service/TargetService.js +97 -0
  58. package/src/service/TrackService.js +11 -0
  59. package/src/service/TrackingEitriAnalytics.js +32 -0
  60. package/src/service/TrackingService.js +183 -0
  61. package/src/service/ValidateResult.js +57 -0
  62. package/src/service/Watcher.js +119 -0
  63. package/src/service/Workspace.js +1069 -0
  64. package/src/service/WorkspaceManager.js +74 -0
  65. package/src/service/factories/DoubtsStarterFactory.js +25 -0
  66. package/src/service/factories/MiniWebAppFactory.js +43 -0
  67. package/src/service/factories/QRCodeStarterFactory.js +78 -0
  68. package/src/service/factories/WebStarterFactory.js +88 -0
  69. package/src/service/factories/WoodCoffeeFactory.js +230 -0
  70. package/src/util/AboutTemplate.jsx +14 -0
  71. package/src/util/UrlUtils.js +12 -0
  72. package/src/util/UserLocalCredential.js +122 -0
  73. package/src/util/error-messages/error-messages.js +24 -0
  74. package/src/util/error-messages/invite/invite-error-messages.js +14 -0
  75. package/src/util/getCliVersion.js +13 -0
  76. package/src/util/getCreateFactory.js +9 -0
  77. package/src/util/ipv4.js +19 -0
  78. package/src/util/manage-env.js +65 -0
  79. package/src/util/open-docs.js +7 -0
  80. package/src/util/os.js +39 -0
  81. package/src/util/server-url.js +15 -0
  82. package/src/util/template-utils.js +21 -0
  83. package/src/view/index.html +19 -0
  84. package/targetMobileStickyness.md +47 -0
  85. package/targetWebStickyness.md +40 -0
  86. package/test/_fixtures/factory.js +30 -0
  87. package/test/_fixtures/miniWebApp/miniapp.conf.js +4 -0
  88. package/test/_fixtures/miniapp.conf.js +5 -0
  89. package/test/_fixtures/server/HelloWorldBackend.js +7 -0
  90. package/test/_fixtures/src/Home.js +5 -0
  91. package/test/_fixtures/src/Home2.js +5 -0
  92. package/test/_fixtures/src/commons/util.js +3 -0
  93. package/test/_fixtures/src/components/TagA.jsx +4 -0
  94. package/test/_fixtures/src/components/TagB.jsx +4 -0
  95. package/test/_fixtures/src/components/TagC.jsx +3 -0
  96. package/test/_fixtures/src/components/TagD.jsx +3 -0
  97. package/test/_fixtures/src/server/foo.js +7 -0
  98. package/test/_fixtures/src/views/AboutTemplate.jsx +14 -0
  99. package/test/_fixtures/woodcoffee/miniapp.conf.js +3 -0
  100. package/test/ame.conf.js +3 -0
  101. package/test/cmd/clean.test.js +66 -0
  102. package/test/cmd/create.test.js +252 -0
  103. package/test/cmd/credentials.test.js +159 -0
  104. package/test/cmd/list.test.js +74 -0
  105. package/test/cmd/manage-env.test.js +168 -0
  106. package/test/cmd/signup.test.js +20 -0
  107. package/test/cmd/start.test.js +5 -0
  108. package/test/miniapp.conf.js +3 -0
  109. package/test/model/Payload.test.js +35 -0
  110. package/test/service/BlindGuardian.test.js +84 -0
  111. package/test/service/CheckAmeConf.test.js +313 -0
  112. package/test/service/Http.test.js +312 -0
  113. package/test/service/InviteService.test.js +117 -0
  114. package/test/service/MiniWebAppFactory.test.js +40 -0
  115. package/test/service/TagTree.test.js +81 -0
  116. package/test/service/TargetService.test.js +48 -0
  117. package/test/service/TrackingService.test.js +105 -0
  118. package/test/service/UserAmeConf.test.js +47 -0
  119. package/test/service/WoodCoffeeFactory.test.js +148 -0
  120. package/test/service/Workspace.test.js +364 -0
  121. package/thinQrCode.md +58 -0
  122. package/v1.5.0.md +3 -0
@@ -0,0 +1,6 @@
1
+ const start = require('./start')
2
+
3
+ module.exports = async function orderDetails(orderId, cmdObj) {
4
+ let args = {...cmdObj, view: 'OrderDetails', orderId: orderId}
5
+ await start(args)
6
+ }
@@ -0,0 +1,182 @@
1
+ const path = require('path')
2
+ const { workspace } = require('../service/Workspace')
3
+ const validator = require('./validate')
4
+ const MiniLog = require('../service/MiniLog')
5
+ const TrackingService = require('../service/TrackingService')
6
+ const fs = require('fs')
7
+ const config = require('../service/ConfigService')
8
+ const TargetService = require('../service/TargetService')
9
+ const inquirer = require('inquirer')
10
+ const TrackingEitriAnalytics = require('../service/TrackingEitriAnalytics')
11
+
12
+ const blindGuardian = workspace.blindGuardian
13
+ const trackingService = new TrackingService(blindGuardian)
14
+ const targetService = new TargetService(workspace)
15
+
16
+ module.exports = async function pushVersion(cmdObj) {
17
+ try {
18
+ await validator.assertPushVersionMessage(cmdObj.message)
19
+ await validator.assertCommandNotRunning('push-version')
20
+ const folder2watch = path.join(process.cwd(), 'src')
21
+ const miniLog = new MiniLog(config.get('miniLog'))
22
+ workspace.setFolder2Watch(folder2watch)
23
+
24
+ const resourceFolders2watch = [path.join(process.cwd(), 'public')]
25
+ if (fs.existsSync(resourceFolders2watch)) {
26
+ workspace.setResourceFolder2Watch(resourceFolders2watch)
27
+ }
28
+ workspace.publishing = true
29
+ let miniConf = workspace.getMiniConf()
30
+ let validateResult = checkErros(miniConf)
31
+
32
+ if (!validateResult.isSuccess()) {
33
+ console.log(
34
+ 'Por favor, verifique atentamente os erros exibidos acima. Siga o exemplo abaixo: ' +
35
+ `
36
+ module.exports = {
37
+
38
+ // Dados da sua empresa
39
+ organization: {
40
+ "name": "Minha Empresa"
41
+ },
42
+
43
+ // Nome do seu mini app
44
+ "name": "Meu Mini App",
45
+
46
+ // Titulo do mini app, que vai em baixo do botao na pagina de transacoes
47
+ "title": "Meu super mini app",
48
+
49
+ // Chave para gerar a ordem/qrcode de pagamento (opcional)
50
+ "public-key": "",
51
+
52
+ // Identificador amigavel para colocar em uma url
53
+ "slug": "com.eitri.loja",
54
+
55
+ // Versao do mini app
56
+ "version": "1.0.0",
57
+
58
+ ${await targetService.getAppConfExampleSnippet()}
59
+ };
60
+
61
+
62
+ `
63
+ )
64
+
65
+ return
66
+ }
67
+ const separator = '======================================================================='
68
+ blindGuardian.readConf()
69
+ workspace.setServerUrl(config.get('workspace').url)
70
+ console.log('Conectando à forja de Eitri')
71
+ await workspace.init()
72
+ await miniLog.connect(workspace.userEmail)
73
+ console.log(separator)
74
+ console.log('Analisando versões')
75
+ const {target} = await workspace.checkVersions()
76
+
77
+ const {addedPermissions, removedPermissions} = await workspace.comparePermissions(target)
78
+ await logPermissionsAndOpenPrompt(addedPermissions, removedPermissions, cmdObj)
79
+ console.log(separator)
80
+ console.log('Preparando os arquivos do seu eitri-app')
81
+
82
+ await workspace.uploadAll()
83
+ const webhooks = workspace.getWebhooks()
84
+ printAvailableWebhooks(webhooks)
85
+ console.log('')
86
+ console.log(separator)
87
+ console.log('Gerando eitri-app')
88
+
89
+ const start = Date.now()
90
+ let pushVersionPromise = miniLog.awaitForPushVersion()
91
+ await workspace.pushVersionAsJson(cmdObj.message)
92
+ await pushVersionPromise
93
+ console.log(separator)
94
+ console.log('\x1b[1m\x1b[32mSucesso!!\x1b[0m');
95
+ console.log(`\x1b[1mA versão [${miniConf.version}] do seu eitri-app foi gerada e está\x1b[0m`);
96
+ console.log('\x1b[1mdisponível no Eitri-console para aprovação\x1b[0m');
97
+ console.log(separator)
98
+
99
+
100
+ await track(miniConf, start)
101
+ await TrackingEitriAnalytics.sendEvent({
102
+ command: "push-version",
103
+ success: true,
104
+ data: {
105
+ eitriApp: {
106
+ ...miniConf,
107
+ organization: Object.keys(miniConf?.organization).length !== 0 ? miniConf?.organization : "-"
108
+ },
109
+ target,
110
+ startDate: `${start}`,
111
+ }
112
+ })
113
+ process.exit(0)
114
+ } catch (e) {
115
+ if (cmdObj.verbose) {
116
+ console.error(e)
117
+ } else if (e.response && e.response.data && e.response.data.friendlyMessage) {
118
+ console.log(`\x1b[1m\x1b[31m${e.response.data.friendlyMessage}\x1b[0m`);
119
+ } else if (e && e.message) {
120
+ console.log(`\x1b[1m\x1b[31m${e.message}\x1b[0m`);
121
+ } else {
122
+ console.log(`\x1b[1m\x1b[31mNão será possível continuar por enquanto. A forja encontrou um erro.\x1b[0m`);
123
+ }
124
+
125
+ await trackingService.sendError(e)
126
+ await TrackingEitriAnalytics.sendEvent({
127
+ command: "push-version",
128
+ success: false,
129
+ errorMessage: e?.message
130
+ })
131
+ process.exit(1)
132
+ }
133
+ }
134
+
135
+ function printAvailableWebhooks(webhooks) {
136
+ if(!webhooks || webhooks.length === 0) return
137
+ console.log('\nWebhooks do MiniApp.')
138
+ console.table(webhooks)
139
+ }
140
+
141
+ async function track(miniConf, start) {
142
+ let libs = await targetService.getLibs()
143
+ let event = {
144
+ superClientVersion: miniConf[libs.superAppClientLibName],
145
+ componentsVersion: miniConf[libs.componentsLibName],
146
+ miniAppSlug: miniConf.slug,
147
+ miniAppVersion: miniConf.version,
148
+ timeMs: Date.now() - start,
149
+ }
150
+ await trackingService.sendPushedVersion(event)
151
+ }
152
+
153
+ function checkErros(miniConf) {
154
+ let validateResult = validator.validate(miniConf)
155
+ validateResult.errors.forEach(message => console.log(message))
156
+ return validateResult
157
+ }
158
+
159
+ async function logPermissionsAndOpenPrompt(addedPermissions, removedPermissions, cmdObj) {
160
+ const GREEN_COLOR = '\x1b[32m'
161
+ const RED_COLOR = '\x1b[31m'
162
+ const MINIMAL_LENGTH = 0
163
+ if(addedPermissions.length > MINIMAL_LENGTH) {
164
+ console.log(`${GREEN_COLOR}\nPermissões adicionadas: ${addedPermissions}${GREEN_COLOR}`)
165
+ }
166
+ if(removedPermissions.length > MINIMAL_LENGTH) {
167
+ console.log(`${RED_COLOR}Permissões removidas: ${removedPermissions}\n${RED_COLOR}`)
168
+ }
169
+ if(!cmdObj.yes && (addedPermissions.length > MINIMAL_LENGTH || removedPermissions.length > MINIMAL_LENGTH)) {
170
+ const answer = await inquirer.prompt([
171
+ {
172
+ name: 'option',
173
+ message: 'Houve uma alteração nas permissões em relação a versão publicada. Deseja Continuar?',
174
+ type: 'rawlist',
175
+ choices: ['Sim', 'Não']
176
+ }
177
+ ])
178
+ if(answer.option === 'Não') {
179
+ process.exit(0)
180
+ }
181
+ }
182
+ }
@@ -0,0 +1,32 @@
1
+ const {getVersion} = require('../cmd/version')
2
+ module.exports = function showMessageIfOutdatedPackage(workspace, packageName ) {
3
+
4
+ let miniConf = workspace.getMiniConf()
5
+ const userVersion = miniConf[packageName]
6
+ const publishedVersion = getVersion(packageName)
7
+
8
+ if('eitri-app-components' === packageName) {
9
+ if(/^1/.test(`${userVersion}`)){
10
+ console.log('\n')
11
+ console.log('\t╔═══════════════════════════════════════╗')
12
+ console.log('\t║ Atenção: O suporte para as bibliotecas║')
13
+ console.log('\t║ de componente com versão anteriores a ║')
14
+ console.log('\t║ 2.0.0 finalizarão em outubro de 2021. ║')
15
+ console.log('\t╚═══════════════════════════════════════╝\n')
16
+ } else {
17
+ if (userVersion !== publishedVersion) {
18
+ console.log(
19
+ `\t> Alerta: Já existe uma versão ${ publishedVersion} da biblioteca ${packageName}.\n\t> Você está usando uma mais antiga (${userVersion}), recomenda-se atualizar.`
20
+ )
21
+ console.log('\t> Maiores informações em: https://eitri-app-components.calindra.com.br/\n')
22
+ }
23
+ }
24
+ } else {
25
+ if (userVersion !== publishedVersion) {
26
+ console.log(
27
+ `\t> Alerta: Já existe uma versão ${ publishedVersion} da biblioteca ${packageName}.\n\t> Você está usando uma mais antiga (${userVersion}), recomenda-se atualizar.`
28
+ )
29
+ console.log('\t> Maiores informações em: https://super-app-client.calindra.com.br/docs/eitri-app-client/\n')
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,69 @@
1
+ const BlindGuardian = require('../service/BlindGuardian')
2
+ const validator = require('./validate')
3
+ const User = require('../model/User')
4
+ const UserLocalCredential = require('../util/UserLocalCredential')
5
+ const TrackingEitriAnalytics = require('../service/TrackingEitriAnalytics')
6
+
7
+ module.exports = async function signup(args) {
8
+ try {
9
+
10
+ process.env['LOG_LEVEL'] = args.verbose
11
+
12
+ if (!args.force) {
13
+ await validator.assertCommandNotRunning('signup')
14
+ }
15
+
16
+ const { name, email } = args
17
+
18
+ if(!name) {
19
+ console.log('"Nome" deve ser fornecido!')
20
+ process.exit(1)
21
+ }
22
+
23
+ if(!email) {
24
+ console.log('"E-mail" deve ser fornecido!')
25
+ process.exit(1)
26
+ }
27
+ const user = new User(name, email)
28
+
29
+ const blind = new BlindGuardian()
30
+ const persistentUser = await blind.createUser(user)
31
+ const {credential } = persistentUser
32
+ const { clientId: devUser, clientSecret: devKey } = credential
33
+ const conf = { devUser, devKey }
34
+
35
+ new UserLocalCredential().saveContent(conf)
36
+
37
+ TrackingEitriAnalytics.sendEvent({
38
+ command: "signup",
39
+ success: true,
40
+ data: {
41
+ args
42
+ }
43
+ })
44
+ } catch (e) {
45
+ await TrackingEitriAnalytics.sendEvent({
46
+ command: "signup",
47
+ success: false,
48
+ errorMessage: e?.message
49
+ })
50
+
51
+ if (args.verbose) console.error(e)
52
+
53
+ if (e.response && e.response.data && e.response.data.friendlyMessage) {
54
+ const { name, friendlyMessage } = e.response.data
55
+
56
+ console.error(`ERRO: ${friendlyMessage}`)
57
+
58
+ if (name === 'NameCharacterLimitExceed') {
59
+ process.exit(1)
60
+ }
61
+ } else if (e && e.message) {
62
+ console.error(`ERRO: ${e.message}`)
63
+ } else {
64
+ console.log('Erro inesperado, tente novamente mais tarde.')
65
+ }
66
+
67
+ process.exit(1)
68
+ }
69
+ }
@@ -0,0 +1,171 @@
1
+ const path = require('path')
2
+ const Watcher = require('../service/Watcher')
3
+ const { workspace } = require('../service/Workspace')
4
+ const MiniLog = require('../service/MiniLog')
5
+ const { version } = require('./version')
6
+ const showMessageIfOutdatedPackage = require('./show-message-if-outdated-package.js')
7
+ const validator = require('./validate')
8
+ const TrackingService = require('../service/TrackingService')
9
+ const fs = require('fs')
10
+ const config = require('../service/ConfigService')
11
+ const handleStartServer = require('../service/StarterService')
12
+ const inquirer = require('inquirer')
13
+ const TrackingEitriAnalytics = require('../service/TrackingEitriAnalytics')
14
+
15
+ const blindGuardian = workspace.blindGuardian
16
+ const hashFolder = workspace.hashFolder
17
+ const trackingService = new TrackingService(blindGuardian, { ignoreCredentialError: true })
18
+ const watcher = new Watcher(workspace, hashFolder, trackingService)
19
+
20
+ module.exports = async function start(args) {
21
+ try {
22
+ if (!args.force) {
23
+ await validator.assertCommandNotRunning('start')
24
+ }
25
+
26
+ const miniLog = new MiniLog(config.get('miniLog'))
27
+
28
+ // TODO EITRI: descomentar apos publicacao das libs no npm
29
+ //version()
30
+
31
+ const resourceFolders2watch = [path.join(process.cwd(), 'public')]
32
+ if (fs.existsSync(resourceFolders2watch)) {
33
+ workspace.setResourceFolder2Watch(resourceFolders2watch)
34
+ }
35
+
36
+ const url = config.get('workspace').url
37
+ const setupResult = await workspace.setup()
38
+ const target = setupResult.target.name
39
+
40
+ let targetConfig = {}
41
+
42
+ if(args.listTargetConfigs) {
43
+ await listTargetConfigs(target)
44
+ process.exit(1)
45
+ }
46
+
47
+ if(args.targetConfig) {
48
+ targetConfig = await askTargetConfig(args, target)
49
+ } else {
50
+ targetConfig = await getDefaultTargetConfig(target)
51
+ }
52
+
53
+ blindGuardian.readConf()
54
+ const qrCodeUrl = config.get('qrCode').url
55
+ if (args.verbose) {
56
+ blindGuardian.verbose = true
57
+ miniLog.verbose = true
58
+ console.log('WS url', url)
59
+ }
60
+ workspace.setServerUrl(url)
61
+ workspace.setQrCodeUrl(qrCodeUrl)
62
+ await workspace.init()
63
+ const silentOnConnect = args.verbose ? false : true
64
+ await miniLog.connect(workspace.userEmail, silentOnConnect)
65
+
66
+ // TODO EITRI: descomentar apos publicacao das libs no npm
67
+ // setupResult.state.libs.forEach(lib => {
68
+ // showMessageIfOutdatedPackage(workspace, lib.name)
69
+ // })
70
+
71
+ if (args.unzip) {
72
+ await workspace.uploadAll(args)
73
+ } else {
74
+ await workspace.uploadZip(args)
75
+ }
76
+ const loadedTarget = await workspace.getTarget()
77
+ const platform = loadedTarget.platform
78
+ await handleStartServer(args, trackingService, watcher, workspace, target, targetConfig, platform)
79
+
80
+ TrackingEitriAnalytics.sendEvent({
81
+ command: "start",
82
+ success: true,
83
+ data: {
84
+ args,
85
+ platform,
86
+ workspace: {
87
+ id: workspace?.target?.id,
88
+ name: workspace?.target?.name,
89
+ superAppClientLibName: workspace?.target?.superAppClientLibName,
90
+ componentsLibName: workspace?.target?.componentsLibName,
91
+ description: workspace?.target?.description,
92
+ status: workspace?.target?.status,
93
+ platform: workspace?.target?.platform,
94
+ organization: {...workspace?.target?.organization},
95
+ userEmail: workspace?.userEmail,
96
+ },
97
+ eitriApp: {
98
+ name: workspace?._miniConf?.name,
99
+ title: workspace?._miniConf?.title,
100
+ slug: workspace?._miniConf?.slug,
101
+ version: workspace?._miniConf?.version,
102
+ organization: workspace?._miniConf?.organization,
103
+ "eitri-app-components": workspace?._miniConf?.["eitri-app-components"],
104
+ "eitri-app-client": workspace?._miniConf?.["eitri-app-client"],
105
+ "eitri-commons": workspace?._miniConf?.["eitri-commons"],
106
+ publickey: workspace?._miniConf?.["public-key"]
107
+ }
108
+ }
109
+ })
110
+ } catch (e) {
111
+ TrackingEitriAnalytics.sendEvent({
112
+ command: "start",
113
+ success: false,
114
+ data: {
115
+ args,
116
+ },
117
+ errorMessage: e?.message || ""
118
+ })
119
+
120
+ if (args.verbose) console.error(e)
121
+
122
+ if (e.response && e.response.data && e.response.data.friendlyMessage) {
123
+ const { name, friendlyMessage } = e.response.data
124
+
125
+ console.error(`ERRO: ${friendlyMessage}`)
126
+
127
+ if (name === 'NameCharacterLimitExceed') {
128
+ process.exit(1)
129
+ }
130
+ } else if (e && e.message) {
131
+ console.log(`\x1b[1m\x1b[31m${e.message}\x1b[0m`);
132
+ } else {
133
+ console.log(`\x1b[1m\x1b[31mEitri encontrou um erro e por isso parou, tente novamente mais tarde.\x1b[0m`);
134
+ }
135
+
136
+ await trackingService.sendError(e)
137
+
138
+ process.exit(1)
139
+ }
140
+ }
141
+
142
+ async function askTargetConfig(args, target) {
143
+ const avaiableConfigs = await workspace.getTargetConfig(args.targetConfig, target)
144
+
145
+ console.log(`Utilizando configuração: ${avaiableConfigs[0].id}`)
146
+ return avaiableConfigs[0]
147
+
148
+ }
149
+
150
+ async function getDefaultTargetConfig(target) {
151
+ const configs = await workspace.getTargetConfig('default', target)
152
+ return configs[0]
153
+ }
154
+
155
+ async function listTargetConfigs(target) {
156
+ const avaiableConfigs = await workspace.getAllTargetConfigs(target)
157
+
158
+ const avaiableConfigsIds = avaiableConfigs.map(config => config.id)
159
+
160
+ const res = await inquirer.prompt([
161
+ {
162
+ name: 'accepted',
163
+ type: 'rawlist',
164
+ message: 'Configurações disponíveis:',
165
+ choices: avaiableConfigsIds
166
+ }
167
+ ]).then(input => input)
168
+
169
+ const config = avaiableConfigs.find(cfg => cfg.id === res.accepted)
170
+ console.log(`Utilize o comando --target-config ${config.id} para iniciar o miniapp com a configuração desejada`)
171
+ }
@@ -0,0 +1,26 @@
1
+ const path = require('path')
2
+ const {Workspace} = require('../service/Workspace')
3
+ const BlindGuardian = require('../service/BlindGuardian')
4
+ const MiniLog = require('../service/MiniLog')
5
+ const version = require('./version')
6
+ const HashFolder = require('../service/HashFolder')
7
+ const blindGuardian = new BlindGuardian()
8
+ const hashFolder = new HashFolder()
9
+ const workspace = new Workspace(blindGuardian, hashFolder)
10
+
11
+ module.exports = async function tailLogs(clientEmail) {
12
+ const config = require('config')
13
+ const miniLog = new MiniLog(config.get('miniLog'))
14
+ version()
15
+ const folder2watch = path.join(process.cwd(), 'src')
16
+ workspace.setFolder2Watch(folder2watch)
17
+ blindGuardian.readConf()
18
+
19
+ const url = config.get('workspace').url
20
+ workspace.setServerUrl(url)
21
+ await workspace.init()
22
+ await miniLog.connect(workspace.userEmail)
23
+ let miniConf = await workspace.getMiniConf()
24
+ let fullUrl = `https://miniapps.eitri.com/open/${miniConf.slug}?logsFrom=${clientEmail}&logsTo=${workspace.userEmail}`
25
+ console.log(fullUrl)
26
+ }
@@ -0,0 +1,6 @@
1
+ const start = require('./start')
2
+
3
+ module.exports = async function testInitializationParams(initializationParams, cmdObj) {
4
+ let args = {...cmdObj, initializationParams: initializationParams}
5
+ await start(args)
6
+ }
@@ -0,0 +1,170 @@
1
+ const ValidateResult = require('../service/ValidateResult')
2
+ const ps = require('ps-node')
3
+
4
+ const NAME_TITLE_REGEX = /^([a-zA-ZÀ-ú0-9\s]|-|\+|&|!)+$/
5
+ const SLUG_REGEX = /^(\.|[a-z0-9]|-)+$/i
6
+
7
+ module.exports.NAME_TITLE_REGEX = NAME_TITLE_REGEX
8
+ module.exports.SLUG_REGEX = SLUG_REGEX
9
+
10
+ module.exports.assertCommandNotRunning = function (commandName) {
11
+ return new Promise((resolve, reject) => {
12
+ ps.lookup({command: 'node'}, (err, processes) => {
13
+ if (err) throw new Error('erro ao executar comando')
14
+
15
+ console.log('\x1b[1m\x1b[34mIniciando eitri builder\x1b[0m');
16
+
17
+ const runningProcesses = processes.filter((process) => {
18
+ let isAmeToolsRunning = false
19
+ let isCommandRunning = false
20
+
21
+ for (var argument of process.arguments) {
22
+ if (argument.includes('eitri')) {
23
+ isAmeToolsRunning = true
24
+ continue
25
+ }
26
+ if (argument === commandName) isCommandRunning = true
27
+ }
28
+
29
+ return isAmeToolsRunning && isCommandRunning
30
+ })
31
+
32
+ // if (runningProcesses && runningProcesses.length > 1) {
33
+ // console.error('EITRI: o comando ' + commandName + ' já está sendo executado')
34
+ // reject()
35
+ // process.exit(1)
36
+ // } else {
37
+ resolve()
38
+ // }
39
+ })
40
+ })
41
+ }
42
+
43
+ //TODO: ESSE MÓDULO DEVE SER APAGADO, QUANDO NÃO EXISTIR MAIS O COMANDO PUBLISH
44
+ module.exports.assertPublishMessage = function (publishMessage) {
45
+ if (publishMessage) {
46
+ if (publishMessage.length > 255) {
47
+ console.error(`Se fornecida, a mensagem de publicação precisa ter menos de 255 caracteres. Tamanho atual: ${publishMessage.length}`)
48
+ process.exit(1)
49
+ }
50
+ }
51
+ }
52
+
53
+ module.exports.assertBuildMessage = function (buildMessage) {
54
+ if (buildMessage) {
55
+ if (buildMessage.length > 255) {
56
+ console.error(`Se fornecida, a mensagem de build precisa ter menos de 255 caracteres. Tamanho atual: ${buildMessage.length}`)
57
+ process.exit(1)
58
+ }
59
+ }
60
+ }
61
+
62
+ module.exports.assertPushVersionMessage = function (buildMessage) {
63
+ if (buildMessage) {
64
+ if (buildMessage.length > 255) {
65
+ console.error(`Se fornecida, a mensagem de push-version precisa ter menos de 255 caracteres. Tamanho atual: ${buildMessage.length}`)
66
+ process.exit(1)
67
+ }
68
+ }
69
+ }
70
+
71
+ module.exports.validate = function (miniConf) {
72
+ let validateResult = new ValidateResult([])
73
+ let isversionvalid = checkAmeVersion(miniConf)
74
+
75
+
76
+ if (!miniConf.organization) {
77
+ validateResult.addError(
78
+ 'Por Favor, preencha o campo \'organization\' (Utilize apenas caracteres maiusculo, minusculo e espaco. Ex: \'Minha Empresa\').'
79
+ )
80
+ }
81
+
82
+ if (!miniConf.name) {
83
+ validateResult.addError(
84
+ 'Por Favor, preencha o campo \'name\' (Utilize apenas caracteres maiusculo, minusculo e espaco. Ex: \'Meu Mini App\').'
85
+ )
86
+ } else if (!miniConf.name.match(NAME_TITLE_REGEX)) {
87
+ validateResult.addError(
88
+ 'Por Favor, preencha o campo \'name\' corretamente antes de publicar'
89
+ )
90
+ }
91
+
92
+ if (!miniConf.title) {
93
+ validateResult.addError(
94
+ 'Por Favor, preencha o campo \'title\' (Utilize apenas caracteres maiusculo, minusculo e espaco. Ex: \'Meu super mini app\').'
95
+ )
96
+ } else if (!miniConf.title.match(NAME_TITLE_REGEX)) {
97
+ validateResult.addError(
98
+ 'Por Favor, preencha o campo \'title\' corretamente antes de publicar'
99
+ )
100
+ }
101
+
102
+ if (!miniConf.slug) {
103
+ validateResult.addError(
104
+ 'Por Favor, preencha o campo \'slug\' (Utilize apenas caracteres minusculo e ponto. Ex: \'com.eitri.loja\').'
105
+ )
106
+ } else if (!miniConf.slug.match(SLUG_REGEX)) {
107
+ validateResult.addError(
108
+ 'Por Favor, preencha o campo \'slug\' corretamente antes de publicar'
109
+ )
110
+ }
111
+
112
+ if (!isversionvalid) {
113
+ validateResult.addError(
114
+ 'Por Favor, preencha o campo \'version\' (Utilize esse formato X.Y.Z. Ex: \'1.0.0\').'
115
+ )
116
+ }
117
+
118
+ // Se houver objeto privacy, onboarding eh obrigatorio. Mode eh opcional.
119
+ if (miniConf.privacy) {
120
+ if (miniConf.privacy.onBoarding) {
121
+ const onBoarding = miniConf.privacy.onBoarding
122
+ const onBoardingItems = onBoarding.items
123
+ if (!Array.isArray(onBoardingItems)) {
124
+ validateResult.addError(
125
+ 'Objeto de configuração "privacy.onBoarding.items" deve ser um array de {img, title, description}'
126
+ )
127
+ } else {
128
+ onBoardingItems.forEach((item, index) => {
129
+ if (!(item.img && item.title && item.description)) {
130
+ validateResult.addError(
131
+ `Um ou mais itens do objeto de "onBoarding" nao possui as propriedades {img, title, description}: ${JSON.stringify(item)}`
132
+ )
133
+ }
134
+
135
+ try {
136
+ new URL(item.img)
137
+ } catch (e) {
138
+ if (e.code === 'ERR_INVALID_URL') {
139
+ validateResult.addError(
140
+ `onBoarding.Item[${index}] invalido. Atributo "img" nao eh uma URL: ${item.img}`
141
+ )
142
+ }
143
+ }
144
+ })
145
+ }
146
+ } else {
147
+ validateResult.addError(
148
+ 'Objeto "privacy" nao possui atributo "onBoarding"'
149
+ )
150
+ }
151
+ }
152
+ return validateResult
153
+ }
154
+
155
+ function checkAmeVersion(miniConf) {
156
+ if (!miniConf.version) {
157
+ return false
158
+ }
159
+ let value = typeof miniConf.version
160
+ if (!(value === 'string')) {
161
+ return false
162
+ }
163
+
164
+ const digit = miniConf.version.match(/^(\d+\.)(\d+\.)(\d+)$/)
165
+ if (!digit) {
166
+ return false
167
+ }
168
+
169
+ return true
170
+ }