@nlxai/core 1.2.6 → 1.2.7-alpha.2

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.
@@ -0,0 +1,5 @@
1
+ import baseConfig from "@nlxai/eslint-config";
2
+ import documentation from "@nlxai/eslint-config/documentation";
3
+
4
+ /** @type {import('eslint').Linter.Config[]} */
5
+ export default [...baseConfig, ...documentation];
package/lib/index.cjs CHANGED
@@ -1,12 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var fetch = require('isomorphic-fetch');
4
3
  var ramda = require('ramda');
5
4
  var ReconnectingWebSocket = require('reconnecting-websocket');
6
5
  var uuid = require('uuid');
7
6
 
8
7
  var name = "@nlxai/core";
9
- var version$1 = "1.2.6";
8
+ var version$1 = "1.2.7-alpha.2";
10
9
  var description = "Low-level SDK for building NLX experiences";
11
10
  var type = "module";
12
11
  var main = "lib/index.cjs";
@@ -22,8 +21,8 @@ var exports$1 = {
22
21
  };
23
22
  var scripts = {
24
23
  build: "rm -rf lib && rollup -c --configPlugin typescript --configImportAttributesKey with",
25
- "lint:check": "eslint src/ --ext .ts,.tsx,.js,.jsx --max-warnings 0",
26
- lint: "eslint src/ --ext .ts,.tsx,.js,.jsx --fix",
24
+ "lint:check": "eslint src/",
25
+ lint: "eslint src/ --fix",
27
26
  prepublish: "npm run build",
28
27
  test: "typedoc --emit none",
29
28
  tsc: "tsc",
@@ -42,27 +41,23 @@ var devDependencies = {
42
41
  "@rollup/plugin-replace": "^5.0.5",
43
42
  "@rollup/plugin-terser": "^0.4.4",
44
43
  "@rollup/plugin-typescript": "^11.1.6",
45
- "@types/isomorphic-fetch": "^0.0.39",
46
44
  "@types/node": "^24.10.1",
47
45
  "@types/ramda": "0.31.1",
48
- "@types/uuid": "^9.0.7",
49
46
  prettier: "^3.1.0",
50
47
  rollup: "^4.59.0",
51
- "rollup-plugin-node-polyfills": "^0.2.1",
52
48
  typedoc: "^0.28.14",
53
49
  "typedoc-plugin-markdown": "^4.9.0",
54
50
  typescript: "^5.5.4"
55
51
  };
56
52
  var dependencies = {
57
- "isomorphic-fetch": "^3.0.0",
58
53
  ramda: "^0.32.0",
59
54
  "reconnecting-websocket": "^4.4.0",
60
- uuid: "^9.0.1"
55
+ uuid: "^14.0.0"
61
56
  };
62
57
  var publishConfig = {
63
58
  access: "public"
64
59
  };
65
- var gitHead = "fb9a0b00ca2184fb69ffd1e11e8f55d30fe1d85e";
60
+ var gitHead = "28deac5208ff64f99a3d038050172c1ac9a78630";
66
61
  var packageJson = {
67
62
  name: name,
68
63
  version: version$1,
@@ -97,6 +92,10 @@ exports.Protocol = void 0;
97
92
  * Supported for development purposes only
98
93
  */
99
94
  Protocol["Http"] = "http";
95
+ /**
96
+ * Supported for development purposes only
97
+ */
98
+ Protocol["HttpWithStreaming"] = "httpWithStreaming";
100
99
  /**
101
100
  * Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
102
101
  */
@@ -207,7 +206,13 @@ const parseConnection = (config) => {
207
206
  if (parseResult?.pathname.groups.channelKey != null &&
208
207
  parseResult?.pathname.groups.deploymentKey != null) {
209
208
  return {
210
- protocol: urlObject.protocol === "http:" ? exports.Protocol.Http : protocol,
209
+ protocol:
210
+ // Correction for the dev case
211
+ urlObject.protocol === "http:"
212
+ ? config.experimental?.streamHttp === false
213
+ ? exports.Protocol.Http
214
+ : exports.Protocol.HttpWithStreaming
215
+ : protocol,
211
216
  channelKey: parseResult.pathname.groups.channelKey,
212
217
  deploymentKey: parseResult.pathname.groups.deploymentKey,
213
218
  host,
@@ -227,6 +232,9 @@ const isWebsocketUrl = (url) => {
227
232
  };
228
233
  const fetchUserMessage = async ({ fullApplicationUrl, apiKey, headers, body, stream, eventListeners, }) => {
229
234
  const streamRequest = async (body) => {
235
+ eventListeners.interimMessage.forEach((listener) => {
236
+ listener("Thinking...");
237
+ });
230
238
  const response = await fetch(fullApplicationUrl, {
231
239
  method: "POST",
232
240
  headers: {
@@ -284,7 +292,7 @@ const fetchUserMessage = async ({ fullApplicationUrl, apiKey, headers, body, str
284
292
  foundObject = true;
285
293
  break;
286
294
  }
287
- catch (e) {
295
+ catch (_e) {
288
296
  /* keep scanning */
289
297
  }
290
298
  }
@@ -358,16 +366,28 @@ function createConversation(configuration) {
358
366
  let voicePlusSocketMessageQueue = [];
359
367
  let voicePlusSocketMessageQueueCheckInterval = null;
360
368
  const connection = parseConnection(configuration);
361
- const websocketApplicationUrl = connection != null
362
- ? toWebsocketUrl(connection)
363
- : configuration.applicationUrl ?? "";
364
- const httpApplicationUrl = connection != null
365
- ? toHttpUrl(connection)
366
- : configuration.applicationUrl ?? "";
369
+ const complete = configuration.experimental?.completeApplicationUrl === true;
370
+ const websocketApplicationUrl = complete && isWebsocketUrl(configuration.applicationUrl ?? "")
371
+ ? (configuration.applicationUrl ?? "")
372
+ : connection != null
373
+ ? toWebsocketUrl(connection)
374
+ : (configuration.applicationUrl ?? "");
375
+ const httpApplicationUrl = complete && !isWebsocketUrl(configuration.applicationUrl ?? "")
376
+ ? (configuration.applicationUrl ?? "")
377
+ : connection != null
378
+ ? toHttpUrl(connection)
379
+ : (configuration.applicationUrl ?? "");
367
380
  // Check if the application URL has a language code appended to it
368
381
  if (/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(httpApplicationUrl)) {
369
382
  Console.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.");
370
383
  }
384
+ const protocol = connection != null
385
+ ? connection.protocol
386
+ : isWebsocketUrl(configuration.applicationUrl ?? "")
387
+ ? exports.Protocol.Websocket
388
+ : configuration.experimental?.streamHttp === false
389
+ ? exports.Protocol.Https
390
+ : exports.Protocol.HttpsWithStreaming;
371
391
  const eventListeners = {
372
392
  voicePlusCommand: [],
373
393
  interimMessage: [],
@@ -379,9 +399,7 @@ function createConversation(configuration) {
379
399
  userId: configuration.userId,
380
400
  conversationId: initialConversationId,
381
401
  };
382
- const fullApplicationHttpUrl = () => `${httpApplicationUrl}${configuration.experimental?.completeApplicationUrl === true
383
- ? ""
384
- : `-${state.languageCode}`}`;
402
+ const fullApplicationHttpUrl = () => `${httpApplicationUrl}${complete ? "" : `-${state.languageCode}`}`;
385
403
  const setState = (change,
386
404
  // Optionally send the response that causes the current state change, to be sent to subscribers
387
405
  newResponse) => {
@@ -394,6 +412,9 @@ function createConversation(configuration) {
394
412
  });
395
413
  };
396
414
  const failureHandler = () => {
415
+ eventListeners.interimMessage.forEach((listener) => {
416
+ listener(undefined);
417
+ });
397
418
  const newResponse = {
398
419
  type: exports.ResponseType.Failure,
399
420
  receivedAt: new Date().getTime(),
@@ -450,6 +471,11 @@ function createConversation(configuration) {
450
471
  voicePlusSocketMessageQueue = [...voicePlusSocketMessageQueue, message];
451
472
  }
452
473
  };
474
+ const setInterimMessage = (message) => {
475
+ eventListeners.interimMessage.forEach((listener) => {
476
+ listener(message);
477
+ });
478
+ };
453
479
  const sendToApplication = async (body) => {
454
480
  if (requestOverride != null) {
455
481
  requestOverride(body, (payload) => {
@@ -473,7 +499,7 @@ function createConversation(configuration) {
473
499
  channelType: configuration.experimental?.channelType,
474
500
  environment: configuration.environment,
475
501
  };
476
- if (connection?.protocol === exports.Protocol.Websocket) {
502
+ if (protocol === exports.Protocol.Websocket) {
477
503
  if (socket?.readyState === 1) {
478
504
  socket.send(JSON.stringify(bodyWithContext));
479
505
  }
@@ -487,7 +513,8 @@ function createConversation(configuration) {
487
513
  fullApplicationUrl: fullApplicationHttpUrl(),
488
514
  apiKey: connection?.apiKey ?? "",
489
515
  headers: configuration.headers ?? {},
490
- stream: connection?.protocol === exports.Protocol.HttpsWithStreaming,
516
+ stream: protocol === exports.Protocol.HttpsWithStreaming ||
517
+ protocol === exports.Protocol.HttpWithStreaming,
491
518
  eventListeners,
492
519
  body: bodyWithContext,
493
520
  });
@@ -583,7 +610,7 @@ function createConversation(configuration) {
583
610
  voicePlusSocket = undefined;
584
611
  }
585
612
  };
586
- if (connection?.protocol === exports.Protocol.Websocket) {
613
+ if (protocol === exports.Protocol.Websocket) {
587
614
  setupWebsocket();
588
615
  }
589
616
  setupCommandWebsocket();
@@ -717,6 +744,7 @@ function createConversation(configuration) {
717
744
  responses: [...state.responses, newResponseWithTimestamp],
718
745
  }, newResponseWithTimestamp);
719
746
  },
747
+ setInterimMessage,
720
748
  sendStructured: (structured, context) => {
721
749
  appendStructuredUserResponse(structured, context);
722
750
  void sendToApplication({
package/lib/index.d.ts CHANGED
@@ -235,6 +235,11 @@ export interface ConversationHandler {
235
235
  * @internal
236
236
  */
237
237
  sendVoicePlusContext: (context: VoicePlusContext) => void;
238
+ /**
239
+ * Set interim message. Setting `undefined` clears the current interim message.
240
+ * @param message - interim message.
241
+ */
242
+ setInterimMessage: (message?: string) => void;
238
243
  }
239
244
  /**
240
245
  * [Context](https://docs.nlx.ai/platform/nlx-platform-guide/flows-and-building-blocks/advanced/context-variables) for usage later in the flow.
@@ -264,6 +269,10 @@ export declare enum Protocol {
264
269
  * Supported for development purposes only
265
270
  */
266
271
  Http = "http",
272
+ /**
273
+ * Supported for development purposes only
274
+ */
275
+ HttpWithStreaming = "httpWithStreaming",
267
276
  /**
268
277
  * Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
269
278
  */
package/lib/index.esm.js CHANGED
@@ -1,10 +1,9 @@
1
- import fetch from 'isomorphic-fetch';
2
1
  import { equals, adjust } from 'ramda';
3
2
  import ReconnectingWebSocket from 'reconnecting-websocket';
4
3
  import { v4 } from 'uuid';
5
4
 
6
5
  var name = "@nlxai/core";
7
- var version$1 = "1.2.6";
6
+ var version$1 = "1.2.7-alpha.2";
8
7
  var description = "Low-level SDK for building NLX experiences";
9
8
  var type = "module";
10
9
  var main = "lib/index.cjs";
@@ -20,8 +19,8 @@ var exports$1 = {
20
19
  };
21
20
  var scripts = {
22
21
  build: "rm -rf lib && rollup -c --configPlugin typescript --configImportAttributesKey with",
23
- "lint:check": "eslint src/ --ext .ts,.tsx,.js,.jsx --max-warnings 0",
24
- lint: "eslint src/ --ext .ts,.tsx,.js,.jsx --fix",
22
+ "lint:check": "eslint src/",
23
+ lint: "eslint src/ --fix",
25
24
  prepublish: "npm run build",
26
25
  test: "typedoc --emit none",
27
26
  tsc: "tsc",
@@ -40,27 +39,23 @@ var devDependencies = {
40
39
  "@rollup/plugin-replace": "^5.0.5",
41
40
  "@rollup/plugin-terser": "^0.4.4",
42
41
  "@rollup/plugin-typescript": "^11.1.6",
43
- "@types/isomorphic-fetch": "^0.0.39",
44
42
  "@types/node": "^24.10.1",
45
43
  "@types/ramda": "0.31.1",
46
- "@types/uuid": "^9.0.7",
47
44
  prettier: "^3.1.0",
48
45
  rollup: "^4.59.0",
49
- "rollup-plugin-node-polyfills": "^0.2.1",
50
46
  typedoc: "^0.28.14",
51
47
  "typedoc-plugin-markdown": "^4.9.0",
52
48
  typescript: "^5.5.4"
53
49
  };
54
50
  var dependencies = {
55
- "isomorphic-fetch": "^3.0.0",
56
51
  ramda: "^0.32.0",
57
52
  "reconnecting-websocket": "^4.4.0",
58
- uuid: "^9.0.1"
53
+ uuid: "^14.0.0"
59
54
  };
60
55
  var publishConfig = {
61
56
  access: "public"
62
57
  };
63
- var gitHead = "fb9a0b00ca2184fb69ffd1e11e8f55d30fe1d85e";
58
+ var gitHead = "28deac5208ff64f99a3d038050172c1ac9a78630";
64
59
  var packageJson = {
65
60
  name: name,
66
61
  version: version$1,
@@ -95,6 +90,10 @@ var Protocol;
95
90
  * Supported for development purposes only
96
91
  */
97
92
  Protocol["Http"] = "http";
93
+ /**
94
+ * Supported for development purposes only
95
+ */
96
+ Protocol["HttpWithStreaming"] = "httpWithStreaming";
98
97
  /**
99
98
  * Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
100
99
  */
@@ -205,7 +204,13 @@ const parseConnection = (config) => {
205
204
  if (parseResult?.pathname.groups.channelKey != null &&
206
205
  parseResult?.pathname.groups.deploymentKey != null) {
207
206
  return {
208
- protocol: urlObject.protocol === "http:" ? Protocol.Http : protocol,
207
+ protocol:
208
+ // Correction for the dev case
209
+ urlObject.protocol === "http:"
210
+ ? config.experimental?.streamHttp === false
211
+ ? Protocol.Http
212
+ : Protocol.HttpWithStreaming
213
+ : protocol,
209
214
  channelKey: parseResult.pathname.groups.channelKey,
210
215
  deploymentKey: parseResult.pathname.groups.deploymentKey,
211
216
  host,
@@ -225,6 +230,9 @@ const isWebsocketUrl = (url) => {
225
230
  };
226
231
  const fetchUserMessage = async ({ fullApplicationUrl, apiKey, headers, body, stream, eventListeners, }) => {
227
232
  const streamRequest = async (body) => {
233
+ eventListeners.interimMessage.forEach((listener) => {
234
+ listener("Thinking...");
235
+ });
228
236
  const response = await fetch(fullApplicationUrl, {
229
237
  method: "POST",
230
238
  headers: {
@@ -282,7 +290,7 @@ const fetchUserMessage = async ({ fullApplicationUrl, apiKey, headers, body, str
282
290
  foundObject = true;
283
291
  break;
284
292
  }
285
- catch (e) {
293
+ catch (_e) {
286
294
  /* keep scanning */
287
295
  }
288
296
  }
@@ -356,16 +364,28 @@ function createConversation(configuration) {
356
364
  let voicePlusSocketMessageQueue = [];
357
365
  let voicePlusSocketMessageQueueCheckInterval = null;
358
366
  const connection = parseConnection(configuration);
359
- const websocketApplicationUrl = connection != null
360
- ? toWebsocketUrl(connection)
361
- : configuration.applicationUrl ?? "";
362
- const httpApplicationUrl = connection != null
363
- ? toHttpUrl(connection)
364
- : configuration.applicationUrl ?? "";
367
+ const complete = configuration.experimental?.completeApplicationUrl === true;
368
+ const websocketApplicationUrl = complete && isWebsocketUrl(configuration.applicationUrl ?? "")
369
+ ? (configuration.applicationUrl ?? "")
370
+ : connection != null
371
+ ? toWebsocketUrl(connection)
372
+ : (configuration.applicationUrl ?? "");
373
+ const httpApplicationUrl = complete && !isWebsocketUrl(configuration.applicationUrl ?? "")
374
+ ? (configuration.applicationUrl ?? "")
375
+ : connection != null
376
+ ? toHttpUrl(connection)
377
+ : (configuration.applicationUrl ?? "");
365
378
  // Check if the application URL has a language code appended to it
366
379
  if (/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(httpApplicationUrl)) {
367
380
  Console.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.");
368
381
  }
382
+ const protocol = connection != null
383
+ ? connection.protocol
384
+ : isWebsocketUrl(configuration.applicationUrl ?? "")
385
+ ? Protocol.Websocket
386
+ : configuration.experimental?.streamHttp === false
387
+ ? Protocol.Https
388
+ : Protocol.HttpsWithStreaming;
369
389
  const eventListeners = {
370
390
  voicePlusCommand: [],
371
391
  interimMessage: [],
@@ -377,9 +397,7 @@ function createConversation(configuration) {
377
397
  userId: configuration.userId,
378
398
  conversationId: initialConversationId,
379
399
  };
380
- const fullApplicationHttpUrl = () => `${httpApplicationUrl}${configuration.experimental?.completeApplicationUrl === true
381
- ? ""
382
- : `-${state.languageCode}`}`;
400
+ const fullApplicationHttpUrl = () => `${httpApplicationUrl}${complete ? "" : `-${state.languageCode}`}`;
383
401
  const setState = (change,
384
402
  // Optionally send the response that causes the current state change, to be sent to subscribers
385
403
  newResponse) => {
@@ -392,6 +410,9 @@ function createConversation(configuration) {
392
410
  });
393
411
  };
394
412
  const failureHandler = () => {
413
+ eventListeners.interimMessage.forEach((listener) => {
414
+ listener(undefined);
415
+ });
395
416
  const newResponse = {
396
417
  type: ResponseType.Failure,
397
418
  receivedAt: new Date().getTime(),
@@ -448,6 +469,11 @@ function createConversation(configuration) {
448
469
  voicePlusSocketMessageQueue = [...voicePlusSocketMessageQueue, message];
449
470
  }
450
471
  };
472
+ const setInterimMessage = (message) => {
473
+ eventListeners.interimMessage.forEach((listener) => {
474
+ listener(message);
475
+ });
476
+ };
451
477
  const sendToApplication = async (body) => {
452
478
  if (requestOverride != null) {
453
479
  requestOverride(body, (payload) => {
@@ -471,7 +497,7 @@ function createConversation(configuration) {
471
497
  channelType: configuration.experimental?.channelType,
472
498
  environment: configuration.environment,
473
499
  };
474
- if (connection?.protocol === Protocol.Websocket) {
500
+ if (protocol === Protocol.Websocket) {
475
501
  if (socket?.readyState === 1) {
476
502
  socket.send(JSON.stringify(bodyWithContext));
477
503
  }
@@ -485,7 +511,8 @@ function createConversation(configuration) {
485
511
  fullApplicationUrl: fullApplicationHttpUrl(),
486
512
  apiKey: connection?.apiKey ?? "",
487
513
  headers: configuration.headers ?? {},
488
- stream: connection?.protocol === Protocol.HttpsWithStreaming,
514
+ stream: protocol === Protocol.HttpsWithStreaming ||
515
+ protocol === Protocol.HttpWithStreaming,
489
516
  eventListeners,
490
517
  body: bodyWithContext,
491
518
  });
@@ -581,7 +608,7 @@ function createConversation(configuration) {
581
608
  voicePlusSocket = undefined;
582
609
  }
583
610
  };
584
- if (connection?.protocol === Protocol.Websocket) {
611
+ if (protocol === Protocol.Websocket) {
585
612
  setupWebsocket();
586
613
  }
587
614
  setupCommandWebsocket();
@@ -715,6 +742,7 @@ function createConversation(configuration) {
715
742
  responses: [...state.responses, newResponseWithTimestamp],
716
743
  }, newResponseWithTimestamp);
717
744
  },
745
+ setInterimMessage,
718
746
  sendStructured: (structured, context) => {
719
747
  appendStructuredUserResponse(structured, context);
720
748
  void sendToApplication({
package/lib/index.umd.js CHANGED
@@ -1,15 +1,15 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).nlx={})}(this,(function(e){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||"undefined"!=typeof global&&global||{},r="URLSearchParams"in n,o="Symbol"in n&&"iterator"in Symbol,s="FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(e){return!1}}(),i="FormData"in n,a="ArrayBuffer"in n;if(a)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(e){return e&&c.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function d(e){return"string"!=typeof e&&(e=String(e)),e}function p(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return o&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function y(e){return new Promise((function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function m(e){var t=new FileReader,n=y(t);return t.readAsArrayBuffer(e),n}function g(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:s&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:i&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():a&&s&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=g(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=g(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var e=f(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(s)return this.blob().then(m);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,n,r,o,s=f(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=y(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),o=r?r[1]:"utf-8",t.readAsText(e,o),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},i&&(this.formData=function(){return this.text().then(w)}),this.json=function(){return this.text().then(JSON.parse)},this}h.prototype.append=function(e,t){e=l(e),t=d(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},h.prototype.delete=function(e){delete this.map[l(e)]},h.prototype.get=function(e){return e=l(e),this.has(e)?this.map[e]:null},h.prototype.has=function(e){return this.map.hasOwnProperty(l(e))},h.prototype.set=function(e,t){this.map[l(e)]=d(t)},h.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},h.prototype.keys=function(){var e=[];return this.forEach((function(t,n){e.push(n)})),p(e)},h.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),p(e)},h.prototype.entries=function(){var e=[];return this.forEach((function(t,n){e.push([n,t])})),p(e)},o&&(h.prototype[Symbol.iterator]=h.prototype.entries);var v=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function _(e,t){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,o,s=(t=t||{}).body;if(e instanceof _){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new h(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,s||null==e._bodyInit||(s=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new h(t.headers)),this.method=(r=t.method||this.method||"GET",o=r.toUpperCase(),v.indexOf(o)>-1?o:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&s)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(s),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var i=/([?&])_=[^&]*/;if(i.test(this.url))this.url=this.url.replace(i,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),o=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(o))}})),t}function T(e,t){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})},b.call(_.prototype),b.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},T.error=function(){var e=new T(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var x=[301,302,303,307,308];T.redirect=function(e,t){if(-1===x.indexOf(t))throw new RangeError("Invalid status code");return new T(null,{status:t,headers:{location:e}})};var E=n.DOMException;try{new E}catch(e){E=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},E.prototype=Object.create(Error.prototype),E.prototype.constructor=E}function O(e,t){return new Promise((function(r,o){var i=new _(e,t);if(i.signal&&i.signal.aborted)return o(new E("Aborted","AbortError"));var c=new XMLHttpRequest;function u(){c.abort()}if(c.onload=function(){var e,t,n={statusText:c.statusText,headers:(e=c.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e})).forEach((function(e){var n=e.split(":"),r=n.shift().trim();if(r){var o=n.join(":").trim();try{t.append(r,o)}catch(e){console.warn("Response "+e.message)}}})),t)};0===i.url.indexOf("file://")&&(c.status<200||c.status>599)?n.status=200:n.status=c.status,n.url="responseURL"in c?c.responseURL:n.headers.get("X-Request-URL");var o="response"in c?c.response:c.responseText;setTimeout((function(){r(new T(o,n))}),0)},c.onerror=function(){setTimeout((function(){o(new TypeError("Network request failed"))}),0)},c.ontimeout=function(){setTimeout((function(){o(new TypeError("Network request timed out"))}),0)},c.onabort=function(){setTimeout((function(){o(new E("Aborted","AbortError"))}),0)},c.open(i.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(i.url),!0),"include"===i.credentials?c.withCredentials=!0:"omit"===i.credentials&&(c.withCredentials=!1),"responseType"in c&&(s?c.responseType="blob":a&&(c.responseType="arraybuffer")),t&&"object"==typeof t.headers&&!(t.headers instanceof h||n.Headers&&t.headers instanceof n.Headers)){var p=[];Object.getOwnPropertyNames(t.headers).forEach((function(e){p.push(l(e)),c.setRequestHeader(e,d(t.headers[e]))})),i.headers.forEach((function(e,t){-1===p.indexOf(t)&&c.setRequestHeader(t,e)}))}else i.headers.forEach((function(e,t){c.setRequestHeader(t,e)}));i.signal&&(i.signal.addEventListener("abort",u),c.onreadystatechange=function(){4===c.readyState&&i.signal.removeEventListener("abort",u)}),c.send(void 0===i._bodyInit?null:i._bodyInit)}))}O.polyfill=!0,n.fetch||(n.fetch=O,n.Headers=h,n.Request=_,n.Response=T);var I=t(self.fetch.bind(self));function A(e){return null!=e&&"object"==typeof e&&!0===e["@@functional/placeholder"]}function C(e){return function t(n){return 0===arguments.length||A(n)?t:e.apply(this,arguments)}}function P(e){return function t(n,r){switch(arguments.length){case 0:return t;case 1:return A(n)?t:C((function(t){return e(n,t)}));default:return A(n)&&A(r)?t:A(n)?C((function(t){return e(t,r)})):A(r)?C((function(t){return e(n,t)})):e(n,r)}}}function S(e){return function t(n,r,o){switch(arguments.length){case 0:return t;case 1:return A(n)?t:P((function(t,r){return e(n,t,r)}));case 2:return A(n)&&A(r)?t:A(n)?P((function(t,n){return e(t,r,n)})):A(r)?P((function(t,r){return e(n,t,r)})):C((function(t){return e(n,r,t)}));default:return A(n)&&A(r)&&A(o)?t:A(n)&&A(r)?P((function(t,n){return e(t,n,o)})):A(n)&&A(o)?P((function(t,n){return e(t,r,n)})):A(r)&&A(o)?P((function(t,r){return e(n,t,r)})):A(n)?C((function(t){return e(t,r,o)})):A(r)?C((function(t){return e(n,t,o)})):A(o)?C((function(t){return e(n,r,t)})):e(n,r,o)}}}var U=S((function(e,t,n){var r=n.length;if(e>=r||e<-r)return n;var o=(r+e)%r,s=function(e,t){var n;t=t||[];var r=(e=e||[]).length,o=t.length,s=[];for(n=0;n<r;)s[s.length]=e[n],n+=1;for(n=0;n<o;)s[s.length]=t[n],n+=1;return s}(n);return s[o]=t(n[o]),s}));function R(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}function j(e,t,n){for(var r=0,o=n.length;r<o;){if(e(t,n[r]))return!0;r+=1}return!1}function L(e,t){return Object.prototype.hasOwnProperty.call(t,e)}var D="function"==typeof Object.is?Object.is:function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t},k=Object.prototype.toString,N=function(){return"[object Arguments]"===k.call(arguments)?function(e){return"[object Arguments]"===k.call(e)}:function(e){return L("callee",e)}}(),B=!{toString:null}.propertyIsEnumerable("toString"),K=["constructor","valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],q=function(){return arguments.propertyIsEnumerable("length")}(),F=function(e,t){for(var n=0;n<e.length;){if(e[n]===t)return!0;n+=1}return!1},$="function"!=typeof Object.keys||q?C((function(e){if(Object(e)!==e)return[];var t,n,r=[],o=q&&N(e);for(t in e)!L(t,e)||o&&"length"===t||(r[r.length]=t);if(B)for(n=K.length-1;n>=0;)L(t=K[n],e)&&!F(r,t)&&(r[r.length]=t),n-=1;return r})):C((function(e){return Object(e)!==e?[]:Object.keys(e)})),H=C((function(e){return null===e?"Null":void 0===e?"Undefined":Object.prototype.toString.call(e).slice(8,-1)}));function W(e,t,n,r){var o=R(e);function s(e,t){return M(e,t,n.slice(),r.slice())}return!j((function(e,t){return!j(s,t,e)}),R(t),o)}function M(e,t,n,r){if(D(e,t))return!0;var o,s,i=H(e);if(i!==H(t))return!1;if("function"==typeof e["fantasy-land/equals"]||"function"==typeof t["fantasy-land/equals"])return"function"==typeof e["fantasy-land/equals"]&&e["fantasy-land/equals"](t)&&"function"==typeof t["fantasy-land/equals"]&&t["fantasy-land/equals"](e);if("function"==typeof e.equals||"function"==typeof t.equals)return"function"==typeof e.equals&&e.equals(t)&&"function"==typeof t.equals&&t.equals(e);switch(i){case"Arguments":case"Array":case"Object":if("function"==typeof e.constructor&&"Promise"===(o=e.constructor,null==(s=String(o).match(/^function (\w*)/))?"":s[1]))return e===t;break;case"Boolean":case"Number":case"String":if(typeof e!=typeof t||!D(e.valueOf(),t.valueOf()))return!1;break;case"Date":if(!D(e.valueOf(),t.valueOf()))return!1;break;case"Error":return e.name===t.name&&e.message===t.message;case"RegExp":if(e.source!==t.source||e.global!==t.global||e.ignoreCase!==t.ignoreCase||e.multiline!==t.multiline||e.sticky!==t.sticky||e.unicode!==t.unicode)return!1}for(var a=n.length-1;a>=0;){if(n[a]===e)return r[a]===t;a-=1}switch(i){case"Map":return e.size===t.size&&W(e.entries(),t.entries(),n.concat([e]),r.concat([t]));case"Set":return e.size===t.size&&W(e.values(),t.values(),n.concat([e]),r.concat([t]));case"Arguments":case"Array":case"Object":case"Boolean":case"Number":case"String":case"Date":case"Error":case"RegExp":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"ArrayBuffer":break;default:return!1}var c=$(e);if(c.length!==$(t).length)return!1;var u=n.concat([e]),l=r.concat([t]);for(a=c.length-1;a>=0;){var d=c[a];if(!L(d,t)||!M(t[d],e[d],u,l))return!1;a-=1}return!0}var G=P((function(e,t){return M(e,t,[],[])})),V=function(e,t){return V=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},V(e,t)};
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).nlxai=e.nlxai||{},e.nlxai.core={}))}(this,function(e){"use strict";function t(e){return null!=e&&"object"==typeof e&&!0===e["@@functional/placeholder"]}function n(e){return function n(o){return 0===arguments.length||t(o)?n:e.apply(this,arguments)}}function o(e){return function o(r,s){switch(arguments.length){case 0:return o;case 1:return t(r)?o:n(function(t){return e(r,t)});default:return t(r)&&t(s)?o:t(r)?n(function(t){return e(t,s)}):t(s)?n(function(t){return e(r,t)}):e(r,s)}}}function r(e){return function r(s,i,a){switch(arguments.length){case 0:return r;case 1:return t(s)?r:o(function(t,n){return e(s,t,n)});case 2:return t(s)&&t(i)?r:t(s)?o(function(t,n){return e(t,i,n)}):t(i)?o(function(t,n){return e(s,t,n)}):n(function(t){return e(s,i,t)});default:return t(s)&&t(i)&&t(a)?r:t(s)&&t(i)?o(function(t,n){return e(t,n,a)}):t(s)&&t(a)?o(function(t,n){return e(t,i,n)}):t(i)&&t(a)?o(function(t,n){return e(s,t,n)}):t(s)?n(function(t){return e(t,i,a)}):t(i)?n(function(t){return e(s,t,a)}):t(a)?n(function(t){return e(s,i,t)}):e(s,i,a)}}}var s=r(function(e,t,n){var o=n.length;if(e>=o||e<-o)return n;var r=(o+e)%o,s=function(e,t){var n;t=t||[];var o=(e=e||[]).length,r=t.length,s=[];for(n=0;n<o;)s[s.length]=e[n],n+=1;for(n=0;n<r;)s[s.length]=t[n],n+=1;return s}(n);return s[r]=t(n[r]),s});function i(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}function a(e,t,n){for(var o=0,r=n.length;o<r;){if(e(t,n[o]))return!0;o+=1}return!1}function c(e,t){return Object.prototype.hasOwnProperty.call(t,e)}var l="function"==typeof Object.is?Object.is:function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t},u=Object.prototype.toString,p=function(){return"[object Arguments]"===u.call(arguments)?function(e){return"[object Arguments]"===u.call(e)}:function(e){return c("callee",e)}}(),d=!{toString:null}.propertyIsEnumerable("toString"),h=["constructor","valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],f=function(){return arguments.propertyIsEnumerable("length")}(),y=function(e,t){for(var n=0;n<e.length;){if(e[n]===t)return!0;n+=1}return!1},g="function"!=typeof Object.keys||f?n(function(e){if(Object(e)!==e)return[];var t,n,o=[],r=f&&p(e);for(t in e)!c(t,e)||r&&"length"===t||(o[o.length]=t);if(d)for(n=h.length-1;n>=0;)c(t=h[n],e)&&!y(o,t)&&(o[o.length]=t),n-=1;return o}):n(function(e){return Object(e)!==e?[]:Object.keys(e)}),m=n(function(e){return null===e?"Null":void 0===e?"Undefined":Object.prototype.toString.call(e).slice(8,-1)});function v(e,t,n,o){var r=i(e);function s(e,t){return _(e,t,n.slice(),o.slice())}return!a(function(e,t){return!a(s,t,e)},i(t),r)}function _(e,t,n,o){if(l(e,t))return!0;var r,s,i=m(e);if(i!==m(t))return!1;if("function"==typeof e["fantasy-land/equals"]||"function"==typeof t["fantasy-land/equals"])return"function"==typeof e["fantasy-land/equals"]&&e["fantasy-land/equals"](t)&&"function"==typeof t["fantasy-land/equals"]&&t["fantasy-land/equals"](e);if("function"==typeof e.equals||"function"==typeof t.equals)return"function"==typeof e.equals&&e.equals(t)&&"function"==typeof t.equals&&t.equals(e);switch(i){case"Arguments":case"Array":case"Object":if("function"==typeof e.constructor&&"Promise"===(r=e.constructor,null==(s=String(r).match(/^function (\w*)/))?"":s[1]))return e===t;break;case"Boolean":case"Number":case"String":if(typeof e!=typeof t||!l(e.valueOf(),t.valueOf()))return!1;break;case"Date":if(!l(e.valueOf(),t.valueOf()))return!1;break;case"Error":return e.name===t.name&&e.message===t.message;case"RegExp":if(e.source!==t.source||e.global!==t.global||e.ignoreCase!==t.ignoreCase||e.multiline!==t.multiline||e.sticky!==t.sticky||e.unicode!==t.unicode)return!1}for(var a=n.length-1;a>=0;){if(n[a]===e)return o[a]===t;a-=1}switch(i){case"Map":return e.size===t.size&&v(e.entries(),t.entries(),n.concat([e]),o.concat([t]));case"Set":return e.size===t.size&&v(e.values(),t.values(),n.concat([e]),o.concat([t]));case"Arguments":case"Array":case"Object":case"Boolean":case"Number":case"String":case"Date":case"Error":case"RegExp":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"ArrayBuffer":break;default:return!1}var u=g(e);if(u.length!==g(t).length)return!1;var p=n.concat([e]),d=o.concat([t]);for(a=u.length-1;a>=0;){var h=u[a];if(!c(h,t)||!_(t[h],e[h],p,d))return!1;a-=1}return!0}var b=o(function(e,t){return _(e,t,[],[])}),w=function(e,t){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},w(e,t)};
2
2
  /*! *****************************************************************************
3
- Copyright (c) Microsoft Corporation. All rights reserved.
4
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
- this file except in compliance with the License. You may obtain a copy of the
6
- License at http://www.apache.org/licenses/LICENSE-2.0
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
+ this file except in compliance with the License. You may obtain a copy of the
6
+ License at http://www.apache.org/licenses/LICENSE-2.0
7
7
 
8
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
9
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
10
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
11
- MERCHANTABLITY OR NON-INFRINGEMENT.
8
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
9
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
10
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
11
+ MERCHANTABLITY OR NON-INFRINGEMENT.
12
12
 
13
- See the Apache Version 2.0 License for specific language governing permissions
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.6";const ue=ce,le=console;var de,pe;e.Protocol=void 0,(de=e.Protocol||(e.Protocol={})).Http="http",de.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=t=>{const n=t.applicationUrl??"",r=t.apiKey??t.headers?.["nlx-api-key"]??"",o=t.protocol??(ve(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(ve(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:o,channelKey:i,deploymentKey:a,host:e,apiKey:r}: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?e.Protocol.Http:o,channelKey:a.pathname.groups.channelKey,deploymentKey:a.pathname.groups.deploymentKey,host:i,apiKey:r}:null},ve=e=>0===e.indexOf("wss://"),_e=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 we=/^[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=be(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?(t=>`${t.protocol===e.Protocol.Http?"http":"https"}://${t.host}/c/${t.deploymentKey}/${t.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 _e({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?.flowId??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!=be(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(!we.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}));
13
+ See the Apache Version 2.0 License for specific language governing permissions
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});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nlxai/core",
3
- "version": "1.2.6",
3
+ "version": "1.2.7-alpha.2",
4
4
  "description": "Low-level SDK for building NLX experiences",
5
5
  "type": "module",
6
6
  "main": "lib/index.cjs",
@@ -16,8 +16,8 @@
16
16
  },
17
17
  "scripts": {
18
18
  "build": "rm -rf lib && rollup -c --configPlugin typescript --configImportAttributesKey with",
19
- "lint:check": "eslint src/ --ext .ts,.tsx,.js,.jsx --max-warnings 0",
20
- "lint": "eslint src/ --ext .ts,.tsx,.js,.jsx --fix",
19
+ "lint:check": "eslint src/",
20
+ "lint": "eslint src/ --fix",
21
21
  "prepublish": "npm run build",
22
22
  "test": "typedoc --emit none",
23
23
  "tsc": "tsc",
@@ -36,25 +36,21 @@
36
36
  "@rollup/plugin-replace": "^5.0.5",
37
37
  "@rollup/plugin-terser": "^0.4.4",
38
38
  "@rollup/plugin-typescript": "^11.1.6",
39
- "@types/isomorphic-fetch": "^0.0.39",
40
39
  "@types/node": "^24.10.1",
41
40
  "@types/ramda": "0.31.1",
42
- "@types/uuid": "^9.0.7",
43
41
  "prettier": "^3.1.0",
44
42
  "rollup": "^4.59.0",
45
- "rollup-plugin-node-polyfills": "^0.2.1",
46
43
  "typedoc": "^0.28.14",
47
44
  "typedoc-plugin-markdown": "^4.9.0",
48
45
  "typescript": "^5.5.4"
49
46
  },
50
47
  "dependencies": {
51
- "isomorphic-fetch": "^3.0.0",
52
48
  "ramda": "^0.32.0",
53
49
  "reconnecting-websocket": "^4.4.0",
54
- "uuid": "^9.0.1"
50
+ "uuid": "^14.0.0"
55
51
  },
56
52
  "publishConfig": {
57
53
  "access": "public"
58
54
  },
59
- "gitHead": "fb9a0b00ca2184fb69ffd1e11e8f55d30fe1d85e"
55
+ "gitHead": "28deac5208ff64f99a3d038050172c1ac9a78630"
60
56
  }
package/rollup.config.ts CHANGED
@@ -3,7 +3,7 @@ import pkg from "./package.json" with { type: "json" };
3
3
 
4
4
  export default rollupConfig({
5
5
  pkg: pkg,
6
- name: "nlx",
7
- externalDeps: ["isomorphic-fetch", "reconnecting-websocket", "uuid", "ramda"],
6
+ name: "nlxai.core",
7
+ externalDeps: ["reconnecting-websocket", "uuid", "ramda"],
8
8
  input: "src/index.ts",
9
9
  });
package/tsdoc.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
3
- "extends": ["typedoc/tsdoc.json"],
4
3
  "noStandardTags": false,
5
- "tagDefinitions": []
4
+ "tagDefinitions": [
5
+ {
6
+ "tagName": "@category",
7
+ "syntaxKind": "block",
8
+ "allowMultiple": true
9
+ },
10
+ {
11
+ "tagName": "@hidden",
12
+ "syntaxKind": "modifier"
13
+ },
14
+ {
15
+ "tagName": "@inline",
16
+ "syntaxKind": "modifier"
17
+ },
18
+ {
19
+ "tagName": "@event",
20
+ "syntaxKind": "modifier"
21
+ }
22
+ ]
6
23
  }
package/.eslintrc.cjs DELETED
@@ -1,5 +0,0 @@
1
- /** @type {import('eslint').Linter.Config } */
2
- module.exports = {
3
- root: true,
4
- extends: ["@nlxai/eslint-config", "@nlxai/eslint-config/documentation"],
5
- };