Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add generator for Visual Studio Code launch configuration #123

Merged
merged 8 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions generators/add-vscode-config/VsCodeConfiguration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
Copyright 2021 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 path = require('path')

/**
* Create a VS Code launch compound.
*
* @param {Object} params the parameters
* @param {String} params.name the compound name
* @param {Array<string>} params.configurations an array of launch configuration names
*/
function createLaunchCompound (params) {
const { name, configurations = [] } = params
return {
name,
configurations
}
}

/**
* Create a VS Code basic launch configuration.
*
* @param {Object} params the parameters
* @param {String} params.type the launch configuration type
* @param {String} params.name the launch configuration name
* @param {String} params.request the launch configuration request
*/
function createLaunchConfiguration (params) {
const { type, name, request } = params
return {
type,
name,
request
}
}

/**
* Create a VS Code Chrome launch configuration.
*
* @param {Object} params the parameters
* @param {String} params.url the frontend URL
* @param {String} params.webRoot the path to the web root
* @param {String} params.webDistDev the path to the web dist-dev folder
*/
function createChromeLaunchConfiguration (params) {
const { url, webRoot, webDistDev } = params
return {
...createLaunchConfiguration({ type: 'chrome', name: 'Web', request: 'launch' }),
url,
webRoot,
breakOnLoad: true,
sourceMapPathOverrides: {
'*': path.join(webDistDev, '*')
}
}
}

/**
* Create a VS Code launch compound.
*
* @param {Object} params the parameters
* @param {String} params.packageName the Openwhisk package name
* @param {String} params.actionName the Openwhisk action name
* @param {String} params.actionFileRelativePath the relative path to the action file
* @param {String} params.envFileRelativePath the relative path to the env file
* @param {String} params.remoteRoot the remote root path
*/
function createPwaNodeLaunchConfiguration (params) {
const { packageName, actionName, actionFileRelativePath, envFileRelativePath, remoteRoot } = params
const configurationName = `Action:${packageName}/${actionName}`

return {
...createLaunchConfiguration({ type: 'pwa-node', name: configurationName, request: 'launch' }),
runtimeExecutable: '${workspaceFolder}/node_modules/.bin/wskdebug', // eslint-disable-line no-template-curly-in-string
envFile: `\${workspaceFolder}/${envFileRelativePath}`,
timeout: 30000,
localRoot: '${workspaceFolder}', // eslint-disable-line no-template-curly-in-string
remoteRoot,
outputCapture: 'std',
attachSimplePort: 0,
runtimeArgs: [
`${packageName}/${actionName}`,
`\${workspaceFolder}/${actionFileRelativePath}`,
'-v'
]
}
}

/**
* Create a VS Code configuration.
*
* @param {Object} params the parameters
* @param {Array<Object>} params.configurations an array of VS Code launch configurations
* @param {Array<Object>} params.compunds an array of VS Code launch compounds
*/
function createVsCodeConfiguration (params = {}) {
const { configurations = [], compounds = [] } = params
return {
configurations,
compounds
}
}

module.exports = {
createVsCodeConfiguration,
createLaunchCompound,
createChromeLaunchConfiguration,
createPwaNodeLaunchConfiguration
}
209 changes: 209 additions & 0 deletions generators/add-vscode-config/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/*
Copyright 2021 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 Generator = require('yeoman-generator')
const path = require('path')
const fs = require('fs-extra')
const { absApp, objGetValue } = require('./utils')

const {
createVsCodeConfiguration,
createLaunchCompound,
createChromeLaunchConfiguration,
createPwaNodeLaunchConfiguration
} = require('./VsCodeConfiguration')

/*
'initializing',
'prompting',
'configuring',
'default',
'writing',
'conflicts',
'install',
'end'
*/

const Default = {
DESTINATION_FILE: '.vscode/launch.json',
REMOTE_ROOT: '/code'
}

const Option = {
DESTINATION_FILE: 'destination-file',
FRONTEND_URL: 'frontend-url',
REMOTE_ROOT: 'remote-root',
APP_CONFIG: 'app-config'
}

class AddVsCodeConfig extends Generator {
constructor (args, opts) {
super(args, opts)

// options are inputs from CLI or yeoman parent generator
this.option(Option.APP_CONFIG, { type: Object })
this.option(Option.FRONTEND_URL, { type: String })
this.option(Option.REMOTE_ROOT, { type: String, default: Default.REMOTE_ROOT })
this.option(Option.DESTINATION_FILE, { type: String, default: Default.DESTINATION_FILE })
}

verifyConfig () {
const appConfig = this.options[Option.APP_CONFIG]
const verifyKeys = [
'app.hasFrontend',
'app.hasBackend',
'ow.package',
'ow.apihost',
'manifest.package.actions',
'web.src',
'web.distDev',
'root',
'envFile'
]

const missingKeys = []
verifyKeys.forEach(key => {
if (objGetValue(appConfig, key) === undefined) {
missingKeys.push(key)
}
})

if (missingKeys.length > 0) {
throw new Error(`App config missing keys: ${missingKeys.join(', ')}`)
}
}

_getActionEntryFile (pkgJson) {
const pkgJsonContent = fs.readJsonSync(pkgJson)
if (pkgJsonContent.main) {
return pkgJsonContent.main
}
return 'index.js'
}

_processRuntimeArgsForActionEntryFile (action, runtimeArgs) {
const appConfig = this.options[Option.APP_CONFIG]
const actionPath = absApp(appConfig.root, action.function)

const actionFileStats = fs.lstatSync(actionPath)
if (actionFileStats.isDirectory()) {
// take package.json main or 'index.js'
const zipMain = this._getActionEntryFile(path.join(actionPath, 'package.json'))
return path.join(actionPath, zipMain)
}

return runtimeArgs
}

_processForBackend () {
const appConfig = this.options[Option.APP_CONFIG]
const nodeVersion = this.options[Option.NODE_VERSION]
const remoteRoot = this.options[Option.REMOTE_ROOT]

const packageName = appConfig.ow.package
const manifestActions = appConfig.manifest.package.actions

Object.keys(manifestActions).map(actionName => {
const action = manifestActions[actionName]

const launchConfig = createPwaNodeLaunchConfiguration({
packageName,
actionName,
actionFileRelativePath: action.function,
envFileRelativePath: appConfig.envFile,
remoteRoot,
nodeVersion
})

launchConfig.runtimeArgs = this._processRuntimeArgsForActionEntryFile(action, launchConfig.runtimeArgs)

if (
action.annotations &&
action.annotations['require-adobe-auth'] &&
appConfig.ow.apihost === 'https://adobeioruntime.net'
) {
// NOTE: The require-adobe-auth annotation is a feature implemented in the
// runtime plugin. The current implementation replaces the action by a sequence
// and renames the action to __secured_<action>. The annotation will soon be
// natively supported in Adobe I/O Runtime, at which point this condition won't
// be needed anymore.
/* instanbul ignore next */
launchConfig.runtimeArgs[0] = `${packageName}/__secured_${actionName}`
}

if (action.runtime) {
launchConfig.runtimeArgs.push('--kind')
launchConfig.runtimeArgs.push(action.runtime)
}

this.vsCodeConfig.configurations.push(launchConfig)
})

this.vsCodeConfig.compounds.push({
name: 'Actions',
configurations: this.vsCodeConfig.configurations.map(config => config.name)
})
}

_processForFrontend () {
const appConfig = this.options[Option.APP_CONFIG]
const frontEndUrl = this.options[Option.FRONTEND_URL]

if (!frontEndUrl) {
throw new Error(`Missing option for generator: ${Option.FRONTEND_URL}`)
}

const webConfig = createChromeLaunchConfiguration({
url: frontEndUrl,
webRoot: appConfig.web.src,
webDistDev: appConfig.web.distDev
})

this.vsCodeConfig.configurations.push(webConfig)

this.vsCodeConfig.compounds.push(createLaunchCompound({
name: 'WebAndActions',
configurations: this.vsCodeConfig.configurations.map(config => config.name)
}))
}

initializing () {
this.verifyConfig()
this.vsCodeConfig = createVsCodeConfiguration()

const appConfig = this.options[Option.APP_CONFIG]

if (appConfig.app.hasBackend) {
this._processForBackend()
}

if (appConfig.app.hasFrontend) {
this._processForFrontend()
}
}

writing () {
const appConfig = this.options[Option.APP_CONFIG]
const destFile = this.options[Option.DESTINATION_FILE]

this.fs.writeJSON(this.destinationPath(destFile), this.vsCodeConfig)

this.sourceRoot(path.join(__dirname, './templates/'))

this.fs.copyTpl(
this.templatePath('env.local'),
this.destinationPath(appConfig.envFile),
{}
)
}
}

module.exports = AddVsCodeConfig
4 changes: 4 additions & 0 deletions generators/add-vscode-config/templates/env.local
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# these are the default secrets for a standalone openwhisk jar and is *not* secret
OW_NAMESPACE=guest
OW_AUTH=23bc46b1-71f6-4ed5-8c54-816aa4f8c502:123zO3xZCLrMN6v2BKK1dXYFpXlPkccOFqm12CdAsMgRU4VrNZ9lyGVCGuMDGIwP
OW_APIHOST=http://localhost:3233
31 changes: 31 additions & 0 deletions generators/add-vscode-config/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
Copyright 2021 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 path = require('path')

function absApp (root, p) {
if (path.isAbsolute(p)) return p
return path.join(root, path.normalize(p))
}

function objGetProp (obj, key) {
return obj[Object.keys(obj).find(k => k.toLowerCase() === key.toLowerCase())]
}

function objGetValue (obj, key) {
const keys = (key || '').toString().split('.')
return keys.filter(o => o.trim()).reduce((o, i) => o && objGetProp(o, i), obj)
}

module.exports = {
absApp,
objGetValue
}
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
"description": "Adobe I/O application yeoman code generator",
"main": "generators/app/index.js",
"scripts": {
"test": "eslint . && jest -c ./jest.config.js",
"unit-test": "jest -c ./jest.config.js"
"lint": "eslint .",
"test": "npm run lint && npm run unit-tests",
"unit-tests": "jest -c ./jest.config.js"
},
"repository": {
"type": "git",
Expand Down
Loading