@botpress/sdk 2.0.4 → 2.1.0

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.
Files changed (66) hide show
  1. package/.turbo/turbo-build.log +12 -0
  2. package/dist/base-logger.d.ts +13 -0
  3. package/dist/bot/bot-logger.d.ts +14 -0
  4. package/dist/bot/client/index.d.ts +62 -0
  5. package/dist/bot/client/types.d.ts +141 -0
  6. package/dist/bot/client/types.test.d.ts +1 -0
  7. package/dist/bot/definition.d.ts +111 -0
  8. package/dist/bot/implementation.d.ts +39 -0
  9. package/dist/bot/index.d.ts +6 -0
  10. package/dist/bot/merge-bots.d.ts +2 -0
  11. package/dist/bot/server/context.d.ts +2 -0
  12. package/dist/bot/server/index.d.ts +5 -0
  13. package/dist/bot/server/types.d.ts +254 -0
  14. package/dist/bot/server/types.test.d.ts +1 -0
  15. package/dist/bot/types/common.d.ts +50 -0
  16. package/dist/bot/types/common.test.d.ts +1 -0
  17. package/dist/bot/types/generic.d.ts +31 -0
  18. package/dist/bot/types/generic.test.d.ts +1 -0
  19. package/dist/bot/types/index.d.ts +2 -0
  20. package/dist/const.d.ts +8 -0
  21. package/dist/fixtures.d.ts +108 -0
  22. package/dist/index.d.ts +15 -0
  23. package/dist/index.js +2 -0
  24. package/dist/index.js.map +7 -0
  25. package/dist/integration/client/index.d.ts +47 -0
  26. package/dist/integration/client/types.d.ts +177 -0
  27. package/dist/integration/client/types.test.d.ts +1 -0
  28. package/dist/integration/definition/branded-schema.d.ts +21 -0
  29. package/dist/integration/definition/generic.d.ts +9 -0
  30. package/dist/integration/definition/index.d.ts +76 -0
  31. package/dist/integration/definition/types.d.ts +106 -0
  32. package/dist/integration/implementation.d.ts +31 -0
  33. package/dist/integration/index.d.ts +5 -0
  34. package/dist/integration/server/action-metadata.d.ts +9 -0
  35. package/dist/integration/server/context.d.ts +3 -0
  36. package/dist/integration/server/index.d.ts +6 -0
  37. package/dist/integration/server/integration-logger.d.ts +16 -0
  38. package/dist/integration/server/types.d.ts +102 -0
  39. package/dist/integration/types/common.d.ts +11 -0
  40. package/dist/integration/types/generic.d.ts +52 -0
  41. package/dist/integration/types/generic.test.d.ts +1 -0
  42. package/dist/integration/types/index.d.ts +2 -0
  43. package/dist/interface/definition.d.ts +70 -0
  44. package/dist/interface/index.d.ts +1 -0
  45. package/dist/interface/types/generic.d.ts +34 -0
  46. package/dist/interface/types/generic.test.d.ts +1 -0
  47. package/dist/log.d.ts +7 -0
  48. package/dist/message.d.ts +474 -0
  49. package/dist/package.d.ts +58 -0
  50. package/dist/plugin/definition.d.ts +50 -0
  51. package/dist/plugin/implementation.d.ts +39 -0
  52. package/dist/plugin/index.d.ts +3 -0
  53. package/dist/plugin/server/types.d.ts +1 -0
  54. package/dist/plugin/server/types.test.d.ts +1 -0
  55. package/dist/plugin/types/generic.d.ts +30 -0
  56. package/dist/plugin/types/generic.test.d.ts +1 -0
  57. package/dist/retry.d.ts +2 -0
  58. package/dist/schema.d.ts +18 -0
  59. package/dist/serve.d.ts +20 -0
  60. package/dist/utils/array-utils.d.ts +1 -0
  61. package/dist/utils/index.d.ts +3 -0
  62. package/dist/utils/record-utils.d.ts +3 -0
  63. package/dist/utils/type-utils.d.ts +33 -0
  64. package/dist/utils/type-utils.test.d.ts +1 -0
  65. package/dist/zui.d.ts +5 -0
  66. package/package.json +2 -2
@@ -0,0 +1,254 @@
1
+ import * as client from '@botpress/client';
2
+ import * as plugin from '../../plugin';
3
+ import * as utils from '../../utils/type-utils';
4
+ import { type BotLogger } from '../bot-logger';
5
+ import { BotSpecificClient } from '../client';
6
+ import * as types from '../types';
7
+ export type BotOperation = 'event_received' | 'register' | 'unregister' | 'ping' | 'action_triggered';
8
+ export type BotContext = {
9
+ botId: string;
10
+ type: string;
11
+ operation: BotOperation;
12
+ configuration: {
13
+ payload: string;
14
+ };
15
+ };
16
+ type _IncomingEvents<TBot extends types.BaseBot> = {
17
+ [K in keyof types.EnumerateEvents<TBot>]: utils.Merge<client.Event, {
18
+ type: K;
19
+ payload: types.EnumerateEvents<TBot>[K];
20
+ }>;
21
+ };
22
+ type _IncomingMessages<TBot extends types.BaseBot> = {
23
+ [K in keyof types.GetMessages<TBot>]: utils.Merge<client.Message, {
24
+ type: K;
25
+ payload: types.GetMessages<TBot>[K];
26
+ }>;
27
+ };
28
+ type _OutgoingMessageRequests<TBot extends types.BaseBot> = {
29
+ [K in keyof types.GetMessages<TBot>]: utils.Merge<client.ClientInputs['createMessage'], {
30
+ type: K;
31
+ payload: types.GetMessages<TBot>[K];
32
+ }>;
33
+ };
34
+ type _OutgoingMessageResponses<TBot extends types.BaseBot> = {
35
+ [K in keyof types.GetMessages<TBot>]: utils.Merge<client.ClientOutputs['createMessage'], {
36
+ message: utils.Merge<client.Message, {
37
+ type: K;
38
+ payload: types.GetMessages<TBot>[K];
39
+ }>;
40
+ }>;
41
+ };
42
+ type _OutgoingCallActionRequests<TBot extends types.BaseBot> = {
43
+ [K in keyof types.EnumerateActionInputs<TBot>]: utils.Merge<client.ClientInputs['callAction'], {
44
+ type: K;
45
+ input: types.EnumerateActionInputs<TBot>[K];
46
+ }>;
47
+ };
48
+ type _OutgoingCallActionResponses<TBot extends types.BaseBot> = {
49
+ [K in keyof types.EnumerateActionOutputs<TBot>]: utils.Merge<client.ClientOutputs['callAction'], {
50
+ output: types.EnumerateActionOutputs<TBot>[K];
51
+ }>;
52
+ };
53
+ export type AnyIncomingEvent<TBot extends types.BaseBot> = TBot['unknownDefinitions'] extends true ? client.Event : utils.ValueOf<_IncomingEvents<TBot>>;
54
+ export type AnyIncomingMessage<TBot extends types.BaseBot> = TBot['unknownDefinitions'] extends true ? client.Message : utils.ValueOf<_IncomingMessages<TBot>>;
55
+ export type AnyOutgoingMessageRequest<TBot extends types.BaseBot> = TBot['unknownDefinitions'] extends true ? client.ClientInputs['createMessage'] : utils.ValueOf<_OutgoingMessageRequests<TBot>>;
56
+ export type AnyOutgoingMessageResponse<TBot extends types.BaseBot> = TBot['unknownDefinitions'] extends true ? client.ClientOutputs['createMessage'] : utils.ValueOf<_OutgoingMessageResponses<TBot>>;
57
+ export type AnyOutgoingCallActionRequest<TBot extends types.BaseBot> = TBot['unknownDefinitions'] extends true ? client.ClientInputs['callAction'] : utils.ValueOf<_OutgoingCallActionRequests<TBot>>;
58
+ export type AnyOutgoingCallActionResponse<TBot extends types.BaseBot> = TBot['unknownDefinitions'] extends true ? client.ClientOutputs['callAction'] : utils.ValueOf<_OutgoingCallActionResponses<TBot>>;
59
+ export type IncomingEvents<TBot extends types.BaseBot> = _IncomingEvents<TBot> & {
60
+ '*': AnyIncomingEvent<TBot>;
61
+ };
62
+ export type IncomingMessages<TBot extends types.BaseBot> = _IncomingMessages<TBot> & {
63
+ '*': AnyIncomingMessage<TBot>;
64
+ };
65
+ export type IncomingStates<_TBot extends types.BaseBot> = {
66
+ '*': client.State;
67
+ };
68
+ export type OutgoingMessageRequests<TBot extends types.BaseBot> = _OutgoingMessageRequests<TBot> & {
69
+ '*': AnyOutgoingMessageRequest<TBot>;
70
+ };
71
+ export type OutgoingMessageResponses<TBot extends types.BaseBot> = _OutgoingMessageResponses<TBot> & {
72
+ '*': AnyOutgoingMessageResponse<TBot>;
73
+ };
74
+ export type OutgoingCallActionRequests<TBot extends types.BaseBot> = _OutgoingCallActionRequests<TBot> & {
75
+ '*': AnyOutgoingCallActionRequest<TBot>;
76
+ };
77
+ export type OutgoingCallActionResponses<TBot extends types.BaseBot> = _OutgoingCallActionResponses<TBot> & {
78
+ '*': AnyOutgoingCallActionResponse<TBot>;
79
+ };
80
+ export type BotClient<TBot extends types.BaseBot> = TBot['unknownDefinitions'] extends true ? BotSpecificClient<types.BaseBot> : BotSpecificClient<TBot>;
81
+ export type CommonHandlerProps<TBot extends types.BaseBot> = {
82
+ ctx: BotContext;
83
+ logger: BotLogger;
84
+ client: BotClient<TBot>;
85
+ };
86
+ export type MessagePayloads<TBot extends types.BaseBot> = {
87
+ [K in keyof IncomingMessages<TBot>]: {
88
+ message: IncomingMessages<TBot>[K];
89
+ user: client.User;
90
+ conversation: client.Conversation;
91
+ event: client.Event;
92
+ states: {
93
+ [TState in keyof TBot['states']]: {
94
+ type: 'user' | 'conversation' | 'bot';
95
+ payload: TBot['states'][TState];
96
+ };
97
+ };
98
+ };
99
+ };
100
+ export type MessageHandlers<TBot extends types.BaseBot> = {
101
+ [K in keyof IncomingMessages<TBot>]: (args: CommonHandlerProps<TBot> & MessagePayloads<TBot>[K]) => Promise<void>;
102
+ };
103
+ export type EventPayloads<TBot extends types.BaseBot> = {
104
+ [K in keyof IncomingEvents<TBot>]: {
105
+ event: IncomingEvents<TBot>[K];
106
+ };
107
+ };
108
+ export type EventHandlers<TBot extends types.BaseBot> = {
109
+ [K in keyof IncomingEvents<TBot>]: (args: CommonHandlerProps<TBot> & EventPayloads<TBot>[K]) => Promise<void>;
110
+ };
111
+ export type StateExpiredPayloads<TBot extends types.BaseBot> = {
112
+ [K in keyof IncomingStates<TBot>]: {
113
+ state: IncomingStates<TBot>[K];
114
+ };
115
+ };
116
+ export type StateExpiredHandlers<TBot extends types.BaseBot> = {
117
+ [K in keyof IncomingStates<TBot>]: (args: CommonHandlerProps<TBot> & StateExpiredPayloads<TBot>[K]) => Promise<void>;
118
+ };
119
+ export type ActionHandlerPayloads<TBot extends types.BaseBot> = {
120
+ [K in keyof TBot['actions']]: {
121
+ type?: K;
122
+ input: TBot['actions'][K]['input'];
123
+ };
124
+ };
125
+ export type ActionHandlers<TBot extends types.BaseBot> = {
126
+ [K in keyof TBot['actions']]: (props: CommonHandlerProps<TBot> & ActionHandlerPayloads<TBot>[K]) => Promise<TBot['actions'][K]['output']>;
127
+ };
128
+ type BaseHookDefinition = {
129
+ stoppable?: boolean;
130
+ data: any;
131
+ };
132
+ type HookDefinition<THookDef extends BaseHookDefinition = BaseHookDefinition> = THookDef;
133
+ /**
134
+ * TODO: add hooks for:
135
+ * - before_register
136
+ * - after_register
137
+ * - before_state_expired
138
+ * - after_state_expired
139
+ * - before_incoming_call_action
140
+ * - after_incoming_call_action
141
+ */
142
+ export type HookDefinitions<TBot extends types.BaseBot> = {
143
+ before_incoming_event: HookDefinition<{
144
+ stoppable: true;
145
+ data: _IncomingEvents<TBot> & {
146
+ '*': AnyIncomingEvent<TBot>;
147
+ };
148
+ }>;
149
+ before_incoming_message: HookDefinition<{
150
+ stoppable: true;
151
+ data: _IncomingMessages<TBot> & {
152
+ '*': AnyIncomingMessage<TBot>;
153
+ };
154
+ }>;
155
+ before_outgoing_message: HookDefinition<{
156
+ stoppable: false;
157
+ data: _OutgoingMessageRequests<TBot> & {
158
+ '*': AnyOutgoingMessageRequest<TBot>;
159
+ };
160
+ }>;
161
+ before_outgoing_call_action: HookDefinition<{
162
+ stoppable: false;
163
+ data: _OutgoingCallActionRequests<TBot> & {
164
+ '*': AnyOutgoingCallActionRequest<TBot>;
165
+ };
166
+ }>;
167
+ after_incoming_event: HookDefinition<{
168
+ stoppable: true;
169
+ data: _IncomingEvents<TBot> & {
170
+ '*': AnyIncomingEvent<TBot>;
171
+ };
172
+ }>;
173
+ after_incoming_message: HookDefinition<{
174
+ stoppable: true;
175
+ data: _IncomingMessages<TBot> & {
176
+ '*': AnyIncomingMessage<TBot>;
177
+ };
178
+ }>;
179
+ after_outgoing_message: HookDefinition<{
180
+ stoppable: false;
181
+ data: _OutgoingMessageResponses<TBot> & {
182
+ '*': AnyOutgoingMessageResponse<TBot>;
183
+ };
184
+ }>;
185
+ after_outgoing_call_action: HookDefinition<{
186
+ stoppable: false;
187
+ data: _OutgoingCallActionResponses<TBot> & {
188
+ '*': AnyOutgoingCallActionResponse<TBot>;
189
+ };
190
+ }>;
191
+ };
192
+ export type HookData<TBot extends types.BaseBot> = {
193
+ [H in keyof HookDefinitions<TBot>]: {
194
+ [T in keyof HookDefinitions<TBot>[H]['data']]: HookDefinitions<TBot>[H]['data'][T];
195
+ };
196
+ };
197
+ export type HookInputs<TBot extends types.BaseBot> = {
198
+ [H in keyof HookData<TBot>]: {
199
+ [T in keyof HookData<TBot>[H]]: CommonHandlerProps<TBot> & {
200
+ data: HookData<TBot>[H][T];
201
+ };
202
+ };
203
+ };
204
+ export type HookOutputs<TBot extends types.BaseBot> = {
205
+ [H in keyof HookData<TBot>]: {
206
+ [T in keyof HookData<TBot>[H]]: {
207
+ data?: HookData<TBot>[H][T];
208
+ } & (HookDefinitions<TBot>[H]['stoppable'] extends true ? {
209
+ stop?: boolean;
210
+ } : {});
211
+ };
212
+ };
213
+ export type HookHandlers<TBot extends types.BaseBot> = {
214
+ [H in keyof HookData<TBot>]: {
215
+ [T in keyof HookData<TBot>[H]]: (input: HookInputs<TBot>[H][T]) => Promise<HookOutputs<TBot>[H][T] | undefined>;
216
+ };
217
+ };
218
+ export type MessageHandlersMap<TBot extends types.BaseBot> = {
219
+ [T in keyof IncomingMessages<TBot>]?: MessageHandlers<TBot>[T][];
220
+ };
221
+ export type EventHandlersMap<TBot extends types.BaseBot> = {
222
+ [T in keyof IncomingEvents<TBot>]?: EventHandlers<TBot>[T][];
223
+ };
224
+ export type StateExpiredHandlersMap<TBot extends types.BaseBot> = {
225
+ [T in keyof IncomingStates<TBot>]?: StateExpiredHandlers<TBot>[T][];
226
+ };
227
+ export type HookHandlersMap<TBot extends types.BaseBot> = {
228
+ [H in keyof HookData<TBot>]: {
229
+ [T in keyof HookData<TBot>[H]]?: HookHandlers<TBot>[H][T][];
230
+ };
231
+ };
232
+ export type BotActionHandlers<TBot extends types.BaseBot> = ActionHandlers<TBot>;
233
+ export type BotMessageHandlers<TBot extends types.BaseBot> = MessageHandlersMap<TBot>;
234
+ export type BotEventHandlers<TBot extends types.BaseBot> = EventHandlersMap<TBot>;
235
+ export type BotStateExpiredHandlers<TBot extends types.BaseBot> = StateExpiredHandlersMap<TBot>;
236
+ export type BotHookHandlers<TBot extends types.BaseBot> = HookHandlersMap<TBot>;
237
+ export type BotHandlers<TBot extends types.BaseBot> = {
238
+ actionHandlers: BotActionHandlers<TBot>;
239
+ messageHandlers: BotMessageHandlers<TBot>;
240
+ eventHandlers: BotEventHandlers<TBot>;
241
+ stateExpiredHandlers: BotStateExpiredHandlers<TBot>;
242
+ hookHandlers: BotHookHandlers<TBot>;
243
+ };
244
+ type ImplementedActions<_TBot extends types.BaseBot, TPlugins extends Record<string, plugin.BasePlugin>> = utils.UnionToIntersection<utils.ValueOf<{
245
+ [K in keyof TPlugins]: TPlugins[K]['actions'];
246
+ }>>;
247
+ type UnimplementedActions<TBot extends types.BaseBot, TPlugins extends Record<string, plugin.BasePlugin>> = Omit<TBot['actions'], keyof ImplementedActions<TBot, TPlugins>>;
248
+ export type ImplementedActionHandlers<TBot extends types.BaseBot, TPlugins extends Record<string, plugin.BasePlugin>> = {
249
+ [K in keyof ImplementedActions<TBot, TPlugins>]: ActionHandlers<TBot>[utils.Cast<K, keyof ActionHandlers<TBot>>];
250
+ };
251
+ export type UnimplementedActionHandlers<TBot extends types.BaseBot, TPlugins extends Record<string, plugin.BasePlugin>> = {
252
+ [K in keyof UnimplementedActions<TBot, TPlugins>]: ActionHandlers<TBot>[utils.Cast<K, keyof ActionHandlers<TBot>>];
253
+ };
254
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,50 @@
1
+ import { Join, UnionToIntersection, Split, Cast } from '../../utils/type-utils';
2
+ import { BaseBot } from './generic';
3
+ export type EventDefinition = BaseBot['events'][string];
4
+ export type StateDefinition = BaseBot['states'][string];
5
+ export type IntegrationInstanceDefinition = BaseBot['integrations'][string];
6
+ export type IntegrationInstanceConfigurationDefinition = IntegrationInstanceDefinition['configuration'];
7
+ export type IntegrationInstanceActionDefinition = IntegrationInstanceDefinition['actions'][string];
8
+ export type IntegrationInstanceChannelDefinition = IntegrationInstanceDefinition['channels'][string];
9
+ export type IntegrationInstanceMessageDefinition = IntegrationInstanceChannelDefinition['messages'][string];
10
+ export type IntegrationInstanceEventDefinition = IntegrationInstanceDefinition['events'][string];
11
+ export type IntegrationInstanceStateDefinition = IntegrationInstanceDefinition['states'][string];
12
+ export type IntegrationInstanceUserDefinition = IntegrationInstanceDefinition['user'];
13
+ type ActionKey<TIntegrationName extends string, TActionName extends string> = string extends TIntegrationName ? string : string extends TActionName ? string : Join<[TIntegrationName, ':', TActionName]>;
14
+ export type EnumerateActions<TBot extends BaseBot> = UnionToIntersection<{
15
+ [TIntegrationName in keyof TBot['integrations']]: {
16
+ [TActionName in keyof TBot['integrations'][TIntegrationName]['actions'] as ActionKey<Cast<TIntegrationName, string>, Cast<TActionName, string>>]: TBot['integrations'][TIntegrationName]['actions'][TActionName];
17
+ };
18
+ }[keyof TBot['integrations']]> & {};
19
+ export type EnumerateActionInputs<TBot extends BaseBot> = {
20
+ [K in keyof EnumerateActions<TBot>]: Cast<EnumerateActions<TBot>[K], IntegrationInstanceActionDefinition>['input'];
21
+ };
22
+ export type EnumerateActionOutputs<TBot extends BaseBot> = {
23
+ [K in keyof EnumerateActions<TBot>]: Cast<EnumerateActions<TBot>[K], IntegrationInstanceActionDefinition>['output'];
24
+ };
25
+ type EventKey<TIntegrationName extends string, TEventName extends string> = string extends TIntegrationName ? string : string extends TEventName ? string : Join<[TIntegrationName, ':', TEventName]>;
26
+ export type EnumerateEvents<TBot extends BaseBot> = UnionToIntersection<{
27
+ [TIntegrationName in keyof TBot['integrations']]: {
28
+ [TEventName in keyof TBot['integrations'][TIntegrationName]['events'] as EventKey<Cast<TIntegrationName, string>, Cast<TEventName, string>>]: TBot['integrations'][TIntegrationName]['events'][TEventName];
29
+ };
30
+ }[keyof TBot['integrations']]> & {
31
+ [TEventName in keyof TBot['events']]: TBot['events'][TEventName];
32
+ };
33
+ type ChannelKey<TIntegrationName extends string, TChannelName extends string> = string extends TIntegrationName ? string : string extends TChannelName ? string : Join<[TIntegrationName, ':', TChannelName]>;
34
+ export type EnumerateChannels<TBot extends BaseBot> = UnionToIntersection<{
35
+ [TIntegrationName in keyof TBot['integrations']]: {
36
+ [TChannelName in keyof TBot['integrations'][TIntegrationName]['channels'] as ChannelKey<Cast<TIntegrationName, string>, Cast<TChannelName, string>>]: TBot['integrations'][TIntegrationName]['channels'][TChannelName];
37
+ };
38
+ }[keyof TBot['integrations']]> & {};
39
+ type MessageKey<TIntegrationName extends string, TChannelName extends string, TMessageName extends string> = string extends TIntegrationName ? string : string extends TChannelName ? string : string extends TMessageName ? string : Join<[TIntegrationName, ':', TChannelName, ':', TMessageName]>;
40
+ export type EnumerateMessages<TBot extends BaseBot> = UnionToIntersection<{
41
+ [TIntegrationName in keyof TBot['integrations']]: {
42
+ [TChannelName in keyof TBot['integrations'][TIntegrationName]['channels']]: {
43
+ [TMessageName in keyof TBot['integrations'][TIntegrationName]['channels'][TChannelName]['messages'] as MessageKey<Cast<TIntegrationName, string>, Cast<TChannelName, string>, Cast<TMessageName, string>>]: TBot['integrations'][TIntegrationName]['channels'][TChannelName]['messages'][TMessageName];
44
+ };
45
+ }[keyof TBot['integrations'][TIntegrationName]['channels']];
46
+ }[keyof TBot['integrations']]> & {};
47
+ export type GetMessages<TBot extends BaseBot> = {
48
+ [K in keyof EnumerateMessages<TBot> as Cast<Split<K, ':'>[2], string>]: EnumerateMessages<TBot>[K];
49
+ };
50
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,31 @@
1
+ import { BaseIntegration, DefaultIntegration, InputBaseIntegration } from '../../integration/types/generic';
2
+ import * as utils from '../../utils/type-utils';
3
+ export * from '../../integration/types/generic';
4
+ export type BaseAction = {
5
+ input: any;
6
+ output: any;
7
+ };
8
+ export type BaseBot = {
9
+ integrations: Record<string, BaseIntegration>;
10
+ events: Record<string, any>;
11
+ states: Record<string, any>;
12
+ actions: Record<string, BaseAction>;
13
+ /**
14
+ * In a bot, all events, actions, states, and integrations definitions are known.
15
+ * This mean the Bot typings should not allow for unknown types.
16
+ *
17
+ * In a plugin, we don't known about extra definitions of the bot that installed the plugin.
18
+ * This mean the Plugin typings should allow for unknown types.
19
+ */
20
+ unknownDefinitions: boolean;
21
+ };
22
+ export type InputBaseBot = utils.DeepPartial<BaseBot>;
23
+ export type DefaultBot<B extends InputBaseBot> = {
24
+ events: utils.Default<B['events'], BaseBot['events']>;
25
+ states: utils.Default<B['states'], BaseBot['states']>;
26
+ actions: utils.Default<B['actions'], BaseBot['actions']>;
27
+ unknownDefinitions: utils.Default<B['unknownDefinitions'], BaseBot['unknownDefinitions']>;
28
+ integrations: undefined extends B['integrations'] ? BaseBot['integrations'] : {
29
+ [K in keyof B['integrations']]: DefaultIntegration<utils.Cast<B['integrations'][K], InputBaseIntegration>>;
30
+ };
31
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export * from './generic';
2
+ export * from './common';
@@ -0,0 +1,8 @@
1
+ export declare const botIdHeader = "x-bot-id";
2
+ export declare const botUserIdHeader = "x-bot-user-id";
3
+ export declare const integrationIdHeader = "x-integration-id";
4
+ export declare const webhookIdHeader = "x-webhook-id";
5
+ export declare const configurationTypeHeader = "x-bp-configuration-type";
6
+ export declare const configurationHeader = "x-bp-configuration";
7
+ export declare const operationHeader = "x-bp-operation";
8
+ export declare const typeHeader = "x-bp-type";
@@ -0,0 +1,108 @@
1
+ import { DefaultBot } from './bot/types/generic';
2
+ import { DefaultChannel, DefaultIntegration } from './integration/types/generic';
3
+ import { DefaultPlugin } from './plugin/types/generic';
4
+ type _FooBarBazIntegration = {
5
+ actions: {
6
+ doFoo: {
7
+ input: {
8
+ inputFoo: string;
9
+ };
10
+ output: {
11
+ outputFoo: string;
12
+ };
13
+ };
14
+ doBar: {
15
+ input: {
16
+ inputBar: number;
17
+ };
18
+ output: {
19
+ outputBar: number;
20
+ };
21
+ };
22
+ doBaz: {
23
+ input: {
24
+ inputBaz: boolean;
25
+ };
26
+ output: {
27
+ outputBaz: boolean;
28
+ };
29
+ };
30
+ };
31
+ events: {
32
+ onFoo: {
33
+ eventFoo: string;
34
+ };
35
+ onBar: {
36
+ eventBar: number;
37
+ };
38
+ onBaz: {
39
+ eventBaz: boolean;
40
+ };
41
+ };
42
+ channels: {
43
+ channelFoo: DefaultChannel<{
44
+ messages: {
45
+ messageFoo: {
46
+ foo: string;
47
+ };
48
+ };
49
+ }>;
50
+ channelBar: DefaultChannel<{
51
+ messages: {
52
+ messageBar: {
53
+ bar: number;
54
+ };
55
+ };
56
+ }>;
57
+ channelBaz: DefaultChannel<{
58
+ messages: {
59
+ messageBaz: {
60
+ baz: boolean;
61
+ };
62
+ };
63
+ }>;
64
+ };
65
+ };
66
+ export type FooBarBazIntegration = DefaultIntegration<_FooBarBazIntegration>;
67
+ export type FooBarBazBot = DefaultBot<{
68
+ integrations: {
69
+ fooBarBaz: _FooBarBazIntegration;
70
+ };
71
+ actions: {
72
+ act: {
73
+ input: {
74
+ arguments: Record<string, unknown>;
75
+ };
76
+ output: {
77
+ result: unknown;
78
+ };
79
+ };
80
+ };
81
+ }>;
82
+ export type FooBarBazPlugin = DefaultPlugin<{
83
+ integrations: {
84
+ fooBarBaz: _FooBarBazIntegration;
85
+ };
86
+ actions: {
87
+ act: {
88
+ input: {
89
+ arguments: Record<string, unknown>;
90
+ };
91
+ output: {
92
+ result: unknown;
93
+ };
94
+ };
95
+ };
96
+ }>;
97
+ export type EmptyBot = DefaultBot<{
98
+ integrations: {};
99
+ events: {};
100
+ states: {};
101
+ actions: {};
102
+ }>;
103
+ export type EmptyPlugin = DefaultPlugin<{
104
+ integrations: {};
105
+ actions: {};
106
+ events: {};
107
+ }>;
108
+ export {};
@@ -0,0 +1,15 @@
1
+ export * as messages from './message';
2
+ export * from './const';
3
+ export * from './serve';
4
+ export * from './zui';
5
+ export { isApiError, RuntimeError, } from '@botpress/client';
6
+ export { DefaultIntegration, IntegrationDefinition, IntegrationDefinitionProps, IntegrationImplementation as Integration, IntegrationImplementationProps as IntegrationProps, IntegrationLogger, IntegrationSpecificClient, TagDefinition, ConfigurationDefinition, AdditionalConfigurationDefinition, EventDefinition, ChannelDefinition, MessageDefinition, ActionDefinition, StateDefinition, UserDefinition, SecretDefinition, EntityDefinition, } from './integration';
7
+ export {
8
+ /**
9
+ * @deprecated use Context exported from '.botpress' instead
10
+ */
11
+ IntegrationContext, } from './integration/server';
12
+ export { DefaultBot, BotDefinition, BotDefinitionProps, BotImplementation as Bot, BotImplementationProps as BotProps, BotSpecificClient, BotHandlers, TagDefinition as BotTagDefinition, StateType as BotStateType, StateDefinition as BotStateDefinition, RecurringEventDefinition as BotRecurringEventDefinition, EventDefinition as BotEventDefinition, ConfigurationDefinition as BotConfigurationDefinition, UserDefinition as BotUserDefinition, ConversationDefinition as BotConversationDefinition, MessageDefinition as BotMessageDefinition, ActionDefinition as BotActionDefinition, BotLogger, } from './bot';
13
+ export { InterfaceDefinition, InterfaceDefinitionProps, } from './interface';
14
+ export { DefaultPlugin, PluginDefinition, PluginImplementation as Plugin, } from './plugin';
15
+ export { IntegrationPackage, InterfacePackage, PluginPackage, Package, } from './package';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var Ze=Object.create;var F=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var M=(n,e)=>{for(var t in e)F(n,t,{get:e[t],enumerable:!0})},K=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ze(e))!$e.call(n,i)&&i!==t&&F(n,i,{get:()=>e[i],enumerable:!(s=Ve(e,i))||s.enumerable});return n},f=(n,e,t)=>(K(n,e,"default"),t&&K(t,e,"default")),ce=(n,e,t)=>(t=n!=null?Ze(Je(n)):{},K(e||!n||!n.__esModule?F(t,"default",{value:n,enumerable:!0}):t,n)),We=n=>K(F({},"__esModule",{value:!0}),n);var y={};M(y,{Bot:()=>z,BotDefinition:()=>V,BotLogger:()=>x,BotSpecificClient:()=>B,Integration:()=>Z,IntegrationDefinition:()=>G,IntegrationLogger:()=>P,IntegrationSpecificClient:()=>k,InterfaceDefinition:()=>J,Plugin:()=>W,PluginDefinition:()=>$,RuntimeError:()=>q.RuntimeError,botIdHeader:()=>O,botUserIdHeader:()=>se,configurationHeader:()=>A,configurationTypeHeader:()=>ae,integrationIdHeader:()=>ie,isApiError:()=>q.isApiError,messages:()=>ne,operationHeader:()=>R,parseBody:()=>v,serve:()=>U,typeHeader:()=>re,webhookIdHeader:()=>oe});module.exports=We(y);var ne={};M(ne,{defaults:()=>et,markdown:()=>Ye});var r={};M(r,{default:()=>te});var le=require("@bpinternal/zui");f(r,require("@bpinternal/zui"));var te=le.z;var m=r.z.string().min(1),pe=r.z.object({text:m}),ue=r.z.object({markdown:m}),de=r.z.object({imageUrl:m}),fe=r.z.object({audioUrl:m}),me=r.z.object({videoUrl:m}),he=r.z.object({fileUrl:m,title:m.optional()}),ye=r.z.object({latitude:r.z.number(),longitude:r.z.number(),address:r.z.string().optional(),title:r.z.string().optional()}),Te=r.z.object({title:m,subtitle:m.optional(),imageUrl:m.optional(),actions:r.z.array(r.z.object({action:r.z.enum(["postback","url","say"]),label:m,value:m}))}),ge=r.z.object({text:m,options:r.z.array(r.z.object({label:m,value:m}))}),qe=r.z.object({items:r.z.array(Te)}),Qe=r.z.union([r.z.object({type:r.z.literal("text"),payload:pe}),r.z.object({type:r.z.literal("markdown"),payload:ue}),r.z.object({type:r.z.literal("image"),payload:de}),r.z.object({type:r.z.literal("audio"),payload:fe}),r.z.object({type:r.z.literal("video"),payload:me}),r.z.object({type:r.z.literal("file"),payload:he}),r.z.object({type:r.z.literal("location"),payload:ye})]),Xe=r.z.object({items:r.z.array(Qe)}),Ye={schema:ue},et={text:{schema:pe},image:{schema:de},audio:{schema:fe},video:{schema:me},file:{schema:he},location:{schema:ye},carousel:{schema:qe},card:{schema:Te},dropdown:{schema:ge},choice:{schema:ge},bloc:{schema:Xe}};var O="x-bot-id",se="x-bot-user-id",ie="x-integration-id",oe="x-webhook-id",ae="x-bp-configuration-type",A="x-bp-configuration",R="x-bp-operation",re="x-bp-type";var be=require("node:http");var H=console;function v(n){if(!n.body)throw new Error("Missing body");return JSON.parse(n.body)}async function U(n,e=8072,t=it){let s=(0,be.createServer)(async(i,c)=>{try{let o=await tt(i);if(o.path==="/health"){c.writeHead(200).end("ok");return}let a=await n(o);c.writeHead(a?.status??200,a?.headers??{}).end(a?.body??"{}")}catch(o){H.error("Error while handling request",{error:o?.message??"Internal error occured"}),c.writeHead(500).end(JSON.stringify({error:o?.message??"Internal error occured"}))}});return s.listen(e,()=>t(e)),s}async function tt(n){let e=await st(n),t={};for(let i=0;i<n.rawHeaders.length;i+=2){let c=n.rawHeaders[i].toLowerCase(),o=n.rawHeaders[i+1];t[c]=o}let s=new URL(n.url??"",n.headers.host?`http://${n.headers.host}`:"http://botpress.cloud");return{body:e,path:s.pathname,query:nt(s.search,"?"),headers:t,method:n.method?.toUpperCase()??"GET"}}function nt(n,e){return n.indexOf(e)===0?n.slice(e.length):n}async function st(n){return new Promise((e,t)=>{if(n.method!=="POST"&&n.method!=="PUT"&&n.method!=="PATCH")return e(void 0);let s="";n.on("data",i=>s+=i.toString()),n.on("error",i=>t(i)),n.on("end",()=>e(s))})}function it(n){H.info(`Listening on port ${n}`)}f(y,r,module.exports);var q=require("@botpress/client");var h={};M(h,{mapValues:()=>at,pairs:()=>ve,values:()=>ot});var ve=n=>Object.entries(n),ot=n=>Object.values(n),at=(n,e)=>Object.fromEntries(ve(n).map(([t,s])=>[t,e(s,t)]));var l={};M(l,{safePush:()=>rt});var rt=(n,...e)=>n?[...n,...e]:[...e];var j=Symbol("schemaName"),Be=n=>n?h.mapValues(n,(t,s)=>({...t,[j]:s})):{},_e=n=>j in n&&n[j]!==void 0,Pe=n=>n[j];var G=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.configurations=e.configurations,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities,this.interfaces=e.interfaces}name;version;title;description;icon;readme;configuration;configurations;events;actions;channels;states;user;secrets;identifier;entities;interfaces;extend(e,t){let s=t(Be(this.entities)),i=h.pairs(s).find(([g,d])=>!_e(d));if(i)throw new Error(`Cannot extend interface "${e.name}" with entity "${i[0]}"; the provided schema is not part of the integration's entities.`);let c=this;c.interfaces??={};let o=h.mapValues(s,g=>({name:Pe(g),schema:g.schema})),a=Object.values(o).map(g=>g.name),p=a.length===0?e.name:`${e.name}<${a.join(",")}>`;return c.interfaces[p]={...e,entities:o},this}};var I=require("@botpress/client");var xe=require("@botpress/client"),N={retries:3,retryCondition:n=>xe.axiosRetry.isNetworkOrIdempotentRequestError(n)||[429,502].includes(n.response?.status??0),retryDelay:n=>n*1e3};var k=class{constructor(e){this._client=e}createConversation=e=>this._client.createConversation(e);getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);createEvent=e=>this._client.createEvent(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);createUser=e=>this._client.createUser(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);getOrCreateUser=e=>this._client.getOrCreateUser(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e);setState=e=>this._client.setState(e);getOrSetState=e=>this._client.getOrSetState(e);patchState=e=>this._client.patchState(e);configureIntegration=e=>this._client.configureIntegration(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e)};var L=class{_cost=0;get cost(){return this._cost}setCost(e){this._cost=e}toJSON(){return{cost:this.cost}}};var Ie=require("@bpinternal/zui");var ct=Ie.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),Ee=n=>{let e=n[O],t=n[se],s=n[ie],i=n[oe],c=n[ae],o=n[A],a=ct.parse(n[R]);if(!e)throw new Error("Missing bot headers");if(!t)throw new Error("Missing bot user headers");if(!s)throw new Error("Missing integration headers");if(!i)throw new Error("Missing webhook headers");if(!o)throw new Error("Missing configuration headers");if(!a)throw new Error("Missing operation headers");return{botId:e,botUserId:t,integrationId:s,webhookId:i,operation:a,configurationType:c??null,configuration:o?JSON.parse(Buffer.from(o,"base64").toString("utf-8")):{}}};var He=ce(require("util")),S=class{defaultOptions;constructor(e){this.defaultOptions=e}info(...e){this._log("info",e)}debug(...e){this._log("debug",e)}warn(...e){this._log("warn",e)}error(...e){this._log("error",e)}_log(e,t){this._getConsoleMethod(e)(this._serializeMessage(t))}_serializeMessage(e){let t=He.default.format(...e);return process.env.BP_LOG_FORMAT==="json"?this.getJsonMessage(t):t}getJsonMessage(e){return JSON.stringify({msg:e,options:this.defaultOptions})}_getConsoleMethod(e){switch(e){case"debug":return console.debug;case"warn":return console.warn;case"error":return console.error;default:return console.info}}};var P=class extends S{constructor(e){super({visibleToBotOwners:!0,...e})}with(e){return new P({...this.defaultOptions,...e})}withUserID(e){return this.with({userID:e})}withConversationID(e){return this.with({conversationID:e})}withVisibleToBotOwners(e){return this.with({visibleToBotOwners:e})}forBot(){return this.withVisibleToBotOwners(!0)}getJsonMessage(e){return JSON.stringify({msg:e,visible_to_bot_owner:this.defaultOptions.visibleToBotOwners,options:this.defaultOptions})}};var Ce=n=>async e=>{let t=Ee(e.headers),s=new I.Client({botId:t.botId,integrationId:t.integrationId,retry:N}),i=new k(s),c=new P,o={ctx:t,req:e,client:i,logger:c,instance:n};try{let a;switch(t.operation){case"webhook_received":a=await gt(o);break;case"register":a=await pt(o);break;case"unregister":a=await ut(o);break;case"message_created":a=await mt(o);break;case"action_triggered":a=await ht(o);break;case"ping":a=await lt(o);break;case"create_user":a=await dt(o);break;case"create_conversation":a=await ft(o);break;default:throw new Error(`Unknown operation ${t.operation}`)}return a?{...a,status:a.status??200}:{status:200}}catch(a){if((0,I.isApiError)(a)){let g=new I.RuntimeError(a.message,a);return c.forBot().error(g.message),{status:g.code,body:JSON.stringify(g.toJSON())}}console.error(a);let p=new I.RuntimeError("An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.");return c.forBot().error(p.message),{status:p.code,body:JSON.stringify(p.toJSON())}}},lt=async n=>{},gt=async({client:n,ctx:e,req:t,logger:s,instance:i})=>{let{req:c}=v(t);return i.webhook({client:n,ctx:e,req:c,logger:s})},pt=async({client:n,ctx:e,req:t,logger:s,instance:i})=>{if(!i.register)return;let{webhookUrl:c}=v(t);await i.register({client:n,ctx:e,webhookUrl:c,logger:s})},ut=async({client:n,ctx:e,req:t,logger:s,instance:i})=>{if(!i.unregister)return;let{webhookUrl:c}=v(t);await i.unregister({ctx:e,webhookUrl:c,client:n,logger:s})},dt=async({client:n,ctx:e,req:t,logger:s,instance:i})=>{if(!i.createUser)return;let{tags:c}=v(t);return await i.createUser({ctx:e,client:n,tags:c,logger:s})},ft=async({client:n,ctx:e,req:t,logger:s,instance:i})=>{if(!i.createConversation)return;let{channel:c,tags:o}=v(t);return await i.createConversation({ctx:e,client:n,channel:c,tags:o,logger:s})},mt=async({ctx:n,req:e,client:t,logger:s,instance:i})=>{let{conversation:c,user:o,type:a,payload:p,message:g}=v(e),d=i.channels[c.channel];if(!d)throw new Error(`Channel ${c.channel} not found`);let T=d.messages[a];if(!T)throw new Error(`Message of type ${a} not found in channel ${c.channel}`);await T({ctx:n,conversation:c,message:g,user:o,type:a,client:t,payload:p,ack:async({tags:Q})=>{await t.updateMessage({id:g.id,tags:Q})},logger:s})},ht=async({req:n,ctx:e,client:t,logger:s,instance:i})=>{let{input:c,type:o}=v(n);if(!o)throw new Error("Missing action type");let a=i.actions[o];if(!a)throw new Error(`Action ${o} not found`);let p=new L,d={output:await a({ctx:e,input:c,client:t,type:o,logger:s,metadata:p}),meta:p.toJSON()};return{body:JSON.stringify(d)}};var Z=class{constructor(e){this.props=e;this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}actions;channels;register;unregister;createUser;createConversation;webhook;handler=Ce(this);start=e=>U(this.handler,e)};var V=class{constructor(e){this.props=e;this.integrations=e.integrations,this.plugins=e.plugins,this.user=e.user,this.conversation=e.conversation,this.message=e.message,this.states=e.states,this.configuration=e.configuration,this.events=e.events,this.recurringEvents=e.recurringEvents,this.actions=e.actions}integrations;plugins;user;conversation;message;states;configuration;events;recurringEvents;actions;addIntegration(e,t){let s=this;return s.integrations||(s.integrations={}),s.integrations[e.name]={enabled:t.enabled,...e,configurationType:t.configurationType,configuration:t.configuration},this}addPlugin(e,t){let s=this;return s.plugins||(s.plugins={}),s.plugins[e.name]={...e,configuration:t.configuration,interfaces:t.interfaces},s.user=this._mergeUser(s.user,e.definition.user),s.conversation=this._mergeConversation(s.conversation,e.definition.conversation),s.message=this._mergeMessage(s.message,e.definition.message),s.states=this._mergeStates(s.states,e.definition.states),s.events=this._mergeEvents(s.events,e.definition.events),s.recurringEvents=this._mergeRecurringEvents(s.recurringEvents,e.definition.recurringEvents),s.actions=this._mergeActions(s.actions,e.definition.actions),this}_mergeUser=(e,t)=>({tags:{...e?.tags,...t?.tags}});_mergeConversation=(e,t)=>({tags:{...e?.tags,...t?.tags}});_mergeMessage=(e,t)=>({tags:{...e?.tags,...t?.tags}});_mergeStates=(e,t)=>({...e,...t});_mergeEvents=(e,t)=>({...e,...t});_mergeRecurringEvents=(e,t)=>({...e,...t});_mergeActions=(e,t)=>({...e,...t})};var ke=(n,e)=>{for(let[t,s]of Object.entries(e.actionHandlers))n.actionHandlers[t]=s;for(let[t,s]of Object.entries(e.eventHandlers))s&&(n.eventHandlers[t]=l.safePush(n.eventHandlers[t],...s));for(let[t,s]of Object.entries(e.messageHandlers))s&&(n.messageHandlers[t]=l.safePush(n.messageHandlers[t],...s));for(let[t,s]of Object.entries(e.stateExpiredHandlers))s&&(n.stateExpiredHandlers[t]=l.safePush(n.stateExpiredHandlers[t],...s));for(let[t,s]of Object.entries(e.hookHandlers))for(let[i,c]of Object.entries(s))c&&(n.hookHandlers[t][i]=l.safePush(n.hookHandlers[t][i],...c))};var we=ce(require("@botpress/client"));var x=class extends S{constructor(e){super({...e})}with(e){return new x({...this.defaultOptions,...e})}withUserID(e){return this.with({userID:e})}withConversationID(e){return this.with({conversationID:e})}withWorkflowID(e){return this.with({workflowID:e})}};var B=class{constructor(e,t={before:{},after:{}}){this._client=e;this._hooks=t}getConversation=e=>this._run("getConversation",e);listConversations=e=>this._run("listConversations",e);updateConversation=e=>this._run("updateConversation",e);deleteConversation=e=>this._run("deleteConversation",e);listParticipants=e=>this._run("listParticipants",e);addParticipant=e=>this._run("addParticipant",e);getParticipant=e=>this._run("getParticipant",e);removeParticipant=e=>this._run("removeParticipant",e);getEvent=e=>this._run("getEvent",e);listEvents=e=>this._run("listEvents",e);createMessage=e=>this._run("createMessage",e);getOrCreateMessage=e=>this._run("getOrCreateMessage",e);getMessage=e=>this._run("getMessage",e);updateMessage=e=>this._run("updateMessage",e);listMessages=e=>this._run("listMessages",e);deleteMessage=e=>this._run("deleteMessage",e);getUser=e=>this._run("getUser",e);listUsers=e=>this._run("listUsers",e);updateUser=e=>this._run("updateUser",e);deleteUser=e=>this._run("deleteUser",e);getState=e=>this._run("getState",e);setState=e=>this._run("setState",e);getOrSetState=e=>this._run("getOrSetState",e);patchState=e=>this._run("patchState",e);callAction=e=>this._run("callAction",e);uploadFile=e=>this._run("uploadFile",e);upsertFile=e=>this._run("upsertFile",e);deleteFile=e=>this._run("deleteFile",e);listFiles=e=>this._run("listFiles",e);getFile=e=>this._run("getFile",e);updateFileMetadata=e=>this._run("updateFileMetadata",e);searchFiles=e=>this._run("searchFiles",e);trackAnalytics=e=>this._run("trackAnalytics",e);createConversation=e=>this._client.createConversation(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);createUser=e=>this._client.createUser(e);getOrCreateUser=e=>this._client.getOrCreateUser(e);_run=async(e,t)=>{let s=this._hooks.before[e];s&&(t=await s(t));let i=await this._client[e](t),c=this._hooks.after[e];return c&&(i=await c(i)),i}};var Se=require("@bpinternal/zui");var yt=Se.z.enum(["event_received","register","unregister","ping","action_triggered"]),De=n=>{let e=n[O],t=n[A],s=n[re],i=yt.parse(n[R]);if(!e)throw new Error("Missing bot headers");if(!s)throw new Error("Missing type headers");if(!t)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,operation:i,type:s,configuration:t?JSON.parse(Buffer.from(t,"base64").toString("utf-8")):{}}};var _={status:200},Me=n=>async e=>{let t=De(e.headers),s=new x,i=new we.Client({botId:t.botId,retry:N}),c=new B(i,{before:{createMessage:async a=>{let p=n.hookHandlers.before_outgoing_message[a.type]??[],g=n.hookHandlers.before_outgoing_message["*"]??[],d=[...p,...g];for(let T of d)a=(await T({client:new B(i),ctx:t,logger:s,data:a}))?.data??a;return a},callAction:async a=>{let p=n.hookHandlers.before_outgoing_call_action[a.type]??[],g=n.hookHandlers.before_outgoing_call_action["*"]??[],d=[...p,...g];for(let T of d)a=(await T({client:new B(i),ctx:t,logger:s,data:a}))?.data??a;return a}},after:{createMessage:async a=>{let p=n.hookHandlers.after_outgoing_message[a.message.type]??[],g=n.hookHandlers.after_outgoing_message["*"]??[],d=[...p,...g];for(let T of d)a=(await T({client:new B(i),ctx:t,logger:s,data:a}))?.data??a;return a},callAction:async a=>{let p=n.hookHandlers.after_outgoing_call_action[a.output.type]??[],g=n.hookHandlers.after_outgoing_call_action["*"]??[],d=[...p,...g];for(let T of d)a=(await T({client:new B(i),ctx:t,logger:s,data:a}))?.data??a;return a}}}),o={req:e,ctx:t,logger:s,client:c,self:n};switch(t.operation){case"action_triggered":return await _t(o);case"event_received":return await Bt(o);case"register":return await bt(o);case"unregister":return await vt(o);case"ping":return await Tt(o);default:throw new Error(`Unknown operation ${t.operation}`)}},Tt=async({ctx:n})=>(H.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`),_),bt=async n=>_,vt=async n=>_,Bt=async({ctx:n,logger:e,req:t,client:s,self:i})=>{H.debug(`Received event ${n.type}`);let c=v(t);if(n.type==="message_created"){let b=c.event,u=b.payload.message,X=i.hookHandlers.before_incoming_message[u.type]??[],Y=i.hookHandlers.before_incoming_message["*"]??[],ee=[...X,...Y];for(let D of ee){let w=await D({client:s,ctx:n,logger:e,data:u});if(u=w?.data??u,w?.stop)return _}let Ue={user:b.payload.user,conversation:b.payload.conversation,states:b.payload.states,message:u,event:b},Ke=i.messageHandlers[u.type]??[],Fe=i.messageHandlers["*"]??[],je=[...Ke,...Fe];for(let D of je)await D({...Ue,client:s,ctx:n,logger:e});let Ge=i.hookHandlers.after_incoming_message[u.type]??[],Ne=i.hookHandlers.after_incoming_message["*"]??[],Le=[...Ge,...Ne];for(let D of Le){let w=await D({client:s,ctx:n,data:u,logger:e});if(u=w?.data??u,w?.stop)return _}return _}if(n.type==="state_expired"){let X={state:c.event.payload.state},Y=i.stateExpiredHandlers["*"]??[];for(let ee of Y)await ee({...X,client:s,ctx:n,logger:e});return _}let o=c.event,a=i.hookHandlers.before_incoming_event[o.type]??[],p=i.hookHandlers.before_incoming_event["*"]??[],g=[...a,...p];for(let b of g){let u=await b({client:s,ctx:n,data:o,logger:e});if(o=u?.data??o,u?.stop)return _}let d={event:o},T=i.eventHandlers[o.type]??[],E=i.eventHandlers["*"]??[],Q=[...T,...E];for(let b of Q)await b({...d,client:s,ctx:n,logger:e});let Oe=i.hookHandlers.after_incoming_event[o.type]??[],Ae=i.hookHandlers.after_incoming_event["*"]??[],Re=[...Oe,...Ae];for(let b of Re){let u=await b({client:s,ctx:n,data:o,logger:e});if(o=u?.data??o,u?.stop)return _}return _},_t=async({ctx:n,logger:e,req:t,client:s,self:i})=>{let{input:c,type:o}=v(t);if(!o)throw new Error("Missing action type");let a=i.actionHandlers[o];if(!a)throw new Error(`Action ${o} not found`);let g={output:await a({ctx:n,logger:e,input:c,client:s,type:o})};return{status:200,body:JSON.stringify(g)}};var z=class{constructor(e){this.props=e;this.actionHandlers=e.actions;let t=h.values(e.plugins);for(let s of t)this._use(s)}actionHandlers;messageHandlers={};eventHandlers={};stateExpiredHandlers={};hookHandlers={before_incoming_event:{},before_incoming_message:{},before_outgoing_message:{},before_outgoing_call_action:{},after_incoming_event:{},after_incoming_message:{},after_outgoing_message:{},after_outgoing_call_action:{}};get actions(){return this.actionHandlers}on={message:(e,t)=>{this.messageHandlers[e]=l.safePush(this.messageHandlers[e],t)},event:(e,t)=>{this.eventHandlers[e]=l.safePush(this.eventHandlers[e],t)},stateExpired:(e,t)=>{this.stateExpiredHandlers[e]=l.safePush(this.stateExpiredHandlers[e],t)},beforeIncomingEvent:(e,t)=>{this.hookHandlers.before_incoming_event[e]=l.safePush(this.hookHandlers.before_incoming_event[e],t)},beforeIncomingMessage:(e,t)=>{this.hookHandlers.before_incoming_message[e]=l.safePush(this.hookHandlers.before_incoming_message[e],t)},beforeOutgoingMessage:(e,t)=>{this.hookHandlers.before_outgoing_message[e]=l.safePush(this.hookHandlers.before_outgoing_message[e],t)},beforeOutgoingCallAction:(e,t)=>{this.hookHandlers.before_outgoing_call_action[e]=l.safePush(this.hookHandlers.before_outgoing_call_action[e],t)},afterIncomingEvent:(e,t)=>{this.hookHandlers.after_incoming_event[e]=l.safePush(this.hookHandlers.after_incoming_event[e],t)},afterIncomingMessage:(e,t)=>{this.hookHandlers.after_incoming_message[e]=l.safePush(this.hookHandlers.after_incoming_message[e],t)},afterOutgoingMessage:(e,t)=>{this.hookHandlers.after_outgoing_message[e]=l.safePush(this.hookHandlers.after_outgoing_message[e],t)},afterOutgoingCallAction:(e,t)=>{this.hookHandlers.after_outgoing_call_action[e]=l.safePush(this.hookHandlers.after_outgoing_call_action[e],t)}};_use=e=>{ke(this,e)};handler=Me(this);start=e=>U(this.handler,e)};var J=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.entities=e.entities??{},this.templateName=e.templateName;let t=this._getEntityReference(this.entities),s=e.events===void 0?{}:h.mapValues(e.events,o=>({...o,schema:o.schema(t)})),i=e.actions===void 0?{}:h.mapValues(e.actions,o=>({...o,input:{...o.input,schema:o.input.schema(t)},output:{...o.output,schema:o.output.schema(t)}})),c=e.channels===void 0?{}:h.mapValues(e.channels,o=>({...o,messages:h.mapValues(o.messages,a=>({...a,schema:a.schema(t)}))}));this.events=s,this.actions=i,this.channels=c}name;version;entities;events;actions;channels;templateName;_getEntityReference=e=>{let t={};for(let[s,i]of Object.entries(e)){let c=i.schema._def["x-zui"]?.title,o=i.schema._def.description,a=te.ref(s);c&&a.title(c),o&&a.describe(o),t[s]=a}return t}};var $=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.integrations=e.integrations,this.interfaces=e.interfaces,this.user=e.user,this.conversation=e.conversation,this.message=e.message,this.states=e.states,this.configuration=e.configuration,this.events=e.events,this.recurringEvents=e.recurringEvents,this.actions=e.actions}name;version;integrations;interfaces;user;conversation;message;states;configuration;events;recurringEvents;actions};var W=class{constructor(e){this.props=e;this.actionHandlers=e.actions}_runtimeProps;actionHandlers;messageHandlers={};eventHandlers={};stateExpiredHandlers={};hookHandlers={before_incoming_event:{},before_incoming_message:{},before_outgoing_message:{},before_outgoing_call_action:{},after_incoming_event:{},after_incoming_message:{},after_outgoing_message:{},after_outgoing_call_action:{}};initialize(e){return this._runtimeProps=e,this}get config(){if(!this._runtimeProps)throw new Error("Plugin not correctly initialized. This is likely because you access your plugin config outside of an handler.");return this._runtimeProps}on={message:(e,t)=>{this.messageHandlers[e]=l.safePush(this.messageHandlers[e],t)},event:(e,t)=>{this.eventHandlers[e]=l.safePush(this.eventHandlers[e],t)},stateExpired:(e,t)=>{this.stateExpiredHandlers[e]=l.safePush(this.stateExpiredHandlers[e],t)},beforeIncomingEvent:(e,t)=>{this.hookHandlers.before_incoming_event[e]=l.safePush(this.hookHandlers.before_incoming_event[e],t)},beforeIncomingMessage:(e,t)=>{this.hookHandlers.before_incoming_message[e]=l.safePush(this.hookHandlers.before_incoming_message[e],t)},beforeOutgoingMessage:(e,t)=>{this.hookHandlers.before_outgoing_message[e]=l.safePush(this.hookHandlers.before_outgoing_message[e],t)},beforeOutgoingCallAction:(e,t)=>{this.hookHandlers.before_outgoing_call_action[e]=l.safePush(this.hookHandlers.before_outgoing_call_action[e],t)},afterIncomingEvent:(e,t)=>{this.hookHandlers.after_incoming_event[e]=l.safePush(this.hookHandlers.after_incoming_event[e],t)},afterIncomingMessage:(e,t)=>{this.hookHandlers.after_incoming_message[e]=l.safePush(this.hookHandlers.after_incoming_message[e],t)},afterOutgoingMessage:(e,t)=>{this.hookHandlers.after_outgoing_message[e]=l.safePush(this.hookHandlers.after_outgoing_message[e],t)},afterOutgoingCallAction:(e,t)=>{this.hookHandlers.after_outgoing_call_action[e]=l.safePush(this.hookHandlers.after_outgoing_call_action[e],t)}}};0&&(module.exports={Bot,BotDefinition,BotLogger,BotSpecificClient,Integration,IntegrationDefinition,IntegrationLogger,IntegrationSpecificClient,InterfaceDefinition,Plugin,PluginDefinition,RuntimeError,botIdHeader,botUserIdHeader,configurationHeader,configurationTypeHeader,integrationIdHeader,isApiError,messages,operationHeader,parseBody,serve,typeHeader,webhookIdHeader});
2
+ //# sourceMappingURL=index.js.map