@botpress/sdk 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +3 -3
- package/dist/bot/client/index.d.ts +42 -41
- package/dist/bot/client/types.d.ts +127 -74
- package/dist/bot/client/types.test.d.ts +1 -0
- package/dist/bot/implementation.d.ts +1 -1
- package/dist/bot/index.d.ts +1 -1
- package/dist/bot/server/context.d.ts +2 -0
- package/dist/bot/server/index.d.ts +5 -0
- package/dist/bot/server/types.d.ts +59 -0
- package/dist/bot/types/common.d.ts +56 -0
- package/dist/bot/types/common.test.d.ts +1 -0
- package/dist/bot/types/generic.d.ts +15 -0
- package/dist/bot/types/index.d.ts +2 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/integration/client/index.d.ts +42 -41
- package/dist/integration/client/types.d.ts +127 -21
- package/dist/integration/implementation.d.ts +2 -2
- package/dist/integration/index.d.ts +1 -2
- package/dist/integration/server/context.d.ts +3 -0
- package/dist/integration/server/index.d.ts +6 -0
- package/dist/integration/server/types.d.ts +102 -0
- package/dist/integration/types/common.d.ts +11 -0
- package/dist/integration/types/generic.d.ts +54 -0
- package/dist/integration/types/index.d.ts +2 -0
- package/dist/message.d.ts +1 -1
- package/dist/utils/type-utils.d.ts +19 -3
- package/dist/utils/type-utils.test.d.ts +1 -0
- package/package.json +1 -1
- package/dist/bot/client/routes.d.ts +0 -81
- package/dist/bot/context.d.ts +0 -12
- package/dist/bot/generic.d.ts +0 -7
- package/dist/bot/server.d.ts +0 -40
- package/dist/integration/client/routes.d.ts +0 -128
- package/dist/integration/context.d.ts +0 -23
- package/dist/integration/generic.d.ts +0 -30
- package/dist/integration/server.d.ts +0 -88
- /package/dist/integration/{action-metadata.d.ts → server/action-metadata.d.ts} +0 -0
- /package/dist/integration/{logger.d.ts → server/logger.d.ts} +0 -0
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/
|
|
4
|
-
"sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport {\n //\n isApiError,\n RuntimeError,\n} from '@botpress/client'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationLogger,\n IntegrationSpecificClient,\n TagDefinition,\n ConfigurationDefinition,\n AdditionalConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport {\n BotDefinition,\n BotDefinitionProps,\n BotImplementation as Bot,\n BotImplementationProps as BotProps,\n BotSpecificClient,\n TagDefinition as BotTagDefinition,\n StateType as BotStateType,\n StateDefinition as BotStateDefinition,\n RecurringEventDefinition as BotRecurringEventDefinition,\n EventDefinition as BotEventDefinition,\n ConfigurationDefinition as BotConfigurationDefinition,\n UserDefinition as BotUserDefinition,\n ConversationDefinition as BotConversationDefinition,\n MessageDefinition as BotMessageDefinition,\n} from './bot'\n\nexport {\n //\n InterfaceDeclaration,\n InterfaceDeclarationProps,\n} from './interface'\n\nexport {\n //\n IntegrationPackage,\n InterfacePackage,\n} from './package'\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 } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\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 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 configurationTypeHeader = 'x-bp-configuration-type'\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 configurationTypeHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\nimport { ValueOf } from '../utils/type-utils'\nimport { BaseIntegration } from './generic'\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\ntype IntegrationContextConfig<TIntegration extends BaseIntegration> =\n | {\n configurationType: null\n configuration: TIntegration['configuration']\n }\n | ValueOf<{\n [TConfigType in keyof TIntegration['configurations']]: {\n configurationType: TConfigType\n configuration: TIntegration['configurations'][TConfigType]\n }\n }>\n\nexport type IntegrationContext<TIntegration extends BaseIntegration = BaseIntegration> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n} & IntegrationContextConfig<TIntegration>\n\nexport const extractContext = <TIntegration extends BaseIntegration>(\n headers: Record<string, string | undefined>\n): IntegrationContext<TIntegration> => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const configurationType = headers[configurationTypeHeader]\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 configurationType: configurationType ?? null,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n } as IntegrationContext<TIntegration>\n}\n", "export const pairs = <K extends string, V>(obj: Record<K, V>) => Object.entries(obj) as [K, 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 * as utils from '../../utils'\nimport { z } from '../../zui'\n\nconst schemaName = Symbol('schemaName')\n\ntype BaseSchemas = Record<string, z.ZodSchema>\n\nexport type SchemaStoreProps<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: {\n schema: TSchemas[K]\n }\n}\n\nexport type BrandedSchema<TSchema extends BaseSchemas[string] = BaseSchemas[string]> = {\n schema: TSchema\n [schemaName]: string\n}\n\nexport type SchemaStore<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: BrandedSchema<TSchemas[K]>\n}\n\nexport const createStore = <TSchemas extends BaseSchemas>(\n props: SchemaStoreProps<TSchemas> | undefined\n): SchemaStore<TSchemas> => {\n if (!props) {\n return {} as SchemaStore<TSchemas>\n }\n const store: SchemaStore<BaseSchemas> = utils.records.mapValues(props, (e, k) => ({ ...e, [schemaName]: k }))\n return store as SchemaStore<TSchemas>\n}\n\nexport const isBranded = (schema: BrandedSchema | { schema: z.ZodSchema }): schema is BrandedSchema => {\n return schemaName in schema && schema[schemaName] !== undefined\n}\n\nexport const getName = (schema: BrandedSchema): string => {\n return schema[schemaName]\n}\n", "import { InterfacePackage } from '../../package'\nimport * as utils from '../../utils'\nimport { z } from '../../zui'\nimport { SchemaStore, BrandedSchema, createStore, isBranded, getName } from './branded-schema'\nimport { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities, BaseConfigs } from './generic'\nimport {\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n AdditionalConfigurationDefinition,\n} from './types'\n\nexport * from './types'\n\nexport type InterfaceInstance = InterfacePackage & {\n entities: Record<\n string,\n {\n name: string\n schema: z.AnyZodObject\n }\n >\n}\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\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 configurations?: {\n [K in keyof TConfigs]: AdditionalConfigurationDefinition<TConfigs[K]>\n }\n\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 interfaces?: Record<string, InterfaceInstance>\n}\n\ntype EntitiesOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['entities']]: NonNullable<TPackage['definition']['entities']>[K]['schema']\n}\n\ntype ExtensionBuilderInput<TIntegrationEntities extends BaseEntities> = SchemaStore<TIntegrationEntities>\n\ntype ExtensionBuilderOutput<TInterfaceEntities extends BaseEntities> = {\n [K in keyof TInterfaceEntities]: BrandedSchema<z.ZodSchema<z.infer<TInterfaceEntities[K]>>>\n}\n\ntype ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (\n input: ExtensionBuilderInput<TIntegrationEntities>\n) => ExtensionBuilderOutput<TInterfaceEntities>\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\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 configurations: this['props']['configurations']\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 public readonly interfaces: this['props']['interfaces']\n public constructor(\n public readonly props: IntegrationDefinitionProps<\n TConfig,\n TConfigs,\n TEvents,\n TActions,\n TChannels,\n TStates,\n TEntities\n >\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.configurations = props.configurations\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 this.interfaces = props.interfaces\n }\n\n public extend<P extends InterfacePackage>(\n interfacePkg: P,\n builder: ExtensionBuilder<TEntities, EntitiesOfPackage<P>>\n ): this {\n const extensionBuilderOutput = builder(createStore(this.entities))\n const unbrandedEntity = utils.records.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 \"${interfacePkg.definition.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n\n const self = this as utils.types.Writable<IntegrationDefinition>\n self.interfaces ??= {}\n\n const interfaceTypeArguments = utils.records.mapValues(extensionBuilderOutput, (e) => ({\n name: getName(e),\n schema: e.schema as z.AnyZodObject,\n }))\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n\n const key =\n entityNames.length === 0\n ? interfacePkg.definition.name\n : `${interfacePkg.definition.name}<${entityNames.join(',')}>`\n\n self.interfaces[key] = {\n ...interfacePkg,\n entities: interfaceTypeArguments,\n }\n\n return this\n }\n}\n", "import { isApiError, Client, type Conversation, type Message, type User, RuntimeError } from '@botpress/client'\nimport { retryConfig } from '../retry'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../utils/type-utils'\nimport { ActionMetadataStore } from './action-metadata'\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>\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 ActionMetadata = { setCost: (cost: number) => void }\ntype ActionPayload<T extends string, I> = { type: T; input: I; metadata: ActionMetadata }\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 channel: TChannel\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<TIntegration>(req.headers)\n\n const vanillaClient = new Client({\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n retry: retryConfig,\n })\n const client = new IntegrationSpecificClient<TIntegration>(vanillaClient)\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 integrationLogger.forBot().error(runtimeError.message)\n\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n\n // prints the error in the integration logs\n console.error(thrown)\n\n const runtimeError = new RuntimeError(\n 'An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.'\n )\n integrationLogger.forBot().error(runtimeError.message)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\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 metadata = new ActionMetadataStore()\n const output = await action({ ctx, input, client, type, logger, metadata })\n\n const response = { output, meta: metadata.toJSON() }\n return {\n body: JSON.stringify(response),\n }\n}\n", "import { RetryConfig, axiosRetry } from '@botpress/client'\n\nexport const retryConfig: RetryConfig = {\n retries: 3,\n retryCondition: (err) =>\n axiosRetry.isNetworkOrIdempotentRequestError(err) || [429, 502].includes(err.response?.status ?? 0),\n retryDelay: (retryCount) => retryCount * 1000,\n}\n", "export type ActionMetadata = {\n cost: number\n}\n\nexport class ActionMetadataStore {\n private _cost: number = 0\n\n public get cost(): number {\n return this._cost\n }\n\n public setCost(cost: number): void {\n this._cost = cost\n }\n\n public toJSON(): ActionMetadata {\n return {\n cost: this.cost,\n }\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", "import 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 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(public readonly props: IntegrationImplementationProps<TIntegration>) {\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 { IntegrationPackage } from '../package'\nimport { SchemaDefinition } from '../schema'\nimport { ValueOf, Writable } from '../utils/type-utils'\nimport z, { AnyZodObject } from '../zui'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\nexport type TagDefinition = {\n title?: string\n description?: string\n}\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\nexport type RecurringEventDefinition<TEvents extends BaseEvents = BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\nexport type EventDefinition<TEvent extends BaseEvents[string] = BaseEvents[string]> = SchemaDefinition<TEvent>\n\nexport type ConfigurationDefinition = SchemaDefinition\n\nexport type UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type IntegrationConfigInstance<I extends IntegrationPackage = IntegrationPackage> = {\n enabled: boolean\n} & (\n | {\n configurationType?: null\n configuration: z.infer<NonNullable<I['definition']['configuration']>['schema']>\n }\n | ValueOf<{\n [K in keyof NonNullable<I['definition']['configurations']>]: {\n configurationType: K\n configuration: z.infer<NonNullable<I['definition']['configurations']>[K]['schema']>\n }\n }>\n)\n\nexport type IntegrationInstance = IntegrationPackage & IntegrationConfigInstance\n\nexport type BotDefinitionProps<TStates extends BaseStates = BaseStates, TEvents extends BaseEvents = BaseEvents> = {\n integrations?: {\n [K: string]: IntegrationInstance\n }\n user?: UserDefinition\n conversation?: ConversationDefinition\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\nexport class BotDefinition<TStates extends BaseStates = BaseStates, TEvents extends BaseEvents = BaseEvents> {\n public readonly integrations: this['props']['integrations']\n public readonly user: this['props']['user']\n public readonly conversation: this['props']['conversation']\n public readonly message: this['props']['message']\n public readonly states: this['props']['states']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly recurringEvents: this['props']['recurringEvents']\n public constructor(public readonly props: BotDefinitionProps<TStates, TEvents>) {\n this.integrations = props.integrations\n this.user = props.user\n this.conversation = props.conversation\n this.message = props.message\n this.states = props.states\n this.configuration = props.configuration\n this.events = props.events\n this.recurringEvents = props.recurringEvents\n }\n\n public add<I extends IntegrationPackage>(integrationPkg: I, config: IntegrationConfigInstance<I>): this {\n const self = this as Writable<BotDefinition>\n if (!self.integrations) {\n self.integrations = {}\n }\n\n self.integrations[integrationPkg.definition.name] = {\n enabled: config.enabled,\n ...integrationPkg,\n configurationType: config.configurationType as string,\n configuration: config.configuration,\n }\n return this\n }\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { retryConfig } from '../retry'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { StateType } from './definition'\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 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 vanillaClient = new client.Client({\n botId: ctx.botId,\n retry: retryConfig,\n })\n const botClient = new BotSpecificClient<TBot>(vanillaClient)\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) =>\n 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) =>\n 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) =>\n 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\n .getState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this._client\n .setState(x)\n .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 type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseBot } from './generic'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler } from './server'\n\ntype BotState<TBot extends BaseBot = BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\nexport type BotImplementationProps<_TBot extends BaseBot = BaseBot> = {\n // TODO: add actions here\n}\n\nexport class BotImplementation<TBot extends BaseBot = BaseBot> {\n private _state: BotState<TBot> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public constructor(public readonly props: BotImplementationProps<TBot>) {}\n\n public readonly message = (handler: MessageHandler<TBot>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<TBot>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<TBot>): 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", "import { ActionDefinition, ChannelDefinition, EntityDefinition, EventDefinition } from '../integration/definition'\nimport * as utils from '../utils'\nimport z, { AnyZodObject, GenericZuiSchema, ZodRef } from '../zui'\n\ntype BaseEvents = Record<string, AnyZodObject>\ntype BaseActions = Record<string, AnyZodObject>\ntype BaseMessages = Record<string, AnyZodObject>\ntype BaseChannels = Record<string, BaseMessages>\ntype BaseEntities = Record<string, AnyZodObject>\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 GenericChannelDefinition<\n TEntities extends BaseEntities,\n TChannel extends BaseChannels[string] = BaseChannels[string]\n> = {\n messages: {\n [K in keyof TChannel]: {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TChannel[K]>\n }\n }\n}\n\ntype GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string]\n> = {\n billable?: boolean\n cacheable?: boolean\n input: { schema: GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject> }\n}\n\nexport type InterfaceDeclarationProps<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEntities = BaseEntities,\n TChannels extends BaseChannels = BaseChannels\n> = {\n name: string\n version: string\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\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 channels?: {\n [K in keyof TChannels]: GenericChannelDefinition<TEntities, TChannels[K]>\n }\n\n templateName?: string\n}\n\nexport class InterfaceDeclaration<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents,\n TChannels extends BaseChannels = BaseChannels\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n\n public readonly entities: { [K in keyof TEntities]: EntityDefinition<TEntities[K]> }\n public readonly events: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n public readonly actions: { [K in keyof TActions]: ActionDefinition<TActions[K]> }\n public readonly channels: { [K in keyof TChannels]: ChannelDefinition<TChannels[K]> }\n\n public readonly templateName: this['props']['templateName']\n\n public constructor(public readonly props: InterfaceDeclarationProps<TEntities, TActions, TEvents, TChannels>) {\n this.name = props.name\n this.version = props.version\n this.entities = props.entities ?? ({} as this['entities'])\n this.templateName = props.templateName\n\n const entityReferences = this._getEntityReference(this.entities)\n\n const events: Record<string, EventDefinition> =\n props.events === undefined\n ? {}\n : utils.records.mapValues(\n props.events,\n (event): EventDefinition => ({\n ...event,\n schema: event.schema(entityReferences),\n })\n )\n\n const actions: Record<string, ActionDefinition> =\n props.actions === undefined\n ? {}\n : utils.records.mapValues(\n props.actions,\n (action): ActionDefinition => ({\n ...action,\n input: {\n ...action.input,\n schema: action.input.schema(entityReferences),\n },\n output: {\n ...action.output,\n schema: action.output.schema(entityReferences),\n },\n })\n )\n\n const channels: Record<string, ChannelDefinition> =\n props.channels === undefined\n ? {}\n : utils.records.mapValues(\n props.channels,\n (channel): ChannelDefinition => ({\n ...channel,\n messages: utils.records.mapValues(channel.messages, (message) => ({\n ...message,\n schema: message.schema(entityReferences),\n })),\n })\n )\n\n this.events = events as this['events']\n this.actions = actions as this['actions']\n this.channels = channels as this['channels']\n }\n\n private _getEntityReference = (entities: this['entities']): EntityReferences<TEntities> => {\n const entityReferences: Record<string, ZodRef> = {} as EntityReferences<TEntities>\n for (const entityName of Object.keys(entities)) {\n entityReferences[entityName] = z.ref(entityName)\n }\n return entityReferences as EntityReferences<TEntities>\n }\n}\n"],
|
|
5
|
-
"mappings": "mnBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,kBAAAC,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,gDAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,yCAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAApB,GCAA,IAAAqB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KCAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,IAAAC,EAAkB,2BAClBC,EAAAJ,EAAc,4BAOd,IAAOE,EAAQ,IDNf,IAAMG,EAAiB,IAAE,OAAO,EAAE,IAAI,CAAC,EAEjCC,EAAoB,IAAE,OAAO,CACjC,KAAMD,CACR,CAAC,EAEKE,EAAwB,IAAE,OAAO,CACrC,SAAUF,CACZ,CAAC,EAEKG,GAAqB,IAAE,OAAO,CAClC,SAAUH,CACZ,CAAC,EAEKI,GAAqB,IAAE,OAAO,CAClC,SAAUJ,CACZ,CAAC,EAEKK,GAAqB,IAAE,OAAO,CAClC,SAAUL,CACZ,CAAC,EAEKM,GAAoB,IAAE,OAAO,CACjC,QAASN,EACT,MAAOA,EAAe,SAAS,CACjC,CAAC,EAEKO,GA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C9C,EACA,OAAQ,CACN,GAAGK,EAAO,OACV,OAAQA,EAAO,OAAO,OAAOL,CAAgB,CAC/C,CACF,EACF,EAEAM,EACJP,EAAM,WAAa,OACf,CAAC,EACKG,EAAQ,UACZH,EAAM,SACLQ,IAAgC,CAC/B,GAAGA,EACH,SAAgBL,EAAQ,UAAUK,EAAQ,SAAWC,IAAa,CAChE,GAAGA,EACH,OAAQA,EAAQ,OAAOR,CAAgB,CACzC,EAAE,CACJ,EACF,EAEN,KAAK,OAASC,EACd,KAAK,QAAUG,EACf,KAAK,SAAWE,CAClB,CAhEgB,KACA,QAEA,SACA,OACA,QACA,SAEA,aA0DR,oBAAuBG,GAA4D,CACzF,IAAMT,EAA2C,CAAC,EAClD,QAAWU,KAAc,OAAO,KAAKD,CAAQ,EAC3CT,EAAiBU,CAAU,EAAIC,EAAE,IAAID,CAAU,EAEjD,OAAOV,CACT,CACF",
|
|
6
|
-
"names": ["src_exports", "__export", "BotImplementation", "BotDefinition", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "InterfaceDeclaration", "botIdHeader", "botUserIdHeader", "configurationHeader", "configurationTypeHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "import_zui", "__reExport", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "defaults", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationTypeHeader", "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", "
|
|
3
|
+
"sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/utils/record-utils.ts", "../src/integration/definition/branded-schema.ts", "../src/integration/definition/index.ts", "../src/integration/server/index.ts", "../src/retry.ts", "../src/integration/client/index.ts", "../src/integration/server/action-metadata.ts", "../src/integration/server/context.ts", "../src/integration/server/logger.ts", "../src/integration/implementation.ts", "../src/bot/definition.ts", "../src/bot/server/index.ts", "../src/bot/client/index.ts", "../src/bot/server/context.ts", "../src/bot/implementation.ts", "../src/interface/definition.ts"],
|
|
4
|
+
"sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport {\n //\n isApiError,\n RuntimeError,\n} from '@botpress/client'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationLogger,\n IntegrationSpecificClient,\n TagDefinition,\n ConfigurationDefinition,\n AdditionalConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport {\n /**\n * @deprecated use Context exported from '.botpress' instead\n */\n IntegrationContext,\n} from './integration/server'\n\nexport {\n BotDefinition,\n BotDefinitionProps,\n BotImplementation as Bot,\n BotImplementationProps as BotProps,\n BotSpecificClient,\n TagDefinition as BotTagDefinition,\n StateType as BotStateType,\n StateDefinition as BotStateDefinition,\n RecurringEventDefinition as BotRecurringEventDefinition,\n EventDefinition as BotEventDefinition,\n ConfigurationDefinition as BotConfigurationDefinition,\n UserDefinition as BotUserDefinition,\n ConversationDefinition as BotConversationDefinition,\n MessageDefinition as BotMessageDefinition,\n} from './bot'\n\nexport {\n //\n InterfaceDeclaration,\n InterfaceDeclarationProps,\n} from './interface'\n\nexport {\n //\n IntegrationPackage,\n InterfacePackage,\n} from './package'\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.union([\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 } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\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 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 configurationTypeHeader = 'x-bp-configuration-type'\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", "export const pairs = <K extends string, V>(obj: Record<K, V>) => Object.entries(obj) as [K, 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 * as utils from '../../utils'\nimport { z } from '../../zui'\n\nconst schemaName = Symbol('schemaName')\n\ntype BaseSchemas = Record<string, z.ZodSchema>\n\nexport type SchemaStoreProps<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: {\n schema: TSchemas[K]\n }\n}\n\nexport type BrandedSchema<TSchema extends BaseSchemas[string] = BaseSchemas[string]> = {\n schema: TSchema\n [schemaName]: string\n}\n\nexport type SchemaStore<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: BrandedSchema<TSchemas[K]>\n}\n\nexport const createStore = <TSchemas extends BaseSchemas>(\n props: SchemaStoreProps<TSchemas> | undefined\n): SchemaStore<TSchemas> => {\n if (!props) {\n return {} as SchemaStore<TSchemas>\n }\n const store: SchemaStore<BaseSchemas> = utils.records.mapValues(props, (e, k) => ({ ...e, [schemaName]: k }))\n return store as SchemaStore<TSchemas>\n}\n\nexport const isBranded = (schema: BrandedSchema | { schema: z.ZodSchema }): schema is BrandedSchema => {\n return schemaName in schema && schema[schemaName] !== undefined\n}\n\nexport const getName = (schema: BrandedSchema): string => {\n return schema[schemaName]\n}\n", "import { InterfacePackage } from '../../package'\nimport * as utils from '../../utils'\nimport { z } from '../../zui'\nimport { SchemaStore, BrandedSchema, createStore, isBranded, getName } from './branded-schema'\nimport { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities, BaseConfigs } from './generic'\nimport {\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n AdditionalConfigurationDefinition,\n} from './types'\n\nexport * from './types'\n\nexport type InterfaceInstance = InterfacePackage & {\n entities: Record<\n string,\n {\n name: string\n schema: z.AnyZodObject\n }\n >\n}\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\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 configurations?: {\n [K in keyof TConfigs]: AdditionalConfigurationDefinition<TConfigs[K]>\n }\n\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 interfaces?: Record<string, InterfaceInstance>\n}\n\ntype EntitiesOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['entities']]: NonNullable<TPackage['definition']['entities']>[K]['schema']\n}\n\ntype ExtensionBuilderInput<TIntegrationEntities extends BaseEntities> = SchemaStore<TIntegrationEntities>\n\ntype ExtensionBuilderOutput<TInterfaceEntities extends BaseEntities> = {\n [K in keyof TInterfaceEntities]: BrandedSchema<z.ZodSchema<z.infer<TInterfaceEntities[K]>>>\n}\n\ntype ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (\n input: ExtensionBuilderInput<TIntegrationEntities>\n) => ExtensionBuilderOutput<TInterfaceEntities>\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\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 configurations: this['props']['configurations']\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 public readonly interfaces: this['props']['interfaces']\n public constructor(\n public readonly props: IntegrationDefinitionProps<\n TConfig,\n TConfigs,\n TEvents,\n TActions,\n TChannels,\n TStates,\n TEntities\n >\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.configurations = props.configurations\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 this.interfaces = props.interfaces\n }\n\n public extend<P extends InterfacePackage>(\n interfacePkg: P,\n builder: ExtensionBuilder<TEntities, EntitiesOfPackage<P>>\n ): this {\n const extensionBuilderOutput = builder(createStore(this.entities))\n const unbrandedEntity = utils.records.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 \"${interfacePkg.definition.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n\n const self = this as utils.types.Writable<IntegrationDefinition>\n self.interfaces ??= {}\n\n const interfaceTypeArguments = utils.records.mapValues(extensionBuilderOutput, (e) => ({\n name: getName(e),\n schema: e.schema as z.AnyZodObject,\n }))\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n\n const key =\n entityNames.length === 0\n ? interfacePkg.definition.name\n : `${interfacePkg.definition.name}<${entityNames.join(',')}>`\n\n self.interfaces[key] = {\n ...interfacePkg,\n entities: interfaceTypeArguments,\n }\n\n return this\n }\n}\n", "import { isApiError, Client, RuntimeError } from '@botpress/client'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody } from '../../serve'\nimport { IntegrationSpecificClient } from '../client'\nimport { BaseIntegration } from '../types'\nimport { ActionMetadataStore } from './action-metadata'\nimport { extractContext } from './context'\nimport { integrationLogger } from './logger'\nimport {\n CommonHandlerProps,\n IntegrationHandlers,\n WebhookPayload,\n ActionPayload,\n MessagePayload,\n RegisterPayload,\n CreateUserPayload,\n UnregisterPayload,\n CreateConversationPayload,\n IntegrationContext,\n} from './types'\n\nexport * from './types'\nexport * from './logger'\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonHandlerProps<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) as IntegrationContext<TIntegration>\n\n const vanillaClient = new Client({\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n retry: retryConfig,\n })\n const client = new IntegrationSpecificClient<TIntegration>(vanillaClient)\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 integrationLogger.forBot().error(runtimeError.message)\n\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n\n // prints the error in the integration logs\n console.error(thrown)\n\n const runtimeError = new RuntimeError(\n 'An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.'\n )\n integrationLogger.forBot().error(runtimeError.message)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\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 metadata = new ActionMetadataStore()\n const output = await action({ ctx, input, client, type, logger, metadata })\n\n const response = { output, meta: metadata.toJSON() }\n return {\n body: JSON.stringify(response),\n }\n}\n", "import { RetryConfig, axiosRetry } from '@botpress/client'\n\nexport const retryConfig: RetryConfig = {\n retries: 3,\n retryCondition: (err) =>\n axiosRetry.isNetworkOrIdempotentRequestError(err) || [429, 502].includes(err.response?.status ?? 0),\n retryDelay: (retryCount) => retryCount * 1000,\n}\n", "import * as client from '@botpress/client'\nimport * as common from '../types'\nimport * as types from './types'\n\nexport * from './types'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends common.BaseIntegration> {\n public constructor(private readonly _client: client.Client) {}\n\n public createConversation: types.CreateConversation<TIntegration> = ((x) =>\n this._client.createConversation(x)) as types.CreateConversation<TIntegration>\n public getConversation: types.GetConversation<TIntegration> = ((x) =>\n this._client.getConversation(x)) as types.GetConversation<TIntegration>\n public listConversations: types.ListConversations<TIntegration> = ((x) =>\n this._client.listConversations(x)) as types.ListConversations<TIntegration>\n public getOrCreateConversation: types.GetOrCreateConversation<TIntegration> = ((x) =>\n this._client.getOrCreateConversation(x)) as types.GetOrCreateConversation<TIntegration>\n public updateConversation: types.UpdateConversation<TIntegration> = ((x) =>\n this._client.updateConversation(x)) as types.UpdateConversation<TIntegration>\n public deleteConversation: types.DeleteConversation<TIntegration> = ((x) =>\n this._client.deleteConversation(x)) as types.DeleteConversation<TIntegration>\n\n public listParticipants: types.ListParticipants<TIntegration> = ((x) =>\n this._client.listParticipants(x)) as types.ListParticipants<TIntegration>\n public addParticipant: types.AddParticipant<TIntegration> = ((x) =>\n this._client.addParticipant(x)) as types.AddParticipant<TIntegration>\n public getParticipant: types.GetParticipant<TIntegration> = ((x) =>\n this._client.getParticipant(x)) as types.GetParticipant<TIntegration>\n public removeParticipant: types.RemoveParticipant<TIntegration> = ((x) =>\n this._client.removeParticipant(x)) as types.RemoveParticipant<TIntegration>\n\n public createEvent: types.CreateEvent<TIntegration> = ((x) =>\n this._client.createEvent(x)) as types.CreateEvent<TIntegration>\n public getEvent: types.GetEvent<TIntegration> = ((x) => this._client.getEvent(x)) as types.GetEvent<TIntegration>\n public listEvents: types.ListEvents<TIntegration> = ((x) =>\n this._client.listEvents(x)) as types.ListEvents<TIntegration>\n\n public createMessage: types.CreateMessage<TIntegration> = ((x) =>\n this._client.createMessage(x)) as types.CreateMessage<TIntegration>\n public getOrCreateMessage: types.GetOrCreateMessage<TIntegration> = ((x) =>\n this._client.getOrCreateMessage(x)) as types.GetOrCreateMessage<TIntegration>\n public getMessage: types.GetMessage<TIntegration> = ((x) =>\n this._client.getMessage(x)) as types.GetMessage<TIntegration>\n public updateMessage: types.UpdateMessage<TIntegration> = ((x) =>\n this._client.updateMessage(x)) as types.UpdateMessage<TIntegration>\n public listMessages: types.ListMessages<TIntegration> = ((x) =>\n this._client.listMessages(x)) as types.ListMessages<TIntegration>\n public deleteMessage: types.DeleteMessage<TIntegration> = ((x) =>\n this._client.deleteMessage(x)) as types.DeleteMessage<TIntegration>\n\n public createUser: types.CreateUser<TIntegration> = ((x) =>\n this._client.createUser(x)) as types.CreateUser<TIntegration>\n public getUser: types.GetUser<TIntegration> = ((x) => this._client.getUser(x)) as types.GetUser<TIntegration>\n public listUsers: types.ListUsers<TIntegration> = (x) => this._client.listUsers(x)\n public getOrCreateUser: types.GetOrCreateUser<TIntegration> = ((x) =>\n this._client.getOrCreateUser(x)) as types.GetOrCreateUser<TIntegration>\n public updateUser: types.UpdateUser<TIntegration> = ((x) =>\n this._client.updateUser(x)) as types.UpdateUser<TIntegration>\n public deleteUser: types.DeleteUser<TIntegration> = (x) => this._client.deleteUser(x)\n\n public getState: types.GetState<TIntegration> = ((x) => this._client.getState(x)) as types.GetState<TIntegration>\n public setState: types.SetState<TIntegration> = ((x) => this._client.setState(x)) as types.SetState<TIntegration>\n public getOrSetState: types.GetOrSetState<TIntegration> = ((x) =>\n this._client.getOrSetState(x)) as types.GetOrSetState<TIntegration>\n public patchState: types.PatchState<TIntegration> = ((x) =>\n this._client.patchState(x)) as types.PatchState<TIntegration>\n\n public configureIntegration: types.ConfigureIntegration<TIntegration> = (x) => this._client.configureIntegration(x)\n\n public uploadFile: types.UploadFile<TIntegration> = (x) => this._client.uploadFile(x)\n public upsertFile: types.UpsertFile<TIntegration> = (x) => this._client.upsertFile(x)\n public deleteFile: types.DeleteFile<TIntegration> = (x) => this._client.deleteFile(x)\n public listFiles: types.ListFiles<TIntegration> = (x) => this._client.listFiles(x)\n public getFile: types.GetFile<TIntegration> = (x) => this._client.getFile(x)\n public updateFileMetadata: types.UpdateFileMetadata<TIntegration> = (x) => this._client.updateFileMetadata(x)\n}\n", "export type ActionMetadata = {\n cost: number\n}\n\nexport class ActionMetadataStore {\n private _cost: number = 0\n\n public get cost(): number {\n return this._cost\n }\n\n public setCost(cost: number): void {\n this._cost = cost\n }\n\n public toJSON(): ActionMetadata {\n return {\n cost: this.cost,\n }\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n configurationTypeHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../../const'\nimport { IntegrationContext } from './types'\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 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 configurationType = headers[configurationTypeHeader]\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 configurationType: configurationType ?? null,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import 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 {\n RegisterHandler as RegisterFunction,\n UnregisterHandler as UnregisterFunction,\n WebhookHandler as WebhookFunction,\n CreateUserHandler as CreateUserFunction,\n CreateConversationHandler as CreateConversationFunction,\n ActionHandlers as ActionFunctions,\n ChannelHandlers as ChannelFunctions,\n integrationHandler,\n} from './server'\nimport { BaseIntegration } from './types'\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 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(public readonly props: IntegrationImplementationProps<TIntegration>) {\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 { IntegrationPackage } from '../package'\nimport { SchemaDefinition } from '../schema'\nimport { ValueOf, Writable } from '../utils/type-utils'\nimport z, { AnyZodObject } from '../zui'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\nexport type TagDefinition = {\n title?: string\n description?: string\n}\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\nexport type RecurringEventDefinition<TEvents extends BaseEvents = BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\nexport type EventDefinition<TEvent extends BaseEvents[string] = BaseEvents[string]> = SchemaDefinition<TEvent>\n\nexport type ConfigurationDefinition = SchemaDefinition\n\nexport type UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type IntegrationConfigInstance<I extends IntegrationPackage = IntegrationPackage> = {\n enabled: boolean\n} & (\n | {\n configurationType?: null\n configuration: z.infer<NonNullable<I['definition']['configuration']>['schema']>\n }\n | ValueOf<{\n [K in keyof NonNullable<I['definition']['configurations']>]: {\n configurationType: K\n configuration: z.infer<NonNullable<I['definition']['configurations']>[K]['schema']>\n }\n }>\n)\n\nexport type IntegrationInstance = IntegrationPackage & IntegrationConfigInstance\n\nexport type BotDefinitionProps<TStates extends BaseStates = BaseStates, TEvents extends BaseEvents = BaseEvents> = {\n integrations?: {\n [K: string]: IntegrationInstance\n }\n user?: UserDefinition\n conversation?: ConversationDefinition\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\nexport class BotDefinition<TStates extends BaseStates = BaseStates, TEvents extends BaseEvents = BaseEvents> {\n public readonly integrations: this['props']['integrations']\n public readonly user: this['props']['user']\n public readonly conversation: this['props']['conversation']\n public readonly message: this['props']['message']\n public readonly states: this['props']['states']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly recurringEvents: this['props']['recurringEvents']\n public constructor(public readonly props: BotDefinitionProps<TStates, TEvents>) {\n this.integrations = props.integrations\n this.user = props.user\n this.conversation = props.conversation\n this.message = props.message\n this.states = props.states\n this.configuration = props.configuration\n this.events = props.events\n this.recurringEvents = props.recurringEvents\n }\n\n public add<I extends IntegrationPackage>(integrationPkg: I, config: IntegrationConfigInstance<I>): this {\n const self = this as Writable<BotDefinition>\n if (!self.integrations) {\n self.integrations = {}\n }\n\n self.integrations[integrationPkg.definition.name] = {\n enabled: config.enabled,\n ...integrationPkg,\n configurationType: config.configurationType as string,\n configuration: config.configuration,\n }\n return this\n }\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../../log'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody } from '../../serve'\nimport { BotSpecificClient } from '../client'\nimport * as common from '../types'\nimport { extractContext } from './context'\nimport * as types from './types'\n\nexport * from './types'\n\ntype ServerProps<TBot extends common.BaseBot> = types.CommonHandlerProps<TBot> & {\n req: Request\n instance: types.BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends common.BaseBot>(instance: types.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 vanillaClient = new client.Client({\n botId: ctx.botId,\n retry: retryConfig,\n })\n const botClient = new BotSpecificClient<TBot>(vanillaClient)\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 common.BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends common.BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends common.BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends common.BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<types.EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: types.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: types.StateExpiredPayload<TBot> = { 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 types.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 * as client from '@botpress/client'\nimport * as common from '../types'\nimport * as types from './types'\n\nexport * from './types'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends common.BaseBot> implements types.ClientOperations<TBot> {\n public constructor(private readonly _client: client.Client) {}\n\n public getConversation: types.GetConversation<TBot> = (x) => this._client.getConversation(x)\n public listConversations: types.ListConversations<TBot> = (x) => this._client.listConversations(x)\n public updateConversation: types.UpdateConversation<TBot> = (x) => this._client.updateConversation(x)\n public deleteConversation: types.DeleteConversation<TBot> = (x) => this._client.deleteConversation(x)\n public listParticipants: types.ListParticipants<TBot> = (x) => this._client.listParticipants(x)\n public addParticipant: types.AddParticipant<TBot> = (x) => this._client.addParticipant(x)\n public getParticipant: types.GetParticipant<TBot> = (x) => this._client.getParticipant(x)\n public removeParticipant: types.RemoveParticipant<TBot> = (x) => this._client.removeParticipant(x)\n public getEvent: types.GetEvent<TBot> = ((x) => this._client.getEvent(x)) as types.GetEvent<TBot>\n public listEvents: types.ListEvents<TBot> = ((x) => this._client.listEvents(x)) as types.ListEvents<TBot>\n public createMessage: types.CreateMessage<TBot> = ((x) => this._client.createMessage(x)) as types.CreateMessage<TBot>\n public getOrCreateMessage: types.GetOrCreateMessage<TBot> = ((x) =>\n this._client.getOrCreateMessage(x)) as types.GetOrCreateMessage<TBot>\n public getMessage: types.GetMessage<TBot> = ((x) => this._client.getMessage(x)) as types.GetMessage<TBot>\n public updateMessage: types.UpdateMessage<TBot> = ((x) => this._client.updateMessage(x)) as types.UpdateMessage<TBot>\n public listMessages: types.ListMessages<TBot> = ((x) => this._client.listMessages(x)) as types.ListMessages<TBot>\n public deleteMessage: types.DeleteMessage<TBot> = ((x) => this._client.deleteMessage(x)) as types.DeleteMessage<TBot>\n public getUser: types.GetUser<TBot> = (x) => this._client.getUser(x)\n public listUsers: types.ListUsers<TBot> = (x) => this._client.listUsers(x)\n public updateUser: types.UpdateUser<TBot> = (x) => this._client.updateUser(x)\n public deleteUser: types.DeleteUser<TBot> = (x) => this._client.deleteUser(x)\n public getState: types.GetState<TBot> = ((x) =>\n this._client.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as types.GetState<TBot>\n public setState: types.SetState<TBot> = ((x) =>\n this._client.setState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as types.SetState<TBot>\n public getOrSetState: types.GetOrSetState<TBot> = ((x) =>\n this._client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as types.GetOrSetState<TBot>\n public patchState: types.PatchState<TBot> = ((x) =>\n this._client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as types.PatchState<TBot>\n public callAction: types.CallAction<TBot> = (x) => this._client.callAction(x)\n public uploadFile: types.UploadFile<TBot> = (x) => this._client.uploadFile(x)\n public upsertFile: types.UpsertFile<TBot> = (x) => this._client.upsertFile(x)\n public deleteFile: types.DeleteFile<TBot> = (x) => this._client.deleteFile(x)\n public listFiles: types.ListFiles<TBot> = (x) => this._client.listFiles(x)\n public getFile: types.GetFile<TBot> = (x) => this._client.getFile(x)\n public updateFileMetadata: types.UpdateFileMetadata<TBot> = (x) => this._client.updateFileMetadata(x)\n public searchFiles: types.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: types.CreateConversation<TBot> = (x) => this._client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: types.GetOrCreateConversation<TBot> = (x) => this._client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: types.CreateUser<TBot> = (x) => this._client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: types.GetOrCreateUser<TBot> = (x) => this._client.getOrCreateUser(x)\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../../const'\nimport { BotContext } from './types'\n\nconst botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\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 type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler } from './server'\nimport { BaseBot } from './types'\n\ntype BotState<TBot extends BaseBot = BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\nexport type BotImplementationProps<_TBot extends BaseBot = BaseBot> = {\n // TODO: add actions here\n}\n\nexport class BotImplementation<TBot extends BaseBot = BaseBot> {\n private _state: BotState<TBot> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public constructor(public readonly props: BotImplementationProps<TBot>) {}\n\n public readonly message = (handler: MessageHandler<TBot>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<TBot>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<TBot>): 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", "import { ActionDefinition, ChannelDefinition, EntityDefinition, EventDefinition } from '../integration/definition'\nimport * as utils from '../utils'\nimport z, { AnyZodObject, GenericZuiSchema, ZodRef } from '../zui'\n\ntype BaseEvents = Record<string, AnyZodObject>\ntype BaseActions = Record<string, AnyZodObject>\ntype BaseMessages = Record<string, AnyZodObject>\ntype BaseChannels = Record<string, BaseMessages>\ntype BaseEntities = Record<string, AnyZodObject>\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 GenericChannelDefinition<\n TEntities extends BaseEntities,\n TChannel extends BaseChannels[string] = BaseChannels[string]\n> = {\n messages: {\n [K in keyof TChannel]: {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TChannel[K]>\n }\n }\n}\n\ntype GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string]\n> = {\n billable?: boolean\n cacheable?: boolean\n input: { schema: GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject> }\n}\n\nexport type InterfaceDeclarationProps<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEntities = BaseEntities,\n TChannels extends BaseChannels = BaseChannels\n> = {\n name: string\n version: string\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\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 channels?: {\n [K in keyof TChannels]: GenericChannelDefinition<TEntities, TChannels[K]>\n }\n\n templateName?: string\n}\n\nexport class InterfaceDeclaration<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents,\n TChannels extends BaseChannels = BaseChannels\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n\n public readonly entities: { [K in keyof TEntities]: EntityDefinition<TEntities[K]> }\n public readonly events: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n public readonly actions: { [K in keyof TActions]: ActionDefinition<TActions[K]> }\n public readonly channels: { [K in keyof TChannels]: ChannelDefinition<TChannels[K]> }\n\n public readonly templateName: this['props']['templateName']\n\n public constructor(public readonly props: InterfaceDeclarationProps<TEntities, TActions, TEvents, TChannels>) {\n this.name = props.name\n this.version = props.version\n this.entities = props.entities ?? ({} as this['entities'])\n this.templateName = props.templateName\n\n const entityReferences = this._getEntityReference(this.entities)\n\n const events: Record<string, EventDefinition> =\n props.events === undefined\n ? {}\n : utils.records.mapValues(\n props.events,\n (event): EventDefinition => ({\n ...event,\n schema: event.schema(entityReferences),\n })\n )\n\n const actions: Record<string, ActionDefinition> =\n props.actions === undefined\n ? {}\n : utils.records.mapValues(\n props.actions,\n (action): ActionDefinition => ({\n ...action,\n input: {\n ...action.input,\n schema: action.input.schema(entityReferences),\n },\n output: {\n ...action.output,\n schema: action.output.schema(entityReferences),\n },\n })\n )\n\n const channels: Record<string, ChannelDefinition> =\n props.channels === undefined\n ? {}\n : utils.records.mapValues(\n props.channels,\n (channel): ChannelDefinition => ({\n ...channel,\n messages: utils.records.mapValues(channel.messages, (message) => ({\n ...message,\n schema: message.schema(entityReferences),\n })),\n })\n )\n\n this.events = events as this['events']\n this.actions = actions as this['actions']\n this.channels = channels as this['channels']\n }\n\n private _getEntityReference = (entities: this['entities']): EntityReferences<TEntities> => {\n const entityReferences: Record<string, ZodRef> = {} as EntityReferences<TEntities>\n for (const entityName of Object.keys(entities)) {\n entityReferences[entityName] = z.ref(entityName)\n }\n return entityReferences as EntityReferences<TEntities>\n }\n}\n"],
|
|
5
|
+
"mappings": "mnBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,kBAAAC,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,gDAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,yCAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAApB,GCAA,IAAAqB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KCAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,IAAAC,EAAkB,2BAClBC,EAAAJ,EAAc,4BAOd,IAAOE,EAAQ,IDNf,IAAMG,EAAiB,IAAE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,CAAC,EACpC,KAAK,aAAeA,EAAM,aAE1B,IAAMC,EAAmB,KAAK,oBAAoB,KAAK,QAAQ,EAEzDC,EACJF,EAAM,SAAW,OACb,CAAC,EACKG,EAAQ,UACZH,EAAM,OACLI,IAA4B,CAC3B,GAAGA,EACH,OAAQA,EAAM,OAAOH,CAAgB,CACvC,EACF,EAEAI,EACJL,EAAM,UAAY,OACd,CAAC,EACKG,EAAQ,UACZH,EAAM,QACLM,IAA8B,CAC7B,GAAGA,EACH,MAAO,CACL,GAAGA,EAAO,MACV,OAAQA,EAAO,MAAM,OAAOL,CAAgB,CAC9C,EACA,OAAQ,CACN,GAAGK,EAAO,OACV,OAAQA,EAAO,OAAO,OAAOL,CAAgB,CAC/C,CACF,EACF,EAEAM,EACJP,EAAM,WAAa,OACf,CAAC,EACKG,EAAQ,UACZH,EAAM,SACLQ,IAAgC,CAC/B,GAAGA,EACH,SAAgBL,EAAQ,UAAUK,EAAQ,SAAWC,IAAa,CAChE,GAAGA,EACH,OAAQA,EAAQ,OAAOR,CAAgB,CACzC,EAAE,CACJ,EACF,EAEN,KAAK,OAASC,EACd,KAAK,QAAUG,EACf,KAAK,SAAWE,CAClB,CAhEgB,KACA,QAEA,SACA,OACA,QACA,SAEA,aA0DR,oBAAuBG,GAA4D,CACzF,IAAMT,EAA2C,CAAC,EAClD,QAAWU,KAAc,OAAO,KAAKD,CAAQ,EAC3CT,EAAiBU,CAAU,EAAIC,EAAE,IAAID,CAAU,EAEjD,OAAOV,CACT,CACF",
|
|
6
|
+
"names": ["src_exports", "__export", "BotImplementation", "BotDefinition", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "InterfaceDeclaration", "botIdHeader", "botUserIdHeader", "configurationHeader", "configurationTypeHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "import_zui", "__reExport", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "defaults", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationTypeHeader", "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", "record_utils_exports", "__export", "mapValues", "pairs", "obj", "fn", "key", "value", "schemaName", "createStore", "props", "record_utils_exports", "e", "k", "isBranded", "schema", "getName", "IntegrationDefinition", "props", "interfacePkg", "builder", "extensionBuilderOutput", "createStore", "unbrandedEntity", "record_utils_exports", "_k", "e", "isBranded", "self", "interfaceTypeArguments", "getName", "entityNames", "key", "import_client", "import_client", "retryConfig", "err", "retryCount", "IntegrationSpecificClient", "_client", "x", "ActionMetadataStore", "cost", "import_zui", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "configurationType", "configurationTypeHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "vanillaClient", "retryConfig", "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", "metadata", "ActionMetadataStore", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "BotDefinition", "props", "integrationPkg", "config", "self", "client", "BotSpecificClient", "_client", "x", "y", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "vanillaClient", "retryConfig", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "BotImplementation", "props", "handler", "botHandler", "port", "serve", "InterfaceDeclaration", "props", "entityReferences", "events", "record_utils_exports", "event", "actions", "action", "channels", "channel", "message", "entities", "entityName", "zui_default"]
|
|
7
7
|
}
|
|
@@ -1,46 +1,47 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import * as
|
|
1
|
+
import * as client from '@botpress/client';
|
|
2
|
+
import * as common from '../types';
|
|
3
|
+
import * as types from './types';
|
|
4
|
+
export * from './types';
|
|
4
5
|
/**
|
|
5
6
|
* Just like the regular botpress client, but typed with the integration's properties.
|
|
6
7
|
*/
|
|
7
|
-
export declare class IntegrationSpecificClient<TIntegration extends BaseIntegration> {
|
|
8
|
+
export declare class IntegrationSpecificClient<TIntegration extends common.BaseIntegration> {
|
|
8
9
|
private readonly _client;
|
|
9
|
-
constructor(_client: Client);
|
|
10
|
-
createConversation:
|
|
11
|
-
getConversation:
|
|
12
|
-
listConversations:
|
|
13
|
-
getOrCreateConversation:
|
|
14
|
-
updateConversation:
|
|
15
|
-
deleteConversation:
|
|
16
|
-
listParticipants:
|
|
17
|
-
addParticipant:
|
|
18
|
-
getParticipant:
|
|
19
|
-
removeParticipant:
|
|
20
|
-
createEvent:
|
|
21
|
-
getEvent:
|
|
22
|
-
listEvents:
|
|
23
|
-
createMessage:
|
|
24
|
-
getOrCreateMessage:
|
|
25
|
-
getMessage:
|
|
26
|
-
updateMessage:
|
|
27
|
-
listMessages:
|
|
28
|
-
deleteMessage:
|
|
29
|
-
createUser:
|
|
30
|
-
getUser:
|
|
31
|
-
listUsers:
|
|
32
|
-
getOrCreateUser:
|
|
33
|
-
updateUser:
|
|
34
|
-
deleteUser:
|
|
35
|
-
getState:
|
|
36
|
-
setState:
|
|
37
|
-
getOrSetState:
|
|
38
|
-
patchState:
|
|
39
|
-
configureIntegration:
|
|
40
|
-
uploadFile:
|
|
41
|
-
upsertFile:
|
|
42
|
-
deleteFile:
|
|
43
|
-
listFiles:
|
|
44
|
-
getFile:
|
|
45
|
-
updateFileMetadata:
|
|
10
|
+
constructor(_client: client.Client);
|
|
11
|
+
createConversation: types.CreateConversation<TIntegration>;
|
|
12
|
+
getConversation: types.GetConversation<TIntegration>;
|
|
13
|
+
listConversations: types.ListConversations<TIntegration>;
|
|
14
|
+
getOrCreateConversation: types.GetOrCreateConversation<TIntegration>;
|
|
15
|
+
updateConversation: types.UpdateConversation<TIntegration>;
|
|
16
|
+
deleteConversation: types.DeleteConversation<TIntegration>;
|
|
17
|
+
listParticipants: types.ListParticipants<TIntegration>;
|
|
18
|
+
addParticipant: types.AddParticipant<TIntegration>;
|
|
19
|
+
getParticipant: types.GetParticipant<TIntegration>;
|
|
20
|
+
removeParticipant: types.RemoveParticipant<TIntegration>;
|
|
21
|
+
createEvent: types.CreateEvent<TIntegration>;
|
|
22
|
+
getEvent: types.GetEvent<TIntegration>;
|
|
23
|
+
listEvents: types.ListEvents<TIntegration>;
|
|
24
|
+
createMessage: types.CreateMessage<TIntegration>;
|
|
25
|
+
getOrCreateMessage: types.GetOrCreateMessage<TIntegration>;
|
|
26
|
+
getMessage: types.GetMessage<TIntegration>;
|
|
27
|
+
updateMessage: types.UpdateMessage<TIntegration>;
|
|
28
|
+
listMessages: types.ListMessages<TIntegration>;
|
|
29
|
+
deleteMessage: types.DeleteMessage<TIntegration>;
|
|
30
|
+
createUser: types.CreateUser<TIntegration>;
|
|
31
|
+
getUser: types.GetUser<TIntegration>;
|
|
32
|
+
listUsers: types.ListUsers<TIntegration>;
|
|
33
|
+
getOrCreateUser: types.GetOrCreateUser<TIntegration>;
|
|
34
|
+
updateUser: types.UpdateUser<TIntegration>;
|
|
35
|
+
deleteUser: types.DeleteUser<TIntegration>;
|
|
36
|
+
getState: types.GetState<TIntegration>;
|
|
37
|
+
setState: types.SetState<TIntegration>;
|
|
38
|
+
getOrSetState: types.GetOrSetState<TIntegration>;
|
|
39
|
+
patchState: types.PatchState<TIntegration>;
|
|
40
|
+
configureIntegration: types.ConfigureIntegration<TIntegration>;
|
|
41
|
+
uploadFile: types.UploadFile<TIntegration>;
|
|
42
|
+
upsertFile: types.UpsertFile<TIntegration>;
|
|
43
|
+
deleteFile: types.DeleteFile<TIntegration>;
|
|
44
|
+
listFiles: types.ListFiles<TIntegration>;
|
|
45
|
+
getFile: types.GetFile<TIntegration>;
|
|
46
|
+
updateFileMetadata: types.UpdateFileMetadata<TIntegration>;
|
|
46
47
|
}
|