├── .gitignore ├── .npmignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── declarations.d.ts ├── demo ├── simple │ ├── demoFunctions.js │ ├── index.html │ └── layout.js └── typescript-project │ ├── .gitignore │ ├── README.md │ ├── deploy │ └── index.html │ ├── package.json │ ├── src │ ├── Application.ts │ └── index.ts │ ├── tsconfig.json │ └── webpack.config.js ├── es6 ├── ApiAiClient.js ├── ApiAiConstants.js ├── Errors.js ├── Interfaces.js ├── Request │ ├── EventRequest.js │ ├── Request.js │ └── TextRequest.js └── XhrRequest.js ├── index.js ├── index.ts ├── karma.conf.js ├── package.json ├── spec ├── Client.spec.ts ├── Utils.spec.ts └── api.spec.ts ├── target ├── ApiAi.js ├── ApiAi.min.js ├── ApiAi.streamless.js └── ApiAi.streamless.min.js ├── ts ├── ApiAiClient.ts ├── ApiAiConstants.ts ├── Errors.ts ├── Interfaces.ts ├── Models │ └── Entity.ts ├── Request │ ├── ContextsRequest.ts │ ├── EventRequest.ts │ ├── LocalTTSRequest.ts │ ├── Request.ts │ ├── TTSRequest.ts │ ├── TextRequest.ts │ ├── UserEntitiesRequest.ts │ └── VoiceRequest.ts ├── Utils.ts └── XhrRequest.ts ├── tsconfig.es6.json ├── tsconfig.json ├── tslint.json └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .vscode 3 | api-ai-javascript.iml 4 | npm-debug.log 5 | node_modules 6 | target/ApiAi.js.map 7 | target/ApiAi.min.js.map 8 | target/ApiAi.streamless.js.map 9 | target/ApiAi.commonjs2.js.map 10 | .DS_Store 11 | demo/.DS_Store -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | demo 2 | spec 3 | target 4 | karma.conf.js 5 | tsconfig.es6src.json 6 | tsconfig.json 7 | tslint.json 8 | webpack.config.js -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). 15 | 16 | Follow either of the two links above to access the appropriate CLA and 17 | instructions for how to sign and return it. Once we receive it, we'll be able to 18 | accept your pull requests. 19 | 20 | ## Contributing A Patch 21 | 22 | 1. Submit an issue describing your proposed change to the repo in question. 23 | 1. The repo owner will respond to your issue promptly. 24 | 1. If your proposed change is accepted, and you haven't already done so, sign a 25 | Contributor License Agreement (see details above). 26 | 1. Fork the desired repo, develop and test your code changes. 27 | 1. Ensure that your code adheres to the existing style in the sample to which 28 | you are contributing. Refer to the 29 | [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the 30 | recommended coding standards for this organization. 31 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 32 | 1. Submit a pull request. 33 | -------------------------------------------------------------------------------- /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, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # DEPRECATED 3 | 4 | | Deprecated | 5 | |-------| 6 | | This Dialogflow client library and Dialogflow API V1 [have been deprecated and will be shut down on October 23th, 2019](https://blog.dialogflow.com/post/migrate-to-dialogflow-api-v2/). Please [migrate to Dialogflow API V2](https://cloud.google.com/dialogflow-enterprise/docs/migrating). | 7 | 8 | You can use this library as common pre-built .js ([choose there](target)). 9 | 10 | Or you can install it with nodejs and that import as es6 (or .ts) module. See below. 11 | 12 | `npm install api-ai-javascript@2.0.0-beta.14` 13 | 14 | 15 | # Usage 16 | 17 | ## .textRequest 18 | 19 | ```javascript 20 | 21 | const client = new ApiAi.ApiAiClient({accessToken: 'YOUR_ACCESS_TOKEN'}); 22 | const promise = client.textRequest(longTextRequest); 23 | 24 | promise 25 | .then(handleResponse) 26 | .catch(handleError); 27 | 28 | function handleResponse(serverResponse) { 29 | console.log(serverResponse); 30 | } 31 | function handleError(serverError) { 32 | console.log(serverError); 33 | } 34 | 35 | ``` 36 | 37 | ## .eventRequest 38 | 39 | ```javascript 40 | const promise = client.eventRequest("EVENT_NAME", options); 41 | ``` 42 | 43 | # TypeScript and ES6 44 | 45 | This SDK written with Typescript and all it's sources are available in this package. So basically if you are using something like *webpack* or *browserify* with ES6 imports and so on, you can just install this SDK with `$ npm install api-ai-javascript --save-dev` command and then import original sources with something like: 46 | 47 | ```javascript 48 | 49 | import {ApiAiClient} from "api-ai-javascript"; 50 | 51 | const client = new ApiAiClient({accessToken: 'YOUR_ACCESS_TOKEN'}) 52 | 53 | .textRequest('Hello!') 54 | .then((response) => {/* do something */}) 55 | .catch((error) => {/* do something here too */}) 56 | 57 | ``` 58 | 59 | *Note:* If you are going to build es5 version of your bundle with ApiAiClient inside, please add some typings for promises (e.g. @types/es6-promise) 60 | 61 | You also can import and use all defined interfaces and ApiAiConstants: 62 | 63 | ```javascript 64 | import {IRequestOptions, IServerResponse, ApiAiConstants} from "api-ai-javascript/ApiAiClient" 65 | const lang = ApiAiConstants.AVAILABLE_LANGUAGES.EN; 66 | ``` 67 | 68 | You can find full list of interfaces [here](ts/Interfaces.ts) 69 | 70 | # Development 71 | 72 | * Checkout from this repository, do not forget to switch to "v2" branch 73 | * run `$ npm install` 74 | * run `$ webpack -w` or just `$ npm start` (as an option for non globally installed dev-server - `$ ./node_modules/.bin/webpack-dev-server`) 75 | * develop! (webpack will automatically compile SDK to ./target/ApiAi.js file on each change, just include it into some test HTML file (./demo/index.html will probably do the job) and test it). 76 | 77 | # Building 78 | 79 | `$ npm run-script build` command will build everything 80 | 81 | # Testing 82 | 83 | `$ npm test` 84 | 85 | ## Changelog 86 | 87 | ## 2.0.0-beta.21 88 | * tts and asr support removed (discontinued on API.AI side) 89 | ## 2.0.0-beta.19 90 | * minor typings changes 91 | ## 2.0.0-beta.18 92 | * some minor typings changes 93 | ## 2.0.0-beta.17 94 | * dependencies updated 95 | * webrtc typings removed (now part of typescript default lib) 96 | ## 2.0.0-beta.16 97 | * some linting (ionic2 compatibility issues) 98 | ## 2.0.0-beta.15 99 | * minor fixes, minor readme updates 100 | * exported constants 101 | ## 2.0.0-beta.14 102 | * minor fixes 103 | * GainNode removed (for now) as non-working in current setup 104 | ## 2.0.0-beta.13 105 | * IStreamClient is aligned with StreamClient needs, thanks to @muuki88 (#26) 106 | * Callbacks in IStremClientOptions are now typed properly 107 | * Added IStreamClient.getGain(): GainNode (#25) to allow set up gain of listener 108 | * Fixed UTF8 requests, thanks to @elaval (#24) 109 | ## 2.0.0-beta.12 110 | * Possibility to import ApiAiClient separately from ApiAiStreamClient 111 | * Typescript project demo setup added 112 | ## 2.0.0-beta.8 113 | ### Breaking changes: 114 | * Main class renamed from Client to ApiAiClient 115 | * StreamClient renamed (in exports at least) to ApiAiStreamClient 116 | * StreamClient class is no longer available inside main ApiAiClient class and now should be passed directly in ApiAiClient constructor: `const client = new ApiAiClient("ACCESS_TOKEN", {streamClientClass: ApiAiStreamClient})`.That was made to allow building your applications without streamclient at all (streamclient now takes about 70% of whole library). And also there will be other implementation of streamClient in the future 117 | ### Non-breaking changes: 118 | * Demo updated 119 | 120 | ## How to make contributions? 121 | Please read and follow the steps in the [CONTRIBUTING.md](CONTRIBUTING.md). 122 | 123 | ## License 124 | See [LICENSE](LICENSE). 125 | 126 | ## Terms 127 | Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/). 128 | 129 | This is not an official Google product. 130 | -------------------------------------------------------------------------------- /declarations.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | interface Navigator { 18 | Resampler: any; 19 | webkitGetUserMedia: any; 20 | mozGetUserMedia: any; 21 | } 22 | interface AudioContext { 23 | createResampleProcessor: Function; 24 | createEndOfSpeechProcessor: Function; 25 | } 26 | interface Window { 27 | webkitURL: any; 28 | } 29 | 30 | declare var webkitAudioContext: { 31 | new (): AudioContext; 32 | } 33 | 34 | declare var webkitOfflineAudioContext: { 35 | new (numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; 36 | } 37 | 38 | interface AudioContextConstructor { 39 | new(): AudioContext; 40 | } 41 | 42 | interface Window { 43 | AudioContext: AudioContextConstructor; 44 | } 45 | 46 | interface AudioContext { 47 | createMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode; 48 | } 49 | 50 | interface MediaStreamAudioSourceNode extends AudioNode { 51 | 52 | } 53 | 54 | interface MediaStreamAudioDestinationNode extends AudioNode { 55 | stream: MediaStream; 56 | } 57 | 58 | interface AudioBuffer { 59 | copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; 60 | 61 | copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; 62 | } 63 | 64 | interface AudioNode { 65 | disconnect(destination: AudioNode): void; 66 | } 67 | 68 | interface AudioContext { 69 | suspend(): Promise; 70 | resume(): Promise; 71 | close(): Promise; 72 | createMediaStreamDestination(): MediaStreamAudioDestinationNode; 73 | } 74 | -------------------------------------------------------------------------------- /demo/simple/demoFunctions.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | "use strict"; 18 | 19 | /** 20 | * All this stuff is moved into global namespace and separate files just to be 21 | * MAXIMUM clear and easy to understand 22 | */ 23 | 24 | var client; 25 | window.init = function(token) { 26 | client = new ApiAi.ApiAiClient({accessToken: token}); 27 | }; 28 | 29 | function sendText(text) { 30 | return client.textRequest(text); 31 | } 32 | -------------------------------------------------------------------------------- /demo/simple/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Title 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 26 | 27 | 28 |
29 |
30 |
Configure demo:
31 |
32 |
33 |
34 | 35 | 36 |
37 |
38 | Set 39 |
40 |
41 |
42 |
43 |
Please, fill access token before start
44 |
45 |
46 |
47 |
48 |
49 |
50 | 51 |
52 |
53 | 55 |
56 |
57 |
58 |
59 | 61 |
Response payload:
62 |

63 |             
64 |
65 |
66 |
67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /demo/simple/layout.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | (function() { 18 | "use strict"; 19 | 20 | var ENTER_KEY_CODE = 13; 21 | var queryInput, resultDiv, accessTokenInput; 22 | 23 | window.onload = init; 24 | 25 | function init() { 26 | queryInput = document.getElementById("q"); 27 | resultDiv = document.getElementById("result"); 28 | accessTokenInput = document.getElementById("access_token"); 29 | var setAccessTokenButton = document.getElementById("set_access_token"); 30 | 31 | queryInput.addEventListener("keydown", queryInputKeyDown); 32 | setAccessTokenButton.addEventListener("click", setAccessToken); 33 | } 34 | 35 | function setAccessToken() { 36 | document.getElementById("placeholder").style.display = "none"; 37 | document.getElementById("main-wrapper").style.display = "block"; 38 | window.init(accessTokenInput.value); 39 | } 40 | 41 | function queryInputKeyDown(event) { 42 | if (event.which !== ENTER_KEY_CODE) { 43 | return; 44 | } 45 | 46 | var value = queryInput.value; 47 | queryInput.value = ""; 48 | 49 | createQueryNode(value); 50 | var responseNode = createResponseNode(); 51 | 52 | sendText(value) 53 | .then(function(response) { 54 | var result; 55 | try { 56 | result = response.result.fulfillment.speech 57 | } catch(error) { 58 | result = ""; 59 | } 60 | setResponseJSON(response); 61 | setResponseOnNode(result, responseNode); 62 | }) 63 | .catch(function(err) { 64 | setResponseJSON(err); 65 | setResponseOnNode("Something goes wrong", responseNode); 66 | }); 67 | } 68 | 69 | function createQueryNode(query) { 70 | var node = document.createElement('div'); 71 | node.className = "clearfix left-align left card-panel green accent-1"; 72 | node.innerHTML = query; 73 | resultDiv.appendChild(node); 74 | } 75 | 76 | function createResponseNode() { 77 | var node = document.createElement('div'); 78 | node.className = "clearfix right-align right card-panel blue-text text-darken-2 hoverable"; 79 | node.innerHTML = "..."; 80 | resultDiv.appendChild(node); 81 | return node; 82 | } 83 | 84 | function setResponseOnNode(response, node) { 85 | node.innerHTML = response ? response : "[empty response]"; 86 | node.setAttribute('data-actual-response', response); 87 | } 88 | 89 | function setResponseJSON(response) { 90 | var node = document.getElementById("jsonResponse"); 91 | node.innerHTML = JSON.stringify(response, null, 2); 92 | } 93 | 94 | function sendRequest() { 95 | 96 | } 97 | 98 | })(); 99 | -------------------------------------------------------------------------------- /demo/typescript-project/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | deploy/*.js -------------------------------------------------------------------------------- /demo/typescript-project/README.md: -------------------------------------------------------------------------------- 1 | This is the sample typescript setup with usage of api-ai-javascript library inside. 2 | 3 | Installation: 4 | 5 | `$ npm install` 6 | 7 | Running (webpack-dev-server on localhost:8080 by default): 8 | 9 | `$ npm start` 10 | -------------------------------------------------------------------------------- /demo/typescript-project/deploy/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |

Open dev-console to see logs

8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /demo/typescript-project/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-ai-javascript-typescript-demo-project", 3 | "version": "2.0.0-beta.20", 4 | "description": "Javascript SDK for https://api.ai/ typescript demo project", 5 | "devDependencies": { 6 | "@types/es6-promise": "0.0.32", 7 | "api-ai-javascript": "^2.0.0-beta.21", 8 | "awesome-typescript-loader": "^3.0.8", 9 | "typescript": "^2.2.1", 10 | "webpack": "^2.2.1", 11 | "webpack-dev-server": "^2.4.1" 12 | }, 13 | "scripts": { 14 | "build": "webpack", 15 | "start": "webpack-dev-server" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "git+https://github.com/api-ai/api-ai-javascript.git" 20 | }, 21 | "author": "Eugeny Shingarev", 22 | "license": "Apache-2.0", 23 | "bugs": { 24 | "url": "https://github.com/api-ai/api-ai-javascript/issues" 25 | }, 26 | "homepage": "https://github.com/api-ai/api-ai-javascript#readme" 27 | } 28 | -------------------------------------------------------------------------------- /demo/typescript-project/src/Application.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient, IStreamClient} from "api-ai-javascript/ApiAiClient"; 18 | import {ApiAiStreamClient} from "api-ai-javascript/ApiAiStreamClient"; 19 | 20 | export class ApiAiEnabledApplication { 21 | 22 | private static BUTTON_ID = "button"; 23 | 24 | private apiAiClient: ApiAiClient; 25 | private button: HTMLButtonElement; 26 | 27 | private isListening: boolean = false; 28 | 29 | public init(accessToken: string): ApiAiEnabledApplication { 30 | 31 | this.apiAiClient = new ApiAiClient({accessToken, streamClientClass: ApiAiStreamClient}); 32 | this.button = document.getElementById(ApiAiEnabledApplication.BUTTON_ID) as HTMLButtonElement; 33 | this.button.addEventListener("click", this.handleClick.bind(this)); 34 | return this; 35 | } 36 | 37 | private handleClick() { 38 | this.apiAiClient.textRequest("test").then((response) => { 39 | console.log(response); 40 | }); 41 | } 42 | 43 | private setIsListening(isListening: boolean) { 44 | this.isListening = isListening; 45 | this.button.innerText = (isListening) ? "Stop listening" : "Start listening"; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /demo/typescript-project/src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiEnabledApplication} from "./Application"; 18 | const app = new ApiAiEnabledApplication(); 19 | 20 | app.init("ACCESS_TOKEN"); 21 | 22 | 23 | window["app"] = app; 24 | -------------------------------------------------------------------------------- /demo/typescript-project/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES5", 4 | "moduleResolution": "node", 5 | "typeRoots": ["./node_modules/@types"] 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /demo/typescript-project/webpack.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | "use strict"; 18 | 19 | const webpack = require('webpack'); 20 | const path = require('path'); 21 | 22 | module.exports = { 23 | entry: [ 24 | path.join(__dirname, 'src', 'index.ts') 25 | ], 26 | output: { 27 | path: path.join(__dirname, 'deploy'), 28 | publicPath: "/deploy", 29 | filename: 'index.js' 30 | }, 31 | plugins: [ 32 | new webpack.LoaderOptionsPlugin({ 33 | minimize: true, 34 | debug: false 35 | }), 36 | new webpack.optimize.UglifyJsPlugin({ 37 | compress: { 38 | warnings: true 39 | }, 40 | output: { 41 | comments: false 42 | }, 43 | sourceMap: false 44 | }) 45 | ], 46 | module: { 47 | loaders: [ 48 | {test: /\.tsx?$/, loader: "awesome-typescript-loader"} 49 | ] 50 | }, 51 | resolve: { 52 | modules: [ 53 | 'node_modules', 54 | path.resolve(__dirname, 'app') 55 | ], 56 | extensions: ['.ts', '.js'] 57 | }, 58 | devServer: { 59 | port: 8000 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /es6/ApiAiClient.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { ApiAiConstants } from "./ApiAiConstants"; 18 | import { ApiAiClientConfigurationError } from "./Errors"; 19 | import { EventRequest } from "./Request/EventRequest"; 20 | import TextRequest from "./Request/TextRequest"; 21 | export * from "./Interfaces"; 22 | export { ApiAiConstants } from "./ApiAiConstants"; 23 | export class ApiAiClient { 24 | constructor(options) { 25 | if (!options || !options.accessToken) { 26 | throw new ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance"); 27 | } 28 | this.accessToken = options.accessToken; 29 | this.apiLang = options.lang || ApiAiConstants.DEFAULT_CLIENT_LANG; 30 | this.apiVersion = options.version || ApiAiConstants.DEFAULT_API_VERSION; 31 | this.apiBaseUrl = options.baseUrl || ApiAiConstants.DEFAULT_BASE_URL; 32 | this.sessionId = options.sessionId || this.guid(); 33 | } 34 | textRequest(query, options = {}) { 35 | if (!query) { 36 | throw new ApiAiClientConfigurationError("Query should not be empty"); 37 | } 38 | options.query = query; 39 | return new TextRequest(this, options).perform(); 40 | } 41 | eventRequest(eventName, eventData = {}, options = {}) { 42 | if (!eventName) { 43 | throw new ApiAiClientConfigurationError("Event name can not be empty"); 44 | } 45 | options.event = { name: eventName, data: eventData }; 46 | return new EventRequest(this, options).perform(); 47 | } 48 | // @todo: implement local tts request 49 | /*public ttsRequest(query) { 50 | if (!query) { 51 | throw new ApiAiClientConfigurationError("Query should not be empty"); 52 | } 53 | return new TTSRequest(this).makeTTSRequest(query); 54 | }*/ 55 | /*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest { 56 | return new UserEntitiesRequest(this, options); 57 | }*/ 58 | getAccessToken() { 59 | return this.accessToken; 60 | } 61 | getApiVersion() { 62 | return (this.apiVersion) ? this.apiVersion : ApiAiConstants.DEFAULT_API_VERSION; 63 | } 64 | getApiLang() { 65 | return (this.apiLang) ? this.apiLang : ApiAiConstants.DEFAULT_CLIENT_LANG; 66 | } 67 | getApiBaseUrl() { 68 | return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants.DEFAULT_BASE_URL; 69 | } 70 | setSessionId(sessionId) { 71 | this.sessionId = sessionId; 72 | } 73 | getSessionId() { 74 | return this.sessionId; 75 | } 76 | /** 77 | * generates new random UUID 78 | * @returns {string} 79 | */ 80 | guid() { 81 | const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); 82 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" + 83 | s4() + "-" + s4() + s4() + s4(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /es6/ApiAiConstants.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export var ApiAiConstants; 18 | (function (ApiAiConstants) { 19 | let AVAILABLE_LANGUAGES; 20 | (function (AVAILABLE_LANGUAGES) { 21 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["EN"] = "en"] = "EN"; 22 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["DE"] = "de"] = "DE"; 23 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ES"] = "es"] = "ES"; 24 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT_BR"] = "pt-BR"] = "PT_BR"; 25 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_HK"] = "zh-HK"] = "ZH_HK"; 26 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_CN"] = "zh-CN"] = "ZH_CN"; 27 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_TW"] = "zh-TW"] = "ZH_TW"; 28 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["NL"] = "nl"] = "NL"; 29 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["FR"] = "fr"] = "FR"; 30 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["IT"] = "it"] = "IT"; 31 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["JA"] = "ja"] = "JA"; 32 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["KO"] = "ko"] = "KO"; 33 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT"] = "pt"] = "PT"; 34 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["RU"] = "ru"] = "RU"; 35 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["UK"] = "uk"] = "UK"; 36 | })(AVAILABLE_LANGUAGES = ApiAiConstants.AVAILABLE_LANGUAGES || (ApiAiConstants.AVAILABLE_LANGUAGES = {})); 37 | ApiAiConstants.VERSION = "2.0.0-beta.20"; 38 | ApiAiConstants.DEFAULT_BASE_URL = "https://api.api.ai/v1/"; 39 | ApiAiConstants.DEFAULT_API_VERSION = "20150910"; 40 | ApiAiConstants.DEFAULT_CLIENT_LANG = AVAILABLE_LANGUAGES.EN; 41 | })(ApiAiConstants || (ApiAiConstants = {})); 42 | -------------------------------------------------------------------------------- /es6/Errors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class ApiAiBaseError extends Error { 18 | constructor(message) { 19 | super(message); 20 | this.message = message; 21 | this.stack = new Error().stack; 22 | } 23 | } 24 | export class ApiAiClientConfigurationError extends ApiAiBaseError { 25 | constructor(message) { 26 | super(message); 27 | this.name = "ApiAiClientConfigurationError"; 28 | } 29 | } 30 | export class ApiAiRequestError extends ApiAiBaseError { 31 | constructor(message, code = null) { 32 | super(message); 33 | this.message = message; 34 | this.code = code; 35 | this.name = "ApiAiRequestError"; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /es6/Interfaces.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export var IStreamClient; 18 | (function (IStreamClient) { 19 | let ERROR; 20 | (function (ERROR) { 21 | ERROR[ERROR["ERR_NETWORK"] = 0] = "ERR_NETWORK"; 22 | ERROR[ERROR["ERR_AUDIO"] = 1] = "ERR_AUDIO"; 23 | ERROR[ERROR["ERR_SERVER"] = 2] = "ERR_SERVER"; 24 | ERROR[ERROR["ERR_CLIENT"] = 3] = "ERR_CLIENT"; 25 | })(ERROR = IStreamClient.ERROR || (IStreamClient.ERROR = {})); 26 | let EVENT; 27 | (function (EVENT) { 28 | EVENT[EVENT["MSG_WAITING_MICROPHONE"] = 0] = "MSG_WAITING_MICROPHONE"; 29 | EVENT[EVENT["MSG_MEDIA_STREAM_CREATED"] = 1] = "MSG_MEDIA_STREAM_CREATED"; 30 | EVENT[EVENT["MSG_INIT_RECORDER"] = 2] = "MSG_INIT_RECORDER"; 31 | EVENT[EVENT["MSG_RECORDING"] = 3] = "MSG_RECORDING"; 32 | EVENT[EVENT["MSG_SEND"] = 4] = "MSG_SEND"; 33 | EVENT[EVENT["MSG_SEND_EMPTY"] = 5] = "MSG_SEND_EMPTY"; 34 | EVENT[EVENT["MSG_SEND_EOS_OR_JSON"] = 6] = "MSG_SEND_EOS_OR_JSON"; 35 | EVENT[EVENT["MSG_WEB_SOCKET"] = 7] = "MSG_WEB_SOCKET"; 36 | EVENT[EVENT["MSG_WEB_SOCKET_OPEN"] = 8] = "MSG_WEB_SOCKET_OPEN"; 37 | EVENT[EVENT["MSG_WEB_SOCKET_CLOSE"] = 9] = "MSG_WEB_SOCKET_CLOSE"; 38 | EVENT[EVENT["MSG_STOP"] = 10] = "MSG_STOP"; 39 | EVENT[EVENT["MSG_CONFIG_CHANGED"] = 11] = "MSG_CONFIG_CHANGED"; 40 | })(EVENT = IStreamClient.EVENT || (IStreamClient.EVENT = {})); 41 | })(IStreamClient || (IStreamClient = {})); 42 | -------------------------------------------------------------------------------- /es6/Request/EventRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export class EventRequest extends Request { 19 | } 20 | -------------------------------------------------------------------------------- /es6/Request/Request.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { ApiAiRequestError } from "../Errors"; 18 | import XhrRequest from "../XhrRequest"; 19 | class Request { 20 | constructor(apiAiClient, options) { 21 | this.apiAiClient = apiAiClient; 22 | this.options = options; 23 | this.uri = this.apiAiClient.getApiBaseUrl() + "query?v=" + this.apiAiClient.getApiVersion(); 24 | this.requestMethod = XhrRequest.Method.POST; 25 | this.headers = { 26 | Authorization: "Bearer " + this.apiAiClient.getAccessToken(), 27 | }; 28 | this.options.lang = this.apiAiClient.getApiLang(); 29 | this.options.sessionId = this.apiAiClient.getSessionId(); 30 | } 31 | static handleSuccess(xhr) { 32 | return Promise.resolve(JSON.parse(xhr.responseText)); 33 | } 34 | static handleError(xhr) { 35 | let error = new ApiAiRequestError(null); 36 | try { 37 | const serverResponse = JSON.parse(xhr.responseText); 38 | if (serverResponse.status && serverResponse.status.errorDetails) { 39 | error = new ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code); 40 | } 41 | else { 42 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 43 | } 44 | } 45 | catch (e) { 46 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 47 | } 48 | return Promise.reject(error); 49 | } 50 | perform(overrideOptions = null) { 51 | const options = overrideOptions ? overrideOptions : this.options; 52 | return XhrRequest.ajax(this.requestMethod, this.uri, options, this.headers) 53 | .then(Request.handleSuccess.bind(this)) 54 | .catch(Request.handleError.bind(this)); 55 | } 56 | } 57 | export default Request; 58 | -------------------------------------------------------------------------------- /es6/Request/TextRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export default class TextRequest extends Request { 19 | } 20 | -------------------------------------------------------------------------------- /es6/XhrRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * quick ts implementation of example from 19 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise 20 | * with some minor improvements 21 | * @todo: test (?) 22 | * @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform 23 | */ 24 | class XhrRequest { 25 | // Method that performs the ajax request 26 | static ajax(method, url, args = null, headers = null, options = {}) { 27 | // Creating a promise 28 | return new Promise((resolve, reject) => { 29 | // Instantiates the XMLHttpRequest 30 | const client = XhrRequest.createXMLHTTPObject(); 31 | let uri = url; 32 | let payload = null; 33 | // Add given payload to get request 34 | if (args && (method === XhrRequest.Method.GET)) { 35 | uri += "?"; 36 | let argcount = 0; 37 | for (const key in args) { 38 | if (args.hasOwnProperty(key)) { 39 | if (argcount++) { 40 | uri += "&"; 41 | } 42 | uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]); 43 | } 44 | } 45 | } 46 | else if (args) { 47 | if (!headers) { 48 | headers = {}; 49 | } 50 | headers["Content-Type"] = "application/json; charset=utf-8"; 51 | payload = JSON.stringify(args); 52 | } 53 | for (const key in options) { 54 | if (key in client) { 55 | client[key] = options[key]; 56 | } 57 | } 58 | // hack: method[method] is somewhat like .toString for enum Method 59 | // should be made in normal way 60 | client.open(XhrRequest.Method[method], uri, true); 61 | // Add given headers 62 | if (headers) { 63 | for (const key in headers) { 64 | if (headers.hasOwnProperty(key)) { 65 | client.setRequestHeader(key, headers[key]); 66 | } 67 | } 68 | } 69 | payload ? client.send(payload) : client.send(); 70 | client.onload = () => { 71 | if (client.status >= 200 && client.status < 300) { 72 | // Performs the function "resolve" when this.status is equal to 2xx 73 | resolve(client); 74 | } 75 | else { 76 | // Performs the function "reject" when this.status is different than 2xx 77 | reject(client); 78 | } 79 | }; 80 | client.onerror = () => { 81 | reject(client); 82 | }; 83 | }); 84 | } 85 | static get(url, payload = null, headers = null, options = {}) { 86 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 87 | } 88 | static post(url, payload = null, headers = null, options = {}) { 89 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 90 | } 91 | static put(url, payload = null, headers = null, options = {}) { 92 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 93 | } 94 | static delete(url, payload = null, headers = null, options = {}) { 95 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 96 | } 97 | static createXMLHTTPObject() { 98 | let xmlhttp = null; 99 | for (const i of XhrRequest.XMLHttpFactories) { 100 | try { 101 | xmlhttp = i(); 102 | } 103 | catch (e) { 104 | continue; 105 | } 106 | break; 107 | } 108 | return xmlhttp; 109 | } 110 | } 111 | XhrRequest.XMLHttpFactories = [ 112 | () => new XMLHttpRequest(), 113 | () => new window["ActiveXObject"]("Msxml2.XMLHTTP"), 114 | () => new window["ActiveXObject"]("Msxml3.XMLHTTP"), 115 | () => new window["ActiveXObject"]("Microsoft.XMLHTTP") 116 | ]; 117 | (function (XhrRequest) { 118 | let Method; 119 | (function (Method) { 120 | Method[Method["GET"] = "GET"] = "GET"; 121 | Method[Method["POST"] = "POST"] = "POST"; 122 | Method[Method["PUT"] = "PUT"] = "PUT"; 123 | Method[Method["DELETE"] = "DELETE"] = "DELETE"; 124 | })(Method = XhrRequest.Method || (XhrRequest.Method = {})); 125 | })(XhrRequest || (XhrRequest = {})); 126 | export default XhrRequest; 127 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export * from "./es6/ApiAiClient"; 18 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /// 18 | export * from "./ts/ApiAiClient"; 19 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | var webpackConfig = require('./webpack.config')({}); 18 | 19 | module.exports = function(config) { 20 | config.set({ 21 | basePath: '', 22 | frameworks: ['mocha', 'chai'], 23 | files: [ 24 | 'node_modules/babel-polyfill/dist/polyfill.js', 25 | 'spec/**/*.spec.ts', 26 | ], 27 | exclude: [], 28 | preprocessors: { 29 | 'spec/**/*.spec.ts': ['webpack'], 30 | }, 31 | webpack: { 32 | module: webpackConfig.module, 33 | resolve: webpackConfig.resolve, 34 | }, 35 | phantomjsLauncher: { 36 | // Have phantomjs exit if a ResourceError is encountered 37 | // (useful if karma exits without killing phantom) 38 | // exitOnResourceError: true, 39 | base: 'PhantomJS', 40 | flags: [ 41 | '--web-security=false', 42 | '--load-images=true', 43 | '--ignore-ssl-errors=yes', 44 | '--ssl-protocol=any', 45 | ], 46 | }, 47 | reporters: ['progress'], 48 | port: 9876, 49 | colors: true, 50 | logLevel: config.LOG_INFO, 51 | autoWatch: true, 52 | browsers: ['PhantomJS'], 53 | singleRun: false, 54 | concurrency: Infinity, 55 | }); 56 | }; 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-ai-javascript", 3 | "version": "2.0.0-beta.21", 4 | "description": "Javascript SDK for https://api.ai/", 5 | "main": "index", 6 | "dependencies": { 7 | }, 8 | "devDependencies": { 9 | "@types/chai": "^3.4.35", 10 | "@types/es6-promise": "0.0.32", 11 | "@types/mocha": "^2.2.39", 12 | "awesome-typescript-loader": "^3.0.8", 13 | "babel-polyfill": "^6.23.0", 14 | "chai": "^3.5.0", 15 | "eslint": "^3.16.1", 16 | "eslint-config-google": "^0.7.1", 17 | "karma": "^1.5.0", 18 | "karma-chai": "^0.1.0", 19 | "karma-mocha": "^1.1.1", 20 | "karma-phantomjs-launcher": "^1.0.2", 21 | "karma-sinon": "^1.0.5", 22 | "karma-typescript-preprocessor2": "^1.2.1", 23 | "karma-webpack": "^2.0.2", 24 | "mocha": "^3.2.0", 25 | "mocha-phantomjs": "^4.1.0", 26 | "phantomjs-prebuilt": "^2.1.12", 27 | "rimraf": "^2.6.1", 28 | "sinon": "^1.17.3", 29 | "tslint": "^4.5.1", 30 | "typescript": "^2.3.2", 31 | "webpack": "^2.5.1", 32 | "webpack-dev-server": "^2.4.5" 33 | }, 34 | "scripts": { 35 | "start": "webpack-dev-server --port 8002", 36 | "build": "webpack && webpack --env.compress && rimraf ./es6 && tsc -p ./tsconfig.es6.json", 37 | "test": "karma start" 38 | }, 39 | "repository": { 40 | "type": "git", 41 | "url": "git+https://github.com/api-ai/api-ai-javascript.git" 42 | }, 43 | "keywords": [ 44 | "api.ai", 45 | "nlu", 46 | "nlp", 47 | "chatbots", 48 | "conversational", 49 | "UX" 50 | ], 51 | "author": "Eugeny Shingarev", 52 | "license": "Apache-2.0", 53 | "bugs": { 54 | "url": "https://github.com/api-ai/api-ai-javascript/issues" 55 | }, 56 | "homepage": "https://github.com/api-ai/api-ai-javascript#readme", 57 | "eslintConfig": { 58 | "extends": "google" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /spec/Client.spec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ts/ApiAiClient"; 18 | import {ApiAiConstants} from "../ts/ApiAiConstants"; 19 | 20 | const ACCESS_TOKEN = "AT"; 21 | const expect = chai.expect; 22 | 23 | describe("ApiAi.Client", () => { 24 | 25 | const client = new ApiAiClient({accessToken: ACCESS_TOKEN}); 26 | 27 | it("should instantinates", () => { 28 | expect(client instanceof ApiAiClient).to.be.true; 29 | }); 30 | 31 | it("sould fail without access token", () => { 32 | expect(() => new ApiAiClient({accessToken: undefined})).to.throw( 33 | "Access token is required for new ApiAi.Client instance" 34 | ); 35 | }); 36 | 37 | it("sould create session id in case it was not provided", () => { 38 | expect(typeof client.getSessionId() === "string").to.be.true; 39 | }); 40 | 41 | it("should use valid credentials", () => { 42 | expect(client.getApiLang()).to.eq(ApiAiConstants.DEFAULT_CLIENT_LANG); 43 | expect(client.getApiVersion()).to.eq(ApiAiConstants.DEFAULT_API_VERSION); 44 | expect(client.getApiBaseUrl()).to.eq(ApiAiConstants.DEFAULT_BASE_URL); 45 | expect(client.getAccessToken()).to.eq(ACCESS_TOKEN); 46 | }); 47 | 48 | it("should use valid setted credentilas", () => { 49 | const version = "2"; 50 | const baseUrl = "3"; 51 | const sessionId = "test"; 52 | const innerClient = new ApiAiClient({ 53 | accessToken: ACCESS_TOKEN, 54 | lang: ApiAiConstants.AVAILABLE_LANGUAGES.DE, 55 | baseUrl, 56 | sessionId, 57 | version 58 | }); 59 | 60 | expect(innerClient.getApiLang()).to.eq(ApiAiConstants.AVAILABLE_LANGUAGES.DE); 61 | expect(innerClient.getApiVersion()).to.eq(version); 62 | expect(innerClient.getApiBaseUrl()).to.eq(baseUrl); 63 | expect(innerClient.getAccessToken()).to.eq(ACCESS_TOKEN); 64 | expect(innerClient.getSessionId()).to.eq(sessionId); 65 | }); 66 | }); 67 | -------------------------------------------------------------------------------- /spec/Utils.spec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Utils from "../ts/Utils"; 18 | const expect = chai.expect; 19 | 20 | describe("ApiAi.Utils", () => { 21 | describe("#cloneObject", () => { 22 | it ("should clone object", () => { 23 | let originalObject = {}; 24 | let clonedObject = Utils.cloneObject(originalObject); 25 | 26 | expect(originalObject).not.to.eq(clonedObject); 27 | expect(JSON.stringify(originalObject)).to.eq(JSON.stringify(clonedObject)); 28 | }); 29 | }); 30 | }); 31 | -------------------------------------------------------------------------------- /spec/api.spec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ts/ApiAiClient"; 18 | describe("API", () => { 19 | 20 | const client = new ApiAiClient({accessToken: "3485a96fb27744db83e78b8c4bc9e7b7"}); 21 | 22 | describe("Text Query", () => { 23 | it ("should return response", function (done) { 24 | this.timeout(5000); 25 | client.textRequest("Hello!").then((response) => { 26 | chai.expect(response.result.action).to.eq("greeting"); 27 | chai.expect(response.result.resolvedQuery).to.eq("Hello!"); 28 | done(); 29 | }); 30 | }); 31 | 32 | it("should respect UTF-8", function(done) { 33 | this.timeout(5000); 34 | client.textRequest("¿Cuál es la población de España?").then((response) => { 35 | chai.expect(response.result.resolvedQuery).to.eq("¿Cuál es la población de España?"); 36 | done(); 37 | }); 38 | }); 39 | }); 40 | 41 | }); 42 | -------------------------------------------------------------------------------- /target/ApiAi.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | var ApiAi = 18 | /******/ (function(modules) { // webpackBootstrap 19 | /******/ // The module cache 20 | /******/ var installedModules = {}; 21 | /******/ 22 | /******/ // The require function 23 | /******/ function __webpack_require__(moduleId) { 24 | /******/ 25 | /******/ // Check if module is in cache 26 | /******/ if(installedModules[moduleId]) { 27 | /******/ return installedModules[moduleId].exports; 28 | /******/ } 29 | /******/ // Create a new module (and put it into the cache) 30 | /******/ var module = installedModules[moduleId] = { 31 | /******/ i: moduleId, 32 | /******/ l: false, 33 | /******/ exports: {} 34 | /******/ }; 35 | /******/ 36 | /******/ // Execute the module function 37 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 38 | /******/ 39 | /******/ // Flag the module as loaded 40 | /******/ module.l = true; 41 | /******/ 42 | /******/ // Return the exports of the module 43 | /******/ return module.exports; 44 | /******/ } 45 | /******/ 46 | /******/ 47 | /******/ // expose the modules object (__webpack_modules__) 48 | /******/ __webpack_require__.m = modules; 49 | /******/ 50 | /******/ // expose the module cache 51 | /******/ __webpack_require__.c = installedModules; 52 | /******/ 53 | /******/ // identity function for calling harmony imports with the correct context 54 | /******/ __webpack_require__.i = function(value) { return value; }; 55 | /******/ 56 | /******/ // define getter function for harmony exports 57 | /******/ __webpack_require__.d = function(exports, name, getter) { 58 | /******/ if(!__webpack_require__.o(exports, name)) { 59 | /******/ Object.defineProperty(exports, name, { 60 | /******/ configurable: false, 61 | /******/ enumerable: true, 62 | /******/ get: getter 63 | /******/ }); 64 | /******/ } 65 | /******/ }; 66 | /******/ 67 | /******/ // getDefaultExport function for compatibility with non-harmony modules 68 | /******/ __webpack_require__.n = function(module) { 69 | /******/ var getter = module && module.__esModule ? 70 | /******/ function getDefault() { return module['default']; } : 71 | /******/ function getModuleExports() { return module; }; 72 | /******/ __webpack_require__.d(getter, 'a', getter); 73 | /******/ return getter; 74 | /******/ }; 75 | /******/ 76 | /******/ // Object.prototype.hasOwnProperty.call 77 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; 78 | /******/ 79 | /******/ // __webpack_public_path__ 80 | /******/ __webpack_require__.p = "/target/"; 81 | /******/ 82 | /******/ // Load entry module and return exports 83 | /******/ return __webpack_require__(__webpack_require__.s = 8); 84 | /******/ }) 85 | /************************************************************************/ 86 | /******/ ([ 87 | /* 0 */ 88 | /***/ (function(module, exports, __webpack_require__) { 89 | 90 | "use strict"; 91 | 92 | Object.defineProperty(exports, "__esModule", { value: true }); 93 | var ApiAiConstants; 94 | (function (ApiAiConstants) { 95 | var AVAILABLE_LANGUAGES; 96 | (function (AVAILABLE_LANGUAGES) { 97 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["EN"] = "en"] = "EN"; 98 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["DE"] = "de"] = "DE"; 99 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ES"] = "es"] = "ES"; 100 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT_BR"] = "pt-BR"] = "PT_BR"; 101 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_HK"] = "zh-HK"] = "ZH_HK"; 102 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_CN"] = "zh-CN"] = "ZH_CN"; 103 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_TW"] = "zh-TW"] = "ZH_TW"; 104 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["NL"] = "nl"] = "NL"; 105 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["FR"] = "fr"] = "FR"; 106 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["IT"] = "it"] = "IT"; 107 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["JA"] = "ja"] = "JA"; 108 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["KO"] = "ko"] = "KO"; 109 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT"] = "pt"] = "PT"; 110 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["RU"] = "ru"] = "RU"; 111 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["UK"] = "uk"] = "UK"; 112 | })(AVAILABLE_LANGUAGES = ApiAiConstants.AVAILABLE_LANGUAGES || (ApiAiConstants.AVAILABLE_LANGUAGES = {})); 113 | ApiAiConstants.VERSION = "2.0.0-beta.20"; 114 | ApiAiConstants.DEFAULT_BASE_URL = "https://api.api.ai/v1/"; 115 | ApiAiConstants.DEFAULT_API_VERSION = "20150910"; 116 | ApiAiConstants.DEFAULT_CLIENT_LANG = AVAILABLE_LANGUAGES.EN; 117 | })(ApiAiConstants = exports.ApiAiConstants || (exports.ApiAiConstants = {})); 118 | 119 | 120 | /***/ }), 121 | /* 1 */ 122 | /***/ (function(module, exports, __webpack_require__) { 123 | 124 | "use strict"; 125 | 126 | var __extends = (this && this.__extends) || (function () { 127 | var extendStatics = Object.setPrototypeOf || 128 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 129 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 130 | return function (d, b) { 131 | extendStatics(d, b); 132 | function __() { this.constructor = d; } 133 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 134 | }; 135 | })(); 136 | Object.defineProperty(exports, "__esModule", { value: true }); 137 | var ApiAiBaseError = (function (_super) { 138 | __extends(ApiAiBaseError, _super); 139 | function ApiAiBaseError(message) { 140 | var _this = _super.call(this, message) || this; 141 | _this.message = message; 142 | _this.stack = new Error().stack; 143 | return _this; 144 | } 145 | return ApiAiBaseError; 146 | }(Error)); 147 | exports.ApiAiBaseError = ApiAiBaseError; 148 | var ApiAiClientConfigurationError = (function (_super) { 149 | __extends(ApiAiClientConfigurationError, _super); 150 | function ApiAiClientConfigurationError(message) { 151 | var _this = _super.call(this, message) || this; 152 | _this.name = "ApiAiClientConfigurationError"; 153 | return _this; 154 | } 155 | return ApiAiClientConfigurationError; 156 | }(ApiAiBaseError)); 157 | exports.ApiAiClientConfigurationError = ApiAiClientConfigurationError; 158 | var ApiAiRequestError = (function (_super) { 159 | __extends(ApiAiRequestError, _super); 160 | function ApiAiRequestError(message, code) { 161 | if (code === void 0) { code = null; } 162 | var _this = _super.call(this, message) || this; 163 | _this.message = message; 164 | _this.code = code; 165 | _this.name = "ApiAiRequestError"; 166 | return _this; 167 | } 168 | return ApiAiRequestError; 169 | }(ApiAiBaseError)); 170 | exports.ApiAiRequestError = ApiAiRequestError; 171 | 172 | 173 | /***/ }), 174 | /* 2 */ 175 | /***/ (function(module, exports, __webpack_require__) { 176 | 177 | "use strict"; 178 | 179 | Object.defineProperty(exports, "__esModule", { value: true }); 180 | var Errors_1 = __webpack_require__(1); 181 | var XhrRequest_1 = __webpack_require__(7); 182 | var Request = (function () { 183 | function Request(apiAiClient, options) { 184 | this.apiAiClient = apiAiClient; 185 | this.options = options; 186 | this.uri = this.apiAiClient.getApiBaseUrl() + "query?v=" + this.apiAiClient.getApiVersion(); 187 | this.requestMethod = XhrRequest_1.default.Method.POST; 188 | this.headers = { 189 | Authorization: "Bearer " + this.apiAiClient.getAccessToken(), 190 | }; 191 | this.options.lang = this.apiAiClient.getApiLang(); 192 | this.options.sessionId = this.apiAiClient.getSessionId(); 193 | } 194 | Request.handleSuccess = function (xhr) { 195 | return Promise.resolve(JSON.parse(xhr.responseText)); 196 | }; 197 | Request.handleError = function (xhr) { 198 | var error = new Errors_1.ApiAiRequestError(null); 199 | try { 200 | var serverResponse = JSON.parse(xhr.responseText); 201 | if (serverResponse.status && serverResponse.status.errorDetails) { 202 | error = new Errors_1.ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code); 203 | } 204 | else { 205 | error = new Errors_1.ApiAiRequestError(xhr.statusText, xhr.status); 206 | } 207 | } 208 | catch (e) { 209 | error = new Errors_1.ApiAiRequestError(xhr.statusText, xhr.status); 210 | } 211 | return Promise.reject(error); 212 | }; 213 | Request.prototype.perform = function (overrideOptions) { 214 | if (overrideOptions === void 0) { overrideOptions = null; } 215 | var options = overrideOptions ? overrideOptions : this.options; 216 | return XhrRequest_1.default.ajax(this.requestMethod, this.uri, options, this.headers) 217 | .then(Request.handleSuccess.bind(this)) 218 | .catch(Request.handleError.bind(this)); 219 | }; 220 | return Request; 221 | }()); 222 | exports.default = Request; 223 | 224 | 225 | /***/ }), 226 | /* 3 */ 227 | /***/ (function(module, exports, __webpack_require__) { 228 | 229 | "use strict"; 230 | 231 | function __export(m) { 232 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; 233 | } 234 | Object.defineProperty(exports, "__esModule", { value: true }); 235 | var ApiAiConstants_1 = __webpack_require__(0); 236 | var Errors_1 = __webpack_require__(1); 237 | var EventRequest_1 = __webpack_require__(5); 238 | var TextRequest_1 = __webpack_require__(6); 239 | __export(__webpack_require__(4)); 240 | var ApiAiConstants_2 = __webpack_require__(0); 241 | exports.ApiAiConstants = ApiAiConstants_2.ApiAiConstants; 242 | var ApiAiClient = (function () { 243 | function ApiAiClient(options) { 244 | if (!options || !options.accessToken) { 245 | throw new Errors_1.ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance"); 246 | } 247 | this.accessToken = options.accessToken; 248 | this.apiLang = options.lang || ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG; 249 | this.apiVersion = options.version || ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION; 250 | this.apiBaseUrl = options.baseUrl || ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL; 251 | this.sessionId = options.sessionId || this.guid(); 252 | } 253 | ApiAiClient.prototype.textRequest = function (query, options) { 254 | if (options === void 0) { options = {}; } 255 | if (!query) { 256 | throw new Errors_1.ApiAiClientConfigurationError("Query should not be empty"); 257 | } 258 | options.query = query; 259 | return new TextRequest_1.default(this, options).perform(); 260 | }; 261 | ApiAiClient.prototype.eventRequest = function (eventName, eventData, options) { 262 | if (eventData === void 0) { eventData = {}; } 263 | if (options === void 0) { options = {}; } 264 | if (!eventName) { 265 | throw new Errors_1.ApiAiClientConfigurationError("Event name can not be empty"); 266 | } 267 | options.event = { name: eventName, data: eventData }; 268 | return new EventRequest_1.EventRequest(this, options).perform(); 269 | }; 270 | // @todo: implement local tts request 271 | /*public ttsRequest(query) { 272 | if (!query) { 273 | throw new ApiAiClientConfigurationError("Query should not be empty"); 274 | } 275 | return new TTSRequest(this).makeTTSRequest(query); 276 | }*/ 277 | /*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest { 278 | return new UserEntitiesRequest(this, options); 279 | }*/ 280 | ApiAiClient.prototype.getAccessToken = function () { 281 | return this.accessToken; 282 | }; 283 | ApiAiClient.prototype.getApiVersion = function () { 284 | return (this.apiVersion) ? this.apiVersion : ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION; 285 | }; 286 | ApiAiClient.prototype.getApiLang = function () { 287 | return (this.apiLang) ? this.apiLang : ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG; 288 | }; 289 | ApiAiClient.prototype.getApiBaseUrl = function () { 290 | return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL; 291 | }; 292 | ApiAiClient.prototype.setSessionId = function (sessionId) { 293 | this.sessionId = sessionId; 294 | }; 295 | ApiAiClient.prototype.getSessionId = function () { 296 | return this.sessionId; 297 | }; 298 | /** 299 | * generates new random UUID 300 | * @returns {string} 301 | */ 302 | ApiAiClient.prototype.guid = function () { 303 | var s4 = function () { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }; 304 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" + 305 | s4() + "-" + s4() + s4() + s4(); 306 | }; 307 | return ApiAiClient; 308 | }()); 309 | exports.ApiAiClient = ApiAiClient; 310 | 311 | 312 | /***/ }), 313 | /* 4 */ 314 | /***/ (function(module, exports, __webpack_require__) { 315 | 316 | "use strict"; 317 | 318 | Object.defineProperty(exports, "__esModule", { value: true }); 319 | var IStreamClient; 320 | (function (IStreamClient) { 321 | var ERROR; 322 | (function (ERROR) { 323 | ERROR[ERROR["ERR_NETWORK"] = 0] = "ERR_NETWORK"; 324 | ERROR[ERROR["ERR_AUDIO"] = 1] = "ERR_AUDIO"; 325 | ERROR[ERROR["ERR_SERVER"] = 2] = "ERR_SERVER"; 326 | ERROR[ERROR["ERR_CLIENT"] = 3] = "ERR_CLIENT"; 327 | })(ERROR = IStreamClient.ERROR || (IStreamClient.ERROR = {})); 328 | var EVENT; 329 | (function (EVENT) { 330 | EVENT[EVENT["MSG_WAITING_MICROPHONE"] = 0] = "MSG_WAITING_MICROPHONE"; 331 | EVENT[EVENT["MSG_MEDIA_STREAM_CREATED"] = 1] = "MSG_MEDIA_STREAM_CREATED"; 332 | EVENT[EVENT["MSG_INIT_RECORDER"] = 2] = "MSG_INIT_RECORDER"; 333 | EVENT[EVENT["MSG_RECORDING"] = 3] = "MSG_RECORDING"; 334 | EVENT[EVENT["MSG_SEND"] = 4] = "MSG_SEND"; 335 | EVENT[EVENT["MSG_SEND_EMPTY"] = 5] = "MSG_SEND_EMPTY"; 336 | EVENT[EVENT["MSG_SEND_EOS_OR_JSON"] = 6] = "MSG_SEND_EOS_OR_JSON"; 337 | EVENT[EVENT["MSG_WEB_SOCKET"] = 7] = "MSG_WEB_SOCKET"; 338 | EVENT[EVENT["MSG_WEB_SOCKET_OPEN"] = 8] = "MSG_WEB_SOCKET_OPEN"; 339 | EVENT[EVENT["MSG_WEB_SOCKET_CLOSE"] = 9] = "MSG_WEB_SOCKET_CLOSE"; 340 | EVENT[EVENT["MSG_STOP"] = 10] = "MSG_STOP"; 341 | EVENT[EVENT["MSG_CONFIG_CHANGED"] = 11] = "MSG_CONFIG_CHANGED"; 342 | })(EVENT = IStreamClient.EVENT || (IStreamClient.EVENT = {})); 343 | })(IStreamClient = exports.IStreamClient || (exports.IStreamClient = {})); 344 | 345 | 346 | /***/ }), 347 | /* 5 */ 348 | /***/ (function(module, exports, __webpack_require__) { 349 | 350 | "use strict"; 351 | 352 | var __extends = (this && this.__extends) || (function () { 353 | var extendStatics = Object.setPrototypeOf || 354 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 355 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 356 | return function (d, b) { 357 | extendStatics(d, b); 358 | function __() { this.constructor = d; } 359 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 360 | }; 361 | })(); 362 | Object.defineProperty(exports, "__esModule", { value: true }); 363 | var Request_1 = __webpack_require__(2); 364 | var EventRequest = (function (_super) { 365 | __extends(EventRequest, _super); 366 | function EventRequest() { 367 | return _super !== null && _super.apply(this, arguments) || this; 368 | } 369 | return EventRequest; 370 | }(Request_1.default)); 371 | exports.EventRequest = EventRequest; 372 | 373 | 374 | /***/ }), 375 | /* 6 */ 376 | /***/ (function(module, exports, __webpack_require__) { 377 | 378 | "use strict"; 379 | 380 | var __extends = (this && this.__extends) || (function () { 381 | var extendStatics = Object.setPrototypeOf || 382 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 383 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 384 | return function (d, b) { 385 | extendStatics(d, b); 386 | function __() { this.constructor = d; } 387 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 388 | }; 389 | })(); 390 | Object.defineProperty(exports, "__esModule", { value: true }); 391 | var Request_1 = __webpack_require__(2); 392 | var TextRequest = (function (_super) { 393 | __extends(TextRequest, _super); 394 | function TextRequest() { 395 | return _super !== null && _super.apply(this, arguments) || this; 396 | } 397 | return TextRequest; 398 | }(Request_1.default)); 399 | exports.default = TextRequest; 400 | 401 | 402 | /***/ }), 403 | /* 7 */ 404 | /***/ (function(module, exports, __webpack_require__) { 405 | 406 | "use strict"; 407 | 408 | Object.defineProperty(exports, "__esModule", { value: true }); 409 | /** 410 | * quick ts implementation of example from 411 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise 412 | * with some minor improvements 413 | * @todo: test (?) 414 | * @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform 415 | */ 416 | var XhrRequest = (function () { 417 | function XhrRequest() { 418 | } 419 | // Method that performs the ajax request 420 | XhrRequest.ajax = function (method, url, args, headers, options) { 421 | if (args === void 0) { args = null; } 422 | if (headers === void 0) { headers = null; } 423 | if (options === void 0) { options = {}; } 424 | // Creating a promise 425 | return new Promise(function (resolve, reject) { 426 | // Instantiates the XMLHttpRequest 427 | var client = XhrRequest.createXMLHTTPObject(); 428 | var uri = url; 429 | var payload = null; 430 | // Add given payload to get request 431 | if (args && (method === XhrRequest.Method.GET)) { 432 | uri += "?"; 433 | var argcount = 0; 434 | for (var key in args) { 435 | if (args.hasOwnProperty(key)) { 436 | if (argcount++) { 437 | uri += "&"; 438 | } 439 | uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]); 440 | } 441 | } 442 | } 443 | else if (args) { 444 | if (!headers) { 445 | headers = {}; 446 | } 447 | headers["Content-Type"] = "application/json; charset=utf-8"; 448 | payload = JSON.stringify(args); 449 | } 450 | for (var key in options) { 451 | if (key in client) { 452 | client[key] = options[key]; 453 | } 454 | } 455 | // hack: method[method] is somewhat like .toString for enum Method 456 | // should be made in normal way 457 | client.open(XhrRequest.Method[method], uri, true); 458 | // Add given headers 459 | if (headers) { 460 | for (var key in headers) { 461 | if (headers.hasOwnProperty(key)) { 462 | client.setRequestHeader(key, headers[key]); 463 | } 464 | } 465 | } 466 | payload ? client.send(payload) : client.send(); 467 | client.onload = function () { 468 | if (client.status >= 200 && client.status < 300) { 469 | // Performs the function "resolve" when this.status is equal to 2xx 470 | resolve(client); 471 | } 472 | else { 473 | // Performs the function "reject" when this.status is different than 2xx 474 | reject(client); 475 | } 476 | }; 477 | client.onerror = function () { 478 | reject(client); 479 | }; 480 | }); 481 | }; 482 | XhrRequest.get = function (url, payload, headers, options) { 483 | if (payload === void 0) { payload = null; } 484 | if (headers === void 0) { headers = null; } 485 | if (options === void 0) { options = {}; } 486 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 487 | }; 488 | XhrRequest.post = function (url, payload, headers, options) { 489 | if (payload === void 0) { payload = null; } 490 | if (headers === void 0) { headers = null; } 491 | if (options === void 0) { options = {}; } 492 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 493 | }; 494 | XhrRequest.put = function (url, payload, headers, options) { 495 | if (payload === void 0) { payload = null; } 496 | if (headers === void 0) { headers = null; } 497 | if (options === void 0) { options = {}; } 498 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 499 | }; 500 | XhrRequest.delete = function (url, payload, headers, options) { 501 | if (payload === void 0) { payload = null; } 502 | if (headers === void 0) { headers = null; } 503 | if (options === void 0) { options = {}; } 504 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 505 | }; 506 | XhrRequest.createXMLHTTPObject = function () { 507 | var xmlhttp = null; 508 | for (var _i = 0, _a = XhrRequest.XMLHttpFactories; _i < _a.length; _i++) { 509 | var i = _a[_i]; 510 | try { 511 | xmlhttp = i(); 512 | } 513 | catch (e) { 514 | continue; 515 | } 516 | break; 517 | } 518 | return xmlhttp; 519 | }; 520 | XhrRequest.XMLHttpFactories = [ 521 | function () { return new XMLHttpRequest(); }, 522 | function () { return new window["ActiveXObject"]("Msxml2.XMLHTTP"); }, 523 | function () { return new window["ActiveXObject"]("Msxml3.XMLHTTP"); }, 524 | function () { return new window["ActiveXObject"]("Microsoft.XMLHTTP"); } 525 | ]; 526 | return XhrRequest; 527 | }()); 528 | (function (XhrRequest) { 529 | var Method; 530 | (function (Method) { 531 | Method[Method["GET"] = "GET"] = "GET"; 532 | Method[Method["POST"] = "POST"] = "POST"; 533 | Method[Method["PUT"] = "PUT"] = "PUT"; 534 | Method[Method["DELETE"] = "DELETE"] = "DELETE"; 535 | })(Method = XhrRequest.Method || (XhrRequest.Method = {})); 536 | })(XhrRequest || (XhrRequest = {})); 537 | exports.default = XhrRequest; 538 | 539 | 540 | /***/ }), 541 | /* 8 */ 542 | /***/ (function(module, exports, __webpack_require__) { 543 | 544 | module.exports = __webpack_require__(3); 545 | 546 | 547 | /***/ }) 548 | /******/ ]); 549 | //# sourceMappingURL=ApiAi.js.map -------------------------------------------------------------------------------- /target/ApiAi.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | var ApiAi=function(t){function __webpack_require__(n){if(e[n])return e[n].exports;var r=e[n]={i:n,l:!1,exports:{}};return t[n].call(r.exports,r,r.exports,__webpack_require__),r.l=!0,r.exports}var e={};return __webpack_require__.m=t,__webpack_require__.c=e,__webpack_require__.i=function(t){return t},__webpack_require__.d=function(t,e,n){__webpack_require__.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},__webpack_require__.n=function(t){var e=t&&t.__esModule?function getDefault(){return t.default}:function getModuleExports(){return t};return __webpack_require__.d(e,"a",e),e},__webpack_require__.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},__webpack_require__.p="/target/",__webpack_require__(__webpack_require__.s=8)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});!function(t){var e;!function(t){t[t.EN="en"]="EN",t[t.DE="de"]="DE",t[t.ES="es"]="ES",t[t.PT_BR="pt-BR"]="PT_BR",t[t.ZH_HK="zh-HK"]="ZH_HK",t[t.ZH_CN="zh-CN"]="ZH_CN",t[t.ZH_TW="zh-TW"]="ZH_TW",t[t.NL="nl"]="NL",t[t.FR="fr"]="FR",t[t.IT="it"]="IT",t[t.JA="ja"]="JA",t[t.KO="ko"]="KO",t[t.PT="pt"]="PT",t[t.RU="ru"]="RU",t[t.UK="uk"]="UK"}(e=t.AVAILABLE_LANGUAGES||(t.AVAILABLE_LANGUAGES={})),t.VERSION="2.0.0-beta.20",t.DEFAULT_BASE_URL="https://api.api.ai/v1/",t.DEFAULT_API_VERSION="20150910",t.DEFAULT_CLIENT_LANG=e.EN}(e.ApiAiConstants||(e.ApiAiConstants={}))},function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}();Object.defineProperty(e,"__esModule",{value:!0});var i=function(t){function ApiAiBaseError(e){var n=t.call(this,e)||this;return n.message=e,n.stack=(new Error).stack,n}return r(ApiAiBaseError,t),ApiAiBaseError}(Error);e.ApiAiBaseError=i;var o=function(t){function ApiAiClientConfigurationError(e){var n=t.call(this,e)||this;return n.name="ApiAiClientConfigurationError",n}return r(ApiAiClientConfigurationError,t),ApiAiClientConfigurationError}(i);e.ApiAiClientConfigurationError=o;var s=function(t){function ApiAiRequestError(e,n){void 0===n&&(n=null);var r=t.call(this,e)||this;return r.message=e,r.code=n,r.name="ApiAiRequestError",r}return r(ApiAiRequestError,t),ApiAiRequestError}(i);e.ApiAiRequestError=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=n(7),o=function(){function Request(t,e){this.apiAiClient=t,this.options=e,this.uri=this.apiAiClient.getApiBaseUrl()+"query?v="+this.apiAiClient.getApiVersion(),this.requestMethod=i.default.Method.POST,this.headers={Authorization:"Bearer "+this.apiAiClient.getAccessToken()},this.options.lang=this.apiAiClient.getApiLang(),this.options.sessionId=this.apiAiClient.getSessionId()}return Request.handleSuccess=function(t){return Promise.resolve(JSON.parse(t.responseText))},Request.handleError=function(t){var e=new r.ApiAiRequestError(null);try{var n=JSON.parse(t.responseText);e=n.status&&n.status.errorDetails?new r.ApiAiRequestError(n.status.errorDetails,n.status.code):new r.ApiAiRequestError(t.statusText,t.status)}catch(n){e=new r.ApiAiRequestError(t.statusText,t.status)}return Promise.reject(e)},Request.prototype.perform=function(t){void 0===t&&(t=null);var e=t||this.options;return i.default.ajax(this.requestMethod,this.uri,e,this.headers).then(Request.handleSuccess.bind(this)).catch(Request.handleError.bind(this))},Request}();e.default=o},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(5),s=n(6);!function __export(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}(n(4));var u=n(0);e.ApiAiConstants=u.ApiAiConstants;var _=function(){function ApiAiClient(t){if(!t||!t.accessToken)throw new i.ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance");this.accessToken=t.accessToken,this.apiLang=t.lang||r.ApiAiConstants.DEFAULT_CLIENT_LANG,this.apiVersion=t.version||r.ApiAiConstants.DEFAULT_API_VERSION,this.apiBaseUrl=t.baseUrl||r.ApiAiConstants.DEFAULT_BASE_URL,this.sessionId=t.sessionId||this.guid()}return ApiAiClient.prototype.textRequest=function(t,e){if(void 0===e&&(e={}),!t)throw new i.ApiAiClientConfigurationError("Query should not be empty");return e.query=t,new s.default(this,e).perform()},ApiAiClient.prototype.eventRequest=function(t,e,n){if(void 0===e&&(e={}),void 0===n&&(n={}),!t)throw new i.ApiAiClientConfigurationError("Event name can not be empty");return n.event={name:t,data:e},new o.EventRequest(this,n).perform()},ApiAiClient.prototype.getAccessToken=function(){return this.accessToken},ApiAiClient.prototype.getApiVersion=function(){return this.apiVersion?this.apiVersion:r.ApiAiConstants.DEFAULT_API_VERSION},ApiAiClient.prototype.getApiLang=function(){return this.apiLang?this.apiLang:r.ApiAiConstants.DEFAULT_CLIENT_LANG},ApiAiClient.prototype.getApiBaseUrl=function(){return this.apiBaseUrl?this.apiBaseUrl:r.ApiAiConstants.DEFAULT_BASE_URL},ApiAiClient.prototype.setSessionId=function(t){this.sessionId=t},ApiAiClient.prototype.getSessionId=function(){return this.sessionId},ApiAiClient.prototype.guid=function(){var t=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)};return t()+t()+"-"+t()+"-"+t()+"-"+t()+"-"+t()+t()+t()},ApiAiClient}();e.ApiAiClient=_},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});!function(t){!function(t){t[t.ERR_NETWORK=0]="ERR_NETWORK",t[t.ERR_AUDIO=1]="ERR_AUDIO",t[t.ERR_SERVER=2]="ERR_SERVER",t[t.ERR_CLIENT=3]="ERR_CLIENT"}(t.ERROR||(t.ERROR={}));!function(t){t[t.MSG_WAITING_MICROPHONE=0]="MSG_WAITING_MICROPHONE",t[t.MSG_MEDIA_STREAM_CREATED=1]="MSG_MEDIA_STREAM_CREATED",t[t.MSG_INIT_RECORDER=2]="MSG_INIT_RECORDER",t[t.MSG_RECORDING=3]="MSG_RECORDING",t[t.MSG_SEND=4]="MSG_SEND",t[t.MSG_SEND_EMPTY=5]="MSG_SEND_EMPTY",t[t.MSG_SEND_EOS_OR_JSON=6]="MSG_SEND_EOS_OR_JSON",t[t.MSG_WEB_SOCKET=7]="MSG_WEB_SOCKET",t[t.MSG_WEB_SOCKET_OPEN=8]="MSG_WEB_SOCKET_OPEN",t[t.MSG_WEB_SOCKET_CLOSE=9]="MSG_WEB_SOCKET_CLOSE",t[t.MSG_STOP=10]="MSG_STOP",t[t.MSG_CONFIG_CHANGED=11]="MSG_CONFIG_CHANGED"}(t.EVENT||(t.EVENT={}))}(e.IStreamClient||(e.IStreamClient={}))},function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}();Object.defineProperty(e,"__esModule",{value:!0});var i=n(2),o=function(t){function EventRequest(){return null!==t&&t.apply(this,arguments)||this}return r(EventRequest,t),EventRequest}(i.default);e.EventRequest=o},function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}();Object.defineProperty(e,"__esModule",{value:!0});var i=n(2),o=function(t){function TextRequest(){return null!==t&&t.apply(this,arguments)||this}return r(TextRequest,t),TextRequest}(i.default);e.default=o},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function XhrRequest(){}return XhrRequest.ajax=function(t,e,n,r,i){return void 0===n&&(n=null),void 0===r&&(r=null),void 0===i&&(i={}),new Promise(function(o,s){var u=XhrRequest.createXMLHTTPObject(),_=e,a=null;if(n&&t===XhrRequest.Method.GET){_+="?";var c=0;for(var p in n)n.hasOwnProperty(p)&&(c++&&(_+="&"),_+=encodeURIComponent(p)+"="+encodeURIComponent(n[p]))}else n&&(r||(r={}),r["Content-Type"]="application/json; charset=utf-8",a=JSON.stringify(n));for(var p in i)p in u&&(u[p]=i[p]);if(u.open(XhrRequest.Method[t],_,!0),r)for(var p in r)r.hasOwnProperty(p)&&u.setRequestHeader(p,r[p]);a?u.send(a):u.send(),u.onload=function(){u.status>=200&&u.status<300?o(u):s(u)},u.onerror=function(){s(u)}})},XhrRequest.get=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.GET,t,e,n,r)},XhrRequest.post=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.POST,t,e,n,r)},XhrRequest.put=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.PUT,t,e,n,r)},XhrRequest.delete=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.DELETE,t,e,n,r)},XhrRequest.createXMLHTTPObject=function(){for(var t=null,e=0,n=XhrRequest.XMLHttpFactories;e= 200 && client.status < 300) { 294 | // Performs the function "resolve" when this.status is equal to 2xx 295 | resolve(client); 296 | } 297 | else { 298 | // Performs the function "reject" when this.status is different than 2xx 299 | reject(client); 300 | } 301 | }; 302 | client.onerror = function () { 303 | reject(client); 304 | }; 305 | }); 306 | }; 307 | XhrRequest.get = function (url, payload, headers, options) { 308 | if (payload === void 0) { payload = null; } 309 | if (headers === void 0) { headers = null; } 310 | if (options === void 0) { options = {}; } 311 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 312 | }; 313 | XhrRequest.post = function (url, payload, headers, options) { 314 | if (payload === void 0) { payload = null; } 315 | if (headers === void 0) { headers = null; } 316 | if (options === void 0) { options = {}; } 317 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 318 | }; 319 | XhrRequest.put = function (url, payload, headers, options) { 320 | if (payload === void 0) { payload = null; } 321 | if (headers === void 0) { headers = null; } 322 | if (options === void 0) { options = {}; } 323 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 324 | }; 325 | XhrRequest.delete = function (url, payload, headers, options) { 326 | if (payload === void 0) { payload = null; } 327 | if (headers === void 0) { headers = null; } 328 | if (options === void 0) { options = {}; } 329 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 330 | }; 331 | XhrRequest.createXMLHTTPObject = function () { 332 | var xmlhttp = null; 333 | for (var _i = 0, _a = XhrRequest.XMLHttpFactories; _i < _a.length; _i++) { 334 | var i = _a[_i]; 335 | try { 336 | xmlhttp = i(); 337 | } 338 | catch (e) { 339 | continue; 340 | } 341 | break; 342 | } 343 | return xmlhttp; 344 | }; 345 | return XhrRequest; 346 | }()); 347 | XhrRequest.XMLHttpFactories = [ 348 | function () { return new XMLHttpRequest(); }, 349 | function () { return new window["ActiveXObject"]("Msxml2.XMLHTTP"); }, 350 | function () { return new window["ActiveXObject"]("Msxml3.XMLHTTP"); }, 351 | function () { return new window["ActiveXObject"]("Microsoft.XMLHTTP"); } 352 | ]; 353 | (function (XhrRequest) { 354 | var Method; 355 | (function (Method) { 356 | Method[Method["GET"] = "GET"] = "GET"; 357 | Method[Method["POST"] = "POST"] = "POST"; 358 | Method[Method["PUT"] = "PUT"] = "PUT"; 359 | Method[Method["DELETE"] = "DELETE"] = "DELETE"; 360 | })(Method = XhrRequest.Method || (XhrRequest.Method = {})); 361 | })(XhrRequest || (XhrRequest = {})); 362 | exports.default = XhrRequest; 363 | 364 | 365 | /***/ }), 366 | /* 4 */ 367 | /***/ (function(module, exports, __webpack_require__) { 368 | 369 | "use strict"; 370 | 371 | function __export(m) { 372 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; 373 | } 374 | Object.defineProperty(exports, "__esModule", { value: true }); 375 | __export(__webpack_require__(5)); 376 | 377 | 378 | /***/ }), 379 | /* 5 */ 380 | /***/ (function(module, exports, __webpack_require__) { 381 | 382 | "use strict"; 383 | 384 | function __export(m) { 385 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; 386 | } 387 | Object.defineProperty(exports, "__esModule", { value: true }); 388 | var ApiAiConstants_1 = __webpack_require__(0); 389 | var Errors_1 = __webpack_require__(1); 390 | var EventRequest_1 = __webpack_require__(7); 391 | var TextRequest_1 = __webpack_require__(9); 392 | var TTSRequest_1 = __webpack_require__(8); 393 | __export(__webpack_require__(6)); 394 | var ApiAiConstants_2 = __webpack_require__(0); 395 | exports.ApiAiConstants = ApiAiConstants_2.ApiAiConstants; 396 | var ApiAiClient = (function () { 397 | function ApiAiClient(options) { 398 | if (!options || !options.accessToken) { 399 | throw new Errors_1.ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance"); 400 | } 401 | this.accessToken = options.accessToken; 402 | this.apiLang = options.lang || ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG; 403 | this.apiVersion = options.version || ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION; 404 | this.apiBaseUrl = options.baseUrl || ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL; 405 | this.sessionId = options.sessionId || this.guid(); 406 | this.streamClientClass = options.streamClientClass || null; 407 | } 408 | ApiAiClient.prototype.textRequest = function (query, options) { 409 | if (options === void 0) { options = {}; } 410 | if (!query) { 411 | throw new Errors_1.ApiAiClientConfigurationError("Query should not be empty"); 412 | } 413 | options.query = query; 414 | return new TextRequest_1.default(this, options).perform(); 415 | }; 416 | ApiAiClient.prototype.eventRequest = function (eventName, eventData, options) { 417 | if (eventData === void 0) { eventData = {}; } 418 | if (options === void 0) { options = {}; } 419 | if (!eventName) { 420 | throw new Errors_1.ApiAiClientConfigurationError("Event name can not be empty"); 421 | } 422 | options.event = { name: eventName, data: eventData }; 423 | return new EventRequest_1.EventRequest(this, options).perform(); 424 | }; 425 | ApiAiClient.prototype.ttsRequest = function (query) { 426 | if (!query) { 427 | throw new Errors_1.ApiAiClientConfigurationError("Query should not be empty"); 428 | } 429 | return new TTSRequest_1.TTSRequest(this).makeTTSRequest(query); 430 | }; 431 | /*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest { 432 | return new UserEntitiesRequest(this, options); 433 | }*/ 434 | ApiAiClient.prototype.createStreamClient = function (streamClientOptions) { 435 | if (streamClientOptions === void 0) { streamClientOptions = {}; } 436 | if (this.streamClientClass) { 437 | streamClientOptions.token = this.getAccessToken(); 438 | streamClientOptions.sessionId = this.getSessionId(); 439 | streamClientOptions.lang = this.getApiLang(); 440 | return new this.streamClientClass(streamClientOptions); 441 | } 442 | else { 443 | throw new Errors_1.ApiAiClientConfigurationError("No StreamClient implementation given to ApiAi Client constructor"); 444 | } 445 | }; 446 | ApiAiClient.prototype.getAccessToken = function () { 447 | return this.accessToken; 448 | }; 449 | ApiAiClient.prototype.getApiVersion = function () { 450 | return (this.apiVersion) ? this.apiVersion : ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION; 451 | }; 452 | ApiAiClient.prototype.getApiLang = function () { 453 | return (this.apiLang) ? this.apiLang : ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG; 454 | }; 455 | ApiAiClient.prototype.getApiBaseUrl = function () { 456 | return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL; 457 | }; 458 | ApiAiClient.prototype.setSessionId = function (sessionId) { 459 | this.sessionId = sessionId; 460 | }; 461 | ApiAiClient.prototype.getSessionId = function () { 462 | return this.sessionId; 463 | }; 464 | /** 465 | * generates new random UUID 466 | * @returns {string} 467 | */ 468 | ApiAiClient.prototype.guid = function () { 469 | var s4 = function () { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }; 470 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" + 471 | s4() + "-" + s4() + s4() + s4(); 472 | }; 473 | return ApiAiClient; 474 | }()); 475 | exports.ApiAiClient = ApiAiClient; 476 | 477 | 478 | /***/ }), 479 | /* 6 */ 480 | /***/ (function(module, exports, __webpack_require__) { 481 | 482 | "use strict"; 483 | 484 | Object.defineProperty(exports, "__esModule", { value: true }); 485 | var IStreamClient; 486 | (function (IStreamClient) { 487 | var ERROR; 488 | (function (ERROR) { 489 | ERROR[ERROR["ERR_NETWORK"] = 0] = "ERR_NETWORK"; 490 | ERROR[ERROR["ERR_AUDIO"] = 1] = "ERR_AUDIO"; 491 | ERROR[ERROR["ERR_SERVER"] = 2] = "ERR_SERVER"; 492 | ERROR[ERROR["ERR_CLIENT"] = 3] = "ERR_CLIENT"; 493 | })(ERROR = IStreamClient.ERROR || (IStreamClient.ERROR = {})); 494 | var EVENT; 495 | (function (EVENT) { 496 | EVENT[EVENT["MSG_WAITING_MICROPHONE"] = 0] = "MSG_WAITING_MICROPHONE"; 497 | EVENT[EVENT["MSG_MEDIA_STREAM_CREATED"] = 1] = "MSG_MEDIA_STREAM_CREATED"; 498 | EVENT[EVENT["MSG_INIT_RECORDER"] = 2] = "MSG_INIT_RECORDER"; 499 | EVENT[EVENT["MSG_RECORDING"] = 3] = "MSG_RECORDING"; 500 | EVENT[EVENT["MSG_SEND"] = 4] = "MSG_SEND"; 501 | EVENT[EVENT["MSG_SEND_EMPTY"] = 5] = "MSG_SEND_EMPTY"; 502 | EVENT[EVENT["MSG_SEND_EOS_OR_JSON"] = 6] = "MSG_SEND_EOS_OR_JSON"; 503 | EVENT[EVENT["MSG_WEB_SOCKET"] = 7] = "MSG_WEB_SOCKET"; 504 | EVENT[EVENT["MSG_WEB_SOCKET_OPEN"] = 8] = "MSG_WEB_SOCKET_OPEN"; 505 | EVENT[EVENT["MSG_WEB_SOCKET_CLOSE"] = 9] = "MSG_WEB_SOCKET_CLOSE"; 506 | EVENT[EVENT["MSG_STOP"] = 10] = "MSG_STOP"; 507 | EVENT[EVENT["MSG_CONFIG_CHANGED"] = 11] = "MSG_CONFIG_CHANGED"; 508 | })(EVENT = IStreamClient.EVENT || (IStreamClient.EVENT = {})); 509 | })(IStreamClient = exports.IStreamClient || (exports.IStreamClient = {})); 510 | 511 | 512 | /***/ }), 513 | /* 7 */ 514 | /***/ (function(module, exports, __webpack_require__) { 515 | 516 | "use strict"; 517 | 518 | var __extends = (this && this.__extends) || (function () { 519 | var extendStatics = Object.setPrototypeOf || 520 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 521 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 522 | return function (d, b) { 523 | extendStatics(d, b); 524 | function __() { this.constructor = d; } 525 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 526 | }; 527 | })(); 528 | Object.defineProperty(exports, "__esModule", { value: true }); 529 | var Request_1 = __webpack_require__(2); 530 | var EventRequest = (function (_super) { 531 | __extends(EventRequest, _super); 532 | function EventRequest() { 533 | return _super !== null && _super.apply(this, arguments) || this; 534 | } 535 | return EventRequest; 536 | }(Request_1.default)); 537 | exports.EventRequest = EventRequest; 538 | 539 | 540 | /***/ }), 541 | /* 8 */ 542 | /***/ (function(module, exports, __webpack_require__) { 543 | 544 | "use strict"; 545 | 546 | var __extends = (this && this.__extends) || (function () { 547 | var extendStatics = Object.setPrototypeOf || 548 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 549 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 550 | return function (d, b) { 551 | extendStatics(d, b); 552 | function __() { this.constructor = d; } 553 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 554 | }; 555 | })(); 556 | Object.defineProperty(exports, "__esModule", { value: true }); 557 | var ApiAiConstants_1 = __webpack_require__(0); 558 | var Errors_1 = __webpack_require__(1); 559 | var XhrRequest_1 = __webpack_require__(3); 560 | var Request_1 = __webpack_require__(2); 561 | var TTSRequest = (function (_super) { 562 | __extends(TTSRequest, _super); 563 | function TTSRequest(apiAiClient, options) { 564 | if (options === void 0) { options = {}; } 565 | var _this = _super.call(this, apiAiClient, options) || this; 566 | _this.apiAiClient = apiAiClient; 567 | _this.resolveTTSPromise = function (data) { 568 | return _this.speak(data.response); 569 | }; 570 | _this.rejectTTSPromise = function (reason) { 571 | throw new Errors_1.ApiAiRequestError(reason); 572 | }; 573 | // this.requestMethod = XhrRequest.Method.GET; 574 | _this.uri = ApiAiConstants_1.ApiAiConstants.DEFAULT_TTS_HOST; 575 | var AudioContext = window.AudioContext || webkitAudioContext; 576 | if (!TTSRequest.audioContext) { 577 | TTSRequest.audioContext = new AudioContext(); 578 | } 579 | return _this; 580 | } 581 | TTSRequest.prototype.makeTTSRequest = function (text) { 582 | if (!text) { 583 | throw new Errors_1.ApiAiClientConfigurationError("Request can not be empty"); 584 | } 585 | var params = { 586 | lang: "en-US", 587 | text: encodeURIComponent(text), 588 | v: this.apiAiClient.getApiVersion() 589 | }; 590 | var headers = { 591 | "Accept-language": "en-US", 592 | "Authorization": "Bearer " + this.apiAiClient.getAccessToken() 593 | }; 594 | return this.makeRequest(this.uri, params, headers, { responseType: TTSRequest.RESPONSE_TYPE_ARRAYBUFFER }) 595 | .then(this.resolveTTSPromise) 596 | .catch(this.rejectTTSPromise.bind(this)); 597 | }; 598 | TTSRequest.prototype.makeRequest = function (url, params, headers, options) { 599 | return XhrRequest_1.default.get(url, params, headers, options); 600 | }; 601 | TTSRequest.prototype.speak = function (data) { 602 | var _this = this; 603 | if (!data.byteLength) { 604 | return Promise.reject("TTS Server unavailable"); 605 | } 606 | return new Promise(function (resolve, reject) { 607 | TTSRequest.audioContext.decodeAudioData(data, function (buffer) { 608 | return _this.playSound(buffer, resolve); 609 | }, reject).then(null, function (err) { return reject(err); }); 610 | }); 611 | }; 612 | TTSRequest.prototype.playSound = function (buffer, resolve) { 613 | var source = TTSRequest.audioContext.createBufferSource(); 614 | source.buffer = buffer; 615 | source.connect(TTSRequest.audioContext.destination); 616 | source.onended = resolve; 617 | source.start(0); 618 | }; 619 | ; 620 | return TTSRequest; 621 | }(Request_1.default)); 622 | TTSRequest.RESPONSE_TYPE_ARRAYBUFFER = "arraybuffer"; 623 | exports.TTSRequest = TTSRequest; 624 | 625 | 626 | /***/ }), 627 | /* 9 */ 628 | /***/ (function(module, exports, __webpack_require__) { 629 | 630 | "use strict"; 631 | 632 | var __extends = (this && this.__extends) || (function () { 633 | var extendStatics = Object.setPrototypeOf || 634 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 635 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 636 | return function (d, b) { 637 | extendStatics(d, b); 638 | function __() { this.constructor = d; } 639 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 640 | }; 641 | })(); 642 | Object.defineProperty(exports, "__esModule", { value: true }); 643 | var Request_1 = __webpack_require__(2); 644 | var TextRequest = (function (_super) { 645 | __extends(TextRequest, _super); 646 | function TextRequest() { 647 | return _super !== null && _super.apply(this, arguments) || this; 648 | } 649 | return TextRequest; 650 | }(Request_1.default)); 651 | exports.default = TextRequest; 652 | 653 | 654 | /***/ }), 655 | /* 10 */ 656 | /***/ (function(module, exports, __webpack_require__) { 657 | 658 | module.exports = __webpack_require__(4); 659 | 660 | 661 | /***/ }) 662 | /******/ ]); 663 | //# sourceMappingURL=ApiAi.streamless.js.map -------------------------------------------------------------------------------- /target/ApiAi.streamless.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | var ApiAi=function(e){function __webpack_require__(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,__webpack_require__),r.l=!0,r.exports}var t={};return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.i=function(e){return e},__webpack_require__.d=function(e,t,n){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:n})},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="/target/",__webpack_require__(__webpack_require__.s=10)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});!function(e){var t;!function(e){e[e.EN="en"]="EN",e[e.DE="de"]="DE",e[e.ES="es"]="ES",e[e.PT_BR="pt-BR"]="PT_BR",e[e.ZH_HK="zh-HK"]="ZH_HK",e[e.ZH_CN="zh-CN"]="ZH_CN",e[e.ZH_TW="zh-TW"]="ZH_TW",e[e.NL="nl"]="NL",e[e.FR="fr"]="FR",e[e.IT="it"]="IT",e[e.JA="ja"]="JA",e[e.KO="ko"]="KO",e[e.PT="pt"]="PT",e[e.RU="ru"]="RU",e[e.UK="uk"]="UK"}(t=e.AVAILABLE_LANGUAGES||(e.AVAILABLE_LANGUAGES={})),e.VERSION="2.0.0-beta.18",e.DEFAULT_BASE_URL="https://api.api.ai/v1/",e.DEFAULT_API_VERSION="20150910",e.DEFAULT_CLIENT_LANG=t.EN,e.DEFAULT_TTS_HOST="https://api.api.ai/api/tts"}(t.ApiAiConstants||(t.ApiAiConstants={}))},function(e,t,n){"use strict";var r=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};return function(t,n){function __(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}();Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){function ApiAiBaseError(t){var n=e.call(this,t)||this;return n.message=t,n.stack=(new Error).stack,n}return r(ApiAiBaseError,e),ApiAiBaseError}(Error);t.ApiAiBaseError=i;var o=function(e){function ApiAiClientConfigurationError(t){var n=e.call(this,t)||this;return n.name="ApiAiClientConfigurationError",n}return r(ApiAiClientConfigurationError,e),ApiAiClientConfigurationError}(i);t.ApiAiClientConfigurationError=o;var s=function(e){function ApiAiRequestError(t,n){void 0===n&&(n=null);var r=e.call(this,t)||this;return r.message=t,r.code=n,r.name="ApiAiRequestError",r}return r(ApiAiRequestError,e),ApiAiRequestError}(i);t.ApiAiRequestError=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=n(3),o=function(){function Request(e,t){this.apiAiClient=e,this.options=t,this.uri=this.apiAiClient.getApiBaseUrl()+"query?v="+this.apiAiClient.getApiVersion(),this.requestMethod=i.default.Method.POST,this.headers={Authorization:"Bearer "+this.apiAiClient.getAccessToken()},this.options.lang=this.apiAiClient.getApiLang(),this.options.sessionId=this.apiAiClient.getSessionId()}return Request.handleSuccess=function(e){return Promise.resolve(JSON.parse(e.responseText))},Request.handleError=function(e){var t=new r.ApiAiRequestError(null);try{var n=JSON.parse(e.responseText);t=n.status&&n.status.errorDetails?new r.ApiAiRequestError(n.status.errorDetails,n.status.code):new r.ApiAiRequestError(e.statusText,e.status)}catch(n){t=new r.ApiAiRequestError(e.statusText,e.status)}return Promise.reject(t)},Request.prototype.perform=function(e){void 0===e&&(e=null);var t=e||this.options;return i.default.ajax(this.requestMethod,this.uri,t,this.headers).then(Request.handleSuccess.bind(this)).catch(Request.handleError.bind(this))},Request}();t.default=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function XhrRequest(){}return XhrRequest.ajax=function(e,t,n,r,i){return void 0===n&&(n=null),void 0===r&&(r=null),void 0===i&&(i={}),new Promise(function(o,s){var u=XhrRequest.createXMLHTTPObject(),a=t,_=null;if(n&&e===XhrRequest.Method.GET){a+="?";var p=0;for(var c in n)n.hasOwnProperty(c)&&(p++&&(a+="&"),a+=encodeURIComponent(c)+"="+encodeURIComponent(n[c]))}else n&&(r||(r={}),r["Content-Type"]="application/json; charset=utf-8",_=JSON.stringify(n));for(var c in i)c in u&&(u[c]=i[c]);if(u.open(XhrRequest.Method[e],a,!0),r)for(var c in r)r.hasOwnProperty(c)&&u.setRequestHeader(c,r[c]);_?u.send(_):u.send(),u.onload=function(){u.status>=200&&u.status<300?o(u):s(u)},u.onerror=function(){s(u)}})},XhrRequest.get=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.GET,e,t,n,r)},XhrRequest.post=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.POST,e,t,n,r)},XhrRequest.put=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.PUT,e,t,n,r)},XhrRequest.delete=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.DELETE,e,t,n,r)},XhrRequest.createXMLHTTPObject=function(){for(var e=null,t=0,n=XhrRequest.XMLHttpFactories;t { 50 | if (!query) { 51 | throw new ApiAiClientConfigurationError("Query should not be empty"); 52 | } 53 | options.query = query; 54 | return new TextRequest(this, options).perform(); 55 | } 56 | 57 | public eventRequest(eventName, eventData: IStringMap = {}, 58 | options: IRequestOptions = {}): Promise { 59 | if (!eventName) { 60 | throw new ApiAiClientConfigurationError("Event name can not be empty"); 61 | } 62 | options.event = {name: eventName, data: eventData}; 63 | return new EventRequest(this, options).perform(); 64 | } 65 | 66 | // @todo: implement local tts request 67 | /*public ttsRequest(query) { 68 | if (!query) { 69 | throw new ApiAiClientConfigurationError("Query should not be empty"); 70 | } 71 | return new TTSRequest(this).makeTTSRequest(query); 72 | }*/ 73 | 74 | /*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest { 75 | return new UserEntitiesRequest(this, options); 76 | }*/ 77 | 78 | public getAccessToken(): string { 79 | return this.accessToken; 80 | } 81 | 82 | public getApiVersion(): string { 83 | return (this.apiVersion) ? this.apiVersion : ApiAiConstants.DEFAULT_API_VERSION; 84 | } 85 | 86 | public getApiLang(): ApiAiConstants.AVAILABLE_LANGUAGES { 87 | return (this.apiLang) ? this.apiLang : ApiAiConstants.DEFAULT_CLIENT_LANG; 88 | } 89 | 90 | public getApiBaseUrl(): string { 91 | return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants.DEFAULT_BASE_URL; 92 | } 93 | 94 | public setSessionId(sessionId: string) { 95 | this.sessionId = sessionId; 96 | } 97 | 98 | public getSessionId(): string { 99 | return this.sessionId; 100 | } 101 | 102 | /** 103 | * generates new random UUID 104 | * @returns {string} 105 | */ 106 | private guid(): string { 107 | const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); 108 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" + 109 | s4() + "-" + s4() + s4() + s4(); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /ts/ApiAiConstants.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export namespace ApiAiConstants { 18 | export enum AVAILABLE_LANGUAGES { 19 | EN = "en" as any, DE = "de" as any, ES = "es" as any, PT_BR = "pt-BR" as any, ZH_HK = "zh-HK" as any, 20 | ZH_CN = "zh-CN" as any, ZH_TW = "zh-TW" as any, NL = "nl" as any, FR = "fr" as any, IT = "it" as any, 21 | JA = "ja" as any, KO = "ko" as any, PT = "pt" as any, RU = "ru" as any, UK = "uk" as any 22 | } 23 | 24 | export const VERSION: string = "2.0.0-beta.20"; 25 | export const DEFAULT_BASE_URL: string = "https://api.api.ai/v1/"; 26 | export const DEFAULT_API_VERSION: string = "20150910"; 27 | export const DEFAULT_CLIENT_LANG: AVAILABLE_LANGUAGES = AVAILABLE_LANGUAGES.EN; 28 | } 29 | -------------------------------------------------------------------------------- /ts/Errors.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export abstract class ApiAiBaseError extends Error { 18 | 19 | public abstract name: string; 20 | public stack: string; 21 | constructor(public message: string) { 22 | super(message); 23 | this.stack = new Error().stack; 24 | } 25 | } 26 | 27 | export class ApiAiClientConfigurationError extends ApiAiBaseError { 28 | 29 | public name: string = "ApiAiClientConfigurationError"; 30 | 31 | constructor(message: string) { 32 | super(message); 33 | } 34 | } 35 | 36 | export class ApiAiRequestError extends ApiAiBaseError { 37 | 38 | public name: string = "ApiAiRequestError"; 39 | 40 | constructor(public message: string, public code: number = null) { 41 | super(message); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ts/Interfaces.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiConstants} from "./ApiAiConstants"; 18 | 19 | export interface IRequestOptions { 20 | query?: string; 21 | event?: {name: string, data?: IStringMap}; 22 | sessionId?: string; 23 | lang?: ApiAiConstants.AVAILABLE_LANGUAGES; 24 | originalRequest?: {source: string, data?: IStringMap}; 25 | } 26 | 27 | export interface IServerResponse { 28 | id?: string; 29 | result?: { 30 | action: string, 31 | resolvedQuery: string, 32 | speech: string; 33 | fulfillment?: { 34 | speech: string 35 | } 36 | }; 37 | status: { 38 | code: number, 39 | errorDetails?: string, 40 | errorID?: string, 41 | errorType: string 42 | }; 43 | } 44 | 45 | export interface IStringMap { [s: string]: string; } 46 | 47 | export interface IApiClientOptions { 48 | lang?: ApiAiConstants.AVAILABLE_LANGUAGES; 49 | version?: string; 50 | baseUrl?: string; 51 | sessionId?: string; 52 | streamClientClass?: IStreamClientConstructor; 53 | accessToken: string; 54 | } 55 | 56 | export interface IStreamClientConstructor { 57 | new (options: IStreamClientOptions): IStreamClient; 58 | } 59 | 60 | export interface IStreamClient { 61 | init(): void; 62 | open(): void; 63 | close(): void; 64 | startListening(): void; 65 | stopListening(): void; 66 | } 67 | 68 | export interface IStreamClientOptions { 69 | server?: string; 70 | token?: string; 71 | sessionId?: string; 72 | lang?: ApiAiConstants.AVAILABLE_LANGUAGES; 73 | contentType?: string; 74 | readingInterval?: string; 75 | onOpen?: () => void; 76 | onClose?: () => void; 77 | onInit?: () => void; 78 | onStartListening?: () => void; 79 | onStopListening?: () => void; 80 | onResults?: (data: IServerResponse) => void; 81 | onEvent?: (eventCode: IStreamClient.EVENT, message: string) => void; 82 | onError?: (errorCode: IStreamClient.ERROR, message: string) => void; 83 | } 84 | 85 | export namespace IStreamClient { 86 | export enum ERROR { 87 | ERR_NETWORK, 88 | ERR_AUDIO, 89 | ERR_SERVER, 90 | ERR_CLIENT 91 | } 92 | export enum EVENT { 93 | MSG_WAITING_MICROPHONE, 94 | MSG_MEDIA_STREAM_CREATED, 95 | MSG_INIT_RECORDER, 96 | MSG_RECORDING, 97 | MSG_SEND, 98 | MSG_SEND_EMPTY, 99 | MSG_SEND_EOS_OR_JSON, 100 | MSG_WEB_SOCKET, 101 | MSG_WEB_SOCKET_OPEN, 102 | MSG_WEB_SOCKET_CLOSE, 103 | MSG_STOP, 104 | MSG_CONFIG_CHANGED 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /ts/Models/Entity.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class Entity implements IEntity{ 18 | public name: string; 19 | public entires: Entity.Entry[]; 20 | } 21 | 22 | export namespace Entity { 23 | export class Entry implements IEntity.IEntry { 24 | public value: string; 25 | public synonyms: string[]; 26 | } 27 | } 28 | 29 | export interface IEntity { 30 | name: string; 31 | entires: IEntity.IEntry[]; 32 | } 33 | 34 | export namespace IEntity { 35 | export interface IEntry { 36 | value: string; 37 | synonyms: string[]; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ts/Request/ContextsRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | /** 19 | * @todo: implement 20 | */ 21 | 22 | export class ContextsRequest extends Request {} 23 | -------------------------------------------------------------------------------- /ts/Request/EventRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export class EventRequest extends Request { 19 | 20 | } 21 | -------------------------------------------------------------------------------- /ts/Request/LocalTTSRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class LocalTTSRequest { 18 | private isSupported() { 19 | return !!window.speechSynthesis; 20 | } 21 | private getLanguage() { 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ts/Request/Request.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {ApiAiRequestError} from "../Errors"; 19 | import {IRequestOptions, IServerResponse, IStringMap} from "../Interfaces"; 20 | import XhrRequest from "../XhrRequest"; 21 | 22 | abstract class Request { 23 | 24 | private static handleSuccess(xhr: XMLHttpRequest): Promise { 25 | return Promise.resolve(JSON.parse(xhr.responseText)); 26 | } 27 | 28 | private static handleError(xhr: XMLHttpRequest): Promise { 29 | 30 | let error = new ApiAiRequestError(null); 31 | try { 32 | const serverResponse: IServerResponse = JSON.parse(xhr.responseText); 33 | if (serverResponse.status && serverResponse.status.errorDetails) { 34 | error = new ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code); 35 | } else { 36 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 37 | } 38 | } catch (e) { 39 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 40 | } 41 | 42 | return Promise.reject(error); 43 | } 44 | 45 | protected uri; 46 | protected requestMethod; 47 | protected headers; 48 | 49 | constructor(protected apiAiClient: ApiAiClient, protected options: IRequestOptions) { 50 | 51 | this.uri = this.apiAiClient.getApiBaseUrl() + "query?v=" + this.apiAiClient.getApiVersion(); 52 | this.requestMethod = XhrRequest.Method.POST; 53 | this.headers = { 54 | Authorization: "Bearer " + this.apiAiClient.getAccessToken(), 55 | }; 56 | 57 | this.options.lang = this.apiAiClient.getApiLang(); 58 | this.options.sessionId = this.apiAiClient.getSessionId(); 59 | 60 | } 61 | 62 | public perform(overrideOptions = null): Promise { 63 | 64 | const options = overrideOptions ? overrideOptions : this.options; 65 | 66 | return XhrRequest.ajax(this.requestMethod, this.uri, options as IStringMap, this.headers) 67 | .then(Request.handleSuccess.bind(this)) 68 | .catch(Request.handleError.bind(this)); 69 | } 70 | } 71 | 72 | export default Request; 73 | -------------------------------------------------------------------------------- /ts/Request/TTSRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {ApiAiConstants} from "../ApiAiConstants"; 19 | import {ApiAiClientConfigurationError, ApiAiRequestError} from "../Errors"; 20 | import {IRequestOptions} from "../Interfaces"; 21 | import XhrRequest from "../XhrRequest"; 22 | import Request from "./Request"; 23 | 24 | export class TTSRequest extends Request { 25 | 26 | private static RESPONSE_TYPE_ARRAYBUFFER = "arraybuffer"; 27 | 28 | private static audioContext: AudioContext; 29 | 30 | constructor(protected apiAiClient: ApiAiClient, options: IRequestOptions = {}) { 31 | super(apiAiClient, options); 32 | // this.requestMethod = XhrRequest.Method.GET; 33 | this.uri = ApiAiConstants.DEFAULT_TTS_HOST; 34 | const AudioContext = window.AudioContext || webkitAudioContext; 35 | 36 | if (!TTSRequest.audioContext) { 37 | TTSRequest.audioContext = new AudioContext(); 38 | } 39 | } 40 | 41 | public makeTTSRequest(text: string) { 42 | 43 | if (!text) { 44 | throw new ApiAiClientConfigurationError("Request can not be empty"); 45 | } 46 | 47 | const params = { 48 | lang: "en-US", // this.apiAiClient.getApiLang(), 49 | text: encodeURIComponent(text), 50 | v: this.apiAiClient.getApiVersion() 51 | }; 52 | 53 | const headers = { 54 | "Accept-language": "en-US", 55 | "Authorization": "Bearer " + this.apiAiClient.getAccessToken() 56 | }; 57 | 58 | return this.makeRequest(this.uri, params, headers, {responseType: TTSRequest.RESPONSE_TYPE_ARRAYBUFFER}) 59 | .then(this.resolveTTSPromise) 60 | .catch(this.rejectTTSPromise.bind(this)) 61 | ; 62 | } 63 | 64 | private resolveTTSPromise = (data: {response: ArrayBuffer}) => { 65 | return this.speak(data.response); 66 | } 67 | 68 | private rejectTTSPromise = (reason: string) => { 69 | throw new ApiAiRequestError(reason); 70 | } 71 | 72 | private makeRequest(url, params, headers, options): Promise<{response: ArrayBuffer}> { 73 | return XhrRequest.get(url, params, headers, options); 74 | } 75 | 76 | private speak(data: ArrayBuffer): Promise { 77 | 78 | if (!data.byteLength) { 79 | return Promise.reject("TTS Server unavailable"); 80 | } 81 | 82 | return new Promise((resolve, reject) => { 83 | TTSRequest.audioContext.decodeAudioData( 84 | data, 85 | (buffer: AudioBuffer) => { 86 | return this.playSound(buffer, resolve); 87 | }, 88 | reject 89 | ).then(null, (err) => reject(err)); 90 | }); 91 | } 92 | 93 | private playSound(buffer: AudioBuffer, resolve) { 94 | const source = TTSRequest.audioContext.createBufferSource(); 95 | source.buffer = buffer; 96 | source.connect(TTSRequest.audioContext.destination); 97 | source.onended = resolve; 98 | source.start(0); 99 | }; 100 | } 101 | -------------------------------------------------------------------------------- /ts/Request/TextRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export default class TextRequest extends Request { 19 | 20 | } 21 | -------------------------------------------------------------------------------- /ts/Request/UserEntitiesRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {IRequestOptions} from "../Interfaces"; 19 | import {IEntity} from "../Models/Entity"; 20 | import ApiAiUtils from "../Utils"; 21 | import XhrRequest from "../XhrRequest"; 22 | import Request from "./Request"; 23 | 24 | export class UserEntitiesRequest extends Request { 25 | 26 | private static ENDPOINT: string = "userEntities"; 27 | private baseUri: string; 28 | 29 | constructor(apiAiClient: ApiAiClient, protected options: IUserEntitiesRequestOptions = {}) { 30 | super(apiAiClient, options); 31 | this.baseUri = this.apiAiClient.getApiBaseUrl() + UserEntitiesRequest.ENDPOINT; 32 | } 33 | 34 | public create(entities: IEntity[]|IEntity) { 35 | this.uri = this.baseUri; 36 | const options = ApiAiUtils.cloneObject(this.options); 37 | options.entities = Array.isArray(entities) ? entities : [entities]; 38 | return this.perform(options); 39 | } 40 | 41 | public retrieve(name: string) { 42 | this.uri = this.baseUri + "/" + name; 43 | this.requestMethod = XhrRequest.Method.GET; 44 | return this.perform(); 45 | } 46 | 47 | public update(name: string, entries: IEntity.IEntry[], extend: boolean = false) { 48 | this.uri = this.baseUri + "/" + name; 49 | this.requestMethod = XhrRequest.Method.PUT; 50 | const options = ApiAiUtils.cloneObject(this.options); 51 | options.extend = extend; 52 | options.entries = entries; 53 | options.name = name; 54 | return this.perform(options); 55 | } 56 | 57 | public delete(name: string) { 58 | this.uri = this.baseUri + "/" + name; 59 | this.requestMethod = XhrRequest.Method.DELETE; 60 | return this.perform(); 61 | } 62 | } 63 | 64 | interface IUserEntitiesRequestOptions extends IRequestOptions { 65 | extend?: boolean; 66 | name?: string; 67 | entities?: IEntity[]; 68 | entries?: IEntity.IEntry[]; 69 | } 70 | -------------------------------------------------------------------------------- /ts/Request/VoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {IRequestOptions} from "../Interfaces"; 19 | import Request from "./Request"; 20 | 21 | /** 22 | * @todo: implement 23 | */ 24 | 25 | class VoiceRequest extends Request { 26 | constructor(client: ApiAiClient, options: IRequestOptions = {}) { 27 | super(client, options); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ts/Utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export default class ApiAiUtils { 18 | /** 19 | * make it in more appropriate way 20 | * @param object 21 | * @returns object 22 | */ 23 | public static cloneObject(object: T): T { 24 | return JSON.parse(JSON.stringify(object)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ts/XhrRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {IStringMap} from "./Interfaces"; 18 | /** 19 | * quick ts implementation of example from 20 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise 21 | * with some minor improvements 22 | * @todo: test (?) 23 | * @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform 24 | */ 25 | class XhrRequest { 26 | // Method that performs the ajax request 27 | public static ajax( 28 | method: XhrRequest.Method, 29 | url: string, 30 | args: IStringMap = null, 31 | headers: IStringMap = null, 32 | options: IStringMap = {} 33 | ): Promise { 34 | 35 | // Creating a promise 36 | return new Promise((resolve, reject) => { 37 | 38 | // Instantiates the XMLHttpRequest 39 | const client: XMLHttpRequest = XhrRequest.createXMLHTTPObject(); 40 | let uri: string = url; 41 | let payload = null; 42 | 43 | // Add given payload to get request 44 | if (args && (method === XhrRequest.Method.GET)) { 45 | uri += "?"; 46 | let argcount = 0; 47 | for (const key in args) { 48 | if (args.hasOwnProperty(key)) { 49 | if (argcount++) { 50 | uri += "&"; 51 | } 52 | uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]); 53 | } 54 | } 55 | } else if (args) { 56 | if (!headers) { 57 | headers = {}; 58 | } 59 | headers["Content-Type"] = "application/json; charset=utf-8"; 60 | payload = JSON.stringify(args); 61 | } 62 | 63 | for (const key in options) { 64 | if (key in client) { 65 | client[key] = options[key]; 66 | } 67 | } 68 | 69 | // hack: method[method] is somewhat like .toString for enum Method 70 | // should be made in normal way 71 | client.open(XhrRequest.Method[method], uri, true); 72 | // Add given headers 73 | 74 | if (headers) { 75 | for (const key in headers) { 76 | if (headers.hasOwnProperty(key)) { 77 | client.setRequestHeader(key, headers[key]); 78 | } 79 | } 80 | } 81 | 82 | payload ? client.send(payload) : client.send(); 83 | 84 | client.onload = () => { 85 | if (client.status >= 200 && client.status < 300) { 86 | // Performs the function "resolve" when this.status is equal to 2xx 87 | resolve(client); 88 | } else { 89 | // Performs the function "reject" when this.status is different than 2xx 90 | reject(client); 91 | } 92 | }; 93 | client.onerror = () => { 94 | reject(client); 95 | }; 96 | }); 97 | 98 | } 99 | 100 | public static get(url, payload: IStringMap = null, headers: IStringMap = null, options = {}): Promise { 101 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 102 | } 103 | 104 | public static post(url: string, payload: IStringMap = null, headers: IStringMap = null, 105 | options = {}): Promise { 106 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 107 | } 108 | 109 | public static put(url: string, payload: IStringMap = null, headers: IStringMap = null, 110 | options = {}): Promise { 111 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 112 | } 113 | 114 | public static delete(url: string, payload: IStringMap = null, headers: IStringMap = null, 115 | options = {}): Promise { 116 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 117 | } 118 | 119 | private static XMLHttpFactories: Function[] = [ 120 | () => new XMLHttpRequest(), 121 | () => new window["ActiveXObject"]("Msxml2.XMLHTTP"), 122 | () => new window["ActiveXObject"]("Msxml3.XMLHTTP"), 123 | () => new window["ActiveXObject"]("Microsoft.XMLHTTP") 124 | ]; 125 | 126 | private static createXMLHTTPObject(): XMLHttpRequest { 127 | let xmlhttp: XMLHttpRequest = null; 128 | for (const i of XhrRequest.XMLHttpFactories) { 129 | try { 130 | xmlhttp = i(); 131 | } catch (e) { 132 | continue; 133 | } 134 | break; 135 | } 136 | 137 | return xmlhttp; 138 | } 139 | } 140 | 141 | namespace XhrRequest { 142 | export enum Method { 143 | GET = "GET" as any, 144 | POST = "POST" as any, 145 | PUT = "PUT" as any, 146 | DELETE = "DELETE" as any 147 | } 148 | } 149 | 150 | export default XhrRequest; 151 | -------------------------------------------------------------------------------- /tsconfig.es6.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES6", 4 | "outDir": "es6", 5 | "sourceMap": false, 6 | "typeRoots": ["node_modules/@types/"], 7 | "types": [], 8 | "declaration": false 9 | }, 10 | "files": [ 11 | "declarations.d.ts", 12 | "ts/ApiAiClient.ts" 13 | ] 14 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES5", 4 | "sourceMap": true, 5 | "typeRoots": ["node_modules/@types/"], 6 | "types": ["es6-promise", "mocha", "chai"] 7 | }, 8 | "files": [ 9 | "declarations.d.ts" 10 | ] 11 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:latest", 3 | "rules": { 4 | "max-classes-per-file": 0, 5 | "object-literal-sort-keys": false, 6 | "no-namespace": false, 7 | "trailing-comma": false, 8 | "no-console": false 9 | } 10 | } -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | "use strict"; 18 | 19 | const webpack = require('webpack'); 20 | const path = require('path'); 21 | 22 | let libraryName = 'ApiAi'; 23 | let libraryTarget = 'var'; 24 | let outputFile = libraryName; 25 | let sourceMaps = true; 26 | let plugins = []; 27 | let entry = "ApiAiClient.ts"; 28 | 29 | module.exports = function(env) { 30 | if (!env) { 31 | env = {}; 32 | } 33 | 34 | // handle minification 35 | if (env && env.compress) { 36 | plugins.push( 37 | new webpack.LoaderOptionsPlugin({ 38 | minimize: true, 39 | debug: false 40 | }) 41 | ); 42 | 43 | plugins.push( 44 | new webpack.optimize.UglifyJsPlugin({ 45 | compress: { 46 | warnings: true, 47 | keep_fnames: true 48 | }, 49 | mangle: { 50 | keep_fnames: true 51 | } 52 | }) 53 | ); 54 | outputFile += '.min'; 55 | sourceMaps = false; 56 | } else { 57 | // outputFile += libraryName; 58 | } 59 | 60 | // handle custom target 61 | if (env && env.target) { 62 | libraryTarget = env.target; 63 | outputFile += '.' + libraryTarget; 64 | } 65 | 66 | outputFile += '.js'; 67 | 68 | return { 69 | entry: [ 70 | path.join(__dirname, 'ts', entry) 71 | ], 72 | devtool: sourceMaps ? 'source-map' : false, 73 | output: { 74 | path: path.join(__dirname, 'target'), 75 | publicPath: "/target/", 76 | filename: outputFile, 77 | library: libraryName, 78 | libraryTarget: libraryTarget 79 | }, 80 | 81 | module: { 82 | loaders: [ 83 | {test: /\.tsx?$/, loader: "awesome-typescript-loader"} 84 | ] 85 | }, 86 | resolve: { 87 | extensions: ['.js', '.ts'] 88 | }, 89 | plugins: plugins 90 | }; 91 | }; 92 | --------------------------------------------------------------------------------