-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
317 lines (266 loc) · 11 KB
/
index.js
File metadata and controls
317 lines (266 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
Copyright 2024 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const ora = require('ora')
const fs = require('fs-extra')
const https = require('node:https')
const getPort = require('get-port')
const open = require('open')
const chalk = require('chalk')
const { Flags, ux } = require('@oclif/core')
const coreConfig = require('@adobe/aio-lib-core-config')
const aioLogger = require('@adobe/aio-lib-core-logging')('@adobe/aio-cli-plugin-app-dev:index', { level: process.env.LOG_LEVEL, provider: 'winston' })
const { buildActions } = require('@adobe/aio-lib-runtime')
const BaseCommand = require('../../../BaseCommand')
const { runDev } = require('../../../lib/run-dev')
const { runInProcess } = require('../../../lib/app-helper')
const { createWatcher } = require('../../../lib/actions-watcher')
const APP_EVENT_PRE_APP_DEV = 'pre-app-dev'
const APP_EVENT_POST_APP_DEV = 'post-app-dev'
const { PUB_CERT_PATH, PRIVATE_KEY_PATH, DEV_KEYS_DIR, DEV_KEYS_CONFIG_KEY, SERVER_DEFAULT_PORT, DEV_API_WEB_PREFIX } = require('../../../lib/constants')
const Cleanup = require('../../../lib/cleanup')
class Dev extends BaseCommand {
async run () {
const { flags } = await this.parse(Dev)
const spinner = ora()
const runConfigs = await this.getAppExtConfigs(flags)
const entries = Object.entries(runConfigs)
let entry = entries[0]
if (flags.extension) {
flags.extension.forEach((extName) => {
entry = entries.find(([entryName]) => entryName === extName)
})
if (!entry) {
this.error(`extension '${flags.extension}' was not found.`)
}
} else if (entries.length > 1) {
this.error('Your app implements multiple extensions. You can only run one at the time, please select which extension to run with the \'-e\' flag.')
}
const [name, config] = entry
try {
// do some verification
await this.verifyActionConfig(config)
// now we are good, either there is only 1 extension point or -e flag for one was provided
await this.runOneExtensionPoint(name, config, flags)
} catch (error) {
spinner.stop()
// delegate to top handler
throw error
}
}
displayFrontendUrl (flags, frontendUrl) {
this.log(chalk.blue(chalk.bold(`To view your local application:\n -> ${frontendUrl}`)))
const launchUrl = this.getLaunchUrlPrefix() + frontendUrl
if (flags.open) {
this.log(chalk.blue(chalk.bold(`Opening your deployed application in the Experience Cloud shell:\n -> ${launchUrl}`)))
open(launchUrl)
} else {
this.log(chalk.blue(chalk.bold(`To view your deployed application in the Experience Cloud shell:\n -> ${launchUrl}`)))
}
}
displayActionUrls (actionUrls) {
const blueBoldLog = (...args) => this.log(chalk.blue(chalk.bold(...args)))
const printUrl = (url) => blueBoldLog(` -> ${url}`)
blueBoldLog('Your actions:')
const webActions = Object.values(actionUrls).filter(url => url.includes(DEV_API_WEB_PREFIX))
const nonWebActions = Object.keys(actionUrls).filter((key) => {
const url = actionUrls[key]
return !url.includes(DEV_API_WEB_PREFIX)
})
this.log('web actions:')
webActions.forEach(printUrl)
this.log('non-web actions:')
nonWebActions.forEach(printUrl)
}
/**
* Verifies the app config sequences and actions, based on criteria.
* 1. all actions in sequences must exist
* 2. a sequence cannot have the same name as an action
*
* @param {object} config the config for the app
*/
async verifyActionConfig (config) {
const actionConfig = config.manifest?.full?.packages
const errors = []
// there might not be a runtime manifest, that's ok
if (!actionConfig) {
return
}
// 1. all actions in sequences must exist
Object.entries(actionConfig).forEach(([_, pkg]) => { // iterate through each package
const sequences = pkg?.sequences || {}
const actions = pkg?.actions || {}
Object.entries(sequences).forEach(([sequenceName, sequence]) => {
const sequenceActions = sequence?.actions?.split(',') || []
if (sequenceActions.length === 0) {
this.error(`Actions for the sequence '${sequenceName}' not provided.`)
}
const actionExistsWithSequenceName = actions[sequenceName]
if (actionExistsWithSequenceName) {
errors.push(`Sequence '${sequenceName}' is already defined as an action under the same package. Actions and sequences can not have the same name in a single package.`)
return
}
sequenceActions
.map((a) => a.trim())
.forEach((actionName) => {
const action = actions[actionName]
if (!action) {
errors.push(`Sequence component '${actionName}' does not exist (sequence = '${sequenceName}')`)
}
})
})
})
if (errors.length) {
this.error(errors.join('\n'))
}
}
async runAppBuild (extensionConfig) {
this.log('Building the app...')
if (extensionConfig.app.hasBackend) {
await buildActions(extensionConfig, null /* filterActions[] */, false /* skipCheck */)
}
}
async runOneExtensionPoint (name, config, flags) {
aioLogger.debug('runOneExtensionPoint called with', name, flags)
const hasBackend = config.app.hasBackend
const hasFrontend = config.app.hasFrontend
if (!hasBackend && !hasFrontend) {
this.error('nothing to run... there is no frontend and no manifest.yml, are you in a valid app?')
}
const runOptions = {
skipActions: false,
skipServe: false,
parcel: {
logLevel: flags.verbose ? 'verbose' : 'warn',
// always set to false on localhost to get debugging and hot reloading
shouldContentHash: false
},
fetchLogs: true,
verbose: flags.verbose
}
try {
await runInProcess(config.hooks[APP_EVENT_PRE_APP_DEV], { config, options: runOptions })
} catch (err) {
this.log(err)
}
// check if there are certificates available, and generate them if not
try {
runOptions.parcel.https = await this.getOrGenerateCertificates({
pubCertPath: PUB_CERT_PATH,
privateKeyPath: PRIVATE_KEY_PATH,
devKeysDir: DEV_KEYS_DIR,
devKeysConfigKey: DEV_KEYS_CONFIG_KEY
})
} catch (error) {
console.error(error)
this.error(error)
}
const inprocHook = this.config.runHook.bind(this.config)
const cleanup = new Cleanup()
await this.runAppBuild(config)
const { frontendUrl, actionUrls, serverCleanup } = await runDev(runOptions, config, inprocHook)
cleanup.add(() => serverCleanup(), 'cleaning up runDev...')
// fire post hook
try {
await runInProcess(config.hooks[APP_EVENT_POST_APP_DEV], config)
} catch (err) {
this.log(err)
}
if (hasFrontend) {
this.displayFrontendUrl(flags, frontendUrl)
}
if (hasBackend) {
this.displayActionUrls(actionUrls)
const { watcherCleanup } = await createWatcher({ config, isLocal: true, inprocHook })
cleanup.add(() => watcherCleanup(), 'cleaning up action watcher...')
cleanup.wait()
}
this.log('press CTRL+C to terminate the dev environment')
}
async getOrGenerateCertificates ({ pubCertPath, privateKeyPath, devKeysDir, devKeysConfigKey, maxWaitTimeSeconds = 20 }) {
const certs = {
cert: pubCertPath, // Path to custom certificate
key: privateKeyPath // Path to custom key
}
/* get existing certificates from file.. */
if (fs.existsSync(privateKeyPath) && fs.existsSync(pubCertPath)) {
return certs
}
await fs.ensureDir(devKeysDir)
/* or get existing certificates from config.. */
const devConfig = coreConfig.get(devKeysConfigKey)
if (devConfig?.privateKey && devConfig?.publicCert) {
// yes? write them to file
await fs.writeFile(privateKeyPath, devConfig.privateKey)
await fs.writeFile(pubCertPath, devConfig.publicCert)
return certs
}
/* or if they do not exists, attempt to create them */
// 1. generate them using aio certificate generate command
const CertCmd = this.config.findCommand('certificate:generate')
if (CertCmd) {
const Instance = await CertCmd.load()
await Instance.run([`--keyout=${privateKeyPath}`, `--out=${pubCertPath}`, '-n=DeveloperSelfSigned.cert'])
} else {
// could not find the cert command, error is caught below
throw new Error('error while generating certificate - no certificate:generate command found')
}
// 2. store them globally in config
const privateKey = (await fs.readFile(privateKeyPath, { encoding: 'utf8' }))
const publicCert = (await fs.readFile(pubCertPath, { encoding: 'utf8' }))
coreConfig.set(`${devKeysConfigKey}.privateKey`, privateKey)
coreConfig.set(`${devKeysConfigKey}.publicCert`, publicCert)
// 3. ask the developer to accept them
let certAccepted = false
const startTime = Date.now()
const server = https.createServer({ key: privateKey, cert: publicCert }, (_, res) => {
certAccepted = true
res.writeHead(200)
res.end('Great, you have accepted the certificate and can now use it for development on this machine.\n' +
'You can close this window.')
})
const port = parseInt(process.env.PORT) || SERVER_DEFAULT_PORT
const actualPort = await getPort({ port })
server.listen(actualPort)
this.log('A self signed development certificate has been generated, you will need to accept it in your browser in order to use it.')
open(`https://localhost:${actualPort}`)
ux.action.start('Waiting for the certificate to be accepted.')
// eslint-disable-next-line no-unmodified-loop-condition
while (!certAccepted && (Date.now() - startTime) < (maxWaitTimeSeconds * 1000)) {
await new Promise(resolve => setTimeout(resolve, 1000)) // wait for 1 second
}
if (certAccepted) {
ux.action.stop()
this.log('Great, you accepted the certificate!')
} else {
ux.action.stop('timed out')
}
server.close()
return certs
}
}
Dev.description = 'Run your App Builder app locally'
Dev.args = {}
Dev.flags = {
...BaseCommand.flags,
open: Flags.boolean({
description: 'Open the default web browser after a successful run, only valid if your app has a front-end',
default: false,
char: 'o'
}),
extension: Flags.string({
description: 'Run only a specific extension, this flag can only be specified once',
char: 'e',
parse: (str) => [str],
// we do not support multiple yet
multiple: false
})
}
module.exports = Dev