@nlxai/core 1.2.3-alpha.2 → 1.2.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.d.ts CHANGED
@@ -2,6 +2,208 @@
2
2
  * Package version
3
3
  */
4
4
  export declare const version: string;
5
+ /**
6
+ * The configuration necessary to create a conversation.
7
+ */
8
+ export interface Config {
9
+ /**
10
+ * The URL at which your conversational application is running.
11
+ * Fetch this from the application's API channel tab.
12
+ */
13
+ applicationUrl?: string;
14
+ /**
15
+ * Headers to forward to the NLX API.
16
+ */
17
+ headers: Record<string, string> & {
18
+ /**
19
+ * The `nlx-api-key` is required. Fetch this from the application's API channel tab.
20
+ */
21
+ "nlx-api-key": string;
22
+ };
23
+ /**
24
+ * Set `conversationId` to continue an existing conversation. If not set, a new conversation will be started (and a new conversationId will be generated internally).
25
+ */
26
+ conversationId?: string;
27
+ /**
28
+ * Setting the `userID` allows it to be searchable in application history, as well as usable via `{System.userId}` in the flow.
29
+ */
30
+ userId?: string;
31
+ /**
32
+ * When `responses` is set, initialize the chatHandler with historical messages. This is useful when restoring a previous conversation, that perhaps started on a different page.
33
+ */
34
+ responses?: Response[];
35
+ /**
36
+ * When set, this overrides the default failure message ("We encountered an issue. Please try again soon.").
37
+ */
38
+ failureMessage?: string;
39
+ /**
40
+ * The language code to use for the application. In the browser this can be fetched with `navigator.language`.
41
+ * If you don't have translations, hard-code this to the language code you support.
42
+ */
43
+ languageCode: LanguageCode;
44
+ /**
45
+ * @hidden @internal
46
+ * this should only be used for NLX internal testing.
47
+ */
48
+ environment?: Environment;
49
+ /**
50
+ * Specifies whether the conversation is using bidirectional Voice+ (if so, an additional command socket will be opened).
51
+ */
52
+ bidirectional?: boolean;
53
+ /**
54
+ * Experimental settings
55
+ * @internal
56
+ */
57
+ experimental?: {
58
+ /**
59
+ * Simulate alternative channel types
60
+ */
61
+ channelType?: string;
62
+ /**
63
+ * Prevent the `languageCode` parameter to be appended to the application URL - used in special deployment environments such as the sandbox chat inside Dialog Studio
64
+ */
65
+ completeApplicationUrl?: boolean;
66
+ };
67
+ }
68
+ /**
69
+ * A bundle of functions to interact with a conversation, created by {@link createConversation}.
70
+ */
71
+ export interface ConversationHandler {
72
+ /**
73
+ * Send user's message
74
+ * @param text - the user's message
75
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the flow.
76
+ */
77
+ sendText: (text: string, context?: Context) => void;
78
+ /**
79
+ * Send [slots](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/slots-custom#slot-settings) to the application.
80
+ * @param slots - The slots to populate
81
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the flow.
82
+ */
83
+ sendSlots: (slots: SlotsRecordOrArray, context?: Context) => void;
84
+ /**
85
+ * Respond to [a choice](https://docs.studio.nlx.ai/intentflows/documentation-flows/flows-build-mode/nodes#user-choice) from the application.
86
+ * @param choiceId - The `choiceId` is in the {@link ApplicationResponse}'s `.payload.messages[].choices[].choiceId` fields
87
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the flow.
88
+ * @param metadata - links the choice to the specific message and node in the conversation.
89
+ */
90
+ sendChoice: (choiceId: string, context?: Context, metadata?: ChoiceRequestMetadata) => void;
91
+ /**
92
+ * Trigger the welcome flow. This should be done when the user starts interacting with the conversation.
93
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the flow.
94
+ */
95
+ sendWelcomeFlow: (context?: Context) => void;
96
+ /**
97
+ * Trigger the welcome [intent](https://docs.studio.nlx.ai/intents/introduction-to-intents). This should be done when the user starts interacting with the conversation.
98
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the intent.
99
+ * @deprecated use `sendWelcomeFlow` instead
100
+ * @hidden
101
+ */
102
+ sendWelcomeIntent: (context?: Context) => void;
103
+ /**
104
+ * Trigger a specific flow.
105
+ * @param flowId - the flow to trigger. The id is the name under the application's _Intents_.
106
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the intent.
107
+ */
108
+ sendFlow: (flowId: string, context?: Context) => void;
109
+ /**
110
+ * Trigger a specific [intent](https://docs.studio.nlx.ai/intents/introduction-to-intents).
111
+ * @param intentId - the intent to trigger. The id is the name under the application's _Intents_.
112
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the intent.
113
+ * @deprecated use `sendFlow` instead
114
+ * @hidden
115
+ */
116
+ sendIntent: (intentId: string, context?: Context) => void;
117
+ /**
118
+ * Send context without sending a message
119
+ * @param context - [Context](https://docs.nlx.ai/platform/nlx-platform-guide/build-with-nlx/flows/context-variables#what-are-context-variables) for usage later in the intent.
120
+ */
121
+ sendContext: (context: Context) => Promise<void>;
122
+ /**
123
+ * Obtain Voice credentials to run the experience in voice.
124
+ * @internal
125
+ * @returns Voice credentials in promise form
126
+ */
127
+ getVoiceCredentials: (context?: Context, options?: {
128
+ autoTriggerWelcomeFlow?: boolean;
129
+ }) => Promise<VoiceCredentials>;
130
+ /**
131
+ * Append messages manually to the transcript. This is an advanced feature that allows routing and aggregation of different chat message
132
+ * sources.
133
+ * @param response - the response with optional timestamps.
134
+ */
135
+ appendMessageToTranscript: (response: (Omit<ApplicationResponse, "receivedAt"> & {
136
+ receivedAt?: Time;
137
+ }) | (Omit<UserResponse, "receivedAt"> & {
138
+ receivedAt?: Time;
139
+ }) | (Omit<FailureMessage, "receivedAt"> & {
140
+ receivedAt?: Time;
141
+ })) => void;
142
+ /**
143
+ * Send a combination of choice, slots, and intent in one request.
144
+ * @param request -
145
+ * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
146
+ */
147
+ sendStructured: (request: StructuredRequest, context?: Context) => void;
148
+ /**
149
+ * Subscribe a callback to the conversation. On subscribe, the subscriber will receive all of the Responses that the conversation has already received.
150
+ * @param subscriber - The callback to subscribe
151
+ * @returns A function to unsubscribe the callback.
152
+ */
153
+ subscribe: (subscriber: Subscriber) => () => void;
154
+ /**
155
+ * Unsubscribe a callback from the conversation.
156
+ * @param subscriber - The callback to unsubscribe
157
+ */
158
+ unsubscribe: (subscriber: Subscriber) => void;
159
+ /**
160
+ * Unsubscribe all callback from the conversation.
161
+ */
162
+ unsubscribeAll: () => void;
163
+ /**
164
+ * Get the current conversation ID if it's set, or undefined if there is no conversation.
165
+ */
166
+ currentConversationId: () => string | undefined;
167
+ /**
168
+ * Get the current language code
169
+ */
170
+ currentLanguageCode: () => LanguageCode;
171
+ /**
172
+ * Set the language code
173
+ */
174
+ setLanguageCode: (languageCode: LanguageCode) => void;
175
+ /**
176
+ * Forces a new conversation. If `clearResponses` is set to true, will also clear historical responses passed to subscribers.
177
+ * Retains all existing subscribers.
178
+ */
179
+ reset: (options?: {
180
+ /**
181
+ * If set to true, will clear historical responses passed to subscribers.
182
+ */
183
+ clearResponses?: boolean;
184
+ }) => void;
185
+ /**
186
+ * Removes all subscribers and, if using websockets, closes the connection.
187
+ */
188
+ destroy: () => void;
189
+ /**
190
+ * Optional {@link RequestOverride} function used to bypass the application request and handle them in a custom fashion
191
+ */
192
+ setRequestOverride: (override: RequestOverride | undefined) => void;
193
+ /**
194
+ * Add a listener to one of the handler's custom events
195
+ */
196
+ addEventListener: (event: ConversationHandlerEvent, handler: EventHandlers[ConversationHandlerEvent]) => void;
197
+ /**
198
+ * Remove a listener to one of the handler's custom events
199
+ */
200
+ removeEventListener: (event: ConversationHandlerEvent, handler: EventHandlers[ConversationHandlerEvent]) => void;
201
+ /**
202
+ * Send voicePlus message
203
+ * @internal
204
+ */
205
+ sendVoicePlusContext: (context: VoicePlusContext) => void;
206
+ }
5
207
  /**
6
208
  * [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
7
209
  */
@@ -343,67 +545,6 @@ export type Time = number;
343
545
  * @hidden
344
546
  */
345
547
  export type Environment = "production" | "development";
346
- /**
347
- * The configuration to create a conversation.
348
- */
349
- export interface Config {
350
- /**
351
- * Fetch this from the application's Deployment page.
352
- */
353
- applicationUrl?: string;
354
- /**
355
- * Headers to forward to the NLX API.
356
- */
357
- headers: Record<string, string> & {
358
- /**
359
- * The `nlx-api-key` is required. Fetch this from the application's Deployment page.
360
- */
361
- "nlx-api-key": string;
362
- };
363
- /**
364
- * Set `conversationId` to continue an existing conversation. If not set, a new conversation will be started.
365
- */
366
- conversationId?: string;
367
- /**
368
- * Setting the `userID` allows it to be searchable in application history, as well as usable via `{System.userId}` in the intent.
369
- */
370
- userId?: string;
371
- /**
372
- * When `responses` is set, initialize the chatHandler with historical messages.
373
- */
374
- responses?: Response[];
375
- /**
376
- * When set, this overrides the default failure message ("We encountered an issue. Please try again soon.").
377
- */
378
- failureMessage?: string;
379
- /**
380
- * The language code to use for the application. In the browser this can be fetched with `navigator.language`.
381
- * If you don't have translations, hard-code this to the language code you support.
382
- */
383
- languageCode: LanguageCode;
384
- /**
385
- * @hidden
386
- * this should only be used for NLX internal testing.
387
- */
388
- environment?: Environment;
389
- /**
390
- * Specifies whether the conversation is bidirectional
391
- */
392
- bidirectional?: boolean;
393
- /**
394
- * Experimental settings
395
- */
396
- experimental?: {
397
- /**
398
- * Simulate alternative channel types
399
- */
400
- channelType?: string;
401
- /**
402
- * Prevent the `languageCode` parameter to be appended to the application URL - used in special deployment environments such as the sandbox chat inside Dialog Studio
403
- */
404
- completeApplicationUrl?: boolean;
405
- };
406
- }
407
548
  /**
408
549
  * The body of `sendStructured`
409
550
  * Includes a combination of choice, slots, and intent in one request.
@@ -566,6 +707,7 @@ export interface VoicePlusMessage {
566
707
  }
567
708
  /**
568
709
  * Handler events
710
+ * @event voicePlusCommand
569
711
  */
570
712
  export type ConversationHandlerEvent = "voicePlusCommand";
571
713
  /**
@@ -577,145 +719,35 @@ export interface EventHandlers {
577
719
  */
578
720
  voicePlusCommand: (payload: any) => void;
579
721
  }
580
- /**
581
- * A bundle of functions to interact with a conversation, created by {@link createConversation}.
582
- */
583
- export interface ConversationHandler {
584
- /**
585
- * Send user's message
586
- * @param text - the user's message
587
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
588
- */
589
- sendText: (text: string, context?: Context) => void;
590
- /**
591
- * Send [slots](https://docs.studio.nlx.ai/workspacesettings/introduction-to-settings) to the application.
592
- * @param slots - The slots to populate
593
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
594
- */
595
- sendSlots: (slots: SlotsRecordOrArray, context?: Context) => void;
596
- /**
597
- * Respond to [a choice](https://docs.studio.nlx.ai/intentflows/documentation-flows/flows-build-mode/nodes#user-choice) from the application.
598
- * @param choidId - The `choiceId` is in the {@link ApplicationResponse}'s `.payload.messages[].choices[].choiceId` fields
599
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
600
- * @param metadata - links the choice to the specific message and node in the conversation.
601
- */
602
- sendChoice: (choiceId: string, context?: Context, metadata?: ChoiceRequestMetadata) => void;
603
- /**
604
- * Trigger the welcome flow. This should be done when the user starts interacting with the chat.
605
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
606
- */
607
- sendWelcomeFlow: (context?: Context) => void;
608
- /**
609
- * Trigger the welcome [intent](https://docs.studio.nlx.ai/intents/introduction-to-intents). This should be done when the user starts interacting with the chat.
610
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
611
- * @deprecated use `sendWelcomeFlow` instead
612
- */
613
- sendWelcomeIntent: (context?: Context) => void;
614
- /**
615
- * Trigger a specific flow.
616
- * @param flowId - the flow to trigger. The id is the name under the application's _Intents_.
617
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
618
- */
619
- sendFlow: (flowId: string, context?: Context) => void;
620
- /**
621
- * Trigger a specific [intent](https://docs.studio.nlx.ai/intents/introduction-to-intents).
622
- * @param intentId - the intent to trigger. The id is the name under the application's _Intents_.
623
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
624
- * @deprecated use `sendFlow` instead
625
- */
626
- sendIntent: (intentId: string, context?: Context) => void;
627
- /**
628
- * Send context without sending a message
629
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
630
- */
631
- sendContext: (context: Context) => Promise<void>;
632
- /**
633
- * Obtain Voice credentials to run the experience in voice.
634
- * @internal
635
- * @returns Voice credentials in promise form
636
- */
637
- getVoiceCredentials: (context?: Context, options?: {
638
- autoTriggerWelcomeFlow?: boolean;
639
- }) => Promise<VoiceCredentials>;
640
- /**
641
- * Append messages manually to the transcript. This is an advanced feature that allows routing and aggregation of different chat message
642
- * sources.
643
- * @param response - the response with optional timestamps.
644
- */
645
- appendMessageToTranscript: (response: (Omit<ApplicationResponse, "receivedAt"> & {
646
- receivedAt?: Time;
647
- }) | (Omit<UserResponse, "receivedAt"> & {
648
- receivedAt?: Time;
649
- }) | (Omit<FailureMessage, "receivedAt"> & {
650
- receivedAt?: Time;
651
- })) => void;
652
- /**
653
- * Send a combination of choice, slots, and intent in one request.
654
- * @param request -
655
- * @param context - [Context](https://docs.studio.nlx.ai/workspacesettings/documentation-settings/settings-context-attributes) for usage later in the intent.
656
- */
657
- sendStructured: (request: StructuredRequest, context?: Context) => void;
658
- /**
659
- * Subscribe a callback to the conversation. On subscribe, the subscriber will receive all of the Responses that the conversation has already received.
660
- * @param subscriber - The callback to subscribe
661
- */
662
- subscribe: (subscriber: Subscriber) => () => void;
663
- /**
664
- * Unsubscribe a callback from the conversation.
665
- * @param subscriber - The callback to unsubscribe
666
- */
667
- unsubscribe: (subscriber: Subscriber) => void;
668
- /**
669
- * Unsubscribe all callback from the conversation.
670
- */
671
- unsubscribeAll: () => void;
672
- /**
673
- * Get the current conversation ID if it's set, or undefined if there is no conversation.
674
- */
675
- currentConversationId: () => string | undefined;
676
- /**
677
- * Get the current language code
678
- */
679
- currentLanguageCode: () => LanguageCode;
680
- /**
681
- * Set the language code
682
- */
683
- setLanguageCode: (languageCode: LanguageCode) => void;
684
- /**
685
- * Forces a new conversation. If `clearResponses` is set to true, will also clear historical responses passed to subscribers.
686
- * Retains all existing subscribers.
687
- */
688
- reset: (options?: {
689
- /**
690
- * If set to true, will clear historical responses passed to subscribers.
691
- */
692
- clearResponses?: boolean;
693
- }) => void;
694
- /**
695
- * Removes all subscribers and, if using websockets, closes the connection.
696
- */
697
- destroy: () => void;
698
- /**
699
- * Optional {@link RequestOverride} function used to bypass the application request and handle them in a custom fashion
700
- */
701
- setRequestOverride: (override: RequestOverride | undefined) => void;
702
- /**
703
- * Add a listener to one of the handler's custom events
704
- */
705
- addEventListener: (event: ConversationHandlerEvent, handler: EventHandlers[ConversationHandlerEvent]) => void;
706
- /**
707
- * Remove a listener to one of the handler's custom events
708
- */
709
- removeEventListener: (event: ConversationHandlerEvent, handler: EventHandlers[ConversationHandlerEvent]) => void;
710
- /**
711
- * Send voicePlus message
712
- */
713
- sendVoicePlusContext: (context: VoicePlusContext) => void;
714
- }
715
722
  /**
716
723
  * The callback function for listening to all responses.
717
724
  */
718
725
  export type Subscriber = (response: Response[], newResponse?: Response) => void;
726
+ /**
727
+ * Call this to create a conversation handler.
728
+ * @param configuration - The necessary configuration to create the conversation.
729
+ * @returns The {@link ConversationHandler} is a bundle of functions to interact with the conversation.
730
+ * @example
731
+ * ```typescript
732
+ * import { createConversation } from "@nlx/core";
733
+ *
734
+ * const conversation = createConversation({
735
+ * applicationUrl: "https://apps.nlx.ai/c/cfab3-243ad-232dc",
736
+ * headers: {
737
+ * "nlx-api-key": "4393029032-dwsd",
738
+ * },
739
+ * userId: "abcd-1234",
740
+ * languageCode: "en-US",
741
+ * });
742
+ * ```
743
+ */
744
+ export declare function createConversation(configuration: Config): ConversationHandler;
745
+ /**
746
+ * Check whether a configuration is valid.
747
+ * @param configuration - Conversation configuration
748
+ * @returns Whether the configuration is valid?
749
+ */
750
+ export declare const isConfigValid: (configuration: Config) => boolean;
719
751
  /**
720
752
  * Helper method to decide when a new {@link Config} requires creating a new {@link ConversationHandler} or whether the old `Config`'s
721
753
  * `ConversationHandler` can be used.
@@ -727,21 +759,31 @@ export type Subscriber = (response: Response[], newResponse?: Response) => void;
727
759
  */
728
760
  export declare const shouldReinitialize: (config1: Config, config2: Config) => boolean;
729
761
  /**
730
- * Check whether a configuration is value.
731
- * @param config - Chat configuration
732
- * @returns isValid - Whether the configuration is valid
733
- */
734
- export declare const isConfigValid: (config: Config) => boolean;
735
- /**
736
- * Call this to create a conversation handler.
737
- * @param config -
738
- * @returns The {@link ConversationHandler} is a bundle of functions to interact with the conversation.
739
- */
740
- export declare function createConversation(config: Config): ConversationHandler;
741
- /**
742
- * Get current expiration timestamp from the current list of reponses
743
- * @param responses - the current list of user and application responses (first argument in the subscribe callback)
744
- * @returns an expiration timestamp in Unix Epoch (`new Date().getTime()`), or `null` if this is not known (typically occurs if the application has not responded yet)
762
+ * Get current expiration timestamp from a list of responses. Can be used to determine if a conversation has timed out.
763
+ * @example
764
+ * ```typescript
765
+ * import { useState } from "react";
766
+ * import { getCurrentExpirationTimestamp } from "@nlxai/core";
767
+ *
768
+ * const [isTimedOut, setIsTimedOut] = useState(false);
769
+ *
770
+ * conversation.subscribe((responses) => {
771
+ * const expirationTimestamp = getCurrentExpirationTimestamp(responses);
772
+ * if (expirationTimestamp != null && expirationTimestamp < new Date().getTime()) {
773
+ * setIsTimedOut(true);
774
+ * }
775
+ * });
776
+ *
777
+ * return (<div>
778
+ * {isTimedOut ? (
779
+ * <p>Your session has timed out. Please start a new conversation.</p>
780
+ * ) : (
781
+ * <p>Your session is active.</p>
782
+ * )}
783
+ * </div>
784
+ * ```
785
+ * @param responses - The current list of user and application responses (first argument in the subscribe callback)
786
+ * @returns An expiration timestamp in Unix Epoch (`new Date().getTime()`), or `null` if this is not known (typically occurs if the application has not responded yet)
745
787
  */
746
788
  export declare const getCurrentExpirationTimestamp: (responses: Response[]) => number | null;
747
789
  /**
@@ -760,10 +802,10 @@ export declare const getCurrentExpirationTimestamp: (responses: Response[]) => n
760
802
  * console.log(response);
761
803
  * });
762
804
  * ```
763
- * @typeParam T - the type of the function's params, e.g. for `sendText` it's `text: string, context?: Context`
805
+ * @typeParam Params - the type of the function's params, e.g. for `sendText` it's `text: string, context?: Context`
764
806
  * @param fn - the function to wrap (e.g. `convo.sendText`, `convo.sendChoice`, etc.)
765
807
  * @param convo - the `ConversationHandler` (from {@link createConversation})
766
808
  * @param timeout - the timeout in milliseconds
767
809
  * @returns A promise-wrapped version of the function. The function, when called, returns a promise that resolves to the Conversation's next response.
768
810
  */
769
- export declare function promisify<T>(fn: (payload: T) => void, convo: ConversationHandler, timeout?: number): (payload: T) => Promise<Response | null>;
811
+ export declare function promisify<Params>(fn: (payload: Params) => void, convo: ConversationHandler, timeout?: number): (payload: Params) => Promise<Response | null>;