├── .gitignore ├── LICENSE.md ├── README.md ├── package-lock.json ├── package.json ├── src ├── CodePipelineEvent.ts └── index.ts ├── tsconfig.json ├── tslint.json └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Node stuff 2 | node_modules/ 3 | *.log 4 | npm-debug.log* 5 | .npm 6 | .node_repl_history 7 | 8 | # IntelliJ stuff 9 | *.iml 10 | .idea/ 11 | 12 | # Build output 13 | dist/ 14 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | 6 | 7 | 8 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 9 | 10 | ## 1. Definitions 11 | 12 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 17 | 18 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 19 | 20 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 21 | 22 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 23 | 24 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 25 | 26 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 27 | 28 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 29 | 30 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 31 | 32 | ## 2. Grant of Copyright License 33 | 34 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 35 | 36 | ## 3. Grant of Patent License 37 | 38 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 39 | 40 | ## 4. Redistribution 41 | 42 | You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 43 | 44 | 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and 45 | 46 | 2. You must cause any modified files to carry prominent notices stating that You changed the files; and 47 | 48 | 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 49 | 50 | 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 51 | 52 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 53 | 54 | ## 5. Submission of Contributions 55 | 56 | Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 57 | 58 | ## 6. Trademarks 59 | 60 | This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 61 | 62 | ## 7. Disclaimer of Warranty 63 | 64 | Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 65 | 66 | ## 8. Limitation of Liability 67 | 68 | In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 69 | 70 | ## 9. Accepting Warranty or Additional Liability 71 | 72 | While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 73 | 74 | END OF TERMS AND CONDITIONS 75 | 76 | # APPENDIX: How to apply the Apache License to your work. 77 | 78 | > To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 79 | 80 | Copyright 2022 Giftbit 81 | 82 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 83 | 84 | 85 | 86 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodePipeline GitHub Action 2 | 3 | Trigger GitHub actions in AWS CodePipeline 4 | 5 | ## Usage 6 | 7 | This is the source code for an [AWS Lambda](http://docs.aws.amazon.com/lambda/latest/dg/welcome.html) function that can be used as a [CodePipeline](http://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) step to create and optionally merge a [GitHub pull request](https://help.github.com/articles/about-pull-requests/) between branches. This is most useful as part of a continuous integration flow between a staging pipeline and a production pipeline. 8 | 9 | To use this in your own CodePipeline you can build the project and upload it to your own S3 bucket, or you can reference the latest build at s3://lightrail-public-resources/cloudformation/codepipeline-github-action/2020-03-17.zip 10 | 11 | This function uses the following environment variables: 12 | - `GITHUB_REPO_OWNER` 13 | - The owner of the GitHub repo to create a pull request in. eg: Giftbit in https://github.com/Giftbit/codepipeline-github-action 14 | - `GITHUB_REPO` 15 | - The GitHub repo to create a pull request in. eg: codepipeline-github-action in https://github.com/Giftbit/codepipeline-github-action 16 | - `GITHUB_SOURCE_BRANCH` 17 | - The GitHub branch to pull from (head). 18 | - `GITHUB_DEST_BRANCH` 19 | - The GitHub branch to pull to (base). 20 | - `GITHUB_OAUTH` 21 | - The [github oauth token](https://help.github.com/articles/creating-an-access-token-for-command-line-use/) for the GitHub user to run the commands as. This value *must* be KMS encrypted and the lambda function must have permission to decrypt. See the example CloudFormation template linked below on how this is best configured. 22 | - `AUTO_MERGE` *(optional)* 23 | - If `true` automatically merge the created pull request. 24 | - `PULL_REQUEST_MESSAGE` *(optional)* 25 | - The message to apply to the pull request. Defaults to `"Automatic pull request by CI"`. 26 | - `MERGE_MESSAGE` *(optional)* 27 | - The message to apply to the merge, if `AUTO_MERGE` is `true`. Defaults to `"Automatic merge by CI"`. 28 | 29 | Check out [Giftbit/sam-scaffold](https://github.com/Giftbit/sam-scaffold/blob/master/typescript/infrastructure/ci.yaml) for an example CloudFormation template that uses this function. 30 | 31 | ## Development 32 | 33 | The only external dependency is [node](https://nodejs.org/en/) >= 10. The source code is written in [TypeScript](https://www.typescriptlang.org/). 34 | 35 | From the command line `npm install && npm run build` to build the distribution zip file, which will be at `dist/dist.zip`. 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "codepipeline-github-action", 3 | "version": "1.0.0", 4 | "description": "Push GitHub branches in a CodePipeline.", 5 | "scripts": { 6 | "build": "webpack", 7 | "clean": "rimraf ./dist", 8 | "lint": "tslint --project tsconfig.json", 9 | "test": "echo \"Error: no test specified\" && exit 1", 10 | "upload": "npm run clean && npm run build && aws s3 cp ./dist/dist.zip s3://lightrail-public-resources/cloudformation/codepipeline-github-action/`date +%Y-%m-%d`.zip --acl public-read" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/Giftbit/codepipeline-github-action.git" 15 | }, 16 | "keywords": [], 17 | "author": "Jeffery Grajkowski ", 18 | "contributors": [ 19 | { 20 | "name": "Jeffery Grajkowski", 21 | "email": "pushplay@gmail.com" 22 | } 23 | ], 24 | "license": "MIT", 25 | "bugs": { 26 | "url": "https://github.com/Giftbit/codepipeline-github-action/issues" 27 | }, 28 | "homepage": "https://github.com/Giftbit/codepipeline-github-action#readme", 29 | "devDependencies": { 30 | "@babel/core": "^7.8.7", 31 | "@babel/preset-env": "^7.8.7", 32 | "@types/aws-lambda": "8.10.46", 33 | "@types/node": "^10.12.18", 34 | "babel-loader": "^8.0.6", 35 | "file-loader": "^6.0.0", 36 | "rimraf": "^3.0.2", 37 | "ts-loader": "^6.2.0", 38 | "tslint": "^5.12.0", 39 | "typescript": "^3.8.3", 40 | "webpack": "^4.42.0", 41 | "webpack-cli": "^3.3.11", 42 | "zip-webpack-plugin": "^3.0.0" 43 | }, 44 | "dependencies": { 45 | "aws-sdk": "^2.814.0" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/CodePipelineEvent.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * see: http://docs.aws.amazon.com/codepipeline/latest/userguide/how-to-lambda-integration.html#how-to-lambda-JSON 3 | * see: http://docs.aws.amazon.com/codepipeline/latest/APIReference/API_GetJobDetails.html 4 | */ 5 | export interface CodePipelineEvent { 6 | "CodePipeline.job": { 7 | id: string; 8 | accountId: string; 9 | data: { 10 | actionConfiguration: { 11 | configuration: { 12 | FunctionName: string; 13 | UserParameters: string; 14 | } 15 | }, 16 | inputArtifacts: CodePipelineArtifact[]; 17 | outputArtifacts: CodePipelineArtifact[]; 18 | artifactCredentials: { 19 | secretAccessKey: string; 20 | sessionToken: string; 21 | accessKeyId: string; 22 | } 23 | } 24 | }; 25 | } 26 | 27 | export interface CodePipelineArtifact { 28 | location: CodePipelineLocation; 29 | revision: string; 30 | name: string; 31 | } 32 | 33 | export interface CodePipelineLocation { 34 | s3Location: CodePipelineS3Location; 35 | type: "S3"; 36 | } 37 | 38 | export interface CodePipelineS3Location { 39 | bucketName: string; 40 | objectKey: string; 41 | } 42 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import * as aws from "aws-sdk"; 2 | import * as awslambda from "aws-lambda"; 3 | import * as https from "https"; 4 | import {CodePipelineEvent} from "./CodePipelineEvent"; 5 | 6 | const creds = new aws.EnvironmentCredentials("AWS"); 7 | const codepipeline = new aws.CodePipeline({ 8 | apiVersion: "2015-07-09", 9 | credentials: creds 10 | }); 11 | const kms = new aws.KMS({ 12 | apiVersion: "2014-11-01", 13 | credentials: creds 14 | }); 15 | 16 | //noinspection JSUnusedGlobalSymbols 17 | export async function handler(evt: CodePipelineEvent, ctx: awslambda.Context): Promise { 18 | console.log("event", JSON.stringify(evt, null, 2)); 19 | const jobId = evt["CodePipeline.job"].id; 20 | 21 | try { 22 | checkConfig(); 23 | } catch (err) { 24 | console.error(err); 25 | await codepipeline.putJobFailureResult({ 26 | jobId: jobId, 27 | failureDetails: { 28 | type: "ConfigurationError", 29 | message: err.message, 30 | externalExecutionId: ctx.awsRequestId 31 | } 32 | }).promise(); 33 | return; 34 | } 35 | 36 | try { 37 | const prNumber = await createPullRequest(); 38 | if (process.env["AUTO_MERGE"] === "true" && prNumber) { 39 | await mergePullRequest(prNumber); 40 | } 41 | await codepipeline.putJobSuccessResult({ 42 | jobId: jobId 43 | }).promise(); 44 | } catch (err) { 45 | console.error(err); 46 | await codepipeline.putJobFailureResult({ 47 | jobId: jobId, 48 | failureDetails: { 49 | type: "JobFailed", 50 | message: err.message, 51 | externalExecutionId: ctx.awsRequestId 52 | } 53 | }).promise(); 54 | } 55 | return {}; 56 | } 57 | 58 | async function createPullRequest(): Promise { 59 | try { 60 | const createPath = `/repos/${process.env["GITHUB_REPO_OWNER"]}/${process.env["GITHUB_REPO"]}/pulls`; 61 | const createBody = { 62 | title: process.env["PULL_REQUEST_MESSAGE"] || "Automatic pull request by CI", 63 | head: process.env["GITHUB_SOURCE_BRANCH"], // src 64 | base: process.env["GITHUB_DEST_BRANCH"] // dest 65 | }; 66 | console.log("create pull request", createPath, createBody); 67 | const createResp = await request(createPath, "POST", createBody); 68 | console.log("createResp", createResp); 69 | 70 | return createResp.number; 71 | } catch (err) { 72 | if (err && Array.isArray(err.errors) && err.errors.length === 1) { 73 | if (err.errors[0].code === "custom" && err.errors[0].message === "No commits between master and staging") { 74 | // Nothing changed so no pull request. This is fine. 75 | return null; 76 | } 77 | if (err.errors[0].code === "custom" && /^A pull request already exists for /.test(err.errors[0].message)) { 78 | // There's already a pull request for this. This is fine. 79 | return null; 80 | } 81 | } 82 | 83 | throw err; 84 | } 85 | } 86 | 87 | async function mergePullRequest(prNumber: string): Promise { 88 | const mergePath = `/repos/${process.env["GITHUB_REPO_OWNER"]}/${process.env["GITHUB_REPO"]}/pulls/${prNumber}/merge`; 89 | const mergeBody = { 90 | "commit_message": process.env["MERGE_MESSAGE"] || "Automatic merge by CI" 91 | }; 92 | console.log("merge pull request", mergePath, mergeBody); 93 | const mergeResp = await request(mergePath, "PUT", mergeBody); 94 | console.log("mergeResp", mergeResp); 95 | } 96 | 97 | let cachedOauthToken: string = null; 98 | async function getGithubOauthToken(): Promise { 99 | if (!cachedOauthToken) { 100 | const response = await kms.decrypt({ 101 | CiphertextBlob: new Buffer(process.env["GITHUB_OAUTH"], "base64") 102 | }).promise(); 103 | cachedOauthToken = (response.Plaintext as Buffer).toString("ascii"); 104 | } 105 | return cachedOauthToken; 106 | } 107 | 108 | /** 109 | * All the libraries suck. Make this github api request manually. 110 | */ 111 | async function request(path: string, method: string, body?: Object): Promise { 112 | const oauthToken = await getGithubOauthToken(); 113 | 114 | const bodyJson = JSON.stringify(body); 115 | const options: https.RequestOptions = { 116 | hostname: "api.github.com", 117 | port: 443, 118 | path: path, 119 | method: method, 120 | headers: { 121 | "Authorization": `token ${oauthToken}`, 122 | "Accept": "application/json", 123 | "User-Agent": "Giftbit/lambda-github-pusher" 124 | } 125 | }; 126 | 127 | if (body) { 128 | options.headers["Content-Length"] = bodyJson.length; 129 | options.headers["Content-Type"] = "application/json"; 130 | } 131 | 132 | return await new Promise((resolve, reject) => { 133 | const request = https.request(options, (response) => { 134 | console.log(`response.statusCode ${response.statusCode}`); 135 | console.log(`response.headers ${JSON.stringify(response.headers)}`); 136 | 137 | const responseBody: string[] = []; 138 | response.setEncoding("utf8"); 139 | response.on("data", d => { 140 | responseBody.push(d as string); 141 | }); 142 | response.on("end", () => { 143 | if (response.statusCode >= 400) { 144 | try { 145 | console.log("response error", responseBody.join("")); 146 | reject(JSON.parse(responseBody.join(""))); 147 | } catch (e) { 148 | reject(e); 149 | } 150 | } else { 151 | try { 152 | const responseJson = JSON.parse(responseBody.join("")); 153 | resolve(responseJson); 154 | } catch (e) { 155 | reject(e); 156 | } 157 | } 158 | }); 159 | }); 160 | 161 | request.on("error", error => { 162 | console.log("request error", error); 163 | reject(error); 164 | }); 165 | 166 | if (body) { 167 | request.write(bodyJson); 168 | } 169 | request.end(); 170 | }); 171 | } 172 | 173 | function checkConfig(): void { 174 | if (!process.env["GITHUB_REPO_OWNER"]) { 175 | throw new Error("Missing environment variable GITHUB_REPO_OWNER"); 176 | } 177 | if (!process.env["GITHUB_REPO"]) { 178 | throw new Error("Missing environment variable GITHUB_REPO"); 179 | } 180 | if (!process.env["GITHUB_SOURCE_BRANCH"]) { 181 | throw new Error("Missing environment variable GITHUB_SOURCE_BRANCH"); 182 | } 183 | if (!process.env["GITHUB_DEST_BRANCH"]) { 184 | throw new Error("Missing environment variable GITHUB_DEST_BRANCH"); 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "module": "commonjs", 5 | "target": "es6", 6 | "noImplicitAny": true, 7 | "sourceMap": false 8 | } 9 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "jsRules": { 3 | "class-name": true, 4 | "comment-format": [ 5 | true, 6 | "check-space" 7 | ], 8 | "indent": [ 9 | true, 10 | "spaces" 11 | ], 12 | "no-duplicate-variable": true, 13 | "no-eval": true, 14 | "no-trailing-whitespace": true, 15 | "no-unsafe-finally": true, 16 | "one-line": [ 17 | true, 18 | "check-open-brace", 19 | "check-whitespace" 20 | ], 21 | "quotemark": [ 22 | true, 23 | "double" 24 | ], 25 | "semicolon": [ 26 | true, 27 | "always" 28 | ], 29 | "triple-equals": [ 30 | true, 31 | "allow-null-check" 32 | ], 33 | "variable-name": [ 34 | true, 35 | "ban-keywords" 36 | ], 37 | "whitespace": [ 38 | true, 39 | "check-branch", 40 | "check-decl", 41 | "check-operator", 42 | "check-separator", 43 | "check-type" 44 | ] 45 | }, 46 | "rules": { 47 | "class-name": true, 48 | "comment-format": [ 49 | true, 50 | "check-space" 51 | ], 52 | "indent": [ 53 | true, 54 | "spaces" 55 | ], 56 | "no-eval": true, 57 | "no-internal-module": true, 58 | "no-trailing-whitespace": true, 59 | "no-unsafe-finally": true, 60 | "no-var-keyword": true, 61 | "one-line": [ 62 | true, 63 | "check-open-brace", 64 | "check-whitespace" 65 | ], 66 | "quotemark": [ 67 | true, 68 | "double" 69 | ], 70 | "semicolon": [ 71 | true, 72 | "always" 73 | ], 74 | "triple-equals": [ 75 | true, 76 | "allow-null-check" 77 | ], 78 | "typedef-whitespace": [ 79 | true, 80 | { 81 | "call-signature": "nospace", 82 | "index-signature": "nospace", 83 | "parameter": "nospace", 84 | "property-declaration": "nospace", 85 | "variable-declaration": "nospace" 86 | } 87 | ], 88 | "variable-name": [ 89 | true, 90 | "ban-keywords" 91 | ], 92 | "whitespace": [ 93 | true, 94 | "check-branch", 95 | "check-decl", 96 | "check-operator", 97 | "check-separator", 98 | "check-type" 99 | ] 100 | } 101 | } -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const ZipPlugin = require('zip-webpack-plugin'); 3 | 4 | module.exports = { 5 | mode: 'production', 6 | entry: path.join(__dirname, 'src', 'index.ts'), 7 | target: 'node', 8 | node: { 9 | // Allow these globals. 10 | __filename: false, 11 | __dirname: false, 12 | Base64: false 13 | }, 14 | output: { 15 | path: path.join(__dirname, 'dist'), 16 | filename: 'index.js', 17 | libraryTarget: 'commonjs2' 18 | }, 19 | externals: { 20 | // These modules are already installed on the Lambda instance. 21 | 'aws-sdk': 'aws-sdk', 22 | 'awslambda': 'awslambda', 23 | 'dynamodb-doc': 'dynamodb-doc', 24 | 'imagemagick': 'imagemagick' 25 | }, 26 | bail: true, 27 | resolve: { 28 | extensions: ['.ts', '.tsx', '.js'] 29 | }, 30 | module: { 31 | rules: [ 32 | { 33 | test: /\.js$/, 34 | use: [ 35 | { 36 | loader: 'babel-loader', 37 | options: { 38 | presets: [['@babel/env', {targets: {node: '10.16'}}]], 39 | plugins: [], 40 | compact: false, 41 | babelrc: false 42 | } 43 | } 44 | ] 45 | }, 46 | { 47 | test: /\.ts(x?)$/, 48 | use: [ 49 | { 50 | loader: 'babel-loader', 51 | options: { 52 | presets: [['@babel/env', {targets: {node: '10.16'}}]], 53 | plugins: [], 54 | compact: false, 55 | babelrc: false 56 | } 57 | }, 58 | 'ts-loader' 59 | ] 60 | }, 61 | { 62 | test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$|\.wav$|\.mp3$/, 63 | use: [ 64 | 'file-loader' 65 | ] 66 | } 67 | ] 68 | }, 69 | plugins: [ 70 | new ZipPlugin({ 71 | path: path.join(__dirname, 'dist'), 72 | pathPrefix: "", 73 | filename: `dist.zip` 74 | }) 75 | ] 76 | }; 77 | --------------------------------------------------------------------------------