├── .gitignore ├── lessons ├── assets │ ├── adobe.png │ ├── lint.png │ ├── aio_run.png │ ├── action_name.png │ ├── folder_move.png │ ├── init_options.png │ ├── rename_js_ts.png │ ├── actions_generic.png │ └── ts-logo-256.svg ├── welldone.md ├── done.md ├── requirements.md ├── lesson1.md ├── frontend.md ├── conversion.md └── build.md ├── COPYRIGHT ├── head.html ├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── CONTRIBUTING.md ├── index.html ├── manifest.json ├── README.md ├── CODE_OF_CONDUCT.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /.hlx 2 | /logs -------------------------------------------------------------------------------- /lessons/assets/adobe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/adobe.png -------------------------------------------------------------------------------- /lessons/assets/lint.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/lint.png -------------------------------------------------------------------------------- /lessons/assets/aio_run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/aio_run.png -------------------------------------------------------------------------------- /lessons/assets/action_name.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/action_name.png -------------------------------------------------------------------------------- /lessons/assets/folder_move.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/folder_move.png -------------------------------------------------------------------------------- /lessons/assets/init_options.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/init_options.png -------------------------------------------------------------------------------- /lessons/assets/rename_js_ts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/rename_js_ts.png -------------------------------------------------------------------------------- /lessons/assets/actions_generic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdobeDocs/adobeio-codelabs-typescript/master/lessons/assets/actions_generic.png -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | © Copyright 2020 Adobe. All rights reserved. 2 | 3 | Adobe holds the copyright for all the files found in this repository. 4 | 5 | See the LICENSE file for licensing information. 6 | -------------------------------------------------------------------------------- /head.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lessons/welldone.md: -------------------------------------------------------------------------------- 1 | ## Well done 2 | 3 | You have successfully completed the codelab and learnt how to use TypeScript to make your Firefly app easier to develop and debug. 4 | 5 | ### What's next ? 6 | 7 | Check out other useful codelabs for your projects at [Adobe I/O Codelabs website](https://adobedocs.github.io/adobeio-codelabs). -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Expected Behavior 2 | 3 | ### Actual Behavior 4 | 5 | ### Reproduce Scenario (including but not limited to) 6 | 7 | #### Steps to Reproduce 8 | 9 | #### Browser name/version/os (ie Chrome Version 62.0.3202.94 (Official Build) (64-bit) MacOS) 10 | 11 | #### Coral Spectrum version 12 | 13 | #### Sample Code that illustrates the problem (use the Playground if possible) 14 | 15 | #### Screenshots (if applicable) 16 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /lessons/done.md: -------------------------------------------------------------------------------- 1 | ## Well done 2 | 3 | **You've reached the end**. 4 | Now you can leverage TypeScript in your Project Firefly applications. 5 | 6 | ### Achievements 7 | 8 | In this codelab, you have learned the following: 9 | 10 | * Bootstrap a Firefly Headless App with the Firefly CLI 11 | * Convert your project to use TypeScript 12 | 13 | ### What's next ? 14 | 15 | Check out other useful codelabs for your projects at [Adobe I/O Codelabs website](https://adobedocs.github.io/adobeio-codelabs). 16 | 17 | More information about TypeScript can be found at the [TypeScript documentation website](https://www.typescriptlang.org/docs). -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Using TypeScript to develop a Project Firefly app", 3 | "repository": "https://github.com/AdobeDocs/adobeio-codelabs-typescript", 4 | "navigation": [{ 5 | "title": "Introduction", 6 | "url": "/README" 7 | }, { 8 | "title": "Requirements", 9 | "url": "/lessons/requirements" 10 | }, { 11 | "title": "Lesson 1: Bootstrap your app", 12 | "url": "/lessons/lesson1" 13 | }, { 14 | "title": "Lesson 2: Converting application to TypeScript", 15 | "url": "/lessons/conversion" 16 | }, { 17 | "title": "Lesson 3: Tweaking the build to support TypeScript", 18 | "url": "/lessons/build" 19 | }, { 20 | "title": "Lesson 4: Add TypeScript support for web-src", 21 | "url": "/lessons/frontend" 22 | },{ 23 | "title": "Well done", 24 | "url": "/lessons/welldone" 25 | }] 26 | } -------------------------------------------------------------------------------- /lessons/requirements.md: -------------------------------------------------------------------------------- 1 | ## Requirements 2 | 3 | This codelab is useful for both the skilled and begining Project Firefly developers. 4 | 5 | ### Required skills 6 | 7 | * **Required:** programming skills in any language 8 | * *Optional:* basic knowledge of TypeScript 9 | * *Optional:* basic understanding of Node.js based development 10 | 11 | ### Pre-requisites 12 | 13 | If not already done, you should follow the below links to have your environment set up before starting the codelab: 14 | 15 | * [How to Get Access to Project Firefly](https://github.com/AdobeDocs/project-firefly/blob/master/overview/getting_access.md) 16 | * [Setting up Your Environment](https://github.com/AdobeDocs/project-firefly/blob/master/getting_started/setup.md) 17 | * [Creating your First Firefly App](https://github.com/AdobeDocs/project-firefly/blob/master/getting_started/first_app.md) 18 | 19 | * [Install TypeScript](https://www.typescriptlang.org/#installation) Typically done with 20 | ```Shell 21 | npm install -g typescript 22 | ``` 23 | 24 | [Next](lesson1.md) -------------------------------------------------------------------------------- /lessons/lesson1.md: -------------------------------------------------------------------------------- 1 | ## Lesson 1: Bootstrap a new app 2 | 3 | In order to create your barcode application, use the following command: 4 | ```bash 5 | aio app init adobeio-samples-typescript 6 | ``` 7 | We select the org, project and workspace for our app, and then be presented with a few options what you want your app to include (Serverless Actions, Web UI, CI/CD pipeline, I/O Events). Since we are building a headless app, we're only interested in using `Actions: Deploy Runtime actions`. 8 | ![Build Options](assets/init_options.png) 9 | 10 | The second question, the CLI asks us which experience cloud or experience platform apps you want to extend or build. In this case, we're going to choose `Generic`. 11 | ![Generic Actions](assets/actions_generic.png) 12 | 13 | The third question, we'll specify the action name `tsaction`. 14 | ![Action name](assets/action_name.png) 15 | 16 | We didn't include the UI setup nor the CI/CD pipeline nor I/O Events. These topics will be covered in other codelabs. 17 | 18 | All done with bootstrap process 19 | 20 | [Next](conversion.md) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Using TypeScript to develop a Project Firefly app 2 | 3 | This codelab will guide you through creating a headless app using [Project Firefly](https://github.com/AdobeDocs/project-firefly) the twist is that instead of using Javascript we will be using TypeScript. 4 | 5 | 6 | - Do you like a little more structure in your Firefly project? 7 | - Does the thought of loosely typed code make you loose sleep? 8 | - Do you enjoy better refactoring tooling? 9 | - Does having interfaces, namespaces, generics, abstract classes, data modifiers, optionals, function overloading, decorators, type utils, and the readonly keyword sound like it would make your project better? 10 | 11 | 12 | If you answered yes to any of the questions above then I think you should investigate using TypeScript with Project Firefly. 13 | 14 | ![TypeScript](lessons/assets/ts-logo-256.svg) 15 | 16 | The project source code of the codelab is available [here](https://github.com/AdobeDocs/adobeio-samples-typescript) 17 | 18 | 19 | Next: [Requirements](/lessons/requirements.md) 20 | -------------------------------------------------------------------------------- /lessons/frontend.md: -------------------------------------------------------------------------------- 1 | ## Lesson 4: Add TypeScript support for web-src 2 | 3 | By default, [ParcelJS](https://parceljs.org/) is used under the hood to bundle your frontend code. 4 | If you're using [React Spectrum](https://react-spectrum.adobe.com/) which is written in TypeScript, it makes sense to write your frontend code in TypeScript as well to benefit from TypeScript features. 5 | 6 | To use Typescript + React + JSX in your your `web-src` folder, you'll need to: 7 | * Use the `.tsx` extension 8 | * Properly require React 9 | * Add a tsconfig with a [special option](https://www.typescriptlang.org/docs/handbook/jsx.html) `"jsx": "react"` at the root of `web-src` folder. 10 | 11 | ```json 12 | // tsconfig.json 13 | { 14 | "compilerOptions": { 15 | "jsx": "react" 16 | } 17 | } 18 | ``` 19 | 20 | See the [ParcelJS](https://parceljs.org/typeScript.html) documentation for more information and the [Firefly app with TypeScript support](https://github.com/AdobeDocs/adobeio-samples-typescript) for a full example. 21 | 22 | [Next](welldone.md) -------------------------------------------------------------------------------- /lessons/assets/ts-logo-256.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 5 | 6 | ## Related Issue 7 | 8 | 9 | 10 | 11 | 12 | ## Motivation and Context 13 | 14 | 15 | ## How Has This Been Tested? 16 | 17 | 18 | 19 | 20 | ## Screenshots (if appropriate): 21 | 22 | ## Types of changes 23 | 24 | - [ ] Bug fix (non-breaking change which fixes an issue) 25 | - [ ] New feature (non-breaking change which adds functionality) 26 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 27 | 28 | ## Checklist: 29 | 30 | 31 | - [ ] My change requires a change to the documentation. 32 | - [ ] I have updated the documentation accordingly. 33 | - [ ] I have read the **CONTRIBUTING** document. 34 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Adobe Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at Grp-opensourceoffice@adobe.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [https://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: https://contributor-covenant.org 74 | [version]: https://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We love pull requests from everyone. 4 | 5 | The following are a set of guidelines to follow when contributing to this project. 6 | 7 | ## Code Of Conduct 8 | 9 | This project adheres to the Adobe [code of conduct](CODE_OF_CONDUCT.md). By participating, 10 | you are expected to uphold this code. Please report unacceptable behavior to 11 | [Grp-opensourceoffice@adobe.com](mailto:Grp-opensourceoffice@adobe.com). 12 | 13 | ## Have A Question? 14 | 15 | Start by filing an issue. The existing committers on this project work to reach 16 | consensus around project direction and issue solutions within issue threads 17 | (when appropriate). 18 | 19 | ### Security Issues 20 | 21 | Security issues shouldn't be reported on this issue tracker. Instead, [file an issue to our security experts](https://helpx.adobe.com/security/alertus.html). 22 | 23 | ## Contributor License Agreement 24 | 25 | All third-party contributions to this project must be accompanied by a signed contributor 26 | license agreement. This gives Adobe permission to redistribute your contributions 27 | as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html). You 28 | only need to submit an Adobe CLA one time, so if you have submitted one previously, 29 | you are good to go! 30 | 31 | ## Code Reviews 32 | 33 | All submissions should come in the form of pull requests and need to be reviewed 34 | by project committers. 35 | 36 | Start by [forking](https://help.github.com/articles/fork-a-repo/) the repo, then [clone](https://help.github.com/articles/cloning-a-repository/) your fork: 37 | 38 | ``` 39 | git clone git@github.com:yourusername/coral-spectrum.git 40 | ``` 41 | 42 | Set up a branch for your feature or bug fix, push it to your fork, and set up a remote for the upstream repo: 43 | 44 | ``` 45 | git checkout -b my-awesome-new-feature 46 | git push -u origin my-awesome-new-feature 47 | git remote add upstream git@github.com:adobe/coral-spectrum.git 48 | ``` 49 | 50 | Install dependencies: 51 | 52 | ``` 53 | npm install 54 | ``` 55 | 56 | Make sure the [gulp-cli](https://github.com/gulpjs/gulp-cli) is installed globally: 57 | 58 | ``` 59 | npm install -g gulp-cli 60 | ``` 61 | 62 | Build the project, open a browser window, and watch for changes: 63 | 64 | ``` 65 | gulp 66 | ``` 67 | 68 | Commit changes, referencing the relevant issue number (if any): 69 | 70 | ``` 71 | git commit -m "Cool stuff, closes #250, fixes #252" 72 | ``` 73 | 74 | Consider starting the commit message with an applicable emoji: 75 | 76 | * :art: `:art:` when improving the format/structure of the code 77 | * :zap: `:zap:` when improving performance 78 | * :non-potable_water: `:non-potable_water:` when plugging memory leaks 79 | * :memo: `:memo:` when writing docs 80 | * :ambulance: `:ambulance:` a critical hotfix. 81 | * :sparkles: `:sparkles:` when introducing new features 82 | * :bookmark: `:bookmark:` when releasing / version tags 83 | * :rocket: `:rocket:` when deploying stuff 84 | * :penguin: `:penguin:` when fixing something on Android 85 | * :apple: `:apple:` when fixing something on iOS 86 | * :checkered_flag: `:checkered_flag:` when fixing something on Windows 87 | * :bug: `:bug:` when fixing a bug 88 | * :fire: `:fire:` when removing code or files 89 | * :green_heart: `:green_heart:` when fixing the CI build 90 | * :white_check_mark: `:white_check_mark:` when adding tests 91 | * :lock: `:lock:` when dealing with security 92 | * :arrow_up: `:arrow_up:` when upgrading dependencies 93 | * :arrow_down: `:arrow_down:` when downgrading dependencies 94 | * :shirt: `:shirt:` when removing linter warnings 95 | * :hammer: `:hammer:` when doing heavy refactoring 96 | * :heavy_minus_sign: `:heavy_minus_sign:` when removing a dependency. 97 | * :heavy_plus_sign: `:heavy_plus_sign:` when adding a dependency. 98 | * :wrench: `:wrench:` when changing configuration files. 99 | * :globe_with_meridians: `:globe_with_meridians:` when dealing with internationalization and localization. 100 | * :pencil2: `:pencil2:` when fixing typos. 101 | * :hankey: `:hankey:` when writing bad code that needs to be improved. 102 | * :package: `:package:` when updating compiled files or packages. 103 | 104 | Make sure your branch is up to date with the original repo: 105 | 106 | ``` 107 | git fetch upstream 108 | git merge upstream/master 109 | ``` 110 | 111 | Review your changes and any possible conflicts and push to your fork: 112 | 113 | ``` 114 | git push origin 115 | ``` 116 | 117 | [Submit a pull request](https://help.github.com/articles/creating-a-pull-request/). 118 | 119 | At this point you're waiting on us. We do our best to keep on top of all the pull requests. We may suggest some changes, improvements or alternatives. 120 | 121 | Some things that will increase the chance that your pull request is accepted: 122 | 123 | - Write a [good commit message](http://chris.beams.io/posts/git-commit/). 124 | - Make sure the PR merges cleanly with the latest master. 125 | - Describe your feature/bugfix and why it's needed/important in the pull request description. 126 | -------------------------------------------------------------------------------- /lessons/conversion.md: -------------------------------------------------------------------------------- 1 | ## Lesson 2: Converting application to TypeScript 2 | 3 | ### Step one: move the code 4 | When we first generated the project the aio CLI created some default directories for us to use and some boilerplate code as well. We need to move this boilerplate and convert it to TypeScript. 5 | 6 | First step is to rename the `actions` folder and rename it to `actions-src`. 7 | ![Rename](assets/folder_move.png) 8 | 9 | ### Step two: convert the code 10 | We now need to convert the boilerplate code from Javascript to TypeScript. 11 | There should just be two files that we need to convert to TypeScript 12 | `actions/tsaction/index.js` and `actions/utils.js` 13 | 14 | To convert these two files we start with changing the file extension from `.js` to `.ts.` 15 | `actions/tsaction/index.ts` and `actions/utils.ts` 16 | 17 | ![TS to JS](assets/rename_js_ts.png) 18 | 19 | Now we need to modify the files starting with `utils.ts` 20 | In this file we need to change all the functions to have an export keyword in front of them and we will remove the exports statement at the end of the file. 21 | Here is the final `utils.ts` 22 | ```javascript 23 | /* 24 | * 25 | */ 26 | 27 | /* This file exposes some common utilities for your actions */ 28 | 29 | /** 30 | * 31 | * Returns a log ready string of the action input parameters. 32 | * The `Authorization` header content will be replaced by ''. 33 | * 34 | * @param {object} params action input parameters. 35 | * 36 | * @returns {string} 37 | * 38 | */ 39 | export function stringParameters (params) { 40 | // hide authorization token without overriding params 41 | let headers = params.__ow_headers || {} 42 | if (headers.authorization) { 43 | headers = { ...headers, authorization: '' } 44 | } 45 | return JSON.stringify({ ...params, __ow_headers: headers }) 46 | } 47 | 48 | /** 49 | * 50 | * Returns the list of missing keys giving an object and its required keys. 51 | * A parameter is missing if its value is undefined or ''. 52 | * A value of 0 or null is not considered as missing. 53 | * 54 | * @param {object} obj object to check. 55 | * @param {array} required list of required keys. 56 | * Each element can be multi level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey' 57 | * 58 | * @returns {array} 59 | * @private 60 | */ 61 | export function getMissingKeys (obj, required) { 62 | return required.filter(r => { 63 | const splits = r.split('.') 64 | const last = splits[splits.length - 1] 65 | const traverse = splits.slice(0, -1).reduce((tObj, split) => { tObj = (tObj[split] || {}); return tObj }, obj) 66 | return traverse[last] === undefined || traverse[last] === '' // missing default params are empty string 67 | }) 68 | } 69 | 70 | /** 71 | * 72 | * Returns the list of missing keys giving an object and its required keys. 73 | * A parameter is missing if its value is undefined or ''. 74 | * A value of 0 or null is not considered as missing. 75 | * 76 | * @param {object} params action input parameters. 77 | * @param {array} requiredHeaders list of required input headers. 78 | * @param {array} requiredParams list of required input parameters. 79 | * Each element can be multi level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'. 80 | * 81 | * @returns {string} if the return value is not null, then it holds an error message describing the missing inputs. 82 | * 83 | */ 84 | export function checkMissingRequestInputs (params, requiredParams = [], requiredHeaders = []) { 85 | let errorMessage = null 86 | 87 | // input headers are always lowercase 88 | requiredHeaders = requiredHeaders.map(h => h.toLowerCase()) 89 | // check for missing headers 90 | const missingHeaders = getMissingKeys(params.__ow_headers || {}, requiredHeaders) 91 | if (missingHeaders.length > 0) { 92 | errorMessage = `missing header(s) '${missingHeaders}'` 93 | } 94 | 95 | // check for missing parameters 96 | const missingParams = getMissingKeys(params, requiredParams) 97 | if (missingParams.length > 0) { 98 | if (errorMessage) { 99 | errorMessage += ' and ' 100 | } else { 101 | errorMessage = '' 102 | } 103 | errorMessage += `missing parameter(s) '${missingParams}'` 104 | } 105 | 106 | return errorMessage 107 | } 108 | 109 | /** 110 | * 111 | * Extracts the bearer token string from the Authorization header in the request parameters. 112 | * 113 | * @param {object} params action input parameters. 114 | * 115 | * @returns {string|undefined} the token string or undefined if not set in request headers. 116 | * 117 | */ 118 | export function getBearerToken (params) { 119 | if (params.__ow_headers && 120 | params.__ow_headers.authorization && 121 | params.__ow_headers.authorization.startsWith('Bearer ')) { 122 | return params.__ow_headers.authorization.substring('Bearer '.length) 123 | } 124 | return undefined 125 | } 126 | /** 127 | * 128 | * Returns an error response object and attempts to log.info the status code and error message 129 | * 130 | * @param {number} statusCode the error status code. 131 | * e.g. 400 132 | * @param {string} message the error message. 133 | * e.g. 'missing xyz parameter' 134 | * @param {*} [logger] an optional logger instance object with an `info` method 135 | * e.g. `new require('@adobe/aio-sdk').Core.Logger('name')` 136 | * 137 | * @returns {object} the error object, ready to be returned from the action main's function. 138 | * 139 | */ 140 | export function errorResponse (statusCode, message, logger) { 141 | if (logger && typeof logger.info === 'function') { 142 | logger.info(`${statusCode}: ${message}`) 143 | } 144 | return { 145 | error: { 146 | statusCode, 147 | body: { 148 | error: message 149 | } 150 | } 151 | } 152 | } 153 | 154 | ``` 155 | 156 | Now that the utils has been converted lets move to the default action we had the cli build for us. 157 | In this file we need to convert all the requires to imports at the top of the file 158 | ```javascript 159 | import fetch from 'node-fetch' 160 | import { Core } from '@adobe/aio-sdk' 161 | import { errorResponse, getBearerToken, stringParameters, checkMissingRequestInputs } from '../utils' 162 | ``` 163 | Now we need to change the main function and add on `export` 164 | ```javascript 165 | export async function main (params) { 166 | ``` 167 | 168 | Lastly we need to remove the exports statement from the end of the file. Remove the line `exports.main = main` from the file. We no longer need this export since we are exporting the function. 169 | 170 | 171 | [Next](build.md) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Adobe 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lessons/build.md: -------------------------------------------------------------------------------- 1 | ## Lesson 3: Tweaking the build to support TypeScript 2 | 3 | What we are going to do to convert the project from Javascript to TypeScript is to move the actions directory from the cli templated project setup and rename that folder action-src. Then we convert all the exiting template code to TypeScript. Next we add in a pre app run hook that will transpile the TypeScript into Javascript and put the results back in the /actions directory. The stock build process will take it from there and deploy the actions. 4 | 5 | ### Step one: add in project dependencies 6 | Add in [shx](https://www.npmjs.com/package/shx). Shx is a npm package that helps us use shell commands in a cross-platform manner. We will be using shx to help us clean up the actions directory between builds. 7 | To install this npm module issue the following command from inside your projects home directory 8 | ```bash 9 | npm install shx --save-dev 10 | ``` 11 | 12 | Add in TypeScript module 13 | ```bash 14 | npm install typescript --save-dev 15 | ``` 16 | 17 | **Optional: Install type libraries and lint plugin** 18 | Install some standard type libraries 19 | ```bash 20 | npm install "@types/mime-types" --save-dev 21 | npm install "@types/node-fetch" --save-dev 22 | npm install "@types/node" --save-dev 23 | ``` 24 | 25 | Install the TypeScript lint plugin 26 | ```bash 27 | npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin 28 | ``` 29 | 30 | Add lint config and ignore 31 | Create a new file in your project root named `.eslintrc` 32 | In the new `.eslintrc` file put the following content 33 | ```javascript 34 | { 35 | "root": true, 36 | "parser": "@typescript-eslint/parser", 37 | "plugins": [ 38 | "@typescript-eslint" 39 | ], 40 | "extends": [ 41 | "eslint:recommended", 42 | "plugin:@typescript-eslint/eslint-recommended", 43 | "plugin:@typescript-eslint/recommended" 44 | ] 45 | } 46 | ``` 47 | 48 | Create a new file in your project root named `.eslintignore` 49 | In the new `.eslintignore` file put the following content 50 | ```javascript 51 | node_modules 52 | actions 53 | 54 | # ignore web src if it exists 55 | web-src 56 | ``` 57 | 58 | Add lint scripts to package.json 59 | In the projects `package.json` add in the following lines to the scripts 60 | ```javascript 61 | "lint": "eslint \"actions-src/**/*.{js,ts}\" ", 62 | "lint-fix": "eslint \"actions-src/**/*.{js,ts}\" --quiet --fix" 63 | ``` 64 | 65 | 66 | ### Step two: modify the build hooks 67 | TypeScript will need some instructions on how you want it to transpile your TypeScript into Javascript and where to output it and all the nifty options to use. 68 | In your project directory create the following file `tsconfig.json` 69 | Then in this new file put the following config. I have included a lot of the options in the file but they are commented out. This file is intended to be a starting point and it would be something you tune and modify over time. 70 | ```javascript 71 | { 72 | "compilerOptions": { 73 | /* Basic Options */ 74 | "module": "commonjs", /*Specify module code generation: "None", "CommonJS", "AMD", "System", "UMD", "ES6", "ES2015" or "ESNext". Only "AMD" and "System" can be used in conjunction with --outFile. "ES6" and "ES2015" values may be used when targeting "ES5" or lower.*/ 75 | "target": "es5", /*Specify ECMAScript target version: "ES3" (default),"ES5","ES6"/"ES2015","ES2016","ES2017","ES2018","ES2019","ES2020","ESNext"*/ 76 | //"lib": [ "es2015", "dom" ], /*List of library files to be included in the compilation. see https://www.typescriptlang.org/docs/handbook/compiler-options.html */ 77 | //"removeComments": true, 78 | //"resolveJsonModule": true, 79 | //"esModuleInterop": true, 80 | //"typeRoots" : [ 81 | // "./node_modules/@types/", 82 | // "./typings/" 83 | //], 84 | // "lib": [], /* Specify library files to be included in the compilation. */ 85 | "allowJs": false, /* Allow javascript files to be compiled. */ 86 | "checkJs": false, /* Report errors in .js files. */ 87 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 88 | "declaration": false, /* Generates corresponding '.d.ts' file. */ 89 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 90 | "sourceMap": false, /* Generates corresponding '.map' file. */ 91 | // "outFile": "./", /* Concatenate and emit output to single file. */ 92 | "outDir": "actions", /* Redirect output structure to the directory. */ 93 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 94 | // "composite": true, /* Enable project compilation */ 95 | // "removeComments": true, /* Do not emit comments to output. */ 96 | // "noEmit": true, /* Do not emit outputs. */ 97 | //"importHelpers": true, /* Import emit helpers from 'tslib'. */ 98 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 99 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 100 | 101 | /* Strict Type-Checking Options */ 102 | //"strict": true, /* Enable all strict type-checking options. */ 103 | "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ 104 | //"strictNullChecks": false, /* Enable strict null checks. */ 105 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 106 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 107 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 108 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 109 | 110 | /* Additional Checks */ 111 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 112 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 113 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 114 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 115 | 116 | /* Module Resolution Options */ 117 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 118 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 119 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 120 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 121 | // "typeRoots": [], /* List of folders to include type definitions from. */ 122 | // "types": ["jest", "node"], /* Type declaration files to be included in compilation. */ 123 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 124 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 125 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 126 | 127 | /* Source Map Options */ 128 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 129 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 130 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 131 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 132 | 133 | /* Experimental Options */ 134 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 135 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 136 | }, 137 | "include": [ 138 | "./actions-src/**/*" 139 | ], 140 | "exclude": [ 141 | "dev-keys" 142 | ] 143 | } 144 | ``` 145 | The important bits of this config file are the **include** telling it to include TypeScript found `/actions-src/` directory. The other important bit is telling the transpiler what **module** type, the target type **target**, and the **output** directory for the transpiled code. 146 | 147 | ### Step three: modify the build hooks 148 | Inside your project directory you will see a file named package.json. Inside that file you will see a section named "scripts". We are going to modify this to include two new scripts. One for cleaning up the directories we build into and another script to run before the aio run command. 149 | In package.json add in the following lines. 150 | ```javascript 151 | "pre-app-run": "npm run clean && tsc" 152 | ``` 153 | pre-app-run: this is a hook that gets run before aio run. Here we are telling it to run the clean script then run the TypeScript compiler. To find out more about the application tooling lifecycle event hooks [read this](https://github.com/AdobeDocs/project-firefly/blob/master/guides/app-hooks.md). 154 | 155 | and add this line to handle cleanup 156 | ```javascript 157 | "clean": "shx rm -rf actions && shx echo Action Cleaning Done" 158 | ``` 159 | This will use shx to remove recursively the actions directory so we can put our new freshly transpiled TypeScript in there. 160 | 161 | When your done your package.json scripts section should look similar to this 162 | ```javascript 163 | "scripts": { 164 | "pre-app-run": "npm run clean && tsc", 165 | "test": "jest --passWithNoTests --verbose ./test", 166 | "e2e": "jest --collectCoverage=false --testRegex ./e2e", 167 | "clean": "shx rm -rf actions && shx echo Action Cleaning Done" 168 | } 169 | ``` 170 | 171 | ### Step four: test and modify gitignore 172 | 173 | To avoid checking in transpiled output you will want to modify `.gitignore` to include the TypeScript output directory. In this case its the actions directory so we will add that to the `.gitignore` config. 174 | The contents of `.gitignore` should look similar to this when your done. 175 | ```javascript 176 | 177 | # package directories 178 | node_modules 179 | jspm_packages 180 | 181 | # build 182 | build 183 | dist 184 | .manifest-dist.yml 185 | 186 | # Config 187 | config.json 188 | .env* 189 | 190 | # Adobe I/O console config 191 | console.json 192 | 193 | # Test output 194 | junit.xml 195 | 196 | # IDE & Temp 197 | .cache 198 | .idea 199 | .nyc_output 200 | .vscode 201 | coverage 202 | .aws.tmp.creds.json 203 | .wskdebug.props.tmp 204 | 205 | # OSX 206 | .DS_Store 207 | 208 | # yeoman 209 | .yo-repository 210 | 211 | # logs folder for aio-run-detached 212 | logs 213 | 214 | # ignore the build output 215 | actions 216 | 217 | ``` 218 | 219 | Now lets try out the build by running the command `aio app run` 220 | ![AIO Run](assets/aio_run.png) 221 | 222 | 223 | If you installed the optional lint plugins you will also be able to run `npm run lint` or `npm run lint-fix` 224 | ![NPM Lint](assets/lint.png) 225 | We have 16 Warnings to address but that's not a bad start. 226 | 227 | 228 | [Next](frontend.md) 229 | --------------------------------------------------------------------------------