@nlxai/core 1.2.7-alpha.2 → 1.2.7-alpha.3

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/lib/index.cjs CHANGED
@@ -5,7 +5,7 @@ var ReconnectingWebSocket = require('reconnecting-websocket');
5
5
  var uuid = require('uuid');
6
6
 
7
7
  var name = "@nlxai/core";
8
- var version$1 = "1.2.7-alpha.2";
8
+ var version$1 = "1.2.7-alpha.3";
9
9
  var description = "Low-level SDK for building NLX experiences";
10
10
  var type = "module";
11
11
  var main = "lib/index.cjs";
@@ -57,7 +57,7 @@ var dependencies = {
57
57
  var publishConfig = {
58
58
  access: "public"
59
59
  };
60
- var gitHead = "28deac5208ff64f99a3d038050172c1ac9a78630";
60
+ var gitHead = "f08836bfc1133fc7aca671b66ac87f9b8b457ae8";
61
61
  var packageJson = {
62
62
  name: name,
63
63
  version: version$1,
@@ -126,6 +126,10 @@ exports.ResponseType = void 0;
126
126
  * Generic failure (cannot be attributed to the application)
127
127
  */
128
128
  ResponseType["Failure"] = "failure";
129
+ /**
130
+ * Notices for important conversation events like agent joined
131
+ */
132
+ ResponseType["Notice"] = "notice";
129
133
  })(exports.ResponseType || (exports.ResponseType = {}));
130
134
  const welcomeIntent = "NLX.Welcome";
131
135
  const defaultFailureMessage = "We encountered an issue. Please try again soon.";
package/lib/index.d.ts CHANGED
@@ -161,6 +161,8 @@ export interface ConversationHandler {
161
161
  receivedAt?: Time;
162
162
  }) | (Omit<FailureMessage, "receivedAt"> & {
163
163
  receivedAt?: Time;
164
+ }) | (Omit<NoticeResponse, "receivedAt"> & {
165
+ receivedAt?: Time;
164
166
  })) => void;
165
167
  /**
166
168
  * Send a combination of choice, slots, and flow in one request.
@@ -301,7 +303,11 @@ export declare enum ResponseType {
301
303
  /**
302
304
  * Generic failure (cannot be attributed to the application)
303
305
  */
304
- Failure = "failure"
306
+ Failure = "failure",
307
+ /**
308
+ * Notices for important conversation events like agent joined
309
+ */
310
+ Notice = "notice"
305
311
  }
306
312
  /**
307
313
  * Values to fill an flow's [attached slots](https://docs.nlx.ai/platform/nlx-platform-guide/flows-and-building-blocks/overview/setup#attached-slots).
@@ -326,6 +332,7 @@ export type SlotsRecordOrArray = SlotsRecord | SlotValue[];
326
332
  * See also:
327
333
  * - {@link UserResponse}
328
334
  * - {@link FailureMessage}
335
+ * - {@link FailureMessage}
329
336
  * - {@link Response}
330
337
  */
331
338
  export interface ApplicationResponse {
@@ -525,6 +532,7 @@ export interface Choice {
525
532
  *
526
533
  * See also:
527
534
  * - {@link ApplicationResponse}
535
+ * - {@link NoticeResponse}
528
536
  * - {@link FailureMessage}
529
537
  * - {@link Response}
530
538
  *
@@ -585,6 +593,12 @@ export type UserResponsePayload = {
585
593
  } & StructuredRequest);
586
594
  /**
587
595
  * A failure message is received when the NLX api is unreachable, or sends an unparsable response.
596
+ *
597
+ * See also:
598
+ * - {@link ApplicationResponse}
599
+ * - {@link NoticeResponse}
600
+ * - {@link UserResponse}
601
+ * - {@link Response}
588
602
  */
589
603
  export interface FailureMessage {
590
604
  /**
@@ -605,10 +619,38 @@ export interface FailureMessage {
605
619
  */
606
620
  receivedAt: Time;
607
621
  }
622
+ /**
623
+ * A message from the user
624
+ *
625
+ * See also:
626
+ * - {@link ApplicationResponse}
627
+ * - {@link FailureMessage}
628
+ * - {@link Response}
629
+ *
630
+ */
631
+ export interface NoticeResponse {
632
+ /**
633
+ * The notice response type
634
+ */
635
+ type: ResponseType.Notice;
636
+ /**
637
+ * When the response was received
638
+ */
639
+ receivedAt: Time;
640
+ /**
641
+ * The payload of the response
642
+ */
643
+ payload: {
644
+ /**
645
+ * The error message is either the default, or the `failureMessage` set in the {@link Config}.
646
+ */
647
+ text: string;
648
+ };
649
+ }
608
650
  /**
609
651
  * A response from the application or the user.
610
652
  */
611
- export type Response = ApplicationResponse | UserResponse | FailureMessage;
653
+ export type Response = ApplicationResponse | UserResponse | NoticeResponse | FailureMessage;
612
654
  /**
613
655
  * The time value in milliseconds since midnight, January 1, 1970 UTC.
614
656
  */
package/lib/index.esm.js CHANGED
@@ -3,7 +3,7 @@ import ReconnectingWebSocket from 'reconnecting-websocket';
3
3
  import { v4 } from 'uuid';
4
4
 
5
5
  var name = "@nlxai/core";
6
- var version$1 = "1.2.7-alpha.2";
6
+ var version$1 = "1.2.7-alpha.3";
7
7
  var description = "Low-level SDK for building NLX experiences";
8
8
  var type = "module";
9
9
  var main = "lib/index.cjs";
@@ -55,7 +55,7 @@ var dependencies = {
55
55
  var publishConfig = {
56
56
  access: "public"
57
57
  };
58
- var gitHead = "28deac5208ff64f99a3d038050172c1ac9a78630";
58
+ var gitHead = "f08836bfc1133fc7aca671b66ac87f9b8b457ae8";
59
59
  var packageJson = {
60
60
  name: name,
61
61
  version: version$1,
@@ -124,6 +124,10 @@ var ResponseType;
124
124
  * Generic failure (cannot be attributed to the application)
125
125
  */
126
126
  ResponseType["Failure"] = "failure";
127
+ /**
128
+ * Notices for important conversation events like agent joined
129
+ */
130
+ ResponseType["Notice"] = "notice";
127
131
  })(ResponseType || (ResponseType = {}));
128
132
  const welcomeIntent = "NLX.Welcome";
129
133
  const defaultFailureMessage = "We encountered an issue. Please try again soon.";
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 x(e,t){function n(){this.constructor=e}w(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function T(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var o,r,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(o=s.next()).done;)i.push(o.value)}catch(e){r={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}var I=function(e,t){this.target=t,this.type=e},C=function(e){function t(t,n){var o=e.call(this,"error",n)||this;return o.message=t.message,o.error=t,o}return x(t,e),t}(I),O=function(e){function t(t,n,o){void 0===t&&(t=1e3),void 0===n&&(n="");var r=e.call(this,"close",o)||this;return r.wasClean=!0,r.code=t,r.reason=n,r}return x(t,e),t}(I),E=function(){if("undefined"!=typeof WebSocket)return WebSocket},P={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},S=function(){function e(e,t,n){var o=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){o._debug("open event");var t=o._options.minUptime,n=void 0===t?P.minUptime:t;clearTimeout(o._connectTimeout),o._uptimeTimeout=setTimeout(function(){return o._acceptOpen()},n),o._ws.binaryType=o._binaryType,o._messageQueue.forEach(function(e){return o._ws.send(e)}),o._messageQueue=[],o.onopen&&o.onopen(e),o._listeners.open.forEach(function(t){return o._callEventListener(e,t)})},this._handleMessage=function(e){o._debug("message event"),o.onmessage&&o.onmessage(e),o._listeners.message.forEach(function(t){return o._callEventListener(e,t)})},this._handleError=function(e){o._debug("error event",e.message),o._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),o.onerror&&o.onerror(e),o._debug("exec error listeners"),o._listeners.error.forEach(function(t){return o._callEventListener(e,t)}),o._connect()},this._handleClose=function(e){o._debug("close event"),o._clearTimeouts(),o._shouldReconnect&&o._connect(),o.onclose&&o.onclose(e),o._listeners.close.forEach(function(t){return o._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?P.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,o=this._listeners[e.type];if(o)try{for(var r=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}}}}(o),s=r.next();!s.done;s=r.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}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(T(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?P.reconnectionDelayGrowFactor:t,o=e.minReconnectionDelay,r=void 0===o?P.minReconnectionDelay:o,s=e.maxReconnectionDelay,i=void 0===s?P.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=r*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,o=void 0===n?P.maxRetries:n,r=t.connectionTimeout,s=void 0===r?P.connectionTimeout:r,i=t.WebSocket,a=void 0===i?E():i;if(this._retryCount>=o)this._debug("max retries reached",this._retryCount,">=",o);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 C(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 O(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}();const L=[];for(let e=0;e<256;++e)L.push((e+256).toString(16).slice(1));const A=new Uint8Array(16);function R(e,t,n){return crypto.randomUUID?crypto.randomUUID():function(e){e=e||{};const t=e.random??e.rng?.()??crypto.getRandomValues(A);if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return(L[e[t+0]]+L[e[t+1]]+L[e[t+2]]+L[e[t+3]]+"-"+L[e[t+4]]+L[e[t+5]]+"-"+L[e[t+6]]+L[e[t+7]]+"-"+L[e[t+8]]+L[e[t+9]]+"-"+L[e[t+10]]+L[e[t+11]]+L[e[t+12]]+L[e[t+13]]+L[e[t+14]]+L[e[t+15]]).toLowerCase()}(t)}(e)}var U="1.2.7-alpha.2";const k=U,j=console;var K,N;e.Protocol=void 0,(K=e.Protocol||(e.Protocol={})).Http="http",K.HttpWithStreaming="httpWithStreaming",K.Https="https",K.HttpsWithStreaming="httpsWithStreaming",K.Websocket="websocket",e.ResponseType=void 0,(N=e.ResponseType||(e.ResponseType={})).Application="bot",N.User="user",N.Failure="failure";const D="NLX.Welcome",W=e=>Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({slotId:e,value:t})),q=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?W(e.slots):e.slots}),$=e=>e.responses,M=e=>{try{return JSON.parse(e)}catch(e){return null}},F=t=>{const n=t.applicationUrl??"",o=t.apiKey??t.headers?.["nlx-api-key"]??"",r=t.protocol??(H(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:r,apiKey:o,host:t.host,channelKey:t.channelKey,deploymentKey:t.deploymentKey};if(H(n)){const e=(e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai")(n),t=new URL(n),s=new URLSearchParams(t.search),i=s.get("channelKey"),a=s.get("deploymentKey");return null!=i&&null!=a?{protocol:r,channelKey:i,deploymentKey:a,host:e,apiKey:o}:null}const s=new URL(n),i=s.host,a=new URLPattern({pathname:"/c/:deploymentKey/:channelKey"}).exec(n);return null!=a?.pathname.groups.channelKey&&null!=a?.pathname.groups.deploymentKey?{protocol:"http:"===s.protocol?!1===t.experimental?.streamHttp?e.Protocol.Http:e.Protocol.HttpWithStreaming:r,channelKey:a.pathname.groups.channelKey,deploymentKey:a.pathname.groups.deploymentKey,host:i,apiKey:o}:null},H=e=>0===e.indexOf("wss://"),G=async({fullApplicationUrl:e,apiKey:t,headers:n,body:o,stream:r,eventListeners:s})=>{if(r)return await(async o=>{s.interimMessage.forEach(e=>{e("Thinking...")});const r=await fetch(e,{method:"POST",headers:{...n,"nlx-api-key":t,"Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({...o,stream:!0})});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);const i=r.body.getReader(),a=new TextDecoder;let c="";const l=[];let u={};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 o=c.substring(e,n+1);try{const e=JSON.parse(o);if("interim"===e.type){const t=e.text;"string"==typeof t&&s.interimMessage.forEach(e=>{e(t)})}else"message"===e.type?l.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(u=e.data);c=c.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return s.interimMessage.forEach(e=>{e(void 0)}),{...u,messages:[...l,...(u.messages??[]).map(e=>({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}))]}})(o);{const r=await fetch(e,{method:"POST",headers:{...n??{},"nlx-api-key":t,Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify(o)});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);return await r.json()}};const J=/^[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,o,r=[],i=null,a=[],c=null;const l=F(t),u=!0===t.experimental?.completeApplicationUrl,p=u&&H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(e=>`wss://us-east-1-ws.${e.host}?deploymentKey=${e.deploymentKey}&channelKey=${e.channelKey}&apiKey=${e.apiKey}`)(l):t.applicationUrl??"",d=u&&!H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(t=>`${t.protocol===e.Protocol.Http?"http":"https"}://${t.host}/c/${t.deploymentKey}/${t.channelKey}`)(l):t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(d)&&j.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 h=null!=l?l.protocol:H(t.applicationUrl??"")?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming,f={voicePlusCommand:[],interimMessage:[]},y=t.conversationId??R();let g={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:y};const m=()=>`${d}${u?"":`-${g.languageCode}`}`,v=(e,t)=>{g={...g,...e},I.forEach(e=>{e($(g),t)})},_=()=>{f.interimMessage.forEach(e=>{e(void 0)});const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};v({responses:[...g.responses,n]},n)},b=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??[]}))}};v({responses:[...g.responses,n]},n),t.metadata.hasPendingDataRequest&&(L({poll:!0}),setTimeout(()=>{T({request:{structured:{poll:!0}}})},1500))}else j.warn("Invalid message structure, expected object with field 'messages'."),_()};let w;const x=e=>{1===o?.readyState?o.send(JSON.stringify(e)):a=[...a,e]},T=async o=>{if(null!=w)return void w(o,t=>{j.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};v({responses:[...g.responses,n]},n)});const s={userId:g.userId,conversationId:g.conversationId,...o,languageCode:g.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(h===e.Protocol.Websocket)1===n?.readyState?n.send(JSON.stringify(s)):r=[...r,s];else try{const n=await G({fullApplicationUrl:m(),apiKey:l?.apiKey??"",headers:t.headers??{},stream:h===e.Protocol.HttpsWithStreaming||h===e.Protocol.HttpWithStreaming,eventListeners:f,body:s});b(n)}catch(e){j.warn(e),_()}};let I=[];const C=()=>{E();const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),n=new S(e.href),i=setInterval(()=>{(async()=>{1===n?.readyState&&null!=r[0]&&(await T(r[0]),r=r.slice(1))})()},500),n.onmessage=function(e){"string"==typeof e?.data&&b(M(e.data))}},O=()=>{if(P(),!0!==t.bidirectional)return;const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),e.searchParams.set("type","voice-plus"),null!=l?.apiKey&&e.searchParams.set("apiKey",l.apiKey),o=new S(e.href),c=setInterval(()=>{1===o?.readyState&&null!=a[0]&&(x(a[0]),a=a.slice(1))},500),o.onmessage=e=>{if("string"==typeof e?.data){const t=M(e.data);null!=t&&f.voicePlusCommand.forEach(e=>{e(t)})}}},E=()=>{null!=i&&clearInterval(i),null!=n&&(n.onmessage=null,n.close(),n=void 0)},P=()=>{null!=c&&clearInterval(c),null!=o&&(o.onmessage=null,o.close(),o=void 0)};h===e.Protocol.Websocket&&C(),O();const L=(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...q(t),context:n}};v({responses:[...g.responses,o]},o)},A=(e,t)=>{L({intentId:e},t),T({context:t,request:{structured:{intentId:e}}})},k=e=>{I=I.filter(t=>t!==e)};return{sendText:(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};v({responses:[...g.responses,o]},o),T({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await fetch(`${m()}/context`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.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()};v({responses:[...g.responses,t]},t)},setInterimMessage:e=>{f.interimMessage.forEach(t=>{t(e)})},sendStructured:(e,t)=>{L(e,t),T({context:t,request:{structured:q(e)}})},sendSlots:(e,t)=>{L({slots:e},t),T({context:t,request:{structured:{slots:W(e)}}})},sendFlow:A,sendIntent:(e,t)=>{j.warn("Calling `sendIntent` is deprecated and will be removed in a future version of the SDK. Use `sendFlow` instead."),A(e,t)},sendWelcomeFlow:e=>{A(D,e)},sendWelcomeIntent:e=>{j.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),A(D,e)},sendChoice:(t,n,o)=>{let r=[...g.responses];const i={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},a=o?.responseIndex??-1,c=o?.messageIndex??-1;a>-1&&c>-1&&(r=s(a,n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:s(c,e=>({...e,selectedChoiceId:t}),n.payload.messages)}}:n,r)),r=[...r,i],v({responses:r},i),T({context:n,request:{structured:{nodeId:o?.nodeId,intentId:o?.flowId??o?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>g.conversationId,setLanguageCode:t=>{t!==g.languageCode?(l?.protocol===e.Protocol.Websocket&&C(),O(),v({languageCode:t})):j.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>g.languageCode,getVoiceCredentials:async(e,n)=>{const o=await fetch(`${d}-${g.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(o.status>=400)throw new Error(`Responded with ${o.status}`);const r=await o.json();if(null==r?.url)throw new Error("Invalid response");return r},subscribe:e=>(I=[...I,e],e($(g)),()=>{k(e)}),unsubscribe:k,unsubscribeAll:()=>{I=[]},reset:t=>{v({conversationId:R(),responses:!0===t?.clearResponses?[]:g.responses}),l?.protocol===e.Protocol.Websocket&&C(),O()},destroy:()=>{I=[],l?.protocol===e.Protocol.Websocket&&E(),P()},setRequestOverride:e=>{w=e},addEventListener:(e,t)=>{f[e]=[...f[e],t]},removeEventListener:(e,t)=>{f[e]=f[e].filter(e=>e!==t)},sendVoicePlusContext:e=>{x({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!=F(e),e.promisify=function(t,n,o=1e4){return async r=>await new Promise((s,i)=>{const a=setTimeout(()=>{i(new Error("The request timed out.")),n.unsubscribe(c)},o),c=(t,o)=>{o?.type!==e.ResponseType.Application&&o?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(o))};n.subscribe(c),t(r)})},e.sendVoicePlusStep=async({apiKey:e,workspaceId:t,conversationId:n,scriptId:o,languageCode:r,step:s,context:i,debug:a=!1,dev:c=!1})=>{if(null==o)throw new Error("Voice+ scriptId is not defined.");if("string"!=typeof n||0===n.length)throw new Error("Voice+ conversationId is not defined.");const[l,u]="string"==typeof s?[s,void 0]:[s.stepId,s.stepTriggerDescription];if(!J.test(l))throw new Error("Invalid stepId. It should be formatted as a UUID.");const p={stepId:l,context:i,conversationId:n,journeyId:o,languageCode:r,stepTriggerDescription:u};try{await fetch(`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":U,"nlx-core-version":U},body:JSON.stringify(p)}),a&&j.info(`✓ step: ${l}`,p)}catch(e){throw a&&j.error(`× step: ${l}`,e,p),e}},e.shouldReinitialize=(e,t)=>!b(e,t),e.version=k});
15
+ ***************************************************************************** */function x(e,t){function n(){this.constructor=e}w(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function T(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var o,r,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(o=s.next()).done;)i.push(o.value)}catch(e){r={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}var I=function(e,t){this.target=t,this.type=e},C=function(e){function t(t,n){var o=e.call(this,"error",n)||this;return o.message=t.message,o.error=t,o}return x(t,e),t}(I),O=function(e){function t(t,n,o){void 0===t&&(t=1e3),void 0===n&&(n="");var r=e.call(this,"close",o)||this;return r.wasClean=!0,r.code=t,r.reason=n,r}return x(t,e),t}(I),E=function(){if("undefined"!=typeof WebSocket)return WebSocket},P={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},S=function(){function e(e,t,n){var o=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){o._debug("open event");var t=o._options.minUptime,n=void 0===t?P.minUptime:t;clearTimeout(o._connectTimeout),o._uptimeTimeout=setTimeout(function(){return o._acceptOpen()},n),o._ws.binaryType=o._binaryType,o._messageQueue.forEach(function(e){return o._ws.send(e)}),o._messageQueue=[],o.onopen&&o.onopen(e),o._listeners.open.forEach(function(t){return o._callEventListener(e,t)})},this._handleMessage=function(e){o._debug("message event"),o.onmessage&&o.onmessage(e),o._listeners.message.forEach(function(t){return o._callEventListener(e,t)})},this._handleError=function(e){o._debug("error event",e.message),o._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),o.onerror&&o.onerror(e),o._debug("exec error listeners"),o._listeners.error.forEach(function(t){return o._callEventListener(e,t)}),o._connect()},this._handleClose=function(e){o._debug("close event"),o._clearTimeouts(),o._shouldReconnect&&o._connect(),o.onclose&&o.onclose(e),o._listeners.close.forEach(function(t){return o._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?P.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,o=this._listeners[e.type];if(o)try{for(var r=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}}}}(o),s=r.next();!s.done;s=r.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}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(T(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?P.reconnectionDelayGrowFactor:t,o=e.minReconnectionDelay,r=void 0===o?P.minReconnectionDelay:o,s=e.maxReconnectionDelay,i=void 0===s?P.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=r*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,o=void 0===n?P.maxRetries:n,r=t.connectionTimeout,s=void 0===r?P.connectionTimeout:r,i=t.WebSocket,a=void 0===i?E():i;if(this._retryCount>=o)this._debug("max retries reached",this._retryCount,">=",o);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 C(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 O(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}();const L=[];for(let e=0;e<256;++e)L.push((e+256).toString(16).slice(1));const A=new Uint8Array(16);function R(e,t,n){return crypto.randomUUID?crypto.randomUUID():function(e){e=e||{};const t=e.random??e.rng?.()??crypto.getRandomValues(A);if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return(L[e[t+0]]+L[e[t+1]]+L[e[t+2]]+L[e[t+3]]+"-"+L[e[t+4]]+L[e[t+5]]+"-"+L[e[t+6]]+L[e[t+7]]+"-"+L[e[t+8]]+L[e[t+9]]+"-"+L[e[t+10]]+L[e[t+11]]+L[e[t+12]]+L[e[t+13]]+L[e[t+14]]+L[e[t+15]]).toLowerCase()}(t)}(e)}var U="1.2.7-alpha.3";const k=U,j=console;var K,N;e.Protocol=void 0,(K=e.Protocol||(e.Protocol={})).Http="http",K.HttpWithStreaming="httpWithStreaming",K.Https="https",K.HttpsWithStreaming="httpsWithStreaming",K.Websocket="websocket",e.ResponseType=void 0,(N=e.ResponseType||(e.ResponseType={})).Application="bot",N.User="user",N.Failure="failure",N.Notice="notice";const D="NLX.Welcome",W=e=>Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({slotId:e,value:t})),q=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?W(e.slots):e.slots}),$=e=>e.responses,M=e=>{try{return JSON.parse(e)}catch(e){return null}},F=t=>{const n=t.applicationUrl??"",o=t.apiKey??t.headers?.["nlx-api-key"]??"",r=t.protocol??(H(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:r,apiKey:o,host:t.host,channelKey:t.channelKey,deploymentKey:t.deploymentKey};if(H(n)){const e=(e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai")(n),t=new URL(n),s=new URLSearchParams(t.search),i=s.get("channelKey"),a=s.get("deploymentKey");return null!=i&&null!=a?{protocol:r,channelKey:i,deploymentKey:a,host:e,apiKey:o}:null}const s=new URL(n),i=s.host,a=new URLPattern({pathname:"/c/:deploymentKey/:channelKey"}).exec(n);return null!=a?.pathname.groups.channelKey&&null!=a?.pathname.groups.deploymentKey?{protocol:"http:"===s.protocol?!1===t.experimental?.streamHttp?e.Protocol.Http:e.Protocol.HttpWithStreaming:r,channelKey:a.pathname.groups.channelKey,deploymentKey:a.pathname.groups.deploymentKey,host:i,apiKey:o}:null},H=e=>0===e.indexOf("wss://"),G=async({fullApplicationUrl:e,apiKey:t,headers:n,body:o,stream:r,eventListeners:s})=>{if(r)return await(async o=>{s.interimMessage.forEach(e=>{e("Thinking...")});const r=await fetch(e,{method:"POST",headers:{...n,"nlx-api-key":t,"Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({...o,stream:!0})});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);const i=r.body.getReader(),a=new TextDecoder;let c="";const l=[];let u={};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 o=c.substring(e,n+1);try{const e=JSON.parse(o);if("interim"===e.type){const t=e.text;"string"==typeof t&&s.interimMessage.forEach(e=>{e(t)})}else"message"===e.type?l.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(u=e.data);c=c.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return s.interimMessage.forEach(e=>{e(void 0)}),{...u,messages:[...l,...(u.messages??[]).map(e=>({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}))]}})(o);{const r=await fetch(e,{method:"POST",headers:{...n??{},"nlx-api-key":t,Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify(o)});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);return await r.json()}};const J=/^[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,o,r=[],i=null,a=[],c=null;const l=F(t),u=!0===t.experimental?.completeApplicationUrl,p=u&&H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(e=>`wss://us-east-1-ws.${e.host}?deploymentKey=${e.deploymentKey}&channelKey=${e.channelKey}&apiKey=${e.apiKey}`)(l):t.applicationUrl??"",d=u&&!H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(t=>`${t.protocol===e.Protocol.Http?"http":"https"}://${t.host}/c/${t.deploymentKey}/${t.channelKey}`)(l):t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(d)&&j.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 h=null!=l?l.protocol:H(t.applicationUrl??"")?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming,f={voicePlusCommand:[],interimMessage:[]},y=t.conversationId??R();let g={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:y};const m=()=>`${d}${u?"":`-${g.languageCode}`}`,v=(e,t)=>{g={...g,...e},I.forEach(e=>{e($(g),t)})},_=()=>{f.interimMessage.forEach(e=>{e(void 0)});const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};v({responses:[...g.responses,n]},n)},b=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??[]}))}};v({responses:[...g.responses,n]},n),t.metadata.hasPendingDataRequest&&(L({poll:!0}),setTimeout(()=>{T({request:{structured:{poll:!0}}})},1500))}else j.warn("Invalid message structure, expected object with field 'messages'."),_()};let w;const x=e=>{1===o?.readyState?o.send(JSON.stringify(e)):a=[...a,e]},T=async o=>{if(null!=w)return void w(o,t=>{j.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};v({responses:[...g.responses,n]},n)});const s={userId:g.userId,conversationId:g.conversationId,...o,languageCode:g.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(h===e.Protocol.Websocket)1===n?.readyState?n.send(JSON.stringify(s)):r=[...r,s];else try{const n=await G({fullApplicationUrl:m(),apiKey:l?.apiKey??"",headers:t.headers??{},stream:h===e.Protocol.HttpsWithStreaming||h===e.Protocol.HttpWithStreaming,eventListeners:f,body:s});b(n)}catch(e){j.warn(e),_()}};let I=[];const C=()=>{E();const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),n=new S(e.href),i=setInterval(()=>{(async()=>{1===n?.readyState&&null!=r[0]&&(await T(r[0]),r=r.slice(1))})()},500),n.onmessage=function(e){"string"==typeof e?.data&&b(M(e.data))}},O=()=>{if(P(),!0!==t.bidirectional)return;const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),e.searchParams.set("type","voice-plus"),null!=l?.apiKey&&e.searchParams.set("apiKey",l.apiKey),o=new S(e.href),c=setInterval(()=>{1===o?.readyState&&null!=a[0]&&(x(a[0]),a=a.slice(1))},500),o.onmessage=e=>{if("string"==typeof e?.data){const t=M(e.data);null!=t&&f.voicePlusCommand.forEach(e=>{e(t)})}}},E=()=>{null!=i&&clearInterval(i),null!=n&&(n.onmessage=null,n.close(),n=void 0)},P=()=>{null!=c&&clearInterval(c),null!=o&&(o.onmessage=null,o.close(),o=void 0)};h===e.Protocol.Websocket&&C(),O();const L=(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...q(t),context:n}};v({responses:[...g.responses,o]},o)},A=(e,t)=>{L({intentId:e},t),T({context:t,request:{structured:{intentId:e}}})},k=e=>{I=I.filter(t=>t!==e)};return{sendText:(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};v({responses:[...g.responses,o]},o),T({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await fetch(`${m()}/context`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.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()};v({responses:[...g.responses,t]},t)},setInterimMessage:e=>{f.interimMessage.forEach(t=>{t(e)})},sendStructured:(e,t)=>{L(e,t),T({context:t,request:{structured:q(e)}})},sendSlots:(e,t)=>{L({slots:e},t),T({context:t,request:{structured:{slots:W(e)}}})},sendFlow:A,sendIntent:(e,t)=>{j.warn("Calling `sendIntent` is deprecated and will be removed in a future version of the SDK. Use `sendFlow` instead."),A(e,t)},sendWelcomeFlow:e=>{A(D,e)},sendWelcomeIntent:e=>{j.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),A(D,e)},sendChoice:(t,n,o)=>{let r=[...g.responses];const i={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},a=o?.responseIndex??-1,c=o?.messageIndex??-1;a>-1&&c>-1&&(r=s(a,n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:s(c,e=>({...e,selectedChoiceId:t}),n.payload.messages)}}:n,r)),r=[...r,i],v({responses:r},i),T({context:n,request:{structured:{nodeId:o?.nodeId,intentId:o?.flowId??o?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>g.conversationId,setLanguageCode:t=>{t!==g.languageCode?(l?.protocol===e.Protocol.Websocket&&C(),O(),v({languageCode:t})):j.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>g.languageCode,getVoiceCredentials:async(e,n)=>{const o=await fetch(`${d}-${g.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(o.status>=400)throw new Error(`Responded with ${o.status}`);const r=await o.json();if(null==r?.url)throw new Error("Invalid response");return r},subscribe:e=>(I=[...I,e],e($(g)),()=>{k(e)}),unsubscribe:k,unsubscribeAll:()=>{I=[]},reset:t=>{v({conversationId:R(),responses:!0===t?.clearResponses?[]:g.responses}),l?.protocol===e.Protocol.Websocket&&C(),O()},destroy:()=>{I=[],l?.protocol===e.Protocol.Websocket&&E(),P()},setRequestOverride:e=>{w=e},addEventListener:(e,t)=>{f[e]=[...f[e],t]},removeEventListener:(e,t)=>{f[e]=f[e].filter(e=>e!==t)},sendVoicePlusContext:e=>{x({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!=F(e),e.promisify=function(t,n,o=1e4){return async r=>await new Promise((s,i)=>{const a=setTimeout(()=>{i(new Error("The request timed out.")),n.unsubscribe(c)},o),c=(t,o)=>{o?.type!==e.ResponseType.Application&&o?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(o))};n.subscribe(c),t(r)})},e.sendVoicePlusStep=async({apiKey:e,workspaceId:t,conversationId:n,scriptId:o,languageCode:r,step:s,context:i,debug:a=!1,dev:c=!1})=>{if(null==o)throw new Error("Voice+ scriptId is not defined.");if("string"!=typeof n||0===n.length)throw new Error("Voice+ conversationId is not defined.");const[l,u]="string"==typeof s?[s,void 0]:[s.stepId,s.stepTriggerDescription];if(!J.test(l))throw new Error("Invalid stepId. It should be formatted as a UUID.");const p={stepId:l,context:i,conversationId:n,journeyId:o,languageCode:r,stepTriggerDescription:u};try{await fetch(`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":U,"nlx-core-version":U},body:JSON.stringify(p)}),a&&j.info(`✓ step: ${l}`,p)}catch(e){throw a&&j.error(`× step: ${l}`,e,p),e}},e.shouldReinitialize=(e,t)=>!b(e,t),e.version=k});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nlxai/core",
3
- "version": "1.2.7-alpha.2",
3
+ "version": "1.2.7-alpha.3",
4
4
  "description": "Low-level SDK for building NLX experiences",
5
5
  "type": "module",
6
6
  "main": "lib/index.cjs",
@@ -52,5 +52,5 @@
52
52
  "publishConfig": {
53
53
  "access": "public"
54
54
  },
55
- "gitHead": "28deac5208ff64f99a3d038050172c1ac9a78630"
55
+ "gitHead": "f08836bfc1133fc7aca671b66ac87f9b8b457ae8"
56
56
  }