From a7c22a965362b3173ce123d8e67d0f8b424c3b15 Mon Sep 17 00:00:00 2001 From: Shen Chen Date: Tue, 21 Jul 2020 14:31:39 -0700 Subject: [PATCH] feat: add ask-sdk-local-debug package --- ask-sdk-local-debug/.eslintignore | 3 + ask-sdk-local-debug/.eslintrc.js | 172 +++++++++++++++ ask-sdk-local-debug/.gitignore | 11 + ask-sdk-local-debug/.npmignore | 8 + ask-sdk-local-debug/CHANGELOG.md | 7 + ask-sdk-local-debug/LICENSE | 201 ++++++++++++++++++ ask-sdk-local-debug/NOTICE.txt | 2 + ask-sdk-local-debug/README.md | 75 +++++++ .../lib/LocalDebuggerInvoker.ts | 44 ++++ .../lib/builder/ClientConfigBuilder.ts | 68 ++++++ .../lib/builder/SkillInvokerConfigBuilder.ts | 33 +++ .../builder/WebSocketClientConfigBuilder.ts | 44 ++++ .../lib/client/ILocalDebugClient.ts | 26 +++ .../lib/client/LocalDebugClient.ts | 80 +++++++ .../lib/config/ClientConfig.ts | 47 ++++ .../lib/config/SkillInvokerConfig.ts | 27 +++ .../lib/config/WebSocketClientConfig.ts | 33 +++ .../lib/request/DynamicEndpointsRequest.ts | 24 +++ .../lib/util/ArgsParserUtils.ts | 76 +++++++ .../lib/util/RequestResponseUtils.ts | 56 +++++ ask-sdk-local-debug/package.json | 51 +++++ ask-sdk-local-debug/tsconfig.json | 17 ++ 22 files changed, 1105 insertions(+) create mode 100644 ask-sdk-local-debug/.eslintignore create mode 100644 ask-sdk-local-debug/.eslintrc.js create mode 100644 ask-sdk-local-debug/.gitignore create mode 100644 ask-sdk-local-debug/.npmignore create mode 100644 ask-sdk-local-debug/CHANGELOG.md create mode 100644 ask-sdk-local-debug/LICENSE create mode 100644 ask-sdk-local-debug/NOTICE.txt create mode 100644 ask-sdk-local-debug/README.md create mode 100644 ask-sdk-local-debug/lib/LocalDebuggerInvoker.ts create mode 100644 ask-sdk-local-debug/lib/builder/ClientConfigBuilder.ts create mode 100644 ask-sdk-local-debug/lib/builder/SkillInvokerConfigBuilder.ts create mode 100644 ask-sdk-local-debug/lib/builder/WebSocketClientConfigBuilder.ts create mode 100644 ask-sdk-local-debug/lib/client/ILocalDebugClient.ts create mode 100644 ask-sdk-local-debug/lib/client/LocalDebugClient.ts create mode 100644 ask-sdk-local-debug/lib/config/ClientConfig.ts create mode 100644 ask-sdk-local-debug/lib/config/SkillInvokerConfig.ts create mode 100644 ask-sdk-local-debug/lib/config/WebSocketClientConfig.ts create mode 100644 ask-sdk-local-debug/lib/request/DynamicEndpointsRequest.ts create mode 100644 ask-sdk-local-debug/lib/util/ArgsParserUtils.ts create mode 100644 ask-sdk-local-debug/lib/util/RequestResponseUtils.ts create mode 100644 ask-sdk-local-debug/package.json create mode 100644 ask-sdk-local-debug/tsconfig.json diff --git a/ask-sdk-local-debug/.eslintignore b/ask-sdk-local-debug/.eslintignore new file mode 100644 index 00000000..63520da7 --- /dev/null +++ b/ask-sdk-local-debug/.eslintignore @@ -0,0 +1,3 @@ +node_modules +dist +build diff --git a/ask-sdk-local-debug/.eslintrc.js b/ask-sdk-local-debug/.eslintrc.js new file mode 100644 index 00000000..afedda62 --- /dev/null +++ b/ask-sdk-local-debug/.eslintrc.js @@ -0,0 +1,172 @@ +module.exports = { + root: true, + parser: "@typescript-eslint/parser", + plugins: ["@typescript-eslint", "prettier"], + env: { + node: true, + es6: true, + }, + extends: [ + "airbnb", + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "plugin:eslint-comments/recommended", + // Disable below extends and parser options if having performance issues + // https://github.com/typescript-eslint/typescript-eslint/blob/master/docs/getting-started/linting/TYPED_LINTING.md + "plugin:@typescript-eslint/recommended-requiring-type-checking", + ], + rules: { + // --------------------------------------------------------- + // --- Rules from eslint:recommended that we override + // --------------------------------------------------------- + "class-methods-use-this": ["error", { "exceptMethods": ["errorEvent", "connectedEvent"] }], + "no-unused-vars": "off", // because it flags types that are imported for type declarations (but otherwise unused). + "no-undef": "off", // because if flags lack of import for Set. // TODO: fix the issues and remove this override. + + // --------------------------------------------------------- + // --- Rules that we add and/or customize + // --------------------------------------------------------- + + eqeqeq: ["error", "smart"], + "guard-for-in": "error", + "id-blacklist": [ + "error", + "any", + "Number", + "number", + "String", + "string", + "Boolean", + "boolean", + "Undefined", + "undefined", + ], + "id-match": "error", + "import/extensions": [ + "error", + "ignorePackages", + { + "js": "never", + "jsx": "never", + "ts": "never", + "tsx": "never" + } + ], + "import/no-cycle": "off", + "import/no-default-export": "error", + "import/no-extraneous-dependencies": ["off", { devDependencies: false }], + "import/prefer-default-export": "off", + indent: "off", + "jsx-a11y/control-has-associated-label": "off", + "jsx-a11y/label-has-associated-control": "off", + "new-parens": "error", + "no-caller": "error", + "no-duplicate-imports": "error", + "no-eval": "error", + "no-extra-bind": "error", + "no-new-func": "error", + "no-new-wrappers": "error", + "no-return-await": "error", + "no-sequences": "error", + "no-shadow": ["off", { hoist: "all" }], + "no-undef-init": "error", + "no-underscore-dangle": ["error", { + "allowAfterThis": true + }], + "no-var": "error", + "object-shorthand": "error", + "one-var": ["error", "never"], + "prefer-const": "error", + "prefer-object-spread": "error", + radix: "error", + + "@typescript-eslint/strict-boolean-expressions": ["error"], // avoids frequent sources of errors: 0, "", Promise, null vs undefined + "@typescript-eslint/adjacent-overload-signatures": "error", + "@typescript-eslint/array-type": ["error", { default: "array-simple" }], + "@typescript-eslint/ban-types": [ + "error", + { + types: { + Object: { + message: "Avoid using the `Object` type. Did you mean `object`?", + }, + Function: { + message: + "Avoid using the `Function` type. Prefer a specific function type, like `() => void`.", + }, + Boolean: { + message: "Avoid using the `Boolean` type. Did you mean `boolean`?", + }, + Number: { + message: "Avoid using the `Number` type. Did you mean `number`?", + }, + String: { + message: "Avoid using the `String` type. Did you mean `string`?", + }, + Symbol: { + message: "Avoid using the `Symbol` type. Did you mean `symbol`?", + }, + }, + }, + ], + "@typescript-eslint/consistent-type-assertions": "error", + "@typescript-eslint/consistent-type-definitions": "off", + "@typescript-eslint/explicit-member-accessibility": [ + "off", + { accessibility: "explicit" }, + ], + "@typescript-eslint/interface-name-prefix": "off", + "@typescript-eslint/member-ordering": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-misused-new": "error", + "@typescript-eslint/no-floating-promises": ["error"], // prevent those nasty forgotten promises ! + "@typescript-eslint/no-namespace": "off", + "@typescript-eslint/no-parameter-properties": "off", + "@typescript-eslint/no-this-alias": "error", + "@typescript-eslint/no-unused-expressions": "off", + "@typescript-eslint/no-use-before-define": "off", + "@typescript-eslint/no-var-requires": "error", + "@typescript-eslint/prefer-for-of": "error", + "@typescript-eslint/prefer-function-type": "error", + "@typescript-eslint/prefer-namespace-keyword": "error", + "@typescript-eslint/triple-slash-reference": [ + "error", + { + path: "always", + types: "prefer-import", + lib: "always", + }, + ], + "@typescript-eslint/type-annotation-spacing": "error", + "@typescript-eslint/unified-signatures": "error", + + // -- Rules form tsdoc + // "tsdoc/syntax": "warn", // TODO: enable once we have better tsdoc coverage + }, + parserOptions: { + ecmaVersion: 6, + sourceType: "module", + // Disable below extends and parser options if having performance issues + // https://github.com/typescript-eslint/typescript-eslint/blob/master/docs/getting-started/linting/TYPED_LINTING.md + tsconfigRootDir: __dirname, + project: "./tsconfig.json", + }, + settings: { + "import/extensions": [".js", ".jsx", ".ts", ".tsx"], + "import/parsers": { + "@typescript-eslint/parser": [".ts", ".tsx"], + }, + "import/resolver": { + node: { + extensions: [".js", ".jsx", ".ts", ".tsx"], + }, + // use /tsconfig.json + typescript: { + // "alwaysTryTypes": true, // always try to resolve types under `@types` directory even it doesn't contain any source code, like `@types/unist`, + // "directory": "./" + }, + }, + }, +}; diff --git a/ask-sdk-local-debug/.gitignore b/ask-sdk-local-debug/.gitignore new file mode 100644 index 00000000..b5cca64b --- /dev/null +++ b/ask-sdk-local-debug/.gitignore @@ -0,0 +1,11 @@ +coverage/ +dist/ +doc/ +node_modules/ +package-lock.json +.DS_Store +.idea/ +.vscode/ +build +package/ +*.tgz diff --git a/ask-sdk-local-debug/.npmignore b/ask-sdk-local-debug/.npmignore new file mode 100644 index 00000000..40982362 --- /dev/null +++ b/ask-sdk-local-debug/.npmignore @@ -0,0 +1,8 @@ +coverage/ +doc/ +lib/ +node_modules/ +tst/ +package-lock.json +tsconfig.json +tslint.json diff --git a/ask-sdk-local-debug/CHANGELOG.md b/ask-sdk-local-debug/CHANGELOG.md new file mode 100644 index 00000000..d64dd682 --- /dev/null +++ b/ask-sdk-local-debug/CHANGELOG.md @@ -0,0 +1,7 @@ +# Change Log + +# 1.0.0 (2020-07-21) + +This release contains the following changes : + +- Initial release for local development support for ASK SDK for Node.js. diff --git a/ask-sdk-local-debug/LICENSE b/ask-sdk-local-debug/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/ask-sdk-local-debug/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "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. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "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. + + "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). + + "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. + + "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." + + "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. + + 2. Grant of Copyright License. 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. + + 3. Grant of Patent License. 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. + + 4. Redistribution. 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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. + + 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. + + 5. Submission of Contributions. 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. + + 6. Trademarks. 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. + + 7. Disclaimer of Warranty. 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. + + 8. Limitation of Liability. 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. + + 9. Accepting Warranty or Additional Liability. 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + 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. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/ask-sdk-local-debug/NOTICE.txt b/ask-sdk-local-debug/NOTICE.txt new file mode 100644 index 00000000..11f43f55 --- /dev/null +++ b/ask-sdk-local-debug/NOTICE.txt @@ -0,0 +1,2 @@ +ASK SDK Local Debug for Node.js +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/ask-sdk-local-debug/README.md b/ask-sdk-local-debug/README.md new file mode 100644 index 00000000..68cdf8fa --- /dev/null +++ b/ask-sdk-local-debug/README.md @@ -0,0 +1,75 @@ +# ASK SDK Local Debug (Node.js) + +## About + +ASK SDK Local Debug is a package which enables you to test your skill code locally against your skill invocations by routing requests to your developer machine. This enables you to verify changes quickly to skill code as you can test without needing to deploy skill code to Lambda. + + +> NOTE: Feature is currently only available to customers in the NA region(https://developer.amazon.com/en-US/docs/alexa/custom-skills/develop-skills-in-multiple-languages.html#h2-multiple-endpoints). + +## Installation + +``` +`npm install --save ask-sdk-model@^1.29.0 +``npm install --save-dev ask-sdk-local-debug +` +``` + +## Configuration + +### USING Alexa SKills toolkit for VS code + +The [Alexa Skills Toolkit for Visual Studio](https://developer.amazon.com/en-US/docs/alexa/ask-toolkit/get-started-with-the-ask-toolkit-for-visual-studio-code.html) offer integrated support for local debugging. To get started, please review our technical documentation on how to [Test your local Alexa skill](https://developer.amazon.com/en-US/docs/alexa/ask-toolkit/vs-code-ask-skills.html#test) using VS Code. + + +> NOTE: If you have existing an ASK CLI profile, you will need to sign in again using the latest version of ASK CLI (>=2.13). Once installed, simply re-run `ask configure` to re-authorize your profile for local debugging. + +### USING with other IDEs and Debuggers + +1. To instantiate a connection to the local debugging service, execute the following from your skill’s `lambda` directory: +``` +node ./node_modules/ask-sdk-local-debug/dist/LocalDebuggerInvoker.js + --accessToken + --skillID + --skillEntryFile + --handlerName +``` + 1. ACCESS_TOKEN: + 1. Install ASK CLI v2 + 2. npm install ask-cli@2 -g + 3. Generate the accessToken using ASK CLI + 4. ask util generate-lwa-tokens --scopes alexa::ask:skills:debug + 5. You will be directed to a Login with Amazon page. Sign in and retrieve your ACCESS_TOKEN from the terminal. + 2. SKILL_ID: The ID of the skill you are trying to debug. Ensure that the developer account you used to login to obtain the access token has access to this skill. + 3. FILE_NAME: The path to your skill code's main file (typically `index.js`). This file or module contains the skill's handler function. + 4. HANDLER_NAME: The exported handler method (typically `handler`). For example, please see the [Hello world example](https://github.com/alexa/skill-sample-nodejs-hello-world/blob/master/lambda/custom/index.js#L159). +3. Configure your preferred IDE or other debugging tool to attach to the above process or execute directly from your preferred IDE. For example, in VS Code, this would be included in the `launch.json`: +``` +{ + "type": "node", + "request": "launch", + "name": "Skill Debug", + "program": "<5. Program>", + "args": [ + "--accessToken","", + "--skillId", "", + "--skillEntryFile", "", + "--handlerName" , "" + ] +} +``` + +## Things to note + +1. Local debugging is only available for a skill’s **`development`** stage. +2. A connection remains active for **1 hour. **You will need to reinstantiate the connection after 1 hour. +3. All Alexa requests for the skill will be routed to your development machine while the connection is active. +4. Only one connection session may be active for a given skill ID and developer account. + +## Opening Issues + +For bug reports, feature requests and questions, we would like to hear about it. Search the [existing issues](https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs/issues) and try to make sure your problem doesn’t already exist before opening a new issue. It’s helpful if you include the version of the SDK, Node.js or browser environment and OS you’re using. Please include a stack trace and reduced repro case when appropriate, too. + +## License + +This SDK is distributed under the Apache License, Version 2.0, see LICENSE for more information. diff --git a/ask-sdk-local-debug/lib/LocalDebuggerInvoker.ts b/ask-sdk-local-debug/lib/LocalDebuggerInvoker.ts new file mode 100644 index 00000000..567538be --- /dev/null +++ b/ask-sdk-local-debug/lib/LocalDebuggerInvoker.ts @@ -0,0 +1,44 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import WsClient from 'ws'; +import { ClientConfigBuilder } from './builder/ClientConfigBuilder'; +import { SkillInvokerConfigBuilder } from './builder/SkillInvokerConfigBuilder'; +import { WebSocketClientConfigBuilder } from './builder/WebSocketClientConfigBuilder'; +import { LocalDebugClient } from './client/LocalDebugClient'; +import { argsParser } from './util/ArgsParserUtils'; + +const { argv } = argsParser(); + +const clientConfig = new ClientConfigBuilder() + .withAccessToken(argv.accessToken) + .withHandlerName(argv.handlerName) + .withSkillEntryFile(argv.skillEntryFile) + .withSkillId(argv.skillId) + .build(); + +const skillInvokerConfig = new SkillInvokerConfigBuilder() + // eslint-disable-next-line import/no-dynamic-require + .withHandler(require(clientConfig.skillEntryFile)[clientConfig.handlerName]) + .build(); + +const webSocketClientConfig = new WebSocketClientConfigBuilder() + .withSkillId(clientConfig.skillId) + .withAccessToken(clientConfig.accessToken) + .build(); + +const webSocketClient = new WsClient(webSocketClientConfig.webSocketServerUri, { + headers: webSocketClientConfig.headers, +}); + +const client = new LocalDebugClient(webSocketClient, skillInvokerConfig); diff --git a/ask-sdk-local-debug/lib/builder/ClientConfigBuilder.ts b/ask-sdk-local-debug/lib/builder/ClientConfigBuilder.ts new file mode 100644 index 00000000..b8221fee --- /dev/null +++ b/ask-sdk-local-debug/lib/builder/ClientConfigBuilder.ts @@ -0,0 +1,68 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { ClientConfig } from '../config/ClientConfig'; + +export class ClientConfigBuilder { + private _skillEntryFile: string; + + private _handlerName: string; + + private _accessToken: string; + + private _skillId: string; + + public withSkillEntryFile(skillEntryFile: string): ClientConfigBuilder { + this._skillEntryFile = skillEntryFile; + + return this; + } + + public withHandlerName(handlerName: string): ClientConfigBuilder { + this._handlerName = handlerName; + + return this; + } + + public withAccessToken(accessToken: string): ClientConfigBuilder { + this._accessToken = accessToken; + + return this; + } + + public withSkillId(skillId: string): ClientConfigBuilder { + this._skillId = skillId; + + return this; + } + + public get skillEntryFile(): string { + return this._skillEntryFile; + } + + public get handlerName(): string { + return this._handlerName; + } + + public get accessToken(): string { + return this._accessToken; + } + + public get skillId(): string { + return this._skillId; + } + + public build(): ClientConfig { + return new ClientConfig(this); + } +} diff --git a/ask-sdk-local-debug/lib/builder/SkillInvokerConfigBuilder.ts b/ask-sdk-local-debug/lib/builder/SkillInvokerConfigBuilder.ts new file mode 100644 index 00000000..977489ef --- /dev/null +++ b/ask-sdk-local-debug/lib/builder/SkillInvokerConfigBuilder.ts @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { LambdaHandler } from 'ask-sdk-core'; +import { SkillInvokerConfig } from '../config/SkillInvokerConfig'; + +export class SkillInvokerConfigBuilder { + private _skillHandler: LambdaHandler; + + public withHandler(handlerName: LambdaHandler): SkillInvokerConfigBuilder { + this._skillHandler = handlerName; + + return this; + } + + public get handler(): LambdaHandler { + return this._skillHandler; + } + + public build(): SkillInvokerConfig { + return new SkillInvokerConfig(this); + } +} diff --git a/ask-sdk-local-debug/lib/builder/WebSocketClientConfigBuilder.ts b/ask-sdk-local-debug/lib/builder/WebSocketClientConfigBuilder.ts new file mode 100644 index 00000000..699efc53 --- /dev/null +++ b/ask-sdk-local-debug/lib/builder/WebSocketClientConfigBuilder.ts @@ -0,0 +1,44 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { WebSocketClientConfig } from '../config/WebSocketClientConfig'; + +export class WebSocketClientConfigBuilder { + private _webSocketServerUri: string; + + private _headers: {}; + + public withSkillId(skillId: string): WebSocketClientConfigBuilder { + this._webSocketServerUri = `wss://bob-dispatch-prod-na.amazon.com/v1/skills/${skillId}/stages/development/connectCustomDebugEndpoint`; + + return this; + } + + public withAccessToken(accessToken: string): WebSocketClientConfigBuilder { + this._headers = { authorization: accessToken }; + + return this; + } + + public get webSocketServerUri(): string { + return this._webSocketServerUri; + } + + public get headers(): {} { + return this._headers; + } + + public build(): WebSocketClientConfig { + return new WebSocketClientConfig(this); + } +} diff --git a/ask-sdk-local-debug/lib/client/ILocalDebugClient.ts b/ask-sdk-local-debug/lib/client/ILocalDebugClient.ts new file mode 100644 index 00000000..8ccae6ff --- /dev/null +++ b/ask-sdk-local-debug/lib/client/ILocalDebugClient.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import WebSocket from 'ws'; + +export interface ILocalDebugClient { + connectedEvent(): void; + + messageEvent(data: WebSocket.Data): void; + + errorEvent(event: WebSocket.ErrorEvent): void; + + closeEvent(event: WebSocket.CloseEvent): void; + + sendResponse(responseString: string): void; +} diff --git a/ask-sdk-local-debug/lib/client/LocalDebugClient.ts b/ask-sdk-local-debug/lib/client/LocalDebugClient.ts new file mode 100644 index 00000000..c8d19875 --- /dev/null +++ b/ask-sdk-local-debug/lib/client/LocalDebugClient.ts @@ -0,0 +1,80 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import WebSocket from 'ws'; +import { SkillInvokerConfig } from '../config/SkillInvokerConfig'; +import { getDynamicEndpointsRequest, getSkillResponse } from '../util/RequestResponseUtils'; +import { ILocalDebugClient } from './ILocalDebugClient'; + +const PING_FREQUENCY_IN_MILLISECONDS = 5 * 60 * 1000; + +export class LocalDebugClient implements ILocalDebugClient { + private readonly _skillInvokerConfig: SkillInvokerConfig; + + private readonly _webSocketClient: WebSocket; + + private readonly heartbeat: NodeJS.Timeout; + + constructor(webSocketClient: WebSocket, skillInvokerConfig: SkillInvokerConfig) { + this._skillInvokerConfig = skillInvokerConfig; + this._webSocketClient = webSocketClient; + this.configureClientEvents(); + this.heartbeat = setInterval(() => { + if (this._webSocketClient.readyState === 1) { + this._webSocketClient.ping('heartbeat'); + } + }, PING_FREQUENCY_IN_MILLISECONDS); + } + + private configureClientEvents(): void { + this._webSocketClient.onopen = (event) => { + this.connectedEvent(); + }; + this._webSocketClient.onmessage = (event) => { + this.messageEvent(event.data); + }; + this._webSocketClient.onerror = (event) => { + this.errorEvent(event); + }; + this._webSocketClient.onclose = (event) => { + this.closeEvent(event); + }; + } + + public connectedEvent(): void { + console.log('*****Starting Skill Debug Session in NA region*****', '\n'); + console.log('*****NOTE: Skill debugging is currently only available for invocations from customer in North America region (https://developer.amazon.com/en-US/docs/alexa/custom-skills/develop-skills-in-multiple-languages.html#h2-multiple-endpoints)*****', '\n'); + console.log('*****Session will last for 1 hour*****', '\n'); + } + + public messageEvent(data: WebSocket.Data): void { + console.log('Skill request', '\n', JSON.stringify(JSON.parse(data.toString()), null, 2), '\n'); + const dynamicEndpointsRequest = getDynamicEndpointsRequest(data.toString()); + getSkillResponse(dynamicEndpointsRequest, this._skillInvokerConfig, (responseString) => { + this.sendResponse(responseString); + }); + } + + public sendResponse(responseString: string): void { + this._webSocketClient.send(responseString); + } + + public errorEvent(event: WebSocket.ErrorEvent): void { + console.error('WebSocket error:', event.message); + } + + public closeEvent(event: WebSocket.CloseEvent): void { + console.log('WebSocket is closed:', event); + clearInterval(this.heartbeat); + } +} diff --git a/ask-sdk-local-debug/lib/config/ClientConfig.ts b/ask-sdk-local-debug/lib/config/ClientConfig.ts new file mode 100644 index 00000000..6ea84192 --- /dev/null +++ b/ask-sdk-local-debug/lib/config/ClientConfig.ts @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { ClientConfigBuilder } from '../builder/ClientConfigBuilder'; + +export class ClientConfig { + private readonly _accessToken: string; + + private readonly _skillId: string; + + private readonly _handlerName: string; + + private readonly _skillEntryFile: string; + + constructor(clientConfigBuilder: ClientConfigBuilder) { + this._skillEntryFile = clientConfigBuilder.skillEntryFile; + this._handlerName = clientConfigBuilder.handlerName; + this._accessToken = clientConfigBuilder.accessToken; + this._skillId = clientConfigBuilder.skillId; + } + + public get skillEntryFile(): string { + return this._skillEntryFile; + } + + public get skillId(): string { + return this._skillId; + } + + public get handlerName(): string { + return this._handlerName; + } + + public get accessToken(): string { + return this._accessToken; + } +} diff --git a/ask-sdk-local-debug/lib/config/SkillInvokerConfig.ts b/ask-sdk-local-debug/lib/config/SkillInvokerConfig.ts new file mode 100644 index 00000000..3106772f --- /dev/null +++ b/ask-sdk-local-debug/lib/config/SkillInvokerConfig.ts @@ -0,0 +1,27 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { LambdaHandler } from 'ask-sdk-core'; +import { SkillInvokerConfigBuilder } from '../builder/SkillInvokerConfigBuilder'; + +export class SkillInvokerConfig { + public readonly _handler: LambdaHandler; + + constructor(skillInvokerConfigBuilder: SkillInvokerConfigBuilder) { + this._handler = skillInvokerConfigBuilder.handler; + } + + public get handler(): LambdaHandler { + return this._handler; + } +} diff --git a/ask-sdk-local-debug/lib/config/WebSocketClientConfig.ts b/ask-sdk-local-debug/lib/config/WebSocketClientConfig.ts new file mode 100644 index 00000000..e18cbd52 --- /dev/null +++ b/ask-sdk-local-debug/lib/config/WebSocketClientConfig.ts @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { WebSocketClientConfigBuilder } from '../builder/WebSocketClientConfigBuilder'; + +export class WebSocketClientConfig { + private readonly _webSocketServerUri: string; + + private readonly _headers: {}; + + constructor(webSocketClientConfigBuilder: WebSocketClientConfigBuilder) { + this._webSocketServerUri = webSocketClientConfigBuilder.webSocketServerUri; + this._headers = webSocketClientConfigBuilder.headers; + } + + public get webSocketServerUri(): string { + return this._webSocketServerUri; + } + + public get headers(): {} { + return this._headers; + } +} diff --git a/ask-sdk-local-debug/lib/request/DynamicEndpointsRequest.ts b/ask-sdk-local-debug/lib/request/DynamicEndpointsRequest.ts new file mode 100644 index 00000000..ffe6d9e6 --- /dev/null +++ b/ask-sdk-local-debug/lib/request/DynamicEndpointsRequest.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { dynamicEndpoints } from 'ask-sdk-model'; + +export class DynamicEndpointsRequest implements dynamicEndpoints.Request { + public version: string; + + public type: string; + + public requestId: string; + + public requestPayload: string; +} diff --git a/ask-sdk-local-debug/lib/util/ArgsParserUtils.ts b/ask-sdk-local-debug/lib/util/ArgsParserUtils.ts new file mode 100644 index 00000000..e57f566a --- /dev/null +++ b/ask-sdk-local-debug/lib/util/ArgsParserUtils.ts @@ -0,0 +1,76 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { option } from 'yargs'; +import { existsSync } from 'fs'; + +export function argsParser(): any { + return option({ + accessToken: { + type: 'string', + description: 'Access Token', + demandOption: true, + requiresArg: true, + }, + skillId: { + type: 'string', + description: 'Skill id', + demandOption: true, + requiresArg: true, + }, + handlerName: { + type: 'string', + description: 'Handler method to invoke in your skillEntryFile', + demandOption: true, + requiresArg: true, + }, + skillEntryFile: { + type: 'string', + description: 'Skill entry file', + demandOption: true, + requiresArg: true, + }, + }) + .check((argv) => { + if (argv.accessToken == null) { + console.error('Access Token cannot be null or empty.'); + return false; + } + return true; + }) + .check((argv) => { + if (argv.skillId == null) { + console.error('Skill Id cannot be null or empty.'); + return false; + } + return true; + }) + .check((argv) => { + if (argv.handlerName == null) { + console.error('Handler name cannot be null or empty.'); + return false; + } + return true; + }) + .check((argv) => { + if (argv.skillEntryFile == null) { + console.error('Skill entry file cannot be null or empty.'); + return false; + } + if (!existsSync(argv.skillEntryFile)) { + console.error('Skill entry file does not exist.'); + return false; + } + return true; + }); +} diff --git a/ask-sdk-local-debug/lib/util/RequestResponseUtils.ts b/ask-sdk-local-debug/lib/util/RequestResponseUtils.ts new file mode 100644 index 00000000..93e96c3d --- /dev/null +++ b/ask-sdk-local-debug/lib/util/RequestResponseUtils.ts @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the 'license' file accompanying this file. This file 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. + */ + +import { dynamicEndpoints } from 'ask-sdk-model'; +import { SkillInvokerConfig } from '../config/SkillInvokerConfig'; +import { DynamicEndpointsRequest } from '../request/DynamicEndpointsRequest'; + +export function getDynamicEndpointsRequest(skillRequest: string): DynamicEndpointsRequest { + return { DynamicEndpointsRequest, ...JSON.parse(skillRequest) }; +} + +const ERROR_CODE = '500'; + +const SKILL_RESPONSE_SUCCESS_MESSAGE_TYPE = 'SkillResponseSuccessMessage'; + +const SKILL_RESPONSE_FAILURE_MESSAGE_TYPE = 'SkillResponseFailureMessage'; + +export function getSkillResponse(dynamicEndpointsRequest: DynamicEndpointsRequest, + skillInvokerConfig: SkillInvokerConfig, + callback: (responseString: string) => void): void { + skillInvokerConfig.handler(JSON.parse(dynamicEndpointsRequest.requestPayload), + null, (_invokeErr: Error, response: any) => { + let responseString: string; + if (_invokeErr == null) { + const successResponse: dynamicEndpoints.SuccessResponse = { + type: SKILL_RESPONSE_SUCCESS_MESSAGE_TYPE, + originalRequestId: dynamicEndpointsRequest.requestId, + version: dynamicEndpointsRequest.version, + responsePayload: JSON.stringify(response), + }; + responseString = JSON.stringify(successResponse, null, 2); + } else { + const failureResponse: dynamicEndpoints.FailureResponse = { + type: SKILL_RESPONSE_FAILURE_MESSAGE_TYPE, + version: dynamicEndpointsRequest.version, + originalRequestId: dynamicEndpointsRequest.requestId, + errorCode: ERROR_CODE, + errorMessage: _invokeErr.message, + }; + responseString = JSON.stringify(failureResponse, null, 2); + } + console.log('Skill response', '\n', responseString); + console.log('----------------------'); + callback(responseString); + }); +} diff --git a/ask-sdk-local-debug/package.json b/ask-sdk-local-debug/package.json new file mode 100644 index 00000000..c68eeb16 --- /dev/null +++ b/ask-sdk-local-debug/package.json @@ -0,0 +1,51 @@ +{ + "name": "ask-sdk-local-debug", + "version": "1.0.0", + "description": "Local debug package for Alexa Skills Kit SDK", + "main": "dist/client/WebSocketClient.js", + "types": "dist/client/WebSocketClient.d.ts", + "scripts": { + "lint": "eslint . --ext .ts", + "lint-and-fix": "eslint . --ext .ts --fix", + "compile": "tsc", + "mkdir": "mkdir -p build/lib/commonjs/ask-sdk-local-debug", + "copy-pkg": "cp package.json build/lib/commonjs/ask-sdk-local-debug/", + "copy-dist": "cp -r dist build/lib/commonjs/ask-sdk-local-debug/", + "copy-src": "cp -r lib build/lib/commonjs/ask-sdk-local-debug/", + "copy-tst": "cp -r tst build/lib/commonjs/ask-sdk-local-debug/", + "copy": "npm run mkdir && npm run copy-pkg && npm run copy-src && npm run copy-dist", + "cleanup": "rm -rf dist", + "start": "npm run lint && npm run cleanup && npm run compile && npm run copy", + "release": "npm run start", + "pack": "npm run release && npm pack" + }, + "author": "Amazon.com", + "license": "Apache-2.0", + "devDependencies": { + "@types/node": "^14.0.10", + "@types/ws": "^7.2.4", + "@types/yargs": "^15.0.5", + "@typescript-eslint/eslint-plugin": "^2.34.0", + "@typescript-eslint/parser": "^2.34.0", + "ask-sdk-model": "^1.28.1", + "ask-sdk-core": "^2.8.0", + "eslint-config-airbnb": "^18.2.0", + "eslint-import-resolver-typescript": "^2.0.0", + "eslint-config-prettier": "^6.11.0", + "eslint-plugin-import": "^2.21.2", + "eslint-plugin-json": "^2.1.1", + "eslint-plugin-jsx-a11y": "^5.1.1", + "eslint-plugin-prettier": "^3.1.4", + "eslint-plugin-react": "^7.20.0", + "eslint-plugin-eslint-comments": "^3.2.0", + "prettier": "^2.0.5", + "eslint": "^6.8.0", + "ts-node": "^8.10.2", + "tsc-watch": "^4.2.3", + "typescript": "^3.9.5" + }, + "dependencies": { + "ws": "^7.3.0", + "yargs": "^15.3.1" + } +} diff --git a/ask-sdk-local-debug/tsconfig.json b/ask-sdk-local-debug/tsconfig.json new file mode 100644 index 00000000..dcb675d0 --- /dev/null +++ b/ask-sdk-local-debug/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "outDir": "./dist", + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "target": "es6", + "noImplicitAny": true, + "moduleResolution": "node", + "sourceMap": true, + "baseUrl": ".", + "paths": { + "*": ["node_modules/*"] + } + }, + "include": ["lib/**/*"] +}