@nlxai/core 1.2.4-alpha.10 → 1.2.4-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -562,26 +562,60 @@ The configuration necessary to create a conversation.
562
562
  optional applicationUrl: string;
563
563
  ```
564
564
 
565
- The URL at which your conversational application is running.
566
- Fetch this from the application's API channel tab.
565
+ The URL at which your conversational application is running. Fetch this from the application's API channel tab.
566
+ Currently, there are a few ways to specify the application URL:
567
567
 
568
- ##### headers
568
+ - (recommended) leave out `applicationUrl` and specify `protocol`, `host`, `deploymentKey` and `channelKey`.
569
+ - specify the full `applicationUrl` as well as the `protocol`.
570
+ - (legacy) specify the `applicationUrl` generated either as an HTTP or websocket URL. Use `experimental.streamHttp` to control streaming.
571
+
572
+ ##### protocol?
569
573
 
570
574
  ```ts
571
- headers: Record<string, string> & object;
575
+ optional protocol: Protocol;
572
576
  ```
573
577
 
574
- Headers to forward to the NLX API.
578
+ Specify the protocol (http, websocket or httpWithStreaming)
575
579
 
576
- ###### Type Declaration
580
+ ##### host?
581
+
582
+ ```ts
583
+ optional host: string;
584
+ ```
585
+
586
+ Hostname of the application deployment, without a leading `https://`.
587
+
588
+ ##### deploymentKey?
589
+
590
+ ```ts
591
+ optional deploymentKey: string;
592
+ ```
593
+
594
+ Deployment key.
595
+
596
+ ##### channelKey?
597
+
598
+ ```ts
599
+ optional channelKey: string;
600
+ ```
601
+
602
+ Channel key.
603
+
604
+ ##### apiKey?
605
+
606
+ ```ts
607
+ optional apiKey: string;
608
+ ```
609
+
610
+ API key.
577
611
 
578
- ###### nlx-api-key
612
+ ##### headers?
579
613
 
580
614
  ```ts
581
- nlx-api-key: string;
615
+ optional headers: Record<string, string>;
582
616
  ```
583
617
 
584
- The `nlx-api-key` is required. Fetch this from the application's API channel tab.
618
+ Headers to forward to the NLX API.
585
619
 
586
620
  ##### conversationId?
587
621
 
@@ -1921,6 +1955,38 @@ Interim message event handler
1921
1955
 
1922
1956
  ## Enumerations
1923
1957
 
1958
+ ### Protocol
1959
+
1960
+ The protocol used to communicate with the application
1961
+
1962
+ #### Enumeration Members
1963
+
1964
+ ##### Https
1965
+
1966
+ ```ts
1967
+ Https: "https";
1968
+ ```
1969
+
1970
+ Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
1971
+
1972
+ ##### HttpsWithStreaming
1973
+
1974
+ ```ts
1975
+ HttpsWithStreaming: "httpsWithStreaming";
1976
+ ```
1977
+
1978
+ Encrypted HTTPS with streaming enabled. This is the default setting and supports interim messages. Does not support post-escalation message handling.
1979
+
1980
+ ##### Websocket
1981
+
1982
+ ```ts
1983
+ Websocket: "websocket";
1984
+ ```
1985
+
1986
+ Websocket, with support for post-escalation message handling.
1987
+
1988
+ ---
1989
+
1924
1990
  ### ResponseType
1925
1991
 
1926
1992
  Response type
package/docs/README.md CHANGED
@@ -214,6 +214,101 @@ sendTextWrapped("Hello").then((response) => {
214
214
  });
215
215
  ```
216
216
 
217
+ ---
218
+
219
+ ### sendVoicePlusStep()
220
+
221
+ ```ts
222
+ function sendVoicePlusStep(configuration): Promise<void>;
223
+ ```
224
+
225
+ Use this function when using **Voice+ scripts** to advance the conversation to the step specified.
226
+
227
+ This functionality is orthogonal from other usage of the core SDK, as it may be used either using standard SDK communication channels or it can be used to provide a Voice+ script experience with for instance a telephony based channel.
228
+
229
+ #### Parameters
230
+
231
+ ##### configuration
232
+
233
+ Configuration for sending the step. Many of the values can be found on the deployment modal of the Voice+ script.
234
+
235
+ ###### apiKey
236
+
237
+ `string`
238
+
239
+ - the API key generated for the Voice+ script. Note that this value is different from the API key you would pass to [createConversation](#createconversation). You can control the API key on the Voice+ script settings page.
240
+
241
+ ###### scriptId?
242
+
243
+ `string`
244
+
245
+ The ID of the Voice+ script.
246
+
247
+ ###### workspaceId
248
+
249
+ `string`
250
+
251
+ Your workspace ID.
252
+
253
+ ###### conversationId
254
+
255
+ `string`
256
+
257
+ The active conversation ID, passed from the active NLX voice application. This is what ties the script exectution to the specific Voice application.
258
+
259
+ _Note: This must be dynamically set by the voice application._ Normally, when the voice application directs the user to the webpage running this code, it will include the conversation ID as a URL parameter which you can extract and pass here.
260
+
261
+ **Example**
262
+
263
+ ```typescript
264
+ const conversationId = new URLSearchParams(window.location.search).get("cid");
265
+ ```
266
+
267
+ ###### languageCode
268
+
269
+ `string`
270
+
271
+ The user's language code, consistent with the language codes defined on the Voice+ script.
272
+
273
+ ###### step
274
+
275
+ [`StepInfo`](#stepinfo)
276
+
277
+ Which step to send.
278
+
279
+ ###### context
280
+
281
+ [`Context`](#context)
282
+
283
+ Any context.
284
+
285
+ ###### debug?
286
+
287
+ `boolean` = `false`
288
+
289
+ Set to `true` to help debug issues or errors. Defaults to `false`.
290
+
291
+ #### Returns
292
+
293
+ `Promise`\<`void`\>
294
+
295
+ #### Example
296
+
297
+ ```typescript
298
+ import { sendVoicePlusStep } from "@nlxai/core";
299
+
300
+ await sendVoicePlusStep({
301
+ // hard-coded params
302
+ apiKey: "REPLACE_WITH_API_KEY",
303
+ workspaceId: "REPLACE_WITH_WORKSPACE_ID",
304
+ scriptId: "REPLACE_WITH_SCRIPT_ID",
305
+ step: "REPLACE_WITH_STEP_ID",
306
+ // dynamic params
307
+ conversationId: "REPLACE_WITH_CONVERSATION_ID",
308
+ languageCode: "en-US",
309
+ });
310
+ ```
311
+
217
312
  ## Variables
218
313
 
219
314
  ### version
@@ -238,26 +333,60 @@ The configuration necessary to create a conversation.
238
333
  optional applicationUrl: string;
239
334
  ```
240
335
 
241
- The URL at which your conversational application is running.
242
- Fetch this from the application's API channel tab.
336
+ The URL at which your conversational application is running. Fetch this from the application's API channel tab.
337
+ Currently, there are a few ways to specify the application URL:
338
+
339
+ - (recommended) leave out `applicationUrl` and specify `protocol`, `host`, `deploymentKey` and `channelKey`.
340
+ - specify the full `applicationUrl` as well as the `protocol`.
341
+ - (legacy) specify the `applicationUrl` generated either as an HTTP or websocket URL. Use `experimental.streamHttp` to control streaming.
243
342
 
244
- ##### headers
343
+ ##### protocol?
245
344
 
246
345
  ```ts
247
- headers: Record<string, string> & object;
346
+ optional protocol: Protocol;
248
347
  ```
249
348
 
250
- Headers to forward to the NLX API.
349
+ Specify the protocol (http, websocket or httpWithStreaming)
251
350
 
252
- ###### Type Declaration
351
+ ##### host?
352
+
353
+ ```ts
354
+ optional host: string;
355
+ ```
356
+
357
+ Hostname of the application deployment, without a leading `https://`.
253
358
 
254
- ###### nlx-api-key
359
+ ##### deploymentKey?
255
360
 
256
361
  ```ts
257
- nlx-api-key: string;
362
+ optional deploymentKey: string;
258
363
  ```
259
364
 
260
- The `nlx-api-key` is required. Fetch this from the application's API channel tab.
365
+ Deployment key.
366
+
367
+ ##### channelKey?
368
+
369
+ ```ts
370
+ optional channelKey: string;
371
+ ```
372
+
373
+ Channel key.
374
+
375
+ ##### apiKey?
376
+
377
+ ```ts
378
+ optional apiKey: string;
379
+ ```
380
+
381
+ API key.
382
+
383
+ ##### headers?
384
+
385
+ ```ts
386
+ optional headers: Record<string, string>;
387
+ ```
388
+
389
+ Headers to forward to the NLX API.
261
390
 
262
391
  ##### conversationId?
263
392
 
@@ -1597,6 +1726,38 @@ Interim message event handler
1597
1726
 
1598
1727
  ## Enumerations
1599
1728
 
1729
+ ### Protocol
1730
+
1731
+ The protocol used to communicate with the application
1732
+
1733
+ #### Enumeration Members
1734
+
1735
+ ##### Https
1736
+
1737
+ ```ts
1738
+ Https: "https";
1739
+ ```
1740
+
1741
+ Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
1742
+
1743
+ ##### HttpsWithStreaming
1744
+
1745
+ ```ts
1746
+ HttpsWithStreaming: "httpsWithStreaming";
1747
+ ```
1748
+
1749
+ Encrypted HTTPS with streaming enabled. This is the default setting and supports interim messages. Does not support post-escalation message handling.
1750
+
1751
+ ##### Websocket
1752
+
1753
+ ```ts
1754
+ Websocket: "websocket";
1755
+ ```
1756
+
1757
+ Websocket, with support for post-escalation message handling.
1758
+
1759
+ ---
1760
+
1600
1761
  ### ResponseType
1601
1762
 
1602
1763
  Response type
@@ -1928,3 +2089,45 @@ The callback function for listening to all responses.
1928
2089
  #### Returns
1929
2090
 
1930
2091
  `void`
2092
+
2093
+ ---
2094
+
2095
+ ### StepInfo
2096
+
2097
+ ```ts
2098
+ type StepInfo =
2099
+ | string
2100
+ | {
2101
+ stepId: string;
2102
+ stepTriggerDescription?: string;
2103
+ };
2104
+ ```
2105
+
2106
+ Step information, either a step ID as a single string or an object
2107
+
2108
+ #### Type Declaration
2109
+
2110
+ `string`
2111
+
2112
+ ```ts
2113
+ {
2114
+ stepId: string;
2115
+ stepTriggerDescription?: string;
2116
+ }
2117
+ ```
2118
+
2119
+ ##### stepId
2120
+
2121
+ ```ts
2122
+ stepId: string;
2123
+ ```
2124
+
2125
+ Step ID
2126
+
2127
+ ##### stepTriggerDescription?
2128
+
2129
+ ```ts
2130
+ optional stepTriggerDescription: string;
2131
+ ```
2132
+
2133
+ Step trigger description
package/lib/index.cjs CHANGED
@@ -6,7 +6,7 @@ var ReconnectingWebSocket = require('reconnecting-websocket');
6
6
  var uuid = require('uuid');
7
7
 
8
8
  var name = "@nlxai/core";
9
- var version$1 = "1.2.4-alpha.10";
9
+ var version$1 = "1.2.4-alpha.12";
10
10
  var description = "Low-level SDK for building NLX experiences";
11
11
  var type = "module";
12
12
  var main = "lib/index.cjs";
@@ -62,7 +62,7 @@ var dependencies = {
62
62
  var publishConfig = {
63
63
  access: "public"
64
64
  };
65
- var gitHead = "9a1bfacce5cc21ca2d64e79c86805dab37568de3";
65
+ var gitHead = "e1813c1b87516f8d5b5d03d0d6ba5245f18d7869";
66
66
  var packageJson = {
67
67
  name: name,
68
68
  version: version$1,
package/lib/index.esm.js CHANGED
@@ -4,7 +4,7 @@ import ReconnectingWebSocket from 'reconnecting-websocket';
4
4
  import { v4 } from 'uuid';
5
5
 
6
6
  var name = "@nlxai/core";
7
- var version$1 = "1.2.4-alpha.10";
7
+ var version$1 = "1.2.4-alpha.12";
8
8
  var description = "Low-level SDK for building NLX experiences";
9
9
  var type = "module";
10
10
  var main = "lib/index.cjs";
@@ -60,7 +60,7 @@ var dependencies = {
60
60
  var publishConfig = {
61
61
  access: "public"
62
62
  };
63
- var gitHead = "9a1bfacce5cc21ca2d64e79c86805dab37568de3";
63
+ var gitHead = "e1813c1b87516f8d5b5d03d0d6ba5245f18d7869";
64
64
  var packageJson = {
65
65
  name: name,
66
66
  version: version$1,
package/lib/index.umd.js CHANGED
@@ -12,4 +12,4 @@
12
12
 
13
13
  See the Apache Version 2.0 License for specific language governing permissions
14
14
  and limitations under the License.
15
- ***************************************************************************** */function J(e,t){function n(){this.constructor=e}V(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function z(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return i}var Q=function(e,t){this.target=t,this.type=e},X=function(e){function t(t,n){var r=e.call(this,"error",n)||this;return r.message=t.message,r.error=t,r}return J(t,e),t}(Q),Z=function(e){function t(t,n,r){void 0===t&&(t=1e3),void 0===n&&(n="");var o=e.call(this,"close",r)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return J(t,e),t}(Q),Y=function(){if("undefined"!=typeof WebSocket)return WebSocket},ee={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},te=function(){function e(e,t,n){var r=this;void 0===n&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){r._debug("open event");var t=r._options.minUptime,n=void 0===t?ee.minUptime:t;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout((function(){return r._acceptOpen()}),n),r._ws.binaryType=r._binaryType,r._messageQueue.forEach((function(e){return r._ws.send(e)})),r._messageQueue=[],r.onopen&&r.onopen(e),r._listeners.open.forEach((function(t){return r._callEventListener(e,t)}))},this._handleMessage=function(e){r._debug("message event"),r.onmessage&&r.onmessage(e),r._listeners.message.forEach((function(t){return r._callEventListener(e,t)}))},this._handleError=function(e){r._debug("error event",e.message),r._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),r.onerror&&r.onerror(e),r._debug("exec error listeners"),r._listeners.error.forEach((function(t){return r._callEventListener(e,t)})),r._connect()},this._handleClose=function(e){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(e),r._listeners.close.forEach((function(t){return r._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=void 0===t?ee.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,n,r=this._listeners[e.type];if(r)try{for(var o=function(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}(r),s=o.next();!s.done;s=o.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(z(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?ee.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=void 0===r?ee.minReconnectionDelay:r,s=e.maxReconnectionDelay,i=void 0===s?ee.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=o*Math.pow(n,this._retryCount-1))>i&&(a=i),this._debug("next delay",a),a},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,n=t.maxRetries,r=void 0===n?ee.maxRetries:n,o=t.connectionTimeout,s=void 0===o?ee.connectionTimeout:o,i=t.WebSocket,a=void 0===i?Y():i;if(this._retryCount>=r)this._debug("max retries reached",this._retryCount,">=",r);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),void 0===(c=a)||!c||2!==c.CLOSING)throw Error("No valid WebSocket class provided");var c;this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new a(t,e._protocols):new a(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),s))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new X(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new Z(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();let ne;const re=new Uint8Array(16);function oe(){if(!ne&&(ne="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ne))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ne(re)}const se=[];for(let e=0;e<256;++e)se.push((e+256).toString(16).slice(1));var ie={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ae(e,t,n){if(ie.randomUUID&&!e)return ie.randomUUID();const r=(e=e||{}).random||(e.rng||oe)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return se[e[t+0]]+se[e[t+1]]+se[e[t+2]]+se[e[t+3]]+"-"+se[e[t+4]]+se[e[t+5]]+"-"+se[e[t+6]]+se[e[t+7]]+"-"+se[e[t+8]]+se[e[t+9]]+"-"+se[e[t+10]]+se[e[t+11]]+se[e[t+12]]+se[e[t+13]]+se[e[t+14]]+se[e[t+15]]}(r)}var ce="1.2.4-alpha.10";const ue=ce,le=console;var de,pe;e.Protocol=void 0,(de=e.Protocol||(e.Protocol={})).Https="https",de.HttpsWithStreaming="httpsWithStreaming",de.Websocket="websocket",e.ResponseType=void 0,(pe=e.ResponseType||(e.ResponseType={})).Application="bot",pe.User="user",pe.Failure="failure";const he="NLX.Welcome",fe=e=>Array.isArray(e)?e:Object.entries(e).map((([e,t])=>({slotId:e,value:t}))),ye=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?fe(e.slots):e.slots}),me=e=>e.responses,ge=e=>{try{return JSON.parse(e)}catch(e){return null}},be=e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai",ve=t=>{const n=t.applicationUrl??"",r=t.apiKey??t.headers?.["nlx-api-key"]??"",o=t.protocol??(_e(n)?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming);if(null!=t.host&&null!=t.channelKey&&null!=t.deploymentKey)return{protocol:o,apiKey:r,host:t.host,channelKey:t.channelKey,deploymentKey:t.deploymentKey};if(_e(n)){const e=be(n),t=new URL(n),s=new URLSearchParams(t.search),i=s.get("channelKey"),a=s.get("deploymentKey");return null!=i&&null!=a?{protocol:o,channelKey:i,deploymentKey:a,host:e,apiKey:r}:null}const s=be(n),i=new URLPattern({pathname:"/c/:deploymentKey/:channelKey"}).exec(n);return null!=i?.pathname.groups.channelKey&&null!=i?.pathname.groups.deploymentKey?{protocol:o,channelKey:i.pathname.groups.channelKey,deploymentKey:i.pathname.groups.deploymentKey,host:s,apiKey:r}:null},_e=e=>0===e.indexOf("wss://"),we=async({fullApplicationUrl:e,apiKey:t,headers:n,body:r,stream:o,eventListeners:s})=>{if(o)return await(async r=>{const o=await I(e,{method:"POST",headers:{...n,"nlx-api-key":t,"Content-Type":"application/json","nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify({...r,stream:!0})});if(!o.ok||null==o.body)throw new Error(`HTTP Error: ${o.status}`);const i=o.body.getReader(),a=new TextDecoder;let c="";const u=[];let l={};for(;;){const{done:e,value:t}=await i.read();if(e)break;for(c+=a.decode(t,{stream:!0});;){const e=c.indexOf("{");if(-1===e)break;let t=!1;for(let n=0;n<c.length;n++)if("}"===c[n]){const r=c.substring(e,n+1);try{const e=JSON.parse(r);if("interim"===e.type){const t=e.text;"string"==typeof t&&s.interimMessage.forEach((e=>{e(t)}))}else"message"===e.type?u.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(l=e.data);c=c.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return s.interimMessage.forEach((e=>{e(void 0)})),{...l,messages:[...u,...(l.messages??[]).map((e=>({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata})))]}})(r);{const o=await I(e,{method:"POST",headers:{...n??{},"nlx-api-key":t,Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify(r)});if(!o.ok||null==o.body)throw new Error(`HTTP Error: ${o.status}`);return await o.json()}};const Te=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;e.createConversation=function(t){let n,r,o=[],s=null,i=[],a=null;const c=ve(t),u=null!=c?(e=>`wss://us-east-1-ws.${e.host}?deploymentKey=${e.deploymentKey}&channelKey=${e.channelKey}&apiKey=${e.apiKey}`)(c):t.applicationUrl??"",l=null!=c?(e=>`https://${e.host}/c/${e.deploymentKey}/${e.channelKey}`)(c):t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(l)&&le.warn("Since v1.0.0, the language code is no longer added at the end of the application URL. Please remove the modifier (e.g. '-en-US') from the URL, and specify it in the `languageCode` parameter instead.");const d={voicePlusCommand:[],interimMessage:[]},p=t.conversationId??ae();let h={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:p};const f=()=>`${l}${!0===t.experimental?.completeApplicationUrl?"":`-${h.languageCode}`}`,y=(e,t)=>{h={...h,...e},w.forEach((e=>{e(me(h),t)}))},m=()=>{const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};y({responses:[...h.responses,n]},n)},g=t=>{if(t?.messages.length>0){const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:{...t,messages:t.messages.map((e=>({nodeId:e.nodeId,messageId:e.messageId,text:e.text,choices:e.choices??[]})))}};y({responses:[...h.responses,n]},n),t.metadata.hasPendingDataRequest&&(A({poll:!0}),setTimeout((()=>{_({request:{structured:{poll:!0}}})}),1500))}else le.warn("Invalid message structure, expected object with field 'messages'."),m()};let b;const v=e=>{1===r?.readyState?r.send(JSON.stringify(e)):i=[...i,e]},_=async r=>{if(null!=b)return void b(r,(t=>{le.warn("Using the second argument in `setRequestOverride` is deprecated. Use `conversationHandler.appendMessageToTranscript` instead.");const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:t};y({responses:[...h.responses,n]},n)}));const s={userId:h.userId,conversationId:h.conversationId,...r,languageCode:h.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(c?.protocol===e.Protocol.Websocket)1===n?.readyState?n.send(JSON.stringify(s)):o=[...o,s];else try{const n=await we({fullApplicationUrl:f(),apiKey:c?.apiKey??"",headers:t.headers??{},stream:c?.protocol===e.Protocol.HttpsWithStreaming,eventListeners:d,body:s});g(n)}catch(e){le.warn(e),m()}};let w=[];const T=()=>{E();const e=new URL(u);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",h.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${h.languageCode}`)),e.searchParams.set("conversationId",h.conversationId),n=new te(e.href),s=setInterval((()=>{(async()=>{1===n?.readyState&&null!=o[0]&&(await _(o[0]),o=o.slice(1))})()}),500),n.onmessage=function(e){"string"==typeof e?.data&&g(ge(e.data))}},x=()=>{if(O(),!0!==t.bidirectional)return;const e=new URL(u);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",h.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${h.languageCode}`)),e.searchParams.set("conversationId",h.conversationId),e.searchParams.set("type","voice-plus"),null!=c?.apiKey&&e.searchParams.set("apiKey",c.apiKey),r=new te(e.href),a=setInterval((()=>{1===r?.readyState&&null!=i[0]&&(v(i[0]),i=i.slice(1))}),500),r.onmessage=e=>{if("string"==typeof e?.data){const t=ge(e.data);null!=t&&d.voicePlusCommand.forEach((e=>{e(t)}))}}},E=()=>{null!=s&&clearInterval(s),null!=n&&(n.onmessage=null,n.close(),n=void 0)},O=()=>{null!=a&&clearInterval(a),null!=r&&(r.onmessage=null,r.close(),r=void 0)};c?.protocol===e.Protocol.Websocket&&T(),x();const A=(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...ye(t),context:n}};y({responses:[...h.responses,r]},r)},C=(e,t)=>{A({intentId:e},t),_({context:t,request:{structured:{intentId:e}}})},P=e=>{w=w.filter((t=>t!==e))};return{sendText:(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};y({responses:[...h.responses,r]},r),_({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await I(`${f()}/context`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":c?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":h.conversationId,"nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify({languageCode:h.languageCode,conversationId:h.conversationId,userId:h.userId,context:e})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},appendMessageToTranscript:e=>{const t={...e,receivedAt:e.receivedAt??(new Date).getTime()};y({responses:[...h.responses,t]},t)},sendStructured:(e,t)=>{A(e,t),_({context:t,request:{structured:ye(e)}})},sendSlots:(e,t)=>{A({slots:e},t),_({context:t,request:{structured:{slots:fe(e)}}})},sendFlow:C,sendIntent:(e,t)=>{le.warn("Calling `sendIntent` is deprecated and will be removed in a future version of the SDK. Use `sendFlow` instead."),C(e,t)},sendWelcomeFlow:e=>{C(he,e)},sendWelcomeIntent:e=>{le.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),C(he,e)},sendChoice:(t,n,r)=>{let o=[...h.responses];const s={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},i=r?.responseIndex??-1,a=r?.messageIndex??-1;i>-1&&a>-1&&(o=U(i,(n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:U(a,(e=>({...e,selectedChoiceId:t})),n.payload.messages)}}:n),o)),o=[...o,s],y({responses:o},s),_({context:n,request:{structured:{nodeId:r?.nodeId,intentId:r?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await I(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:h.languageCode,conversationId:h.conversationId,userId:h.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>h.conversationId,setLanguageCode:t=>{t!==h.languageCode?(c?.protocol===e.Protocol.Websocket&&T(),x(),y({languageCode:t})):le.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>h.languageCode,getVoiceCredentials:async(e,n)=>{const r=await I(`${l}-${h.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":c?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":h.conversationId,"nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify({languageCode:h.languageCode,conversationId:h.conversationId,userId:h.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(r.status>=400)throw new Error(`Responded with ${r.status}`);const o=await r.json();if(null==o?.url)throw new Error("Invalid response");return o},subscribe:e=>(w=[...w,e],e(me(h)),()=>{P(e)}),unsubscribe:P,unsubscribeAll:()=>{w=[]},reset:t=>{y({conversationId:ae(),responses:!0===t?.clearResponses?[]:h.responses}),c?.protocol===e.Protocol.Websocket&&T(),x()},destroy:()=>{w=[],c?.protocol===e.Protocol.Websocket&&E(),O()},setRequestOverride:e=>{b=e},addEventListener:(e,t)=>{d[e]=[...d[e],t]},removeEventListener:(e,t)=>{d[e]=d[e].filter((e=>e!==t))},sendVoicePlusContext:e=>{v({context:e})}}},e.getCurrentExpirationTimestamp=t=>{let n=null;return t.forEach((t=>{t.type===e.ResponseType.Application&&null!=t.payload.expirationTimestamp&&(n=t.payload.expirationTimestamp)})),n},e.isConfigValid=e=>null!=ve(e),e.promisify=function(t,n,r=1e4){return async o=>await new Promise(((s,i)=>{const a=setTimeout((()=>{i(new Error("The request timed out.")),n.unsubscribe(c)}),r),c=(t,r)=>{r?.type!==e.ResponseType.Application&&r?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(r))};n.subscribe(c),t(o)}))},e.sendVoicePlusStep=async({apiKey:e,workspaceId:t,conversationId:n,scriptId:r,languageCode:o,step:s,context:i,debug:a=!1,dev:c=!1})=>{if(null==r)throw new Error("Voice+ scriptId is not defined.");if("string"!=typeof n||0===n.length)throw new Error("Voice+ conversationId is not defined.");const[u,l]="string"==typeof s?[s,void 0]:[s.stepId,s.stepTriggerDescription];if(!Te.test(u))throw new Error("Invalid stepId. It should be formatted as a UUID.");const d={stepId:u,context:i,conversationId:n,journeyId:r,languageCode:o,stepTriggerDescription:l};try{await I(`https://${c?"dev.":""}mm.nlx.ai/v1/track`,{method:"POST",headers:{"x-api-key":e,"x-nlx-id":t,"Content-Type":"application/json","nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify(d)}),a&&le.info(`✓ step: ${u}`,d)}catch(e){throw a&&le.error(`× step: ${u}`,e,d),e}},e.shouldReinitialize=(e,t)=>!G(e,t),e.version=ue}));
15
+ ***************************************************************************** */function J(e,t){function n(){this.constructor=e}V(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function z(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return i}var Q=function(e,t){this.target=t,this.type=e},X=function(e){function t(t,n){var r=e.call(this,"error",n)||this;return r.message=t.message,r.error=t,r}return J(t,e),t}(Q),Z=function(e){function t(t,n,r){void 0===t&&(t=1e3),void 0===n&&(n="");var o=e.call(this,"close",r)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return J(t,e),t}(Q),Y=function(){if("undefined"!=typeof WebSocket)return WebSocket},ee={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},te=function(){function e(e,t,n){var r=this;void 0===n&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){r._debug("open event");var t=r._options.minUptime,n=void 0===t?ee.minUptime:t;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout((function(){return r._acceptOpen()}),n),r._ws.binaryType=r._binaryType,r._messageQueue.forEach((function(e){return r._ws.send(e)})),r._messageQueue=[],r.onopen&&r.onopen(e),r._listeners.open.forEach((function(t){return r._callEventListener(e,t)}))},this._handleMessage=function(e){r._debug("message event"),r.onmessage&&r.onmessage(e),r._listeners.message.forEach((function(t){return r._callEventListener(e,t)}))},this._handleError=function(e){r._debug("error event",e.message),r._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),r.onerror&&r.onerror(e),r._debug("exec error listeners"),r._listeners.error.forEach((function(t){return r._callEventListener(e,t)})),r._connect()},this._handleClose=function(e){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(e),r._listeners.close.forEach((function(t){return r._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=void 0===t?ee.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,n,r=this._listeners[e.type];if(r)try{for(var o=function(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}(r),s=o.next();!s.done;s=o.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(z(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?ee.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=void 0===r?ee.minReconnectionDelay:r,s=e.maxReconnectionDelay,i=void 0===s?ee.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=o*Math.pow(n,this._retryCount-1))>i&&(a=i),this._debug("next delay",a),a},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,n=t.maxRetries,r=void 0===n?ee.maxRetries:n,o=t.connectionTimeout,s=void 0===o?ee.connectionTimeout:o,i=t.WebSocket,a=void 0===i?Y():i;if(this._retryCount>=r)this._debug("max retries reached",this._retryCount,">=",r);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),void 0===(c=a)||!c||2!==c.CLOSING)throw Error("No valid WebSocket class provided");var c;this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new a(t,e._protocols):new a(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),s))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new X(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new Z(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();let ne;const re=new Uint8Array(16);function oe(){if(!ne&&(ne="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ne))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ne(re)}const se=[];for(let e=0;e<256;++e)se.push((e+256).toString(16).slice(1));var ie={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ae(e,t,n){if(ie.randomUUID&&!e)return ie.randomUUID();const r=(e=e||{}).random||(e.rng||oe)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return se[e[t+0]]+se[e[t+1]]+se[e[t+2]]+se[e[t+3]]+"-"+se[e[t+4]]+se[e[t+5]]+"-"+se[e[t+6]]+se[e[t+7]]+"-"+se[e[t+8]]+se[e[t+9]]+"-"+se[e[t+10]]+se[e[t+11]]+se[e[t+12]]+se[e[t+13]]+se[e[t+14]]+se[e[t+15]]}(r)}var ce="1.2.4-alpha.12";const ue=ce,le=console;var de,pe;e.Protocol=void 0,(de=e.Protocol||(e.Protocol={})).Https="https",de.HttpsWithStreaming="httpsWithStreaming",de.Websocket="websocket",e.ResponseType=void 0,(pe=e.ResponseType||(e.ResponseType={})).Application="bot",pe.User="user",pe.Failure="failure";const he="NLX.Welcome",fe=e=>Array.isArray(e)?e:Object.entries(e).map((([e,t])=>({slotId:e,value:t}))),ye=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?fe(e.slots):e.slots}),me=e=>e.responses,ge=e=>{try{return JSON.parse(e)}catch(e){return null}},be=e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai",ve=t=>{const n=t.applicationUrl??"",r=t.apiKey??t.headers?.["nlx-api-key"]??"",o=t.protocol??(_e(n)?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming);if(null!=t.host&&null!=t.channelKey&&null!=t.deploymentKey)return{protocol:o,apiKey:r,host:t.host,channelKey:t.channelKey,deploymentKey:t.deploymentKey};if(_e(n)){const e=be(n),t=new URL(n),s=new URLSearchParams(t.search),i=s.get("channelKey"),a=s.get("deploymentKey");return null!=i&&null!=a?{protocol:o,channelKey:i,deploymentKey:a,host:e,apiKey:r}:null}const s=be(n),i=new URLPattern({pathname:"/c/:deploymentKey/:channelKey"}).exec(n);return null!=i?.pathname.groups.channelKey&&null!=i?.pathname.groups.deploymentKey?{protocol:o,channelKey:i.pathname.groups.channelKey,deploymentKey:i.pathname.groups.deploymentKey,host:s,apiKey:r}:null},_e=e=>0===e.indexOf("wss://"),we=async({fullApplicationUrl:e,apiKey:t,headers:n,body:r,stream:o,eventListeners:s})=>{if(o)return await(async r=>{const o=await I(e,{method:"POST",headers:{...n,"nlx-api-key":t,"Content-Type":"application/json","nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify({...r,stream:!0})});if(!o.ok||null==o.body)throw new Error(`HTTP Error: ${o.status}`);const i=o.body.getReader(),a=new TextDecoder;let c="";const u=[];let l={};for(;;){const{done:e,value:t}=await i.read();if(e)break;for(c+=a.decode(t,{stream:!0});;){const e=c.indexOf("{");if(-1===e)break;let t=!1;for(let n=0;n<c.length;n++)if("}"===c[n]){const r=c.substring(e,n+1);try{const e=JSON.parse(r);if("interim"===e.type){const t=e.text;"string"==typeof t&&s.interimMessage.forEach((e=>{e(t)}))}else"message"===e.type?u.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(l=e.data);c=c.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return s.interimMessage.forEach((e=>{e(void 0)})),{...l,messages:[...u,...(l.messages??[]).map((e=>({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata})))]}})(r);{const o=await I(e,{method:"POST",headers:{...n??{},"nlx-api-key":t,Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify(r)});if(!o.ok||null==o.body)throw new Error(`HTTP Error: ${o.status}`);return await o.json()}};const Te=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;e.createConversation=function(t){let n,r,o=[],s=null,i=[],a=null;const c=ve(t),u=null!=c?(e=>`wss://us-east-1-ws.${e.host}?deploymentKey=${e.deploymentKey}&channelKey=${e.channelKey}&apiKey=${e.apiKey}`)(c):t.applicationUrl??"",l=null!=c?(e=>`https://${e.host}/c/${e.deploymentKey}/${e.channelKey}`)(c):t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(l)&&le.warn("Since v1.0.0, the language code is no longer added at the end of the application URL. Please remove the modifier (e.g. '-en-US') from the URL, and specify it in the `languageCode` parameter instead.");const d={voicePlusCommand:[],interimMessage:[]},p=t.conversationId??ae();let h={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:p};const f=()=>`${l}${!0===t.experimental?.completeApplicationUrl?"":`-${h.languageCode}`}`,y=(e,t)=>{h={...h,...e},w.forEach((e=>{e(me(h),t)}))},m=()=>{const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};y({responses:[...h.responses,n]},n)},g=t=>{if(t?.messages.length>0){const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:{...t,messages:t.messages.map((e=>({nodeId:e.nodeId,messageId:e.messageId,text:e.text,choices:e.choices??[]})))}};y({responses:[...h.responses,n]},n),t.metadata.hasPendingDataRequest&&(A({poll:!0}),setTimeout((()=>{_({request:{structured:{poll:!0}}})}),1500))}else le.warn("Invalid message structure, expected object with field 'messages'."),m()};let b;const v=e=>{1===r?.readyState?r.send(JSON.stringify(e)):i=[...i,e]},_=async r=>{if(null!=b)return void b(r,(t=>{le.warn("Using the second argument in `setRequestOverride` is deprecated. Use `conversationHandler.appendMessageToTranscript` instead.");const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:t};y({responses:[...h.responses,n]},n)}));const s={userId:h.userId,conversationId:h.conversationId,...r,languageCode:h.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(c?.protocol===e.Protocol.Websocket)1===n?.readyState?n.send(JSON.stringify(s)):o=[...o,s];else try{const n=await we({fullApplicationUrl:f(),apiKey:c?.apiKey??"",headers:t.headers??{},stream:c?.protocol===e.Protocol.HttpsWithStreaming,eventListeners:d,body:s});g(n)}catch(e){le.warn(e),m()}};let w=[];const T=()=>{E();const e=new URL(u);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",h.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${h.languageCode}`)),e.searchParams.set("conversationId",h.conversationId),n=new te(e.href),s=setInterval((()=>{(async()=>{1===n?.readyState&&null!=o[0]&&(await _(o[0]),o=o.slice(1))})()}),500),n.onmessage=function(e){"string"==typeof e?.data&&g(ge(e.data))}},x=()=>{if(O(),!0!==t.bidirectional)return;const e=new URL(u);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",h.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${h.languageCode}`)),e.searchParams.set("conversationId",h.conversationId),e.searchParams.set("type","voice-plus"),null!=c?.apiKey&&e.searchParams.set("apiKey",c.apiKey),r=new te(e.href),a=setInterval((()=>{1===r?.readyState&&null!=i[0]&&(v(i[0]),i=i.slice(1))}),500),r.onmessage=e=>{if("string"==typeof e?.data){const t=ge(e.data);null!=t&&d.voicePlusCommand.forEach((e=>{e(t)}))}}},E=()=>{null!=s&&clearInterval(s),null!=n&&(n.onmessage=null,n.close(),n=void 0)},O=()=>{null!=a&&clearInterval(a),null!=r&&(r.onmessage=null,r.close(),r=void 0)};c?.protocol===e.Protocol.Websocket&&T(),x();const A=(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...ye(t),context:n}};y({responses:[...h.responses,r]},r)},C=(e,t)=>{A({intentId:e},t),_({context:t,request:{structured:{intentId:e}}})},P=e=>{w=w.filter((t=>t!==e))};return{sendText:(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};y({responses:[...h.responses,r]},r),_({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await I(`${f()}/context`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":c?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":h.conversationId,"nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify({languageCode:h.languageCode,conversationId:h.conversationId,userId:h.userId,context:e})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},appendMessageToTranscript:e=>{const t={...e,receivedAt:e.receivedAt??(new Date).getTime()};y({responses:[...h.responses,t]},t)},sendStructured:(e,t)=>{A(e,t),_({context:t,request:{structured:ye(e)}})},sendSlots:(e,t)=>{A({slots:e},t),_({context:t,request:{structured:{slots:fe(e)}}})},sendFlow:C,sendIntent:(e,t)=>{le.warn("Calling `sendIntent` is deprecated and will be removed in a future version of the SDK. Use `sendFlow` instead."),C(e,t)},sendWelcomeFlow:e=>{C(he,e)},sendWelcomeIntent:e=>{le.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),C(he,e)},sendChoice:(t,n,r)=>{let o=[...h.responses];const s={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},i=r?.responseIndex??-1,a=r?.messageIndex??-1;i>-1&&a>-1&&(o=U(i,(n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:U(a,(e=>({...e,selectedChoiceId:t})),n.payload.messages)}}:n),o)),o=[...o,s],y({responses:o},s),_({context:n,request:{structured:{nodeId:r?.nodeId,intentId:r?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await I(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:h.languageCode,conversationId:h.conversationId,userId:h.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>h.conversationId,setLanguageCode:t=>{t!==h.languageCode?(c?.protocol===e.Protocol.Websocket&&T(),x(),y({languageCode:t})):le.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>h.languageCode,getVoiceCredentials:async(e,n)=>{const r=await I(`${l}-${h.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":c?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":h.conversationId,"nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify({languageCode:h.languageCode,conversationId:h.conversationId,userId:h.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(r.status>=400)throw new Error(`Responded with ${r.status}`);const o=await r.json();if(null==o?.url)throw new Error("Invalid response");return o},subscribe:e=>(w=[...w,e],e(me(h)),()=>{P(e)}),unsubscribe:P,unsubscribeAll:()=>{w=[]},reset:t=>{y({conversationId:ae(),responses:!0===t?.clearResponses?[]:h.responses}),c?.protocol===e.Protocol.Websocket&&T(),x()},destroy:()=>{w=[],c?.protocol===e.Protocol.Websocket&&E(),O()},setRequestOverride:e=>{b=e},addEventListener:(e,t)=>{d[e]=[...d[e],t]},removeEventListener:(e,t)=>{d[e]=d[e].filter((e=>e!==t))},sendVoicePlusContext:e=>{v({context:e})}}},e.getCurrentExpirationTimestamp=t=>{let n=null;return t.forEach((t=>{t.type===e.ResponseType.Application&&null!=t.payload.expirationTimestamp&&(n=t.payload.expirationTimestamp)})),n},e.isConfigValid=e=>null!=ve(e),e.promisify=function(t,n,r=1e4){return async o=>await new Promise(((s,i)=>{const a=setTimeout((()=>{i(new Error("The request timed out.")),n.unsubscribe(c)}),r),c=(t,r)=>{r?.type!==e.ResponseType.Application&&r?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(r))};n.subscribe(c),t(o)}))},e.sendVoicePlusStep=async({apiKey:e,workspaceId:t,conversationId:n,scriptId:r,languageCode:o,step:s,context:i,debug:a=!1,dev:c=!1})=>{if(null==r)throw new Error("Voice+ scriptId is not defined.");if("string"!=typeof n||0===n.length)throw new Error("Voice+ conversationId is not defined.");const[u,l]="string"==typeof s?[s,void 0]:[s.stepId,s.stepTriggerDescription];if(!Te.test(u))throw new Error("Invalid stepId. It should be formatted as a UUID.");const d={stepId:u,context:i,conversationId:n,journeyId:r,languageCode:o,stepTriggerDescription:l};try{await I(`https://${c?"dev.":""}mm.nlx.ai/v1/track`,{method:"POST",headers:{"x-api-key":e,"x-nlx-id":t,"Content-Type":"application/json","nlx-sdk-version":ce,"nlx-core-version":ce},body:JSON.stringify(d)}),a&&le.info(`✓ step: ${u}`,d)}catch(e){throw a&&le.error(`× step: ${u}`,e,d),e}},e.shouldReinitialize=(e,t)=>!G(e,t),e.version=ue}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nlxai/core",
3
- "version": "1.2.4-alpha.10",
3
+ "version": "1.2.4-alpha.12",
4
4
  "description": "Low-level SDK for building NLX experiences",
5
5
  "type": "module",
6
6
  "main": "lib/index.cjs",
@@ -56,5 +56,5 @@
56
56
  "publishConfig": {
57
57
  "access": "public"
58
58
  },
59
- "gitHead": "9a1bfacce5cc21ca2d64e79c86805dab37568de3"
59
+ "gitHead": "e1813c1b87516f8d5b5d03d0d6ba5245f18d7869"
60
60
  }