@asgard-js/core 0.0.40 → 0.0.41-canary.1

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.
@@ -1,120 +0,0 @@
1
- import { EventType } from '../constants/enum';
2
- import { ConversationMessage, SseResponse } from '../types';
3
-
4
- interface IConversation {
5
- messages: Map<string, ConversationMessage> | null;
6
- }
7
-
8
- export default class Conversation implements IConversation {
9
- public messages: Map<string, ConversationMessage> | null = null;
10
-
11
- constructor({ messages }: IConversation) {
12
- this.messages = messages;
13
- }
14
-
15
- pushMessage(message: ConversationMessage): Conversation {
16
- const messages = new Map(this.messages);
17
- messages.set(message.messageId, message);
18
-
19
- return new Conversation({ messages });
20
- }
21
-
22
- onMessage(response: SseResponse<EventType>): Conversation {
23
- switch (response.eventType) {
24
- case EventType.MESSAGE_START:
25
- return this.onMessageStart(
26
- response as SseResponse<EventType.MESSAGE_START>
27
- );
28
- case EventType.MESSAGE_DELTA:
29
- return this.onMessageDelta(
30
- response as SseResponse<EventType.MESSAGE_DELTA>
31
- );
32
- case EventType.MESSAGE_COMPLETE:
33
- return this.onMessageComplete(
34
- response as SseResponse<EventType.MESSAGE_COMPLETE>
35
- );
36
- case EventType.ERROR:
37
- return this.onMessageError(response as SseResponse<EventType.ERROR>);
38
- default:
39
- return this;
40
- }
41
- }
42
-
43
- onMessageStart(response: SseResponse<EventType.MESSAGE_START>): Conversation {
44
- const message = response.fact.messageStart.message;
45
- const messages = new Map(this.messages);
46
-
47
- messages.set(message.messageId, {
48
- type: 'bot',
49
- eventType: EventType.MESSAGE_START,
50
- isTyping: true,
51
- typingText: '',
52
- messageId: message.messageId,
53
- message,
54
- time: new Date(),
55
- });
56
-
57
- return new Conversation({ messages });
58
- }
59
-
60
- onMessageDelta(response: SseResponse<EventType.MESSAGE_DELTA>): Conversation {
61
- const message = response.fact.messageDelta.message;
62
-
63
- const messages = new Map(this.messages);
64
-
65
- const currentMessage = messages.get(message.messageId);
66
-
67
- if (currentMessage?.type !== 'bot') return this;
68
-
69
- const typingText = `${currentMessage?.typingText ?? ''}${message.text}`;
70
-
71
- messages.set(message.messageId, {
72
- type: 'bot',
73
- eventType: EventType.MESSAGE_DELTA,
74
- isTyping: true,
75
- typingText,
76
- messageId: message.messageId,
77
- message,
78
- time: new Date(),
79
- });
80
-
81
- return new Conversation({ messages });
82
- }
83
-
84
- onMessageComplete(
85
- response: SseResponse<EventType.MESSAGE_COMPLETE>
86
- ): Conversation {
87
- const message = response.fact.messageComplete.message;
88
-
89
- const messages = new Map(this.messages);
90
-
91
- messages.set(message.messageId, {
92
- type: 'bot',
93
- eventType: EventType.MESSAGE_COMPLETE,
94
- isTyping: false,
95
- typingText: null,
96
- messageId: message.messageId,
97
- message,
98
- time: new Date(),
99
- });
100
-
101
- return new Conversation({ messages });
102
- }
103
-
104
- onMessageError(response: SseResponse<EventType.ERROR>): Conversation {
105
- const messageId = crypto.randomUUID();
106
- const error = response.fact.runError.error;
107
-
108
- const messages = new Map(this.messages);
109
-
110
- messages.set(messageId, {
111
- type: 'error',
112
- eventType: EventType.ERROR,
113
- messageId,
114
- error,
115
- time: new Date(),
116
- });
117
-
118
- return new Conversation({ messages });
119
- }
120
- }
@@ -1,77 +0,0 @@
1
- import { Observable } from 'rxjs';
2
- import {
3
- EventSourceMessage,
4
- fetchEventSource,
5
- } from '@microsoft/fetch-event-source';
6
- import { FetchSsePayload, SseResponse } from '../types';
7
- import { EventType } from '../constants/enum';
8
-
9
- interface CreateSseObservableOptions {
10
- endpoint: string;
11
- apiKey?: string;
12
- debugMode?: boolean;
13
- payload: FetchSsePayload;
14
- }
15
-
16
- export function createSseObservable(
17
- options: CreateSseObservableOptions
18
- ): Observable<SseResponse<EventType>> {
19
- const { endpoint, apiKey, payload, debugMode } = options;
20
-
21
- return new Observable<SseResponse<EventType>>((subscriber) => {
22
- const controller = new AbortController();
23
-
24
- const headers: Record<string, string> = {
25
- 'Content-Type': 'application/json',
26
- };
27
-
28
- if (apiKey) {
29
- headers['X-API-KEY'] = apiKey;
30
- }
31
-
32
- const searchParams = new URLSearchParams();
33
-
34
- if (debugMode) {
35
- searchParams.set('is_debug', 'true');
36
- }
37
-
38
- const url = new URL(endpoint);
39
-
40
- if (searchParams.toString()) {
41
- url.search = searchParams.toString();
42
- }
43
-
44
- fetchEventSource(url.toString(), {
45
- method: 'POST',
46
- headers,
47
- body: payload ? JSON.stringify(payload) : undefined,
48
- signal: controller.signal,
49
- /**
50
- * Allow SSE to work when the page is hidden.
51
- * https://github.com/Azure/fetch-event-source/issues/17#issuecomment-1525904929
52
- */
53
- openWhenHidden: true,
54
- onopen: async (response) => {
55
- if (!response.ok) {
56
- subscriber.error(response);
57
- controller.abort();
58
- }
59
- },
60
- onmessage: (esm: EventSourceMessage) => {
61
- subscriber.next(JSON.parse(esm.data));
62
- },
63
- onclose: () => {
64
- subscriber.complete();
65
- },
66
- onerror: (err) => {
67
- subscriber.error(err);
68
- controller.abort();
69
- throw err;
70
- },
71
- });
72
-
73
- return (): void => {
74
- controller.abort();
75
- };
76
- });
77
- }
@@ -1,30 +0,0 @@
1
- import { Listeners } from '../types';
2
-
3
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
4
- export class EventEmitter<Events extends Record<string, any>> {
5
- private listeners: Listeners<Events> = {};
6
-
7
- on<K extends keyof Events>(event: K, listener: Events[K]): void {
8
- this.listeners = Object.assign({}, this.listeners, {
9
- [event]: (this.listeners[event] ?? []).concat(listener),
10
- });
11
- }
12
-
13
- off<K extends keyof Events>(event: K, listener: Events[K]): void {
14
- if (!this.listeners[event]) return;
15
-
16
- this.listeners = Object.assign({}, this.listeners, {
17
- [event]: (this.listeners[event] ?? []).filter((l: Events[K]) => l !== listener),
18
- });
19
- }
20
-
21
- remove<K extends keyof Events>(event: K): void {
22
- delete this.listeners[event];
23
- }
24
-
25
- emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void {
26
- if (!this.listeners[event]) return;
27
-
28
- this.listeners[event].forEach((listener: Events[K]) => listener(...args));
29
- }
30
- }
@@ -1,50 +0,0 @@
1
- import { Observer } from 'rxjs';
2
- import { EventType } from '../constants/enum';
3
- import Conversation from '../lib/conversation';
4
- import { IAsgardServiceClient } from './client';
5
- import { ErrorMessage, Message } from './sse-response';
6
-
7
- export type ObserverOrNext<T> = Partial<Observer<T>> | ((value: T) => void);
8
-
9
- export interface ChannelStates {
10
- isConnecting: boolean;
11
- conversation: Conversation;
12
- }
13
-
14
- export interface ChannelConfig {
15
- client: IAsgardServiceClient;
16
- customChannelId: string;
17
- customMessageId?: string;
18
- conversation: Conversation;
19
- statesObserver?: ObserverOrNext<ChannelStates>;
20
- }
21
-
22
- export type ConversationUserMessage = {
23
- type: 'user';
24
- messageId: string;
25
- text: string;
26
- time: Date;
27
- };
28
-
29
- export type ConversationBotMessage = {
30
- type: 'bot';
31
- messageId: string;
32
- eventType: EventType;
33
- isTyping: boolean;
34
- typingText: string | null;
35
- message: Message;
36
- time: Date;
37
- };
38
-
39
- export type ConversationErrorMessage = {
40
- type: 'error';
41
- messageId: string;
42
- eventType: EventType;
43
- error: ErrorMessage;
44
- time: Date;
45
- };
46
-
47
- export type ConversationMessage =
48
- | ConversationUserMessage
49
- | ConversationBotMessage
50
- | ConversationErrorMessage;
@@ -1,89 +0,0 @@
1
- import { EventType, FetchSseAction } from '../constants/enum';
2
- import { SseResponse } from './sse-response';
3
- import { EventHandler } from './event-emitter';
4
-
5
- export interface IAsgardServiceClient {
6
- fetchSse(payload: FetchSsePayload, options?: FetchSseOptions): void;
7
- }
8
-
9
- export type InitEventHandler = EventHandler<SseResponse<EventType.INIT>>;
10
- export type MessageEventHandler = EventHandler<
11
- SseResponse<
12
- | EventType.MESSAGE_START
13
- | EventType.MESSAGE_DELTA
14
- | EventType.MESSAGE_COMPLETE
15
- >
16
- >;
17
- export type ProcessEventHandler = EventHandler<
18
- SseResponse<EventType.PROCESS_START | EventType.PROCESS_COMPLETE>
19
- >;
20
- export type DoneEventHandler = EventHandler<SseResponse<EventType.DONE>>;
21
- export type ErrorEventHandler = EventHandler<SseResponse<EventType.ERROR>>;
22
- export type ToolCallEventHandler = EventHandler<
23
- SseResponse<EventType.TOOL_CALL_START | EventType.TOOL_CALL_COMPLETE>
24
- >;
25
-
26
- export interface SseHandlers {
27
- onRunInit?: InitEventHandler;
28
- onMessage?: MessageEventHandler;
29
- onToolCall?: ToolCallEventHandler;
30
- onProcess?: ProcessEventHandler;
31
- onRunDone?: DoneEventHandler;
32
- onRunError?: ErrorEventHandler;
33
- }
34
-
35
- export type ClientConfig = SseHandlers & {
36
- apiKey?: string;
37
- debugMode?: boolean;
38
- transformSsePayload?: (payload: FetchSsePayload) => FetchSsePayload;
39
- } & (
40
- | {
41
- /**
42
- * @deprecated Use `botProviderEndpoint` instead. This will be removed in the next major version.
43
- * If provided, it will be used. Otherwise, it will be automatically derived as `${botProviderEndpoint}/message/sse`
44
- */
45
- endpoint: string;
46
- /**
47
- * Base URL for the bot provider service.
48
- * The SSE endpoint will be automatically derived as `${botProviderEndpoint}/message/sse`
49
- */
50
- botProviderEndpoint?: string;
51
- }
52
- | {
53
- /**
54
- * Base URL for the bot provider service.
55
- * The SSE endpoint will be automatically derived as `${botProviderEndpoint}/message/sse`
56
- */
57
- botProviderEndpoint: string;
58
- /**
59
- * @deprecated Use `botProviderEndpoint` instead. This will be removed in the next major version.
60
- * If provided, it will be used. Otherwise, it will be automatically derived as `${botProviderEndpoint}/message/sse`
61
- */
62
- endpoint?: string;
63
- }
64
- );
65
-
66
- export interface FetchSsePayload {
67
- customChannelId: string;
68
- customMessageId?: string;
69
- text: string;
70
- payload?: Record<string, unknown>;
71
- action: FetchSseAction;
72
- }
73
-
74
- export interface FetchSseOptions {
75
- delayTime?: number;
76
- onSseStart?: () => void;
77
- onSseMessage?: (response: SseResponse<EventType>) => void;
78
- onSseError?: (error: unknown) => void;
79
- onSseCompleted?: () => void;
80
- }
81
-
82
- export type SseEvents = {
83
- [EventType.INIT]: InitEventHandler;
84
- [EventType.PROCESS]: ProcessEventHandler;
85
- [EventType.MESSAGE]: MessageEventHandler;
86
- [EventType.TOOL_CALL]: ToolCallEventHandler;
87
- [EventType.DONE]: DoneEventHandler;
88
- [EventType.ERROR]: ErrorEventHandler;
89
- };
@@ -1,8 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- export type EventHandler<Args, Return = void> = Args extends any[]
3
- ? (...args: Args) => Return
4
- : (arg: Args) => Return;
5
-
6
- export type Listeners<Events extends Record<string, any>> = {
7
- [K in keyof Events]?: Array<Events[K]>;
8
- };
@@ -1,4 +0,0 @@
1
- export type * from './client';
2
- export type * from './channel';
3
- export type * from './sse-response';
4
- export type * from './event-emitter';
@@ -1,176 +0,0 @@
1
- import { EventType, MessageTemplateType } from '../constants/enum';
2
-
3
- export interface MessageTemplate {
4
- quickReplies: { text: string }[];
5
- }
6
-
7
- export interface TextMessageTemplate extends MessageTemplate {
8
- type: MessageTemplateType.TEXT;
9
- text: string;
10
- }
11
-
12
- export interface HintMessageTemplate extends MessageTemplate {
13
- type: MessageTemplateType.HINT;
14
- text: string;
15
- }
16
-
17
- export interface ImageMessageTemplate extends MessageTemplate {
18
- type: MessageTemplateType.IMAGE;
19
- originalContentUrl: string;
20
- previewImageUrl: string;
21
- }
22
-
23
- export interface VideoMessageTemplate extends MessageTemplate {
24
- type: MessageTemplateType.VIDEO;
25
- originalContentUrl: string;
26
- previewImageUrl: string;
27
- duration: number;
28
- }
29
-
30
- export interface AudioMessageTemplate extends MessageTemplate {
31
- type: MessageTemplateType.AUDIO;
32
- originalContentUrl: string;
33
- duration: number;
34
- }
35
-
36
- export interface LocationMessageTemplate extends MessageTemplate {
37
- type: MessageTemplateType.LOCATION;
38
- title: string;
39
- text: string;
40
- latitude: number;
41
- longitude: number;
42
- }
43
-
44
- export interface ChartMessageTemplate extends MessageTemplate {
45
- type: MessageTemplateType.CHART;
46
- title: string;
47
- text: string;
48
- chartOptions: {
49
- type: string;
50
- title: string;
51
- spec: Record<string, unknown>;
52
- }[];
53
- defaultChart: string;
54
- quickReplies: { text: string }[];
55
- }
56
-
57
- export type ButtonAction =
58
- | {
59
- type: 'message' | 'MESSAGE';
60
- text: string;
61
- uri?: null;
62
- }
63
- | {
64
- type: 'uri' | 'URI';
65
- text?: null;
66
- uri: string;
67
- target?: '_blank' | '_self' | '_parent' | '_top';
68
- }
69
- | {
70
- type: 'emit' | 'EMIT';
71
- payload: Record<string, unknown>;
72
- };
73
-
74
- export interface ButtonMessageTemplate extends MessageTemplate {
75
- type: MessageTemplateType.BUTTON;
76
- title: string;
77
- text: string;
78
- thumbnailImageUrl: string;
79
- imageAspectRatio: 'rectangle' | 'square';
80
- imageSize: 'cover' | 'contain';
81
- imageBackgroundColor: string;
82
- defaultAction: ButtonAction;
83
- buttons: { label: string; action: ButtonAction }[];
84
- }
85
-
86
- export interface CarouselMessageTemplate extends MessageTemplate {
87
- type: MessageTemplateType.CAROUSEL;
88
- columns: Omit<ButtonMessageTemplate, 'type' | 'quickReplies'>[];
89
- }
90
-
91
- export interface Message<Payload = unknown> {
92
- messageId: string;
93
- replyToCustomMessageId: string;
94
- text: string;
95
- payload: Payload | null;
96
- isDebug: boolean;
97
- idx: number;
98
- template:
99
- | TextMessageTemplate
100
- | HintMessageTemplate
101
- | ButtonMessageTemplate
102
- | ImageMessageTemplate
103
- | VideoMessageTemplate
104
- | AudioMessageTemplate
105
- | LocationMessageTemplate
106
- | CarouselMessageTemplate
107
- | ChartMessageTemplate;
108
- }
109
-
110
- export type IsEqual<A, B, DataType> = A extends B
111
- ? B extends A
112
- ? DataType
113
- : null
114
- : null;
115
-
116
- export interface MessageEventData {
117
- message: Message;
118
- }
119
-
120
- export interface ErrorMessage {
121
- message: string;
122
- code: string;
123
- inner: string;
124
- location: {
125
- namespace: string;
126
- workflowName: string;
127
- processorName: string;
128
- processorType: string;
129
- };
130
- }
131
-
132
- export interface ErrorEventData {
133
- error: ErrorMessage;
134
- }
135
-
136
- export interface ToolCallBaseEventData {
137
- processId: string;
138
- callSeq: number;
139
- toolCall: {
140
- toolsetName: string;
141
- toolName: string;
142
- parameter: Record<string, unknown>;
143
- };
144
- }
145
-
146
- export interface ToolCallCompleteEventData extends ToolCallBaseEventData {
147
- toolCallResult: Record<string, unknown>;
148
- }
149
-
150
- export interface Fact<Type extends EventType> {
151
- runInit: null;
152
- runDone: null;
153
- runError: IsEqual<Type, EventType.ERROR, ErrorEventData>;
154
- messageStart: IsEqual<Type, EventType.MESSAGE_START, MessageEventData>;
155
- messageDelta: IsEqual<Type, EventType.MESSAGE_DELTA, MessageEventData>;
156
- messageComplete: IsEqual<Type, EventType.MESSAGE_COMPLETE, MessageEventData>;
157
- toolCallStart: IsEqual<
158
- Type,
159
- EventType.TOOL_CALL_START,
160
- ToolCallBaseEventData
161
- >;
162
- toolCallComplete: IsEqual<
163
- Type,
164
- EventType.TOOL_CALL_COMPLETE,
165
- ToolCallCompleteEventData
166
- >;
167
- }
168
-
169
- export interface SseResponse<Type extends EventType> {
170
- eventType: Type;
171
- requestId: string;
172
- namespace: string;
173
- botProviderName: string;
174
- customChannelId: string;
175
- fact: Fact<Type>;
176
- }
package/tsconfig.json DELETED
@@ -1,13 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "files": [],
4
- "include": [],
5
- "references": [
6
- {
7
- "path": "./tsconfig.lib.json"
8
- },
9
- {
10
- "path": "./tsconfig.spec.json"
11
- }
12
- ]
13
- }
package/tsconfig.lib.json DELETED
@@ -1,28 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "baseUrl": ".",
5
- "paths": {
6
- "src/*": ["src/*"]
7
- },
8
- "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo",
9
- "emitDeclarationOnly": false,
10
- "types": ["node", "vite/client"]
11
- },
12
- "include": ["src/**/*.ts"],
13
- "references": [],
14
- "exclude": [
15
- "vite.config.ts",
16
- "vite.config.mts",
17
- "vitest.config.ts",
18
- "vitest.config.mts",
19
- "src/**/*.test.ts",
20
- "src/**/*.spec.ts",
21
- "src/**/*.test.tsx",
22
- "src/**/*.spec.tsx",
23
- "src/**/*.test.js",
24
- "src/**/*.spec.js",
25
- "src/**/*.test.jsx",
26
- "src/**/*.spec.jsx"
27
- ]
28
- }
@@ -1,33 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "./out-tsc/vitest",
5
- "types": [
6
- "vitest/globals",
7
- "vitest/importMeta",
8
- "vite/client",
9
- "node",
10
- "vitest"
11
- ]
12
- },
13
- "include": [
14
- "vite.config.ts",
15
- "vite.config.mts",
16
- "vitest.config.ts",
17
- "vitest.config.mts",
18
- "src/**/*.test.ts",
19
- "src/**/*.spec.ts",
20
- "src/**/*.test.tsx",
21
- "src/**/*.spec.tsx",
22
- "src/**/*.test.js",
23
- "src/**/*.spec.js",
24
- "src/**/*.test.jsx",
25
- "src/**/*.spec.jsx",
26
- "src/**/*.d.ts"
27
- ],
28
- "references": [
29
- {
30
- "path": "./tsconfig.lib.json"
31
- }
32
- ]
33
- }