From 9cecbcafa187e3c02300c938869aa6dd1f4f0d0f Mon Sep 17 00:00:00 2001 From: CeciliaAvila Date: Thu, 9 Dec 2021 12:18:09 -0300 Subject: [PATCH] Add generators-botbuilder + Echo bot template --- generators/generator-botbuilder/LICENSE.md | 21 + generators/generator-botbuilder/README.md | 289 +++++++++++++ .../components/commonFilesWriter.js | 115 ++++++ .../components/constants.js | 23 ++ .../components/coreTemplateWriter.js | 379 ++++++++++++++++++ .../components/echoTemplateWriter.js | 94 +++++ .../components/emptyTemplateWriter.js | 94 +++++ .../components/prompts.js | 204 ++++++++++ .../generators/app/index.js | 192 +++++++++ .../app/templates/echo/README.md.js | 61 +++ .../app/templates/echo/README.md.ts | 67 ++++ .../generators/app/templates/echo/_env | 4 + .../app/templates/echo/_eslintrc.js | 15 + .../generators/app/templates/echo/_gitignore | 3 + .../generators/app/templates/echo/bot.js | 31 ++ .../generators/app/templates/echo/bot.ts | 29 ++ .../echo/deploymentScripts/webConfigPrep.js | 21 + .../new-rg-parameters.json | 54 +++ .../preexisting-rg-parameters.json | 51 +++ .../template-with-new-rg.json | 258 ++++++++++++ .../template-with-preexisting-rg.json | 229 +++++++++++ .../generators/app/templates/echo/index.js | 88 ++++ .../generators/app/templates/echo/index.ts | 90 +++++ .../app/templates/echo/package.json.js | 32 ++ .../app/templates/echo/package.json.ts | 32 ++ .../app/templates/echo/tsconfig.json | 12 + .../generators/app/templates/echo/tslint.json | 18 + generators/generator-botbuilder/package.json | 32 ++ generators/generator-botbuilder/testGen.cmd | 162 ++++++++ 29 files changed, 2700 insertions(+) create mode 100644 generators/generator-botbuilder/LICENSE.md create mode 100644 generators/generator-botbuilder/README.md create mode 100644 generators/generator-botbuilder/components/commonFilesWriter.js create mode 100644 generators/generator-botbuilder/components/constants.js create mode 100644 generators/generator-botbuilder/components/coreTemplateWriter.js create mode 100644 generators/generator-botbuilder/components/echoTemplateWriter.js create mode 100644 generators/generator-botbuilder/components/emptyTemplateWriter.js create mode 100644 generators/generator-botbuilder/components/prompts.js create mode 100644 generators/generator-botbuilder/generators/app/index.js create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/README.md.js create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/README.md.ts create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/_env create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/_eslintrc.js create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/_gitignore create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/bot.js create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/bot.ts create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/deploymentScripts/webConfigPrep.js create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/new-rg-parameters.json create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/preexisting-rg-parameters.json create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-new-rg.json create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-preexisting-rg.json create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/index.js create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/index.ts create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/package.json.js create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/package.json.ts create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/tsconfig.json create mode 100644 generators/generator-botbuilder/generators/app/templates/echo/tslint.json create mode 100644 generators/generator-botbuilder/package.json create mode 100644 generators/generator-botbuilder/testGen.cmd diff --git a/generators/generator-botbuilder/LICENSE.md b/generators/generator-botbuilder/LICENSE.md new file mode 100644 index 0000000000..506ab97e56 --- /dev/null +++ b/generators/generator-botbuilder/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/generators/generator-botbuilder/README.md b/generators/generator-botbuilder/README.md new file mode 100644 index 0000000000..eb6e9700ee --- /dev/null +++ b/generators/generator-botbuilder/README.md @@ -0,0 +1,289 @@ +# generator-botbuilder + +Yeoman generator for [Bot Framework v4](https://dev.botframework.com). Will let you quickly set up a conversational AI bot +using core AI capabilities. + +## About + +`generator-botbuilder` will help you build new conversational AI bots using the [Bot Framework v4](https://dev.botframework.com). + +## Templates + +The generator supports three different template options. The table below can help guide which template is right for you. + +| Template | Description | +| ---------- | --------- | +| Echo Bot | A good template if you want a little more than "Hello World!", but not much more. This template handles the very basics of sending messages to a bot, and having the bot process the messages by repeating them back to the user. This template produces a bot that simply "echoes" back to the user anything the user says to the bot. | +| Core Bot | Our most advanced template, the Core template provides 6 core features every bot is likely to have. This template covers the core features of a Conversational-AI bot using [LUIS](https://www.luis.ai). See the **Core Bot Features** table below for more details. | +| Empty Bot | A good template if you are familiar with Bot Framework v4, and simply want a basic skeleton project. Also a good option if you want to take sample code from the documentation and paste it into a minimal bot in order to learn. | + +### How to Choose a Template + +| Template | When This Template is a Good Choice | +| -------- | -------- | +| Echo Bot | You are new to Bot Framework v4 and want a working bot with minimal features. | +| Core Bot | You understand some of the core concepts of Bot Framework v4 and are beyond the concepts introduced in the Echo Bot template. You're familiar with or are ready to learn concepts such as language understanding using LUIS, managing multi-turn conversations with Dialogs, handling user initiated Dialog interruptions, and using Adaptive Cards to welcome your users. | +| Empty Bot | You are a seasoned Bot Framework v4 developer. You've built bots before, and want the minimum skeleton of a bot. | + +### Template Overview + +#### Echo Bot Template + +The Echo Bot template is slightly more than the a classic "Hello World!" example, but not by much. This template shows the basic structure of a bot, how a bot recieves messages from a user, and how a bot sends messages to a user. The bot will "echo" back to the user, what the user says to the bot. It is a good choice for first time, new to Bot Framework v4 developers. + +#### Core Bot Template + +The Core Bot template consists of set of core features most every bot is likely to have. Building off of the core message processing features found in the Echo Bot template, this template adds a number of more sophisticated features. The table below lists these features and provides links to additional documentation. + +| Core Bot Features | Description | +| ------------------ | ----------- | +| [Send and receive messages](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-send-messages?view=azure-bot-service-4.0&tabs=javascript) | The primary way your bot will communicate with users, and likewise receive communication, is through message activities. Some messages may simply consist of plain text, while others may contain richer content such as cards or attachments. | +| [Proactive messaging](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-proactive-message?view=azure-bot-service-4.0) using [Adaptive Cards](https://docs.microsoft.com/azure/bot-service/bot-builder-send-welcome-message?view=azure-bot-service-4.0?#using-adaptive-card-greeting) | The primary goal when creating any bot is to engage your user in a meaningful conversation. One of the best ways to achieve this goal is to ensure that from the moment a user first connects to your bot, they understand your bot’s main purpose and capabilities. We refer to this as "welcoming the user." The Core template uses an [Adaptive Card](http://adaptivecards.io) to implement this behavior. | +| [Language understanding using LUIS](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0) | The ability to understand what your user means conversationally and contextually can be a difficult task, but can provide your bot a more natural conversation feel. Language Understanding, called LUIS, enables you to do just that so that your bot can recognize the intent of user messages, allow for more natural language from your user, and better direct the conversation flow. | +| [Multi-turn conversation support using Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0) | The ability to manage conversations is an important part of the bot/user interation. Bot Framework introduces the concept of a Dialog to handle this conversational pattern. Dialog objects process inbound Activities and generate outbound responses. The business logic of the bot runs either directly or indirectly within Dialog classes. | +| [Managing conversation state](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-v4-state?view=azure-bot-service-4.0) | A key to good bot design is to track the context of a conversation, so that your bot remembers things like the answers to previous questions. | +| [How to handle user-initiated interruptions](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-handle-user-interrupt?view=azure-bot-service-4.0) | While you may think that your users will follow your defined conversation flow step by step, chances are good that they will change their minds or ask a question in the middle of the process instead of answering the question. Handling interruptions means making sure your bot is prepared to handle situations like this. | +| [How to unit test a bot](https://aka.ms/cs-unit-test-docs) | Optionally, the Core Bot template can generate corresponding unit tests that shows how to use the testing framework introduced in Bot Framework version 4.5. Selecting this option provides a complete set of units tests for Core Bot. It shows how to write unit tests to test the various features of Core Bot. To add the Core Bot unit tests, run the generator and answer `yes` when prompted. See below for an example of how to do this from the command line. | + +#### Empty Bot Template + +The Empty Bot template is the minimal skeleton code for a bot. It provides a stub `onTurn` handler but does not perform any actions. If you are experienced writing bots with Bot Framework v4 and want the minimum scaffolding, the Empty template is for you. + +## Features by Template + +| Feature | Empty Bot | Echo Bot | Core Bot | +| --------- | :-----: | :-----: | :-----: | +| Generate code in JavaScript or TypesScript | X | X | X | +| Support local development and testing using the [Bot Framework Emulator v4](https://www.github.com/microsoft/botframework-emulator) | X | X | X | +| Core bot message processing | | X | X | +| Deploy your bot to Microsoft Azure | | X | X | +| Welcome new users using Adaptive Card technology | | | X | +| Support AI-based greetings using [LUIS](https://www.luis.ai) | | | X | +| Use Dialogs to manage more in-depth conversations | | | X | +| Manage conversation state | | | X | +| Handle user interruptions | | | X | +| Unit test a bot using Bot Framework Testing framework (optional) | | | X | + +## Installation + +1. Install [Yeoman](http://yeoman.io) using [npm](https://www.npmjs.com) (we assume you have pre-installed [node.js](https://nodejs.org/)). + + ```bash + # Make sure both are installed globally + npm install -g yo + ``` + +2. Install generator-botbuilder by typing the following in your console: + + ```bash + # Make sure both are installed globally + npm install -g generator-botbuilder + ``` + +3. Verify that Yeoman and generator-botbuilder have been installed correctly by typing the following into your console: + + ```bash + yo botbuilder --help + ``` + + +## Usage + +### Creating a New Bot Project + +When the generator is launched, it will prompt for the information required to create a new bot. + +```bash +# Run the generator in interactive mode +yo botbuilder +``` + +### Generator Command Line Options + +The generator supports a number of command line options that can be used to change the generator's default options or to pre-seed a prompt. + +| Command line Option | Description | +| ------------------- | ----------- | +| --help, -h | List help text for all supported command-line options | +| --botname, -N | The name given to the bot project | +| --description, -D | A brief bit of text that describes the purpose of the bot | +| --language, -L | The programming language for the project. Options are `JavaScript` or `TypeScript`. | +| --template, -T | The template used to generate the project. Options are `empty`, `echo`, or `core`. See [https://aka.ms/botbuilder-generator](https://aka.ms/botbuilder-generator) for additional information regarding the different template option and their functional differences. | +| --addtests | _A Core Bot Template Only Feature_. The generator will add unit tests to the Core Bot generated bot. This option is not available to other templates at this time. To learn more about the test framework released with Bot Framework v4.5, see [How to unit test bots](https://aka.ms/js-unit-test-docs). This option is intended to enable automated bot generation for testing purposes. | +| --noprompt | The generator will not prompt for confirmation before creating a new bot. Any requirement options not passed on the command line will use a reasonable default value. This option is intended to enable automated bot generation for testing purposes. | + +#### Example Using Command Line Options + +This example shows how to pass command line options to the generator, setting the default language to TypeScript and the default template to Core. + +```bash +# Run the generator defaulting the language to TypeScript and the template to core +yo botbuilder --L "TypeScript" --T "core" +``` + +### Generating a Bot Using --noprompt + +The generator can be run in `--noprompt` mode, which can be used for automated bot creation. When run in `--noprompt` mode, the generator can be configured using command line options as documented above. If a command line option is ommitted a reasonable default will be used. In addition, passing the `--noprompt` option will cause the generator to create a new bot project without prompting for confirmation before generating the bot. + +#### Default Options + +| Command line Option | Default Value | +| ------------------- | ----------- | +| --botname, -N | `my-chat-bot` | +| --description, -D | "Demonstrate the core capabilities of the Microsoft Bot Framework" | +| --language, -L | `JavaScript` | +| --template, -T | `echo` | +| --addtests | When specified, will cause the Core Bot template to add unit tests. | + +#### Examples Using --noprompt + +This example shows how to run the generator in --noprompt mode, setting all required options on the command line. + +```bash +# Run the generator, setting all command line options +yo botbuilder --noprompt -N "my-first-bot" -D "A bot that demonstrates core AI capabilities" -L "JavaScript" -T "Echo" +``` + +This example shows how to run the generator in --noprompt mode, using all the default command line options. The generator will create a bot project using all the default values specified in the **Default Options** table above. + +```bash +# Run the generator using all default options +yo botbuilder --noprompt +``` + +This example shows how to run the generator in --noprompt mode, generating a TypeScript Core Bot with unit tests. + +```bash +# Run the generator using all default options +yo botbuilder -N "my-core-bot-with-tests" -D "A core bot with tests in TypeScript" -L "TypeScript" -T "core" --addtests --noprompt +``` + +## Running Your Bot + +### Running Your Bot Locally + +To run your bot locally, type the following in your console: + +```bash +# install modules +npm install +``` + +```bash +# run the bot +npm start +``` + +### Interacting With Your Bot Using the Emulator + +- Launch Bot Framework Emulator +- File -> Open Bot +- Enter a Bot URL of `http://localhost:3978/api/messages` + +Once the Emulator is connected, you can interact with and receive messages from your bot. + +### Developing Your Bot Locally + +It's often easier to develop the capabilities of your bot locally, and to use the Microsoft Bot Framework Emulator to test your changes. When the generator generated your bot project it added a file watcher to the project. When run, the watcher which will cause nodejs to reload the bot whenever any of the bot's source files change. Causing nodejs to reload your bot under these circumstances will ensure you are always running the latest version of your bot. Enable the watch feature by typing the following in your console: + +```bash +# From the directory that contains your bot +npm run watch +``` + +When you run the `watch` task, nodejs will reload your bot anytime a file in your project changes. When using the Emulator to interact with +your bot, you will need to click the Emulator's 'Start Over' tab in order to force the Emulator to also reload the latest version of your bot. + +#### Lint Compliant Code + +The code generated by the botbuilder generator is lint compliant. Depending on whether the bot was generated using JavaScript or TypeScript, there is either a `.eslint` or `.tslint` file that contains the linting rules used to lint the generated code. To use lint as your develop your bot: + +```bash +npm run lint +``` + +#### Testing Core Bots with Tests + +Core Bot templates generated with unit tests can be tested using the following: + +```bash +# launch mocha, run unit tests, report code coverage +npm test +``` + +## Deploy Your Bot to Azure + +After creating the bot and testing it locally, you can deploy it to Azure to make it accessible from anywhere. +To learn how, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete set of deployment instructions. + +If you are new to Microsoft Azure, please refer to [Getting started with Azure](https://azure.microsoft.com/get-started/) for guidance on how to get started on Azure. + +## Optionally Using Development Builds + +Development builds are based off of "work in progress" code. This means they may or may not be stable and may have incomplete documentation. These builds are better suited for more experienced users and developers, although everyone is welcome to give them a shot and provide feedback. + +You can get the latest development builds of `generator-botbuilder` from the [BotBuilder MyGet](https://botbuilder.myget.org/gallery) feed. To install the latest development build, follow the following steps: + +```bash +# configure npm to pull from the developer builds registry +npm config set registry https://botbuilder.myget.org/F/aitemplates/npm/ +``` + +```bash +# installing using npm +npm install -g generator-botbuilder +``` + +```bash +# reset npm to use the public registry +npm config set registry https://registry.npmjs.org +``` + +Now when `yo botbuilder` is run, it will use the development build. To remove the development build, run the following: + +```bash +# installing using npm +npm uninstall -g generator-botbuilder +``` + +## Creating a Local Development Environment + +To work on the template, evolve it, fix bugs in it, you need to create a local development environment. This setup process entails clone the repository, installing dependencies and creating a symlink that allows the local generated to be run by Yeoman. Here are the steps to create and use a local development environment for development: + +```bash +# clone the repository +git clone https://github.com/microsoft/BotBuilder-JS.git +``` + +```bash +# change into the generator-botbuilder folder +cd BotBuilder-JS/generators/generator-botbuilder +``` + +```bash +# install the generators npm dependencies +npm install +``` + +```bash +# create a symlink to your local package folder +npm link +``` + +At this point you have everything setup to make changes to the sources. The steps that follow show how to run the changed generator using Yeoman, and when you're finished, deleting the symlink. + +```bash +# run the local copy of the generator +yo botbuilder +``` + +```bash +# delete the symlink to your local package folder +npm unlink +``` + + + +## Logging Issues and Providing Feedback + +Issues and feedback about the botbuilder generator can be submitted through the project's [GitHub Issues](https://github.com/Microsoft/botbuilder-js/issues) page. diff --git a/generators/generator-botbuilder/components/commonFilesWriter.js b/generators/generator-botbuilder/components/commonFilesWriter.js new file mode 100644 index 0000000000..9f250438d5 --- /dev/null +++ b/generators/generator-botbuilder/components/commonFilesWriter.js @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const path = require('path'); +const _ = require('lodash'); +const mkdirp = require('mkdirp'); + +const pkg = require('../package.json'); + +/** + * Create the folder for the generated bot code, if it doesn't exist + * + * @param {Generator} generator Yeoman's generator object + * @param {String} directoryName root folder for the generated code + */ +const makeProjectDirectory = (generator, directoryName) => { + generator.log(path.basename(generator.destinationPath())); + generator.log(directoryName); + if (path.basename(generator.destinationPath()) !== directoryName) { + generator.log(`Your bot should be in a directory named ${directoryName}\nI'll automatically create this folder.`); + mkdirp.sync(directoryName); + generator.destinationRoot(generator.destinationPath(directoryName)); + } +} + +/** + * Based on the template, write the files common across the given template options + * + * @param {Generator} generator Yeoman's generator object + * @param {String} templatePath file path to write the generated code + */ +// const writeCommonFiles = (generator, templatePath) => { +module.exports.commonFilesWriter = (generator, templatePath) => { + const extension = _.toLower(generator.templateConfig.language) === 'javascript' ? 'js' : 'ts'; + const npmMain = extension === 'js' ? `index.js` : `./lib/index.js`; + + + // ensure our project directory exists before we start writing files into it + makeProjectDirectory(generator, _.kebabCase(generator.templateConfig.botname)); + + // write the project files common to all templates + // do any text token processing where required + // NOTE: core bot with tests overwrites this file to add a npm test script command + generator.fs.copyTpl( + generator.templatePath(path.join(templatePath, 'package.json.' + extension)), + generator.destinationPath('package.json'), + { + botname: generator.templateConfig.botname, + botDescription: generator.templateConfig.description, + version: pkg.version, + npmMain: npmMain + } + ); + generator.fs.copy( + generator.templatePath(path.join(templatePath, '_gitignore')), + generator.destinationPath('.gitignore') + ); + + // gen a .env file that points to the botfile + generator.fs.copyTpl( + generator.templatePath(path.join(templatePath, '_env')), + generator.destinationPath('.env'), + { + botFileName: generator.templateConfig.botname + } + ); + + // determine what language we are working in, TypeScript or JavaScript + // and write language specific files now + if (extension === 'ts') { + generator.fs.copy( + generator.templatePath(path.join(templatePath, 'tsconfig.json')), + generator.destinationPath('tsconfig.json') + ); + generator.fs.copy( + generator.templatePath(path.join(templatePath, 'tslint.json')), + generator.destinationPath('tslint.json') + ); + srcReadmePath = path.join(templatePath, 'README.md.ts') + } else { + generator.fs.copy( + generator.templatePath(path.join(templatePath, '_eslintrc.js')), + generator.destinationPath('.eslintrc.js') + ); + srcReadmePath = path.join(templatePath, 'README.md.js') + } + + // gen a readme with specifics to what was generated + generator.fs.copyTpl( + generator.templatePath(srcReadmePath), + generator.destinationPath('README.md'), + { + botname: generator.templateConfig.botname, + description: generator.templateConfig.description + } + ); + + // gen the deployment/Templates folder + const deploymentFolder = 'deploymentTemplates'; + const deploymentFiles = [ + 'template-with-new-rg.json', + 'template-with-preexisting-rg.json', + 'new-rg-parameters.json', + 'preexisting-rg-parameters.json', + ]; + mkdirp.sync(deploymentFolder); + const sourcePath = path.join(templatePath, deploymentFolder); + const destinationPath = path.join(generator.destinationPath(), deploymentFolder); + for(let cnt = 0; cnt < deploymentFiles.length; ++cnt) { + generator.fs.copy( + path.join(sourcePath, deploymentFiles[cnt]), + path.join(destinationPath, deploymentFiles[cnt]), + ); + } +} diff --git a/generators/generator-botbuilder/components/constants.js b/generators/generator-botbuilder/components/constants.js new file mode 100644 index 0000000000..2dcbd60847 --- /dev/null +++ b/generators/generator-botbuilder/components/constants.js @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// display names of the template options +module.exports.BOT_TEMPLATE_NAME_EMPTY = 'Empty Bot'; +module.exports.BOT_TEMPLATE_NAME_SIMPLE = 'Echo Bot'; +module.exports.BOT_TEMPLATE_NAME_CORE = 'Core Bot'; + +// aka.ms links to documentation for each template option +module.exports.BOT_HELP_URL_EMPTY = 'https://aka.ms/bot-template-empty'; +module.exports.BOT_HELP_URL_SIMPLE = 'https://aka.ms/bot-template-echo'; +module.exports.BOT_HELP_URL_CORE = 'https://aka.ms/bot-template-core'; + +// --noprompt template values +module.exports.BOT_TEMPLATE_NOPROMPT_EMPTY = 'empty'; +module.exports.BOT_TEMPLATE_NOPROMPT_SIMPLE = 'echo'; +module.exports.BOT_TEMPLATE_NOPROMPT_CORE = 'core'; + +// programming language name options +module.exports.BOT_LANG_NAME_JAVASCRIPT = 'JavaScript'; +module.exports.BOT_LANG_NAME_TYPESCRIPT = 'TypeScript'; + + diff --git a/generators/generator-botbuilder/components/coreTemplateWriter.js b/generators/generator-botbuilder/components/coreTemplateWriter.js new file mode 100644 index 0000000000..32dd19d5bb --- /dev/null +++ b/generators/generator-botbuilder/components/coreTemplateWriter.js @@ -0,0 +1,379 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const _ = require('lodash'); +const mkdirp = require('mkdirp'); +const path = require('path'); + +const { commonFilesWriter } = require('./commonFilesWriter'); +const { BOT_TEMPLATE_NAME_CORE, BOT_TEMPLATE_NOPROMPT_CORE } = require('./constants'); +const pkg = require('../package.json'); + +// generators/app/templates folder name +const GENERATOR_TEMPLATE_NAME = 'core'; + +const LANG_JS = 'javascript'; +const LANG_TS = 'typescript'; + +/** + * + * @param {String} language either 'javascript' or 'typescript' + */ +const _getSourceFolders = language => { + if(!language || (_.toLower(language) !== LANG_JS && _.toLower(language) !== LANG_TS)) { + throw new Error(`coreTemplateWriter._getTargetFolders called for invalid language: ${ language }`); + } + + // get the folder structure, based on language + let folders = [ + 'bots', + 'cognitiveModels', + 'dialogs', + 'resources', + ]; + // if we're generating TypeScript, then we need a deploymentScripts folder + if(_.toLower(language) === LANG_TS) { + folders = folders.concat(['deploymentScripts']); + } + return folders; +} + +/** + * + * @param {String} language either 'javascript' or 'typescript' + */ +const _getTargetFolders = language => { + if(!language || (_.toLower(language) !== LANG_JS && _.toLower(language) !== LANG_TS)) { + throw new Error(`coreTemplateWriter._getTargetFolders called for invalid language: ${ language }`); + } + + let folders; + if(_.toLower(language) === LANG_TS) { + folders = [ + path.join('src', 'bots'), + 'cognitiveModels', + path.join('src', 'dialogs'), + 'resources', + 'deploymentScripts', + ]; + } else { + folders = [ + 'bots', + 'cognitiveModels', + 'dialogs', + 'resources', + ]; + } + return folders; +} + +/** + * + * @param {String} language either 'javascript' or 'typescript' + */ +const _getSourceTestFolders = language => { + const lang = _.toLower(language); + if(!lang || (lang !== LANG_JS && lang !== LANG_TS)) { + throw new Error(`coreTemplateWriter._getTargetFolders called for invalid language: ${ language }`); + } + + // get the folder structure, based on language + const folders = [ + 'tests', + path.join('tests', 'bots'), + path.join('tests', 'dialogs'), + path.join('tests', 'dialogs', 'testData'), + path.join('tests', 'dialogs', 'testData'), + ]; + return folders; +} + +/** + * + * @param {String} language either 'javascript' or 'typescript' + */ +const _getTargetTestFolders = language => { + const lang = _.toLower(language); + if(!lang || (lang !== LANG_JS && lang !== LANG_TS)) { + throw new Error(`coreTemplateWriter._getTargetTestFolders called for invalid language: ${ language }`); + } + + let folders; + if(_.toLower(language) === LANG_TS) { + folders = [ + path.join('src', 'tests'), + path.join('src', 'tests', 'bots'), + path.join('src', 'tests', 'dialogs'), + path.join('src', 'tests', 'dialogs', 'testData'), + 'testResources', + ]; + } else { + folders = [ + 'tests', + path.join('tests', 'bots'), + path.join('tests', 'dialogs'), + path.join('tests', 'dialogs', 'testData'), + path.join('tests', 'dialogs', 'testData'), + ]; + } + return folders; +} + +/** + * Write the files that are specific to the core bot template + * + * @param {Generator} generator Yeoman's generator object + * @param {String} templatePath file path to write the generated code + */ +const writeCoreTemplateTestFiles = (generator, templatePath) => { + // lets validate that we should be called + if(generator.templateConfig.addtests !== true) { + throw new Error(`writeCoreTemplateTestFiles called when 'addtests' flag is false: ${ generator.templateConfig.addtests }`); + } + // declare some constants that map to srcFolder and destFolder array offsets + const TEST_FOLDER = 0; + const BOTS_TEST_FOLDER = 1; + const DIALOGS_TEST_FOLDER = 2; + const DIALOGS_TESTDATA_FOLDER = 3; + const DIALOGS_TESTDATA_JSON_FOLDER = 4; + + // get the folder structure, based on language + const srcFolders = _getSourceTestFolders(_.toLower(generator.templateConfig.language)); + const destFolders = _getTargetTestFolders(_.toLower(generator.templateConfig.language)); + + const extension = _.toLower(generator.templateConfig.language) === 'javascript' ? 'js' : 'ts'; + + // create the core bot tests folder structure + for (let cnt = 0; cnt < destFolders.length; ++cnt) { + mkdirp.sync(destFolders[cnt]); + } + + // overwrite the commonFilesWriter version as we want to version that has + // the npm test script command `npm test' + generator.fs.copyTpl( + generator.templatePath(path.join(templatePath, 'package-with-tests.json.' + extension)), + generator.destinationPath('package.json'), + { + botname: generator.templateConfig.botname, + botDescription: generator.templateConfig.description, + version: pkg.version, + npmMain: (extension === 'js' ? `index.js` : `./lib/index.js`) + } + ); + + + + // write out the test folder's README.md file + let sourcePath = path.join(templatePath, srcFolders[TEST_FOLDER]); + let destinationPath = path.join(generator.destinationPath(), destFolders[TEST_FOLDER]); + generator.fs.copyTpl( + path.join(sourcePath, 'README.md'), + path.join(destinationPath, 'README.md'), + { + botname: generator.templateConfig.botname + } + ); + + // write out the bots test folder + sourcePath = path.join(templatePath, srcFolders[BOTS_TEST_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[BOTS_TEST_FOLDER]); + generator.fs.copy( + path.join(sourcePath, `dialogAndWelcomeBot.test.${extension}`), + path.join(destinationPath, `dialogAndWelcomeBot.test.${extension}`) + ); + + // write out the dialogs test folder + sourcePath = path.join(templatePath, srcFolders[DIALOGS_TEST_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[DIALOGS_TEST_FOLDER]); + generator.fs.copy( + path.join(sourcePath, `bookingDialog.test.${extension}`), + path.join(destinationPath, `bookingDialog.test.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `cancelAndHelpDialog.test.${extension}`), + path.join(destinationPath, `cancelAndHelpDialog.test.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `dateResolverDialog.test.${extension}`), + path.join(destinationPath, `dateResolverDialog.test.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `mainDialog.test.${extension}`), + path.join(destinationPath, `mainDialog.test.${extension}`) + ); + + // write out the dialogs testData folder (treat .json files separately) + sourcePath = path.join(templatePath, srcFolders[DIALOGS_TESTDATA_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[DIALOGS_TESTDATA_FOLDER]); + generator.fs.copy( + path.join(sourcePath, `bookingDialogTestCases.${extension}`), + path.join(destinationPath, `bookingDialogTestCases.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `dateResolverTestCases.${extension}`), + path.join(destinationPath, `dateResolverTestCases.${extension}`) + ); + + // write out the dialogs testData folder (treat .json files separately) + // tsc won't copy these where I want them, so we move them up to a root folder + sourcePath = path.join(templatePath, srcFolders[DIALOGS_TESTDATA_JSON_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[DIALOGS_TESTDATA_JSON_FOLDER]); + generator.fs.copy( + path.join(sourcePath, 'FlightFromCdgToJfk.json'), + path.join(destinationPath, 'FlightFromCdgToJfk.json') + ); + generator.fs.copy( + path.join(sourcePath, 'FlightFromMadridToChicago.json'), + path.join(destinationPath, 'FlightFromMadridToChicago.json') + ); + generator.fs.copy( + path.join(sourcePath, 'FlightFromParisToNewYork.json'), + path.join(destinationPath, 'FlightFromParisToNewYork.json') + ); + generator.fs.copy( + path.join(sourcePath, 'FlightToMadrid.json'), + path.join(destinationPath, 'FlightToMadrid.json') + ); +} + +/** + * Write the files that are specific to the core bot template + * + * @param {Generator} generator Yeoman's generator object + * @param {String} templatePath file path to write the generated code + */ +const writeCoreTemplateFiles = (generator, templatePath) => { + const BOTS_FOLDER = 0; + const COGNITIVE_MODELS_FOLDER = 1; + const DIALOGS_FOLDER = 2; + const RESOURCES_FOLDER = 3; + const DEPLOYMENT_SCRIPTS_FOLDER = 4; + const TS_SRC_FOLDER = 'src'; + + // get the folder structure, based on language + const srcFolders = _getSourceFolders(_.toLower(generator.templateConfig.language), generator.options.addtests); + const destFolders = _getTargetFolders(_.toLower(generator.templateConfig.language), generator.options.addtests); + + const extension = _.toLower(generator.templateConfig.language) === 'javascript' ? 'js' : 'ts'; + const srcFolder = _.toLower(generator.templateConfig.language) === 'javascript' ? '' : TS_SRC_FOLDER; + + // create the core bot folder structure + for (let cnt = 0; cnt < destFolders.length; ++cnt) { + mkdirp.sync(destFolders[cnt]); + } + + // write out the bots folder + let sourcePath = path.join(templatePath, srcFolders[BOTS_FOLDER]); + let destinationPath = path.join(generator.destinationPath(), destFolders[BOTS_FOLDER]); + generator.fs.copy( + path.join(sourcePath, `dialogAndWelcomeBot.${extension}`), + path.join(destinationPath, `dialogAndWelcomeBot.${extension}`), + { + botname: generator.templateConfig.botname + } + ); + generator.fs.copy( + path.join(sourcePath, `dialogBot.${extension}`), + path.join(destinationPath, `dialogBot.${extension}`) + ); + + // write out the LUIS model + sourcePath = path.join(templatePath, srcFolders[COGNITIVE_MODELS_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[COGNITIVE_MODELS_FOLDER]); + generator.fs.copy( + path.join(sourcePath, 'FlightBooking.json'), + path.join(destinationPath, 'FlightBooking.json') + ); + + // if we're writing out TypeScript, then we need to add a webConfigPrep.js + if(_.toLower(generator.templateConfig.language) === LANG_TS) { + sourcePath = path.join(templatePath, srcFolders[DEPLOYMENT_SCRIPTS_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[DEPLOYMENT_SCRIPTS_FOLDER]); + generator.fs.copy( + path.join(sourcePath, 'webConfigPrep.js'), + path.join(destinationPath, 'webConfigPrep.js') + ); + } + + // write out the dialogs folder + sourcePath = path.join(templatePath, srcFolders[DIALOGS_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[DIALOGS_FOLDER]); + if(_.toLower(generator.templateConfig.language) === LANG_TS) { + generator.fs.copy( + path.join(sourcePath, `bookingDetails.${extension}`), + path.join(destinationPath, `bookingDetails.${extension}`) + ); + } + generator.fs.copy( + path.join(sourcePath, `bookingDialog.${extension}`), + path.join(destinationPath, `bookingDialog.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `cancelAndHelpDialog.${extension}`), + path.join(destinationPath, `cancelAndHelpDialog.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `dateResolverDialog.${extension}`), + path.join(destinationPath, `dateResolverDialog.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `flightBookingRecognizer.${extension}`), + path.join(destinationPath, `flightBookingRecognizer.${extension}`) + ); + generator.fs.copy( + path.join(sourcePath, `mainDialog.${extension}`), + path.join(destinationPath, `mainDialog.${extension}`) + ); + + // write out the resources folder + // which contains the welcome adaptive card + sourcePath = path.join(templatePath, srcFolders[RESOURCES_FOLDER]); + destinationPath = path.join(generator.destinationPath(), destFolders[RESOURCES_FOLDER]); + generator.fs.copy( + path.join(sourcePath, 'welcomeCard.json'), + path.join(destinationPath, 'welcomeCard.json') + ); + + // write out the index.js and bot.js + destinationPath = path.join(generator.destinationPath(), srcFolder); + + // gen index and main dialog files + generator.fs.copyTpl( + generator.templatePath(path.join(templatePath, `index.${extension}`)), + path.join(destinationPath, `index.${extension}`), + { + botname: generator.templateConfig.botname + } + ); + + // if asked to write out unit tests, then let's have a go at it + if(generator.options.addtests) { + writeCoreTemplateTestFiles(generator, templatePath); + } +} + +/** + * Write project files for Core template + * + * @param {Generator} generator Yeoman's generator object + */ +module.exports.coreTemplateWriter = generator => { + // do some simple sanity checking to ensure we're being + // called correctly + const template = _.toLower(generator.templateConfig.template) + if (template !== _.toLower(BOT_TEMPLATE_NAME_CORE) && template !== _.toLower(BOT_TEMPLATE_NOPROMPT_CORE)) { + throw new Error(`coreTemplateWriter called for wrong template: ${ generator.templateConfig.template }`); + } + const templatePath = path.join(generator.templatePath(), GENERATOR_TEMPLATE_NAME); + + // write files common to all template options + commonFilesWriter(generator, templatePath); + + // write files specific to the core bot template + writeCoreTemplateFiles(generator, templatePath); + + // write out unit tests if asked to do so + if(generator.templateConfig.addtests === true) { + writeCoreTemplateTestFiles(generator, templatePath); + } +} diff --git a/generators/generator-botbuilder/components/echoTemplateWriter.js b/generators/generator-botbuilder/components/echoTemplateWriter.js new file mode 100644 index 0000000000..fdef3d187e --- /dev/null +++ b/generators/generator-botbuilder/components/echoTemplateWriter.js @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const _ = require('lodash'); +const mkdirp = require('mkdirp'); +const path = require('path'); + +const { commonFilesWriter } = require('./commonFilesWriter'); +const { BOT_TEMPLATE_NAME_SIMPLE, BOT_TEMPLATE_NOPROMPT_SIMPLE } = require('./constants'); + +// generators/app/templates folder name +const GENERATOR_TEMPLATE_NAME = 'echo'; + +const LANG_TS = 'typescript'; + +/** + * Write the files that are specific to the echo bot template + * + * @param {Generator} gen Yeoman's generator object + * @param {String} templatePath file path to write the generated code + */ +const writeEchoTemplateFiles = (generator, templatePath) => { + const DEPLOYMENT_SCRIPTS = 0; + const DEPLOYMENT_MSBOT = 1; + const TS_SRC_FOLDER = 'src' + const folders = [ + 'deploymentScripts', + ]; + const extension = _.toLower(generator.templateConfig.language) === 'javascript' ? 'js' : 'ts'; + const srcFolder = _.toLower(generator.templateConfig.language) === 'javascript' ? '' : TS_SRC_FOLDER; + + // create the echo bot folder structure common to both languages + if (_.toLower(generator.templateConfig.language) === LANG_TS) { + for (let cnt = 0; cnt < folders.length; ++cnt) { + mkdirp.sync(folders[cnt]); + } + } + // create a src directory if we are generating TypeScript + if (_.toLower(generator.templateConfig.language) === LANG_TS) { + mkdirp.sync(TS_SRC_FOLDER); + } + + let sourcePath = path.join(templatePath, folders[DEPLOYMENT_SCRIPTS]); + let destinationPath = path.join(generator.destinationPath(), folders[DEPLOYMENT_SCRIPTS]); + // if we're writing out TypeScript, then we need to add a webConfigPrep.js + if(_.toLower(generator.templateConfig.language) === LANG_TS) { + generator.fs.copy( + path.join(sourcePath, 'webConfigPrep.js'), + path.join(destinationPath, 'webConfigPrep.js') + ); + } + + // write out the index.js and bot.js + destinationPath = path.join(generator.destinationPath(), srcFolder); + + // gen the main index file + generator.fs.copyTpl( + generator.templatePath(path.join(templatePath, `index.${extension}`)), + path.join(destinationPath, `index.${extension}`), + { + botname: generator.templateConfig.botname + } + ); + + // gen the main bot activity router + generator.fs.copy( + generator.templatePath(path.join(templatePath, `bot.${extension}`)), + path.join(destinationPath, `bot.${extension}`) + ); +} + +/** + * Write project files for Echo template + * + * @param {Generator} generator Yeoman's generator object + */ +module.exports.echoTemplateWriter = generator => { + // do some simple sanity checking to ensure we're being + // called correctly + const template = _.toLower(generator.templateConfig.template) + if (template !== _.toLower(BOT_TEMPLATE_NAME_SIMPLE) && template !== _.toLower(BOT_TEMPLATE_NOPROMPT_SIMPLE)) { + throw new Error(`writeEchoProjectFiles called for wrong template: ${ generator.templateConfig.template }`); + } + + // build the path to the echo template source folder + const templatePath = path.join(generator.templatePath(), GENERATOR_TEMPLATE_NAME); + + // write files common to all our template options + commonFilesWriter(generator, templatePath); + + // write files specific to the echo bot template + writeEchoTemplateFiles(generator, templatePath); +} + diff --git a/generators/generator-botbuilder/components/emptyTemplateWriter.js b/generators/generator-botbuilder/components/emptyTemplateWriter.js new file mode 100644 index 0000000000..cec44e1d90 --- /dev/null +++ b/generators/generator-botbuilder/components/emptyTemplateWriter.js @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const path = require('path'); +const _ = require('lodash'); +const mkdirp = require('mkdirp'); + +const { commonFilesWriter } = require('./commonFilesWriter'); +const { BOT_TEMPLATE_NAME_EMPTY, BOT_TEMPLATE_NOPROMPT_EMPTY } = require('./constants'); + +// generators/app/templates folder name +const GENERATOR_TEMPLATE_NAME = 'empty'; + +const LANG_TS = 'typescript'; + +/** + * Write the files that are specific to the empty bot template + * + * @param {Generator} gen Yeoman's generator object + * @param {String} templatePath file path to write the generated code + */ +const writeEmptyTemplateFiles = (generator, templatePath) => { + const DEPLOYMENT_SCRIPTS = 0; + const TS_SRC_FOLDER = 'src' + const folders = [ + 'deploymentScripts', + ]; + const extension = _.toLower(generator.templateConfig.language) === 'javascript' ? 'js' : 'ts'; + const srcFolder = _.toLower(generator.templateConfig.language) === 'javascript' ? '' : TS_SRC_FOLDER; + + // create the empty bot folder structure + if (_.toLower(generator.templateConfig.language) === LANG_TS) { + for (let cnt = 0; cnt < folders.length; ++cnt) { + mkdirp.sync(folders[cnt]); + } + } + // create a src directory if we are generating TypeScript + if (_.toLower(generator.templateConfig.language) === LANG_TS) { + mkdirp.sync(TS_SRC_FOLDER); + } + + let sourcePath = path.join(templatePath, folders[DEPLOYMENT_SCRIPTS]); + let destinationPath = path.join(generator.destinationPath(), folders[DEPLOYMENT_SCRIPTS]); + + // if we're writing out TypeScript, then we need to add a webConfigPrep.js + if(_.toLower(generator.templateConfig.language) === LANG_TS) { + generator.fs.copy( + path.join(sourcePath, 'webConfigPrep.js'), + path.join(destinationPath, 'webConfigPrep.js') + ); + } + + + // write out the index.js and bot.js + destinationPath = path.join(generator.destinationPath(), srcFolder); + + // gen the main index file + generator.fs.copyTpl( + generator.templatePath(path.join(templatePath, `index.${extension}`)), + path.join(destinationPath, `index.${extension}`), + { + botname: generator.templateConfig.botname + } + ); + // gen the main bot activity router + generator.fs.copy( + generator.templatePath(path.join(templatePath, `bot.${extension}`)), + path.join(destinationPath, `bot.${extension}`) + ); +} + +/** + * Write project files for Empty template + * + * @param {Generator} generator Yeoman's generator object + */ +module.exports.emptyTemplateWriter = generator => { + // do some simple sanity checking to ensure we're being + // called correctly + const template = _.toLower(generator.templateConfig.template) + if (template !== _.toLower(BOT_TEMPLATE_NAME_EMPTY) && template !== _.toLower(BOT_TEMPLATE_NOPROMPT_EMPTY)) { + throw new Error(`basicTemplateWriter called for wrong template: ${ generator.templateConfig.template }`); + } + + // build the path to the empty template source folder + const templatePath = path.join(generator.templatePath(), GENERATOR_TEMPLATE_NAME); + + // write files common to all our template options + commonFilesWriter(generator, templatePath); + + // write files specific to the empty bot template + writeEmptyTemplateFiles(generator, templatePath); +} + diff --git a/generators/generator-botbuilder/components/prompts.js b/generators/generator-botbuilder/components/prompts.js new file mode 100644 index 0000000000..5e9bc81769 --- /dev/null +++ b/generators/generator-botbuilder/components/prompts.js @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const _ = require('lodash'); + +const { + BOT_TEMPLATE_NAME_EMPTY, + BOT_TEMPLATE_NAME_SIMPLE, + BOT_TEMPLATE_NAME_CORE, + BOT_TEMPLATE_NOPROMPT_EMPTY, + BOT_TEMPLATE_NOPROMPT_SIMPLE, + BOT_TEMPLATE_NOPROMPT_CORE, + BOT_HELP_URL_EMPTY, + BOT_HELP_URL_SIMPLE, + BOT_HELP_URL_CORE, + BOT_LANG_NAME_JAVASCRIPT, + BOT_LANG_NAME_TYPESCRIPT + } = require('./constants'); + +/** + * configureCommandlineOptions + * does the work to configure the commandline options that this template will accept + * this is mostly made available so that we can run the template without user + * intervention. e.g. automated test runs + * @param {Generator} gen Yeoman's generator object + */ +module.exports.configureCommandlineOptions = gen => { + gen.option('botname', { + desc: 'The name you want to give to your bot', + type: String, + default: 'my-chat-bot', + alias: 'N' + }); + gen.option('description', { + desc: 'A brief bit of text used to describe what your bot does', + type: String, + default: 'Demonstrate the core capabilities of the Microsoft Bot Framework', + alias: 'D' + }); + const langDesc = `The programming language use by the project. (${BOT_LANG_NAME_JAVASCRIPT} | ${BOT_LANG_NAME_TYPESCRIPT})`; + gen.option('language', { + desc: langDesc, + type: String, + default: BOT_LANG_NAME_JAVASCRIPT, + alias: 'L' + }); + + const templateDesc = `The initial bot capabilities. (${BOT_TEMPLATE_NAME_EMPTY} | ${BOT_TEMPLATE_NAME_SIMPLE} | ${BOT_TEMPLATE_NAME_CORE})`; + gen.option('template', { + desc: templateDesc, + type: String, + default: BOT_TEMPLATE_NOPROMPT_SIMPLE, + alias: 'T' + }); + + gen.argument('addtests', { + desc: `Generate unit tests (${BOT_TEMPLATE_NAME_CORE} only).`, + type: Boolean, + required: false, + default: false + }); + + gen.argument('noprompt', { + desc: 'Do not prompt for any information or confirmation', + type: Boolean, + required: false, + default: false + }); +}; + +/** + * getPrompts + * constructs an array of prompts name/value pairs. This is the input we need from the user + * or passed into the command line to successfully configure a new bot + * @param {Object} options + */ +module.exports.getPrompts = (generator) => { + const noprompt = generator.options.noprompt; + const prompts = { + // ask the user to name their bot + askForBotName: () => { + if(noprompt) { + return Promise.resolve(); + } + + return generator.prompt({ + type: 'input', + name: 'botname', + message: `What's the name of your bot?`, + default: (generator.options.botname ? generator.options.botname : 'my-chat-bot') + }).then(answer => { + // store the botname description answer + generator.templateConfig.botname = answer.botname; + }); + }, + + // as the user for a decription of their bot + askForBotDescription: () => { + if(noprompt) { + return Promise.resolve(); + } + + return generator.prompt({ + type: 'input', + name: 'description', + message: 'What will your bot do?', + default: (generator.options.description ? generator.options.description : 'Demonstrate the core capabilities of a Conversational AI bot') + }).then(answer => { + // store the language description answer + generator.templateConfig.description = answer.description; + }); + }, + + // ask the user which programming language they want to use + askForProgrammingLanguage: () => { + if(noprompt) { + return Promise.resolve(); + } + + return generator.prompt({ + type: 'list', + name: 'language', + message: 'What programming language do you want to use?', + choices: [ + { + name: BOT_LANG_NAME_JAVASCRIPT, + value: _.toLower(BOT_LANG_NAME_JAVASCRIPT) + }, + { + name: BOT_LANG_NAME_TYPESCRIPT, + value: _.toLower(BOT_LANG_NAME_TYPESCRIPT) + } + ], + default: (generator.options.language ? _.toLower(generator.options.language) : BOT_LANG_NAME_JAVASCRIPT) + }).then(answer => { + // store the language prompt answer + generator.templateConfig.language = answer.language; + }); +}, + + // ask the user which bot template we should use + askForBotTemplate: () => { + if(noprompt) { + return Promise.resolve(); + } + + return generator.prompt({ + type: 'list', + name: 'template', + message: 'Which template would you like to start with?', + choices: [ + { + name: `${BOT_TEMPLATE_NAME_SIMPLE} - ${BOT_HELP_URL_SIMPLE}`, + value: BOT_TEMPLATE_NOPROMPT_SIMPLE + }, + { + name: `${BOT_TEMPLATE_NAME_CORE} - ${BOT_HELP_URL_CORE}`, + value: BOT_TEMPLATE_NOPROMPT_CORE + }, + { + name: `${BOT_TEMPLATE_NAME_EMPTY} - ${BOT_HELP_URL_EMPTY}`, + value: BOT_TEMPLATE_NOPROMPT_EMPTY + } + ], + default: (generator.options.template ? _.toLower(generator.options.template) : BOT_TEMPLATE_NOPROMPT_SIMPLE) + }).then(answer => { + // store the template prompt answer + generator.templateConfig.template = answer.template; + + if(_.toLower(answer.template) === _.toLower(BOT_TEMPLATE_NOPROMPT_CORE)) { + return generator.prompt({ + type: 'confirm', + name: 'addtests', + message: 'Would you like to add unit tests to test your new bot?', + default: true + }).then(answer => { + // store the addtests prompt answer + generator.templateConfig.addtests = answer.addtests; + }); + } + }); + }, + + // ask the user for final confirmation before we generate their bot + askForFinalConfirmation: () => { + if(noprompt) { + return Promise.resolve(); + } + + return generator.prompt({ + type: 'confirm', + name: 'finalConfirmation', + message: 'Looking good. Shall I go ahead and create your new bot?', + default: true + }).then(answer => { + // store the finalConfirmation prompt answer + generator.templateConfig.finalConfirmation = answer.finalConfirmation; + }); + } + + + }; + return prompts; +}; diff --git a/generators/generator-botbuilder/generators/app/index.js b/generators/generator-botbuilder/generators/app/index.js new file mode 100644 index 0000000000..a661ec740a --- /dev/null +++ b/generators/generator-botbuilder/generators/app/index.js @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const Generator = require('yeoman-generator'); +const _ = require('lodash'); + +const chalk = require('chalk'); + +const pkg = require('../../package.json'); +const prompts = require('../../components/prompts'); +const { coreTemplateWriter } = require('../../components/coreTemplateWriter'); +const { echoTemplateWriter } = require('../../components/echoTemplateWriter'); +const { emptyTemplateWriter } = require('../../components/emptyTemplateWriter'); +const { + BOT_LANG_NAME_JAVASCRIPT, + BOT_LANG_NAME_TYPESCRIPT, + BOT_TEMPLATE_NAME_EMPTY, + BOT_TEMPLATE_NAME_SIMPLE, + BOT_TEMPLATE_NAME_CORE, + BOT_TEMPLATE_NOPROMPT_EMPTY, + BOT_TEMPLATE_NOPROMPT_SIMPLE, + BOT_TEMPLATE_NOPROMPT_CORE + } = require('../../components/constants'); + + +/** + * Main Generator derivative. This is what Yeoman calls to invoke our generator + */ +module.exports = class extends Generator { + constructor(args, opts) { + super(args, opts); + + // allocate an object that we can use to store our user prompt values from our askFor* functions + this.templateConfig = Object.create(null); + + // configure the commandline options + prompts.configureCommandlineOptions(this); + } + + initializing() { + // give the user some data before we start asking them questions + this.log(`\nWelcome to the Microsoft Bot Builder generator v${pkg.version}. `); + this.log('\nDetailed documentation can be found at ' + chalk.underline('https://aka.ms/botbuilder-generator\n')); + } + + prompting() { + const userPrompts = prompts.getPrompts(this); + let result = Promise.resolve(); + + // if we're told to not prompt, then pick what we need and return + if(this.options.noprompt) { + // this function will throw if it encounters errors/invalid options + this._verifyNoPromptOptions(); + } + + // run all prompts in sequence. Results can be ignored. + for(let taskName in userPrompts) { + let prompt = userPrompts[taskName]; + result = result.then(_ => { + return new Promise((s, r) => { + setTimeout(_ => prompt().then(s, r), 0); // set timeout is required, otherwise node hangs + }); + }) + } + return result; + } + + writing() { + // if the user confirmed their settings, then lets go ahead + // an install module dependencies + if(this.templateConfig.finalConfirmation === true) { + // figure out which language we're going to use + const language = _.toLower(this.templateConfig.language); + switch(language) { + case _.toLower(BOT_LANG_NAME_JAVASCRIPT): + case _.toLower(BOT_LANG_NAME_TYPESCRIPT): + this._writeUsingScripting(); + break; + + default: + const errorMsg = `ERROR: Unable to generate a new bot. Invalid programming language: [${language}]`; + this.log(chalk.red(errorMsg)); + throw new Error(errorMsg); + break; + } + } + } + + install() { + // if the user confirmed their settings, then lets go ahead + // an install module dependencies + if(this.templateConfig.finalConfirmation === true) { + this.installDependencies({ bower: false }); + } + } + + end() { + if(this.templateConfig.finalConfirmation === true) { + this.log(chalk.green('------------------------ ')); + this.log(chalk.green(' Your new bot is ready! ')); + this.log(chalk.green('------------------------ ')); + this.log('Open the ' + chalk.green.bold('README.md') + ' to learn how to run your bot. '); + this.log('Thank you for using the Microsoft Bot Framework. '); + this.log('\n< ** > The Bot Framework Team'); + } else { + this.log(chalk.red.bold('-------------------------------- ')); + this.log(chalk.red.bold(' New bot creation was canceled. ')); + this.log(chalk.red.bold('-------------------------------- ')); + this.log('Thank you for using the Microsoft Bot Framework. '); + this.log('\n< ** > The Bot Framework Team'); + } + + } + + // These routines are internal to the implementation and are not + // part of the Yeoman generator required functions + _writeUsingScripting() { + // figure out which scripting language template to write + // the scripting template writers handle whether + // they should write a JavaScript or TypeScript template + const template = _.toLower(this.templateConfig.template); + switch(template) { + case _.toLower(BOT_TEMPLATE_NAME_EMPTY): + case _.toLower(BOT_TEMPLATE_NOPROMPT_EMPTY): + emptyTemplateWriter(this); + break; + + case _.toLower(BOT_TEMPLATE_NAME_SIMPLE): + case _.toLower(BOT_TEMPLATE_NOPROMPT_SIMPLE): + echoTemplateWriter(this); + break; + + case _.toLower(BOT_TEMPLATE_NAME_CORE): + case _.toLower(BOT_TEMPLATE_NOPROMPT_CORE): + coreTemplateWriter(this); + break; + + default: + const errorMsg = `ERROR: Unable to generate a new bot. Invalid template: [${template}]`; + this.log(chalk.red(errorMsg)); + throw new Error(errorMsg); + break; + } + } + + // if we're run with the --noprompt option, verify that + // we were all passed in all required options. + // return true for success, false for failure + _verifyNoPromptOptions() { + this.templateConfig = _.pick(this.options, ['botname', 'description', 'language', 'template', 'addtests']) + + // validate we have what we need, or we'll need to throw + if(!this.templateConfig.botname) { + throw new Error('Must specify a name for your bot when using --noprompt argument. Use --botname or -N'); + } + if(!this.templateConfig.description) { + throw new Error('Must specify a description for your bot when using --noprompt argument. Use --description or -D'); + } + + // make sure we have a supported language + const language = (this.templateConfig.language ? _.toLower(this.templateConfig.language) : undefined); + const langJS = _.toLower(BOT_LANG_NAME_JAVASCRIPT); + const langTS = _.toLower(BOT_LANG_NAME_TYPESCRIPT); + if(!language || (language !== langJS && language !== langTS)) { + throw new Error('Must specify a programming language when using --noprompt argument. Use --language or -L'); + } + + // make sure we have a supported template + const template = (this.templateConfig.template ? _.toLower(this.templateConfig.template) : undefined); + const tmplEmpty = _.toLower(BOT_TEMPLATE_NOPROMPT_EMPTY); + const tmplSimple = _.toLower(BOT_TEMPLATE_NOPROMPT_SIMPLE); + const tmplCore = _.toLower(BOT_TEMPLATE_NOPROMPT_CORE); + if (!template || (template !== tmplEmpty && template !== tmplSimple && template !== tmplCore)) { + throw new Error('Must specify a template when using --noprompt argument. Use --template or -T'); + } + + // let's see if unit tests are requested + if(this.templateConfig.addtests) { + // so they're asking for tests, let's make sure they've specified the corebot template + // or else we have an invalid set of command line arguments. unit tests are only available + // with the corebot template + if(template !== tmplCore) { + throw new Error('Invalid use of --addtests. Can only be specified when using --template "core" or -T "core" '); + } + } else { + this.templateConfig.addtests = false; + } + // when run using --noprompt and we have all the required templateConfig, then set final confirmation to true + // so we can go forward and create the new bot without prompting the user for confirmation + this.templateConfig.finalConfirmation = true; + } +}; diff --git a/generators/generator-botbuilder/generators/app/templates/echo/README.md.js b/generators/generator-botbuilder/generators/app/templates/echo/README.md.js new file mode 100644 index 0000000000..b530bc21c0 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/README.md.js @@ -0,0 +1,61 @@ +# <%= botname %> + +<%= description %> + +This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back. + +## Prerequisites + +- [Node.js](https://nodejs.org) version 10.14.1 or higher + + ```bash + # determine node version + node --version + ``` + +## To run the bot + +- Install modules + + ```bash + npm install + ``` + +- Start the bot + + ```bash + npm start + ``` + +## Testing the bot using Bot Framework Emulator + +[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel. + +- Install the Bot Framework Emulator version 4.9.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases) + +### Connect to the bot using Bot Framework Emulator + +- Launch Bot Framework Emulator +- File -> Open Bot +- Enter a Bot URL of `http://localhost:3978/api/messages` + +## Deploy the bot to Azure + +To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions. + + +## Further reading + +- [Bot Framework Documentation](https://docs.botframework.com) +- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0) +- [Dialogs](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0) +- [Gathering Input Using Prompts](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0) +- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0) +- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0) +- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0) +- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest) +- [Azure Portal](https://portal.azure.com) +- [Language Understanding using LUIS](https://docs.microsoft.com/en-us/azure/cognitive-services/luis/) +- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0) +- [Restify](https://www.npmjs.com/package/restify) +- [dotenv](https://www.npmjs.com/package/dotenv) diff --git a/generators/generator-botbuilder/generators/app/templates/echo/README.md.ts b/generators/generator-botbuilder/generators/app/templates/echo/README.md.ts new file mode 100644 index 0000000000..9f02311ee3 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/README.md.ts @@ -0,0 +1,67 @@ +# <%= botname %> + +<%= description %> + +This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back. + +## Prerequisites + +- [Node.js](https://nodejs.org) version 10.14.1 or higher + + ```bash + # determine node version + node --version + ``` + +## To run the bot + +- Install modules + + ```bash + npm install + ``` +- Start the bot + + ```bash + npm start + ``` + +## Testing the bot using Bot Framework Emulator + +[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel. + +- Install the Bot Framework Emulator version 4.9.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases) + +### Connect to the bot using Bot Framework Emulator + +- Launch Bot Framework Emulator +- File -> Open Bot +- Enter a Bot URL of `http://localhost:3978/api/messages` + +## Deploy the bot to Azure + +### Publishing Changes to Azure Bot Service + + ```bash + # build the TypeScript bot before you publish + npm run build + ``` + +To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions. + +## Further reading + +- [Bot Framework Documentation](https://docs.botframework.com) +- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0) +- [Dialogs](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0) +- [Gathering Input Using Prompts](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0) +- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0) +- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0) +- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0) +- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest) +- [Azure Portal](https://portal.azure.com) +- [Language Understanding using LUIS](https://docs.microsoft.com/en-us/azure/cognitive-services/luis/) +- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0) +- [TypeScript](https://www.typescriptlang.org) +- [Restify](https://www.npmjs.com/package/restify) +- [dotenv](https://www.npmjs.com/package/dotenv) diff --git a/generators/generator-botbuilder/generators/app/templates/echo/_env b/generators/generator-botbuilder/generators/app/templates/echo/_env new file mode 100644 index 0000000000..cdabaa4d21 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/_env @@ -0,0 +1,4 @@ +MicrosoftAppType= +MicrosoftAppId= +MicrosoftAppPassword= +MicrosoftAppTenantId= diff --git a/generators/generator-botbuilder/generators/app/templates/echo/_eslintrc.js b/generators/generator-botbuilder/generators/app/templates/echo/_eslintrc.js new file mode 100644 index 0000000000..8165b29e9a --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/_eslintrc.js @@ -0,0 +1,15 @@ +/* eslint-disable */ +module.exports = { + "extends": "standard", + "rules": { + "semi": [2, "always"], + "indent": [2, 4], + "no-return-await": 0, + "space-before-function-paren": [2, { + "named": "never", + "anonymous": "never", + "asyncArrow": "always" + }], + "template-curly-spacing": [2, "always"] + } +}; \ No newline at end of file diff --git a/generators/generator-botbuilder/generators/app/templates/echo/_gitignore b/generators/generator-botbuilder/generators/app/templates/echo/_gitignore new file mode 100644 index 0000000000..221d37f803 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/_gitignore @@ -0,0 +1,3 @@ +node_modules +lib +.env diff --git a/generators/generator-botbuilder/generators/app/templates/echo/bot.js b/generators/generator-botbuilder/generators/app/templates/echo/bot.js new file mode 100644 index 0000000000..552a9704ce --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/bot.js @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const { ActivityHandler, MessageFactory } = require('botbuilder'); + +class EchoBot extends ActivityHandler { + constructor() { + super(); + // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types. + this.onMessage(async (context, next) => { + const replyText = `Echo: ${ context.activity.text }`; + await context.sendActivity(MessageFactory.text(replyText, replyText)); + // By calling next() you ensure that the next BotHandler is run. + await next(); + }); + + this.onMembersAdded(async (context, next) => { + const membersAdded = context.activity.membersAdded; + const welcomeText = 'Hello and welcome!'; + for (let cnt = 0; cnt < membersAdded.length; ++cnt) { + if (membersAdded[cnt].id !== context.activity.recipient.id) { + await context.sendActivity(MessageFactory.text(welcomeText, welcomeText)); + } + } + // By calling next() you ensure that the next BotHandler is run. + await next(); + }); + } +} + +module.exports.EchoBot = EchoBot; diff --git a/generators/generator-botbuilder/generators/app/templates/echo/bot.ts b/generators/generator-botbuilder/generators/app/templates/echo/bot.ts new file mode 100644 index 0000000000..9973737d69 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/bot.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import { ActivityHandler, MessageFactory } from 'botbuilder'; + +export class EchoBot extends ActivityHandler { + constructor() { + super(); + // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types. + this.onMessage(async (context, next) => { + const replyText = `Echo: ${ context.activity.text }`; + await context.sendActivity(MessageFactory.text(replyText, replyText)); + // By calling next() you ensure that the next BotHandler is run. + await next(); + }); + + this.onMembersAdded(async (context, next) => { + const membersAdded = context.activity.membersAdded; + const welcomeText = 'Hello and welcome!'; + for (const member of membersAdded) { + if (member.id !== context.activity.recipient.id) { + await context.sendActivity(MessageFactory.text(welcomeText, welcomeText)); + } + } + // By calling next() you ensure that the next BotHandler is run. + await next(); + }); + } +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/deploymentScripts/webConfigPrep.js b/generators/generator-botbuilder/generators/app/templates/echo/deploymentScripts/webConfigPrep.js new file mode 100644 index 0000000000..25191ee0f9 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/deploymentScripts/webConfigPrep.js @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// DO NOT MODIFY THIS CODE +// This script is run as part of the Post Deploy step when +// deploying the bot to Azure. It ensures the Azure Web App +// is configured correctly to host a TypeScript authored bot. +const fs = require('fs'); +const path = require('path'); +const replace = require('replace'); +const WEB_CONFIG_FILE = './web.config'; + +if (fs.existsSync(path.resolve(WEB_CONFIG_FILE))) { + replace({ + regex: "url=\"index.js\"", + replacement: "url=\"lib/index.js\"", + paths: ['./web.config'], + recursive: false, + silent: true, + }) +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/new-rg-parameters.json b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/new-rg-parameters.json new file mode 100644 index 0000000000..090ff426d9 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/new-rg-parameters.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupLocation": { + "value": "" + }, + "groupName": { + "value": "" + }, + "appId": { + "value": "" + }, + "appSecret": { + "value": "" + }, + "appType": { + "value": "MultiTenant" + }, + "botId": { + "value": "" + }, + "botSku": { + "value": "" + }, + "newAppServicePlanName": { + "value": "" + }, + "newAppServicePlanSku": { + "value": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + } + }, + "newAppServicePlanLocation": { + "value": "" + }, + "newWebAppName": { + "value": "" + }, + "tenantId": { + "value": "" + }, + "existingUserAssignedMSIName": { + "value": "" + }, + "existingUserAssignedMSIResourceGroupName": { + "value": "" + } + } +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/preexisting-rg-parameters.json b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/preexisting-rg-parameters.json new file mode 100644 index 0000000000..2281a46fdc --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/preexisting-rg-parameters.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "appId": { + "value": "" + }, + "appSecret": { + "value": "" + }, + "appType": { + "value": "MultiTenant" + }, + "botId": { + "value": "" + }, + "botSku": { + "value": "" + }, + "newAppServicePlanName": { + "value": "" + }, + "newAppServicePlanSku": { + "value": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + } + }, + "appServicePlanLocation": { + "value": "" + }, + "existingAppServicePlan": { + "value": "" + }, + "newWebAppName": { + "value": "" + }, + "tenantId": { + "value": "" + }, + "existingUserAssignedMSIName": { + "value": "" + }, + "existingUserAssignedMSIResourceGroupName": { + "value": "" + } + } +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-new-rg.json b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-new-rg.json new file mode 100644 index 0000000000..13ab1c3b82 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-new-rg.json @@ -0,0 +1,258 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupLocation": { + "type": "string", + "metadata": { + "description": "Specifies the location of the Resource Group." + } + }, + "groupName": { + "type": "string", + "metadata": { + "description": "Specifies the name of the Resource Group." + } + }, + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings." + } + }, + "appSecret": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types. Defaults to \"\"." + } + }, + "appType": { + "type": "string", + "defaultValue": "MultiTenant", + "allowedValues": [ + "MultiTenant", + "SingleTenant", + "UserAssignedMSI" + ], + "metadata": { + "description": "Type of Bot Authentication. set as MicrosoftAppType in the Web App's Application Settings. Allowed values are: MultiTenant, SingleTenant, UserAssignedMSI. Defaults to \"MultiTenant\"." + } + }, + "botId": { + "type": "string", + "metadata": { + "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable." + } + }, + "botSku": { + "type": "string", + "metadata": { + "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1." + } + }, + "newAppServicePlanName": { + "type": "string", + "metadata": { + "description": "The name of the App Service Plan." + } + }, + "newAppServicePlanSku": { + "type": "object", + "defaultValue": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "newAppServicePlanLocation": { + "type": "string", + "metadata": { + "description": "The location of the App Service Plan. Defaults to \"westus\"." + } + }, + "newWebAppName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"." + } + }, + "tenantId": { + "type": "string", + "defaultValue": "[subscription().tenantId]", + "metadata": { + "description": "The Azure AD Tenant ID to use as part of the Bot's Authentication. Only used for SingleTenant and UserAssignedMSI app types. Defaults to \"Subscription Tenant ID\"." + } + }, + "existingUserAssignedMSIName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The User-Assigned Managed Identity Resource used for the Bot's Authentication. Defaults to \"\"." + } + }, + "existingUserAssignedMSIResourceGroupName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The User-Assigned Managed Identity Resource Group used for the Bot's Authentication. Defaults to \"\"." + } + } + }, + "variables": { + "appServicePlanName": "[parameters('newAppServicePlanName')]", + "resourcesLocation": "[parameters('newAppServicePlanLocation')]", + "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]", + "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]", + "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]", + "resourceGroupId": "[concat(subscription().id, '/resourceGroups/', parameters('groupName'))]", + "msiResourceId": "[concat(subscription().id, '/resourceGroups/', parameters('existingUserAssignedMSIResourceGroupName'), '/providers/', 'Microsoft.ManagedIdentity/userAssignedIdentities/', parameters('existingUserAssignedMSIName'))]", + "appTypeDef": { + "MultiTenant": { + "tenantId": "", + "msiResourceId": "", + "identity": { "type": "None" } + }, + "SingleTenant": { + "tenantId": "[parameters('tenantId')]", + "msiResourceId": "", + "identity": { "type": "None" } + }, + "UserAssignedMSI": { + "tenantId": "[parameters('tenantId')]", + "msiResourceId": "[variables('msiResourceId')]", + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "[variables('msiResourceId')]": {} + } + } + } + }, + "appType": { + "tenantId": "[variables('appTypeDef')[parameters('appType')].tenantId]", + "msiResourceId": "[variables('appTypeDef')[parameters('appType')].msiResourceId]", + "identity": "[variables('appTypeDef')[parameters('appType')].identity]" + } + }, + "resources": [ + { + "name": "[parameters('groupName')]", + "type": "Microsoft.Resources/resourceGroups", + "apiVersion": "2018-05-01", + "location": "[parameters('groupLocation')]", + "properties": {} + }, + { + "type": "Microsoft.Resources/deployments", + "apiVersion": "2018-05-01", + "name": "storageDeployment", + "resourceGroup": "[parameters('groupName')]", + "dependsOn": [ + "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]" + ], + "properties": { + "mode": "Incremental", + "template": { + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": {}, + "variables": {}, + "resources": [ + { + "comments": "Create a new App Service Plan", + "type": "Microsoft.Web/serverfarms", + "name": "[variables('appServicePlanName')]", + "apiVersion": "2018-02-01", + "location": "[variables('resourcesLocation')]", + "sku": "[parameters('newAppServicePlanSku')]", + "properties": { + "name": "[variables('appServicePlanName')]" + } + }, + { + "comments": "Create a Web App using the new App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2015-08-01", + "location": "[variables('resourcesLocation')]", + "kind": "app", + "dependsOn": [ + "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/serverfarms/', variables('appServicePlanName'))]" + ], + "name": "[variables('webAppName')]", + "identity": "[variables('appType').identity]", + "properties": { + "name": "[variables('webAppName')]", + "serverFarmId": "[variables('appServicePlanName')]", + "siteConfig": { + "appSettings": [ + { + "name": "WEBSITE_NODE_DEFAULT_VERSION", + "value": "10.14.1" + }, + { + "name": "MicrosoftAppType", + "value": "[parameters('appType')]" + }, + { + "name": "MicrosoftAppId", + "value": "[parameters('appId')]" + }, + { + "name": "MicrosoftAppPassword", + "value": "[parameters('appSecret')]" + }, + { + "name": "MicrosoftAppTenantId", + "value": "[variables('appType').tenantId]" + } + ], + "cors": { + "allowedOrigins": [ + "https://botservice.hosting.portal.azure.net", + "https://hosting.onecloud.azure-test.net/" + ] + } + } + } + }, + { + "apiVersion": "2021-03-01", + "type": "Microsoft.BotService/botServices", + "name": "[parameters('botId')]", + "location": "global", + "kind": "azurebot", + "sku": { + "name": "[parameters('botSku')]" + }, + "properties": { + "name": "[parameters('botId')]", + "displayName": "[parameters('botId')]", + "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png", + "endpoint": "[variables('botEndpoint')]", + "msaAppId": "[parameters('appId')]", + "msaAppTenantId": "[variables('appType').tenantId]", + "msaAppMSIResourceId": "[variables('appType').msiResourceId]", + "msaAppType": "[parameters('appType')]", + "luisAppIds": [], + "schemaTransformationVersion": "1.3", + "isCmekEnabled": false, + "isIsolated": false + }, + "dependsOn": [ + "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/sites/', variables('webAppName'))]" + ] + } + ], + "outputs": {} + } + } + } + ] +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-preexisting-rg.json b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-preexisting-rg.json new file mode 100644 index 0000000000..a9581a56e8 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/deploymentTemplates/template-with-preexisting-rg.json @@ -0,0 +1,229 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings." + } + }, + "appSecret": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types. Defaults to \"\"." + } + }, + "appType": { + "type": "string", + "defaultValue": "MultiTenant", + "allowedValues": [ + "MultiTenant", + "SingleTenant", + "UserAssignedMSI" + ], + "metadata": { + "description": "Type of Bot Authentication. set as MicrosoftAppType in the Web App's Application Settings. Allowed values are: MultiTenant, SingleTenant, UserAssignedMSI. Defaults to \"MultiTenant\"." + } + }, + "botId": { + "type": "string", + "metadata": { + "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable." + } + }, + "botSku": { + "defaultValue": "F0", + "type": "string", + "metadata": { + "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1." + } + }, + "newAppServicePlanName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The name of the new App Service Plan." + } + }, + "newAppServicePlanSku": { + "type": "object", + "defaultValue": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "appServicePlanLocation": { + "type": "string", + "metadata": { + "description": "The location of the App Service Plan." + } + }, + "existingAppServicePlan": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Name of the existing App Service Plan used to create the Web App for the bot." + } + }, + "newWebAppName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"." + } + }, + "tenantId": { + "type": "string", + "defaultValue": "[subscription().tenantId]", + "metadata": { + "description": "The Azure AD Tenant ID to use as part of the Bot's Authentication. Only used for SingleTenant and UserAssignedMSI app types. Defaults to \"Subscription Tenant ID\"." + } + }, + "existingUserAssignedMSIName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The User-Assigned Managed Identity Resource used for the Bot's Authentication. Defaults to \"\"." + } + }, + "existingUserAssignedMSIResourceGroupName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The User-Assigned Managed Identity Resource Group used for the Bot's Authentication. Defaults to \"\"." + } + } + }, + "variables": { + "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]", + "useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]", + "servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), parameters('newAppServicePlanName'))]", + "resourcesLocation": "[parameters('appServicePlanLocation')]", + "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]", + "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]", + "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]", + "msiResourceId": "[concat(subscription().id, '/resourceGroups/', parameters('existingUserAssignedMSIResourceGroupName'), '/providers/', 'Microsoft.ManagedIdentity/userAssignedIdentities/', parameters('existingUserAssignedMSIName'))]", + "appTypeDef": { + "MultiTenant": { + "tenantId": "", + "msiResourceId": "", + "identity": { "type": "None" } + }, + "SingleTenant": { + "tenantId": "[parameters('tenantId')]", + "msiResourceId": "", + "identity": { "type": "None" } + }, + "UserAssignedMSI": { + "tenantId": "[parameters('tenantId')]", + "msiResourceId": "[variables('msiResourceId')]", + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "[variables('msiResourceId')]": {} + } + } + } + }, + "appType": { + "tenantId": "[variables('appTypeDef')[parameters('appType')].tenantId]", + "msiResourceId": "[variables('appTypeDef')[parameters('appType')].msiResourceId]", + "identity": "[variables('appTypeDef')[parameters('appType')].identity]" + } + }, + "resources": [ + { + "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.", + "type": "Microsoft.Web/serverfarms", + "condition": "[not(variables('useExistingAppServicePlan'))]", + "name": "[variables('servicePlanName')]", + "apiVersion": "2018-02-01", + "location": "[variables('resourcesLocation')]", + "sku": "[parameters('newAppServicePlanSku')]", + "properties": { + "name": "[variables('servicePlanName')]" + } + }, + { + "comments": "Create a Web App using an App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2015-08-01", + "location": "[variables('resourcesLocation')]", + "kind": "app", + "dependsOn": [ + "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]" + ], + "name": "[variables('webAppName')]", + "identity": "[variables('appType').identity]", + "properties": { + "name": "[variables('webAppName')]", + "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]", + "siteConfig": { + "appSettings": [ + { + "name": "WEBSITE_NODE_DEFAULT_VERSION", + "value": "10.14.1" + }, + { + "name": "MicrosoftAppType", + "value": "[parameters('appType')]" + }, + { + "name": "MicrosoftAppId", + "value": "[parameters('appId')]" + }, + { + "name": "MicrosoftAppPassword", + "value": "[parameters('appSecret')]" + }, + { + "name": "MicrosoftAppTenantId", + "value": "[variables('appType').tenantId]" + } + ], + "cors": { + "allowedOrigins": [ + "https://botservice.hosting.portal.azure.net", + "https://hosting.onecloud.azure-test.net/" + ] + } + } + } + }, + { + "apiVersion": "2021-03-01", + "type": "Microsoft.BotService/botServices", + "name": "[parameters('botId')]", + "location": "global", + "kind": "azurebot", + "sku": { + "name": "[parameters('botSku')]" + }, + "properties": { + "name": "[parameters('botId')]", + "displayName": "[parameters('botId')]", + "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png", + "endpoint": "[variables('botEndpoint')]", + "msaAppId": "[parameters('appId')]", + "msaAppTenantId": "[variables('appType').tenantId]", + "msaAppMSIResourceId": "[variables('appType').msiResourceId]", + "msaAppType": "[parameters('appType')]", + "luisAppIds": [], + "schemaTransformationVersion": "1.3", + "isCmekEnabled": false, + "isIsolated": false + }, + "dependsOn": [ + "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]" + ] + } + ] +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/index.js b/generators/generator-botbuilder/generators/app/templates/echo/index.js new file mode 100644 index 0000000000..caca16ca0a --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/index.js @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const path = require('path'); + +const dotenv = require('dotenv'); +// Import required bot configuration. +const ENV_FILE = path.join(__dirname, '.env'); +dotenv.config({ path: ENV_FILE }); + +const restify = require('restify'); + +// Import required bot services. +// See https://aka.ms/bot-services to learn more about the different parts of a bot. +const { + CloudAdapter, + ConfigurationServiceClientCredentialFactory, + createBotFrameworkAuthenticationFromConfiguration +} = require('botbuilder'); + +// This bot's main dialog. +const { EchoBot } = require('./bot'); + +// Create HTTP server +const server = restify.createServer(); +server.use(restify.plugins.bodyParser()); + +server.listen(process.env.port || process.env.PORT || 3978, () => { + console.log(`\n${ server.name } listening to ${ server.url }`); + console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator'); + console.log('\nTo talk to your bot, open the emulator select "Open Bot"'); +}); + +const credentialsFactory = new ConfigurationServiceClientCredentialFactory({ + MicrosoftAppId: process.env.MicrosoftAppId, + MicrosoftAppPassword: process.env.MicrosoftAppPassword, + MicrosoftAppType: process.env.MicrosoftAppType, + MicrosoftAppTenantId: process.env.MicrosoftAppTenantId +}); + +const botFrameworkAuthentication = createBotFrameworkAuthenticationFromConfiguration(null, credentialsFactory); + +// Create adapter. +// See https://aka.ms/about-bot-adapter to learn more about adapters. +const adapter = new CloudAdapter(botFrameworkAuthentication); + +// Catch-all for errors. +const onTurnErrorHandler = async (context, error) => { + // This check writes out errors to console log .vs. app insights. + // NOTE: In production environment, you should consider logging this to Azure + // application insights. + console.error(`\n [onTurnError] unhandled error: ${ error }`); + + // Send a trace activity, which will be displayed in Bot Framework Emulator + await context.sendTraceActivity( + 'OnTurnError Trace', + `${ error }`, + 'https://www.botframework.com/schemas/error', + 'TurnError' + ); + + // Send a message to the user + await context.sendActivity('The bot encountered an error or bug.'); + await context.sendActivity('To continue to run this bot, please fix the bot source code.'); +}; + +// Set the onTurnError for the singleton CloudAdapter. +adapter.onTurnError = onTurnErrorHandler; + +// Create the main dialog. +const myBot = new EchoBot(); + +// Listen for incoming requests. +server.post('/api/messages', async (req, res) => { + // Route received a request to adapter for processing + await adapter.process(req, res, (context) => myBot.run(context)); +}); + +// Listen for Upgrade requests for Streaming. +server.on('upgrade', async (req, socket, head) => { + // Create an adapter scoped to this WebSocket connection to allow storing session data. + const streamingAdapter = new CloudAdapter(botFrameworkAuthentication); + + // Set onTurnError for the CloudAdapter created for each connection. + streamingAdapter.onTurnError = onTurnErrorHandler; + + await streamingAdapter.process(req, socket, head, (context) => myBot.run(context)); +}); diff --git a/generators/generator-botbuilder/generators/app/templates/echo/index.ts b/generators/generator-botbuilder/generators/app/templates/echo/index.ts new file mode 100644 index 0000000000..c9bd4ca776 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/index.ts @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import * as path from 'path'; + +import { config } from 'dotenv'; +const ENV_FILE = path.join(__dirname, '..', '.env'); +config({ path: ENV_FILE }); + +import * as restify from 'restify'; + +import { INodeSocket } from 'botframework-streaming'; + +// Import required bot services. +// See https://aka.ms/bot-services to learn more about the different parts of a bot. +import { + CloudAdapter, + ConfigurationServiceClientCredentialFactory, + createBotFrameworkAuthenticationFromConfiguration +} from 'botbuilder'; + +// This bot's main dialog. +import { EchoBot } from './bot'; + + +// Create HTTP server. +const server = restify.createServer(); +server.use(restify.plugins.bodyParser()); + +server.listen(process.env.port || process.env.PORT || 3978, () => { + console.log(`\n${server.name} listening to ${server.url}`); + console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator'); + console.log('\nTo talk to your bot, open the emulator select "Open Bot"'); +}); + +const credentialsFactory = new ConfigurationServiceClientCredentialFactory({ + MicrosoftAppId: process.env.MicrosoftAppId, + MicrosoftAppPassword: process.env.MicrosoftAppPassword, + MicrosoftAppType: process.env.MicrosoftAppType, + MicrosoftAppTenantId: process.env.MicrosoftAppTenantId +}); + +const botFrameworkAuthentication = createBotFrameworkAuthenticationFromConfiguration(null, credentialsFactory); + +// Create adapter. +// See https://aka.ms/about-bot-adapter to learn more about adapters. +const adapter = new CloudAdapter(botFrameworkAuthentication); + +// Catch-all for errors. +const onTurnErrorHandler = async (context, error) => { + // This check writes out errors to console log .vs. app insights. + // NOTE: In production environment, you should consider logging this to Azure + // application insights. + console.error(`\n [onTurnError] unhandled error: ${ error }`); + + // Send a trace activity, which will be displayed in Bot Framework Emulator + await context.sendTraceActivity( + 'OnTurnError Trace', + `${ error }`, + 'https://www.botframework.com/schemas/error', + 'TurnError' + ); + + // Send a message to the user + await context.sendActivity('The bot encountered an error or bug.'); + await context.sendActivity('To continue to run this bot, please fix the bot source code.'); +}; + +// Set the onTurnError for the singleton CloudAdapter. +adapter.onTurnError = onTurnErrorHandler; + +// Create the main dialog. +const myBot = new EchoBot(); + +// Listen for incoming requests. +server.post('/api/messages', async (req, res) => { + // Route received a request to adapter for processing + await adapter.process(req, res, (context) => myBot.run(context)); +}); + +// Listen for Upgrade requests for Streaming. +server.on('upgrade', async (req, socket, head) => { + // Create an adapter scoped to this WebSocket connection to allow storing session data. + const streamingAdapter = new CloudAdapter(botFrameworkAuthentication); + + // Set onTurnError for the CloudAdapter created for each connection. + streamingAdapter.onTurnError = onTurnErrorHandler; + + await streamingAdapter.process(req, socket as unknown as INodeSocket, head, (context) => myBot.run(context)); +}); diff --git a/generators/generator-botbuilder/generators/app/templates/echo/package.json.js b/generators/generator-botbuilder/generators/app/templates/echo/package.json.js new file mode 100644 index 0000000000..5b28b67256 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/package.json.js @@ -0,0 +1,32 @@ +{ + "name": "<%= botname %>", + "version": "1.0.0", + "description": "<%= botDescription %>", + "author": "Generated using Microsoft Bot Builder Yeoman generator v<%= version %>", + "license": "MIT", + "main": "<%= npmMain %>", + "scripts": { + "start": "node ./index.js", + "watch": "nodemon ./index.js", + "lint": "eslint .", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com" + }, + "dependencies": { + "botbuilder": "~4.15.0", + "dotenv": "~8.2.0", + "restify": "~8.5.1" + }, + "devDependencies": { + "eslint": "^7.0.0", + "eslint-config-standard": "^14.1.1", + "eslint-plugin-import": "^2.20.2", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^4.2.1", + "eslint-plugin-standard": "^4.0.1", + "nodemon": "^2.0.4" + } +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/package.json.ts b/generators/generator-botbuilder/generators/app/templates/echo/package.json.ts new file mode 100644 index 0000000000..0d87f9400d --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/package.json.ts @@ -0,0 +1,32 @@ +{ + "name": "<%= botname %>", + "version": "1.0.0", + "description": "<%= botDescription %>", + "author": "Generated using Microsoft Bot Builder Yeoman generator v<%= version %>", + "license": "MIT", + "main": "<%= npmMain %>", + "scripts": { + "build": "tsc --build", + "lint": "tslint -c tslint.json 'src/**/*.ts'", + "postinstall": "npm run build && node ./deploymentScripts/webConfigPrep.js", + "start": "tsc --build && node ./lib/index.js", + "test": "echo \"Error: no test specified\" && exit 1", + "watch": "nodemon --watch ./src -e ts --exec \"npm run start\"" + }, + "repository": { + "type": "git", + "url": "https://github.com" + }, + "dependencies": { + "botbuilder": "~4.15.0", + "dotenv": "~8.2.0", + "replace": "~1.2.0", + "restify": "~8.5.1" + }, + "devDependencies": { + "@types/restify": "8.4.2", + "nodemon": "^2.0.4", + "tslint": "^6.1.2", + "typescript": "^3.9.2" + } +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/tsconfig.json b/generators/generator-botbuilder/generators/app/templates/echo/tsconfig.json new file mode 100644 index 0000000000..556cc10836 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es2016", + "module": "commonjs", + "outDir": "./lib", + "rootDir": "./src", + "sourceMap": true, + "incremental": true, + "tsBuildInfoFile": "./lib/.tsbuildinfo" + } +} diff --git a/generators/generator-botbuilder/generators/app/templates/echo/tslint.json b/generators/generator-botbuilder/generators/app/templates/echo/tslint.json new file mode 100644 index 0000000000..ad00715f85 --- /dev/null +++ b/generators/generator-botbuilder/generators/app/templates/echo/tslint.json @@ -0,0 +1,18 @@ +{ + "defaultSeverity": "error", + "extends": [ + "tslint:recommended" + ], + "jsRules": {}, + "rules": { + "interface-name" : [true, "never-prefix"], + "max-line-length": [false], + "no-console": [false, "log", "error"], + "no-var-requires": false, + "quotemark": [true, "single"], + "one-variable-per-declaration": false, + "curly": [true, "ignore-same-line"], + "trailing-comma": [true, {"multiline": "never", "singleline": "never"}] + }, + "rulesDirectory": [] +} diff --git a/generators/generator-botbuilder/package.json b/generators/generator-botbuilder/package.json new file mode 100644 index 0000000000..8d126d189e --- /dev/null +++ b/generators/generator-botbuilder/package.json @@ -0,0 +1,32 @@ +{ + "name": "generator-botbuilder", + "version": "4.11.0", + "description": "A yeoman generator for creating bots built with Bot Framework v4", + "homepage": "https://github.com/Microsoft/BotBuilder-JS/tree/main/generators/generator-botbuilder", + "author": { + "name": "Microsoft", + "email": "botframework@microsoft.com", + "url": "http://dev.botframework.com" + }, + "license": "SEE LICENSE IN LICENSE.md", + "repository": "https://github.com/Microsoft/BotBuilder-JS.git", + "files": [ + "components", + "generators" + ], + "keywords": [ + "botbuilder", + "bots", + "bot framework", + "yeoman-generator", + "Microsoft AI", + "Microsoft Teams", + "Conversational AI" + ], + "dependencies": { + "chalk": "^4.0.0", + "lodash": "^4.17.15", + "mkdirp": "^1.0.4", + "yeoman-generator": "^4.13.0" + } +} diff --git a/generators/generator-botbuilder/testGen.cmd b/generators/generator-botbuilder/testGen.cmd new file mode 100644 index 0000000000..af744cf507 --- /dev/null +++ b/generators/generator-botbuilder/testGen.cmd @@ -0,0 +1,162 @@ +#!/bin/bash + +# +# CLI Argument processing +# +if [ "$1" = help ] +then + echo "" + echo "USAGE: nocleanup or noclean : Do not delete generated bots after they've been created." + echo "" + exit +fi + + +# +# Empty bot in TypeScript +# +echo Generating my-empty-bot-ts +yo botbuilder -N "my-empty-bot-ts" -D "An empty bot in ts" -L "TypeScript" -T "empty" --noprompt +cd ./my-empty-bot-ts +echo building and linting my-empty-bot-ts +npm run build +npm run lint +cd .. + + +# +# Empty bot in JavaScript +# +echo Generating my-empty-bot-js +yo botbuilder -N "my-empty-bot-js" -D "An empty bot in js" -L "JavaScript" -T "empty" --noprompt +cd ./my-empty-bot-js +echo linting my-empty-bot-js +npm run lint +cd .. + + +# +# Echo bot in TypeScript +# +echo Generating my-echo-bot-ts +yo botbuilder -N "my-echo-bot-ts" -D "An echo bot in ts" -L "TypeScript" -T "echo" --noprompt +cd ./my-echo-bot-ts +echo building and linting my-echo-bot-ts +npm run build +npm run lint +cd .. + + +# +# Echo bot in JavaScript +# +echo Generating my-echo-bot-js +yo botbuilder -N "my-echo-bot-js" -D "An echo bot in js" -L "JavaScript" -T "echo" --noprompt +cd ./my-echo-bot-js +echo linting my-echo-bot-js +npm run lint +cd .. + + +# +# Core bot in TypeScript +# +echo Generating my-core-bot-ts +yo botbuilder -N "my-core-bot-ts" -D "A core bot in ts" -L "TypeScript" -T "core" --noprompt +cd ./my-core-bot-ts +echo building and linting my-core-bot-ts +npm run build +npm run lint +cd .. + + +# +# Core bot with tests in TypeScript +# +echo Generating my-core-bot-with-tests-ts +yo botbuilder -N "my-core-bot-with-tests-ts" -D "A core bot with tests in ts" -L "TypeScript" -T "core" --addtests --noprompt +cd ./my-core-bot-with-tests-ts +echo building and linting my-core-bot-with-tests-ts +npm run build +npm run lint +npm test +cd .. + + +# +# Core bot in JavaScript +# +echo Generating my-core-bot-js +yo botbuilder -N "my-core-bot-js" -D "A core bot in js" -L "JavaScript" -T "core" --noprompt +cd ./my-core-bot-js +echo linting my-core-bot-js +npm run lint +cd .. + + +# +# Core bot with tests in JavaScript +# +echo Generating my-core-bot-with-tests-js +yo botbuilder -N "my-core-bot-with-tests-js" -D "A core bot with tests in js" -L "JavaScript" -T "core" --addtests --noprompt +cd ./my-core-bot-with-tests-js +echo linting my-core-bot-with-tests-js +npm run lint +npm test +cd .. + +if [ "$1" = nocleanup ] || [ "$1" = noclean ] +then + echo "*****************************************************************************" + echo "** noclean(up) option used. You must manually clean up all generated bots **" + echo "*****************************************************************************" +else + ## Clean up all the generated projects ## + echo Cleaning up... + + # + # Empty bot in TypeScript + # + rm -rf ./my-empty-bot-ts + + + # + # Empty bot in JavaScript + # + rm -rf ./my-empty-bot-js + + # + # Echo bot in TypeScript + # + rm -rf ./my-echo-bot-ts + + + # + # Echo bot in JavaScript + # + rm -rf ./my-echo-bot-js + + + # + # Core bot in TypeScript + # + rm -rf ./my-core-bot-ts + + + # + # Core bot with tests in TypeScript + # + rm -rf ./my-core-bot-with-tests-ts + + + # + # Core bot in JavaScript + # + rm -rf ./my-core-bot-js + + + # + # Core bot with tests in JavaScript + # + rm -rf ./my-core-bot-with-tests-js +fi