@botpress/sdk 0.8.28 → 0.8.30

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/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/context.ts", "../src/integration/definition.ts", "../src/integration/server.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.ts", "../src/bot/server.ts", "../src/bot/client/index.ts", "../src/bot/context.ts", "../src/bot/implementation.ts"],
4
- "sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport { isApiError, RuntimeError } from '@botpress/client'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationSpecificClient,\n TagDefinition,\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nconst blocSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('text'), payload: textMessageSchema }),\n z.object({ type: z.literal('markdown'), payload: markdownMessageSchema }),\n z.object({ type: z.literal('image'), payload: imageMessageSchema }),\n z.object({ type: z.literal('audio'), payload: audioMessageSchema }),\n z.object({ type: z.literal('video'), payload: videoMessageSchema }),\n z.object({ type: z.literal('file'), payload: fileMessageSchema }),\n z.object({ type: z.literal('location'), payload: locationMessageSchema }),\n])\n\nconst blocsSchema = z.object({\n items: z.array(blocSchema),\n})\n\nexport const defaults = {\n text: { schema: textMessageSchema },\n markdown: { schema: markdownMessageSchema },\n image: { schema: imageMessageSchema },\n audio: { schema: audioMessageSchema },\n video: { schema: videoMessageSchema },\n file: { schema: fileMessageSchema },\n location: { schema: locationMessageSchema },\n carousel: { schema: carouselSchema },\n card: { schema: cardSchema },\n dropdown: { schema: choiceSchema },\n choice: { schema: choiceSchema },\n bloc: { schema: blocsSchema },\n} as const // should use satisfies operator but this works for older versions of TS\n", "import { z, type UIComponentDefinitions, type DefaultComponentDefinitions } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nconst commonInputParams = z.object({\n allowDynamicVariable: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n})\n\nexport const studioComponentDefinitions = {\n string: {\n text: {\n id: 'text',\n params: commonInputParams.extend({\n multiLine: z.boolean().optional(),\n growVertically: z.boolean().optional(),\n suggestions: z.array(z.string()).optional(),\n }),\n },\n dropdown: {\n id: 'dropdown',\n params: commonInputParams.extend({\n filterable: z.boolean().optional(),\n }),\n },\n radiogroup: {\n id: 'radiogroup',\n params: commonInputParams.extend({}),\n },\n date: {\n id: 'date',\n params: commonInputParams.extend({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n disableTimezoneSelection: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showShortcutButtons: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n time: {\n id: 'time',\n params: commonInputParams.extend({\n useAMPM: z.boolean().optional(),\n timeFormat: z.string().optional(),\n minTime: z.string().optional(),\n maxTime: z.string().optional(),\n showArrowButtons: z.boolean().optional(),\n precision: z.enum(['minute', 'second', 'millisecond']).optional(),\n }),\n },\n richtext: {\n id: 'richtext',\n params: z.object({\n allowDynamicVariable: z.boolean().optional(),\n resizable: z.boolean().optional(),\n }),\n },\n json: {\n id: 'json',\n params: commonInputParams.extend({\n showPreview: z.boolean().optional(),\n showValidationError: z.boolean().optional(),\n }),\n },\n file: {\n id: 'file',\n params: commonInputParams.extend({\n fileTypes: z.array(z.enum(['image', 'audio', 'video'])).optional(),\n showUploadedFiles: z.boolean().optional(),\n }),\n },\n },\n number: {\n number: {\n id: 'number',\n params: commonInputParams.extend({\n allowNumericCharactersOnly: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n slider: {\n id: 'slider',\n params: z.object({\n horizontal: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n },\n boolean: {\n switch: {\n id: 'switch',\n params: commonInputParams,\n },\n },\n array: {\n options: {\n id: 'options',\n params: commonInputParams,\n },\n strings: {\n id: 'strings',\n params: commonInputParams,\n },\n daterange: {\n id: 'daterange',\n params: z.object({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n allowSingleDayRange: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n },\n object: {\n collapsible: {\n id: 'collapsible',\n params: z.object({\n defaultOpen: z.boolean().optional(),\n }),\n },\n modal: {\n id: 'modal',\n params: z.object({\n title: z.string().optional(),\n buttonLabel: z.string().optional(),\n closeButtonLabel: z.string().optional(),\n }),\n },\n popover: {\n id: 'popover',\n params: z.object({\n buttonLabel: z.string().optional(),\n }),\n },\n },\n discriminatedUnion: {},\n} as const satisfies UIComponentDefinitions\n\nexport type UI<Namespace extends 'studio' | 'dashboard' = 'studio'> = Namespace extends 'studio'\n ? typeof studioComponentDefinitions\n : Namespace extends 'dashboard'\n ? DefaultComponentDefinitions\n : any\n\nexport default z\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { SchemaDefinition } from '../schema'\nimport { AnyZodObject } from '../type-utils'\n\ntype BaseConfig = AnyZodObject\ntype BaseEvents = Record<string, AnyZodObject>\ntype BaseActions = Record<string, AnyZodObject>\ntype BaseMessages = Record<string, AnyZodObject>\ntype BaseChannels = Record<string, BaseMessages>\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEntities = Record<string, AnyZodObject>\n\nexport type TagDefinition = {\n title?: string\n description?: string\n}\n\nexport type ConfigurationDefinition<TConfig extends BaseConfig = BaseConfig> = SchemaDefinition<TConfig> & {\n identifier?: {\n required?: boolean\n linkTemplateScript?: string\n }\n}\n\nexport type EventDefinition<TEvent extends BaseEvents[string] = BaseEvents[string]> = SchemaDefinition<TEvent> & {\n title?: string\n description?: string\n}\n\nexport type MessageDefinition<TMessage extends BaseMessages[string] = BaseMessages[string]> = SchemaDefinition<TMessage>\n\nexport type ChannelDefinition<TChannel extends BaseChannels[string] = BaseChannels[string]> = {\n title?: string\n description?: string\n messages: {\n [K in keyof TChannel]: MessageDefinition<TChannel[K]>\n }\n message?: {\n tags?: Record<string, TagDefinition>\n }\n conversation?: Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n }>\n}\n\nexport type ActionDefinition<TAction extends BaseActions[string] = BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<AnyZodObject> // cannot infer both input and output types (typescript limitation)\n}\n\nexport type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = SchemaDefinition<TState> & {\n type: 'integration' | 'conversation' | 'user'\n}\n\nexport type UserDefinition = Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n}>\n\nexport type SecretDefinition = {\n optional?: boolean\n description?: string\n}\n\nexport type EntityDefinition<TEntity extends BaseEntities[string] = BaseEntities[string]> =\n SchemaDefinition<TEntity> & {\n title?: string\n description?: string\n }\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public clone(\n props: Partial<IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>>\n ): IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities> {\n return new IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities>({\n ...this,\n ...props,\n })\n }\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n}\n", "import { isApiError, Client, type Conversation, type Message, type User, RuntimeError } from '@botpress/client'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration['configuration']>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags']>\n}\n\ntype CreateUserArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & CreateUserPayload<TIntegration>\n\ntype CreateConversationPayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'] = keyof TIntegration['channels']\n> = {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n}\n\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags']>\n }\n >\n}\n\ntype MessageArgs<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = CommonArgs<TIntegration> &\n MessagePayload<TIntegration, TChannel, TMessage> & {\n ack: (props: { tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']> }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (thrown) {\n if (isApiError(thrown)) {\n const runtimeError = new RuntimeError(thrown.message, thrown)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n throw thrown\n }\n }\n\nconst onPing = async <TIntegration extends BaseIntegration>(_: ServerProps<TIntegration>) => {}\n\nconst onWebhook = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req: incomingRequest,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<TIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<TIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async <TIntegration extends BaseIntegration>({\n ctx,\n req,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<TIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this.client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this.client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this.client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this.client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this.client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this.client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this.client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this.client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this.client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this.client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this.client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this.client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this.client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this.client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this.client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this.client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this.client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this.client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this.client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this.client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this.client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this.client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this.client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this.client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this.client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this.client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this.client.configureIntegration(x)\n\n public uploadFile: routes.UploadFile<TIntegration> = (x) => this.client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TIntegration> = (x) => this.client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TIntegration> = (x) => this.client.deleteFile(x)\n public listFiles: routes.ListFiles<TIntegration> = (x) => this.client.listFiles(x)\n public getFile: routes.GetFile<TIntegration> = (x) => this.client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TIntegration> = (x) => this.client.updateFileMetadata(x)\n}\n", "/* eslint-disable no-console */\nimport util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\n this.props = props\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this.client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this.client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this.client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this.client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this.client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this.client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this.client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this.client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this.client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) => this.client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this.client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) => this.client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this.client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) => this.client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this.client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this.client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this.client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this.client.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this.client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this.client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this.client.callAction(x)\n\n public uploadFile: routes.UploadFile<TBot> = (x) => this.client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TBot> = (x) => this.client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TBot> = (x) => this.client.deleteFile(x)\n public listFiles: routes.ListFiles<TBot> = (x) => this.client.listFiles(x)\n public getFile: routes.GetFile<TBot> = (x) => this.client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TBot> = (x) => this.client.updateFileMetadata(x)\n public searchFiles: routes.SearchFiles<TBot> = (x) => this.client.searchFiles(x)\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: routes.CreateConversation<TBot> = (x) => this.client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: routes.GetOrCreateConversation<TBot> = (x) => this.client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: routes.CreateUser<TBot> = (x) => this.client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: routes.GetOrCreateUser<TBot> = (x) => this.client.getOrCreateUser(x)\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext = {\n botId: string\n type: string\n operation: BotOperation\n configuration: {\n payload: string\n }\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport type { Server } from 'node:http'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject, Cast } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<Cast<K, string>>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
5
- "mappings": "mnBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,gDAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,wBAAAC,EAAA,yCAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,+BAAAC,EAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAAlB,GCAA,IAAAmB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KCAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,GAAA,+BAAAC,IAAA,IAAAC,EAAiF,2BACjFC,EAAAL,EAAc,4BAEd,IAAMM,EAAoB,IAAE,OAAO,CACjC,qBAAsB,IAAE,QAAQ,EAAE,SAAS,EAC3C,WAAY,IAAE,QAAQ,EAAE,SAAS,CACnC,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YC,EAAkD,CACnE,KAAK,MAAQA,CACf,CAEgB,QAAWC,GAA4E,CACrG,KAAK,OAAO,gBAAgB,KAAKA,CAAO,CAC1C,EACgB,MAASA,GAA0E,CACjG,KAAK,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,GAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
6
- "names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "studioComponentDefinitions", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "studioComponentDefinitions", "import_zui", "__reExport", "commonInputParams", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "defaults", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "import_node_http", "log", "parseBody", "req", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "i", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "__reExport", "src_exports", "zui_exports", "import_client", "import_zui", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "IntegrationDefinition", "props", "import_client", "IntegrationSpecificClient", "client", "x", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "client", "IntegrationSpecificClient", "props", "integrationLogger", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "thrown", "runtimeError", "_", "incomingRequest", "logger", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "client", "BotSpecificClient", "client", "x", "y", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "Bot", "props", "handler", "botHandler", "port", "serve"]
3
+ "sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/interfaces/index.ts", "../src/utils.ts", "../src/integration/definition/entity-store.ts", "../src/integration/definition/integration-definition.ts", "../src/integration/definition/interface-declaration.ts", "../src/interfaces/llm.ts", "../src/interfaces/hitl.ts", "../src/interfaces/sync.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/context.ts", "../src/integration/server.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.ts", "../src/bot/server.ts", "../src/bot/client/index.ts", "../src/bot/context.ts", "../src/bot/implementation.ts"],
4
+ "sourcesContent": ["export * as messages from './message'\nexport * as interfaces from './interfaces'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport { isApiError, RuntimeError } from '@botpress/client'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationSpecificClient,\n InterfaceDeclaration,\n InterfaceDeclarationProps,\n TagDefinition,\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nconst blocSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('text'), payload: textMessageSchema }),\n z.object({ type: z.literal('markdown'), payload: markdownMessageSchema }),\n z.object({ type: z.literal('image'), payload: imageMessageSchema }),\n z.object({ type: z.literal('audio'), payload: audioMessageSchema }),\n z.object({ type: z.literal('video'), payload: videoMessageSchema }),\n z.object({ type: z.literal('file'), payload: fileMessageSchema }),\n z.object({ type: z.literal('location'), payload: locationMessageSchema }),\n])\n\nconst blocsSchema = z.object({\n items: z.array(blocSchema),\n})\n\nexport const defaults = {\n text: { schema: textMessageSchema },\n markdown: { schema: markdownMessageSchema },\n image: { schema: imageMessageSchema },\n audio: { schema: audioMessageSchema },\n video: { schema: videoMessageSchema },\n file: { schema: fileMessageSchema },\n location: { schema: locationMessageSchema },\n carousel: { schema: carouselSchema },\n card: { schema: cardSchema },\n dropdown: { schema: choiceSchema },\n choice: { schema: choiceSchema },\n bloc: { schema: blocsSchema },\n} as const // should use satisfies operator but this works for older versions of TS\n", "import { z, type UIComponentDefinitions, type DefaultComponentDefinitions } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nconst commonInputParams = z.object({\n allowDynamicVariable: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n})\n\nexport const studioComponentDefinitions = {\n string: {\n text: {\n id: 'text',\n params: commonInputParams.extend({\n multiLine: z.boolean().optional(),\n growVertically: z.boolean().optional(),\n suggestions: z.array(z.string()).optional(),\n }),\n },\n dropdown: {\n id: 'dropdown',\n params: commonInputParams.extend({\n filterable: z.boolean().optional(),\n }),\n },\n radiogroup: {\n id: 'radiogroup',\n params: commonInputParams.extend({}),\n },\n date: {\n id: 'date',\n params: commonInputParams.extend({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n disableTimezoneSelection: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showShortcutButtons: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n time: {\n id: 'time',\n params: commonInputParams.extend({\n useAMPM: z.boolean().optional(),\n timeFormat: z.string().optional(),\n minTime: z.string().optional(),\n maxTime: z.string().optional(),\n showArrowButtons: z.boolean().optional(),\n precision: z.enum(['minute', 'second', 'millisecond']).optional(),\n }),\n },\n richtext: {\n id: 'richtext',\n params: z.object({\n allowDynamicVariable: z.boolean().optional(),\n resizable: z.boolean().optional(),\n }),\n },\n json: {\n id: 'json',\n params: commonInputParams.extend({\n showPreview: z.boolean().optional(),\n showValidationError: z.boolean().optional(),\n }),\n },\n file: {\n id: 'file',\n params: commonInputParams.extend({\n fileTypes: z.array(z.enum(['image', 'audio', 'video'])).optional(),\n showUploadedFiles: z.boolean().optional(),\n }),\n },\n },\n number: {\n number: {\n id: 'number',\n params: commonInputParams.extend({\n allowNumericCharactersOnly: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n slider: {\n id: 'slider',\n params: z.object({\n horizontal: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n },\n boolean: {\n switch: {\n id: 'switch',\n params: commonInputParams,\n },\n },\n array: {\n options: {\n id: 'options',\n params: commonInputParams,\n },\n strings: {\n id: 'strings',\n params: commonInputParams,\n },\n daterange: {\n id: 'daterange',\n params: z.object({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n allowSingleDayRange: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n },\n object: {\n collapsible: {\n id: 'collapsible',\n params: z.object({\n defaultOpen: z.boolean().optional(),\n }),\n },\n modal: {\n id: 'modal',\n params: z.object({\n title: z.string().optional(),\n buttonLabel: z.string().optional(),\n closeButtonLabel: z.string().optional(),\n }),\n },\n popover: {\n id: 'popover',\n params: z.object({\n buttonLabel: z.string().optional(),\n }),\n },\n },\n discriminatedUnion: {},\n} as const satisfies UIComponentDefinitions\n\nexport type UI<Namespace extends 'studio' | 'dashboard' = 'studio'> = Namespace extends 'studio'\n ? typeof studioComponentDefinitions\n : Namespace extends 'dashboard'\n ? DefaultComponentDefinitions\n : any\n\nexport type GenericZuiSchema<\n A extends Record<string, z.ZodTypeAny> = Record<string, z.ZodTypeAny>,\n R extends z.ZodTypeAny = z.ZodTypeAny\n> = (typeArguments: A) => R\n\nexport default z\n", "export * from './llm'\nexport * from './hitl'\nexport * from './sync'\n", "export const pairs = <K extends string, V>(obj: Record<K, V>) => Object.entries(obj) as [K, V][]\nexport const values = <K extends string, V>(obj: Record<K, V>) => Object.values(obj) as V[]\nexport const mapValues = <K extends string, V, R>(obj: Record<K, V>, fn: (value: V, key: K) => R): Record<K, R> =>\n Object.fromEntries(pairs(obj).map(([key, value]) => [key, fn(value, key)])) as Record<K, R>\n", "import { Cast } from '../../type-utils'\nimport * as utils from '../../utils'\nimport { BaseEntities } from './generic'\n\nconst entityKey = Symbol('entityKey')\n\nexport type EntityStoreProps<TEntities extends BaseEntities = BaseEntities> = {\n [K in keyof TEntities]: {\n schema: TEntities[K]\n }\n}\n\nexport type BrandedEntity<\n TEntity extends BaseEntities[string] = BaseEntities[string],\n TBrand extends string = string\n> = {\n schema: TEntity\n [entityKey]: TBrand\n}\n\nexport type EntityStore<TEntities extends BaseEntities = BaseEntities> = {\n [K in keyof TEntities]: BrandedEntity<TEntities[K], Cast<K, string>>\n}\n\nexport const createStore = <TEntities extends BaseEntities>(\n props: EntityStoreProps<TEntities> | undefined\n): EntityStore<TEntities> => {\n if (!props) {\n return {} as EntityStore<TEntities>\n }\n\n const store: EntityStore<BaseEntities> = utils.mapValues(props, (e, k) => ({ ...e, [entityKey]: k }))\n return store as EntityStore<TEntities>\n}\n\nexport const isBranded = (entity: BrandedEntity): boolean => {\n return entity[entityKey] !== undefined\n}\n\nexport const getName = (entity: BrandedEntity): string => {\n return entity[entityKey]\n}\n", "import { Writable } from '../../type-utils'\nimport * as utils from '../../utils'\nimport { EntityStore, BrandedEntity, createStore, isBranded, getName } from './entity-store'\nimport { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities } from './generic'\nimport { InterfaceDeclaration, InterfaceResolveInput } from './interface-declaration'\nimport {\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n InterfaceImplementationStatement,\n} from './types'\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\ntype InterfaceTypeArguments<TInterfaceEntities extends BaseEntities> = {\n [K in keyof TInterfaceEntities]: BrandedEntity<TInterfaceEntities[K], string>\n}\n\ntype ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (\n input: EntityStore<TIntegrationEntities>\n) => InterfaceTypeArguments<TInterfaceEntities>\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public readonly interfaces: Record<string, InterfaceImplementationStatement> = {}\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n\n public clone(\n props: Partial<IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>>\n ): IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities> {\n const clone = new IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities>({\n ...this,\n ...props,\n })\n for (const [key, value] of Object.entries(this.interfaces)) {\n clone.interfaces[key] = value\n }\n return clone\n }\n\n public extend<E extends BaseEntities>(\n interfaceDeclaration: InterfaceDeclaration<E>,\n builder: ExtensionBuilder<TEntities, E>\n ): this {\n const extensionBuilderOutput = builder(createStore(this.entities)) as Record<string, BrandedEntity>\n const unbrandedEntity = utils.pairs(extensionBuilderOutput).find(([_k, e]) => !isBranded(e))\n if (unbrandedEntity) {\n // this means the user tried providing a plain schema without referencing an entity from the integration\n throw new Error(\n `Cannot extend interface \"${interfaceDeclaration.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n\n const interfaceTypeArguments = utils.mapValues(extensionBuilderOutput, (e) => ({\n name: getName(e),\n schema: e.schema,\n }))\n\n const { resolved, implementStatement } = interfaceDeclaration.resolve({\n entities: interfaceTypeArguments as InterfaceResolveInput<E>['entities'],\n })\n\n const self = this as Writable<IntegrationDefinition>\n const { actions, events } = resolved\n self.actions = { ...(self.actions ?? {}), ...actions }\n self.events = { ...(self.events ?? {}), ...events }\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n const key = `${interfaceDeclaration.name}<${entityNames.join(',')}>`\n this.interfaces[key] = implementStatement\n\n return this\n }\n}\n", "import * as utils from '../../utils'\nimport z, { AnyZodObject, GenericZuiSchema, ZodRef } from '../../zui'\nimport { BaseActions, BaseEntities, BaseEvents } from './generic'\nimport {\n ActionDefinition,\n EntityDefinition,\n EventDefinition,\n InterfaceImplementationStatement,\n ResolvedInterface,\n} from './types'\n\ntype EntityReferences<TEntities extends BaseEntities> = {\n [K in keyof TEntities]: ZodRef\n}\n\ntype GenericEventDefinition<TEntities extends BaseEntities, TEvent extends BaseEvents[string] = BaseEvents[string]> = {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TEvent>\n}\n\ntype GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string]\n> = {\n input: { schema: GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject> }\n}\n\nexport type InterfaceTemplateNameProps<TEntities extends BaseEntities = BaseEntities> = {\n [K in keyof TEntities]: string\n}\n\nexport type InterfaceDeclarationProps<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n events: { [K in keyof TEvents]: GenericEventDefinition<TEntities, TEvents[K]> }\n\n actions: {\n [K in keyof TActions]: GenericActionDefinition<TEntities, TActions[K]>\n }\n\n entities: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n\n templateName?: (name: string, props: InterfaceTemplateNameProps<TEntities>) => string\n}\n\nexport type InterfaceResolveInput<TEntities extends BaseEntities = BaseEntities> = {\n entities: {\n [K in keyof TEntities]: {\n name: string\n schema: TEntities[K]\n }\n }\n}\n\nexport type InterfaceResolveOutput<\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents\n> = {\n resolved: ResolvedInterface<TActions, TEvents>\n implementStatement: InterfaceImplementationStatement\n}\n\nexport class InterfaceDeclaration<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly entities: this['props']['entities']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly templateName: this['props']['templateName']\n\n public constructor(public readonly props: InterfaceDeclarationProps<TEntities, TActions, TEvents>) {\n this.name = props.name\n this.version = props.version\n this.events = props.events\n this.actions = props.actions\n this.entities = props.entities\n this.templateName = props.templateName\n }\n\n public resolve(props: InterfaceResolveInput<TEntities>): InterfaceResolveOutput<TActions, TEvents> {\n const { entities } = props\n\n const implementStatement: InterfaceImplementationStatement = {\n name: this.name,\n version: this.version,\n entities: utils.mapValues(entities, (entity) => ({ name: entity.name })), // { item: { name: 'issue' } }\n actions: {},\n events: {},\n }\n\n const actions: Record<string, ActionDefinition> = {}\n const events: Record<string, EventDefinition> = {}\n\n // dereference actions\n for (const [actionName, action] of utils.pairs(this.actions)) {\n const resolvedInputSchema = this._dereference(action.input.schema, entities)\n const resolvedOutputSchema = this._dereference(action.output.schema, entities)\n\n const newActionName = this._rename(entities, actionName)\n actions[newActionName] = {\n input: { schema: resolvedInputSchema },\n output: { schema: resolvedOutputSchema },\n }\n implementStatement.actions[actionName] = { name: newActionName }\n }\n\n // dereference events\n for (const [eventName, event] of utils.pairs(this.events)) {\n const resolvedEventSchema = this._dereference(event.schema, entities)\n const newEventName = this._rename(entities, eventName)\n events[newEventName] = { schema: resolvedEventSchema }\n implementStatement.events[eventName] = { name: newEventName }\n }\n\n const resolved = {\n actions,\n events,\n } as ResolvedInterface<TActions, TEvents>\n\n return {\n resolved,\n implementStatement,\n }\n }\n\n private _dereference(\n generic: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject>,\n entities: InterfaceResolveInput<TEntities>['entities']\n ): AnyZodObject {\n const entitySchemas: Record<string, AnyZodObject> = {}\n const entityReferences: Record<string, ZodRef> = {}\n for (const [entityName, entity] of utils.pairs(entities)) {\n entitySchemas[entityName] = entity.schema\n entityReferences[entityName] = z.ref(entityName)\n }\n return generic(entityReferences as EntityReferences<TEntities>).dereference(\n entitySchemas as TEntities\n ) as AnyZodObject\n }\n\n private _rename(entities: InterfaceResolveInput<TEntities>['entities'], name: string): string {\n if (!this.templateName) {\n return name\n }\n\n const templateProps = utils.mapValues(entities, (entity) => entity.name) as Record<keyof TEntities, string>\n return this.templateName(name, templateProps)\n }\n}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport { z } from '../zui'\n\nconst ToolCallSchema = z.object({\n id: z.string(),\n type: z.enum(['function']),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n})\n\nconst ToolChoiceSchema = z.object({\n // TODO: remove empty value from enum once Studio issue is fixed\n type: z.enum(['auto', 'specific', 'any', 'none', '']).optional(), // note: Claude doesn't support \"none\" but we can simply strip out the tools when `type` is \"none\"\n functionName: z.string().optional().describe('Required if `type` is \"specific\"'),\n})\n\nconst MessageSchema = z.object({\n role: z.enum(['user', 'assistant']),\n type: z.enum(['text', 'tool_calls', 'tool_result', 'multipart']),\n toolCalls: z.array(ToolCallSchema).optional().describe('Required if `type` is \"tool_calls\"'),\n toolResultCallId: z.string().optional().describe('Required if `type` is \"tool_result\"'), // note: not supported by Gemini\n content: z\n .string()\n // TODO: union types are not supported yet by the Studio, comment this out when testing via an action card in the Studio\n .or(\n z.array(\n z.object({\n type: z.enum(['text', 'image']),\n mimeType: z.string(),\n text: z.string().optional().describe('Required if part type is \"text\" '),\n url: z.string().optional().describe('Required if part type is \"image\"'),\n })\n )\n )\n .optional()\n .describe(\n 'Required unless `type` is \"tool_call\". If `type` is \"multipart\", this field must be an array of content objects. If `type` is \"tool_result\" then this field should be the result of the tool call (a plain string or a JSON-encoded array or object). If `type` is \"tool_call\" then the `toolCalls` field should be used instead.'\n ),\n})\n\nconst GenerateContentInputSchema = z.object({\n model: z.string().describe('Model to use for content generation'),\n systemPrompt: z.string().optional().describe('Optional system prompt to guide the model'),\n messages: z.array(MessageSchema).describe('Array of messages for the model to process').min(1),\n responseFormat: z\n .enum(['text', 'json_object'])\n .optional()\n .describe(\n 'Response format expected from the model. If \"json_object\" is chosen, you must instruct the model to generate JSON either via the system prompt or a user message.'\n ), // note: only OpenAI and Groq support this but for other models we can just append this as an indication in the system prompt\n // note: we don't support streaming yet\n maxTokens: z.number().optional().describe('Maximum number of tokens allowed in the generated response'),\n temperature: z\n .number()\n .min(0)\n .max(2)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .default(1)\n .describe('Sampling temperature for the model. Higher values result in more random outputs.'),\n topP: z\n .number()\n .min(0)\n .max(1)\n .default(1)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .describe(\n 'Top-p sampling parameter. Limits sampling to the smallest set of tokens with a cumulative probability above the threshold.'\n ), // TODO: .placeholder() from zui doesn't work, so we have to use .default() which introduces some typing issues\n // note: topK is supported by Claude and Gemini but not by OpenAI or Groq\n stopSequences: z\n .array(z.string())\n .max(4)\n .optional()\n .describe('Sequences where the model should stop generating further tokens.'),\n tools: z\n .array(\n z.object({\n type: z.literal('function'),\n function: z.object({\n name: z.string(),\n description: z.string().optional(),\n inputSchema: z.object({}).passthrough().optional(),\n }),\n })\n )\n .optional(),\n // TODO: an object with options doesn't seem to be supported by the Studio as it's not rendering correctly, the dropdown for \"type\" is not working and it's sending a blank value instead which causes a schema validation error unless an empty value is allowed in the `type` enum\n toolChoice: ToolChoiceSchema.optional(), // note: Gemini doesn't support this but we can just ignore it there\n userId: z.string().optional(),\n})\n\nconst GenerateContentOutputSchema = z.object({\n id: z.string().describe('Response ID from LLM provider'),\n provider: z.string().describe('LLM provider name'),\n model: z.string().describe('Model name'),\n choices: z.array(\n MessageSchema.omit({ role: true }).extend({\n role: z.literal('assistant'),\n index: z.number().int(),\n stopReason: z.enum(['stop', 'max_tokens', 'tool_calls', 'content_filter', 'other']),\n // note: stopSequence is supported by Claude but not by OpenAI, Groq or Gemini\n })\n ),\n usage: z.object({\n inputTokens: z.number().int().describe('Number of input tokens used by the model'),\n inputCost: z.number().describe('Cost of the input tokens received by the model, in U.S. dollars'),\n outputTokens: z.number().int().describe('Number of output tokens used by the model'),\n outputCost: z.number().describe('Cost of the output tokens generated by the model, in U.S. dollars'),\n }),\n})\n\nexport const llm = new InterfaceDeclaration({\n name: 'llm',\n version: '0.0.1',\n entities: {},\n events: {},\n actions: {\n generateContent: {\n input: {\n schema: () => GenerateContentInputSchema,\n },\n output: {\n schema: () => GenerateContentOutputSchema,\n },\n },\n },\n})\n\nexport namespace llm {\n export type GenerateContentInput = z.infer<typeof GenerateContentInputSchema>\n export type GenerateContentOutput = z.infer<typeof GenerateContentOutputSchema>\n export type ToolCall = z.infer<typeof ToolCallSchema>\n export type Message = z.infer<typeof MessageSchema>\n}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport { z } from '../zui'\n\nexport const hitl = new InterfaceDeclaration({\n name: 'hitl',\n version: '0.0.1',\n entities: {},\n events: {},\n actions: {\n startHITL: {\n input: {\n schema: () => z.object({ upstreamConversationId: z.string() }),\n },\n output: {\n schema: () => z.object({ downstreamConversationId: z.string() }),\n },\n },\n },\n})\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst baseItem = z.object({ id: z.string() })\nconst withId = (schema: z.ZodTypeAny) => z.intersection(schema, baseItem)\n\nconst capitalize = (s: string) => s[0]!.toUpperCase() + s.slice(1)\nconst camelCase = (...parts: string[]) => {\n const [first, ...rest] = parts.filter((s) => s.length > 0).map((s) => s.toLowerCase())\n if (!first) {\n return ''\n }\n return [first, ...rest.map(capitalize)].join('')\n}\n\nconst nextToken = z.string().optional()\nexport const listable = new InterfaceDeclaration({\n name: 'listable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {},\n actions: {\n list: {\n input: {\n schema: () => z.object({ nextToken }),\n },\n output: {\n schema: (args) =>\n z.object({\n items: z.array(withId(args.item)),\n meta: z.object({ nextToken }),\n }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueList\n})\n\nexport const creatable = new InterfaceDeclaration({\n name: 'creatable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n created: {\n schema: (args) =>\n z.object({\n item: withId(args.item),\n }),\n },\n },\n actions: {\n create: {\n input: {\n schema: (args) => z.object({ item: args.item }),\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueCreate, issueCreated\n})\n\nexport const readable = new InterfaceDeclaration({\n name: 'readable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {},\n actions: {\n read: {\n input: {\n schema: () => baseItem,\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueRead\n})\n\nexport const updatable = new InterfaceDeclaration({\n name: 'updatable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n updated: {\n schema: (args) =>\n z.object({\n item: withId(args.item),\n }),\n },\n },\n actions: {\n update: {\n input: {\n schema: (args) => baseItem.extend({ item: args.item }),\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueUpdate, issueUpdated\n})\n\nexport const deletable = new InterfaceDeclaration({\n name: 'deletable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n deleted: {\n schema: (args) =>\n z.object({\n item: withId(args.item),\n }),\n },\n },\n actions: {\n delete: {\n input: {\n schema: () => baseItem,\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueDelete, issueDeleted\n})\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { isApiError, Client, type Conversation, type Message, type User, RuntimeError } from '@botpress/client'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration['configuration']>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags']>\n}\n\ntype CreateUserArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & CreateUserPayload<TIntegration>\n\ntype CreateConversationPayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'] = keyof TIntegration['channels']\n> = {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n}\n\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags']>\n }\n >\n}\n\ntype MessageArgs<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = CommonArgs<TIntegration> &\n MessagePayload<TIntegration, TChannel, TMessage> & {\n ack: (props: { tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']> }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (thrown) {\n if (isApiError(thrown)) {\n const runtimeError = new RuntimeError(thrown.message, thrown)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n throw thrown\n }\n }\n\nconst onPing = async <TIntegration extends BaseIntegration>(_: ServerProps<TIntegration>) => {}\n\nconst onWebhook = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req: incomingRequest,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<TIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<TIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async <TIntegration extends BaseIntegration>({\n ctx,\n req,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<TIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this.client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this.client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this.client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this.client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this.client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this.client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this.client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this.client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this.client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this.client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this.client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this.client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this.client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this.client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this.client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this.client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this.client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this.client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this.client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this.client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this.client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this.client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this.client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this.client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this.client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this.client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this.client.configureIntegration(x)\n\n public uploadFile: routes.UploadFile<TIntegration> = (x) => this.client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TIntegration> = (x) => this.client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TIntegration> = (x) => this.client.deleteFile(x)\n public listFiles: routes.ListFiles<TIntegration> = (x) => this.client.listFiles(x)\n public getFile: routes.GetFile<TIntegration> = (x) => this.client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TIntegration> = (x) => this.client.updateFileMetadata(x)\n}\n", "/* eslint-disable no-console */\nimport util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\n this.props = props\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this.client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this.client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this.client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this.client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this.client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this.client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this.client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this.client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this.client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) => this.client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this.client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) => this.client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this.client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) => this.client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this.client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this.client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this.client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this.client.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this.client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this.client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this.client.callAction(x)\n\n public uploadFile: routes.UploadFile<TBot> = (x) => this.client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TBot> = (x) => this.client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TBot> = (x) => this.client.deleteFile(x)\n public listFiles: routes.ListFiles<TBot> = (x) => this.client.listFiles(x)\n public getFile: routes.GetFile<TBot> = (x) => this.client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TBot> = (x) => this.client.updateFileMetadata(x)\n public searchFiles: routes.SearchFiles<TBot> = (x) => this.client.searchFiles(x)\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: routes.CreateConversation<TBot> = (x) => this.client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: routes.GetOrCreateConversation<TBot> = (x) => this.client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: routes.CreateUser<TBot> = (x) => this.client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: routes.GetOrCreateUser<TBot> = (x) => this.client.getOrCreateUser(x)\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext = {\n botId: string\n type: string\n operation: BotOperation\n configuration: {\n payload: string\n }\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport type { Server } from 'node:http'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<TIntegrations[K]>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
5
+ "mappings": "mnBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,gDAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,w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AOC,EAA8Bd,CAAG,EACxCe,EAAQF,EAAK,MAEnB,OAAQZ,EAAI,KAAM,CAChB,IAAK,kBACH,IAAMe,EAAuC,CAC3C,KAAMD,EAAM,QAAQ,KACpB,aAAcA,EAAM,QAAQ,aAC5B,QAASA,EAAM,QAAQ,QACvB,OAAQA,EAAM,QAAQ,OACtB,MAAAA,CACF,EAEA,MAAM,QAAQ,IACZhB,EAAS,gBAAgB,IAAKkB,GAC5BA,EAAQ,CACN,OAAAL,EACA,IAAAX,EACA,GAAGe,CACL,CAAC,CACH,CACF,EACA,MACF,IAAK,gBACH,IAAME,EAAoC,CAAE,MAAOH,EAAM,QAAQ,KAAM,EACvE,MAAM,QAAQ,IACZhB,EAAS,qBAAqB,IAAKkB,GACjCA,EAAQ,CACN,OAAAL,EACA,IAAAX,EACA,GAAGiB,CACL,CAAC,CACH,CACF,EACA,MACF,QACE,IAAMC,EAAe,CAAE,MAAON,EAAK,KAAM,EACzC,MAAM,QAAQ,IACZd,EAAS,cAAc,IAAKkB,GAC1BA,EAAQ,CACN,OAAAL,EACA,IAAAX,EACA,GAAGkB,CACL,CAAC,CACH,CACF,CACJ,CACF,EG1DO,IAAMC,EAAN,KAIL,CACQ,OAAoD,CAC1D,gBAAiB,CAAC,EAClB,cAAe,CAAC,EAChB,qBAAsB,CAAC,CACzB,EAEgB,MAET,YAAYC,EAAkD,CACnE,KAAK,MAAQA,CACf,CAEgB,QAAWC,GAA4E,CACrG,KAAK,OAAO,gBAAgB,KAAKA,CAAO,CAC1C,EACgB,MAASA,GAA0E,CACjG,KAAK,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,GAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
6
+ "names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "InterfaceDeclaration", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "interfaces_exports", "message_exports", "operationHeader", "parseBody", "serve", "studioComponentDefinitions", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "studioComponentDefinitions", "import_zui", "__reExport", "commonInputParams", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "defaults", "interfaces_exports", "__export", "creatable", "deletable", "hitl", "listable", "llm", "readable", "updatable", "pairs", "obj", "mapValues", "obj", "fn", "pairs", "key", "value", "entityKey", "createStore", "props", "mapValues", "e", "k", "isBranded", "entity", "getName", "IntegrationDefinition", "props", "clone", "key", "value", "interfaceDeclaration", "builder", "extensionBuilderOutput", "createStore", "unbrandedEntity", "pairs", "_k", "e", "isBranded", "interfaceTypeArguments", "mapValues", "getName", "resolved", "implementStatement", "self", "actions", "events", "entityNames", "InterfaceDeclaration", "props", "entities", "implementStatement", "mapValues", "entity", "actions", "events", "actionName", "action", "pairs", "resolvedInputSchema", "resolvedOutputSchema", "newActionName", "eventName", "event", "resolvedEventSchema", "newEventName", "generic", "entitySchemas", "entityReferences", "entityName", "zui_default", "name", "templateProps", "ToolCallSchema", "ToolChoiceSchema", "MessageSchema", "GenerateContentInputSchema", "GenerateContentOutputSchema", "llm", "InterfaceDeclaration", "hitl", "InterfaceDeclaration", "baseItem", "zui_default", "withId", "schema", "capitalize", "s", "camelCase", "parts", "first", "rest", "nextToken", "listable", "InterfaceDeclaration", "args", "name", "props", "creatable", "readable", "updatable", "deletable", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "import_node_http", "log", "parseBody", "req", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "i", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "__reExport", "src_exports", "zui_exports", "import_client", "import_zui", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "import_client", "IntegrationSpecificClient", "client", "x", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "client", "IntegrationSpecificClient", "props", "integrationLogger", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "thrown", "runtimeError", "_", "incomingRequest", "logger", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "client", "BotSpecificClient", "client", "x", "y", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "Bot", "props", "handler", "botHandler", "port", "serve"]
7
7
  }
@@ -0,0 +1,19 @@
1
+ import { Cast } from '../../type-utils';
2
+ import { BaseEntities } from './generic';
3
+ declare const entityKey: unique symbol;
4
+ export type EntityStoreProps<TEntities extends BaseEntities = BaseEntities> = {
5
+ [K in keyof TEntities]: {
6
+ schema: TEntities[K];
7
+ };
8
+ };
9
+ export type BrandedEntity<TEntity extends BaseEntities[string] = BaseEntities[string], TBrand extends string = string> = {
10
+ schema: TEntity;
11
+ [entityKey]: TBrand;
12
+ };
13
+ export type EntityStore<TEntities extends BaseEntities = BaseEntities> = {
14
+ [K in keyof TEntities]: BrandedEntity<TEntities[K], Cast<K, string>>;
15
+ };
16
+ export declare const createStore: <TEntities extends BaseEntities>(props: EntityStoreProps<TEntities> | undefined) => EntityStore<TEntities>;
17
+ export declare const isBranded: (entity: BrandedEntity) => boolean;
18
+ export declare const getName: (entity: BrandedEntity) => string;
19
+ export {};
@@ -0,0 +1,8 @@
1
+ import { AnyZodObject } from '../../type-utils';
2
+ export type BaseConfig = AnyZodObject;
3
+ export type BaseEvents = Record<string, AnyZodObject>;
4
+ export type BaseActions = Record<string, AnyZodObject>;
5
+ export type BaseMessages = Record<string, AnyZodObject>;
6
+ export type BaseChannels = Record<string, BaseMessages>;
7
+ export type BaseStates = Record<string, AnyZodObject>;
8
+ export type BaseEntities = Record<string, AnyZodObject>;
@@ -0,0 +1,3 @@
1
+ export * from './integration-definition';
2
+ export * from './interface-declaration';
3
+ export * from './types';
@@ -1,74 +1,7 @@
1
- import { SchemaDefinition } from '../schema';
2
- import { AnyZodObject } from '../type-utils';
3
- type BaseConfig = AnyZodObject;
4
- type BaseEvents = Record<string, AnyZodObject>;
5
- type BaseActions = Record<string, AnyZodObject>;
6
- type BaseMessages = Record<string, AnyZodObject>;
7
- type BaseChannels = Record<string, BaseMessages>;
8
- type BaseStates = Record<string, AnyZodObject>;
9
- type BaseEntities = Record<string, AnyZodObject>;
10
- export type TagDefinition = {
11
- title?: string;
12
- description?: string;
13
- };
14
- export type ConfigurationDefinition<TConfig extends BaseConfig = BaseConfig> = SchemaDefinition<TConfig> & {
15
- identifier?: {
16
- required?: boolean;
17
- linkTemplateScript?: string;
18
- };
19
- };
20
- export type EventDefinition<TEvent extends BaseEvents[string] = BaseEvents[string]> = SchemaDefinition<TEvent> & {
21
- title?: string;
22
- description?: string;
23
- };
24
- export type MessageDefinition<TMessage extends BaseMessages[string] = BaseMessages[string]> = SchemaDefinition<TMessage>;
25
- export type ChannelDefinition<TChannel extends BaseChannels[string] = BaseChannels[string]> = {
26
- title?: string;
27
- description?: string;
28
- messages: {
29
- [K in keyof TChannel]: MessageDefinition<TChannel[K]>;
30
- };
31
- message?: {
32
- tags?: Record<string, TagDefinition>;
33
- };
34
- conversation?: Partial<{
35
- tags: Record<string, TagDefinition>;
36
- /**
37
- * @deprecated
38
- */
39
- creation: {
40
- enabled: boolean;
41
- requiredTags: string[];
42
- };
43
- }>;
44
- };
45
- export type ActionDefinition<TAction extends BaseActions[string] = BaseActions[string]> = {
46
- title?: string;
47
- description?: string;
48
- input: SchemaDefinition<TAction>;
49
- output: SchemaDefinition<AnyZodObject>;
50
- };
51
- export type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = SchemaDefinition<TState> & {
52
- type: 'integration' | 'conversation' | 'user';
53
- };
54
- export type UserDefinition = Partial<{
55
- tags: Record<string, TagDefinition>;
56
- /**
57
- * @deprecated
58
- */
59
- creation: {
60
- enabled: boolean;
61
- requiredTags: string[];
62
- };
63
- }>;
64
- export type SecretDefinition = {
65
- optional?: boolean;
66
- description?: string;
67
- };
68
- export type EntityDefinition<TEntity extends BaseEntities[string] = BaseEntities[string]> = SchemaDefinition<TEntity> & {
69
- title?: string;
70
- description?: string;
71
- };
1
+ import { EntityStore, BrandedEntity } from './entity-store';
2
+ import { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities } from './generic';
3
+ import { InterfaceDeclaration } from './interface-declaration';
4
+ import { ConfigurationDefinition, EventDefinition, ChannelDefinition, ActionDefinition, StateDefinition, UserDefinition, SecretDefinition, EntityDefinition, InterfaceImplementationStatement } from './types';
72
5
  export type IntegrationDefinitionProps<TConfig extends BaseConfig = BaseConfig, TEvents extends BaseEvents = BaseEvents, TActions extends BaseActions = BaseActions, TChannels extends BaseChannels = BaseChannels, TStates extends BaseStates = BaseStates, TEntities extends BaseEntities = BaseEntities> = {
73
6
  name: string;
74
7
  version: string;
@@ -99,6 +32,10 @@ export type IntegrationDefinitionProps<TConfig extends BaseConfig = BaseConfig,
99
32
  [K in keyof TEntities]: EntityDefinition<TEntities[K]>;
100
33
  };
101
34
  };
35
+ type InterfaceTypeArguments<TInterfaceEntities extends BaseEntities> = {
36
+ [K in keyof TInterfaceEntities]: BrandedEntity<TInterfaceEntities[K], string>;
37
+ };
38
+ type ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (input: EntityStore<TIntegrationEntities>) => InterfaceTypeArguments<TInterfaceEntities>;
102
39
  export declare class IntegrationDefinition<TConfig extends BaseConfig = BaseConfig, TEvents extends BaseEvents = BaseEvents, TActions extends BaseActions = BaseActions, TChannels extends BaseChannels = BaseChannels, TStates extends BaseStates = BaseStates, TEntities extends BaseEntities = BaseEntities> {
103
40
  readonly props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>;
104
41
  readonly name: this['props']['name'];
@@ -116,7 +53,9 @@ export declare class IntegrationDefinition<TConfig extends BaseConfig = BaseConf
116
53
  readonly secrets: this['props']['secrets'];
117
54
  readonly identifier: this['props']['identifier'];
118
55
  readonly entities: this['props']['entities'];
119
- clone(props: Partial<IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>>): IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities>;
56
+ readonly interfaces: Record<string, InterfaceImplementationStatement>;
120
57
  constructor(props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>);
58
+ clone(props: Partial<IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>>): IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities>;
59
+ extend<E extends BaseEntities>(interfaceDeclaration: InterfaceDeclaration<E>, builder: ExtensionBuilder<TEntities, E>): this;
121
60
  }
122
61
  export {};