forked from jaanus/voicebot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiAi.js
1501 lines (1427 loc) · 58 KB
/
ApiAi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var ApiAi =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/target/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 17);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ApiAiConstants;
(function (ApiAiConstants) {
var AVAILABLE_LANGUAGES;
(function (AVAILABLE_LANGUAGES) {
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["EN"] = "en"] = "EN";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["DE"] = "de"] = "DE";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ES"] = "es"] = "ES";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT_BR"] = "pt-BR"] = "PT_BR";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_HK"] = "zh-HK"] = "ZH_HK";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_CN"] = "zh-CN"] = "ZH_CN";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_TW"] = "zh-TW"] = "ZH_TW";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["NL"] = "nl"] = "NL";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["FR"] = "fr"] = "FR";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["IT"] = "it"] = "IT";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["JA"] = "ja"] = "JA";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["KO"] = "ko"] = "KO";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT"] = "pt"] = "PT";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["RU"] = "ru"] = "RU";
AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["UK"] = "uk"] = "UK";
})(AVAILABLE_LANGUAGES = ApiAiConstants.AVAILABLE_LANGUAGES || (ApiAiConstants.AVAILABLE_LANGUAGES = {}));
ApiAiConstants.VERSION = "2.0.0-beta.18";
ApiAiConstants.DEFAULT_BASE_URL = "https://api.api.ai/v1/";
ApiAiConstants.DEFAULT_API_VERSION = "20150910";
ApiAiConstants.DEFAULT_CLIENT_LANG = AVAILABLE_LANGUAGES.EN;
// @todo: make configurable, ideally fix non-working v1
ApiAiConstants.DEFAULT_TTS_HOST = "https://api.api.ai/api/tts";
})(ApiAiConstants = exports.ApiAiConstants || (exports.ApiAiConstants = {}));
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var ApiAiBaseError = (function (_super) {
__extends(ApiAiBaseError, _super);
function ApiAiBaseError(message) {
var _this = _super.call(this, message) || this;
_this.message = message;
_this.stack = new Error().stack;
return _this;
}
return ApiAiBaseError;
}(Error));
var ApiAiClientConfigurationError = (function (_super) {
__extends(ApiAiClientConfigurationError, _super);
function ApiAiClientConfigurationError(message) {
var _this = _super.call(this, message) || this;
_this.name = "ApiAiClientConfigurationError";
return _this;
}
return ApiAiClientConfigurationError;
}(ApiAiBaseError));
exports.ApiAiClientConfigurationError = ApiAiClientConfigurationError;
var ApiAiRequestError = (function (_super) {
__extends(ApiAiRequestError, _super);
function ApiAiRequestError(message, code) {
if (code === void 0) { code = null; }
var _this = _super.call(this, message) || this;
_this.message = message;
_this.code = code;
_this.name = "ApiAiRequestError";
return _this;
}
return ApiAiRequestError;
}(ApiAiBaseError));
exports.ApiAiRequestError = ApiAiRequestError;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Errors_1 = __webpack_require__(1);
var XhrRequest_1 = __webpack_require__(5);
var Request = (function () {
function Request(apiAiClient, options) {
this.apiAiClient = apiAiClient;
this.options = options;
this.uri = this.apiAiClient.getApiBaseUrl() + "query?v=" + this.apiAiClient.getApiVersion();
this.requestMethod = XhrRequest_1.default.Method.POST;
this.headers = {
Authorization: "Bearer " + this.apiAiClient.getAccessToken(),
};
this.options.lang = this.apiAiClient.getApiLang();
this.options.sessionId = this.apiAiClient.getSessionId();
}
Request.handleSuccess = function (xhr) {
return Promise.resolve(JSON.parse(xhr.responseText));
};
Request.handleError = function (xhr) {
var error = new Errors_1.ApiAiRequestError(null);
try {
var serverResponse = JSON.parse(xhr.responseText);
if (serverResponse.status && serverResponse.status.errorDetails) {
error = new Errors_1.ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code);
}
else {
error = new Errors_1.ApiAiRequestError(xhr.statusText, xhr.status);
}
}
catch (e) {
error = new Errors_1.ApiAiRequestError(xhr.statusText, xhr.status);
}
return Promise.reject(error);
};
Request.prototype.perform = function (overrideOptions) {
if (overrideOptions === void 0) { overrideOptions = null; }
var options = overrideOptions ? overrideOptions : this.options;
return XhrRequest_1.default.ajax(this.requestMethod, this.uri, options, this.headers)
.then(Request.handleSuccess.bind(this))
.catch(Request.handleError.bind(this));
};
return Request;
}());
exports.default = Request;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var IStreamClient;
(function (IStreamClient) {
var ERROR;
(function (ERROR) {
ERROR[ERROR["ERR_NETWORK"] = 0] = "ERR_NETWORK";
ERROR[ERROR["ERR_AUDIO"] = 1] = "ERR_AUDIO";
ERROR[ERROR["ERR_SERVER"] = 2] = "ERR_SERVER";
ERROR[ERROR["ERR_CLIENT"] = 3] = "ERR_CLIENT";
})(ERROR = IStreamClient.ERROR || (IStreamClient.ERROR = {}));
var EVENT;
(function (EVENT) {
EVENT[EVENT["MSG_WAITING_MICROPHONE"] = 0] = "MSG_WAITING_MICROPHONE";
EVENT[EVENT["MSG_MEDIA_STREAM_CREATED"] = 1] = "MSG_MEDIA_STREAM_CREATED";
EVENT[EVENT["MSG_INIT_RECORDER"] = 2] = "MSG_INIT_RECORDER";
EVENT[EVENT["MSG_RECORDING"] = 3] = "MSG_RECORDING";
EVENT[EVENT["MSG_SEND"] = 4] = "MSG_SEND";
EVENT[EVENT["MSG_SEND_EMPTY"] = 5] = "MSG_SEND_EMPTY";
EVENT[EVENT["MSG_SEND_EOS_OR_JSON"] = 6] = "MSG_SEND_EOS_OR_JSON";
EVENT[EVENT["MSG_WEB_SOCKET"] = 7] = "MSG_WEB_SOCKET";
EVENT[EVENT["MSG_WEB_SOCKET_OPEN"] = 8] = "MSG_WEB_SOCKET_OPEN";
EVENT[EVENT["MSG_WEB_SOCKET_CLOSE"] = 9] = "MSG_WEB_SOCKET_CLOSE";
EVENT[EVENT["MSG_STOP"] = 10] = "MSG_STOP";
EVENT[EVENT["MSG_CONFIG_CHANGED"] = 11] = "MSG_CONFIG_CHANGED";
})(EVENT = IStreamClient.EVENT || (IStreamClient.EVENT = {}));
})(IStreamClient = exports.IStreamClient || (exports.IStreamClient = {}));
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* this module is full copy-paste from v1 sdk. It should be like that while we send 'resempler' to worker as
* 'function body'
* @todo: re-make as normal class
* @private
*/
Object.defineProperty(exports, "__esModule", { value: true });
function _resamplerJs() {
function Resampler(fromSampleRate, toSampleRate, channels, outputBufferSize, noReturn) {
this.fromSampleRate = fromSampleRate;
this.toSampleRate = toSampleRate;
this.channels = channels | 0;
this.outputBufferSize = outputBufferSize;
this.noReturn = !!noReturn;
this.initialize();
}
Resampler.prototype.initialize = function () {
//Perform some checks:
if (this.fromSampleRate <= 0 || this.toSampleRate <= 0 || this.channels <= 0) {
throw (new Error("Invalid settings specified for the resampler."));
}
if (this.fromSampleRate == this.toSampleRate) {
//Setup a resampler bypass:
this.resampler = this.bypassResampler; //Resampler just returns what was passed through.
this.ratioWeight = 1;
}
else {
//Resampler is a custom quality interpolation algorithm.
this.resampler = function (buffer) {
var bufferLength = Math.min(buffer.length, this.outputBufferSize);
if ((bufferLength % this.channels) != 0) {
throw (new Error("Buffer was of incorrect sample length."));
}
if (bufferLength <= 0) {
return (this.noReturn) ? 0 : [];
}
var weight = 0;
var output = new Array(this.channels);
for (var channel = 0; channel < this.channels; ++channel) {
output[channel] = 0;
}
var actualPosition = 0;
var amountToNext = 0;
var alreadyProcessedTail = !this.tailExists;
this.tailExists = false;
var outputBuffer = this.outputBuffer;
var outputOffset = 0;
var currentPosition = 0;
var ratioWeight = this.ratioWeight;
do {
if (alreadyProcessedTail) {
weight = ratioWeight;
for (channel = 0; channel < this.channels; ++channel) {
output[channel] = 0;
}
}
else {
weight = this.lastWeight;
for (channel = 0; channel < this.channels; ++channel) {
output[channel] = this.lastOutput[channel];
}
alreadyProcessedTail = true;
}
while (weight > 0 && actualPosition < bufferLength) {
amountToNext = 1 + actualPosition - currentPosition;
if (weight >= amountToNext) {
for (channel = 0; channel < this.channels; ++channel) {
output[channel] += buffer[actualPosition++] * amountToNext;
}
currentPosition = actualPosition;
weight -= amountToNext;
}
else {
for (channel = 0; channel < this.channels; ++channel) {
output[channel] += buffer[actualPosition + ((channel > 0) ? channel : 0)] * weight;
}
currentPosition += weight;
weight = 0;
break;
}
}
if (weight == 0) {
for (channel = 0; channel < this.channels; ++channel) {
outputBuffer[outputOffset++] = output[channel] / ratioWeight;
}
}
else {
this.lastWeight = weight;
for (channel = 0; channel < this.channels; ++channel) {
this.lastOutput[channel] = output[channel];
}
this.tailExists = true;
break;
}
} while (actualPosition < bufferLength);
return this.bufferSlice(outputOffset);
};
this.ratioWeight = this.fromSampleRate / this.toSampleRate;
this.tailExists = false;
this.lastWeight = 0;
this.initializeBuffers();
}
};
Resampler.prototype.bypassResampler = function (buffer) {
if (this.noReturn) {
//Set the buffer passed as our own, as we don't need to resample it:
this.outputBuffer = buffer;
return buffer.length;
}
else {
//Just return the buffer passsed:
return buffer;
}
};
Resampler.prototype.bufferSlice = function (sliceAmount) {
if (this.noReturn) {
//If we're going to access the properties directly from this object:
return sliceAmount;
}
else {
//Typed array and normal array buffer section referencing:
try {
return this.outputBuffer.subarray(0, sliceAmount);
}
catch (error) {
try {
//Regular array pass:
this.outputBuffer.length = sliceAmount;
return this.outputBuffer;
}
catch (error) {
//Nightly Firefox 4 used to have the subarray function named as slice:
return this.outputBuffer.slice(0, sliceAmount);
}
}
}
};
Resampler.prototype.initializeBuffers = function () {
//Initialize the internal buffer:
try {
this.outputBuffer = new Float32Array(this.outputBufferSize);
this.lastOutput = new Float32Array(this.channels);
}
catch (error) {
this.outputBuffer = [];
this.lastOutput = [];
}
};
navigator.Resampler = Resampler;
}
exports.default = _resamplerJs;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* quick ts implementation of example from
* https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
* with some minor improvements
* @todo: test (?)
* @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform
*/
var XhrRequest = (function () {
function XhrRequest() {
}
// Method that performs the ajax request
XhrRequest.ajax = function (method, url, args, headers, options) {
if (args === void 0) { args = null; }
if (headers === void 0) { headers = null; }
if (options === void 0) { options = {}; }
// Creating a promise
return new Promise(function (resolve, reject) {
// Instantiates the XMLHttpRequest
var client = XhrRequest.createXMLHTTPObject();
var uri = url;
var payload = null;
// Add given payload to get request
if (args && (method === XhrRequest.Method.GET)) {
uri += "?";
var argcount = 0;
for (var key in args) {
if (args.hasOwnProperty(key)) {
if (argcount++) {
uri += "&";
}
uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]);
}
}
}
else if (args) {
if (!headers) {
headers = {};
}
headers["Content-Type"] = "application/json; charset=utf-8";
payload = JSON.stringify(args);
}
for (var key in options) {
if (key in client) {
client[key] = options[key];
}
}
// hack: method[method] is somewhat like .toString for enum Method
// should be made in normal way
client.open(XhrRequest.Method[method], uri, true);
// Add given headers
if (headers) {
for (var key in headers) {
if (headers.hasOwnProperty(key)) {
client.setRequestHeader(key, headers[key]);
}
}
}
payload ? client.send(payload) : client.send();
client.onload = function () {
if (client.status >= 200 && client.status < 300) {
// Performs the function "resolve" when this.status is equal to 2xx
resolve(client);
}
else {
// Performs the function "reject" when this.status is different than 2xx
reject(client);
}
};
client.onerror = function () {
reject(client);
};
});
};
XhrRequest.get = function (url, payload, headers, options) {
if (payload === void 0) { payload = null; }
if (headers === void 0) { headers = null; }
if (options === void 0) { options = {}; }
return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options);
};
XhrRequest.post = function (url, payload, headers, options) {
if (payload === void 0) { payload = null; }
if (headers === void 0) { headers = null; }
if (options === void 0) { options = {}; }
return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options);
};
XhrRequest.put = function (url, payload, headers, options) {
if (payload === void 0) { payload = null; }
if (headers === void 0) { headers = null; }
if (options === void 0) { options = {}; }
return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options);
};
XhrRequest.delete = function (url, payload, headers, options) {
if (payload === void 0) { payload = null; }
if (headers === void 0) { headers = null; }
if (options === void 0) { options = {}; }
return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options);
};
XhrRequest.createXMLHTTPObject = function () {
var xmlhttp = null;
for (var _i = 0, _a = XhrRequest.XMLHttpFactories; _i < _a.length; _i++) {
var i = _a[_i];
try {
xmlhttp = i();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
};
return XhrRequest;
}());
XhrRequest.XMLHttpFactories = [
function () { return new XMLHttpRequest(); },
function () { return new window["ActiveXObject"]("Msxml2.XMLHTTP"); },
function () { return new window["ActiveXObject"]("Msxml3.XMLHTTP"); },
function () { return new window["ActiveXObject"]("Microsoft.XMLHTTP"); }
];
(function (XhrRequest) {
var Method;
(function (Method) {
Method[Method["GET"] = "GET"] = "GET";
Method[Method["POST"] = "POST"] = "POST";
Method[Method["PUT"] = "PUT"] = "PUT";
Method[Method["DELETE"] = "DELETE"] = "DELETE";
})(Method = XhrRequest.Method || (XhrRequest.Method = {}));
})(XhrRequest || (XhrRequest = {}));
exports.default = XhrRequest;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(7));
var ApiAiStreamClient_1 = __webpack_require__(8);
exports.ApiAiStreamClient = ApiAiStreamClient_1.ApiAiStreamClient;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var ApiAiConstants_1 = __webpack_require__(0);
var Errors_1 = __webpack_require__(1);
var EventRequest_1 = __webpack_require__(9);
var TextRequest_1 = __webpack_require__(11);
var TTSRequest_1 = __webpack_require__(10);
__export(__webpack_require__(3));
var ApiAiConstants_2 = __webpack_require__(0);
exports.ApiAiConstants = ApiAiConstants_2.ApiAiConstants;
var ApiAiClient = (function () {
function ApiAiClient(options) {
if (!options || !options.accessToken) {
throw new Errors_1.ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance");
}
this.accessToken = options.accessToken;
this.apiLang = options.lang || ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG;
this.apiVersion = options.version || ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION;
this.apiBaseUrl = options.baseUrl || ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL;
this.sessionId = options.sessionId || this.guid();
this.streamClientClass = options.streamClientClass || null;
}
ApiAiClient.prototype.textRequest = function (query, options) {
if (options === void 0) { options = {}; }
if (!query) {
throw new Errors_1.ApiAiClientConfigurationError("Query should not be empty");
}
options.query = query;
return new TextRequest_1.default(this, options).perform();
};
ApiAiClient.prototype.eventRequest = function (eventName, eventData, options) {
if (eventData === void 0) { eventData = {}; }
if (options === void 0) { options = {}; }
if (!eventName) {
throw new Errors_1.ApiAiClientConfigurationError("Event name can not be empty");
}
options.event = { name: eventName, data: eventData };
return new EventRequest_1.EventRequest(this, options).perform();
};
ApiAiClient.prototype.ttsRequest = function (query) {
if (!query) {
throw new Errors_1.ApiAiClientConfigurationError("Query should not be empty");
}
return new TTSRequest_1.TTSRequest(this).makeTTSRequest(query);
};
/*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest {
return new UserEntitiesRequest(this, options);
}*/
ApiAiClient.prototype.createStreamClient = function (streamClientOptions) {
if (streamClientOptions === void 0) { streamClientOptions = {}; }
if (this.streamClientClass) {
streamClientOptions.token = this.getAccessToken();
streamClientOptions.sessionId = this.getSessionId();
streamClientOptions.lang = this.getApiLang();
return new this.streamClientClass(streamClientOptions);
}
else {
throw new Errors_1.ApiAiClientConfigurationError("No StreamClient implementation given to ApiAi Client constructor");
}
};
ApiAiClient.prototype.getAccessToken = function () {
return this.accessToken;
};
ApiAiClient.prototype.getApiVersion = function () {
return (this.apiVersion) ? this.apiVersion : ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION;
};
ApiAiClient.prototype.getApiLang = function () {
return (this.apiLang) ? this.apiLang : ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG;
};
ApiAiClient.prototype.getApiBaseUrl = function () {
return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL;
};
ApiAiClient.prototype.setSessionId = function (sessionId) {
this.sessionId = sessionId;
};
ApiAiClient.prototype.getSessionId = function () {
return this.sessionId;
};
/**
* generates new random UUID
* @returns {string}
*/
ApiAiClient.prototype.guid = function () {
var s4 = function () { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); };
return s4() + s4() + "-" + s4() + "-" + s4() + "-" +
s4() + "-" + s4() + s4() + s4();
};
return ApiAiClient;
}());
exports.ApiAiClient = ApiAiClient;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var StreamClient_1 = __webpack_require__(15);
/**
* @deprecated
*/
var ApiAiStreamClient = (function (_super) {
__extends(ApiAiStreamClient, _super);
function ApiAiStreamClient(streamClientOptions) {
if (streamClientOptions === void 0) { streamClientOptions = {}; }
var _this = this;
if (!streamClientOptions.server) {
streamClientOptions.server = ""
+ ApiAiStreamClient.STREAM_CLIENT_SERVER_PROTO
+ "://" + ApiAiStreamClient.DEFAULT_STREAM_CLIENT_BASE_URL
+ ApiAiStreamClient.STREAM_CLIENT_SERVER_PATH;
}
_this = _super.call(this, streamClientOptions) || this;
return _this;
}
return ApiAiStreamClient;
}(StreamClient_1.default));
ApiAiStreamClient.DEFAULT_STREAM_CLIENT_BASE_URL = "api-ws.api.ai:4435/v1/";
ApiAiStreamClient.STREAM_CLIENT_SERVER_PROTO = "wss";
ApiAiStreamClient.STREAM_CLIENT_SERVER_PATH = "/ws/query";
exports.ApiAiStreamClient = ApiAiStreamClient;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Request_1 = __webpack_require__(2);
var EventRequest = (function (_super) {
__extends(EventRequest, _super);
function EventRequest() {
return _super !== null && _super.apply(this, arguments) || this;
}
return EventRequest;
}(Request_1.default));
exports.EventRequest = EventRequest;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var ApiAiConstants_1 = __webpack_require__(0);
var Errors_1 = __webpack_require__(1);
var XhrRequest_1 = __webpack_require__(5);
var Request_1 = __webpack_require__(2);
var TTSRequest = (function (_super) {
__extends(TTSRequest, _super);
function TTSRequest(apiAiClient, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, apiAiClient, options) || this;
_this.apiAiClient = apiAiClient;
_this.resolveTTSPromise = function (data) {
return _this.speak(data.response);
};
_this.rejectTTSPromise = function (reason) {
throw new Errors_1.ApiAiRequestError(reason);
};
// this.requestMethod = XhrRequest.Method.GET;
_this.uri = ApiAiConstants_1.ApiAiConstants.DEFAULT_TTS_HOST;
var AudioContext = window.AudioContext || webkitAudioContext;
if (!TTSRequest.audioContext) {
TTSRequest.audioContext = new AudioContext();
}
return _this;
}
TTSRequest.prototype.makeTTSRequest = function (text) {
if (!text) {
throw new Errors_1.ApiAiClientConfigurationError("Request can not be empty");
}
var params = {
lang: "en-US",
text: encodeURIComponent(text),
v: this.apiAiClient.getApiVersion()
};
var headers = {
"Accept-language": "en-US",
"Authorization": "Bearer " + this.apiAiClient.getAccessToken()
};
return this.makeRequest(this.uri, params, headers, { responseType: TTSRequest.RESPONSE_TYPE_ARRAYBUFFER })
.then(this.resolveTTSPromise)
.catch(this.rejectTTSPromise.bind(this));
};
TTSRequest.prototype.makeRequest = function (url, params, headers, options) {
return XhrRequest_1.default.get(url, params, headers, options);
};
TTSRequest.prototype.speak = function (data) {
var _this = this;
if (!data.byteLength) {
return Promise.reject("TTS Server unavailable");
}
return new Promise(function (resolve, reject) {
TTSRequest.audioContext.decodeAudioData(data, function (buffer) {
return _this.playSound(buffer, resolve);
}, reject).then(null, function (err) { return reject(err); });
});
};
TTSRequest.prototype.playSound = function (buffer, resolve) {
var source = TTSRequest.audioContext.createBufferSource();
source.buffer = buffer;
source.connect(TTSRequest.audioContext.destination);
source.onended = resolve;
source.start(0);
};
;
return TTSRequest;
}(Request_1.default));
TTSRequest.RESPONSE_TYPE_ARRAYBUFFER = "arraybuffer";
exports.TTSRequest = TTSRequest;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Request_1 = __webpack_require__(2);
var TextRequest = (function (_super) {
__extends(TextRequest, _super);
function TextRequest() {
return _super !== null && _super.apply(this, arguments) || this;
}
return TextRequest;
}(Request_1.default));
exports.default = TextRequest;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Resampler_1 = __webpack_require__(4);
var VAD_1 = __webpack_require__(16);
var Processors = (function () {
function Processors() {
}
Processors.bindProcessors = function () {
Resampler_1.default();
window.AudioContext = window.AudioContext || webkitAudioContext;
AudioContext.prototype.createResampleProcessor = function (bufferSize, numberOfInputChannels, numberOfOutputChannels, destinationSampleRate) {
var script_processor = this.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels);
var resampler = new navigator.Resampler(this.sampleRate, destinationSampleRate, numberOfInputChannels, bufferSize, true);
script_processor.onaudioprocess = function (event) {
var inp = event.inputBuffer.getChannelData(0);
var out = event.outputBuffer.getChannelData(0);
var l = resampler.resampler(inp);
for (var i = 0; i < l; ++i) {
out[i] = resampler.outputBuffer[i];
}
};
return script_processor;
};
function MagicBuffer(chunkSize) {
this.chunkSize = chunkSize;
this.array_data = [];
this.callback = null;
}
MagicBuffer.prototype.push = function (array) {
var l = array.length;
var new_array = new Array(Math.ceil(l / 2));
for (var i = 0; i < l; i += 2) {
new_array[i / 2] = array[i];
}
Array.prototype.push.apply(this.array_data, new_array);
this.process();
};
MagicBuffer.prototype.process = function () {
var elements;
while (this.array_data.length > this.chunkSize) {
elements = this.array_data.splice(0, this.chunkSize);
if (this.callback) {
this.callback(elements);
}
}
};
MagicBuffer.prototype.drop = function () {
this.array_data.splice(0, this.array_data.length);
};
AudioContext.prototype['createEndOfSpeechProcessor'] = function (bufferSize) {
var script_processor = this.createScriptProcessor(bufferSize, 1, 1);
script_processor.endOfSpeechCallback = null;
var vad = new VAD_1.default();
script_processor.vad = vad;
var buffer = new MagicBuffer(160);
buffer.callback = function (elements) {
var vad_result = vad.process(elements);
if (vad_result !== 'CONTINUE' && script_processor.endOfSpeechCallback) {
script_processor.endOfSpeechCallback();
buffer.drop();
}
};
script_processor.onaudioprocess = function (event) {
var inp = event.inputBuffer.getChannelData(0);
var out = event.outputBuffer.getChannelData(0);
buffer.push(inp);
for (var i = 0; i < inp.length; i++) {
out[i] = inp[i];
}
};
return script_processor;
};
};
return Processors;
}());
exports.Processors = Processors;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Resampler_1 = __webpack_require__(4);
var RecorderWorker_1 = __webpack_require__(14);
var Recorder = (function () {
function Recorder(source, config) {
if (config === void 0) { config = {}; }
var bufferLen = config.bufferLen || 4096;
this.context = source.context;
this.node = this.context.createScriptProcessor(bufferLen, 1, 1);
var worker = new Worker(this._getRecorderWorkerUrl());
worker.postMessage({
command: 'init',
config: {
sampleRate: this.context.sampleRate,
resamplerInitializerBody: this._getFunctionBody(Resampler_1.default)
}
});
var recording = false, currCallback;
this.node.onaudioprocess = function (e) {
if (!recording)
return;
worker.postMessage({
command: 'record',
buffer: [
e.inputBuffer.getChannelData(0)
]
});
};
this.configure = function (cfg) {
for (var prop in cfg) {
if (cfg.hasOwnProperty(prop)) {
config[prop] = cfg[prop];
}
}
};
this.record = function () {
recording = true;
};
this.stop = function () {
recording = false;
};
this.clear = function () {
worker.postMessage({ command: 'clear' });
};
this.getBuffer = function (cb) {
currCallback = cb || config.callback;
worker.postMessage({ command: 'getBuffer' });
};
this.export16kMono = function (cb, type) {
currCallback = cb || config.callback;
type = type || config.type || 'audio/raw';
if (!currCallback)
throw new Error('Callback not set');
worker.postMessage({
command: 'export16kMono',
type: type
});
};
worker.onmessage = function (e) {
currCallback(e.data);
};
source.connect(this.node);
this.node.connect(this.context.destination);
}
Recorder.prototype._getRecorderWorkerUrl = function () {
var getBlobUrl = window.URL && URL.createObjectURL.bind(URL);
return getBlobUrl(new Blob([this._getFunctionBody(RecorderWorker_1.default.createRecorderWorker())], { type: 'text/javascript' }));
};
Recorder.prototype._getFunctionBody = function (fn) {
if (typeof fn !== 'function') {
throw new Error("Illegal argument exception: argument is not a funtion: " + fn);